define("vs/editor.api-CykLys8L", ["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;
    });
  }
  function getMonacoEnvironment() {
    return globalThis.MonacoEnvironment;
  }
  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 isArrayOf$1(value, check) {
    return Array.isArray(value) && value.every(check);
  }
  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 the currently held disposable value, or `undefined` if this MutableDisposable has been disposed
     */
    get value() {
      return this._isDisposed ? void 0 : this._value;
    }
    /**
     * Set a new disposable value.
     *
     * Behaviour:
     * - If the MutableDisposable has been disposed, the setter is a no-op.
     * - If the new value is strictly equal to the current value, the setter is a no-op.
     * - Otherwise the previous value (if any) is disposed and the new value is stored.
     *
     * Related helpers:
     * - clear() resets the value to `undefined` (and disposes the previous value).
     * - clearAndLeak() returns the old value without disposing it and removes its parent.
     */
    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.activePromise = null;
      this.queuedPromise = null;
      this.queuedPromiseFactory = null;
      this.cancellationTokenSource = new CancellationTokenSource$1();
    }
    queue(promiseFactory) {
      if (this.cancellationTokenSource.token.isCancellationRequested) {
        return Promise.reject(new Error("Throttler is disposed"));
      }
      if (this.activePromise) {
        this.queuedPromiseFactory = promiseFactory;
        if (!this.queuedPromise) {
          const onComplete = () => {
            this.queuedPromise = null;
            if (this.cancellationTokenSource.token.isCancellationRequested) {
              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(this.cancellationTokenSource.token);
      return new Promise((resolve2, reject) => {
        this.activePromise.then((result) => {
          this.activePromise = null;
          resolve2(result);
        }, (err) => {
          this.activePromise = null;
          reject(err);
        });
      });
    }
    dispose() {
      this.cancellationTokenSource.cancel();
    }
  };
  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 "&lt;";
        case ">":
          return "&gt;";
        case '"':
          return "&quot;";
        case "'":
          return "&apos;";
        case "&":
          return "&amp;";
      }
      return ch;
    });
  }
  function escape$2(html2) {
    return html2.replace(/[<>&]/g, function(match2) {
      switch (match2) {
        case "<":
          return "&lt;";
        case ">":
          return "&gt;";
        case "&":
          return "&amp;";
        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 len = candidate.length;
    return len <= str.length && compareSubstringIgnoreCase(str, candidate, 0, len) === 0;
  }
  function endsWithIgnoreCase(str, candidate) {
    const len = str.length;
    const start = len - candidate.length;
    return start >= 0 && compareSubstringIgnoreCase(str, candidate, start, len) === 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("_") && Object.hasOwn(data, l));
    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$1 = globalThis.vscode;
  if (typeof vscodeGlobal$1 !== "undefined" && typeof vscodeGlobal$1.process !== "undefined") {
    const sandboxProcess = vscodeGlobal$1.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$1 = 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.vscodeLocalChatSession = "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";
    Schemas2.copilotPr = "copilot-pr";
  })(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 mapFilter(array2, fn) {
    const result = [];
    for (const item of array2) {
      const mapped = fn(item);
      if (mapped !== void 0) {
        result.push(mapped);
      }
    }
    return result;
  }
  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 "<unknown>";
    }
  }
  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,
            // eslint-disable-next-line local/code-no-any-casts
            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 "<unknown>";
    }
  }
  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,
            // eslint-disable-next-line local/code-no-any-casts
            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(
      // eslint-disable-next-line local/code-no-any-casts
      new DebugNameData(void 0, void 0, computeFnOrOwner),
      // eslint-disable-next-line local/code-no-any-casts
      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 = /(?<tag>[\w\-]+)?(?:#(?<id>[\w\-]+))?(?<class>(?:\.(?:[\w\-]+))*)(?:@(?<name>(?:[\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),
    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),
    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),
    build: register$2("build", 60506),
    commentDiscussionQuote: register$2("comment-discussion-quote", 60507),
    cursor: register$2("cursor", 60508),
    eraser: register$2("eraser", 60509),
    fileText: register$2("file-text", 60510),
    gitLens: register$2("git-lens", 60511),
    quotes: register$2("quotes", 60512),
    rename: register$2("rename", 60513),
    runWithDeps: register$2("run-with-deps", 60514),
    debugConnected: register$2("debug-connected", 60515),
    strikethrough: register$2("strikethrough", 60516),
    openInProduct: register$2("open-in-product", 60517),
    indexZero: register$2("index-zero", 60518),
    agent: register$2("agent", 60519),
    editCode: register$2("edit-code", 60520),
    repoSelected: register$2("repo-selected", 60521),
    skip: register$2("skip", 60522),
    mergeInto: register$2("merge-into", 60523),
    gitBranchChanges: register$2("git-branch-changes", 60524),
    gitBranchStagedChanges: register$2("git-branch-staged-changes", 60525),
    gitBranchConflicts: register$2("git-branch-conflicts", 60526),
    gitBranch: register$2("git-branch", 60527),
    gitBranchCreate: register$2("git-branch-create", 60527),
    gitBranchDelete: register$2("git-branch-delete", 60527),
    searchLarge: register$2("search-large", 60528),
    terminalGitBash: register$2("terminal-git-bash", 60529)
  };
  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;
    function isFile(icon) {
      return icon?.id === Codicon.file.id;
    }
    ThemeIcon2.isFile = isFile;
    function isFolder(icon) {
      return icon?.id === Codicon.folder.id;
    }
    ThemeIcon2.isFolder = isFolder;
  })(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(1693, "Did you mean {0}?", meant[0]);
      case 2:
        return localize(1694, "Did you mean {0} or {1}?", meant[0], meant[1]);
      case 3:
        return localize(1695, "Did you mean {0}, {1} or {2}?", meant[0], meant[1], meant[2]);
      default:
        return void 0;
    }
  }
  const hintDidYouForgetToOpenOrCloseQuote = localize(1696, "Did you forget to open or close the quote?");
  const hintDidYouForgetToEscapeSlash = localize(1697, "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(1675, "Empty context key expression");
  const hintEmptyString = localize(1676, "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(1677, "'in' after 'not'.");
  const errorClosingParenthesis = localize(1678, "closing parenthesis ')'");
  const errorUnexpectedToken = localize(1679, "Unexpected token");
  const hintUnexpectedToken = localize(1680, "Did you forget to put && or || before the token?");
  const errorUnexpectedEOF = localize(1681, "Unexpected end of expression");
  const hintUnexpectedEOF = localize(1682, "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(1683, "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$37 = 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$30 = 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.SCMHistoryItemRefContext = new _MenuId("SCMHistoryItemRefContext");
  _MenuId.SCMArtifactGroupContext = new _MenuId("SCMArtifactGroupContext");
  _MenuId.SCMArtifactContext = new _MenuId("SCMArtifactContext");
  _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.ChatWelcomeContext = new _MenuId("ChatWelcomeContext");
  _MenuId.ChatMessageFooter = new _MenuId("ChatMessageFooter");
  _MenuId.ChatExecute = new _MenuId("ChatExecute");
  _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.ChatNewMenu = new _MenuId("ChatNewMenu");
  _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.ChatSessionsCreateSubMenu = new _MenuId("ChatSessionsCreateSubMenu");
  _MenuId.ChatConfirmationMenu = new _MenuId("ChatConfirmationMenu");
  _MenuId.ChatEditorInlineExecute = new _MenuId("ChatEditorInputExecute");
  _MenuId.ChatEditorInlineInputSide = new _MenuId("ChatEditorInputSide");
  _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$37([
    __param$30(5, IContextKeyService),
    __param$30(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$1(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));
  const _TriggerInlineEditCommandsRegistry = class _TriggerInlineEditCommandsRegistry {
    static getRegisteredCommands() {
      return [..._TriggerInlineEditCommandsRegistry.REGISTERED_COMMANDS];
    }
    static registerCommand(commandId) {
      _TriggerInlineEditCommandsRegistry.REGISTERED_COMMANDS.add(commandId);
    }
  };
  _TriggerInlineEditCommandsRegistry.REGISTERED_COMMANDS = /* @__PURE__ */ new Set();
  let TriggerInlineEditCommandsRegistry = _TriggerInlineEditCommandsRegistry;
  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;
      this.canTriggerInlineEdits = opts.canTriggerInlineEdits;
    }
    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
      });
      if (this.canTriggerInlineEdits) {
        TriggerInlineEditCommandsRegistry.registerCommand(this.id);
      }
    }
    _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(69, "&&Undo"),
      order: 1
    }, {
      menuId: MenuId.CommandPalette,
      group: "",
      title: localize(70, "Undo"),
      order: 1
    }, {
      menuId: MenuId.SimpleEditorContext,
      group: "1_do",
      title: localize(71, "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(72, "&&Redo"),
      order: 2
    }, {
      menuId: MenuId.CommandPalette,
      group: "",
      title: localize(73, "Redo"),
      order: 1
    }, {
      menuId: MenuId.SimpleEditorContext,
      group: "1_do",
      title: localize(74, "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(75, "&&Select All"),
      order: 1
    }, {
      menuId: MenuId.CommandPalette,
      group: "",
      title: localize(76, "Select All"),
      order: 1
    }, {
      menuId: MenuId.SimpleEditorContext,
      group: "9_select",
      title: localize(77, "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 (prevWord && prevWord.wordType === 2 && 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 (nextWord2 && nextWord2.wordType === 2 && 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;
      }
      if (!isUndefined(cursorMoveArg.noHistory) && !isBoolean(cursorMoveArg.noHistory)) {
        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'.
					* 'noHistory': If 'true' does not add the movement to navigation history. 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
              },
              "noHistory": {
                "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,
        noHistory: !!args.noHistory
      };
    }
    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);
  let product;
  const vscodeGlobal = globalThis.vscode;
  if (typeof vscodeGlobal !== "undefined" && typeof vscodeGlobal.context !== "undefined") {
    const configuration = vscodeGlobal.context.configuration();
    if (configuration) {
      product = configuration.product;
    } else {
      throw new Error("Sandbox: unable to resolve product configuration from preload script.");
    }
  } else if (globalThis._VSCODE_PRODUCT_JSON && globalThis._VSCODE_PACKAGE_JSON) {
    product = globalThis._VSCODE_PRODUCT_JSON;
    if (env["VSCODE_DEV"]) {
      Object.assign(product, {
        nameShort: `${product.nameShort} Dev`,
        nameLong: `${product.nameLong} Dev`,
        dataFolderName: `${product.dataFolderName}-dev`,
        serverDataFolderName: product.serverDataFolderName ? `${product.serverDataFolderName}-dev` : void 0
      });
    }
    if (!product.version) {
      const pkg = globalThis._VSCODE_PACKAGE_JSON;
      Object.assign(product, {
        version: pkg.version
      });
    }
  } else {
    product = {
      /*BUILD->INSERT_PRODUCT_CONFIGURATION*/
    };
    if (Object.keys(product).length === 0) {
      Object.assign(product, {
        version: "1.104.0-dev",
        nameShort: "Code - OSS Dev",
        nameLong: "Code - OSS Dev",
        applicationName: "code-oss",
        dataFolderName: ".vscode-oss",
        urlProtocol: "code-oss",
        reportIssueUrl: "https://github.com/microsoft/vscode/issues/new",
        licenseName: "MIT",
        licenseUrl: "https://github.com/microsoft/vscode/blob/main/LICENSE.txt",
        serverLicenseUrl: "https://github.com/microsoft/vscode/blob/main/LICENSE.txt"
      });
    }
  }
  const product$1 = product;
  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(1664, "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 = {
        section: {
          id: this.defaultLanguageConfigurationOverridesNode.id,
          title: this.defaultLanguageConfigurationOverridesNode.title,
          order: this.defaultLanguageConfigurationOverridesNode.order,
          extensionInfo: this.defaultLanguageConfigurationOverridesNode.extensionInfo
        },
        type: "object",
        default: newDefaultOverride.value,
        description: localize(1665, "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];
          property.section = {
            id: configuration.id,
            title: configuration.title,
            order: configuration.order,
            extensionInfo: configuration.extensionInfo
          };
          if (validate && validateProperty(key, property, extensionInfo?.id)) {
            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(1666, "Configure editor settings to be overridden for a language."),
          errorMessage: localize(1667, "This setting does not support per-language configuration."),
          $ref: resourceLanguageSettingsSchemaId
        };
        this.updatePropertyDefaultValue(overrideIdentifierProperty, resourceLanguagePropertiesSchema);
      }
    }
    registerOverridePropertyPatternKey() {
      ({
        description: localize(1668, "Configure editor settings to be overridden for a language."),
        errorMessage: localize(1669, "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, extensionId) {
    if (!property.trim()) {
      return localize(1670, "Cannot register an empty property");
    }
    if (OVERRIDE_PROPERTY_REGEX.test(property)) {
      return localize(1671, "Cannot register '{0}'. This matches property pattern '\\\\[.*\\\\]$' for describing language specific editor settings. Use 'configurationDefaults' contribution.", property);
    }
    if (configurationRegistry$2.getConfigurationProperties()[property] !== void 0 && (!extensionId || !EXTENSION_UNIFICATION_EXTENSION_IDS.has(extensionId.toLowerCase()))) {
      return localize(1672, "Cannot register '{0}'. This property is already registered.", property);
    }
    if (schema.policy?.name && configurationRegistry$2.getPolicyConfigurations().get(schema.policy?.name) !== void 0) {
      return localize(1673, "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 EXTENSION_UNIFICATION_EXTENSION_IDS = new Set(product$1.defaultChatAgent ? [product$1.defaultChatAgent.extensionId, product$1.defaultChatAgent.chatExtensionId].map((id) => id.toLowerCase()) : []);
  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(784, "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$36 = 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);
    };
  };
  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$36([
    __param$2$(0, IConfigurationService),
    __param$2$(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$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 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$35([
    __param$2_(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(681, "Whether the editor text has focus (cursor is blinking)"));
    EditorContextKeys2.focus = new RawContextKey("editorFocus", false, localize(682, "Whether the editor or an editor widget has focus (e.g. focus is in the find widget)"));
    EditorContextKeys2.textInputFocus = new RawContextKey("textInputFocus", false, localize(683, "Whether an editor or a rich text input has focus (cursor is blinking)"));
    EditorContextKeys2.readOnly = new RawContextKey("editorReadonly", false, localize(684, "Whether the editor is read-only"));
    EditorContextKeys2.inDiffEditor = new RawContextKey("inDiffEditor", false, localize(685, "Whether the context is a diff editor"));
    EditorContextKeys2.isEmbeddedDiffEditor = new RawContextKey("isEmbeddedDiffEditor", false, localize(686, "Whether the context is an embedded diff editor"));
    EditorContextKeys2.inMultiDiffEditor = new RawContextKey("inMultiDiffEditor", false, localize(687, "Whether the context is a multi diff editor"));
    EditorContextKeys2.multiDiffEditorAllCollapsed = new RawContextKey("multiDiffEditorAllCollapsed", void 0, localize(688, "Whether all files in multi diff editor are collapsed"));
    EditorContextKeys2.hasChanges = new RawContextKey("diffEditorHasChanges", false, localize(689, "Whether the diff editor has changes"));
    EditorContextKeys2.comparingMovedCode = new RawContextKey("comparingMovedCode", false, localize(690, "Whether a moved code block is selected for comparison"));
    EditorContextKeys2.accessibleDiffViewerVisible = new RawContextKey("accessibleDiffViewerVisible", false, localize(691, "Whether the accessible diff viewer is visible"));
    EditorContextKeys2.diffEditorRenderSideBySideInlineBreakpointReached = new RawContextKey("diffEditorRenderSideBySideInlineBreakpointReached", false, localize(692, "Whether the diff editor render side by side inline breakpoint is reached"));
    EditorContextKeys2.diffEditorInlineMode = new RawContextKey("diffEditorInlineMode", false, localize(693, "Whether inline mode is active"));
    EditorContextKeys2.diffEditorOriginalWritable = new RawContextKey("diffEditorOriginalWritable", false, localize(694, "Whether modified is writable in the diff editor"));
    EditorContextKeys2.diffEditorModifiedWritable = new RawContextKey("diffEditorModifiedWritable", false, localize(695, "Whether modified is writable in the diff editor"));
    EditorContextKeys2.diffEditorOriginalUri = new RawContextKey("diffEditorOriginalUri", "", localize(696, "The uri of the original document"));
    EditorContextKeys2.diffEditorModifiedUri = new RawContextKey("diffEditorModifiedUri", "", localize(697, "The uri of the modified document"));
    EditorContextKeys2.columnSelection = new RawContextKey("editorColumnSelection", false, localize(698, "Whether `editor.columnSelection` is enabled"));
    EditorContextKeys2.writable = EditorContextKeys2.readOnly.toNegated();
    EditorContextKeys2.hasNonEmptySelection = new RawContextKey("editorHasSelection", false, localize(699, "Whether the editor has text selected"));
    EditorContextKeys2.hasOnlyEmptySelection = EditorContextKeys2.hasNonEmptySelection.toNegated();
    EditorContextKeys2.hasMultipleSelections = new RawContextKey("editorHasMultipleSelections", false, localize(700, "Whether the editor has multiple selections"));
    EditorContextKeys2.hasSingleSelection = EditorContextKeys2.hasMultipleSelections.toNegated();
    EditorContextKeys2.tabMovesFocus = new RawContextKey("editorTabMovesFocus", false, localize(701, "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(702, "Whether the editor hover is visible"));
    EditorContextKeys2.hoverFocused = new RawContextKey("editorHoverFocused", false, localize(703, "Whether the editor hover is focused"));
    EditorContextKeys2.stickyScrollFocused = new RawContextKey("stickyScrollFocused", false, localize(704, "Whether the sticky scroll is focused"));
    EditorContextKeys2.stickyScrollVisible = new RawContextKey("stickyScrollVisible", false, localize(705, "Whether the sticky scroll is visible"));
    EditorContextKeys2.standaloneColorPickerVisible = new RawContextKey("standaloneColorPickerVisible", false, localize(706, "Whether the standalone color picker is visible"));
    EditorContextKeys2.standaloneColorPickerFocused = new RawContextKey("standaloneColorPickerFocused", false, localize(707, "Whether the standalone color picker is focused"));
    EditorContextKeys2.inCompositeEditor = new RawContextKey("inCompositeEditor", void 0, localize(708, "Whether the editor is part of a larger editor (e.g. notebooks)"));
    EditorContextKeys2.notInCompositeEditor = EditorContextKeys2.inCompositeEditor.toNegated();
    EditorContextKeys2.languageId = new RawContextKey("editorLangId", "", localize(709, "The language identifier of the editor"));
    EditorContextKeys2.hasCompletionItemProvider = new RawContextKey("editorHasCompletionItemProvider", false, localize(710, "Whether the editor has a completion item provider"));
    EditorContextKeys2.hasCodeActionsProvider = new RawContextKey("editorHasCodeActionsProvider", false, localize(711, "Whether the editor has a code actions provider"));
    EditorContextKeys2.hasCodeLensProvider = new RawContextKey("editorHasCodeLensProvider", false, localize(712, "Whether the editor has a code lens provider"));
    EditorContextKeys2.hasDefinitionProvider = new RawContextKey("editorHasDefinitionProvider", false, localize(713, "Whether the editor has a definition provider"));
    EditorContextKeys2.hasDeclarationProvider = new RawContextKey("editorHasDeclarationProvider", false, localize(714, "Whether the editor has a declaration provider"));
    EditorContextKeys2.hasImplementationProvider = new RawContextKey("editorHasImplementationProvider", false, localize(715, "Whether the editor has an implementation provider"));
    EditorContextKeys2.hasTypeDefinitionProvider = new RawContextKey("editorHasTypeDefinitionProvider", false, localize(716, "Whether the editor has a type definition provider"));
    EditorContextKeys2.hasHoverProvider = new RawContextKey("editorHasHoverProvider", false, localize(717, "Whether the editor has a hover provider"));
    EditorContextKeys2.hasDocumentHighlightProvider = new RawContextKey("editorHasDocumentHighlightProvider", false, localize(718, "Whether the editor has a document highlight provider"));
    EditorContextKeys2.hasDocumentSymbolProvider = new RawContextKey("editorHasDocumentSymbolProvider", false, localize(719, "Whether the editor has a document symbol provider"));
    EditorContextKeys2.hasReferenceProvider = new RawContextKey("editorHasReferenceProvider", false, localize(720, "Whether the editor has a reference provider"));
    EditorContextKeys2.hasRenameProvider = new RawContextKey("editorHasRenameProvider", false, localize(721, "Whether the editor has a rename provider"));
    EditorContextKeys2.hasSignatureHelpProvider = new RawContextKey("editorHasSignatureHelpProvider", false, localize(722, "Whether the editor has a signature help provider"));
    EditorContextKeys2.hasInlayHintsProvider = new RawContextKey("editorHasInlayHintsProvider", false, localize(723, "Whether the editor has an inline hints provider"));
    EditorContextKeys2.hasDocumentFormattingProvider = new RawContextKey("editorHasDocumentFormattingProvider", false, localize(724, "Whether the editor has a document formatting provider"));
    EditorContextKeys2.hasDocumentSelectionFormattingProvider = new RawContextKey("editorHasDocumentSelectionFormattingProvider", false, localize(725, "Whether the editor has a document selection formatting provider"));
    EditorContextKeys2.hasMultipleDocumentFormattingProvider = new RawContextKey("editorHasMultipleDocumentFormattingProvider", false, localize(726, "Whether the editor has multiple document formatting providers"));
    EditorContextKeys2.hasMultipleDocumentSelectionFormattingProvider = new RawContextKey("editorHasMultipleDocumentSelectionFormattingProvider", false, localize(727, "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) {
        const effectiveSource = args.noHistory ? "api" : source;
        viewModel.model.pushStackElement();
        viewModel.setCursorStates(effectiveSource, 3, CursorMoveImpl._move(viewModel, viewModel.getCursorStates(), args));
        viewModel.revealAllCursors(effectiveSource, 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(66, "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(67, "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(68, "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$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);
    };
  };
  let MarkerDecorationsContribution = (_d = class {
    constructor(_editor, _markerDecorationsService) {
    }
    dispose() {
    }
  }, _d.ID = "editor.contrib.markerDecorations", _d);
  MarkerDecorationsContribution = __decorate$34([
    __param$2Z(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 EditorZoom = new class {
    constructor() {
      this._zoomLevel = 0;
      this._onDidChangeZoomLevel = new Emitter$1();
      this.onDidChangeZoomLevel = this._onDidChangeZoomLevel.event;
    }
    getZoomLevel() {
      return this._zoomLevel;
    }
    setZoomLevel(zoomLevel) {
      zoomLevel = Math.min(Math.max(-5, zoomLevel), 20);
      if (this._zoomLevel === zoomLevel) {
        return;
      }
      this._zoomLevel = zoomLevel;
      this._onDidChangeZoomLevel.fire(this._zoomLevel);
    }
  }();
  const GOLDEN_LINE_HEIGHT_RATIO = isMacintosh ? 1.5 : 1.35;
  const MINIMUM_LINE_HEIGHT = 8;
  class BareFontInfo {
    /**
     * @internal
     */
    static _create(fontFamily, fontWeight, fontSize, fontFeatureSettings, fontVariationSettings, lineHeight, letterSpacing, pixelRatio, ignoreEditorZoom) {
      if (lineHeight === 0) {
        lineHeight = GOLDEN_LINE_HEIGHT_RATIO * fontSize;
      } else if (lineHeight < MINIMUM_LINE_HEIGHT) {
        lineHeight = lineHeight * fontSize;
      }
      lineHeight = Math.round(lineHeight);
      if (lineHeight < MINIMUM_LINE_HEIGHT) {
        lineHeight = MINIMUM_LINE_HEIGHT;
      }
      const editorZoomLevelMultiplier = 1 + (ignoreEditorZoom ? 0 : EditorZoom.getZoomLevel() * 0.1);
      fontSize *= editorZoomLevelMultiplier;
      lineHeight *= editorZoomLevelMultiplier;
      if (fontVariationSettings === FONT_VARIATION_TRANSLATE) {
        if (fontWeight === "normal" || fontWeight === "bold") {
          fontVariationSettings = FONT_VARIATION_OFF;
        } else {
          const fontWeightAsNumber = parseInt(fontWeight, 10);
          fontVariationSettings = `'wght' ${fontWeightAsNumber}`;
          fontWeight = "normal";
        }
      }
      return new BareFontInfo({
        pixelRatio,
        fontFamily,
        fontWeight,
        fontSize,
        fontFeatureSettings,
        fontVariationSettings,
        lineHeight,
        letterSpacing
      });
    }
    /**
     * @internal
     */
    constructor(opts) {
      this._bareFontInfoBrand = void 0;
      this.pixelRatio = opts.pixelRatio;
      this.fontFamily = String(opts.fontFamily);
      this.fontWeight = String(opts.fontWeight);
      this.fontSize = opts.fontSize;
      this.fontFeatureSettings = opts.fontFeatureSettings;
      this.fontVariationSettings = opts.fontVariationSettings;
      this.lineHeight = opts.lineHeight | 0;
      this.letterSpacing = opts.letterSpacing;
    }
    /**
     * @internal
     */
    getId() {
      return `${this.pixelRatio}-${this.fontFamily}-${this.fontWeight}-${this.fontSize}-${this.fontFeatureSettings}-${this.fontVariationSettings}-${this.lineHeight}-${this.letterSpacing}`;
    }
    /**
     * @internal
     */
    getMassagedFontFamily() {
      const fallbackFontFamily = EDITOR_FONT_DEFAULTS.fontFamily;
      const fontFamily = BareFontInfo._wrapInQuotes(this.fontFamily);
      if (this.fontFamily !== fallbackFontFamily) {
        return `${fontFamily}, ${fallbackFontFamily}`;
      }
      return fontFamily;
    }
    static _wrapInQuotes(fontFamily) {
      if (/[,"']/.test(fontFamily)) {
        return fontFamily;
      }
      if (/[+ ]/.test(fontFamily)) {
        return `"${fontFamily}"`;
      }
      return fontFamily;
    }
  }
  const SERIALIZED_FONT_INFO_VERSION = 2;
  class FontInfo extends BareFontInfo {
    /**
     * @internal
     */
    constructor(opts, isTrusted) {
      super(opts);
      this._editorStylingBrand = void 0;
      this.version = SERIALIZED_FONT_INFO_VERSION;
      this.isTrusted = isTrusted;
      this.isMonospace = opts.isMonospace;
      this.typicalHalfwidthCharacterWidth = opts.typicalHalfwidthCharacterWidth;
      this.typicalFullwidthCharacterWidth = opts.typicalFullwidthCharacterWidth;
      this.canUseHalfwidthRightwardsArrow = opts.canUseHalfwidthRightwardsArrow;
      this.spaceWidth = opts.spaceWidth;
      this.middotWidth = opts.middotWidth;
      this.wsmiddotWidth = opts.wsmiddotWidth;
      this.maxDigitWidth = opts.maxDigitWidth;
    }
    /**
     * @internal
     */
    equals(other) {
      return this.fontFamily === other.fontFamily && this.fontWeight === other.fontWeight && this.fontSize === other.fontSize && this.fontFeatureSettings === other.fontFeatureSettings && this.fontVariationSettings === other.fontVariationSettings && this.lineHeight === other.lineHeight && this.letterSpacing === other.letterSpacing && this.typicalHalfwidthCharacterWidth === other.typicalHalfwidthCharacterWidth && this.typicalFullwidthCharacterWidth === other.typicalFullwidthCharacterWidth && this.canUseHalfwidthRightwardsArrow === other.canUseHalfwidthRightwardsArrow && this.spaceWidth === other.spaceWidth && this.middotWidth === other.middotWidth && this.wsmiddotWidth === other.wsmiddotWidth && this.maxDigitWidth === other.maxDigitWidth;
    }
  }
  const FONT_VARIATION_OFF = "normal";
  const FONT_VARIATION_TRANSLATE = "translate";
  const DEFAULT_WINDOWS_FONT_FAMILY = "Consolas, 'Courier New', monospace";
  const DEFAULT_MAC_FONT_FAMILY = "Menlo, Monaco, 'Courier New', monospace";
  const DEFAULT_LINUX_FONT_FAMILY = "'Droid Sans Mono', 'monospace', monospace";
  const EDITOR_FONT_DEFAULTS = {
    fontFamily: isMacintosh ? DEFAULT_MAC_FONT_FAMILY : isWindows ? DEFAULT_WINDOWS_FONT_FAMILY : DEFAULT_LINUX_FONT_FAMILY,
    fontWeight: "normal",
    fontSize: isMacintosh ? 12 : 14,
    lineHeight: 0,
    letterSpacing: 0
  };
  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, defaultValue) {
      this.schema = void 0;
      this.id = id;
      this.name = "_never_";
      this.defaultValue = defaultValue;
    }
    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);
    }
    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 === "string") {
      value = parseInt(value, 10);
    }
    if (typeof value !== "number" || isNaN(value)) {
      return defaultValue;
    }
    let r = value;
    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 === "string") {
        value = parseFloat(value);
      }
      if (typeof value !== "number" || isNaN(value)) {
        return defaultValue;
      }
      return value;
    }
    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.slice(0);
        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(201, "Use platform APIs to detect when a Screen Reader is attached."),
          localize(202, "Optimize for usage with a Screen Reader."),
          localize(203, "Assume a screen reader is not attached.")
        ],
        default: "auto",
        tags: ["accessibility"],
        description: localize(204, "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(205, "Controls whether a space character is inserted when commenting.")
        },
        "editor.comments.ignoreEmptyLines": {
          type: "boolean",
          default: defaults.ignoreEmptyLines,
          description: localize(206, "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, "");
    }
    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(207, "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(208, "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(209, "Never seed search string from the editor selection."),
            localize(210, "Always seed search string from the editor selection, including word at cursor position."),
            localize(211, "Only seed search string from the editor selection.")
          ],
          description: localize(212, "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(213, "Never turn on Find in Selection automatically (default)."),
            localize(214, "Always turn on Find in Selection automatically."),
            localize(215, "Turn on Find in Selection automatically when multiple lines of content are selected.")
          ],
          description: localize(216, "Controls the condition for turning on Find in Selection automatically.")
        },
        "editor.find.globalFindClipboard": {
          type: "boolean",
          default: defaults.globalFindClipboard,
          description: localize(217, "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(218, "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(219, "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(220, "Do not store search history from the find widget."),
            localize(221, "Store search history across the active workspace")
          ],
          description: localize(222, "Controls how the find widget history should be stored")
        },
        "editor.find.replaceHistory": {
          type: "string",
          enum: ["never", "workspace"],
          default: "workspace",
          enumDescriptions: [
            localize(223, "Do not store history from the replace widget."),
            localize(224, "Store replace history across the active workspace")
          ],
          description: localize(225, "Controls how the replace widget history should be stored")
        },
        "editor.find.findOnType": {
          type: "boolean",
          default: defaults.findOnType,
          description: localize(226, "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(227, "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(228, "Explicit 'font-feature-settings' CSS property. A boolean can be passed instead if one only needs to turn on/off ligatures.")
          }
        ],
        description: localize(229, "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(230, "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(231, "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(232, "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 = FONT_VARIATION_OFF;
  _EditorFontVariations.TRANSLATE = FONT_VARIATION_TRANSLATE;
  let EditorFontVariations = _EditorFontVariations;
  class EditorFontInfo extends ComputedEditorOption {
    constructor() {
      super(59, new FontInfo({
        pixelRatio: 0,
        fontFamily: "",
        fontWeight: "",
        fontSize: 0,
        fontFeatureSettings: "",
        fontVariationSettings: "",
        lineHeight: 0,
        letterSpacing: 0,
        isMonospace: false,
        typicalHalfwidthCharacterWidth: 0,
        typicalFullwidthCharacterWidth: 0,
        canUseHalfwidthRightwardsArrow: false,
        spaceWidth: 0,
        middotWidth: 0,
        wsmiddotWidth: 0,
        maxDigitWidth: 0
      }, false));
    }
    compute(env2, options, _) {
      return env2.fontInfo;
    }
  }
  class EffectiveCursorStyle extends ComputedEditorOption {
    constructor() {
      super(161, TextEditorCursorStyle$1.Line);
    }
    compute(env2, options, _) {
      return env2.inputMode === "overtype" ? options.get(
        92
        /* EditorOption.overtypeCursorStyle */
      ) : options.get(
        34
        /* EditorOption.cursorStyle */
      );
    }
  }
  class EffectiveEditContextEnabled extends ComputedEditorOption {
    constructor() {
      super(170, false);
    }
    compute(env2, options) {
      return env2.editContextSupported && options.get(
        44
        /* EditorOption.editContext */
      );
    }
  }
  class EffectiveAllowVariableFonts extends ComputedEditorOption {
    constructor() {
      super(172, false);
    }
    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(233, "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(234, '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(235, '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(236, "Show Peek view of the results (default)"),
          localize(237, "Go to the primary result and show a Peek view"),
          localize(238, "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(239, "This setting is deprecated, please use separate settings like 'editor.editor.gotoLocation.multipleDefinitions' or 'editor.editor.gotoLocation.multipleImplementations' instead.")
        },
        "editor.gotoLocation.multipleDefinitions": {
          description: localize(240, "Controls the behavior the 'Go to Definition'-command when multiple target locations exist."),
          ...jsonSubset
        },
        "editor.gotoLocation.multipleTypeDefinitions": {
          description: localize(241, "Controls the behavior the 'Go to Type Definition'-command when multiple target locations exist."),
          ...jsonSubset
        },
        "editor.gotoLocation.multipleDeclarations": {
          description: localize(242, "Controls the behavior the 'Go to Declaration'-command when multiple target locations exist."),
          ...jsonSubset
        },
        "editor.gotoLocation.multipleImplementations": {
          description: localize(243, "Controls the behavior the 'Go to Implementations'-command when multiple target locations exist."),
          ...jsonSubset
        },
        "editor.gotoLocation.multipleReferences": {
          description: localize(244, "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(245, "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(246, "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(247, "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(248, "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(249, "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: stringSet(input.multipleDefinitions, "peek", ["peek", "gotoAndPeek", "goto"]),
        multipleTypeDefinitions: stringSet(input.multipleTypeDefinitions, "peek", ["peek", "gotoAndPeek", "goto"]),
        multipleDeclarations: stringSet(input.multipleDeclarations, "peek", ["peek", "gotoAndPeek", "goto"]),
        multipleImplementations: stringSet(input.multipleImplementations, "peek", ["peek", "gotoAndPeek", "goto"]),
        multipleReferences: stringSet(input.multipleReferences, "peek", ["peek", "gotoAndPeek", "goto"]),
        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(250, "Controls whether the hover is shown.")
        },
        "editor.hover.delay": {
          type: "number",
          default: defaults.delay,
          minimum: 0,
          maximum: 1e4,
          description: localize(251, "Controls the delay in milliseconds after which the hover is shown.")
        },
        "editor.hover.sticky": {
          type: "boolean",
          default: defaults.sticky,
          description: localize(252, "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(253, "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(254, "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, {
        width: 0,
        height: 0,
        glyphMarginLeft: 0,
        glyphMarginWidth: 0,
        glyphMarginDecorationLaneCount: 0,
        lineNumbersLeft: 0,
        lineNumbersWidth: 0,
        decorationsLeft: 0,
        decorationsWidth: 0,
        contentLeft: 0,
        contentWidth: 0,
        minimap: {
          renderMinimap: 0,
          minimapLeft: 0,
          minimapWidth: 0,
          minimapHeightIsEditorHeight: false,
          minimapIsSampling: false,
          minimapScale: 1,
          minimapLineHeight: 1,
          minimapCanvasInnerWidth: 0,
          minimapCanvasInnerHeight: 0,
          minimapCanvasOuterWidth: 0,
          minimapCanvasOuterHeight: 0
        },
        viewportColumn: 0,
        isWordWrapMinified: false,
        isViewportWrapping: false,
        wrappingColumn: -1,
        verticalScrollbarWidth: 0,
        horizontalScrollbarHeight: 0,
        overviewRuler: {
          top: 0,
          width: 0,
          height: 0,
          right: 0
        }
      });
    }
    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(255, "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(256, "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(257, "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(258, "Disable the code action menu."),
            localize(259, "Show the code action menu when the cursor is on lines with code."),
            localize(260, "Show the code action menu when the cursor is on lines with code or on empty lines.")
          ],
          description: localize(261, "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(262, "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(263, "Defines the maximum number of sticky lines to show.")
        },
        "editor.stickyScroll.defaultModel": {
          type: "string",
          enum: ["outlineModel", "foldingProviderModel", "indentationModel"],
          default: defaults.defaultModel,
          description: localize(264, "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(265, "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(266, "Enables the inlay hints in the editor."),
          enum: ["on", "onUnlessPressed", "offUnlessPressed", "off"],
          markdownEnumDescriptions: [
            localize(267, "Inlay hints are enabled"),
            localize(268, "Inlay hints are showing by default and hide when holding {0}", isMacintosh ? `Ctrl+Option` : `Ctrl+Alt`),
            localize(269, "Inlay hints are hidden by default and show when holding {0}", isMacintosh ? `Ctrl+Option` : `Ctrl+Alt`),
            localize(270, "Inlay hints are disabled")
          ]
        },
        "editor.inlayHints.fontSize": {
          type: "number",
          default: defaults.fontSize,
          markdownDescription: localize(271, "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(272, "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(273, "Enables the padding around the inlay hints in the editor.")
        },
        "editor.inlayHints.maximumLength": {
          type: "number",
          default: defaults.maximumLength,
          markdownDescription: localize(274, "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(275, "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*(?<separator>-?)\\s*(?<label>.*)$",
        sectionHeaderFontSize: 9,
        sectionHeaderLetterSpacing: 1
      };
      super(81, "minimap", defaults, {
        "editor.minimap.enabled": {
          type: "boolean",
          default: defaults.enabled,
          description: localize(276, "Controls whether the minimap is shown.")
        },
        "editor.minimap.autohide": {
          type: "string",
          enum: ["none", "mouseover", "scroll"],
          enumDescriptions: [
            localize(277, "The minimap is always shown."),
            localize(278, "The minimap is hidden when mouse is not over the minimap and shown when mouse is over the minimap."),
            localize(279, "The minimap is only shown when the editor is scrolled")
          ],
          default: defaults.autohide,
          description: localize(280, "Controls whether the minimap is hidden automatically.")
        },
        "editor.minimap.size": {
          type: "string",
          enum: ["proportional", "fill", "fit"],
          enumDescriptions: [
            localize(281, "The minimap has the same size as the editor contents (and might scroll)."),
            localize(282, "The minimap will stretch or shrink as necessary to fill the height of the editor (no scrolling)."),
            localize(283, "The minimap will shrink as necessary to never be larger than the editor (no scrolling).")
          ],
          default: defaults.size,
          description: localize(284, "Controls the size of the minimap.")
        },
        "editor.minimap.side": {
          type: "string",
          enum: ["left", "right"],
          default: defaults.side,
          description: localize(285, "Controls the side where to render the minimap.")
        },
        "editor.minimap.showSlider": {
          type: "string",
          enum: ["always", "mouseover"],
          default: defaults.showSlider,
          description: localize(286, "Controls when the minimap slider is shown.")
        },
        "editor.minimap.scale": {
          type: "number",
          default: defaults.scale,
          minimum: 1,
          maximum: 3,
          enum: [1, 2, 3],
          description: localize(287, "Scale of content drawn in the minimap: 1, 2 or 3.")
        },
        "editor.minimap.renderCharacters": {
          type: "boolean",
          default: defaults.renderCharacters,
          description: localize(288, "Render the actual characters on a line as opposed to color blocks.")
        },
        "editor.minimap.maxColumn": {
          type: "number",
          default: defaults.maxColumn,
          description: localize(289, "Limit the width of the minimap to render at most a certain number of columns.")
        },
        "editor.minimap.showRegionSectionHeaders": {
          type: "boolean",
          default: defaults.showRegionSectionHeaders,
          description: localize(290, "Controls whether named regions are shown as section headers in the minimap.")
        },
        "editor.minimap.showMarkSectionHeaders": {
          type: "boolean",
          default: defaults.showMarkSectionHeaders,
          description: localize(291, "Controls whether MARK: comments are shown as section headers in the minimap.")
        },
        "editor.minimap.markSectionHeaderRegex": {
          type: "string",
          default: defaults.markSectionHeaderRegex,
          description: localize(292, "Defines the regular expression used to find section headers in comments. The regex must contain a named match group `label` (written as `(?<label>.+)`) that encapsulates the section header, otherwise it will not work. Optionally you can include another match group named `separator`. Use \\n in the pattern to match multi-line headers.")
        },
        "editor.minimap.sectionHeaderFontSize": {
          type: "number",
          default: defaults.sectionHeaderFontSize,
          description: localize(293, "Controls the font size of section headers in the minimap.")
        },
        "editor.minimap.sectionHeaderLetterSpacing": {
          type: "number",
          default: defaults.sectionHeaderLetterSpacing,
          description: localize(294, "Controls the amount of space (in pixels) between characters of section header. This helps the readability of the header in small font sizes.")
        }
      });
    }
    validate(_input) {
      if (!_input || typeof _input !== "object") {
        return this.defaultValue;
      }
      const input = _input;
      let markSectionHeaderRegex = this.defaultValue.markSectionHeaderRegex;
      const inputRegex = input.markSectionHeaderRegex;
      if (typeof inputRegex === "string") {
        try {
          new RegExp(inputRegex, "d");
          markSectionHeaderRegex = inputRegex;
        } catch {
        }
      }
      return {
        enabled: boolean(input.enabled, this.defaultValue.enabled),
        autohide: stringSet(input.autohide, this.defaultValue.autohide, ["none", "mouseover", "scroll"]),
        size: stringSet(input.size, this.defaultValue.size, ["proportional", "fill", "fit"]),
        side: stringSet(input.side, this.defaultValue.side, ["right", "left"]),
        showSlider: stringSet(input.showSlider, this.defaultValue.showSlider, ["always", "mouseover"]),
        renderCharacters: boolean(input.renderCharacters, this.defaultValue.renderCharacters),
        scale: EditorIntOption.clampedInt(input.scale, 1, 1, 3),
        maxColumn: EditorIntOption.clampedInt(input.maxColumn, this.defaultValue.maxColumn, 1, 1e4),
        showRegionSectionHeaders: boolean(input.showRegionSectionHeaders, this.defaultValue.showRegionSectionHeaders),
        showMarkSectionHeaders: boolean(input.showMarkSectionHeaders, this.defaultValue.showMarkSectionHeaders),
        markSectionHeaderRegex,
        sectionHeaderFontSize: EditorFloatOption.clamp(EditorFloatOption.float(input.sectionHeaderFontSize, this.defaultValue.sectionHeaderFontSize), 4, 32),
        sectionHeaderLetterSpacing: EditorFloatOption.clamp(EditorFloatOption.float(input.sectionHeaderLetterSpacing, this.defaultValue.sectionHeaderLetterSpacing), 0, 5)
      };
    }
  }
  function _multiCursorModifierFromString(multiCursorModifier) {
    if (multiCursorModifier === "ctrlCmd") {
      return isMacintosh ? "metaKey" : "ctrlKey";
    }
    return "altKey";
  }
  class EditorPadding extends BaseEditorOption {
    constructor() {
      super(96, "padding", { top: 0, bottom: 0 }, {
        "editor.padding.top": {
          type: "number",
          default: 0,
          minimum: 0,
          maximum: 1e3,
          description: localize(295, "Controls the amount of space between the top edge of the editor and the first line.")
        },
        "editor.padding.bottom": {
          type: "number",
          default: 0,
          minimum: 0,
          maximum: 1e3,
          description: localize(296, "Controls the amount of space between the bottom edge of the editor and the last line.")
        }
      });
    }
    validate(_input) {
      if (!_input || typeof _input !== "object") {
        return this.defaultValue;
      }
      const input = _input;
      return {
        top: EditorIntOption.clampedInt(input.top, 0, 0, 1e3),
        bottom: EditorIntOption.clampedInt(input.bottom, 0, 0, 1e3)
      };
    }
  }
  class EditorParameterHints extends BaseEditorOption {
    constructor() {
      const defaults = {
        enabled: true,
        cycle: true
      };
      super(98, "parameterHints", defaults, {
        "editor.parameterHints.enabled": {
          type: "boolean",
          default: defaults.enabled,
          description: localize(297, "Enables a pop-up that shows parameter documentation and type information as you type.")
        },
        "editor.parameterHints.cycle": {
          type: "boolean",
          default: defaults.cycle,
          description: localize(298, "Controls whether the parameter hints menu cycles or closes when reaching the end of the list.")
        }
      });
    }
    validate(_input) {
      if (!_input || typeof _input !== "object") {
        return this.defaultValue;
      }
      const input = _input;
      return {
        enabled: boolean(input.enabled, this.defaultValue.enabled),
        cycle: boolean(input.cycle, this.defaultValue.cycle)
      };
    }
  }
  class EditorPixelRatio extends ComputedEditorOption {
    constructor() {
      super(163, 1);
    }
    compute(env2, options, _) {
      return env2.pixelRatio;
    }
  }
  class PlaceholderOption extends BaseEditorOption {
    constructor() {
      super(100, "placeholder", void 0);
    }
    validate(input) {
      if (typeof input === "undefined") {
        return this.defaultValue;
      }
      if (typeof input === "string") {
        return input;
      }
      return this.defaultValue;
    }
  }
  class EditorQuickSuggestions extends BaseEditorOption {
    constructor() {
      const defaults = {
        other: "on",
        comments: "off",
        strings: "off"
      };
      const types = [
        { type: "boolean" },
        {
          type: "string",
          enum: ["on", "inline", "off"],
          enumDescriptions: [localize(299, "Quick suggestions show inside the suggest widget"), localize(300, "Quick suggestions show as ghost text"), localize(301, "Quick suggestions are disabled")]
        }
      ];
      super(102, "quickSuggestions", defaults, {
        type: "object",
        additionalProperties: false,
        properties: {
          strings: {
            anyOf: types,
            default: defaults.strings,
            description: localize(302, "Enable quick suggestions inside strings.")
          },
          comments: {
            anyOf: types,
            default: defaults.comments,
            description: localize(303, "Enable quick suggestions inside comments.")
          },
          other: {
            anyOf: types,
            default: defaults.other,
            description: localize(304, "Enable quick suggestions outside of strings and comments.")
          }
        },
        default: defaults,
        markdownDescription: localize(305, "Controls whether suggestions should automatically show up while typing. This can be controlled for typing in comments, strings, and other code. Quick suggestion can be configured to show as ghost text or with the suggest widget. Also be aware of the {0}-setting which controls if suggestions are triggered by special characters.", "`#editor.suggestOnTriggerCharacters#`")
      });
      this.defaultValue = defaults;
    }
    validate(input) {
      if (typeof input === "boolean") {
        const value = input ? "on" : "off";
        return { comments: value, strings: value, other: value };
      }
      if (!input || typeof input !== "object") {
        return this.defaultValue;
      }
      const { other, comments, strings } = input;
      const allowedValues = ["on", "inline", "off"];
      let validatedOther;
      let validatedComments;
      let validatedStrings;
      if (typeof other === "boolean") {
        validatedOther = other ? "on" : "off";
      } else {
        validatedOther = stringSet(other, this.defaultValue.other, allowedValues);
      }
      if (typeof comments === "boolean") {
        validatedComments = comments ? "on" : "off";
      } else {
        validatedComments = stringSet(comments, this.defaultValue.comments, allowedValues);
      }
      if (typeof strings === "boolean") {
        validatedStrings = strings ? "on" : "off";
      } else {
        validatedStrings = stringSet(strings, this.defaultValue.strings, allowedValues);
      }
      return {
        other: validatedOther,
        comments: validatedComments,
        strings: validatedStrings
      };
    }
  }
  class EditorRenderLineNumbersOption extends BaseEditorOption {
    constructor() {
      super(76, "lineNumbers", { renderType: 1, renderFn: null }, {
        type: "string",
        enum: ["off", "on", "relative", "interval"],
        enumDescriptions: [
          localize(306, "Line numbers are not rendered."),
          localize(307, "Line numbers are rendered as absolute number."),
          localize(308, "Line numbers are rendered as distance in lines to cursor position."),
          localize(309, "Line numbers are rendered every 10 lines.")
        ],
        default: "on",
        description: localize(310, "Controls the display of line numbers.")
      });
    }
    validate(lineNumbers) {
      let renderType = this.defaultValue.renderType;
      let renderFn = this.defaultValue.renderFn;
      if (typeof lineNumbers !== "undefined") {
        if (typeof lineNumbers === "function") {
          renderType = 4;
          renderFn = lineNumbers;
        } else if (lineNumbers === "interval") {
          renderType = 3;
        } else if (lineNumbers === "relative") {
          renderType = 2;
        } else if (lineNumbers === "on") {
          renderType = 1;
        } else {
          renderType = 0;
        }
      }
      return {
        renderType,
        renderFn
      };
    }
  }
  function filterValidationDecorations(options) {
    const renderValidationDecorations = options.get(
      112
      /* EditorOption.renderValidationDecorations */
    );
    if (renderValidationDecorations === "editable") {
      return options.get(
        104
        /* EditorOption.readOnly */
      );
    }
    return renderValidationDecorations === "on" ? false : true;
  }
  function filterFontDecorations(options) {
    return !options.get(
      172
      /* EditorOption.effectiveAllowVariableFonts */
    );
  }
  class EditorRulers extends BaseEditorOption {
    constructor() {
      const defaults = [];
      const columnSchema = { type: "number", description: localize(311, "Number of monospace characters at which this editor ruler will render.") };
      super(116, "rulers", defaults, {
        type: "array",
        items: {
          anyOf: [
            columnSchema,
            {
              type: [
                "object"
              ],
              properties: {
                column: columnSchema,
                color: {
                  type: "string",
                  description: localize(312, "Color of this editor ruler."),
                  format: "color-hex"
                }
              }
            }
          ]
        },
        default: defaults,
        description: localize(313, "Render vertical rulers after a certain number of monospace characters. Use multiple values for multiple rulers. No rulers are drawn if array is empty.")
      });
    }
    validate(input) {
      if (Array.isArray(input)) {
        const rulers = [];
        for (const _element of input) {
          if (typeof _element === "number") {
            rulers.push({
              column: EditorIntOption.clampedInt(_element, 0, 0, 1e4),
              color: null
            });
          } else if (_element && typeof _element === "object") {
            const element = _element;
            rulers.push({
              column: EditorIntOption.clampedInt(element.column, 0, 0, 1e4),
              color: element.color
            });
          }
        }
        rulers.sort((a, b) => a.column - b.column);
        return rulers;
      }
      return this.defaultValue;
    }
  }
  class ReadonlyMessage extends BaseEditorOption {
    constructor() {
      const defaults = void 0;
      super(105, "readOnlyMessage", defaults);
    }
    validate(_input) {
      if (!_input || typeof _input !== "object") {
        return this.defaultValue;
      }
      return _input;
    }
  }
  function _scrollbarVisibilityFromString(visibility, defaultValue) {
    if (typeof visibility !== "string") {
      return defaultValue;
    }
    switch (visibility) {
      case "hidden":
        return 2;
      case "visible":
        return 3;
      default:
        return 1;
    }
  }
  let EditorScrollbar$1 = class EditorScrollbar extends BaseEditorOption {
    constructor() {
      const defaults = {
        vertical: 1,
        horizontal: 1,
        arrowSize: 11,
        useShadows: true,
        verticalHasArrows: false,
        horizontalHasArrows: false,
        horizontalScrollbarSize: 12,
        horizontalSliderSize: 12,
        verticalScrollbarSize: 14,
        verticalSliderSize: 14,
        handleMouseWheel: true,
        alwaysConsumeMouseWheel: true,
        scrollByPage: false,
        ignoreHorizontalScrollbarInContentHeight: false
      };
      super(117, "scrollbar", defaults, {
        "editor.scrollbar.vertical": {
          type: "string",
          enum: ["auto", "visible", "hidden"],
          enumDescriptions: [
            localize(314, "The vertical scrollbar will be visible only when necessary."),
            localize(315, "The vertical scrollbar will always be visible."),
            localize(316, "The vertical scrollbar will always be hidden.")
          ],
          default: "auto",
          description: localize(317, "Controls the visibility of the vertical scrollbar.")
        },
        "editor.scrollbar.horizontal": {
          type: "string",
          enum: ["auto", "visible", "hidden"],
          enumDescriptions: [
            localize(318, "The horizontal scrollbar will be visible only when necessary."),
            localize(319, "The horizontal scrollbar will always be visible."),
            localize(320, "The horizontal scrollbar will always be hidden.")
          ],
          default: "auto",
          description: localize(321, "Controls the visibility of the horizontal scrollbar.")
        },
        "editor.scrollbar.verticalScrollbarSize": {
          type: "number",
          default: defaults.verticalScrollbarSize,
          description: localize(322, "The width of the vertical scrollbar.")
        },
        "editor.scrollbar.horizontalScrollbarSize": {
          type: "number",
          default: defaults.horizontalScrollbarSize,
          description: localize(323, "The height of the horizontal scrollbar.")
        },
        "editor.scrollbar.scrollByPage": {
          type: "boolean",
          default: defaults.scrollByPage,
          description: localize(324, "Controls whether clicks scroll by page or jump to click position.")
        },
        "editor.scrollbar.ignoreHorizontalScrollbarInContentHeight": {
          type: "boolean",
          default: defaults.ignoreHorizontalScrollbarInContentHeight,
          description: localize(325, "When set, the horizontal scrollbar will not increase the size of the editor's content.")
        }
      });
    }
    validate(_input) {
      if (!_input || typeof _input !== "object") {
        return this.defaultValue;
      }
      const input = _input;
      const horizontalScrollbarSize = EditorIntOption.clampedInt(input.horizontalScrollbarSize, this.defaultValue.horizontalScrollbarSize, 0, 1e3);
      const verticalScrollbarSize = EditorIntOption.clampedInt(input.verticalScrollbarSize, this.defaultValue.verticalScrollbarSize, 0, 1e3);
      return {
        arrowSize: EditorIntOption.clampedInt(input.arrowSize, this.defaultValue.arrowSize, 0, 1e3),
        vertical: _scrollbarVisibilityFromString(input.vertical, this.defaultValue.vertical),
        horizontal: _scrollbarVisibilityFromString(input.horizontal, this.defaultValue.horizontal),
        useShadows: boolean(input.useShadows, this.defaultValue.useShadows),
        verticalHasArrows: boolean(input.verticalHasArrows, this.defaultValue.verticalHasArrows),
        horizontalHasArrows: boolean(input.horizontalHasArrows, this.defaultValue.horizontalHasArrows),
        handleMouseWheel: boolean(input.handleMouseWheel, this.defaultValue.handleMouseWheel),
        alwaysConsumeMouseWheel: boolean(input.alwaysConsumeMouseWheel, this.defaultValue.alwaysConsumeMouseWheel),
        horizontalScrollbarSize,
        horizontalSliderSize: EditorIntOption.clampedInt(input.horizontalSliderSize, horizontalScrollbarSize, 0, 1e3),
        verticalScrollbarSize,
        verticalSliderSize: EditorIntOption.clampedInt(input.verticalSliderSize, verticalScrollbarSize, 0, 1e3),
        scrollByPage: boolean(input.scrollByPage, this.defaultValue.scrollByPage),
        ignoreHorizontalScrollbarInContentHeight: boolean(input.ignoreHorizontalScrollbarInContentHeight, this.defaultValue.ignoreHorizontalScrollbarInContentHeight)
      };
    }
  };
  const inUntrustedWorkspace = "inUntrustedWorkspace";
  const unicodeHighlightConfigKeys = {
    allowedCharacters: "editor.unicodeHighlight.allowedCharacters",
    invisibleCharacters: "editor.unicodeHighlight.invisibleCharacters",
    nonBasicASCII: "editor.unicodeHighlight.nonBasicASCII",
    ambiguousCharacters: "editor.unicodeHighlight.ambiguousCharacters",
    includeComments: "editor.unicodeHighlight.includeComments",
    includeStrings: "editor.unicodeHighlight.includeStrings",
    allowedLocales: "editor.unicodeHighlight.allowedLocales"
  };
  class UnicodeHighlight extends BaseEditorOption {
    constructor() {
      const defaults = {
        nonBasicASCII: inUntrustedWorkspace,
        invisibleCharacters: true,
        ambiguousCharacters: true,
        includeComments: inUntrustedWorkspace,
        includeStrings: true,
        allowedCharacters: {},
        allowedLocales: { _os: true, _vscode: true }
      };
      super(142, "unicodeHighlight", defaults, {
        [unicodeHighlightConfigKeys.nonBasicASCII]: {
          restricted: true,
          type: ["boolean", "string"],
          enum: [true, false, inUntrustedWorkspace],
          default: defaults.nonBasicASCII,
          description: localize(326, "Controls whether all non-basic ASCII characters are highlighted. Only characters between U+0020 and U+007E, tab, line-feed and carriage-return are considered basic ASCII.")
        },
        [unicodeHighlightConfigKeys.invisibleCharacters]: {
          restricted: true,
          type: "boolean",
          default: defaults.invisibleCharacters,
          description: localize(327, "Controls whether characters that just reserve space or have no width at all are highlighted.")
        },
        [unicodeHighlightConfigKeys.ambiguousCharacters]: {
          restricted: true,
          type: "boolean",
          default: defaults.ambiguousCharacters,
          description: localize(328, "Controls whether characters are highlighted that can be confused with basic ASCII characters, except those that are common in the current user locale.")
        },
        [unicodeHighlightConfigKeys.includeComments]: {
          restricted: true,
          type: ["boolean", "string"],
          enum: [true, false, inUntrustedWorkspace],
          default: defaults.includeComments,
          description: localize(329, "Controls whether characters in comments should also be subject to Unicode highlighting.")
        },
        [unicodeHighlightConfigKeys.includeStrings]: {
          restricted: true,
          type: ["boolean", "string"],
          enum: [true, false, inUntrustedWorkspace],
          default: defaults.includeStrings,
          description: localize(330, "Controls whether characters in strings should also be subject to Unicode highlighting.")
        },
        [unicodeHighlightConfigKeys.allowedCharacters]: {
          restricted: true,
          type: "object",
          default: defaults.allowedCharacters,
          description: localize(331, "Defines allowed characters that are not being highlighted."),
          additionalProperties: {
            type: "boolean"
          }
        },
        [unicodeHighlightConfigKeys.allowedLocales]: {
          restricted: true,
          type: "object",
          additionalProperties: {
            type: "boolean"
          },
          default: defaults.allowedLocales,
          description: localize(332, "Unicode characters that are common in allowed locales are not being highlighted.")
        }
      });
    }
    applyUpdate(value, update) {
      let didChange = false;
      if (update.allowedCharacters && value) {
        if (!equals(value.allowedCharacters, update.allowedCharacters)) {
          value = { ...value, allowedCharacters: update.allowedCharacters };
          didChange = true;
        }
      }
      if (update.allowedLocales && value) {
        if (!equals(value.allowedLocales, update.allowedLocales)) {
          value = { ...value, allowedLocales: update.allowedLocales };
          didChange = true;
        }
      }
      const result = super.applyUpdate(value, update);
      if (didChange) {
        return new ApplyUpdateResult(result.newValue, true);
      }
      return result;
    }
    validate(_input) {
      if (!_input || typeof _input !== "object") {
        return this.defaultValue;
      }
      const input = _input;
      return {
        nonBasicASCII: primitiveSet(input.nonBasicASCII, inUntrustedWorkspace, [true, false, inUntrustedWorkspace]),
        invisibleCharacters: boolean(input.invisibleCharacters, this.defaultValue.invisibleCharacters),
        ambiguousCharacters: boolean(input.ambiguousCharacters, this.defaultValue.ambiguousCharacters),
        includeComments: primitiveSet(input.includeComments, inUntrustedWorkspace, [true, false, inUntrustedWorkspace]),
        includeStrings: primitiveSet(input.includeStrings, inUntrustedWorkspace, [true, false, inUntrustedWorkspace]),
        allowedCharacters: this.validateBooleanMap(input.allowedCharacters, this.defaultValue.allowedCharacters),
        allowedLocales: this.validateBooleanMap(input.allowedLocales, this.defaultValue.allowedLocales)
      };
    }
    validateBooleanMap(map, defaultValue) {
      if (typeof map !== "object" || !map) {
        return defaultValue;
      }
      const result = {};
      for (const [key, value] of Object.entries(map)) {
        if (value === true) {
          result[key] = true;
        }
      }
      return result;
    }
  }
  class InlineEditorSuggest extends BaseEditorOption {
    constructor() {
      const defaults = {
        enabled: true,
        mode: "subwordSmart",
        showToolbar: "onHover",
        suppressSuggestions: false,
        keepOnBlur: false,
        fontFamily: "default",
        syntaxHighlightingEnabled: true,
        minShowDelay: 0,
        suppressInSnippetMode: true,
        edits: {
          enabled: true,
          showCollapsed: false,
          renderSideBySide: "auto",
          allowCodeShifting: "always"
        },
        triggerCommandOnProviderChange: false,
        experimental: {
          suppressInlineSuggestions: "",
          showOnSuggestConflict: "never",
          emptyResponseInformation: true
        }
      };
      super(71, "inlineSuggest", defaults, {
        "editor.inlineSuggest.enabled": {
          type: "boolean",
          default: defaults.enabled,
          description: localize(333, "Controls whether to automatically show inline suggestions in the editor.")
        },
        "editor.inlineSuggest.showToolbar": {
          type: "string",
          default: defaults.showToolbar,
          enum: ["always", "onHover", "never"],
          enumDescriptions: [
            localize(334, "Show the inline suggestion toolbar whenever an inline suggestion is shown."),
            localize(335, "Show the inline suggestion toolbar when hovering over an inline suggestion."),
            localize(336, "Never show the inline suggestion toolbar.")
          ],
          description: localize(337, "Controls when to show the inline suggestion toolbar.")
        },
        "editor.inlineSuggest.syntaxHighlightingEnabled": {
          type: "boolean",
          default: defaults.syntaxHighlightingEnabled,
          description: localize(338, "Controls whether to show syntax highlighting for inline suggestions in the editor.")
        },
        "editor.inlineSuggest.suppressSuggestions": {
          type: "boolean",
          default: defaults.suppressSuggestions,
          description: localize(339, "Controls how inline suggestions interact with the suggest widget. If enabled, the suggest widget is not shown automatically when inline suggestions are available.")
        },
        "editor.inlineSuggest.suppressInSnippetMode": {
          type: "boolean",
          default: defaults.suppressInSnippetMode,
          description: localize(340, "Controls whether inline suggestions are suppressed when in snippet mode.")
        },
        "editor.inlineSuggest.minShowDelay": {
          type: "number",
          default: 0,
          minimum: 0,
          maximum: 1e4,
          description: localize(341, "Controls the minimal delay in milliseconds after which inline suggestions are shown after typing.")
        },
        "editor.inlineSuggest.experimental.suppressInlineSuggestions": {
          type: "string",
          default: defaults.experimental.suppressInlineSuggestions,
          tags: ["experimental"],
          description: localize(342, "Suppresses inline completions for specified extension IDs -- comma separated."),
          experiment: {
            mode: "auto"
          }
        },
        "editor.inlineSuggest.experimental.emptyResponseInformation": {
          type: "boolean",
          default: defaults.experimental.emptyResponseInformation,
          tags: ["experimental"],
          description: localize(343, "Controls whether to send request information from the inline suggestion provider."),
          experiment: {
            mode: "auto"
          }
        },
        "editor.inlineSuggest.triggerCommandOnProviderChange": {
          type: "boolean",
          default: defaults.triggerCommandOnProviderChange,
          tags: ["experimental"],
          description: localize(344, "Controls whether to trigger a command when the inline suggestion provider changes."),
          experiment: {
            mode: "auto"
          }
        },
        "editor.inlineSuggest.experimental.showOnSuggestConflict": {
          type: "string",
          default: defaults.experimental.showOnSuggestConflict,
          tags: ["experimental"],
          enum: ["always", "never", "whenSuggestListIsIncomplete"],
          description: localize(345, "Controls whether to show inline suggestions when there is a suggest conflict."),
          experiment: {
            mode: "auto"
          }
        },
        "editor.inlineSuggest.fontFamily": {
          type: "string",
          default: defaults.fontFamily,
          description: localize(346, "Controls the font family of the inline suggestions.")
        },
        "editor.inlineSuggest.edits.allowCodeShifting": {
          type: "string",
          default: defaults.edits.allowCodeShifting,
          description: localize(347, "Controls whether showing a suggestion will shift the code to make space for the suggestion inline."),
          enum: ["always", "horizontal", "never"],
          tags: ["nextEditSuggestions"]
        },
        "editor.inlineSuggest.edits.renderSideBySide": {
          type: "string",
          default: defaults.edits.renderSideBySide,
          description: localize(348, "Controls whether larger suggestions can be shown side by side."),
          enum: ["auto", "never"],
          enumDescriptions: [
            localize(349, "Larger suggestions will show side by side if there is enough space, otherwise they will be shown below."),
            localize(350, "Larger suggestions are never shown side by side and will always be shown below.")
          ],
          tags: ["nextEditSuggestions"]
        },
        "editor.inlineSuggest.edits.showCollapsed": {
          type: "boolean",
          default: defaults.edits.showCollapsed,
          description: localize(351, "Controls whether the suggestion will show as collapsed until jumping to it."),
          tags: ["nextEditSuggestions"]
        }
      });
    }
    validate(_input) {
      if (!_input || typeof _input !== "object") {
        return this.defaultValue;
      }
      const input = _input;
      return {
        enabled: boolean(input.enabled, this.defaultValue.enabled),
        mode: stringSet(input.mode, this.defaultValue.mode, ["prefix", "subword", "subwordSmart"]),
        showToolbar: stringSet(input.showToolbar, this.defaultValue.showToolbar, ["always", "onHover", "never"]),
        suppressSuggestions: boolean(input.suppressSuggestions, this.defaultValue.suppressSuggestions),
        keepOnBlur: boolean(input.keepOnBlur, this.defaultValue.keepOnBlur),
        fontFamily: EditorStringOption.string(input.fontFamily, this.defaultValue.fontFamily),
        syntaxHighlightingEnabled: boolean(input.syntaxHighlightingEnabled, this.defaultValue.syntaxHighlightingEnabled),
        minShowDelay: EditorIntOption.clampedInt(input.minShowDelay, 0, 0, 1e4),
        suppressInSnippetMode: boolean(input.suppressInSnippetMode, this.defaultValue.suppressInSnippetMode),
        edits: this._validateEdits(input.edits),
        triggerCommandOnProviderChange: boolean(input.triggerCommandOnProviderChange, this.defaultValue.triggerCommandOnProviderChange),
        experimental: this._validateExperimental(input.experimental)
      };
    }
    _validateEdits(_input) {
      if (!_input || typeof _input !== "object") {
        return this.defaultValue.edits;
      }
      const input = _input;
      return {
        enabled: boolean(input.enabled, this.defaultValue.edits.enabled),
        showCollapsed: boolean(input.showCollapsed, this.defaultValue.edits.showCollapsed),
        allowCodeShifting: stringSet(input.allowCodeShifting, this.defaultValue.edits.allowCodeShifting, ["always", "horizontal", "never"]),
        renderSideBySide: stringSet(input.renderSideBySide, this.defaultValue.edits.renderSideBySide, ["never", "auto"])
      };
    }
    _validateExperimental(_input) {
      if (!_input || typeof _input !== "object") {
        return this.defaultValue.experimental;
      }
      const input = _input;
      return {
        suppressInlineSuggestions: EditorStringOption.string(input.suppressInlineSuggestions, this.defaultValue.experimental.suppressInlineSuggestions),
        showOnSuggestConflict: stringSet(input.showOnSuggestConflict, this.defaultValue.experimental.showOnSuggestConflict, ["always", "never", "whenSuggestListIsIncomplete"]),
        emptyResponseInformation: boolean(input.emptyResponseInformation, this.defaultValue.experimental.emptyResponseInformation)
      };
    }
  }
  class BracketPairColorization extends BaseEditorOption {
    constructor() {
      const defaults = {
        enabled: EDITOR_MODEL_DEFAULTS.bracketPairColorizationOptions.enabled,
        independentColorPoolPerBracketType: EDITOR_MODEL_DEFAULTS.bracketPairColorizationOptions.independentColorPoolPerBracketType
      };
      super(21, "bracketPairColorization", defaults, {
        "editor.bracketPairColorization.enabled": {
          type: "boolean",
          default: defaults.enabled,
          markdownDescription: localize(352, "Controls whether bracket pair colorization is enabled or not. Use {0} to override the bracket highlight colors.", "`#workbench.colorCustomizations#`")
        },
        "editor.bracketPairColorization.independentColorPoolPerBracketType": {
          type: "boolean",
          default: defaults.independentColorPoolPerBracketType,
          description: localize(353, "Controls whether each bracket type has its own independent color pool.")
        }
      });
    }
    validate(_input) {
      if (!_input || typeof _input !== "object") {
        return this.defaultValue;
      }
      const input = _input;
      return {
        enabled: boolean(input.enabled, this.defaultValue.enabled),
        independentColorPoolPerBracketType: boolean(input.independentColorPoolPerBracketType, this.defaultValue.independentColorPoolPerBracketType)
      };
    }
  }
  class GuideOptions extends BaseEditorOption {
    constructor() {
      const defaults = {
        bracketPairs: false,
        bracketPairsHorizontal: "active",
        highlightActiveBracketPair: true,
        indentation: true,
        highlightActiveIndentation: true
      };
      super(22, "guides", defaults, {
        "editor.guides.bracketPairs": {
          type: ["boolean", "string"],
          enum: [true, "active", false],
          enumDescriptions: [
            localize(354, "Enables bracket pair guides."),
            localize(355, "Enables bracket pair guides only for the active bracket pair."),
            localize(356, "Disables bracket pair guides.")
          ],
          default: defaults.bracketPairs,
          description: localize(357, "Controls whether bracket pair guides are enabled or not.")
        },
        "editor.guides.bracketPairsHorizontal": {
          type: ["boolean", "string"],
          enum: [true, "active", false],
          enumDescriptions: [
            localize(358, "Enables horizontal guides as addition to vertical bracket pair guides."),
            localize(359, "Enables horizontal guides only for the active bracket pair."),
            localize(360, "Disables horizontal bracket pair guides.")
          ],
          default: defaults.bracketPairsHorizontal,
          description: localize(361, "Controls whether horizontal bracket pair guides are enabled or not.")
        },
        "editor.guides.highlightActiveBracketPair": {
          type: "boolean",
          default: defaults.highlightActiveBracketPair,
          description: localize(362, "Controls whether the editor should highlight the active bracket pair.")
        },
        "editor.guides.indentation": {
          type: "boolean",
          default: defaults.indentation,
          description: localize(363, "Controls whether the editor should render indent guides.")
        },
        "editor.guides.highlightActiveIndentation": {
          type: ["boolean", "string"],
          enum: [true, "always", false],
          enumDescriptions: [
            localize(364, "Highlights the active indent guide."),
            localize(365, "Highlights the active indent guide even if bracket guides are highlighted."),
            localize(366, "Do not highlight the active indent guide.")
          ],
          default: defaults.highlightActiveIndentation,
          description: localize(367, "Controls whether the editor should highlight the active indent guide.")
        }
      });
    }
    validate(_input) {
      if (!_input || typeof _input !== "object") {
        return this.defaultValue;
      }
      const input = _input;
      return {
        bracketPairs: primitiveSet(input.bracketPairs, this.defaultValue.bracketPairs, [true, false, "active"]),
        bracketPairsHorizontal: primitiveSet(input.bracketPairsHorizontal, this.defaultValue.bracketPairsHorizontal, [true, false, "active"]),
        highlightActiveBracketPair: boolean(input.highlightActiveBracketPair, this.defaultValue.highlightActiveBracketPair),
        indentation: boolean(input.indentation, this.defaultValue.indentation),
        highlightActiveIndentation: primitiveSet(input.highlightActiveIndentation, this.defaultValue.highlightActiveIndentation, [true, false, "always"])
      };
    }
  }
  function primitiveSet(value, defaultValue, allowedValues) {
    const idx = allowedValues.indexOf(value);
    if (idx === -1) {
      return defaultValue;
    }
    return allowedValues[idx];
  }
  class EditorSuggest extends BaseEditorOption {
    constructor() {
      const defaults = {
        insertMode: "insert",
        filterGraceful: true,
        snippetsPreventQuickSuggestions: false,
        localityBonus: false,
        shareSuggestSelections: false,
        selectionMode: "always",
        showIcons: true,
        showStatusBar: false,
        preview: false,
        previewMode: "subwordSmart",
        showInlineDetails: true,
        showMethods: true,
        showFunctions: true,
        showConstructors: true,
        showDeprecated: true,
        matchOnWordStartOnly: true,
        showFields: true,
        showVariables: true,
        showClasses: true,
        showStructs: true,
        showInterfaces: true,
        showModules: true,
        showProperties: true,
        showEvents: true,
        showOperators: true,
        showUnits: true,
        showValues: true,
        showConstants: true,
        showEnums: true,
        showEnumMembers: true,
        showKeywords: true,
        showWords: true,
        showColors: true,
        showFiles: true,
        showReferences: true,
        showFolders: true,
        showTypeParameters: true,
        showSnippets: true,
        showUsers: true,
        showIssues: true
      };
      super(134, "suggest", defaults, {
        "editor.suggest.insertMode": {
          type: "string",
          enum: ["insert", "replace"],
          enumDescriptions: [
            localize(368, "Insert suggestion without overwriting text right of the cursor."),
            localize(369, "Insert suggestion and overwrite text right of the cursor.")
          ],
          default: defaults.insertMode,
          description: localize(370, "Controls whether words are overwritten when accepting completions. Note that this depends on extensions opting into this feature.")
        },
        "editor.suggest.filterGraceful": {
          type: "boolean",
          default: defaults.filterGraceful,
          description: localize(371, "Controls whether filtering and sorting suggestions accounts for small typos.")
        },
        "editor.suggest.localityBonus": {
          type: "boolean",
          default: defaults.localityBonus,
          description: localize(372, "Controls whether sorting favors words that appear close to the cursor.")
        },
        "editor.suggest.shareSuggestSelections": {
          type: "boolean",
          default: defaults.shareSuggestSelections,
          markdownDescription: localize(373, "Controls whether remembered suggestion selections are shared between multiple workspaces and windows (needs `#editor.suggestSelection#`).")
        },
        "editor.suggest.selectionMode": {
          type: "string",
          enum: ["always", "never", "whenTriggerCharacter", "whenQuickSuggestion"],
          enumDescriptions: [
            localize(374, "Always select a suggestion when automatically triggering IntelliSense."),
            localize(375, "Never select a suggestion when automatically triggering IntelliSense."),
            localize(376, "Select a suggestion only when triggering IntelliSense from a trigger character."),
            localize(377, "Select a suggestion only when triggering IntelliSense as you type.")
          ],
          default: defaults.selectionMode,
          markdownDescription: localize(378, "Controls whether a suggestion is selected when the widget shows. Note that this only applies to automatically triggered suggestions ({0} and {1}) and that a suggestion is always selected when explicitly invoked, e.g via `Ctrl+Space`.", "`#editor.quickSuggestions#`", "`#editor.suggestOnTriggerCharacters#`")
        },
        "editor.suggest.snippetsPreventQuickSuggestions": {
          type: "boolean",
          default: defaults.snippetsPreventQuickSuggestions,
          description: localize(379, "Controls whether an active snippet prevents quick suggestions.")
        },
        "editor.suggest.showIcons": {
          type: "boolean",
          default: defaults.showIcons,
          description: localize(380, "Controls whether to show or hide icons in suggestions.")
        },
        "editor.suggest.showStatusBar": {
          type: "boolean",
          default: defaults.showStatusBar,
          description: localize(381, "Controls the visibility of the status bar at the bottom of the suggest widget.")
        },
        "editor.suggest.preview": {
          type: "boolean",
          default: defaults.preview,
          description: localize(382, "Controls whether to preview the suggestion outcome in the editor.")
        },
        "editor.suggest.showInlineDetails": {
          type: "boolean",
          default: defaults.showInlineDetails,
          description: localize(383, "Controls whether suggest details show inline with the label or only in the details widget.")
        },
        "editor.suggest.maxVisibleSuggestions": {
          type: "number",
          deprecationMessage: localize(384, "This setting is deprecated. The suggest widget can now be resized.")
        },
        "editor.suggest.filteredTypes": {
          type: "object",
          deprecationMessage: localize(385, "This setting is deprecated, please use separate settings like 'editor.suggest.showKeywords' or 'editor.suggest.showSnippets' instead.")
        },
        "editor.suggest.showMethods": {
          type: "boolean",
          default: true,
          markdownDescription: localize(386, "When enabled IntelliSense shows `method`-suggestions.")
        },
        "editor.suggest.showFunctions": {
          type: "boolean",
          default: true,
          markdownDescription: localize(387, "When enabled IntelliSense shows `function`-suggestions.")
        },
        "editor.suggest.showConstructors": {
          type: "boolean",
          default: true,
          markdownDescription: localize(388, "When enabled IntelliSense shows `constructor`-suggestions.")
        },
        "editor.suggest.showDeprecated": {
          type: "boolean",
          default: true,
          markdownDescription: localize(389, "When enabled IntelliSense shows `deprecated`-suggestions.")
        },
        "editor.suggest.matchOnWordStartOnly": {
          type: "boolean",
          default: true,
          markdownDescription: localize(390, "When enabled IntelliSense filtering requires that the first character matches on a word start. For example, `c` on `Console` or `WebContext` but _not_ on `description`. When disabled IntelliSense will show more results but still sorts them by match quality.")
        },
        "editor.suggest.showFields": {
          type: "boolean",
          default: true,
          markdownDescription: localize(391, "When enabled IntelliSense shows `field`-suggestions.")
        },
        "editor.suggest.showVariables": {
          type: "boolean",
          default: true,
          markdownDescription: localize(392, "When enabled IntelliSense shows `variable`-suggestions.")
        },
        "editor.suggest.showClasses": {
          type: "boolean",
          default: true,
          markdownDescription: localize(393, "When enabled IntelliSense shows `class`-suggestions.")
        },
        "editor.suggest.showStructs": {
          type: "boolean",
          default: true,
          markdownDescription: localize(394, "When enabled IntelliSense shows `struct`-suggestions.")
        },
        "editor.suggest.showInterfaces": {
          type: "boolean",
          default: true,
          markdownDescription: localize(395, "When enabled IntelliSense shows `interface`-suggestions.")
        },
        "editor.suggest.showModules": {
          type: "boolean",
          default: true,
          markdownDescription: localize(396, "When enabled IntelliSense shows `module`-suggestions.")
        },
        "editor.suggest.showProperties": {
          type: "boolean",
          default: true,
          markdownDescription: localize(397, "When enabled IntelliSense shows `property`-suggestions.")
        },
        "editor.suggest.showEvents": {
          type: "boolean",
          default: true,
          markdownDescription: localize(398, "When enabled IntelliSense shows `event`-suggestions.")
        },
        "editor.suggest.showOperators": {
          type: "boolean",
          default: true,
          markdownDescription: localize(399, "When enabled IntelliSense shows `operator`-suggestions.")
        },
        "editor.suggest.showUnits": {
          type: "boolean",
          default: true,
          markdownDescription: localize(400, "When enabled IntelliSense shows `unit`-suggestions.")
        },
        "editor.suggest.showValues": {
          type: "boolean",
          default: true,
          markdownDescription: localize(401, "When enabled IntelliSense shows `value`-suggestions.")
        },
        "editor.suggest.showConstants": {
          type: "boolean",
          default: true,
          markdownDescription: localize(402, "When enabled IntelliSense shows `constant`-suggestions.")
        },
        "editor.suggest.showEnums": {
          type: "boolean",
          default: true,
          markdownDescription: localize(403, "When enabled IntelliSense shows `enum`-suggestions.")
        },
        "editor.suggest.showEnumMembers": {
          type: "boolean",
          default: true,
          markdownDescription: localize(404, "When enabled IntelliSense shows `enumMember`-suggestions.")
        },
        "editor.suggest.showKeywords": {
          type: "boolean",
          default: true,
          markdownDescription: localize(405, "When enabled IntelliSense shows `keyword`-suggestions.")
        },
        "editor.suggest.showWords": {
          type: "boolean",
          default: true,
          markdownDescription: localize(406, "When enabled IntelliSense shows `text`-suggestions.")
        },
        "editor.suggest.showColors": {
          type: "boolean",
          default: true,
          markdownDescription: localize(407, "When enabled IntelliSense shows `color`-suggestions.")
        },
        "editor.suggest.showFiles": {
          type: "boolean",
          default: true,
          markdownDescription: localize(408, "When enabled IntelliSense shows `file`-suggestions.")
        },
        "editor.suggest.showReferences": {
          type: "boolean",
          default: true,
          markdownDescription: localize(409, "When enabled IntelliSense shows `reference`-suggestions.")
        },
        "editor.suggest.showCustomcolors": {
          type: "boolean",
          default: true,
          markdownDescription: localize(410, "When enabled IntelliSense shows `customcolor`-suggestions.")
        },
        "editor.suggest.showFolders": {
          type: "boolean",
          default: true,
          markdownDescription: localize(411, "When enabled IntelliSense shows `folder`-suggestions.")
        },
        "editor.suggest.showTypeParameters": {
          type: "boolean",
          default: true,
          markdownDescription: localize(412, "When enabled IntelliSense shows `typeParameter`-suggestions.")
        },
        "editor.suggest.showSnippets": {
          type: "boolean",
          default: true,
          markdownDescription: localize(413, "When enabled IntelliSense shows `snippet`-suggestions.")
        },
        "editor.suggest.showUsers": {
          type: "boolean",
          default: true,
          markdownDescription: localize(414, "When enabled IntelliSense shows `user`-suggestions.")
        },
        "editor.suggest.showIssues": {
          type: "boolean",
          default: true,
          markdownDescription: localize(415, "When enabled IntelliSense shows `issues`-suggestions.")
        }
      });
    }
    validate(_input) {
      if (!_input || typeof _input !== "object") {
        return this.defaultValue;
      }
      const input = _input;
      return {
        insertMode: stringSet(input.insertMode, this.defaultValue.insertMode, ["insert", "replace"]),
        filterGraceful: boolean(input.filterGraceful, this.defaultValue.filterGraceful),
        snippetsPreventQuickSuggestions: boolean(input.snippetsPreventQuickSuggestions, this.defaultValue.filterGraceful),
        localityBonus: boolean(input.localityBonus, this.defaultValue.localityBonus),
        shareSuggestSelections: boolean(input.shareSuggestSelections, this.defaultValue.shareSuggestSelections),
        selectionMode: stringSet(input.selectionMode, this.defaultValue.selectionMode, ["always", "never", "whenQuickSuggestion", "whenTriggerCharacter"]),
        showIcons: boolean(input.showIcons, this.defaultValue.showIcons),
        showStatusBar: boolean(input.showStatusBar, this.defaultValue.showStatusBar),
        preview: boolean(input.preview, this.defaultValue.preview),
        previewMode: stringSet(input.previewMode, this.defaultValue.previewMode, ["prefix", "subword", "subwordSmart"]),
        showInlineDetails: boolean(input.showInlineDetails, this.defaultValue.showInlineDetails),
        showMethods: boolean(input.showMethods, this.defaultValue.showMethods),
        showFunctions: boolean(input.showFunctions, this.defaultValue.showFunctions),
        showConstructors: boolean(input.showConstructors, this.defaultValue.showConstructors),
        showDeprecated: boolean(input.showDeprecated, this.defaultValue.showDeprecated),
        matchOnWordStartOnly: boolean(input.matchOnWordStartOnly, this.defaultValue.matchOnWordStartOnly),
        showFields: boolean(input.showFields, this.defaultValue.showFields),
        showVariables: boolean(input.showVariables, this.defaultValue.showVariables),
        showClasses: boolean(input.showClasses, this.defaultValue.showClasses),
        showStructs: boolean(input.showStructs, this.defaultValue.showStructs),
        showInterfaces: boolean(input.showInterfaces, this.defaultValue.showInterfaces),
        showModules: boolean(input.showModules, this.defaultValue.showModules),
        showProperties: boolean(input.showProperties, this.defaultValue.showProperties),
        showEvents: boolean(input.showEvents, this.defaultValue.showEvents),
        showOperators: boolean(input.showOperators, this.defaultValue.showOperators),
        showUnits: boolean(input.showUnits, this.defaultValue.showUnits),
        showValues: boolean(input.showValues, this.defaultValue.showValues),
        showConstants: boolean(input.showConstants, this.defaultValue.showConstants),
        showEnums: boolean(input.showEnums, this.defaultValue.showEnums),
        showEnumMembers: boolean(input.showEnumMembers, this.defaultValue.showEnumMembers),
        showKeywords: boolean(input.showKeywords, this.defaultValue.showKeywords),
        showWords: boolean(input.showWords, this.defaultValue.showWords),
        showColors: boolean(input.showColors, this.defaultValue.showColors),
        showFiles: boolean(input.showFiles, this.defaultValue.showFiles),
        showReferences: boolean(input.showReferences, this.defaultValue.showReferences),
        showFolders: boolean(input.showFolders, this.defaultValue.showFolders),
        showTypeParameters: boolean(input.showTypeParameters, this.defaultValue.showTypeParameters),
        showSnippets: boolean(input.showSnippets, this.defaultValue.showSnippets),
        showUsers: boolean(input.showUsers, this.defaultValue.showUsers),
        showIssues: boolean(input.showIssues, this.defaultValue.showIssues)
      };
    }
  }
  class SmartSelect extends BaseEditorOption {
    constructor() {
      super(129, "smartSelect", {
        selectLeadingAndTrailingWhitespace: true,
        selectSubwords: true
      }, {
        "editor.smartSelect.selectLeadingAndTrailingWhitespace": {
          description: localize(416, "Whether leading and trailing whitespace should always be selected."),
          default: true,
          type: "boolean"
        },
        "editor.smartSelect.selectSubwords": {
          description: localize(417, "Whether subwords (like 'foo' in 'fooBar' or 'foo_bar') should be selected."),
          default: true,
          type: "boolean"
        }
      });
    }
    validate(input) {
      if (!input || typeof input !== "object") {
        return this.defaultValue;
      }
      return {
        selectLeadingAndTrailingWhitespace: boolean(input.selectLeadingAndTrailingWhitespace, this.defaultValue.selectLeadingAndTrailingWhitespace),
        selectSubwords: boolean(input.selectSubwords, this.defaultValue.selectSubwords)
      };
    }
  }
  class WordSegmenterLocales extends BaseEditorOption {
    constructor() {
      const defaults = [];
      super(147, "wordSegmenterLocales", defaults, {
        anyOf: [
          {
            type: "string"
          },
          {
            type: "array",
            items: {
              type: "string"
            }
          }
        ],
        description: localize(418, "Locales to be used for word segmentation when doing word related navigations or operations. Specify the BCP 47 language tag of the word you wish to recognize (e.g., ja, zh-CN, zh-Hant-TW, etc.)."),
        type: "array",
        items: {
          type: "string"
        },
        default: defaults
      });
    }
    validate(input) {
      if (typeof input === "string") {
        input = [input];
      }
      if (Array.isArray(input)) {
        const validLocales = [];
        for (const locale of input) {
          if (typeof locale === "string") {
            try {
              if (Intl.Segmenter.supportedLocalesOf(locale).length > 0) {
                validLocales.push(locale);
              }
            } catch {
            }
          }
        }
        return validLocales;
      }
      return this.defaultValue;
    }
  }
  class WrappingIndentOption extends BaseEditorOption {
    constructor() {
      super(155, "wrappingIndent", 1, {
        "editor.wrappingIndent": {
          type: "string",
          enum: ["none", "same", "indent", "deepIndent"],
          enumDescriptions: [
            localize(419, "No indentation. Wrapped lines begin at column 1."),
            localize(420, "Wrapped lines get the same indentation as the parent."),
            localize(421, "Wrapped lines get +1 indentation toward the parent."),
            localize(422, "Wrapped lines get +2 indentation toward the parent.")
          ],
          description: localize(423, "Controls the indentation of wrapped lines."),
          default: "same"
        }
      });
    }
    validate(input) {
      switch (input) {
        case "none":
          return 0;
        case "same":
          return 1;
        case "indent":
          return 2;
        case "deepIndent":
          return 3;
      }
      return 1;
    }
    compute(env2, options, value) {
      const accessibilitySupport = options.get(
        2
        /* EditorOption.accessibilitySupport */
      );
      if (accessibilitySupport === 2) {
        return 0;
      }
      return value;
    }
  }
  class EditorWrappingInfoComputer extends ComputedEditorOption {
    constructor() {
      super(166, {
        isDominatedByLongLines: false,
        isWordWrapMinified: false,
        isViewportWrapping: false,
        wrappingColumn: -1
      });
    }
    compute(env2, options, _) {
      const layoutInfo = options.get(
        165
        /* EditorOption.layoutInfo */
      );
      return {
        isDominatedByLongLines: env2.isDominatedByLongLines,
        isWordWrapMinified: layoutInfo.isWordWrapMinified,
        isViewportWrapping: layoutInfo.isViewportWrapping,
        wrappingColumn: layoutInfo.wrappingColumn
      };
    }
  }
  class EditorDropIntoEditor extends BaseEditorOption {
    constructor() {
      const defaults = { enabled: true, showDropSelector: "afterDrop" };
      super(43, "dropIntoEditor", defaults, {
        "editor.dropIntoEditor.enabled": {
          type: "boolean",
          default: defaults.enabled,
          markdownDescription: localize(424, "Controls whether you can drag and drop a file into a text editor by holding down the `Shift` key (instead of opening the file in an editor).")
        },
        "editor.dropIntoEditor.showDropSelector": {
          type: "string",
          markdownDescription: localize(425, "Controls if a widget is shown when dropping files into the editor. This widget lets you control how the file is dropped."),
          enum: [
            "afterDrop",
            "never"
          ],
          enumDescriptions: [
            localize(426, "Show the drop selector widget after a file is dropped into the editor."),
            localize(427, "Never show the drop selector widget. Instead the default drop provider is always used.")
          ],
          default: "afterDrop"
        }
      });
    }
    validate(_input) {
      if (!_input || typeof _input !== "object") {
        return this.defaultValue;
      }
      const input = _input;
      return {
        enabled: boolean(input.enabled, this.defaultValue.enabled),
        showDropSelector: stringSet(input.showDropSelector, this.defaultValue.showDropSelector, ["afterDrop", "never"])
      };
    }
  }
  class EditorPasteAs extends BaseEditorOption {
    constructor() {
      const defaults = { enabled: true, showPasteSelector: "afterPaste" };
      super(97, "pasteAs", defaults, {
        "editor.pasteAs.enabled": {
          type: "boolean",
          default: defaults.enabled,
          markdownDescription: localize(428, "Controls whether you can paste content in different ways.")
        },
        "editor.pasteAs.showPasteSelector": {
          type: "string",
          markdownDescription: localize(429, "Controls if a widget is shown when pasting content in to the editor. This widget lets you control how the file is pasted."),
          enum: [
            "afterPaste",
            "never"
          ],
          enumDescriptions: [
            localize(430, "Show the paste selector widget after content is pasted into the editor."),
            localize(431, "Never show the paste selector widget. Instead the default pasting behavior is always used.")
          ],
          default: "afterPaste"
        }
      });
    }
    validate(_input) {
      if (!_input || typeof _input !== "object") {
        return this.defaultValue;
      }
      const input = _input;
      return {
        enabled: boolean(input.enabled, this.defaultValue.enabled),
        showPasteSelector: stringSet(input.showPasteSelector, this.defaultValue.showPasteSelector, ["afterPaste", "never"])
      };
    }
  }
  const editorOptionsRegistry = [];
  function register$1(option2) {
    editorOptionsRegistry[option2.id] = option2;
    return option2;
  }
  const EditorOptions = {
    acceptSuggestionOnCommitCharacter: register$1(new EditorBooleanOption(0, "acceptSuggestionOnCommitCharacter", true, { markdownDescription: localize(432, "Controls whether suggestions should be accepted on commit characters. For example, in JavaScript, the semi-colon (`;`) can be a commit character that accepts a suggestion and types that character.") })),
    acceptSuggestionOnEnter: register$1(new EditorStringEnumOption(1, "acceptSuggestionOnEnter", "on", ["on", "smart", "off"], {
      markdownEnumDescriptions: [
        "",
        localize(433, "Only accept a suggestion with `Enter` when it makes a textual change."),
        ""
      ],
      markdownDescription: localize(434, "Controls whether suggestions should be accepted on `Enter`, in addition to `Tab`. Helps to avoid ambiguity between inserting new lines or accepting suggestions.")
    })),
    accessibilitySupport: register$1(new EditorAccessibilitySupport()),
    accessibilityPageSize: register$1(new EditorIntOption(3, "accessibilityPageSize", 500, 1, 1073741824, {
      description: localize(435, "Controls the number of lines in the editor that can be read out by a screen reader at once. When we detect a screen reader we automatically set the default to be 500. Warning: this has a performance implication for numbers larger than the default."),
      tags: ["accessibility"]
    })),
    allowOverflow: register$1(new EditorBooleanOption(4, "allowOverflow", true)),
    allowVariableLineHeights: register$1(new EditorBooleanOption(5, "allowVariableLineHeights", true, {
      description: localize(436, "Controls whether to allow using variable line heights in the editor.")
    })),
    allowVariableFonts: register$1(new EditorBooleanOption(6, "allowVariableFonts", true, {
      description: localize(437, "Controls whether to allow using variable fonts in the editor.")
    })),
    allowVariableFontsInAccessibilityMode: register$1(new EditorBooleanOption(7, "allowVariableFontsInAccessibilityMode", false, {
      description: localize(438, "Controls whether to allow using variable fonts in the editor in the accessibility mode."),
      tags: ["accessibility"]
    })),
    ariaLabel: register$1(new EditorStringOption(8, "ariaLabel", localize(439, "Editor content"))),
    ariaRequired: register$1(new EditorBooleanOption(9, "ariaRequired", false, void 0)),
    screenReaderAnnounceInlineSuggestion: register$1(new EditorBooleanOption(12, "screenReaderAnnounceInlineSuggestion", true, {
      description: localize(440, "Control whether inline suggestions are announced by a screen reader."),
      tags: ["accessibility"]
    })),
    autoClosingBrackets: register$1(new EditorStringEnumOption(10, "autoClosingBrackets", "languageDefined", ["always", "languageDefined", "beforeWhitespace", "never"], {
      enumDescriptions: [
        "",
        localize(441, "Use language configurations to determine when to autoclose brackets."),
        localize(442, "Autoclose brackets only when the cursor is to the left of whitespace."),
        ""
      ],
      description: localize(443, "Controls whether the editor should automatically close brackets after the user adds an opening bracket.")
    })),
    autoClosingComments: register$1(new EditorStringEnumOption(11, "autoClosingComments", "languageDefined", ["always", "languageDefined", "beforeWhitespace", "never"], {
      enumDescriptions: [
        "",
        localize(444, "Use language configurations to determine when to autoclose comments."),
        localize(445, "Autoclose comments only when the cursor is to the left of whitespace."),
        ""
      ],
      description: localize(446, "Controls whether the editor should automatically close comments after the user adds an opening comment.")
    })),
    autoClosingDelete: register$1(new EditorStringEnumOption(13, "autoClosingDelete", "auto", ["always", "auto", "never"], {
      enumDescriptions: [
        "",
        localize(447, "Remove adjacent closing quotes or brackets only if they were automatically inserted."),
        ""
      ],
      description: localize(448, "Controls whether the editor should remove adjacent closing quotes or brackets when deleting.")
    })),
    autoClosingOvertype: register$1(new EditorStringEnumOption(14, "autoClosingOvertype", "auto", ["always", "auto", "never"], {
      enumDescriptions: [
        "",
        localize(449, "Type over closing quotes or brackets only if they were automatically inserted."),
        ""
      ],
      description: localize(450, "Controls whether the editor should type over closing quotes or brackets.")
    })),
    autoClosingQuotes: register$1(new EditorStringEnumOption(15, "autoClosingQuotes", "languageDefined", ["always", "languageDefined", "beforeWhitespace", "never"], {
      enumDescriptions: [
        "",
        localize(451, "Use language configurations to determine when to autoclose quotes."),
        localize(452, "Autoclose quotes only when the cursor is to the left of whitespace."),
        ""
      ],
      description: localize(453, "Controls whether the editor should automatically close quotes after the user adds an opening quote.")
    })),
    autoIndent: register$1(new EditorEnumOption(16, "autoIndent", 4, "full", ["none", "keep", "brackets", "advanced", "full"], _autoIndentFromString, {
      enumDescriptions: [
        localize(454, "The editor will not insert indentation automatically."),
        localize(455, "The editor will keep the current line's indentation."),
        localize(456, "The editor will keep the current line's indentation and honor language defined brackets."),
        localize(457, "The editor will keep the current line's indentation, honor language defined brackets and invoke special onEnterRules defined by languages."),
        localize(458, "The editor will keep the current line's indentation, honor language defined brackets, invoke special onEnterRules defined by languages, and honor indentationRules defined by languages.")
      ],
      description: localize(459, "Controls whether the editor should automatically adjust the indentation when users type, paste, move or indent lines.")
    })),
    autoIndentOnPaste: register$1(new EditorBooleanOption(17, "autoIndentOnPaste", false, { description: localize(460, "Controls whether the editor should automatically auto-indent the pasted content.") })),
    autoIndentOnPasteWithinString: register$1(new EditorBooleanOption(18, "autoIndentOnPasteWithinString", true, { description: localize(461, "Controls whether the editor should automatically auto-indent the pasted content when pasted within a string. This takes effect when autoIndentOnPaste is true.") })),
    automaticLayout: register$1(new EditorBooleanOption(19, "automaticLayout", false)),
    autoSurround: register$1(new EditorStringEnumOption(20, "autoSurround", "languageDefined", ["languageDefined", "quotes", "brackets", "never"], {
      enumDescriptions: [
        localize(462, "Use language configurations to determine when to automatically surround selections."),
        localize(463, "Surround with quotes but not brackets."),
        localize(464, "Surround with brackets but not quotes."),
        ""
      ],
      description: localize(465, "Controls whether the editor should automatically surround selections when typing quotes or brackets.")
    })),
    bracketPairColorization: register$1(new BracketPairColorization()),
    bracketPairGuides: register$1(new GuideOptions()),
    stickyTabStops: register$1(new EditorBooleanOption(132, "stickyTabStops", false, { description: localize(466, "Emulate selection behavior of tab characters when using spaces for indentation. Selection will stick to tab stops.") })),
    codeLens: register$1(new EditorBooleanOption(23, "codeLens", true, { description: localize(467, "Controls whether the editor shows CodeLens.") })),
    codeLensFontFamily: register$1(new EditorStringOption(24, "codeLensFontFamily", "", { description: localize(468, "Controls the font family for CodeLens.") })),
    codeLensFontSize: register$1(new EditorIntOption(25, "codeLensFontSize", 0, 0, 100, {
      type: "number",
      default: 0,
      minimum: 0,
      maximum: 100,
      markdownDescription: localize(469, "Controls the font size in pixels for CodeLens. When set to 0, 90% of `#editor.fontSize#` is used.")
    })),
    colorDecorators: register$1(new EditorBooleanOption(26, "colorDecorators", true, { description: localize(470, "Controls whether the editor should render the inline color decorators and color picker.") })),
    colorDecoratorActivatedOn: register$1(new EditorStringEnumOption(168, "colorDecoratorsActivatedOn", "clickAndHover", ["clickAndHover", "hover", "click"], {
      enumDescriptions: [
        localize(471, "Make the color picker appear both on click and hover of the color decorator"),
        localize(472, "Make the color picker appear on hover of the color decorator"),
        localize(473, "Make the color picker appear on click of the color decorator")
      ],
      description: localize(474, "Controls the condition to make a color picker appear from a color decorator.")
    })),
    colorDecoratorsLimit: register$1(new EditorIntOption(27, "colorDecoratorsLimit", 500, 1, 1e6, {
      markdownDescription: localize(475, "Controls the max number of color decorators that can be rendered in an editor at once.")
    })),
    columnSelection: register$1(new EditorBooleanOption(28, "columnSelection", false, { description: localize(476, "Enable that the selection with the mouse and keys is doing column selection.") })),
    comments: register$1(new EditorComments()),
    contextmenu: register$1(new EditorBooleanOption(30, "contextmenu", true)),
    copyWithSyntaxHighlighting: register$1(new EditorBooleanOption(31, "copyWithSyntaxHighlighting", true, { description: localize(477, "Controls whether syntax highlighting should be copied into the clipboard.") })),
    cursorBlinking: register$1(new EditorEnumOption(32, "cursorBlinking", 1, "blink", ["blink", "smooth", "phase", "expand", "solid"], cursorBlinkingStyleFromString, { description: localize(478, "Control the cursor animation style.") })),
    cursorSmoothCaretAnimation: register$1(new EditorStringEnumOption(33, "cursorSmoothCaretAnimation", "off", ["off", "explicit", "on"], {
      enumDescriptions: [
        localize(479, "Smooth caret animation is disabled."),
        localize(480, "Smooth caret animation is enabled only when the user moves the cursor with an explicit gesture."),
        localize(481, "Smooth caret animation is always enabled.")
      ],
      description: localize(482, "Controls whether the smooth caret animation should be enabled.")
    })),
    cursorStyle: register$1(new EditorEnumOption(34, "cursorStyle", TextEditorCursorStyle$1.Line, "line", ["line", "block", "underline", "line-thin", "block-outline", "underline-thin"], cursorStyleFromString, { description: localize(483, "Controls the cursor style in insert input mode.") })),
    overtypeCursorStyle: register$1(new EditorEnumOption(92, "overtypeCursorStyle", TextEditorCursorStyle$1.Block, "block", ["line", "block", "underline", "line-thin", "block-outline", "underline-thin"], cursorStyleFromString, { description: localize(484, "Controls the cursor style in overtype input mode.") })),
    cursorSurroundingLines: register$1(new EditorIntOption(35, "cursorSurroundingLines", 0, 0, 1073741824, { description: localize(485, "Controls the minimal number of visible leading lines (minimum 0) and trailing lines (minimum 1) surrounding the cursor. Known as 'scrollOff' or 'scrollOffset' in some other editors.") })),
    cursorSurroundingLinesStyle: register$1(new EditorStringEnumOption(36, "cursorSurroundingLinesStyle", "default", ["default", "all"], {
      enumDescriptions: [
        localize(486, "`cursorSurroundingLines` is enforced only when triggered via the keyboard or API."),
        localize(487, "`cursorSurroundingLines` is enforced always.")
      ],
      markdownDescription: localize(488, "Controls when `#editor.cursorSurroundingLines#` should be enforced.")
    })),
    cursorWidth: register$1(new EditorIntOption(37, "cursorWidth", 0, 0, 1073741824, { markdownDescription: localize(489, "Controls the width of the cursor when `#editor.cursorStyle#` is set to `line`.") })),
    cursorHeight: register$1(new EditorIntOption(38, "cursorHeight", 0, 0, 1073741824, { markdownDescription: localize(490, "Controls the height of the cursor when `#editor.cursorStyle#` is set to `line`. Cursor's max height depends on line height.") })),
    disableLayerHinting: register$1(new EditorBooleanOption(39, "disableLayerHinting", false)),
    disableMonospaceOptimizations: register$1(new EditorBooleanOption(40, "disableMonospaceOptimizations", false)),
    domReadOnly: register$1(new EditorBooleanOption(41, "domReadOnly", false)),
    dragAndDrop: register$1(new EditorBooleanOption(42, "dragAndDrop", true, { description: localize(491, "Controls whether the editor should allow moving selections via drag and drop.") })),
    emptySelectionClipboard: register$1(new EditorEmptySelectionClipboard()),
    dropIntoEditor: register$1(new EditorDropIntoEditor()),
    editContext: register$1(new EditorBooleanOption(44, "editContext", true, {
      description: localize(492, "Sets whether the EditContext API should be used instead of the text area to power input in the editor."),
      included: isChrome || isEdge || isNative
    })),
    renderRichScreenReaderContent: register$1(new EditorBooleanOption(107, "renderRichScreenReaderContent", false, {
      markdownDescription: localize(493, "Whether to render rich screen reader content when the `#editor.editContext#` setting is enabled.")
    })),
    stickyScroll: register$1(new EditorStickyScroll()),
    experimentalGpuAcceleration: register$1(new EditorStringEnumOption(46, "experimentalGpuAcceleration", "off", ["off", "on"], {
      tags: ["experimental"],
      enumDescriptions: [
        localize(494, "Use regular DOM-based rendering."),
        localize(495, "Use GPU acceleration.")
      ],
      description: localize(496, "Controls whether to use the experimental GPU acceleration to render the editor.")
    })),
    experimentalWhitespaceRendering: register$1(new EditorStringEnumOption(47, "experimentalWhitespaceRendering", "svg", ["svg", "font", "off"], {
      enumDescriptions: [
        localize(497, "Use a new rendering method with svgs."),
        localize(498, "Use a new rendering method with font characters."),
        localize(499, "Use the stable rendering method.")
      ],
      description: localize(500, "Controls whether whitespace is rendered with a new, experimental method.")
    })),
    extraEditorClassName: register$1(new EditorStringOption(48, "extraEditorClassName", "")),
    fastScrollSensitivity: register$1(new EditorFloatOption(49, "fastScrollSensitivity", 5, (x) => x <= 0 ? 5 : x, { markdownDescription: localize(501, "Scrolling speed multiplier when pressing `Alt`.") })),
    find: register$1(new EditorFind()),
    fixedOverflowWidgets: register$1(new EditorBooleanOption(51, "fixedOverflowWidgets", false)),
    folding: register$1(new EditorBooleanOption(52, "folding", true, { description: localize(502, "Controls whether the editor has code folding enabled.") })),
    foldingStrategy: register$1(new EditorStringEnumOption(53, "foldingStrategy", "auto", ["auto", "indentation"], {
      enumDescriptions: [
        localize(503, "Use a language-specific folding strategy if available, else the indentation-based one."),
        localize(504, "Use the indentation-based folding strategy.")
      ],
      description: localize(505, "Controls the strategy for computing folding ranges.")
    })),
    foldingHighlight: register$1(new EditorBooleanOption(54, "foldingHighlight", true, { description: localize(506, "Controls whether the editor should highlight folded ranges.") })),
    foldingImportsByDefault: register$1(new EditorBooleanOption(55, "foldingImportsByDefault", false, { description: localize(507, "Controls whether the editor automatically collapses import ranges.") })),
    foldingMaximumRegions: register$1(new EditorIntOption(
      56,
      "foldingMaximumRegions",
      5e3,
      10,
      65e3,
      // limit must be less than foldingRanges MAX_FOLDING_REGIONS
      { description: localize(508, "The maximum number of foldable regions. Increasing this value may result in the editor becoming less responsive when the current source has a large number of foldable regions.") }
    )),
    unfoldOnClickAfterEndOfLine: register$1(new EditorBooleanOption(57, "unfoldOnClickAfterEndOfLine", false, { description: localize(509, "Controls whether clicking on the empty content after a folded line will unfold the line.") })),
    fontFamily: register$1(new EditorStringOption(58, "fontFamily", EDITOR_FONT_DEFAULTS.fontFamily, { description: localize(510, "Controls the font family.") })),
    fontInfo: register$1(new EditorFontInfo()),
    fontLigatures2: register$1(new EditorFontLigatures()),
    fontSize: register$1(new EditorFontSize()),
    fontWeight: register$1(new EditorFontWeight()),
    fontVariations: register$1(new EditorFontVariations()),
    formatOnPaste: register$1(new EditorBooleanOption(64, "formatOnPaste", false, { description: localize(511, "Controls whether the editor should automatically format the pasted content. A formatter must be available and the formatter should be able to format a range in a document.") })),
    formatOnType: register$1(new EditorBooleanOption(65, "formatOnType", false, { description: localize(512, "Controls whether the editor should automatically format the line after typing.") })),
    glyphMargin: register$1(new EditorBooleanOption(66, "glyphMargin", true, { description: localize(513, "Controls whether the editor should render the vertical glyph margin. Glyph margin is mostly used for debugging.") })),
    gotoLocation: register$1(new EditorGoToLocation()),
    hideCursorInOverviewRuler: register$1(new EditorBooleanOption(68, "hideCursorInOverviewRuler", false, { description: localize(514, "Controls whether the cursor should be hidden in the overview ruler.") })),
    hover: register$1(new EditorHover()),
    inDiffEditor: register$1(new EditorBooleanOption(70, "inDiffEditor", false)),
    inertialScroll: register$1(new EditorBooleanOption(158, "inertialScroll", false, { description: localize(515, "Make scrolling inertial - mostly useful with touchpad on linux.") })),
    letterSpacing: register$1(new EditorFloatOption(72, "letterSpacing", EDITOR_FONT_DEFAULTS.letterSpacing, (x) => EditorFloatOption.clamp(x, -5, 20), { description: localize(516, "Controls the letter spacing in pixels.") })),
    lightbulb: register$1(new EditorLightbulb()),
    lineDecorationsWidth: register$1(new EditorLineDecorationsWidth()),
    lineHeight: register$1(new EditorLineHeight()),
    lineNumbers: register$1(new EditorRenderLineNumbersOption()),
    lineNumbersMinChars: register$1(new EditorIntOption(77, "lineNumbersMinChars", 5, 1, 300)),
    linkedEditing: register$1(new EditorBooleanOption(78, "linkedEditing", false, { description: localize(517, "Controls whether the editor has linked editing enabled. Depending on the language, related symbols such as HTML tags, are updated while editing.") })),
    links: register$1(new EditorBooleanOption(79, "links", true, { description: localize(518, "Controls whether the editor should detect links and make them clickable.") })),
    matchBrackets: register$1(new EditorStringEnumOption(80, "matchBrackets", "always", ["always", "near", "never"], { description: localize(519, "Highlight matching brackets.") })),
    minimap: register$1(new EditorMinimap()),
    mouseStyle: register$1(new EditorStringEnumOption(82, "mouseStyle", "text", ["text", "default", "copy"])),
    mouseWheelScrollSensitivity: register$1(new EditorFloatOption(83, "mouseWheelScrollSensitivity", 1, (x) => x === 0 ? 1 : x, { markdownDescription: localize(520, "A multiplier to be used on the `deltaX` and `deltaY` of mouse wheel scroll events.") })),
    mouseWheelZoom: register$1(new EditorBooleanOption(84, "mouseWheelZoom", false, {
      markdownDescription: isMacintosh ? localize(521, "Zoom the font of the editor when using mouse wheel and holding `Cmd`.") : localize(522, "Zoom the font of the editor when using mouse wheel and holding `Ctrl`.")
    })),
    multiCursorMergeOverlapping: register$1(new EditorBooleanOption(85, "multiCursorMergeOverlapping", true, { description: localize(523, "Merge multiple cursors when they are overlapping.") })),
    multiCursorModifier: register$1(new EditorEnumOption(86, "multiCursorModifier", "altKey", "alt", ["ctrlCmd", "alt"], _multiCursorModifierFromString, {
      markdownEnumDescriptions: [
        localize(524, "Maps to `Control` on Windows and Linux and to `Command` on macOS."),
        localize(525, "Maps to `Alt` on Windows and Linux and to `Option` on macOS.")
      ],
      markdownDescription: localize(526, "The modifier to be used to add multiple cursors with the mouse. The Go to Definition and Open Link mouse gestures will adapt such that they do not conflict with the [multicursor modifier](https://code.visualstudio.com/docs/editor/codebasics#_multicursor-modifier).")
    })),
    mouseMiddleClickAction: register$1(new EditorStringEnumOption(87, "mouseMiddleClickAction", "default", ["default", "openLink", "ctrlLeftClick"], { description: localize(527, "Controls what happens when middle mouse button is clicked in the editor.") })),
    multiCursorPaste: register$1(new EditorStringEnumOption(88, "multiCursorPaste", "spread", ["spread", "full"], {
      markdownEnumDescriptions: [
        localize(528, "Each cursor pastes a single line of the text."),
        localize(529, "Each cursor pastes the full text.")
      ],
      markdownDescription: localize(530, "Controls pasting when the line count of the pasted text matches the cursor count.")
    })),
    multiCursorLimit: register$1(new EditorIntOption(89, "multiCursorLimit", 1e4, 1, 1e5, {
      markdownDescription: localize(531, "Controls the max number of cursors that can be in an active editor at once.")
    })),
    occurrencesHighlight: register$1(new EditorStringEnumOption(90, "occurrencesHighlight", "singleFile", ["off", "singleFile", "multiFile"], {
      markdownEnumDescriptions: [
        localize(532, "Does not highlight occurrences."),
        localize(533, "Highlights occurrences only in the current file."),
        localize(534, "Experimental: Highlights occurrences across all valid open files.")
      ],
      markdownDescription: localize(535, "Controls whether occurrences should be highlighted across open files.")
    })),
    occurrencesHighlightDelay: register$1(new EditorIntOption(91, "occurrencesHighlightDelay", 0, 0, 2e3, {
      description: localize(536, "Controls the delay in milliseconds after which occurrences are highlighted."),
      tags: ["preview"]
    })),
    overtypeOnPaste: register$1(new EditorBooleanOption(93, "overtypeOnPaste", true, { description: localize(537, "Controls whether pasting should overtype.") })),
    overviewRulerBorder: register$1(new EditorBooleanOption(94, "overviewRulerBorder", true, { description: localize(538, "Controls whether a border should be drawn around the overview ruler.") })),
    overviewRulerLanes: register$1(new EditorIntOption(95, "overviewRulerLanes", 3, 0, 3)),
    padding: register$1(new EditorPadding()),
    pasteAs: register$1(new EditorPasteAs()),
    parameterHints: register$1(new EditorParameterHints()),
    peekWidgetDefaultFocus: register$1(new EditorStringEnumOption(99, "peekWidgetDefaultFocus", "tree", ["tree", "editor"], {
      enumDescriptions: [
        localize(539, "Focus the tree when opening peek"),
        localize(540, "Focus the editor when opening peek")
      ],
      description: localize(541, "Controls whether to focus the inline editor or the tree in the peek widget.")
    })),
    placeholder: register$1(new PlaceholderOption()),
    definitionLinkOpensInPeek: register$1(new EditorBooleanOption(101, "definitionLinkOpensInPeek", false, { description: localize(542, "Controls whether the Go to Definition mouse gesture always opens the peek widget.") })),
    quickSuggestions: register$1(new EditorQuickSuggestions()),
    quickSuggestionsDelay: register$1(new EditorIntOption(103, "quickSuggestionsDelay", 10, 0, 1073741824, {
      description: localize(543, "Controls the delay in milliseconds after which quick suggestions will show up."),
      experiment: {
        mode: "auto"
      }
    })),
    readOnly: register$1(new EditorBooleanOption(104, "readOnly", false)),
    readOnlyMessage: register$1(new ReadonlyMessage()),
    renameOnType: register$1(new EditorBooleanOption(106, "renameOnType", false, { description: localize(544, "Controls whether the editor auto renames on type."), markdownDeprecationMessage: localize(545, "Deprecated, use `#editor.linkedEditing#` instead.") })),
    renderControlCharacters: register$1(new EditorBooleanOption(108, "renderControlCharacters", true, { description: localize(546, "Controls whether the editor should render control characters."), restricted: true })),
    renderFinalNewline: register$1(new EditorStringEnumOption(109, "renderFinalNewline", isLinux ? "dimmed" : "on", ["off", "on", "dimmed"], { description: localize(547, "Render last line number when the file ends with a newline.") })),
    renderLineHighlight: register$1(new EditorStringEnumOption(110, "renderLineHighlight", "line", ["none", "gutter", "line", "all"], {
      enumDescriptions: [
        "",
        "",
        "",
        localize(548, "Highlights both the gutter and the current line.")
      ],
      description: localize(549, "Controls how the editor should render the current line highlight.")
    })),
    renderLineHighlightOnlyWhenFocus: register$1(new EditorBooleanOption(111, "renderLineHighlightOnlyWhenFocus", false, { description: localize(550, "Controls if the editor should render the current line highlight only when the editor is focused.") })),
    renderValidationDecorations: register$1(new EditorStringEnumOption(112, "renderValidationDecorations", "editable", ["editable", "on", "off"])),
    renderWhitespace: register$1(new EditorStringEnumOption(113, "renderWhitespace", "selection", ["none", "boundary", "selection", "trailing", "all"], {
      enumDescriptions: [
        "",
        localize(551, "Render whitespace characters except for single spaces between words."),
        localize(552, "Render whitespace characters only on selected text."),
        localize(553, "Render only trailing whitespace characters."),
        ""
      ],
      description: localize(554, "Controls how the editor should render whitespace characters.")
    })),
    revealHorizontalRightPadding: register$1(new EditorIntOption(114, "revealHorizontalRightPadding", 15, 0, 1e3)),
    roundedSelection: register$1(new EditorBooleanOption(115, "roundedSelection", true, { description: localize(555, "Controls whether selections should have rounded corners.") })),
    rulers: register$1(new EditorRulers()),
    scrollbar: register$1(new EditorScrollbar$1()),
    scrollBeyondLastColumn: register$1(new EditorIntOption(118, "scrollBeyondLastColumn", 4, 0, 1073741824, { description: localize(556, "Controls the number of extra characters beyond which the editor will scroll horizontally.") })),
    scrollBeyondLastLine: register$1(new EditorBooleanOption(119, "scrollBeyondLastLine", true, { description: localize(557, "Controls whether the editor will scroll beyond the last line.") })),
    scrollOnMiddleClick: register$1(new EditorBooleanOption(171, "scrollOnMiddleClick", false, { description: localize(558, "Controls whether the editor will scroll when the middle button is pressed.") })),
    scrollPredominantAxis: register$1(new EditorBooleanOption(120, "scrollPredominantAxis", true, { description: localize(559, "Scroll only along the predominant axis when scrolling both vertically and horizontally at the same time. Prevents horizontal drift when scrolling vertically on a trackpad.") })),
    selectionClipboard: register$1(new EditorBooleanOption(121, "selectionClipboard", true, {
      description: localize(560, "Controls whether the Linux primary clipboard should be supported."),
      included: isLinux
    })),
    selectionHighlight: register$1(new EditorBooleanOption(122, "selectionHighlight", true, { description: localize(561, "Controls whether the editor should highlight matches similar to the selection.") })),
    selectionHighlightMaxLength: register$1(new EditorIntOption(123, "selectionHighlightMaxLength", 200, 0, 1073741824, { description: localize(562, "Controls how many characters can be in the selection before similiar matches are not highlighted. Set to zero for unlimited.") })),
    selectionHighlightMultiline: register$1(new EditorBooleanOption(124, "selectionHighlightMultiline", false, { description: localize(563, "Controls whether the editor should highlight selection matches that span multiple lines.") })),
    selectOnLineNumbers: register$1(new EditorBooleanOption(125, "selectOnLineNumbers", true)),
    showFoldingControls: register$1(new EditorStringEnumOption(126, "showFoldingControls", "mouseover", ["always", "never", "mouseover"], {
      enumDescriptions: [
        localize(564, "Always show the folding controls."),
        localize(565, "Never show the folding controls and reduce the gutter size."),
        localize(566, "Only show the folding controls when the mouse is over the gutter.")
      ],
      description: localize(567, "Controls when the folding controls on the gutter are shown.")
    })),
    showUnused: register$1(new EditorBooleanOption(127, "showUnused", true, { description: localize(568, "Controls fading out of unused code.") })),
    showDeprecated: register$1(new EditorBooleanOption(157, "showDeprecated", true, { description: localize(569, "Controls strikethrough deprecated variables.") })),
    inlayHints: register$1(new EditorInlayHints()),
    snippetSuggestions: register$1(new EditorStringEnumOption(128, "snippetSuggestions", "inline", ["top", "bottom", "inline", "none"], {
      enumDescriptions: [
        localize(570, "Show snippet suggestions on top of other suggestions."),
        localize(571, "Show snippet suggestions below other suggestions."),
        localize(572, "Show snippets suggestions with other suggestions."),
        localize(573, "Do not show snippet suggestions.")
      ],
      description: localize(574, "Controls whether snippets are shown with other suggestions and how they are sorted.")
    })),
    smartSelect: register$1(new SmartSelect()),
    smoothScrolling: register$1(new EditorBooleanOption(130, "smoothScrolling", false, { description: localize(575, "Controls whether the editor will scroll using an animation.") })),
    stopRenderingLineAfter: register$1(new EditorIntOption(
      133,
      "stopRenderingLineAfter",
      1e4,
      -1,
      1073741824
      /* Constants.MAX_SAFE_SMALL_INTEGER */
    )),
    suggest: register$1(new EditorSuggest()),
    inlineSuggest: register$1(new InlineEditorSuggest()),
    inlineCompletionsAccessibilityVerbose: register$1(new EditorBooleanOption(169, "inlineCompletionsAccessibilityVerbose", false, { description: localize(576, "Controls whether the accessibility hint should be provided to screen reader users when an inline completion is shown.") })),
    suggestFontSize: register$1(new EditorIntOption(135, "suggestFontSize", 0, 0, 1e3, { markdownDescription: localize(577, "Font size for the suggest widget. When set to {0}, the value of {1} is used.", "`0`", "`#editor.fontSize#`") })),
    suggestLineHeight: register$1(new EditorIntOption(136, "suggestLineHeight", 0, 0, 1e3, { markdownDescription: localize(578, "Line height for the suggest widget. When set to {0}, the value of {1} is used. The minimum value is 8.", "`0`", "`#editor.lineHeight#`") })),
    suggestOnTriggerCharacters: register$1(new EditorBooleanOption(137, "suggestOnTriggerCharacters", true, { description: localize(579, "Controls whether suggestions should automatically show up when typing trigger characters.") })),
    suggestSelection: register$1(new EditorStringEnumOption(138, "suggestSelection", "first", ["first", "recentlyUsed", "recentlyUsedByPrefix"], {
      markdownEnumDescriptions: [
        localize(580, "Always select the first suggestion."),
        localize(581, "Select recent suggestions unless further typing selects one, e.g. `console.| -> console.log` because `log` has been completed recently."),
        localize(582, "Select suggestions based on previous prefixes that have completed those suggestions, e.g. `co -> console` and `con -> const`.")
      ],
      description: localize(583, "Controls how suggestions are pre-selected when showing the suggest list.")
    })),
    tabCompletion: register$1(new EditorStringEnumOption(139, "tabCompletion", "off", ["on", "off", "onlySnippets"], {
      enumDescriptions: [
        localize(584, "Tab complete will insert the best matching suggestion when pressing tab."),
        localize(585, "Disable tab completions."),
        localize(586, "Tab complete snippets when their prefix match. Works best when 'quickSuggestions' aren't enabled.")
      ],
      description: localize(587, "Enables tab completions.")
    })),
    tabIndex: register$1(new EditorIntOption(
      140,
      "tabIndex",
      0,
      -1,
      1073741824
      /* Constants.MAX_SAFE_SMALL_INTEGER */
    )),
    trimWhitespaceOnDelete: register$1(new EditorBooleanOption(141, "trimWhitespaceOnDelete", false, { description: localize(588, "Controls whether the editor will also delete the next line's indentation whitespace when deleting a newline.") })),
    unicodeHighlight: register$1(new UnicodeHighlight()),
    unusualLineTerminators: register$1(new EditorStringEnumOption(143, "unusualLineTerminators", "prompt", ["auto", "off", "prompt"], {
      enumDescriptions: [
        localize(589, "Unusual line terminators are automatically removed."),
        localize(590, "Unusual line terminators are ignored."),
        localize(591, "Unusual line terminators prompt to be removed.")
      ],
      description: localize(592, "Remove unusual line terminators that might cause problems.")
    })),
    useShadowDOM: register$1(new EditorBooleanOption(144, "useShadowDOM", true)),
    useTabStops: register$1(new EditorBooleanOption(145, "useTabStops", true, { description: localize(593, "Spaces and tabs are inserted and deleted in alignment with tab stops.") })),
    wordBreak: register$1(new EditorStringEnumOption(146, "wordBreak", "normal", ["normal", "keepAll"], {
      markdownEnumDescriptions: [
        localize(594, "Use the default line break rule."),
        localize(595, "Word breaks should not be used for Chinese/Japanese/Korean (CJK) text. Non-CJK text behavior is the same as for normal.")
      ],
      description: localize(596, "Controls the word break rules used for Chinese/Japanese/Korean (CJK) text.")
    })),
    wordSegmenterLocales: register$1(new WordSegmenterLocales()),
    wordSeparators: register$1(new EditorStringOption(148, "wordSeparators", USUAL_WORD_SEPARATORS, { description: localize(597, "Characters that will be used as word separators when doing word related navigations or operations.") })),
    wordWrap: register$1(new EditorStringEnumOption(149, "wordWrap", "off", ["off", "on", "wordWrapColumn", "bounded"], {
      markdownEnumDescriptions: [
        localize(598, "Lines will never wrap."),
        localize(599, "Lines will wrap at the viewport width."),
        localize(600, "Lines will wrap at `#editor.wordWrapColumn#`."),
        localize(601, "Lines will wrap at the minimum of viewport and `#editor.wordWrapColumn#`.")
      ],
      description: localize(602, "Controls how lines should wrap.")
    })),
    wordWrapBreakAfterCharacters: register$1(new EditorStringOption(
      150,
      "wordWrapBreakAfterCharacters",
      // allow-any-unicode-next-line
      " 	})]?|/&.,;¢°′″‰℃、。｡､￠，．：；？！％・･ゝゞヽヾーァィゥェォッャュョヮヵヶぁぃぅぇぉっゃゅょゎゕゖㇰㇱㇲㇳㇴㇵㇶㇷㇸㇹㇺㇻㇼㇽㇾㇿ々〻ｧｨｩｪｫｬｭｮｯｰ”〉》」』】〕）］｝｣"
    )),
    wordWrapBreakBeforeCharacters: register$1(new EditorStringOption(
      151,
      "wordWrapBreakBeforeCharacters",
      // allow-any-unicode-next-line
      "([{‘“〈《「『【〔（［｛｢£¥＄￡￥+＋"
    )),
    wordWrapColumn: register$1(new EditorIntOption(152, "wordWrapColumn", 80, 1, 1073741824, {
      markdownDescription: localize(603, "Controls the wrapping column of the editor when `#editor.wordWrap#` is `wordWrapColumn` or `bounded`.")
    })),
    wordWrapOverride1: register$1(new EditorStringEnumOption(153, "wordWrapOverride1", "inherit", ["off", "on", "inherit"])),
    wordWrapOverride2: register$1(new EditorStringEnumOption(154, "wordWrapOverride2", "inherit", ["off", "on", "inherit"])),
    wrapOnEscapedLineFeeds: register$1(new EditorBooleanOption(160, "wrapOnEscapedLineFeeds", false, { markdownDescription: localize(604, 'Controls whether literal `\\n` shall trigger a wordWrap when `#editor.wordWrap#` is enabled.\n\nFor example:\n```c\nchar* str="hello\\nworld"\n```\nwill be displayed as\n```c\nchar* str="hello\\n\n           world"\n```') })),
    // Leave these at the end (because they have dependencies!)
    effectiveCursorStyle: register$1(new EffectiveCursorStyle()),
    editorClassName: register$1(new EditorClassName()),
    defaultColorDecorators: register$1(new EditorStringEnumOption(167, "defaultColorDecorators", "auto", ["auto", "always", "never"], {
      enumDescriptions: [
        localize(605, "Show default color decorators only when no extension provides colors decorators."),
        localize(606, "Always show default color decorators."),
        localize(607, "Never show default color decorators.")
      ],
      description: localize(608, "Controls whether inline color decorations should be shown using the default document color provider.")
    })),
    pixelRatio: register$1(new EditorPixelRatio()),
    tabFocusMode: register$1(new EditorBooleanOption(164, "tabFocusMode", false, { markdownDescription: localize(609, "Controls whether the editor receives tabs or defers them to the workbench for navigation.") })),
    layoutInfo: register$1(new EditorLayoutInfoComputer()),
    wrappingInfo: register$1(new EditorWrappingInfoComputer()),
    wrappingIndent: register$1(new WrappingIndentOption()),
    wrappingStrategy: register$1(new WrappingStrategy()),
    effectiveEditContextEnabled: register$1(new EffectiveEditContextEnabled()),
    effectiveAllowVariableFonts: register$1(new EffectiveAllowVariableFonts())
  };
  class FontMeasurementsImpl extends Disposable {
    constructor() {
      super(...arguments);
      this._cache = /* @__PURE__ */ new Map();
      this._evictUntrustedReadingsTimeout = -1;
      this._onDidChange = this._register(new Emitter$1());
      this.onDidChange = this._onDidChange.event;
    }
    dispose() {
      if (this._evictUntrustedReadingsTimeout !== -1) {
        clearTimeout(this._evictUntrustedReadingsTimeout);
        this._evictUntrustedReadingsTimeout = -1;
      }
      super.dispose();
    }
    /**
     * Clear all cached font information and trigger a change event.
     */
    clearAllFontInfos() {
      this._cache.clear();
      this._onDidChange.fire();
    }
    _ensureCache(targetWindow) {
      const windowId = getWindowId(targetWindow);
      let cache = this._cache.get(windowId);
      if (!cache) {
        cache = new FontMeasurementsCache();
        this._cache.set(windowId, cache);
      }
      return cache;
    }
    _writeToCache(targetWindow, item, value) {
      const cache = this._ensureCache(targetWindow);
      cache.put(item, value);
      if (!value.isTrusted && this._evictUntrustedReadingsTimeout === -1) {
        this._evictUntrustedReadingsTimeout = targetWindow.setTimeout(() => {
          this._evictUntrustedReadingsTimeout = -1;
          this._evictUntrustedReadings(targetWindow);
        }, 5e3);
      }
    }
    _evictUntrustedReadings(targetWindow) {
      const cache = this._ensureCache(targetWindow);
      const values = cache.getValues();
      let somethingRemoved = false;
      for (const item of values) {
        if (!item.isTrusted) {
          somethingRemoved = true;
          cache.remove(item);
        }
      }
      if (somethingRemoved) {
        this._onDidChange.fire();
      }
    }
    /**
     * Read font information.
     */
    readFontInfo(targetWindow, bareFontInfo) {
      const cache = this._ensureCache(targetWindow);
      if (!cache.has(bareFontInfo)) {
        let readConfig = this._actualReadFontInfo(targetWindow, bareFontInfo);
        if (readConfig.typicalHalfwidthCharacterWidth <= 2 || readConfig.typicalFullwidthCharacterWidth <= 2 || readConfig.spaceWidth <= 2 || readConfig.maxDigitWidth <= 2) {
          readConfig = new FontInfo({
            pixelRatio: PixelRatio.getInstance(targetWindow).value,
            fontFamily: readConfig.fontFamily,
            fontWeight: readConfig.fontWeight,
            fontSize: readConfig.fontSize,
            fontFeatureSettings: readConfig.fontFeatureSettings,
            fontVariationSettings: readConfig.fontVariationSettings,
            lineHeight: readConfig.lineHeight,
            letterSpacing: readConfig.letterSpacing,
            isMonospace: readConfig.isMonospace,
            typicalHalfwidthCharacterWidth: Math.max(readConfig.typicalHalfwidthCharacterWidth, 5),
            typicalFullwidthCharacterWidth: Math.max(readConfig.typicalFullwidthCharacterWidth, 5),
            canUseHalfwidthRightwardsArrow: readConfig.canUseHalfwidthRightwardsArrow,
            spaceWidth: Math.max(readConfig.spaceWidth, 5),
            middotWidth: Math.max(readConfig.middotWidth, 5),
            wsmiddotWidth: Math.max(readConfig.wsmiddotWidth, 5),
            maxDigitWidth: Math.max(readConfig.maxDigitWidth, 5)
          }, false);
        }
        this._writeToCache(targetWindow, bareFontInfo, readConfig);
      }
      return cache.get(bareFontInfo);
    }
    _createRequest(chr, type, all, monospace) {
      const result = new CharWidthRequest(chr, type);
      all.push(result);
      monospace?.push(result);
      return result;
    }
    _actualReadFontInfo(targetWindow, bareFontInfo) {
      const all = [];
      const monospace = [];
      const typicalHalfwidthCharacter = this._createRequest("n", 0, all, monospace);
      const typicalFullwidthCharacter = this._createRequest("ｍ", 0, all, null);
      const space = this._createRequest(" ", 0, all, monospace);
      const digit0 = this._createRequest("0", 0, all, monospace);
      const digit1 = this._createRequest("1", 0, all, monospace);
      const digit2 = this._createRequest("2", 0, all, monospace);
      const digit3 = this._createRequest("3", 0, all, monospace);
      const digit4 = this._createRequest("4", 0, all, monospace);
      const digit5 = this._createRequest("5", 0, all, monospace);
      const digit6 = this._createRequest("6", 0, all, monospace);
      const digit7 = this._createRequest("7", 0, all, monospace);
      const digit8 = this._createRequest("8", 0, all, monospace);
      const digit9 = this._createRequest("9", 0, all, monospace);
      const rightwardsArrow = this._createRequest("→", 0, all, monospace);
      const halfwidthRightwardsArrow = this._createRequest("￫", 0, all, null);
      const middot = this._createRequest("·", 0, all, monospace);
      const wsmiddotWidth = this._createRequest(String.fromCharCode(11825), 0, all, null);
      const monospaceTestChars = "|/-_ilm%";
      for (let i2 = 0, len = monospaceTestChars.length; i2 < len; i2++) {
        this._createRequest(monospaceTestChars.charAt(i2), 0, all, monospace);
        this._createRequest(monospaceTestChars.charAt(i2), 1, all, monospace);
        this._createRequest(monospaceTestChars.charAt(i2), 2, all, monospace);
      }
      readCharWidths(targetWindow, bareFontInfo, all);
      const maxDigitWidth = Math.max(digit0.width, digit1.width, digit2.width, digit3.width, digit4.width, digit5.width, digit6.width, digit7.width, digit8.width, digit9.width);
      let isMonospace = bareFontInfo.fontFeatureSettings === EditorFontLigatures.OFF;
      const referenceWidth = monospace[0].width;
      for (let i2 = 1, len = monospace.length; isMonospace && i2 < len; i2++) {
        const diff = referenceWidth - monospace[i2].width;
        if (diff < -1e-3 || diff > 1e-3) {
          isMonospace = false;
          break;
        }
      }
      let canUseHalfwidthRightwardsArrow = true;
      if (isMonospace && halfwidthRightwardsArrow.width !== referenceWidth) {
        canUseHalfwidthRightwardsArrow = false;
      }
      if (halfwidthRightwardsArrow.width > rightwardsArrow.width) {
        canUseHalfwidthRightwardsArrow = false;
      }
      return new FontInfo({
        pixelRatio: PixelRatio.getInstance(targetWindow).value,
        fontFamily: bareFontInfo.fontFamily,
        fontWeight: bareFontInfo.fontWeight,
        fontSize: bareFontInfo.fontSize,
        fontFeatureSettings: bareFontInfo.fontFeatureSettings,
        fontVariationSettings: bareFontInfo.fontVariationSettings,
        lineHeight: bareFontInfo.lineHeight,
        letterSpacing: bareFontInfo.letterSpacing,
        isMonospace,
        typicalHalfwidthCharacterWidth: typicalHalfwidthCharacter.width,
        typicalFullwidthCharacterWidth: typicalFullwidthCharacter.width,
        canUseHalfwidthRightwardsArrow,
        spaceWidth: space.width,
        middotWidth: middot.width,
        wsmiddotWidth: wsmiddotWidth.width,
        maxDigitWidth
      }, true);
    }
  }
  class FontMeasurementsCache {
    constructor() {
      this._keys = /* @__PURE__ */ Object.create(null);
      this._values = /* @__PURE__ */ Object.create(null);
    }
    has(item) {
      const itemId = item.getId();
      return !!this._values[itemId];
    }
    get(item) {
      const itemId = item.getId();
      return this._values[itemId];
    }
    put(item, value) {
      const itemId = item.getId();
      this._keys[itemId] = item;
      this._values[itemId] = value;
    }
    remove(item) {
      const itemId = item.getId();
      delete this._keys[itemId];
      delete this._values[itemId];
    }
    getValues() {
      return Object.keys(this._keys).map((id) => this._values[id]);
    }
  }
  const FontMeasurements = new FontMeasurementsImpl();
  const _EditorSettingMigration = class _EditorSettingMigration {
    constructor(key, migrate) {
      this.key = key;
      this.migrate = migrate;
    }
    apply(options) {
      const value = _EditorSettingMigration._read(options, this.key);
      const read = (key) => _EditorSettingMigration._read(options, key);
      const write = (key, value2) => _EditorSettingMigration._write(options, key, value2);
      this.migrate(value, read, write);
    }
    static _read(source, key) {
      if (typeof source === "undefined" || source === null) {
        return void 0;
      }
      const firstDotIndex = key.indexOf(".");
      if (firstDotIndex >= 0) {
        const firstSegment = key.substring(0, firstDotIndex);
        return this._read(source[firstSegment], key.substring(firstDotIndex + 1));
      }
      return source[key];
    }
    static _write(target, key, value) {
      const firstDotIndex = key.indexOf(".");
      if (firstDotIndex >= 0) {
        const firstSegment = key.substring(0, firstDotIndex);
        target[firstSegment] = target[firstSegment] || {};
        this._write(target[firstSegment], key.substring(firstDotIndex + 1), value);
        return;
      }
      target[key] = value;
    }
  };
  _EditorSettingMigration.items = [];
  let EditorSettingMigration = _EditorSettingMigration;
  function registerEditorSettingMigration(key, migrate) {
    EditorSettingMigration.items.push(new EditorSettingMigration(key, migrate));
  }
  function registerSimpleEditorSettingMigration(key, values) {
    registerEditorSettingMigration(key, (value, read, write) => {
      if (typeof value !== "undefined") {
        for (const [oldValue, newValue] of values) {
          if (value === oldValue) {
            write(key, newValue);
            return;
          }
        }
      }
    });
  }
  function migrateOptions(options) {
    EditorSettingMigration.items.forEach((migration) => migration.apply(options));
  }
  registerSimpleEditorSettingMigration("wordWrap", [[true, "on"], [false, "off"]]);
  registerSimpleEditorSettingMigration("lineNumbers", [[true, "on"], [false, "off"]]);
  registerSimpleEditorSettingMigration("cursorBlinking", [["visible", "solid"]]);
  registerSimpleEditorSettingMigration("renderWhitespace", [[true, "boundary"], [false, "none"]]);
  registerSimpleEditorSettingMigration("renderLineHighlight", [[true, "line"], [false, "none"]]);
  registerSimpleEditorSettingMigration("acceptSuggestionOnEnter", [[true, "on"], [false, "off"]]);
  registerSimpleEditorSettingMigration("tabCompletion", [[false, "off"], [true, "onlySnippets"]]);
  registerSimpleEditorSettingMigration("hover", [[true, { enabled: true }], [false, { enabled: false }]]);
  registerSimpleEditorSettingMigration("parameterHints", [[true, { enabled: true }], [false, { enabled: false }]]);
  registerSimpleEditorSettingMigration("autoIndent", [[false, "advanced"], [true, "full"]]);
  registerSimpleEditorSettingMigration("matchBrackets", [[true, "always"], [false, "never"]]);
  registerSimpleEditorSettingMigration("renderFinalNewline", [[true, "on"], [false, "off"]]);
  registerSimpleEditorSettingMigration("cursorSmoothCaretAnimation", [[true, "on"], [false, "off"]]);
  registerSimpleEditorSettingMigration("occurrencesHighlight", [[true, "singleFile"], [false, "off"]]);
  registerSimpleEditorSettingMigration("wordBasedSuggestions", [[true, "matchingDocuments"], [false, "off"]]);
  registerSimpleEditorSettingMigration("defaultColorDecorators", [[true, "auto"], [false, "never"]]);
  registerSimpleEditorSettingMigration("minimap.autohide", [[true, "mouseover"], [false, "none"]]);
  registerEditorSettingMigration("autoClosingBrackets", (value, read, write) => {
    if (value === false) {
      write("autoClosingBrackets", "never");
      if (typeof read("autoClosingQuotes") === "undefined") {
        write("autoClosingQuotes", "never");
      }
      if (typeof read("autoSurround") === "undefined") {
        write("autoSurround", "never");
      }
    }
  });
  registerEditorSettingMigration("renderIndentGuides", (value, read, write) => {
    if (typeof value !== "undefined") {
      write("renderIndentGuides", void 0);
      if (typeof read("guides.indentation") === "undefined") {
        write("guides.indentation", !!value);
      }
    }
  });
  registerEditorSettingMigration("highlightActiveIndentGuide", (value, read, write) => {
    if (typeof value !== "undefined") {
      write("highlightActiveIndentGuide", void 0);
      if (typeof read("guides.highlightActiveIndentation") === "undefined") {
        write("guides.highlightActiveIndentation", !!value);
      }
    }
  });
  const suggestFilteredTypesMapping = {
    method: "showMethods",
    function: "showFunctions",
    constructor: "showConstructors",
    deprecated: "showDeprecated",
    field: "showFields",
    variable: "showVariables",
    class: "showClasses",
    struct: "showStructs",
    interface: "showInterfaces",
    module: "showModules",
    property: "showProperties",
    event: "showEvents",
    operator: "showOperators",
    unit: "showUnits",
    value: "showValues",
    constant: "showConstants",
    enum: "showEnums",
    enumMember: "showEnumMembers",
    keyword: "showKeywords",
    text: "showWords",
    color: "showColors",
    file: "showFiles",
    reference: "showReferences",
    folder: "showFolders",
    typeParameter: "showTypeParameters",
    snippet: "showSnippets"
  };
  registerEditorSettingMigration("suggest.filteredTypes", (value, read, write) => {
    if (value && typeof value === "object") {
      for (const entry of Object.entries(suggestFilteredTypesMapping)) {
        const v = value[entry[0]];
        if (v === false) {
          if (typeof read(`suggest.${entry[1]}`) === "undefined") {
            write(`suggest.${entry[1]}`, false);
          }
        }
      }
      write("suggest.filteredTypes", void 0);
    }
  });
  registerEditorSettingMigration("quickSuggestions", (input, read, write) => {
    if (typeof input === "boolean") {
      const value = input ? "on" : "off";
      const newValue = { comments: value, strings: value, other: value };
      write("quickSuggestions", newValue);
    }
  });
  registerEditorSettingMigration("experimental.stickyScroll.enabled", (value, read, write) => {
    if (typeof value === "boolean") {
      write("experimental.stickyScroll.enabled", void 0);
      if (typeof read("stickyScroll.enabled") === "undefined") {
        write("stickyScroll.enabled", value);
      }
    }
  });
  registerEditorSettingMigration("experimental.stickyScroll.maxLineCount", (value, read, write) => {
    if (typeof value === "number") {
      write("experimental.stickyScroll.maxLineCount", void 0);
      if (typeof read("stickyScroll.maxLineCount") === "undefined") {
        write("stickyScroll.maxLineCount", value);
      }
    }
  });
  registerEditorSettingMigration("editor.experimentalEditContextEnabled", (value, read, write) => {
    if (typeof value === "boolean") {
      write("editor.experimentalEditContextEnabled", void 0);
      if (typeof read("editor.editContext") === "undefined") {
        write("editor.editContext", value);
      }
    }
  });
  registerEditorSettingMigration("codeActionsOnSave", (value, read, write) => {
    if (value && typeof value === "object") {
      let toBeModified = false;
      const newValue = {};
      for (const entry of Object.entries(value)) {
        if (typeof entry[1] === "boolean") {
          toBeModified = true;
          newValue[entry[0]] = entry[1] ? "explicit" : "never";
        } else {
          newValue[entry[0]] = entry[1];
        }
      }
      if (toBeModified) {
        write(`codeActionsOnSave`, newValue);
      }
    }
  });
  registerEditorSettingMigration("codeActionWidget.includeNearbyQuickfixes", (value, read, write) => {
    if (typeof value === "boolean") {
      write("codeActionWidget.includeNearbyQuickfixes", void 0);
      if (typeof read("codeActionWidget.includeNearbyQuickFixes") === "undefined") {
        write("codeActionWidget.includeNearbyQuickFixes", value);
      }
    }
  });
  registerEditorSettingMigration("lightbulb.enabled", (value, read, write) => {
    if (typeof value === "boolean") {
      write("lightbulb.enabled", value ? void 0 : "off");
    }
  });
  registerEditorSettingMigration("inlineSuggest.edits.codeShifting", (value, read, write) => {
    if (typeof value === "boolean") {
      write("inlineSuggest.edits.codeShifting", void 0);
      write("inlineSuggest.edits.allowCodeShifting", value ? "always" : "never");
    }
  });
  class TabFocusImpl {
    constructor() {
      this._tabFocus = false;
      this._onDidChangeTabFocus = new Emitter$1();
      this.onDidChangeTabFocus = this._onDidChangeTabFocus.event;
    }
    getTabFocusMode() {
      return this._tabFocus;
    }
    setTabFocusMode(tabFocusMode) {
      this._tabFocus = tabFocusMode;
      this._onDidChangeTabFocus.fire(this._tabFocus);
    }
  }
  const TabFocus = new TabFocusImpl();
  function createBareFontInfoFromValidatedSettings(options, pixelRatio, ignoreEditorZoom) {
    const fontFamily = options.get(
      58
      /* EditorOption.fontFamily */
    );
    const fontWeight = options.get(
      62
      /* EditorOption.fontWeight */
    );
    const fontSize = options.get(
      61
      /* EditorOption.fontSize */
    );
    const fontFeatureSettings = options.get(
      60
      /* EditorOption.fontLigatures */
    );
    const fontVariationSettings = options.get(
      63
      /* EditorOption.fontVariations */
    );
    const lineHeight = options.get(
      75
      /* EditorOption.lineHeight */
    );
    const letterSpacing = options.get(
      72
      /* EditorOption.letterSpacing */
    );
    return BareFontInfo._create(fontFamily, fontWeight, fontSize, fontFeatureSettings, fontVariationSettings, lineHeight, letterSpacing, pixelRatio, ignoreEditorZoom);
  }
  function createBareFontInfoFromRawSettings(opts, pixelRatio, ignoreEditorZoom = false) {
    const fontFamily = EditorOptions.fontFamily.validate(opts.fontFamily);
    const fontWeight = EditorOptions.fontWeight.validate(opts.fontWeight);
    const fontSize = EditorOptions.fontSize.validate(opts.fontSize);
    const fontFeatureSettings = EditorOptions.fontLigatures2.validate(opts.fontLigatures);
    const fontVariationSettings = EditorOptions.fontVariations.validate(opts.fontVariations);
    const lineHeight = EditorOptions.lineHeight.validate(opts.lineHeight);
    const letterSpacing = EditorOptions.letterSpacing.validate(opts.letterSpacing);
    return BareFontInfo._create(fontFamily, fontWeight, fontSize, fontFeatureSettings, fontVariationSettings, lineHeight, letterSpacing, pixelRatio, ignoreEditorZoom);
  }
  const IAccessibilityService = createDecorator("accessibilityService");
  const CONTEXT_ACCESSIBILITY_MODE_ENABLED = new RawContextKey("accessibilityModeEnabled", false);
  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);
    };
  };
  let EditorConfiguration = class EditorConfiguration extends Disposable {
    constructor(isSimpleWidget, contextMenuId, options, container, _accessibilityService) {
      super();
      this._accessibilityService = _accessibilityService;
      this._onDidChange = this._register(new Emitter$1());
      this.onDidChange = this._onDidChange.event;
      this._onDidChangeFast = this._register(new Emitter$1());
      this.onDidChangeFast = this._onDidChangeFast.event;
      this._isDominatedByLongLines = false;
      this._viewLineCount = 1;
      this._lineNumbersDigitCount = 1;
      this._reservedHeight = 0;
      this._glyphMarginDecorationLaneCount = 1;
      this._computeOptionsMemory = new ComputeOptionsMemory();
      this.isSimpleWidget = isSimpleWidget;
      this.contextMenuId = contextMenuId;
      this._containerObserver = this._register(new ElementSizeObserver(container, options.dimension));
      this._targetWindowId = getWindow(container).vscodeWindowId;
      this._rawOptions = deepCloneAndMigrateOptions(options);
      this._validatedOptions = EditorOptionsUtil.validateOptions(this._rawOptions);
      this.options = this._computeOptions();
      if (this.options.get(
        19
        /* EditorOption.automaticLayout */
      )) {
        this._containerObserver.startObserving();
      }
      this._register(EditorZoom.onDidChangeZoomLevel(() => this._recomputeOptions()));
      this._register(TabFocus.onDidChangeTabFocus(() => this._recomputeOptions()));
      this._register(this._containerObserver.onDidChange(() => this._recomputeOptions()));
      this._register(FontMeasurements.onDidChange(() => this._recomputeOptions()));
      this._register(PixelRatio.getInstance(getWindow(container)).onDidChange(() => this._recomputeOptions()));
      this._register(this._accessibilityService.onDidChangeScreenReaderOptimized(() => this._recomputeOptions()));
      this._register(InputMode.onDidChangeInputMode(() => this._recomputeOptions()));
    }
    _recomputeOptions() {
      const newOptions = this._computeOptions();
      const changeEvent = EditorOptionsUtil.checkEquals(this.options, newOptions);
      if (changeEvent === null) {
        return;
      }
      this.options = newOptions;
      this._onDidChangeFast.fire(changeEvent);
      this._onDidChange.fire(changeEvent);
    }
    _computeOptions() {
      const partialEnv = this._readEnvConfiguration();
      const bareFontInfo = createBareFontInfoFromValidatedSettings(this._validatedOptions, partialEnv.pixelRatio, this.isSimpleWidget);
      const fontInfo = this._readFontInfo(bareFontInfo);
      const env2 = {
        memory: this._computeOptionsMemory,
        outerWidth: partialEnv.outerWidth,
        outerHeight: partialEnv.outerHeight - this._reservedHeight,
        fontInfo,
        extraEditorClassName: partialEnv.extraEditorClassName,
        isDominatedByLongLines: this._isDominatedByLongLines,
        viewLineCount: this._viewLineCount,
        lineNumbersDigitCount: this._lineNumbersDigitCount,
        emptySelectionClipboard: partialEnv.emptySelectionClipboard,
        pixelRatio: partialEnv.pixelRatio,
        tabFocusMode: this._validatedOptions.get(
          164
          /* EditorOption.tabFocusMode */
        ) || TabFocus.getTabFocusMode(),
        inputMode: InputMode.getInputMode(),
        accessibilitySupport: partialEnv.accessibilitySupport,
        glyphMarginDecorationLaneCount: this._glyphMarginDecorationLaneCount,
        editContextSupported: partialEnv.editContextSupported
      };
      return EditorOptionsUtil.computeOptions(this._validatedOptions, env2);
    }
    _readEnvConfiguration() {
      return {
        extraEditorClassName: getExtraEditorClassName(),
        outerWidth: this._containerObserver.getWidth(),
        outerHeight: this._containerObserver.getHeight(),
        emptySelectionClipboard: isWebKit || isFirefox$1,
        pixelRatio: PixelRatio.getInstance(getWindowById(this._targetWindowId, true).window).value,
        // eslint-disable-next-line local/code-no-any-casts, @typescript-eslint/no-explicit-any
        editContextSupported: typeof globalThis.EditContext === "function",
        accessibilitySupport: this._accessibilityService.isScreenReaderOptimized() ? 2 : this._accessibilityService.getAccessibilitySupport()
      };
    }
    _readFontInfo(bareFontInfo) {
      return FontMeasurements.readFontInfo(getWindowById(this._targetWindowId, true).window, bareFontInfo);
    }
    getRawOptions() {
      return this._rawOptions;
    }
    updateOptions(_newOptions) {
      const newOptions = deepCloneAndMigrateOptions(_newOptions);
      const didChange = EditorOptionsUtil.applyUpdate(this._rawOptions, newOptions);
      if (!didChange) {
        return;
      }
      this._validatedOptions = EditorOptionsUtil.validateOptions(this._rawOptions);
      this._recomputeOptions();
    }
    observeContainer(dimension) {
      this._containerObserver.observe(dimension);
    }
    setIsDominatedByLongLines(isDominatedByLongLines) {
      if (this._isDominatedByLongLines === isDominatedByLongLines) {
        return;
      }
      this._isDominatedByLongLines = isDominatedByLongLines;
      this._recomputeOptions();
    }
    setModelLineCount(modelLineCount) {
      const lineNumbersDigitCount = digitCount(modelLineCount);
      if (this._lineNumbersDigitCount === lineNumbersDigitCount) {
        return;
      }
      this._lineNumbersDigitCount = lineNumbersDigitCount;
      this._recomputeOptions();
    }
    setViewLineCount(viewLineCount) {
      if (this._viewLineCount === viewLineCount) {
        return;
      }
      this._viewLineCount = viewLineCount;
      this._recomputeOptions();
    }
    setReservedHeight(reservedHeight) {
      if (this._reservedHeight === reservedHeight) {
        return;
      }
      this._reservedHeight = reservedHeight;
      this._recomputeOptions();
    }
    setGlyphMarginDecorationLaneCount(decorationLaneCount) {
      if (this._glyphMarginDecorationLaneCount === decorationLaneCount) {
        return;
      }
      this._glyphMarginDecorationLaneCount = decorationLaneCount;
      this._recomputeOptions();
    }
  };
  EditorConfiguration = __decorate$33([
    __param$2Y(4, IAccessibilityService)
  ], EditorConfiguration);
  function digitCount(n2) {
    let r = 0;
    while (n2) {
      n2 = Math.floor(n2 / 10);
      r++;
    }
    return r ? r : 1;
  }
  function getExtraEditorClassName() {
    let extra = "";
    if (isSafari$1 || isWebkitWebView) {
      extra += "no-minimap-shadow ";
      extra += "enable-user-select ";
    } else {
      extra += "no-user-select ";
    }
    if (isMacintosh) {
      extra += "mac ";
    }
    return extra;
  }
  class ValidatedEditorOptions {
    constructor() {
      this._values = [];
    }
    _read(option2) {
      return this._values[option2];
    }
    get(id) {
      return this._values[id];
    }
    _write(option2, value) {
      this._values[option2] = value;
    }
  }
  class ComputedEditorOptions {
    constructor() {
      this._values = [];
    }
    _read(id) {
      if (id >= this._values.length) {
        throw new Error("Cannot read uninitialized value");
      }
      return this._values[id];
    }
    get(id) {
      return this._read(id);
    }
    _write(id, value) {
      this._values[id] = value;
    }
  }
  class EditorOptionsUtil {
    static validateOptions(options) {
      const result = new ValidatedEditorOptions();
      for (const editorOption of editorOptionsRegistry) {
        const value = editorOption.name === "_never_" ? void 0 : options[editorOption.name];
        result._write(editorOption.id, editorOption.validate(value));
      }
      return result;
    }
    static computeOptions(options, env2) {
      const result = new ComputedEditorOptions();
      for (const editorOption of editorOptionsRegistry) {
        result._write(editorOption.id, editorOption.compute(env2, result, options._read(editorOption.id)));
      }
      return result;
    }
    static _deepEquals(a, b) {
      if (typeof a !== "object" || typeof b !== "object" || !a || !b) {
        return a === b;
      }
      if (Array.isArray(a) || Array.isArray(b)) {
        return Array.isArray(a) && Array.isArray(b) ? equals$1(a, b) : false;
      }
      if (Object.keys(a).length !== Object.keys(b).length) {
        return false;
      }
      for (const key in a) {
        if (!EditorOptionsUtil._deepEquals(a[key], b[key])) {
          return false;
        }
      }
      return true;
    }
    static checkEquals(a, b) {
      const result = [];
      let somethingChanged = false;
      for (const editorOption of editorOptionsRegistry) {
        const changed = !EditorOptionsUtil._deepEquals(a._read(editorOption.id), b._read(editorOption.id));
        result[editorOption.id] = changed;
        if (changed) {
          somethingChanged = true;
        }
      }
      return somethingChanged ? new ConfigurationChangedEvent(result) : null;
    }
    /**
     * Returns true if something changed.
     * Modifies `options`.
    */
    static applyUpdate(options, update) {
      let changed = false;
      for (const editorOption of editorOptionsRegistry) {
        if (update.hasOwnProperty(editorOption.name)) {
          const result = editorOption.applyUpdate(options[editorOption.name], update[editorOption.name]);
          options[editorOption.name] = result.newValue;
          changed = changed || result.didChange;
        }
      }
      return changed;
    }
  }
  function deepCloneAndMigrateOptions(_options) {
    const options = deepClone(_options);
    migrateOptions(options);
    return options;
  }
  var inputLatency;
  (function(inputLatency2) {
    const totalKeydownTime = { total: 0, min: Number.MAX_VALUE, max: 0 };
    const totalInputTime = { ...totalKeydownTime };
    const totalRenderTime = { ...totalKeydownTime };
    const totalInputLatencyTime = { ...totalKeydownTime };
    let measurementsCount = 0;
    const state = {
      keydown: 0,
      input: 0,
      render: 0
    };
    function onKeyDown() {
      recordIfFinished();
      performance.mark("inputlatency/start");
      performance.mark("keydown/start");
      state.keydown = 1;
      queueMicrotask(markKeyDownEnd);
    }
    inputLatency2.onKeyDown = onKeyDown;
    function markKeyDownEnd() {
      if (state.keydown === 1) {
        performance.mark("keydown/end");
        state.keydown = 2;
      }
    }
    function onBeforeInput() {
      performance.mark("input/start");
      state.input = 1;
      scheduleRecordIfFinishedTask();
    }
    inputLatency2.onBeforeInput = onBeforeInput;
    function onInput() {
      if (state.input === 0) {
        onBeforeInput();
      }
      queueMicrotask(markInputEnd);
    }
    inputLatency2.onInput = onInput;
    function markInputEnd() {
      if (state.input === 1) {
        performance.mark("input/end");
        state.input = 2;
      }
    }
    function onKeyUp() {
      recordIfFinished();
    }
    inputLatency2.onKeyUp = onKeyUp;
    function onSelectionChange() {
      recordIfFinished();
    }
    inputLatency2.onSelectionChange = onSelectionChange;
    function onRenderStart() {
      if (state.keydown === 2 && state.input === 2 && state.render === 0) {
        performance.mark("render/start");
        state.render = 1;
        queueMicrotask(markRenderEnd);
        scheduleRecordIfFinishedTask();
      }
    }
    inputLatency2.onRenderStart = onRenderStart;
    function markRenderEnd() {
      if (state.render === 1) {
        performance.mark("render/end");
        state.render = 2;
      }
    }
    function scheduleRecordIfFinishedTask() {
      setTimeout(recordIfFinished);
    }
    function recordIfFinished() {
      if (state.keydown === 2 && state.input === 2 && state.render === 2) {
        performance.mark("inputlatency/end");
        performance.measure("keydown", "keydown/start", "keydown/end");
        performance.measure("input", "input/start", "input/end");
        performance.measure("render", "render/start", "render/end");
        performance.measure("inputlatency", "inputlatency/start", "inputlatency/end");
        addMeasure("keydown", totalKeydownTime);
        addMeasure("input", totalInputTime);
        addMeasure("render", totalRenderTime);
        addMeasure("inputlatency", totalInputLatencyTime);
        measurementsCount++;
        reset2();
      }
    }
    function addMeasure(entryName, cumulativeMeasurement) {
      const duration = performance.getEntriesByName(entryName)[0].duration;
      cumulativeMeasurement.total += duration;
      cumulativeMeasurement.min = Math.min(cumulativeMeasurement.min, duration);
      cumulativeMeasurement.max = Math.max(cumulativeMeasurement.max, duration);
    }
    function reset2() {
      performance.clearMarks("keydown/start");
      performance.clearMarks("keydown/end");
      performance.clearMarks("input/start");
      performance.clearMarks("input/end");
      performance.clearMarks("render/start");
      performance.clearMarks("render/end");
      performance.clearMarks("inputlatency/start");
      performance.clearMarks("inputlatency/end");
      performance.clearMeasures("keydown");
      performance.clearMeasures("input");
      performance.clearMeasures("render");
      performance.clearMeasures("inputlatency");
      state.keydown = 0;
      state.input = 0;
      state.render = 0;
    }
    function getAndClearMeasurements() {
      if (measurementsCount === 0) {
        return void 0;
      }
      const result = {
        keydown: cumulativeToFinalMeasurement(totalKeydownTime),
        input: cumulativeToFinalMeasurement(totalInputTime),
        render: cumulativeToFinalMeasurement(totalRenderTime),
        total: cumulativeToFinalMeasurement(totalInputLatencyTime),
        sampleCount: measurementsCount
      };
      clearCumulativeMeasurement(totalKeydownTime);
      clearCumulativeMeasurement(totalInputTime);
      clearCumulativeMeasurement(totalRenderTime);
      clearCumulativeMeasurement(totalInputLatencyTime);
      measurementsCount = 0;
      return result;
    }
    inputLatency2.getAndClearMeasurements = getAndClearMeasurements;
    function cumulativeToFinalMeasurement(cumulative) {
      return {
        average: cumulative.total / measurementsCount,
        max: cumulative.max,
        min: cumulative.min
      };
    }
    function clearCumulativeMeasurement(cumulative) {
      cumulative.total = 0;
      cumulative.min = Number.MAX_VALUE;
      cumulative.max = 0;
    }
  })(inputLatency || (inputLatency = {}));
  const globalStylesheets = /* @__PURE__ */ new Map();
  function createStyleSheet2() {
    return new WrappedStyleElement();
  }
  class WrappedStyleElement {
    constructor() {
      this._currentCssStyle = "";
      this._styleSheet = void 0;
    }
    setStyle(cssStyle) {
      if (cssStyle === this._currentCssStyle) {
        return;
      }
      this._currentCssStyle = cssStyle;
      if (!this._styleSheet) {
        this._styleSheet = createStyleSheet(mainWindow.document.head, (s) => s.textContent = cssStyle);
      } else {
        this._styleSheet.textContent = cssStyle;
      }
    }
    dispose() {
      if (this._styleSheet) {
        this._styleSheet.remove();
        this._styleSheet = void 0;
      }
    }
  }
  function createStyleSheet(container = mainWindow.document.head, beforeAppend, disposableStore) {
    const style = document.createElement("style");
    style.type = "text/css";
    style.media = "screen";
    beforeAppend?.(style);
    container.appendChild(style);
    if (disposableStore) {
      disposableStore.add(toDisposable(() => style.remove()));
    }
    if (container === mainWindow.document.head) {
      const globalStylesheetClones = /* @__PURE__ */ new Set();
      globalStylesheets.set(style, globalStylesheetClones);
      if (disposableStore) {
        disposableStore.add(toDisposable(() => globalStylesheets.delete(style)));
      }
      for (const { window: targetWindow, disposables } of getWindows()) {
        if (targetWindow === mainWindow) {
          continue;
        }
        const cloneDisposable = disposables.add(cloneGlobalStyleSheet(style, globalStylesheetClones, targetWindow));
        disposableStore?.add(cloneDisposable);
      }
    }
    return style;
  }
  function cloneGlobalStyleSheet(globalStylesheet, globalStylesheetClones, targetWindow) {
    const disposables = new DisposableStore();
    const clone2 = globalStylesheet.cloneNode(true);
    targetWindow.document.head.appendChild(clone2);
    disposables.add(toDisposable(() => clone2.remove()));
    for (const rule of getDynamicStyleSheetRules(globalStylesheet)) {
      clone2.sheet?.insertRule(rule.cssText, clone2.sheet?.cssRules.length);
    }
    disposables.add(sharedMutationObserver.observe(globalStylesheet, disposables, { childList: true, subtree: isFirefox$1, characterData: isFirefox$1 })(() => {
      clone2.textContent = globalStylesheet.textContent;
    }));
    globalStylesheetClones.add(clone2);
    disposables.add(toDisposable(() => globalStylesheetClones.delete(clone2)));
    return disposables;
  }
  let _sharedStyleSheet = null;
  function getSharedStyleSheet() {
    if (!_sharedStyleSheet) {
      _sharedStyleSheet = createStyleSheet();
    }
    return _sharedStyleSheet;
  }
  function getDynamicStyleSheetRules(style) {
    if (style?.sheet?.rules) {
      return style.sheet.rules;
    }
    if (style?.sheet?.cssRules) {
      return style.sheet.cssRules;
    }
    return [];
  }
  function createCSSRule(selector, cssText, style = getSharedStyleSheet()) {
    if (!style || !cssText) {
      return;
    }
    style.sheet?.insertRule(`${selector} {${cssText}}`, 0);
    for (const clonedGlobalStylesheet of globalStylesheets.get(style) ?? []) {
      createCSSRule(selector, cssText, clonedGlobalStylesheet);
    }
  }
  function removeCSSRulesContainingSelector(ruleName, style = getSharedStyleSheet()) {
    if (!style) {
      return;
    }
    const rules = getDynamicStyleSheetRules(style);
    const toDelete = [];
    for (let i2 = 0; i2 < rules.length; i2++) {
      const rule = rules[i2];
      if (isCSSStyleRule(rule) && rule.selectorText.indexOf(ruleName) !== -1) {
        toDelete.push(i2);
      }
    }
    for (let i2 = toDelete.length - 1; i2 >= 0; i2--) {
      style.sheet?.deleteRule(toDelete[i2]);
    }
    for (const clonedGlobalStylesheet of globalStylesheets.get(style) ?? []) {
      removeCSSRulesContainingSelector(ruleName, clonedGlobalStylesheet);
    }
  }
  function isCSSStyleRule(rule) {
    return typeof rule.selectorText === "string";
  }
  function createStyleSheetFromObservable(css) {
    const store = new DisposableStore();
    const w = store.add(createStyleSheet2());
    store.add(autorun((reader) => {
      w.setStyle(css.read(reader));
    }));
    return store;
  }
  class GlobalPointerMoveMonitor {
    constructor() {
      this._hooks = new DisposableStore();
      this._pointerMoveCallback = null;
      this._onStopCallback = null;
    }
    dispose() {
      this.stopMonitoring(false);
      this._hooks.dispose();
    }
    stopMonitoring(invokeStopCallback, browserEvent) {
      if (!this.isMonitoring()) {
        return;
      }
      this._hooks.clear();
      this._pointerMoveCallback = null;
      const onStopCallback = this._onStopCallback;
      this._onStopCallback = null;
      if (invokeStopCallback && onStopCallback) {
        onStopCallback(browserEvent);
      }
    }
    isMonitoring() {
      return !!this._pointerMoveCallback;
    }
    startMonitoring(initialElement, pointerId, initialButtons, pointerMoveCallback, onStopCallback) {
      if (this.isMonitoring()) {
        this.stopMonitoring(false);
      }
      this._pointerMoveCallback = pointerMoveCallback;
      this._onStopCallback = onStopCallback;
      let eventSource = initialElement;
      try {
        initialElement.setPointerCapture(pointerId);
        this._hooks.add(toDisposable(() => {
          try {
            initialElement.releasePointerCapture(pointerId);
          } catch (err) {
          }
        }));
      } catch (err) {
        eventSource = getWindow(initialElement);
      }
      this._hooks.add(addDisposableListener(eventSource, EventType$1.POINTER_MOVE, (e) => {
        if (e.buttons !== initialButtons) {
          this.stopMonitoring(true);
          return;
        }
        e.preventDefault();
        this._pointerMoveCallback(e);
      }));
      this._hooks.add(addDisposableListener(eventSource, EventType$1.POINTER_UP, (e) => this.stopMonitoring(true)));
    }
  }
  function roundFloat(number, decimalPoints) {
    const decimal = Math.pow(10, decimalPoints);
    return Math.round(number * decimal) / decimal;
  }
  class RGBA {
    constructor(r, g, b, a = 1) {
      this._rgbaBrand = void 0;
      this.r = Math.min(255, Math.max(0, r)) | 0;
      this.g = Math.min(255, Math.max(0, g)) | 0;
      this.b = Math.min(255, Math.max(0, b)) | 0;
      this.a = roundFloat(Math.max(Math.min(1, a), 0), 3);
    }
    static equals(a, b) {
      return a.r === b.r && a.g === b.g && a.b === b.b && a.a === b.a;
    }
  }
  class HSLA {
    constructor(h2, s, l, a) {
      this._hslaBrand = void 0;
      this.h = Math.max(Math.min(360, h2), 0) | 0;
      this.s = roundFloat(Math.max(Math.min(1, s), 0), 3);
      this.l = roundFloat(Math.max(Math.min(1, l), 0), 3);
      this.a = roundFloat(Math.max(Math.min(1, a), 0), 3);
    }
    static equals(a, b) {
      return a.h === b.h && a.s === b.s && a.l === b.l && a.a === b.a;
    }
    /**
     * Converts an RGB color value to HSL. Conversion formula
     * adapted from http://en.wikipedia.org/wiki/HSL_color_space.
     * Assumes r, g, and b are contained in the set [0, 255] and
     * returns h in the set [0, 360], s, and l in the set [0, 1].
     */
    static fromRGBA(rgba) {
      const r = rgba.r / 255;
      const g = rgba.g / 255;
      const b = rgba.b / 255;
      const a = rgba.a;
      const max = Math.max(r, g, b);
      const min = Math.min(r, g, b);
      let h2 = 0;
      let s = 0;
      const l = (min + max) / 2;
      const chroma = max - min;
      if (chroma > 0) {
        s = Math.min(l <= 0.5 ? chroma / (2 * l) : chroma / (2 - 2 * l), 1);
        switch (max) {
          case r:
            h2 = (g - b) / chroma + (g < b ? 6 : 0);
            break;
          case g:
            h2 = (b - r) / chroma + 2;
            break;
          case b:
            h2 = (r - g) / chroma + 4;
            break;
        }
        h2 *= 60;
        h2 = Math.round(h2);
      }
      return new HSLA(h2, s, l, a);
    }
    static _hue2rgb(p, q, t) {
      if (t < 0) {
        t += 1;
      }
      if (t > 1) {
        t -= 1;
      }
      if (t < 1 / 6) {
        return p + (q - p) * 6 * t;
      }
      if (t < 1 / 2) {
        return q;
      }
      if (t < 2 / 3) {
        return p + (q - p) * (2 / 3 - t) * 6;
      }
      return p;
    }
    /**
     * Converts an HSL color value to RGB. Conversion formula
     * adapted from http://en.wikipedia.org/wiki/HSL_color_space.
     * Assumes h in the set [0, 360] s, and l are contained in the set [0, 1] and
     * returns r, g, and b in the set [0, 255].
     */
    static toRGBA(hsla) {
      const h2 = hsla.h / 360;
      const { s, l, a } = hsla;
      let r, g, b;
      if (s === 0) {
        r = g = b = l;
      } else {
        const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
        const p = 2 * l - q;
        r = HSLA._hue2rgb(p, q, h2 + 1 / 3);
        g = HSLA._hue2rgb(p, q, h2);
        b = HSLA._hue2rgb(p, q, h2 - 1 / 3);
      }
      return new RGBA(Math.round(r * 255), Math.round(g * 255), Math.round(b * 255), a);
    }
  }
  class HSVA {
    constructor(h2, s, v, a) {
      this._hsvaBrand = void 0;
      this.h = Math.max(Math.min(360, h2), 0) | 0;
      this.s = roundFloat(Math.max(Math.min(1, s), 0), 3);
      this.v = roundFloat(Math.max(Math.min(1, v), 0), 3);
      this.a = roundFloat(Math.max(Math.min(1, a), 0), 3);
    }
    static equals(a, b) {
      return a.h === b.h && a.s === b.s && a.v === b.v && a.a === b.a;
    }
    // from http://www.rapidtables.com/convert/color/rgb-to-hsv.htm
    static fromRGBA(rgba) {
      const r = rgba.r / 255;
      const g = rgba.g / 255;
      const b = rgba.b / 255;
      const cmax = Math.max(r, g, b);
      const cmin = Math.min(r, g, b);
      const delta = cmax - cmin;
      const s = cmax === 0 ? 0 : delta / cmax;
      let m;
      if (delta === 0) {
        m = 0;
      } else if (cmax === r) {
        m = ((g - b) / delta % 6 + 6) % 6;
      } else if (cmax === g) {
        m = (b - r) / delta + 2;
      } else {
        m = (r - g) / delta + 4;
      }
      return new HSVA(Math.round(m * 60), s, cmax, rgba.a);
    }
    // from http://www.rapidtables.com/convert/color/hsv-to-rgb.htm
    static toRGBA(hsva) {
      const { h: h2, s, v, a } = hsva;
      const c = v * s;
      const x = c * (1 - Math.abs(h2 / 60 % 2 - 1));
      const m = v - c;
      let [r, g, b] = [0, 0, 0];
      if (h2 < 60) {
        r = c;
        g = x;
      } else if (h2 < 120) {
        r = x;
        g = c;
      } else if (h2 < 180) {
        g = c;
        b = x;
      } else if (h2 < 240) {
        g = x;
        b = c;
      } else if (h2 < 300) {
        r = x;
        b = c;
      } else if (h2 <= 360) {
        r = c;
        b = x;
      }
      r = Math.round((r + m) * 255);
      g = Math.round((g + m) * 255);
      b = Math.round((b + m) * 255);
      return new RGBA(r, g, b, a);
    }
  }
  const _Color = class _Color {
    static fromHex(hex) {
      return _Color.Format.CSS.parseHex(hex) || _Color.red;
    }
    static equals(a, b) {
      if (!a && !b) {
        return true;
      }
      if (!a || !b) {
        return false;
      }
      return a.equals(b);
    }
    get hsla() {
      if (this._hsla) {
        return this._hsla;
      } else {
        return HSLA.fromRGBA(this.rgba);
      }
    }
    get hsva() {
      if (this._hsva) {
        return this._hsva;
      }
      return HSVA.fromRGBA(this.rgba);
    }
    constructor(arg) {
      if (!arg) {
        throw new Error("Color needs a value");
      } else if (arg instanceof RGBA) {
        this.rgba = arg;
      } else if (arg instanceof HSLA) {
        this._hsla = arg;
        this.rgba = HSLA.toRGBA(arg);
      } else if (arg instanceof HSVA) {
        this._hsva = arg;
        this.rgba = HSVA.toRGBA(arg);
      } else {
        throw new Error("Invalid color ctor argument");
      }
    }
    equals(other) {
      return !!other && RGBA.equals(this.rgba, other.rgba) && HSLA.equals(this.hsla, other.hsla) && HSVA.equals(this.hsva, other.hsva);
    }
    /**
     * http://www.w3.org/TR/WCAG20/#relativeluminancedef
     * Returns the number in the set [0, 1]. O => Darkest Black. 1 => Lightest white.
     */
    getRelativeLuminance() {
      const R = _Color._relativeLuminanceForComponent(this.rgba.r);
      const G = _Color._relativeLuminanceForComponent(this.rgba.g);
      const B = _Color._relativeLuminanceForComponent(this.rgba.b);
      const luminance = 0.2126 * R + 0.7152 * G + 0.0722 * B;
      return roundFloat(luminance, 4);
    }
    static _relativeLuminanceForComponent(color) {
      const c = color / 255;
      return c <= 0.03928 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4);
    }
    /**
     *	http://24ways.org/2010/calculating-color-contrast
     *  Return 'true' if lighter color otherwise 'false'
     */
    isLighter() {
      const yiq = (this.rgba.r * 299 + this.rgba.g * 587 + this.rgba.b * 114) / 1e3;
      return yiq >= 128;
    }
    isLighterThan(another) {
      const lum1 = this.getRelativeLuminance();
      const lum2 = another.getRelativeLuminance();
      return lum1 > lum2;
    }
    isDarkerThan(another) {
      const lum1 = this.getRelativeLuminance();
      const lum2 = another.getRelativeLuminance();
      return lum1 < lum2;
    }
    lighten(factor2) {
      return new _Color(new HSLA(this.hsla.h, this.hsla.s, this.hsla.l + this.hsla.l * factor2, this.hsla.a));
    }
    darken(factor2) {
      return new _Color(new HSLA(this.hsla.h, this.hsla.s, this.hsla.l - this.hsla.l * factor2, this.hsla.a));
    }
    transparent(factor2) {
      const { r, g, b, a } = this.rgba;
      return new _Color(new RGBA(r, g, b, a * factor2));
    }
    isTransparent() {
      return this.rgba.a === 0;
    }
    isOpaque() {
      return this.rgba.a === 1;
    }
    opposite() {
      return new _Color(new RGBA(255 - this.rgba.r, 255 - this.rgba.g, 255 - this.rgba.b, this.rgba.a));
    }
    /**
     * Mixes the current color with the provided color based on the given factor.
     * @param color The color to mix with
     * @param factor The factor of mixing (0 means this color, 1 means the input color, 0.5 means equal mix)
     * @returns A new color representing the mix
     */
    mix(color, factor2 = 0.5) {
      const normalize2 = Math.min(Math.max(factor2, 0), 1);
      const thisRGBA = this.rgba;
      const otherRGBA = color.rgba;
      const r = thisRGBA.r + (otherRGBA.r - thisRGBA.r) * normalize2;
      const g = thisRGBA.g + (otherRGBA.g - thisRGBA.g) * normalize2;
      const b = thisRGBA.b + (otherRGBA.b - thisRGBA.b) * normalize2;
      const a = thisRGBA.a + (otherRGBA.a - thisRGBA.a) * normalize2;
      return new _Color(new RGBA(r, g, b, a));
    }
    makeOpaque(opaqueBackground) {
      if (this.isOpaque() || opaqueBackground.rgba.a !== 1) {
        return this;
      }
      const { r, g, b, a } = this.rgba;
      return new _Color(new RGBA(opaqueBackground.rgba.r - a * (opaqueBackground.rgba.r - r), opaqueBackground.rgba.g - a * (opaqueBackground.rgba.g - g), opaqueBackground.rgba.b - a * (opaqueBackground.rgba.b - b), 1));
    }
    toString() {
      if (!this._toString) {
        this._toString = _Color.Format.CSS.format(this);
      }
      return this._toString;
    }
    toNumber32Bit() {
      if (!this._toNumber32Bit) {
        this._toNumber32Bit = (this.rgba.r << 24 | this.rgba.g << 16 | this.rgba.b << 8 | this.rgba.a * 255 << 0) >>> 0;
      }
      return this._toNumber32Bit;
    }
    static getLighterColor(of, relative2, factor2) {
      if (of.isLighterThan(relative2)) {
        return of;
      }
      factor2 = factor2 ? factor2 : 0.5;
      const lum1 = of.getRelativeLuminance();
      const lum2 = relative2.getRelativeLuminance();
      factor2 = factor2 * (lum2 - lum1) / lum2;
      return of.lighten(factor2);
    }
    static getDarkerColor(of, relative2, factor2) {
      if (of.isDarkerThan(relative2)) {
        return of;
      }
      factor2 = factor2 ? factor2 : 0.5;
      const lum1 = of.getRelativeLuminance();
      const lum2 = relative2.getRelativeLuminance();
      factor2 = factor2 * (lum1 - lum2) / lum1;
      return of.darken(factor2);
    }
  };
  _Color.white = new _Color(new RGBA(255, 255, 255, 1));
  _Color.black = new _Color(new RGBA(0, 0, 0, 1));
  _Color.red = new _Color(new RGBA(255, 0, 0, 1));
  _Color.blue = new _Color(new RGBA(0, 0, 255, 1));
  _Color.green = new _Color(new RGBA(0, 255, 0, 1));
  _Color.cyan = new _Color(new RGBA(0, 255, 255, 1));
  _Color.lightgrey = new _Color(new RGBA(211, 211, 211, 1));
  _Color.transparent = new _Color(new RGBA(0, 0, 0, 0));
  let Color = _Color;
  (function(Color2) {
    (function(Format) {
      (function(CSS2) {
        function formatRGB(color) {
          if (color.rgba.a === 1) {
            return `rgb(${color.rgba.r}, ${color.rgba.g}, ${color.rgba.b})`;
          }
          return Color2.Format.CSS.formatRGBA(color);
        }
        CSS2.formatRGB = formatRGB;
        function formatRGBA(color) {
          return `rgba(${color.rgba.r}, ${color.rgba.g}, ${color.rgba.b}, ${+color.rgba.a.toFixed(2)})`;
        }
        CSS2.formatRGBA = formatRGBA;
        function formatHSL(color) {
          if (color.hsla.a === 1) {
            return `hsl(${color.hsla.h}, ${Math.round(color.hsla.s * 100)}%, ${Math.round(color.hsla.l * 100)}%)`;
          }
          return Color2.Format.CSS.formatHSLA(color);
        }
        CSS2.formatHSL = formatHSL;
        function formatHSLA(color) {
          return `hsla(${color.hsla.h}, ${Math.round(color.hsla.s * 100)}%, ${Math.round(color.hsla.l * 100)}%, ${color.hsla.a.toFixed(2)})`;
        }
        CSS2.formatHSLA = formatHSLA;
        function _toTwoDigitHex(n2) {
          const r = n2.toString(16);
          return r.length !== 2 ? "0" + r : r;
        }
        function formatHex(color) {
          return `#${_toTwoDigitHex(color.rgba.r)}${_toTwoDigitHex(color.rgba.g)}${_toTwoDigitHex(color.rgba.b)}`;
        }
        CSS2.formatHex = formatHex;
        function formatHexA(color, compact = false) {
          if (compact && color.rgba.a === 1) {
            return Color2.Format.CSS.formatHex(color);
          }
          return `#${_toTwoDigitHex(color.rgba.r)}${_toTwoDigitHex(color.rgba.g)}${_toTwoDigitHex(color.rgba.b)}${_toTwoDigitHex(Math.round(color.rgba.a * 255))}`;
        }
        CSS2.formatHexA = formatHexA;
        function format2(color) {
          if (color.isOpaque()) {
            return Color2.Format.CSS.formatHex(color);
          }
          return Color2.Format.CSS.formatRGBA(color);
        }
        CSS2.format = format2;
        function parse2(css) {
          if (css === "transparent") {
            return Color2.transparent;
          }
          if (css.startsWith("#")) {
            return parseHex(css);
          }
          if (css.startsWith("rgba(")) {
            const color = css.match(/rgba\((?<r>(?:\+|-)?\d+), *(?<g>(?:\+|-)?\d+), *(?<b>(?:\+|-)?\d+), *(?<a>(?:\+|-)?\d+(\.\d+)?)\)/);
            if (!color) {
              throw new Error("Invalid color format " + css);
            }
            const r = parseInt(color.groups?.r ?? "0");
            const g = parseInt(color.groups?.g ?? "0");
            const b = parseInt(color.groups?.b ?? "0");
            const a = parseFloat(color.groups?.a ?? "0");
            return new Color2(new RGBA(r, g, b, a));
          }
          if (css.startsWith("rgb(")) {
            const color = css.match(/rgb\((?<r>(?:\+|-)?\d+), *(?<g>(?:\+|-)?\d+), *(?<b>(?:\+|-)?\d+)\)/);
            if (!color) {
              throw new Error("Invalid color format " + css);
            }
            const r = parseInt(color.groups?.r ?? "0");
            const g = parseInt(color.groups?.g ?? "0");
            const b = parseInt(color.groups?.b ?? "0");
            return new Color2(new RGBA(r, g, b));
          }
          return parseNamedKeyword(css);
        }
        CSS2.parse = parse2;
        function parseNamedKeyword(css) {
          switch (css) {
            case "aliceblue":
              return new Color2(new RGBA(240, 248, 255, 1));
            case "antiquewhite":
              return new Color2(new RGBA(250, 235, 215, 1));
            case "aqua":
              return new Color2(new RGBA(0, 255, 255, 1));
            case "aquamarine":
              return new Color2(new RGBA(127, 255, 212, 1));
            case "azure":
              return new Color2(new RGBA(240, 255, 255, 1));
            case "beige":
              return new Color2(new RGBA(245, 245, 220, 1));
            case "bisque":
              return new Color2(new RGBA(255, 228, 196, 1));
            case "black":
              return new Color2(new RGBA(0, 0, 0, 1));
            case "blanchedalmond":
              return new Color2(new RGBA(255, 235, 205, 1));
            case "blue":
              return new Color2(new RGBA(0, 0, 255, 1));
            case "blueviolet":
              return new Color2(new RGBA(138, 43, 226, 1));
            case "brown":
              return new Color2(new RGBA(165, 42, 42, 1));
            case "burlywood":
              return new Color2(new RGBA(222, 184, 135, 1));
            case "cadetblue":
              return new Color2(new RGBA(95, 158, 160, 1));
            case "chartreuse":
              return new Color2(new RGBA(127, 255, 0, 1));
            case "chocolate":
              return new Color2(new RGBA(210, 105, 30, 1));
            case "coral":
              return new Color2(new RGBA(255, 127, 80, 1));
            case "cornflowerblue":
              return new Color2(new RGBA(100, 149, 237, 1));
            case "cornsilk":
              return new Color2(new RGBA(255, 248, 220, 1));
            case "crimson":
              return new Color2(new RGBA(220, 20, 60, 1));
            case "cyan":
              return new Color2(new RGBA(0, 255, 255, 1));
            case "darkblue":
              return new Color2(new RGBA(0, 0, 139, 1));
            case "darkcyan":
              return new Color2(new RGBA(0, 139, 139, 1));
            case "darkgoldenrod":
              return new Color2(new RGBA(184, 134, 11, 1));
            case "darkgray":
              return new Color2(new RGBA(169, 169, 169, 1));
            case "darkgreen":
              return new Color2(new RGBA(0, 100, 0, 1));
            case "darkgrey":
              return new Color2(new RGBA(169, 169, 169, 1));
            case "darkkhaki":
              return new Color2(new RGBA(189, 183, 107, 1));
            case "darkmagenta":
              return new Color2(new RGBA(139, 0, 139, 1));
            case "darkolivegreen":
              return new Color2(new RGBA(85, 107, 47, 1));
            case "darkorange":
              return new Color2(new RGBA(255, 140, 0, 1));
            case "darkorchid":
              return new Color2(new RGBA(153, 50, 204, 1));
            case "darkred":
              return new Color2(new RGBA(139, 0, 0, 1));
            case "darksalmon":
              return new Color2(new RGBA(233, 150, 122, 1));
            case "darkseagreen":
              return new Color2(new RGBA(143, 188, 143, 1));
            case "darkslateblue":
              return new Color2(new RGBA(72, 61, 139, 1));
            case "darkslategray":
              return new Color2(new RGBA(47, 79, 79, 1));
            case "darkslategrey":
              return new Color2(new RGBA(47, 79, 79, 1));
            case "darkturquoise":
              return new Color2(new RGBA(0, 206, 209, 1));
            case "darkviolet":
              return new Color2(new RGBA(148, 0, 211, 1));
            case "deeppink":
              return new Color2(new RGBA(255, 20, 147, 1));
            case "deepskyblue":
              return new Color2(new RGBA(0, 191, 255, 1));
            case "dimgray":
              return new Color2(new RGBA(105, 105, 105, 1));
            case "dimgrey":
              return new Color2(new RGBA(105, 105, 105, 1));
            case "dodgerblue":
              return new Color2(new RGBA(30, 144, 255, 1));
            case "firebrick":
              return new Color2(new RGBA(178, 34, 34, 1));
            case "floralwhite":
              return new Color2(new RGBA(255, 250, 240, 1));
            case "forestgreen":
              return new Color2(new RGBA(34, 139, 34, 1));
            case "fuchsia":
              return new Color2(new RGBA(255, 0, 255, 1));
            case "gainsboro":
              return new Color2(new RGBA(220, 220, 220, 1));
            case "ghostwhite":
              return new Color2(new RGBA(248, 248, 255, 1));
            case "gold":
              return new Color2(new RGBA(255, 215, 0, 1));
            case "goldenrod":
              return new Color2(new RGBA(218, 165, 32, 1));
            case "gray":
              return new Color2(new RGBA(128, 128, 128, 1));
            case "green":
              return new Color2(new RGBA(0, 128, 0, 1));
            case "greenyellow":
              return new Color2(new RGBA(173, 255, 47, 1));
            case "grey":
              return new Color2(new RGBA(128, 128, 128, 1));
            case "honeydew":
              return new Color2(new RGBA(240, 255, 240, 1));
            case "hotpink":
              return new Color2(new RGBA(255, 105, 180, 1));
            case "indianred":
              return new Color2(new RGBA(205, 92, 92, 1));
            case "indigo":
              return new Color2(new RGBA(75, 0, 130, 1));
            case "ivory":
              return new Color2(new RGBA(255, 255, 240, 1));
            case "khaki":
              return new Color2(new RGBA(240, 230, 140, 1));
            case "lavender":
              return new Color2(new RGBA(230, 230, 250, 1));
            case "lavenderblush":
              return new Color2(new RGBA(255, 240, 245, 1));
            case "lawngreen":
              return new Color2(new RGBA(124, 252, 0, 1));
            case "lemonchiffon":
              return new Color2(new RGBA(255, 250, 205, 1));
            case "lightblue":
              return new Color2(new RGBA(173, 216, 230, 1));
            case "lightcoral":
              return new Color2(new RGBA(240, 128, 128, 1));
            case "lightcyan":
              return new Color2(new RGBA(224, 255, 255, 1));
            case "lightgoldenrodyellow":
              return new Color2(new RGBA(250, 250, 210, 1));
            case "lightgray":
              return new Color2(new RGBA(211, 211, 211, 1));
            case "lightgreen":
              return new Color2(new RGBA(144, 238, 144, 1));
            case "lightgrey":
              return new Color2(new RGBA(211, 211, 211, 1));
            case "lightpink":
              return new Color2(new RGBA(255, 182, 193, 1));
            case "lightsalmon":
              return new Color2(new RGBA(255, 160, 122, 1));
            case "lightseagreen":
              return new Color2(new RGBA(32, 178, 170, 1));
            case "lightskyblue":
              return new Color2(new RGBA(135, 206, 250, 1));
            case "lightslategray":
              return new Color2(new RGBA(119, 136, 153, 1));
            case "lightslategrey":
              return new Color2(new RGBA(119, 136, 153, 1));
            case "lightsteelblue":
              return new Color2(new RGBA(176, 196, 222, 1));
            case "lightyellow":
              return new Color2(new RGBA(255, 255, 224, 1));
            case "lime":
              return new Color2(new RGBA(0, 255, 0, 1));
            case "limegreen":
              return new Color2(new RGBA(50, 205, 50, 1));
            case "linen":
              return new Color2(new RGBA(250, 240, 230, 1));
            case "magenta":
              return new Color2(new RGBA(255, 0, 255, 1));
            case "maroon":
              return new Color2(new RGBA(128, 0, 0, 1));
            case "mediumaquamarine":
              return new Color2(new RGBA(102, 205, 170, 1));
            case "mediumblue":
              return new Color2(new RGBA(0, 0, 205, 1));
            case "mediumorchid":
              return new Color2(new RGBA(186, 85, 211, 1));
            case "mediumpurple":
              return new Color2(new RGBA(147, 112, 219, 1));
            case "mediumseagreen":
              return new Color2(new RGBA(60, 179, 113, 1));
            case "mediumslateblue":
              return new Color2(new RGBA(123, 104, 238, 1));
            case "mediumspringgreen":
              return new Color2(new RGBA(0, 250, 154, 1));
            case "mediumturquoise":
              return new Color2(new RGBA(72, 209, 204, 1));
            case "mediumvioletred":
              return new Color2(new RGBA(199, 21, 133, 1));
            case "midnightblue":
              return new Color2(new RGBA(25, 25, 112, 1));
            case "mintcream":
              return new Color2(new RGBA(245, 255, 250, 1));
            case "mistyrose":
              return new Color2(new RGBA(255, 228, 225, 1));
            case "moccasin":
              return new Color2(new RGBA(255, 228, 181, 1));
            case "navajowhite":
              return new Color2(new RGBA(255, 222, 173, 1));
            case "navy":
              return new Color2(new RGBA(0, 0, 128, 1));
            case "oldlace":
              return new Color2(new RGBA(253, 245, 230, 1));
            case "olive":
              return new Color2(new RGBA(128, 128, 0, 1));
            case "olivedrab":
              return new Color2(new RGBA(107, 142, 35, 1));
            case "orange":
              return new Color2(new RGBA(255, 165, 0, 1));
            case "orangered":
              return new Color2(new RGBA(255, 69, 0, 1));
            case "orchid":
              return new Color2(new RGBA(218, 112, 214, 1));
            case "palegoldenrod":
              return new Color2(new RGBA(238, 232, 170, 1));
            case "palegreen":
              return new Color2(new RGBA(152, 251, 152, 1));
            case "paleturquoise":
              return new Color2(new RGBA(175, 238, 238, 1));
            case "palevioletred":
              return new Color2(new RGBA(219, 112, 147, 1));
            case "papayawhip":
              return new Color2(new RGBA(255, 239, 213, 1));
            case "peachpuff":
              return new Color2(new RGBA(255, 218, 185, 1));
            case "peru":
              return new Color2(new RGBA(205, 133, 63, 1));
            case "pink":
              return new Color2(new RGBA(255, 192, 203, 1));
            case "plum":
              return new Color2(new RGBA(221, 160, 221, 1));
            case "powderblue":
              return new Color2(new RGBA(176, 224, 230, 1));
            case "purple":
              return new Color2(new RGBA(128, 0, 128, 1));
            case "rebeccapurple":
              return new Color2(new RGBA(102, 51, 153, 1));
            case "red":
              return new Color2(new RGBA(255, 0, 0, 1));
            case "rosybrown":
              return new Color2(new RGBA(188, 143, 143, 1));
            case "royalblue":
              return new Color2(new RGBA(65, 105, 225, 1));
            case "saddlebrown":
              return new Color2(new RGBA(139, 69, 19, 1));
            case "salmon":
              return new Color2(new RGBA(250, 128, 114, 1));
            case "sandybrown":
              return new Color2(new RGBA(244, 164, 96, 1));
            case "seagreen":
              return new Color2(new RGBA(46, 139, 87, 1));
            case "seashell":
              return new Color2(new RGBA(255, 245, 238, 1));
            case "sienna":
              return new Color2(new RGBA(160, 82, 45, 1));
            case "silver":
              return new Color2(new RGBA(192, 192, 192, 1));
            case "skyblue":
              return new Color2(new RGBA(135, 206, 235, 1));
            case "slateblue":
              return new Color2(new RGBA(106, 90, 205, 1));
            case "slategray":
              return new Color2(new RGBA(112, 128, 144, 1));
            case "slategrey":
              return new Color2(new RGBA(112, 128, 144, 1));
            case "snow":
              return new Color2(new RGBA(255, 250, 250, 1));
            case "springgreen":
              return new Color2(new RGBA(0, 255, 127, 1));
            case "steelblue":
              return new Color2(new RGBA(70, 130, 180, 1));
            case "tan":
              return new Color2(new RGBA(210, 180, 140, 1));
            case "teal":
              return new Color2(new RGBA(0, 128, 128, 1));
            case "thistle":
              return new Color2(new RGBA(216, 191, 216, 1));
            case "tomato":
              return new Color2(new RGBA(255, 99, 71, 1));
            case "turquoise":
              return new Color2(new RGBA(64, 224, 208, 1));
            case "violet":
              return new Color2(new RGBA(238, 130, 238, 1));
            case "wheat":
              return new Color2(new RGBA(245, 222, 179, 1));
            case "white":
              return new Color2(new RGBA(255, 255, 255, 1));
            case "whitesmoke":
              return new Color2(new RGBA(245, 245, 245, 1));
            case "yellow":
              return new Color2(new RGBA(255, 255, 0, 1));
            case "yellowgreen":
              return new Color2(new RGBA(154, 205, 50, 1));
            default:
              return null;
          }
        }
        function parseHex(hex) {
          const length = hex.length;
          if (length === 0) {
            return null;
          }
          if (hex.charCodeAt(0) !== 35) {
            return null;
          }
          if (length === 7) {
            const r = 16 * _parseHexDigit(hex.charCodeAt(1)) + _parseHexDigit(hex.charCodeAt(2));
            const g = 16 * _parseHexDigit(hex.charCodeAt(3)) + _parseHexDigit(hex.charCodeAt(4));
            const b = 16 * _parseHexDigit(hex.charCodeAt(5)) + _parseHexDigit(hex.charCodeAt(6));
            return new Color2(new RGBA(r, g, b, 1));
          }
          if (length === 9) {
            const r = 16 * _parseHexDigit(hex.charCodeAt(1)) + _parseHexDigit(hex.charCodeAt(2));
            const g = 16 * _parseHexDigit(hex.charCodeAt(3)) + _parseHexDigit(hex.charCodeAt(4));
            const b = 16 * _parseHexDigit(hex.charCodeAt(5)) + _parseHexDigit(hex.charCodeAt(6));
            const a = 16 * _parseHexDigit(hex.charCodeAt(7)) + _parseHexDigit(hex.charCodeAt(8));
            return new Color2(new RGBA(r, g, b, a / 255));
          }
          if (length === 4) {
            const r = _parseHexDigit(hex.charCodeAt(1));
            const g = _parseHexDigit(hex.charCodeAt(2));
            const b = _parseHexDigit(hex.charCodeAt(3));
            return new Color2(new RGBA(16 * r + r, 16 * g + g, 16 * b + b));
          }
          if (length === 5) {
            const r = _parseHexDigit(hex.charCodeAt(1));
            const g = _parseHexDigit(hex.charCodeAt(2));
            const b = _parseHexDigit(hex.charCodeAt(3));
            const a = _parseHexDigit(hex.charCodeAt(4));
            return new Color2(new RGBA(16 * r + r, 16 * g + g, 16 * b + b, (16 * a + a) / 255));
          }
          return null;
        }
        CSS2.parseHex = parseHex;
        function _parseHexDigit(charCode) {
          switch (charCode) {
            case 48:
              return 0;
            case 49:
              return 1;
            case 50:
              return 2;
            case 51:
              return 3;
            case 52:
              return 4;
            case 53:
              return 5;
            case 54:
              return 6;
            case 55:
              return 7;
            case 56:
              return 8;
            case 57:
              return 9;
            case 97:
              return 10;
            case 65:
              return 10;
            case 98:
              return 11;
            case 66:
              return 11;
            case 99:
              return 12;
            case 67:
              return 12;
            case 100:
              return 13;
            case 68:
              return 13;
            case 101:
              return 14;
            case 69:
              return 14;
            case 102:
              return 15;
            case 70:
              return 15;
          }
          return 0;
        }
      })(Format.CSS || (Format.CSS = {}));
    })(Color2.Format || (Color2.Format = {}));
  })(Color || (Color = {}));
  function asCssVariableName(colorIdent) {
    return `--vscode-${colorIdent.replace(/\./g, "-")}`;
  }
  function asCssVariable(color) {
    return `var(${asCssVariableName(color)})`;
  }
  function asCssVariableWithDefault(color, defaultCssValue) {
    return `var(${asCssVariableName(color)}, ${defaultCssValue})`;
  }
  function isColorDefaults(value) {
    return value !== null && typeof value === "object" && "light" in value && "dark" in value;
  }
  const Extensions$4 = {
    ColorContribution: "base.contributions.colors"
  };
  const DEFAULT_COLOR_CONFIG_VALUE = "default";
  class ColorRegistry extends Disposable {
    constructor() {
      super();
      this._onDidChangeSchema = this._register(new Emitter$1());
      this.onDidChangeSchema = this._onDidChangeSchema.event;
      this.colorSchema = { type: "object", properties: {} };
      this.colorReferenceSchema = { type: "string", enum: [], enumDescriptions: [] };
      this.colorsById = {};
    }
    registerColor(id, defaults, description, needsTransparency = false, deprecationMessage) {
      const colorContribution = { id, description, defaults, needsTransparency, deprecationMessage };
      this.colorsById[id] = colorContribution;
      const propertySchema = { type: "string", format: "color-hex", defaultSnippets: [{ body: "${1:#ff0000}" }] };
      if (deprecationMessage) {
        propertySchema.deprecationMessage = deprecationMessage;
      }
      if (needsTransparency) {
        propertySchema.pattern = "^#(?:(?<rgba>[0-9a-fA-f]{3}[0-9a-eA-E])|(?:[0-9a-fA-F]{6}(?:(?![fF]{2})(?:[0-9a-fA-F]{2}))))?$";
        propertySchema.patternErrorMessage = localize(2022, "This color must be transparent or it will obscure content");
      }
      this.colorSchema.properties[id] = {
        description,
        oneOf: [
          propertySchema,
          { type: "string", const: DEFAULT_COLOR_CONFIG_VALUE, description: localize(2023, "Use the default color.") }
        ]
      };
      this.colorReferenceSchema.enum.push(id);
      this.colorReferenceSchema.enumDescriptions.push(description);
      this._onDidChangeSchema.fire();
      return id;
    }
    getColors() {
      return Object.keys(this.colorsById).map((id) => this.colorsById[id]);
    }
    resolveDefaultColor(id, theme) {
      const colorDesc = this.colorsById[id];
      if (colorDesc?.defaults) {
        const colorValue = isColorDefaults(colorDesc.defaults) ? colorDesc.defaults[theme.type] : colorDesc.defaults;
        return resolveColorValue(colorValue, theme);
      }
      return void 0;
    }
    getColorSchema() {
      return this.colorSchema;
    }
    toString() {
      const sorter2 = (a, b) => {
        const cat1 = a.indexOf(".") === -1 ? 0 : 1;
        const cat2 = b.indexOf(".") === -1 ? 0 : 1;
        if (cat1 !== cat2) {
          return cat1 - cat2;
        }
        return a.localeCompare(b);
      };
      return Object.keys(this.colorsById).sort(sorter2).map((k) => `- \`${k}\`: ${this.colorsById[k].description}`).join("\n");
    }
  }
  const colorRegistry$1 = new ColorRegistry();
  Registry.add(Extensions$4.ColorContribution, colorRegistry$1);
  function registerColor(id, defaults, description, needsTransparency, deprecationMessage) {
    return colorRegistry$1.registerColor(id, defaults, description, needsTransparency, deprecationMessage);
  }
  function executeTransform(transform, theme) {
    switch (transform.op) {
      case 0:
        return resolveColorValue(transform.value, theme)?.darken(transform.factor);
      case 1:
        return resolveColorValue(transform.value, theme)?.lighten(transform.factor);
      case 2:
        return resolveColorValue(transform.value, theme)?.transparent(transform.factor);
      case 7: {
        const primaryColor = resolveColorValue(transform.color, theme) || Color.transparent;
        const otherColor = resolveColorValue(transform.with, theme) || Color.transparent;
        return primaryColor.mix(otherColor, transform.ratio);
      }
      case 3: {
        const backgroundColor = resolveColorValue(transform.background, theme);
        if (!backgroundColor) {
          return resolveColorValue(transform.value, theme);
        }
        return resolveColorValue(transform.value, theme)?.makeOpaque(backgroundColor);
      }
      case 4:
        for (const candidate of transform.values) {
          const color = resolveColorValue(candidate, theme);
          if (color) {
            return color;
          }
        }
        return void 0;
      case 6:
        return resolveColorValue(theme.defines(transform.if) ? transform.then : transform.else, theme);
      case 5: {
        const from = resolveColorValue(transform.value, theme);
        if (!from) {
          return void 0;
        }
        const backgroundColor = resolveColorValue(transform.background, theme);
        if (!backgroundColor) {
          return from.transparent(transform.factor * transform.transparency);
        }
        return from.isDarkerThan(backgroundColor) ? Color.getLighterColor(from, backgroundColor, transform.factor).transparent(transform.transparency) : Color.getDarkerColor(from, backgroundColor, transform.factor).transparent(transform.transparency);
      }
      default:
        throw assertNever();
    }
  }
  function darken(colorValue, factor2) {
    return { op: 0, value: colorValue, factor: factor2 };
  }
  function lighten(colorValue, factor2) {
    return { op: 1, value: colorValue, factor: factor2 };
  }
  function transparent(colorValue, factor2) {
    return { op: 2, value: colorValue, factor: factor2 };
  }
  function oneOf(...colorValues) {
    return { op: 4, values: colorValues };
  }
  function ifDefinedThenElse(ifArg, thenArg, elseArg) {
    return { op: 6, if: ifArg, then: thenArg, else: elseArg };
  }
  function lessProminent(colorValue, backgroundColorValue, factor2, transparency) {
    return { op: 5, value: colorValue, background: backgroundColorValue, factor: factor2, transparency };
  }
  function resolveColorValue(colorValue, theme) {
    if (colorValue === null) {
      return void 0;
    } else if (typeof colorValue === "string") {
      if (colorValue[0] === "#") {
        return Color.fromHex(colorValue);
      }
      return theme.getColor(colorValue);
    } else if (colorValue instanceof Color) {
      return colorValue;
    } else if (typeof colorValue === "object") {
      return executeTransform(colorValue, theme);
    }
    return void 0;
  }
  const workbenchColorsSchemaId = "vscode://schemas/workbench-colors";
  const schemaRegistry$1 = Registry.as(Extensions$7.JSONContribution);
  schemaRegistry$1.registerSchema(workbenchColorsSchemaId, colorRegistry$1.getColorSchema());
  const delayer$1 = new RunOnceScheduler(() => schemaRegistry$1.notifySchemaChanged(workbenchColorsSchemaId), 200);
  colorRegistry$1.onDidChangeSchema(() => {
    if (!delayer$1.isScheduled()) {
      delayer$1.schedule();
    }
  });
  const foreground = registerColor("foreground", { dark: "#CCCCCC", light: "#616161", hcDark: "#FFFFFF", hcLight: "#292929" }, localize(1773, "Overall foreground color. This color is only used if not overridden by a component."));
  registerColor("disabledForeground", { dark: "#CCCCCC80", light: "#61616180", hcDark: "#A5A5A5", hcLight: "#7F7F7F" }, localize(1774, "Overall foreground for disabled elements. This color is only used if not overridden by a component."));
  registerColor("errorForeground", { dark: "#F48771", light: "#A1260D", hcDark: "#F48771", hcLight: "#B5200D" }, localize(1775, "Overall foreground color for error messages. This color is only used if not overridden by a component."));
  const descriptionForeground = registerColor("descriptionForeground", { light: "#717171", dark: transparent(foreground, 0.7), hcDark: transparent(foreground, 0.7), hcLight: transparent(foreground, 0.7) }, localize(1776, "Foreground color for description text providing additional information, for example for a label."));
  const iconForeground = registerColor("icon.foreground", { dark: "#C5C5C5", light: "#424242", hcDark: "#FFFFFF", hcLight: "#292929" }, localize(1777, "The default color for icons in the workbench."));
  const focusBorder = registerColor("focusBorder", { dark: "#007FD4", light: "#0090F1", hcDark: "#F38518", hcLight: "#006BBD" }, localize(1778, "Overall border color for focused elements. This color is only used if not overridden by a component."));
  const contrastBorder = registerColor("contrastBorder", { light: null, dark: null, hcDark: "#6FC3DF", hcLight: "#0F4A85" }, localize(1779, "An extra border around elements to separate them from others for greater contrast."));
  const activeContrastBorder = registerColor("contrastActiveBorder", { light: null, dark: null, hcDark: focusBorder, hcLight: focusBorder }, localize(1780, "An extra border around active elements to separate them from others for greater contrast."));
  registerColor("selection.background", null, localize(1781, "The background color of text selections in the workbench (e.g. for input fields or text areas). Note that this does not apply to selections within the editor."));
  const textLinkForeground = registerColor("textLink.foreground", { light: "#006AB1", dark: "#3794FF", hcDark: "#21A6FF", hcLight: "#0F4A85" }, localize(1782, "Foreground color for links in text."));
  registerColor("textLink.activeForeground", { light: "#006AB1", dark: "#3794FF", hcDark: "#21A6FF", hcLight: "#0F4A85" }, localize(1783, "Foreground color for links in text when clicked on and on mouse hover."));
  registerColor("textSeparator.foreground", { light: "#0000002e", dark: "#ffffff2e", hcDark: Color.black, hcLight: "#292929" }, localize(1784, "Color for text separators."));
  registerColor("textPreformat.foreground", { light: "#A31515", dark: "#D7BA7D", hcDark: "#000000", hcLight: "#FFFFFF" }, localize(1785, "Foreground color for preformatted text segments."));
  registerColor("textPreformat.background", { light: "#0000001A", dark: "#FFFFFF1A", hcDark: "#FFFFFF", hcLight: "#09345f" }, localize(1786, "Background color for preformatted text segments."));
  registerColor("textBlockQuote.background", { light: "#f2f2f2", dark: "#222222", hcDark: null, hcLight: "#F2F2F2" }, localize(1787, "Background color for block quotes in text."));
  registerColor("textBlockQuote.border", { light: "#007acc80", dark: "#007acc80", hcDark: Color.white, hcLight: "#292929" }, localize(1788, "Border color for block quotes in text."));
  registerColor("textCodeBlock.background", { light: "#dcdcdc66", dark: "#0a0a0a66", hcDark: Color.black, hcLight: "#F2F2F2" }, localize(1789, "Background color for code blocks in text."));
  registerColor("sash.hoverBorder", focusBorder, localize(1994, "Border color of active sashes."));
  const badgeBackground = registerColor("badge.background", { dark: "#4D4D4D", light: "#C4C4C4", hcDark: Color.black, hcLight: "#0F4A85" }, localize(1995, "Badge background color. Badges are small information labels, e.g. for search results count."));
  const badgeForeground = registerColor("badge.foreground", { dark: Color.white, light: "#333", hcDark: Color.white, hcLight: Color.white }, localize(1996, "Badge foreground color. Badges are small information labels, e.g. for search results count."));
  registerColor("activityWarningBadge.foreground", { dark: Color.black.lighten(0.2), light: Color.white, hcDark: null, hcLight: Color.black.lighten(0.2) }, localize(1997, "Foreground color of the warning activity badge"));
  registerColor("activityWarningBadge.background", { dark: "#CCA700", light: "#BF8803", hcDark: null, hcLight: "#CCA700" }, localize(1998, "Background color of the warning activity badge"));
  registerColor("activityErrorBadge.foreground", { dark: Color.black.lighten(0.2), light: Color.white, hcDark: null, hcLight: Color.black.lighten(0.2) }, localize(1999, "Foreground color of the error activity badge"));
  registerColor("activityErrorBadge.background", { dark: "#F14C4C", light: "#E51400", hcDark: null, hcLight: "#F14C4C" }, localize(2e3, "Background color of the error activity badge"));
  const scrollbarShadow = registerColor("scrollbar.shadow", { dark: "#000000", light: "#DDDDDD", hcDark: null, hcLight: null }, localize(2001, "Scrollbar shadow to indicate that the view is scrolled."));
  const scrollbarSliderBackground = registerColor("scrollbarSlider.background", { dark: Color.fromHex("#797979").transparent(0.4), light: Color.fromHex("#646464").transparent(0.4), hcDark: transparent(contrastBorder, 0.6), hcLight: transparent(contrastBorder, 0.4) }, localize(2002, "Scrollbar slider background color."));
  const scrollbarSliderHoverBackground = registerColor("scrollbarSlider.hoverBackground", { dark: Color.fromHex("#646464").transparent(0.7), light: Color.fromHex("#646464").transparent(0.7), hcDark: transparent(contrastBorder, 0.8), hcLight: transparent(contrastBorder, 0.8) }, localize(2003, "Scrollbar slider background color when hovering."));
  const scrollbarSliderActiveBackground = registerColor("scrollbarSlider.activeBackground", { dark: Color.fromHex("#BFBFBF").transparent(0.4), light: Color.fromHex("#000000").transparent(0.6), hcDark: contrastBorder, hcLight: contrastBorder }, localize(2004, "Scrollbar slider background color when clicked on."));
  registerColor("scrollbar.background", null, localize(2005, "Scrollbar track background color."));
  const progressBarBackground = registerColor("progressBar.background", { dark: Color.fromHex("#0E70C0"), light: Color.fromHex("#0E70C0"), hcDark: contrastBorder, hcLight: contrastBorder }, localize(2006, "Background color of the progress bar that can show for long running operations."));
  registerColor("chart.line", { dark: "#236B8E", light: "#236B8E", hcDark: "#236B8E", hcLight: "#236B8E" }, localize(2007, "Line color for the chart."));
  registerColor("chart.axis", { dark: Color.fromHex("#BFBFBF").transparent(0.4), light: Color.fromHex("#000000").transparent(0.6), hcDark: contrastBorder, hcLight: contrastBorder }, localize(2008, "Axis color for the chart."));
  registerColor("chart.guide", { dark: Color.fromHex("#BFBFBF").transparent(0.2), light: Color.fromHex("#000000").transparent(0.2), hcDark: contrastBorder, hcLight: contrastBorder }, localize(2009, "Guide line for the chart."));
  const editorBackground = registerColor("editor.background", { light: "#ffffff", dark: "#1E1E1E", hcDark: Color.black, hcLight: Color.white }, localize(1798, "Editor background color."));
  const editorForeground = registerColor("editor.foreground", { light: "#333333", dark: "#BBBBBB", hcDark: Color.white, hcLight: foreground }, localize(1799, "Editor default foreground color."));
  registerColor("editorStickyScroll.background", editorBackground, localize(1800, "Background color of sticky scroll in the editor"));
  registerColor("editorStickyScrollGutter.background", editorBackground, localize(1801, "Background color of the gutter part of sticky scroll in the editor"));
  registerColor("editorStickyScrollHover.background", { dark: "#2A2D2E", light: "#F0F0F0", hcDark: null, hcLight: Color.fromHex("#0F4A85").transparent(0.1) }, localize(1802, "Background color of sticky scroll on hover in the editor"));
  registerColor("editorStickyScroll.border", { dark: null, light: null, hcDark: contrastBorder, hcLight: contrastBorder }, localize(1803, "Border color of sticky scroll in the editor"));
  registerColor("editorStickyScroll.shadow", scrollbarShadow, localize(1804, " Shadow color of sticky scroll in the editor"));
  const editorWidgetBackground = registerColor("editorWidget.background", { dark: "#252526", light: "#F3F3F3", hcDark: "#0C141F", hcLight: Color.white }, localize(1805, "Background color of editor widgets, such as find/replace."));
  const editorWidgetForeground = registerColor("editorWidget.foreground", foreground, localize(1806, "Foreground color of editor widgets, such as find/replace."));
  const editorWidgetBorder = registerColor("editorWidget.border", { dark: "#454545", light: "#C8C8C8", hcDark: contrastBorder, hcLight: contrastBorder }, localize(1807, "Border color of editor widgets. The color is only used if the widget chooses to have a border and if the color is not overridden by a widget."));
  registerColor("editorWidget.resizeBorder", null, localize(1808, "Border color of the resize bar of editor widgets. The color is only used if the widget chooses to have a resize border and if the color is not overridden by a widget."));
  registerColor("editorError.background", null, localize(1809, "Background color of error text in the editor. The color must not be opaque so as not to hide underlying decorations."), true);
  const editorErrorForeground = registerColor("editorError.foreground", { dark: "#F14C4C", light: "#E51400", hcDark: "#F48771", hcLight: "#B5200D" }, localize(1810, "Foreground color of error squigglies in the editor."));
  const editorErrorBorder = registerColor("editorError.border", { dark: null, light: null, hcDark: Color.fromHex("#E47777").transparent(0.8), hcLight: "#B5200D" }, localize(1811, "If set, color of double underlines for errors in the editor."));
  const editorWarningBackground = registerColor("editorWarning.background", null, localize(1812, "Background color of warning text in the editor. The color must not be opaque so as not to hide underlying decorations."), true);
  const editorWarningForeground = registerColor("editorWarning.foreground", { dark: "#CCA700", light: "#BF8803", hcDark: "#FFD370", hcLight: "#895503" }, localize(1813, "Foreground color of warning squigglies in the editor."));
  const editorWarningBorder = registerColor("editorWarning.border", { dark: null, light: null, hcDark: Color.fromHex("#FFCC00").transparent(0.8), hcLight: Color.fromHex("#FFCC00").transparent(0.8) }, localize(1814, "If set, color of double underlines for warnings in the editor."));
  registerColor("editorInfo.background", null, localize(1815, "Background color of info text in the editor. The color must not be opaque so as not to hide underlying decorations."), true);
  const editorInfoForeground = registerColor("editorInfo.foreground", { dark: "#3794FF", light: "#1a85ff", hcDark: "#3794FF", hcLight: "#1a85ff" }, localize(1816, "Foreground color of info squigglies in the editor."));
  const editorInfoBorder = registerColor("editorInfo.border", { dark: null, light: null, hcDark: Color.fromHex("#3794FF").transparent(0.8), hcLight: "#292929" }, localize(1817, "If set, color of double underlines for infos in the editor."));
  const editorHintForeground = registerColor("editorHint.foreground", { dark: Color.fromHex("#eeeeee").transparent(0.7), light: "#6c6c6c", hcDark: null, hcLight: null }, localize(1818, "Foreground color of hint squigglies in the editor."));
  registerColor("editorHint.border", { dark: null, light: null, hcDark: Color.fromHex("#eeeeee").transparent(0.8), hcLight: "#292929" }, localize(1819, "If set, color of double underlines for hints in the editor."));
  const editorActiveLinkForeground = registerColor("editorLink.activeForeground", { dark: "#4E94CE", light: Color.blue, hcDark: Color.cyan, hcLight: "#292929" }, localize(1820, "Color of active links."));
  const editorSelectionBackground = registerColor("editor.selectionBackground", { light: "#ADD6FF", dark: "#264F78", hcDark: "#f3f518", hcLight: "#0F4A85" }, localize(1821, "Color of the editor selection."));
  const editorSelectionForeground = registerColor("editor.selectionForeground", { light: null, dark: null, hcDark: "#000000", hcLight: Color.white }, localize(1822, "Color of the selected text for high contrast."));
  const editorInactiveSelection = registerColor("editor.inactiveSelectionBackground", { light: transparent(editorSelectionBackground, 0.5), dark: transparent(editorSelectionBackground, 0.5), hcDark: transparent(editorSelectionBackground, 0.7), hcLight: transparent(editorSelectionBackground, 0.5) }, localize(1823, "Color of the selection in an inactive editor. The color must not be opaque so as not to hide underlying decorations."), true);
  const editorSelectionHighlight = registerColor("editor.selectionHighlightBackground", { light: lessProminent(editorSelectionBackground, editorBackground, 0.3, 0.6), dark: lessProminent(editorSelectionBackground, editorBackground, 0.3, 0.6), hcDark: null, hcLight: null }, localize(1824, "Color for regions with the same content as the selection. The color must not be opaque so as not to hide underlying decorations."), true);
  registerColor("editor.selectionHighlightBorder", { light: null, dark: null, hcDark: activeContrastBorder, hcLight: activeContrastBorder }, localize(1825, "Border color for regions with the same content as the selection."));
  registerColor("editor.compositionBorder", { light: "#000000", dark: "#ffffff", hcLight: "#000000", hcDark: "#ffffff" }, localize(1826, "The border color for an IME composition."));
  registerColor("editor.findMatchBackground", { light: "#A8AC94", dark: "#515C6A", hcDark: null, hcLight: null }, localize(1827, "Color of the current search match."));
  const editorFindMatchForeground = registerColor("editor.findMatchForeground", null, localize(1828, "Text color of the current search match."));
  const editorFindMatchHighlight = registerColor("editor.findMatchHighlightBackground", { light: "#EA5C0055", dark: "#EA5C0055", hcDark: null, hcLight: null }, localize(1829, "Color of the other search matches. The color must not be opaque so as not to hide underlying decorations."), true);
  const editorFindMatchHighlightForeground = registerColor("editor.findMatchHighlightForeground", null, localize(1830, "Foreground color of the other search matches."), true);
  registerColor("editor.findRangeHighlightBackground", { dark: "#3a3d4166", light: "#b4b4b44d", hcDark: null, hcLight: null }, localize(1831, "Color of the range limiting the search. The color must not be opaque so as not to hide underlying decorations."), true);
  registerColor("editor.findMatchBorder", { light: null, dark: null, hcDark: activeContrastBorder, hcLight: activeContrastBorder }, localize(1832, "Border color of the current search match."));
  const editorFindMatchHighlightBorder = registerColor("editor.findMatchHighlightBorder", { light: null, dark: null, hcDark: activeContrastBorder, hcLight: activeContrastBorder }, localize(1833, "Border color of the other search matches."));
  const editorFindRangeHighlightBorder = registerColor("editor.findRangeHighlightBorder", { dark: null, light: null, hcDark: transparent(activeContrastBorder, 0.4), hcLight: transparent(activeContrastBorder, 0.4) }, localize(1834, "Border color of the range limiting the search. The color must not be opaque so as not to hide underlying decorations."), true);
  registerColor("editor.hoverHighlightBackground", { light: "#ADD6FF26", dark: "#264f7840", hcDark: "#ADD6FF26", hcLight: null }, localize(1835, "Highlight below the word for which a hover is shown. The color must not be opaque so as not to hide underlying decorations."), true);
  const editorHoverBackground = registerColor("editorHoverWidget.background", editorWidgetBackground, localize(1836, "Background color of the editor hover."));
  const editorHoverForeground = registerColor("editorHoverWidget.foreground", editorWidgetForeground, localize(1837, "Foreground color of the editor hover."));
  const editorHoverBorder = registerColor("editorHoverWidget.border", editorWidgetBorder, localize(1838, "Border color of the editor hover."));
  registerColor("editorHoverWidget.statusBarBackground", { dark: lighten(editorHoverBackground, 0.2), light: darken(editorHoverBackground, 0.05), hcDark: editorWidgetBackground, hcLight: editorWidgetBackground }, localize(1839, "Background color of the editor hover status bar."));
  const editorInlayHintForeground = registerColor("editorInlayHint.foreground", { dark: "#969696", light: "#969696", hcDark: Color.white, hcLight: Color.black }, localize(1840, "Foreground color of inline hints"));
  const editorInlayHintBackground = registerColor("editorInlayHint.background", { dark: transparent(badgeBackground, 0.1), light: transparent(badgeBackground, 0.1), hcDark: transparent(Color.white, 0.1), hcLight: transparent(badgeBackground, 0.1) }, localize(1841, "Background color of inline hints"));
  const editorInlayHintTypeForeground = registerColor("editorInlayHint.typeForeground", editorInlayHintForeground, localize(1842, "Foreground color of inline hints for types"));
  const editorInlayHintTypeBackground = registerColor("editorInlayHint.typeBackground", editorInlayHintBackground, localize(1843, "Background color of inline hints for types"));
  const editorInlayHintParameterForeground = registerColor("editorInlayHint.parameterForeground", editorInlayHintForeground, localize(1844, "Foreground color of inline hints for parameters"));
  const editorInlayHintParameterBackground = registerColor("editorInlayHint.parameterBackground", editorInlayHintBackground, localize(1845, "Background color of inline hints for parameters"));
  const editorLightBulbForeground = registerColor("editorLightBulb.foreground", { dark: "#FFCC00", light: "#DDB100", hcDark: "#FFCC00", hcLight: "#007ACC" }, localize(1846, "The color used for the lightbulb actions icon."));
  registerColor("editorLightBulbAutoFix.foreground", { dark: "#75BEFF", light: "#007ACC", hcDark: "#75BEFF", hcLight: "#007ACC" }, localize(1847, "The color used for the lightbulb auto fix actions icon."));
  registerColor("editorLightBulbAi.foreground", editorLightBulbForeground, localize(1848, "The color used for the lightbulb AI icon."));
  registerColor("editor.snippetTabstopHighlightBackground", { dark: new Color(new RGBA(124, 124, 124, 0.3)), light: new Color(new RGBA(10, 50, 100, 0.2)), hcDark: new Color(new RGBA(124, 124, 124, 0.3)), hcLight: new Color(new RGBA(10, 50, 100, 0.2)) }, localize(1849, "Highlight background color of a snippet tabstop."));
  registerColor("editor.snippetTabstopHighlightBorder", null, localize(1850, "Highlight border color of a snippet tabstop."));
  registerColor("editor.snippetFinalTabstopHighlightBackground", null, localize(1851, "Highlight background color of the final tabstop of a snippet."));
  registerColor("editor.snippetFinalTabstopHighlightBorder", { dark: "#525252", light: new Color(new RGBA(10, 50, 100, 0.5)), hcDark: "#525252", hcLight: "#292929" }, localize(1852, "Highlight border color of the final tabstop of a snippet."));
  const defaultInsertColor = new Color(new RGBA(155, 185, 85, 0.2));
  const defaultRemoveColor = new Color(new RGBA(255, 0, 0, 0.2));
  const diffInserted = registerColor("diffEditor.insertedTextBackground", { dark: "#9ccc2c33", light: "#9ccc2c40", hcDark: null, hcLight: null }, localize(1853, "Background color for text that got inserted. The color must not be opaque so as not to hide underlying decorations."), true);
  const diffRemoved = registerColor("diffEditor.removedTextBackground", { dark: "#ff000033", light: "#ff000033", hcDark: null, hcLight: null }, localize(1854, "Background color for text that got removed. The color must not be opaque so as not to hide underlying decorations."), true);
  const diffInsertedLine = registerColor("diffEditor.insertedLineBackground", { dark: defaultInsertColor, light: defaultInsertColor, hcDark: null, hcLight: null }, localize(1855, "Background color for lines that got inserted. The color must not be opaque so as not to hide underlying decorations."), true);
  registerColor("diffEditor.removedLineBackground", { dark: defaultRemoveColor, light: defaultRemoveColor, hcDark: null, hcLight: null }, localize(1856, "Background color for lines that got removed. The color must not be opaque so as not to hide underlying decorations."), true);
  registerColor("diffEditorGutter.insertedLineBackground", null, localize(1857, "Background color for the margin where lines got inserted."));
  registerColor("diffEditorGutter.removedLineBackground", null, localize(1858, "Background color for the margin where lines got removed."));
  const diffOverviewRulerInserted = registerColor("diffEditorOverview.insertedForeground", null, localize(1859, "Diff overview ruler foreground for inserted content."));
  const diffOverviewRulerRemoved = registerColor("diffEditorOverview.removedForeground", null, localize(1860, "Diff overview ruler foreground for removed content."));
  registerColor("diffEditor.insertedTextBorder", { dark: null, light: null, hcDark: "#33ff2eff", hcLight: "#374E06" }, localize(1861, "Outline color for the text that got inserted."));
  registerColor("diffEditor.removedTextBorder", { dark: null, light: null, hcDark: "#FF008F", hcLight: "#AD0707" }, localize(1862, "Outline color for text that got removed."));
  registerColor("diffEditor.border", { dark: null, light: null, hcDark: contrastBorder, hcLight: contrastBorder }, localize(1863, "Border color between the two text editors."));
  registerColor("diffEditor.diagonalFill", { dark: "#cccccc33", light: "#22222233", hcDark: null, hcLight: null }, localize(1864, "Color of the diff editor's diagonal fill. The diagonal fill is used in side-by-side diff views."));
  registerColor("diffEditor.unchangedRegionBackground", "sideBar.background", localize(1865, "The background color of unchanged blocks in the diff editor."));
  registerColor("diffEditor.unchangedRegionForeground", "foreground", localize(1866, "The foreground color of unchanged blocks in the diff editor."));
  registerColor("diffEditor.unchangedCodeBackground", { dark: "#74747429", light: "#b8b8b829", hcDark: null, hcLight: null }, localize(1867, "The background color of unchanged code in the diff editor."));
  const widgetShadow = registerColor("widget.shadow", { dark: transparent(Color.black, 0.36), light: transparent(Color.black, 0.16), hcDark: null, hcLight: null }, localize(1868, "Shadow color of widgets such as find/replace inside the editor."));
  const widgetBorder = registerColor("widget.border", { dark: null, light: null, hcDark: contrastBorder, hcLight: contrastBorder }, localize(1869, "Border color of widgets such as find/replace inside the editor."));
  const toolbarHoverBackground = registerColor("toolbar.hoverBackground", { dark: "#5a5d5e50", light: "#b8b8b850", hcDark: null, hcLight: null }, localize(1870, "Toolbar background when hovering over actions using the mouse"));
  registerColor("toolbar.hoverOutline", { dark: null, light: null, hcDark: activeContrastBorder, hcLight: activeContrastBorder }, localize(1871, "Toolbar outline when hovering over actions using the mouse"));
  registerColor("toolbar.activeBackground", { dark: lighten(toolbarHoverBackground, 0.1), light: darken(toolbarHoverBackground, 0.1), hcDark: null, hcLight: null }, localize(1872, "Toolbar background when holding the mouse over actions"));
  const breadcrumbsForeground = registerColor("breadcrumb.foreground", transparent(foreground, 0.8), localize(1873, "Color of focused breadcrumb items."));
  const breadcrumbsBackground = registerColor("breadcrumb.background", editorBackground, localize(1874, "Background color of breadcrumb items."));
  const breadcrumbsFocusForeground = registerColor("breadcrumb.focusForeground", { light: darken(foreground, 0.2), dark: lighten(foreground, 0.1), hcDark: lighten(foreground, 0.1), hcLight: lighten(foreground, 0.1) }, localize(1875, "Color of focused breadcrumb items."));
  const breadcrumbsActiveSelectionForeground = registerColor("breadcrumb.activeSelectionForeground", { light: darken(foreground, 0.2), dark: lighten(foreground, 0.1), hcDark: lighten(foreground, 0.1), hcLight: lighten(foreground, 0.1) }, localize(1876, "Color of selected breadcrumb items."));
  registerColor("breadcrumbPicker.background", editorWidgetBackground, localize(1877, "Background color of breadcrumb item picker."));
  const headerTransparency = 0.5;
  const currentBaseColor = Color.fromHex("#40C8AE").transparent(headerTransparency);
  const incomingBaseColor = Color.fromHex("#40A6FF").transparent(headerTransparency);
  const commonBaseColor = Color.fromHex("#606060").transparent(0.4);
  const contentTransparency = 0.4;
  const rulerTransparency = 1;
  const mergeCurrentHeaderBackground = registerColor("merge.currentHeaderBackground", { dark: currentBaseColor, light: currentBaseColor, hcDark: null, hcLight: null }, localize(1878, "Current header background in inline merge-conflicts. The color must not be opaque so as not to hide underlying decorations."), true);
  registerColor("merge.currentContentBackground", transparent(mergeCurrentHeaderBackground, contentTransparency), localize(1879, "Current content background in inline merge-conflicts. The color must not be opaque so as not to hide underlying decorations."), true);
  const mergeIncomingHeaderBackground = registerColor("merge.incomingHeaderBackground", { dark: incomingBaseColor, light: incomingBaseColor, hcDark: null, hcLight: null }, localize(1880, "Incoming header background in inline merge-conflicts. The color must not be opaque so as not to hide underlying decorations."), true);
  registerColor("merge.incomingContentBackground", transparent(mergeIncomingHeaderBackground, contentTransparency), localize(1881, "Incoming content background in inline merge-conflicts. The color must not be opaque so as not to hide underlying decorations."), true);
  const mergeCommonHeaderBackground = registerColor("merge.commonHeaderBackground", { dark: commonBaseColor, light: commonBaseColor, hcDark: null, hcLight: null }, localize(1882, "Common ancestor header background in inline merge-conflicts. The color must not be opaque so as not to hide underlying decorations."), true);
  registerColor("merge.commonContentBackground", transparent(mergeCommonHeaderBackground, contentTransparency), localize(1883, "Common ancestor content background in inline merge-conflicts. The color must not be opaque so as not to hide underlying decorations."), true);
  const mergeBorder = registerColor("merge.border", { dark: null, light: null, hcDark: "#C3DF6F", hcLight: "#007ACC" }, localize(1884, "Border color on headers and the splitter in inline merge-conflicts."));
  registerColor("editorOverviewRuler.currentContentForeground", { dark: transparent(mergeCurrentHeaderBackground, rulerTransparency), light: transparent(mergeCurrentHeaderBackground, rulerTransparency), hcDark: mergeBorder, hcLight: mergeBorder }, localize(1885, "Current overview ruler foreground for inline merge-conflicts."));
  registerColor("editorOverviewRuler.incomingContentForeground", { dark: transparent(mergeIncomingHeaderBackground, rulerTransparency), light: transparent(mergeIncomingHeaderBackground, rulerTransparency), hcDark: mergeBorder, hcLight: mergeBorder }, localize(1886, "Incoming overview ruler foreground for inline merge-conflicts."));
  registerColor("editorOverviewRuler.commonContentForeground", { dark: transparent(mergeCommonHeaderBackground, rulerTransparency), light: transparent(mergeCommonHeaderBackground, rulerTransparency), hcDark: mergeBorder, hcLight: mergeBorder }, localize(1887, "Common ancestor overview ruler foreground for inline merge-conflicts."));
  const overviewRulerFindMatchForeground = registerColor("editorOverviewRuler.findMatchForeground", { dark: "#d186167e", light: "#d186167e", hcDark: "#AB5A00", hcLight: "#AB5A00" }, localize(1888, "Overview ruler marker color for find matches. The color must not be opaque so as not to hide underlying decorations."), true);
  const overviewRulerSelectionHighlightForeground = registerColor("editorOverviewRuler.selectionHighlightForeground", "#A0A0A0CC", localize(1889, "Overview ruler marker color for selection highlights. The color must not be opaque so as not to hide underlying decorations."), true);
  const problemsErrorIconForeground = registerColor("problemsErrorIcon.foreground", editorErrorForeground, localize(1890, "The color used for the problems error icon."));
  const problemsWarningIconForeground = registerColor("problemsWarningIcon.foreground", editorWarningForeground, localize(1891, "The color used for the problems warning icon."));
  const problemsInfoIconForeground = registerColor("problemsInfoIcon.foreground", editorInfoForeground, localize(1892, "The color used for the problems info icon."));
  const minimapFindMatch = registerColor("minimap.findMatchHighlight", { light: "#d18616", dark: "#d18616", hcDark: "#AB5A00", hcLight: "#0F4A85" }, localize(1983, "Minimap marker color for find matches."), true);
  const minimapSelectionOccurrenceHighlight = registerColor("minimap.selectionOccurrenceHighlight", { light: "#c9c9c9", dark: "#676767", hcDark: "#ffffff", hcLight: "#0F4A85" }, localize(1984, "Minimap marker color for repeating editor selections."), true);
  const minimapSelection = registerColor("minimap.selectionHighlight", { light: "#ADD6FF", dark: "#264F78", hcDark: "#ffffff", hcLight: "#0F4A85" }, localize(1985, "Minimap marker color for the editor selection."), true);
  const minimapInfo = registerColor("minimap.infoHighlight", { dark: editorInfoForeground, light: editorInfoForeground, hcDark: editorInfoBorder, hcLight: editorInfoBorder }, localize(1986, "Minimap marker color for infos."));
  const minimapWarning = registerColor("minimap.warningHighlight", { dark: editorWarningForeground, light: editorWarningForeground, hcDark: editorWarningBorder, hcLight: editorWarningBorder }, localize(1987, "Minimap marker color for warnings."));
  const minimapError = registerColor("minimap.errorHighlight", { dark: new Color(new RGBA(255, 18, 18, 0.7)), light: new Color(new RGBA(255, 18, 18, 0.7)), hcDark: new Color(new RGBA(255, 50, 50, 1)), hcLight: "#B5200D" }, localize(1988, "Minimap marker color for errors."));
  const minimapBackground = registerColor("minimap.background", null, localize(1989, "Minimap background color."));
  const minimapForegroundOpacity = registerColor("minimap.foregroundOpacity", Color.fromHex("#000f"), localize(1990, 'Opacity of foreground elements rendered in the minimap. For example, "#000000c0" will render the elements with 75% opacity.'));
  registerColor("minimapSlider.background", transparent(scrollbarSliderBackground, 0.5), localize(1991, "Minimap slider background color."));
  registerColor("minimapSlider.hoverBackground", transparent(scrollbarSliderHoverBackground, 0.5), localize(1992, "Minimap slider background color when hovering."));
  registerColor("minimapSlider.activeBackground", transparent(scrollbarSliderActiveBackground, 0.5), localize(1993, "Minimap slider background color when clicked on."));
  registerColor("charts.foreground", foreground, localize(1790, "The foreground color used in charts."));
  registerColor("charts.lines", transparent(foreground, 0.5), localize(1791, "The color used for horizontal lines in charts."));
  registerColor("charts.red", editorErrorForeground, localize(1792, "The red color used in chart visualizations."));
  registerColor("charts.blue", editorInfoForeground, localize(1793, "The blue color used in chart visualizations."));
  registerColor("charts.yellow", editorWarningForeground, localize(1794, "The yellow color used in chart visualizations."));
  registerColor("charts.orange", minimapFindMatch, localize(1795, "The orange color used in chart visualizations."));
  registerColor("charts.green", { dark: "#89D185", light: "#388A34", hcDark: "#89D185", hcLight: "#374e06" }, localize(1796, "The green color used in chart visualizations."));
  registerColor("charts.purple", { dark: "#B180D7", light: "#652D90", hcDark: "#B180D7", hcLight: "#652D90" }, localize(1797, "The purple color used in chart visualizations."));
  const inputBackground = registerColor("input.background", { dark: "#3C3C3C", light: Color.white, hcDark: Color.black, hcLight: Color.white }, localize(1893, "Input box background."));
  const inputForeground = registerColor("input.foreground", foreground, localize(1894, "Input box foreground."));
  const inputBorder = registerColor("input.border", { dark: null, light: null, hcDark: contrastBorder, hcLight: contrastBorder }, localize(1895, "Input box border."));
  const inputActiveOptionBorder = registerColor("inputOption.activeBorder", { dark: "#007ACC", light: "#007ACC", hcDark: contrastBorder, hcLight: contrastBorder }, localize(1896, "Border color of activated options in input fields."));
  const inputActiveOptionHoverBackground = registerColor("inputOption.hoverBackground", { dark: "#5a5d5e80", light: "#b8b8b850", hcDark: null, hcLight: null }, localize(1897, "Background color of activated options in input fields."));
  const inputActiveOptionBackground = registerColor("inputOption.activeBackground", { dark: transparent(focusBorder, 0.4), light: transparent(focusBorder, 0.2), hcDark: Color.transparent, hcLight: Color.transparent }, localize(1898, "Background hover color of options in input fields."));
  const inputActiveOptionForeground = registerColor("inputOption.activeForeground", { dark: Color.white, light: Color.black, hcDark: foreground, hcLight: foreground }, localize(1899, "Foreground color of activated options in input fields."));
  registerColor("input.placeholderForeground", { light: transparent(foreground, 0.5), dark: transparent(foreground, 0.5), hcDark: transparent(foreground, 0.7), hcLight: transparent(foreground, 0.7) }, localize(1900, "Input box foreground color for placeholder text."));
  const inputValidationInfoBackground = registerColor("inputValidation.infoBackground", { dark: "#063B49", light: "#D6ECF2", hcDark: Color.black, hcLight: Color.white }, localize(1901, "Input validation background color for information severity."));
  const inputValidationInfoForeground = registerColor("inputValidation.infoForeground", { dark: null, light: null, hcDark: null, hcLight: foreground }, localize(1902, "Input validation foreground color for information severity."));
  const inputValidationInfoBorder = registerColor("inputValidation.infoBorder", { dark: "#007acc", light: "#007acc", hcDark: contrastBorder, hcLight: contrastBorder }, localize(1903, "Input validation border color for information severity."));
  const inputValidationWarningBackground = registerColor("inputValidation.warningBackground", { dark: "#352A05", light: "#F6F5D2", hcDark: Color.black, hcLight: Color.white }, localize(1904, "Input validation background color for warning severity."));
  const inputValidationWarningForeground = registerColor("inputValidation.warningForeground", { dark: null, light: null, hcDark: null, hcLight: foreground }, localize(1905, "Input validation foreground color for warning severity."));
  const inputValidationWarningBorder = registerColor("inputValidation.warningBorder", { dark: "#B89500", light: "#B89500", hcDark: contrastBorder, hcLight: contrastBorder }, localize(1906, "Input validation border color for warning severity."));
  const inputValidationErrorBackground = registerColor("inputValidation.errorBackground", { dark: "#5A1D1D", light: "#F2DEDE", hcDark: Color.black, hcLight: Color.white }, localize(1907, "Input validation background color for error severity."));
  const inputValidationErrorForeground = registerColor("inputValidation.errorForeground", { dark: null, light: null, hcDark: null, hcLight: foreground }, localize(1908, "Input validation foreground color for error severity."));
  const inputValidationErrorBorder = registerColor("inputValidation.errorBorder", { dark: "#BE1100", light: "#BE1100", hcDark: contrastBorder, hcLight: contrastBorder }, localize(1909, "Input validation border color for error severity."));
  const selectBackground = registerColor("dropdown.background", { dark: "#3C3C3C", light: Color.white, hcDark: Color.black, hcLight: Color.white }, localize(1910, "Dropdown background."));
  const selectListBackground = registerColor("dropdown.listBackground", { dark: null, light: null, hcDark: Color.black, hcLight: Color.white }, localize(1911, "Dropdown list background."));
  const selectForeground = registerColor("dropdown.foreground", { dark: "#F0F0F0", light: foreground, hcDark: Color.white, hcLight: foreground }, localize(1912, "Dropdown foreground."));
  const selectBorder = registerColor("dropdown.border", { dark: selectBackground, light: "#CECECE", hcDark: contrastBorder, hcLight: contrastBorder }, localize(1913, "Dropdown border."));
  const buttonForeground = registerColor("button.foreground", Color.white, localize(1914, "Button foreground color."));
  const buttonSeparator = registerColor("button.separator", transparent(buttonForeground, 0.4), localize(1915, "Button separator color."));
  const buttonBackground = registerColor("button.background", { dark: "#0E639C", light: "#007ACC", hcDark: Color.black, hcLight: "#0F4A85" }, localize(1916, "Button background color."));
  const buttonHoverBackground = registerColor("button.hoverBackground", { dark: lighten(buttonBackground, 0.2), light: darken(buttonBackground, 0.2), hcDark: buttonBackground, hcLight: buttonBackground }, localize(1917, "Button background color when hovering."));
  const buttonBorder = registerColor("button.border", contrastBorder, localize(1918, "Button border color."));
  const buttonSecondaryForeground = registerColor("button.secondaryForeground", { dark: Color.white, light: Color.white, hcDark: Color.white, hcLight: foreground }, localize(1919, "Secondary button foreground color."));
  const buttonSecondaryBackground = registerColor("button.secondaryBackground", { dark: "#3A3D41", light: "#5F6A79", hcDark: null, hcLight: Color.white }, localize(1920, "Secondary button background color."));
  const buttonSecondaryHoverBackground = registerColor("button.secondaryHoverBackground", { dark: lighten(buttonSecondaryBackground, 0.2), light: darken(buttonSecondaryBackground, 0.2), hcDark: null, hcLight: null }, localize(1921, "Secondary button background color when hovering."));
  const radioActiveForeground = registerColor("radio.activeForeground", inputActiveOptionForeground, localize(1922, "Foreground color of active radio option."));
  const radioActiveBackground = registerColor("radio.activeBackground", inputActiveOptionBackground, localize(1923, "Background color of active radio option."));
  const radioActiveBorder = registerColor("radio.activeBorder", inputActiveOptionBorder, localize(1924, "Border color of the active radio option."));
  const radioInactiveForeground = registerColor("radio.inactiveForeground", null, localize(1925, "Foreground color of inactive radio option."));
  const radioInactiveBackground = registerColor("radio.inactiveBackground", null, localize(1926, "Background color of inactive radio option."));
  const radioInactiveBorder = registerColor("radio.inactiveBorder", { light: transparent(radioActiveForeground, 0.2), dark: transparent(radioActiveForeground, 0.2), hcDark: transparent(radioActiveForeground, 0.4), hcLight: transparent(radioActiveForeground, 0.2) }, localize(1927, "Border color of the inactive radio option."));
  const radioInactiveHoverBackground = registerColor("radio.inactiveHoverBackground", inputActiveOptionHoverBackground, localize(1928, "Background color of inactive active radio option when hovering."));
  const checkboxBackground = registerColor("checkbox.background", selectBackground, localize(1929, "Background color of checkbox widget."));
  registerColor("checkbox.selectBackground", editorWidgetBackground, localize(1930, "Background color of checkbox widget when the element it's in is selected."));
  const checkboxForeground = registerColor("checkbox.foreground", selectForeground, localize(1931, "Foreground color of checkbox widget."));
  const checkboxBorder = registerColor("checkbox.border", selectBorder, localize(1932, "Border color of checkbox widget."));
  registerColor("checkbox.selectBorder", iconForeground, localize(1933, "Border color of checkbox widget when the element it's in is selected."));
  const checkboxDisabledBackground = registerColor("checkbox.disabled.background", { op: 7, color: checkboxBackground, with: checkboxForeground, ratio: 0.33 }, localize(1934, "Background of a disabled checkbox."));
  const checkboxDisabledForeground = registerColor("checkbox.disabled.foreground", { op: 7, color: checkboxForeground, with: checkboxBackground, ratio: 0.33 }, localize(1935, "Foreground of a disabled checkbox."));
  const keybindingLabelBackground = registerColor("keybindingLabel.background", { dark: new Color(new RGBA(128, 128, 128, 0.17)), light: new Color(new RGBA(221, 221, 221, 0.4)), hcDark: Color.transparent, hcLight: Color.transparent }, localize(1936, "Keybinding label background color. The keybinding label is used to represent a keyboard shortcut."));
  const keybindingLabelForeground = registerColor("keybindingLabel.foreground", { dark: Color.fromHex("#CCCCCC"), light: Color.fromHex("#555555"), hcDark: Color.white, hcLight: foreground }, localize(1937, "Keybinding label foreground color. The keybinding label is used to represent a keyboard shortcut."));
  const keybindingLabelBorder = registerColor("keybindingLabel.border", { dark: new Color(new RGBA(51, 51, 51, 0.6)), light: new Color(new RGBA(204, 204, 204, 0.4)), hcDark: new Color(new RGBA(111, 195, 223)), hcLight: contrastBorder }, localize(1938, "Keybinding label border color. The keybinding label is used to represent a keyboard shortcut."));
  const keybindingLabelBottomBorder = registerColor("keybindingLabel.bottomBorder", { dark: new Color(new RGBA(68, 68, 68, 0.6)), light: new Color(new RGBA(187, 187, 187, 0.4)), hcDark: new Color(new RGBA(111, 195, 223)), hcLight: foreground }, localize(1939, "Keybinding label border bottom color. The keybinding label is used to represent a keyboard shortcut."));
  const listFocusBackground = registerColor("list.focusBackground", null, localize(1940, "List/Tree background color for the focused item when the list/tree is active. An active list/tree has keyboard focus, an inactive does not."));
  const listFocusForeground = registerColor("list.focusForeground", null, localize(1941, "List/Tree foreground color for the focused item when the list/tree is active. An active list/tree has keyboard focus, an inactive does not."));
  const listFocusOutline = registerColor("list.focusOutline", { dark: focusBorder, light: focusBorder, hcDark: activeContrastBorder, hcLight: activeContrastBorder }, localize(1942, "List/Tree outline color for the focused item when the list/tree is active. An active list/tree has keyboard focus, an inactive does not."));
  const listFocusAndSelectionOutline = registerColor("list.focusAndSelectionOutline", null, localize(1943, "List/Tree outline color for the focused item when the list/tree is active and selected. An active list/tree has keyboard focus, an inactive does not."));
  const listActiveSelectionBackground = registerColor("list.activeSelectionBackground", { dark: "#04395E", light: "#0060C0", hcDark: null, hcLight: Color.fromHex("#0F4A85").transparent(0.1) }, localize(1944, "List/Tree background color for the selected item when the list/tree is active. An active list/tree has keyboard focus, an inactive does not."));
  const listActiveSelectionForeground = registerColor("list.activeSelectionForeground", { dark: Color.white, light: Color.white, hcDark: null, hcLight: null }, localize(1945, "List/Tree foreground color for the selected item when the list/tree is active. An active list/tree has keyboard focus, an inactive does not."));
  const listActiveSelectionIconForeground = registerColor("list.activeSelectionIconForeground", null, localize(1946, "List/Tree icon foreground color for the selected item when the list/tree is active. An active list/tree has keyboard focus, an inactive does not."));
  const listInactiveSelectionBackground = registerColor("list.inactiveSelectionBackground", { dark: "#37373D", light: "#E4E6F1", hcDark: null, hcLight: Color.fromHex("#0F4A85").transparent(0.1) }, localize(1947, "List/Tree background color for the selected item when the list/tree is inactive. An active list/tree has keyboard focus, an inactive does not."));
  const listInactiveSelectionForeground = registerColor("list.inactiveSelectionForeground", null, localize(1948, "List/Tree foreground color for the selected item when the list/tree is inactive. An active list/tree has keyboard focus, an inactive does not."));
  const listInactiveSelectionIconForeground = registerColor("list.inactiveSelectionIconForeground", null, localize(1949, "List/Tree icon foreground color for the selected item when the list/tree is inactive. An active list/tree has keyboard focus, an inactive does not."));
  const listInactiveFocusBackground = registerColor("list.inactiveFocusBackground", null, localize(1950, "List/Tree background color for the focused item when the list/tree is inactive. An active list/tree has keyboard focus, an inactive does not."));
  const listInactiveFocusOutline = registerColor("list.inactiveFocusOutline", null, localize(1951, "List/Tree outline color for the focused item when the list/tree is inactive. An active list/tree has keyboard focus, an inactive does not."));
  const listHoverBackground = registerColor("list.hoverBackground", { dark: "#2A2D2E", light: "#F0F0F0", hcDark: Color.white.transparent(0.1), hcLight: Color.fromHex("#0F4A85").transparent(0.1) }, localize(1952, "List/Tree background when hovering over items using the mouse."));
  const listHoverForeground = registerColor("list.hoverForeground", null, localize(1953, "List/Tree foreground when hovering over items using the mouse."));
  const listDropOverBackground = registerColor("list.dropBackground", { dark: "#062F4A", light: "#D6EBFF", hcDark: null, hcLight: null }, localize(1954, "List/Tree drag and drop background when moving items over other items when using the mouse."));
  const listDropBetweenBackground = registerColor("list.dropBetweenBackground", { dark: iconForeground, light: iconForeground, hcDark: null, hcLight: null }, localize(1955, "List/Tree drag and drop border color when moving items between items when using the mouse."));
  const listHighlightForeground = registerColor("list.highlightForeground", { dark: "#2AAAFF", light: "#0066BF", hcDark: focusBorder, hcLight: focusBorder }, localize(1956, "List/Tree foreground color of the match highlights when searching inside the list/tree."));
  const listFocusHighlightForeground = registerColor("list.focusHighlightForeground", { dark: listHighlightForeground, light: ifDefinedThenElse(listActiveSelectionBackground, listHighlightForeground, "#BBE7FF"), hcDark: listHighlightForeground, hcLight: listHighlightForeground }, localize(1957, "List/Tree foreground color of the match highlights on actively focused items when searching inside the list/tree."));
  registerColor("list.invalidItemForeground", { dark: "#B89500", light: "#B89500", hcDark: "#B89500", hcLight: "#B5200D" }, localize(1958, "List/Tree foreground color for invalid items, for example an unresolved root in explorer."));
  registerColor("list.errorForeground", { dark: "#F88070", light: "#B01011", hcDark: null, hcLight: null }, localize(1959, "Foreground color of list items containing errors."));
  registerColor("list.warningForeground", { dark: "#CCA700", light: "#855F00", hcDark: null, hcLight: null }, localize(1960, "Foreground color of list items containing warnings."));
  const listFilterWidgetBackground = registerColor("listFilterWidget.background", { light: darken(editorWidgetBackground, 0), dark: lighten(editorWidgetBackground, 0), hcDark: editorWidgetBackground, hcLight: editorWidgetBackground }, localize(1961, "Background color of the type filter widget in lists and trees."));
  const listFilterWidgetOutline = registerColor("listFilterWidget.outline", { dark: Color.transparent, light: Color.transparent, hcDark: "#f38518", hcLight: "#007ACC" }, localize(1962, "Outline color of the type filter widget in lists and trees."));
  const listFilterWidgetNoMatchesOutline = registerColor("listFilterWidget.noMatchesOutline", { dark: "#BE1100", light: "#BE1100", hcDark: contrastBorder, hcLight: contrastBorder }, localize(1963, "Outline color of the type filter widget in lists and trees, when there are no matches."));
  const listFilterWidgetShadow = registerColor("listFilterWidget.shadow", widgetShadow, localize(1964, "Shadow color of the type filter widget in lists and trees."));
  registerColor("list.filterMatchBackground", { dark: editorFindMatchHighlight, light: editorFindMatchHighlight, hcDark: null, hcLight: null }, localize(1965, "Background color of the filtered match."));
  registerColor("list.filterMatchBorder", { dark: editorFindMatchHighlightBorder, light: editorFindMatchHighlightBorder, hcDark: contrastBorder, hcLight: activeContrastBorder }, localize(1966, "Border color of the filtered match."));
  registerColor("list.deemphasizedForeground", { dark: "#8C8C8C", light: "#8E8E90", hcDark: "#A7A8A9", hcLight: "#666666" }, localize(1967, "List/Tree foreground color for items that are deemphasized."));
  const treeIndentGuidesStroke = registerColor("tree.indentGuidesStroke", { dark: "#585858", light: "#a9a9a9", hcDark: "#a9a9a9", hcLight: "#a5a5a5" }, localize(1968, "Tree stroke color for the indentation guides."));
  const treeInactiveIndentGuidesStroke = registerColor("tree.inactiveIndentGuidesStroke", transparent(treeIndentGuidesStroke, 0.4), localize(1969, "Tree stroke color for the indentation guides that are not active."));
  const tableColumnsBorder = registerColor("tree.tableColumnsBorder", { dark: "#CCCCCC20", light: "#61616120", hcDark: null, hcLight: null }, localize(1970, "Table border color between columns."));
  const tableOddRowsBackgroundColor = registerColor("tree.tableOddRowsBackground", { dark: transparent(foreground, 0.04), light: transparent(foreground, 0.04), hcDark: null, hcLight: null }, localize(1971, "Background color for odd table rows."));
  registerColor("editorActionList.background", editorWidgetBackground, localize(1972, "Action List background color."));
  const editorActionListForeground = registerColor("editorActionList.foreground", editorWidgetForeground, localize(1973, "Action List foreground color."));
  registerColor("editorActionList.focusForeground", listActiveSelectionForeground, localize(1974, "Action List foreground color for the focused item."));
  registerColor("editorActionList.focusBackground", listActiveSelectionBackground, localize(1975, "Action List background color for the focused item."));
  const menuBorder = registerColor("menu.border", { dark: null, light: null, hcDark: contrastBorder, hcLight: contrastBorder }, localize(1976, "Border color of menus."));
  const menuForeground = registerColor("menu.foreground", selectForeground, localize(1977, "Foreground color of menu items."));
  const menuBackground = registerColor("menu.background", selectBackground, localize(1978, "Background color of menu items."));
  const menuSelectionForeground = registerColor("menu.selectionForeground", listActiveSelectionForeground, localize(1979, "Foreground color of the selected menu item in menus."));
  const menuSelectionBackground = registerColor("menu.selectionBackground", listActiveSelectionBackground, localize(1980, "Background color of the selected menu item in menus."));
  const menuSelectionBorder = registerColor("menu.selectionBorder", { dark: null, light: null, hcDark: activeContrastBorder, hcLight: activeContrastBorder }, localize(1981, "Border color of the selected menu item in menus."));
  const menuSeparatorBackground = registerColor("menu.separatorBackground", { dark: "#606060", light: "#D4D4D4", hcDark: contrastBorder, hcLight: contrastBorder }, localize(1982, "Color of a separator menu item in menus."));
  const quickInputBackground = registerColor("quickInput.background", editorWidgetBackground, localize(2010, "Quick picker background color. The quick picker widget is the container for pickers like the command palette."));
  const quickInputForeground = registerColor("quickInput.foreground", editorWidgetForeground, localize(2011, "Quick picker foreground color. The quick picker widget is the container for pickers like the command palette."));
  const quickInputTitleBackground = registerColor("quickInputTitle.background", { dark: new Color(new RGBA(255, 255, 255, 0.105)), light: new Color(new RGBA(0, 0, 0, 0.06)), hcDark: "#000000", hcLight: Color.white }, localize(2012, "Quick picker title background color. The quick picker widget is the container for pickers like the command palette."));
  const pickerGroupForeground = registerColor("pickerGroup.foreground", { dark: "#3794FF", light: "#0066BF", hcDark: Color.white, hcLight: "#0F4A85" }, localize(2013, "Quick picker color for grouping labels."));
  const pickerGroupBorder = registerColor("pickerGroup.border", { dark: "#3F3F46", light: "#CCCEDB", hcDark: Color.white, hcLight: "#0F4A85" }, localize(2014, "Quick picker color for grouping borders."));
  const _deprecatedQuickInputListFocusBackground = registerColor("quickInput.list.focusBackground", null, "", void 0, localize(2015, "Please use quickInputList.focusBackground instead"));
  const quickInputListFocusForeground = registerColor("quickInputList.focusForeground", listActiveSelectionForeground, localize(2016, "Quick picker foreground color for the focused item."));
  const quickInputListFocusIconForeground = registerColor("quickInputList.focusIconForeground", listActiveSelectionIconForeground, localize(2017, "Quick picker icon foreground color for the focused item."));
  const quickInputListFocusBackground = registerColor("quickInputList.focusBackground", { dark: oneOf(_deprecatedQuickInputListFocusBackground, listActiveSelectionBackground), light: oneOf(_deprecatedQuickInputListFocusBackground, listActiveSelectionBackground), hcDark: null, hcLight: null }, localize(2018, "Quick picker background color for the focused item."));
  registerColor("search.resultsInfoForeground", { light: foreground, dark: transparent(foreground, 0.65), hcDark: foreground, hcLight: foreground }, localize(2019, "Color of the text in the search viewlet's completion message."));
  registerColor("searchEditor.findMatchBackground", { light: transparent(editorFindMatchHighlight, 0.66), dark: transparent(editorFindMatchHighlight, 0.66), hcDark: editorFindMatchHighlight, hcLight: editorFindMatchHighlight }, localize(2020, "Color of the Search Editor query matches."));
  registerColor("searchEditor.findMatchBorder", { light: transparent(editorFindMatchHighlightBorder, 0.66), dark: transparent(editorFindMatchHighlightBorder, 0.66), hcDark: editorFindMatchHighlightBorder, hcLight: editorFindMatchHighlightBorder }, localize(2021, "Border color of the Search Editor query matches."));
  class PageCoordinates {
    constructor(x, y) {
      this.x = x;
      this.y = y;
      this._pageCoordinatesBrand = void 0;
    }
    toClientCoordinates(targetWindow) {
      return new ClientCoordinates(this.x - targetWindow.scrollX, this.y - targetWindow.scrollY);
    }
  }
  class ClientCoordinates {
    constructor(clientX, clientY) {
      this.clientX = clientX;
      this.clientY = clientY;
      this._clientCoordinatesBrand = void 0;
    }
    toPageCoordinates(targetWindow) {
      return new PageCoordinates(this.clientX + targetWindow.scrollX, this.clientY + targetWindow.scrollY);
    }
  }
  class EditorPagePosition {
    constructor(x, y, width2, height) {
      this.x = x;
      this.y = y;
      this.width = width2;
      this.height = height;
      this._editorPagePositionBrand = void 0;
    }
  }
  class CoordinatesRelativeToEditor {
    constructor(x, y) {
      this.x = x;
      this.y = y;
      this._positionRelativeToEditorBrand = void 0;
    }
  }
  function createEditorPagePosition(editorViewDomNode) {
    const editorPos = getDomNodePagePosition(editorViewDomNode);
    return new EditorPagePosition(editorPos.left, editorPos.top, editorPos.width, editorPos.height);
  }
  function createCoordinatesRelativeToEditor(editorViewDomNode, editorPagePosition, pos) {
    const scaleX = editorPagePosition.width / editorViewDomNode.offsetWidth;
    const scaleY = editorPagePosition.height / editorViewDomNode.offsetHeight;
    const relativeX = (pos.x - editorPagePosition.x) / scaleX;
    const relativeY = (pos.y - editorPagePosition.y) / scaleY;
    return new CoordinatesRelativeToEditor(relativeX, relativeY);
  }
  class EditorMouseEvent extends StandardMouseEvent {
    constructor(e, isFromPointerCapture, editorViewDomNode) {
      super(getWindow(editorViewDomNode), e);
      this._editorMouseEventBrand = void 0;
      this.isFromPointerCapture = isFromPointerCapture;
      this.pos = new PageCoordinates(this.posx, this.posy);
      this.editorPos = createEditorPagePosition(editorViewDomNode);
      this.relativePos = createCoordinatesRelativeToEditor(editorViewDomNode, this.editorPos, this.pos);
    }
  }
  class EditorMouseEventFactory {
    constructor(editorViewDomNode) {
      this._editorViewDomNode = editorViewDomNode;
    }
    _create(e) {
      return new EditorMouseEvent(e, false, this._editorViewDomNode);
    }
    onContextMenu(target, callback) {
      return addDisposableListener(target, EventType$1.CONTEXT_MENU, (e) => {
        callback(this._create(e));
      });
    }
    onMouseUp(target, callback) {
      return addDisposableListener(target, EventType$1.MOUSE_UP, (e) => {
        callback(this._create(e));
      });
    }
    onMouseDown(target, callback) {
      return addDisposableListener(target, EventType$1.MOUSE_DOWN, (e) => {
        callback(this._create(e));
      });
    }
    onPointerDown(target, callback) {
      return addDisposableListener(target, EventType$1.POINTER_DOWN, (e) => {
        callback(this._create(e), e.pointerId);
      });
    }
    onMouseLeave(target, callback) {
      return addDisposableListener(target, EventType$1.MOUSE_LEAVE, (e) => {
        callback(this._create(e));
      });
    }
    onMouseMove(target, callback) {
      return addDisposableListener(target, EventType$1.MOUSE_MOVE, (e) => callback(this._create(e)));
    }
  }
  class EditorPointerEventFactory {
    constructor(editorViewDomNode) {
      this._editorViewDomNode = editorViewDomNode;
    }
    _create(e) {
      return new EditorMouseEvent(e, false, this._editorViewDomNode);
    }
    onPointerUp(target, callback) {
      return addDisposableListener(target, "pointerup", (e) => {
        callback(this._create(e));
      });
    }
    onPointerDown(target, callback) {
      return addDisposableListener(target, EventType$1.POINTER_DOWN, (e) => {
        callback(this._create(e), e.pointerId);
      });
    }
    onPointerLeave(target, callback) {
      return addDisposableListener(target, EventType$1.POINTER_LEAVE, (e) => {
        callback(this._create(e));
      });
    }
    onPointerMove(target, callback) {
      return addDisposableListener(target, "pointermove", (e) => callback(this._create(e)));
    }
  }
  class GlobalEditorPointerMoveMonitor extends Disposable {
    constructor(editorViewDomNode) {
      super();
      this._editorViewDomNode = editorViewDomNode;
      this._globalPointerMoveMonitor = this._register(new GlobalPointerMoveMonitor());
      this._keydownListener = null;
    }
    startMonitoring(initialElement, pointerId, initialButtons, pointerMoveCallback, onStopCallback) {
      this._keydownListener = addStandardDisposableListener(initialElement.ownerDocument, "keydown", (e) => {
        const chord = e.toKeyCodeChord();
        if (chord.isModifierKey()) {
          return;
        }
        this._globalPointerMoveMonitor.stopMonitoring(true, e.browserEvent);
      }, true);
      this._globalPointerMoveMonitor.startMonitoring(initialElement, pointerId, initialButtons, (e) => {
        pointerMoveCallback(new EditorMouseEvent(e, true, this._editorViewDomNode));
      }, (e) => {
        this._keydownListener.dispose();
        onStopCallback(e);
      });
    }
    stopMonitoring() {
      this._globalPointerMoveMonitor.stopMonitoring(true);
    }
  }
  const _DynamicCssRules = class _DynamicCssRules {
    constructor(_editor) {
      this._editor = _editor;
      this._instanceId = ++_DynamicCssRules._idPool;
      this._counter = 0;
      this._rules = new DisposableMap();
      this._garbageCollectionScheduler = new RunOnceScheduler(() => this.garbageCollect(), 1e3);
    }
    dispose() {
      this._rules.dispose();
      this._garbageCollectionScheduler.dispose();
    }
    createClassNameRef(options) {
      const rule = this.getOrCreateRule(options);
      rule.increaseRefCount();
      return {
        className: rule.className,
        dispose: () => {
          rule.decreaseRefCount();
          this._garbageCollectionScheduler.schedule();
        }
      };
    }
    getOrCreateRule(properties) {
      const key = this.computeUniqueKey(properties);
      let existingRule = this._rules.get(key);
      if (!existingRule) {
        const counter = this._counter++;
        existingRule = new RefCountedCssRule(key, `dyn-rule-${this._instanceId}-${counter}`, isInShadowDOM(this._editor.getContainerDomNode()) ? this._editor.getContainerDomNode() : void 0, properties);
        this._rules.set(key, existingRule);
      }
      return existingRule;
    }
    computeUniqueKey(properties) {
      return JSON.stringify(properties);
    }
    garbageCollect() {
      for (const rule of this._rules.values()) {
        if (!rule.hasReferences()) {
          this._rules.deleteAndDispose(rule.key);
        }
      }
    }
  };
  _DynamicCssRules._idPool = 0;
  let DynamicCssRules = _DynamicCssRules;
  class RefCountedCssRule {
    constructor(key, className2, _containerElement, properties) {
      this.key = key;
      this.className = className2;
      this.properties = properties;
      this._referenceCount = 0;
      this._styleElementDisposables = new DisposableStore();
      this._styleElement = createStyleSheet(_containerElement, void 0, this._styleElementDisposables);
      this._styleElement.textContent = this.getCssText(this.className, this.properties);
    }
    getCssText(className2, properties) {
      let str = `.${className2} {`;
      for (const prop in properties) {
        const value = properties[prop];
        let cssValue;
        if (typeof value === "object") {
          cssValue = asCssVariable(value.id);
        } else {
          cssValue = value;
        }
        const cssPropName = camelToDashes(prop);
        str += `
	${cssPropName}: ${cssValue};`;
      }
      str += `
}`;
      return str;
    }
    dispose() {
      this._styleElementDisposables.dispose();
      this._styleElement = void 0;
    }
    increaseRefCount() {
      this._referenceCount++;
    }
    decreaseRefCount() {
      this._referenceCount--;
    }
    hasReferences() {
      return this._referenceCount > 0;
    }
  }
  function camelToDashes(str) {
    return str.replace(/(^[A-Z])/, ([first2]) => first2.toLowerCase()).replace(/([A-Z])/g, ([letter]) => `-${letter.toLowerCase()}`);
  }
  class ViewEventHandler extends Disposable {
    constructor() {
      super();
      this._shouldRender = true;
    }
    shouldRender() {
      return this._shouldRender;
    }
    forceShouldRender() {
      this._shouldRender = true;
    }
    setShouldRender() {
      this._shouldRender = true;
    }
    onDidRender() {
      this._shouldRender = false;
    }
    // --- begin event handlers
    onCompositionStart(e) {
      return false;
    }
    onCompositionEnd(e) {
      return false;
    }
    onConfigurationChanged(e) {
      return false;
    }
    onCursorStateChanged(e) {
      return false;
    }
    onDecorationsChanged(e) {
      return false;
    }
    onFlushed(e) {
      return false;
    }
    onFocusChanged(e) {
      return false;
    }
    onLanguageConfigurationChanged(e) {
      return false;
    }
    onLineMappingChanged(e) {
      return false;
    }
    onLinesChanged(e) {
      return false;
    }
    onLinesDeleted(e) {
      return false;
    }
    onLinesInserted(e) {
      return false;
    }
    onRevealRangeRequest(e) {
      return false;
    }
    onScrollChanged(e) {
      return false;
    }
    onThemeChanged(e) {
      return false;
    }
    onTokensChanged(e) {
      return false;
    }
    onTokensColorsChanged(e) {
      return false;
    }
    onZonesChanged(e) {
      return false;
    }
    // --- end event handlers
    handleEvents(events) {
      let shouldRender = false;
      for (let i2 = 0, len = events.length; i2 < len; i2++) {
        const e = events[i2];
        switch (e.type) {
          case 0:
            if (this.onCompositionStart(e)) {
              shouldRender = true;
            }
            break;
          case 1:
            if (this.onCompositionEnd(e)) {
              shouldRender = true;
            }
            break;
          case 2:
            if (this.onConfigurationChanged(e)) {
              shouldRender = true;
            }
            break;
          case 3:
            if (this.onCursorStateChanged(e)) {
              shouldRender = true;
            }
            break;
          case 4:
            if (this.onDecorationsChanged(e)) {
              shouldRender = true;
            }
            break;
          case 5:
            if (this.onFlushed(e)) {
              shouldRender = true;
            }
            break;
          case 6:
            if (this.onFocusChanged(e)) {
              shouldRender = true;
            }
            break;
          case 7:
            if (this.onLanguageConfigurationChanged(e)) {
              shouldRender = true;
            }
            break;
          case 8:
            if (this.onLineMappingChanged(e)) {
              shouldRender = true;
            }
            break;
          case 9:
            if (this.onLinesChanged(e)) {
              shouldRender = true;
            }
            break;
          case 10:
            if (this.onLinesDeleted(e)) {
              shouldRender = true;
            }
            break;
          case 11:
            if (this.onLinesInserted(e)) {
              shouldRender = true;
            }
            break;
          case 12:
            if (this.onRevealRangeRequest(e)) {
              shouldRender = true;
            }
            break;
          case 13:
            if (this.onScrollChanged(e)) {
              shouldRender = true;
            }
            break;
          case 15:
            if (this.onTokensChanged(e)) {
              shouldRender = true;
            }
            break;
          case 14:
            if (this.onThemeChanged(e)) {
              shouldRender = true;
            }
            break;
          case 16:
            if (this.onTokensColorsChanged(e)) {
              shouldRender = true;
            }
            break;
          case 17:
            if (this.onZonesChanged(e)) {
              shouldRender = true;
            }
            break;
          default:
            console.info("View received unknown event: ");
            console.info(e);
        }
      }
      if (shouldRender) {
        this._shouldRender = true;
      }
    }
  }
  class ViewPart extends ViewEventHandler {
    constructor(context) {
      super();
      this._context = context;
      this._context.addEventHandler(this);
    }
    dispose() {
      this._context.removeEventHandler(this);
      super.dispose();
    }
  }
  class PartFingerprints {
    static write(target, partId) {
      target.setAttribute("data-mprt", String(partId));
    }
    static read(target) {
      const r = target.getAttribute("data-mprt");
      if (r === null) {
        return 0;
      }
      return parseInt(r, 10);
    }
    static collect(child, stopAt) {
      const result = [];
      let resultLen = 0;
      while (child && child !== child.ownerDocument.body) {
        if (child === stopAt) {
          break;
        }
        if (child.nodeType === child.ELEMENT_NODE) {
          result[resultLen++] = this.read(child);
        }
        child = child.parentElement;
      }
      const r = new Uint8Array(resultLen);
      for (let i2 = 0; i2 < resultLen; i2++) {
        r[i2] = result[resultLen - i2 - 1];
      }
      return r;
    }
  }
  class RestrictedRenderingContext {
    constructor(viewLayout, viewportData) {
      this._restrictedRenderingContextBrand = void 0;
      this._viewLayout = viewLayout;
      this.viewportData = viewportData;
      this.scrollWidth = this._viewLayout.getScrollWidth();
      this.scrollHeight = this._viewLayout.getScrollHeight();
      this.visibleRange = this.viewportData.visibleRange;
      this.bigNumbersDelta = this.viewportData.bigNumbersDelta;
      const vInfo = this._viewLayout.getCurrentViewport();
      this.scrollTop = vInfo.top;
      this.scrollLeft = vInfo.left;
      this.viewportWidth = vInfo.width;
      this.viewportHeight = vInfo.height;
    }
    getScrolledTopFromAbsoluteTop(absoluteTop) {
      return absoluteTop - this.scrollTop;
    }
    getVerticalOffsetForLineNumber(lineNumber, includeViewZones) {
      return this._viewLayout.getVerticalOffsetForLineNumber(lineNumber, includeViewZones);
    }
    getVerticalOffsetAfterLineNumber(lineNumber, includeViewZones) {
      return this._viewLayout.getVerticalOffsetAfterLineNumber(lineNumber, includeViewZones);
    }
    getLineHeightForLineNumber(lineNumber) {
      return this._viewLayout.getLineHeightForLineNumber(lineNumber);
    }
    getDecorationsInViewport() {
      return this.viewportData.getDecorationsInViewport();
    }
  }
  class RenderingContext extends RestrictedRenderingContext {
    constructor(viewLayout, viewportData, viewLines, viewLinesGpu) {
      super(viewLayout, viewportData);
      this._renderingContextBrand = void 0;
      this._viewLines = viewLines;
      this._viewLinesGpu = viewLinesGpu;
    }
    linesVisibleRangesForRange(range2, includeNewLines) {
      const domRanges = this._viewLines.linesVisibleRangesForRange(range2, includeNewLines);
      if (!this._viewLinesGpu) {
        return domRanges ?? null;
      }
      const gpuRanges = this._viewLinesGpu.linesVisibleRangesForRange(range2, includeNewLines);
      if (!domRanges) {
        return gpuRanges;
      }
      if (!gpuRanges) {
        return domRanges;
      }
      return domRanges.concat(gpuRanges).sort((a, b) => a.lineNumber - b.lineNumber);
    }
    visibleRangeForPosition(position) {
      return this._viewLines.visibleRangeForPosition(position) ?? this._viewLinesGpu?.visibleRangeForPosition(position) ?? null;
    }
  }
  class LineVisibleRanges {
    constructor(outsideRenderedLine, lineNumber, ranges, continuesOnNextLine) {
      this.outsideRenderedLine = outsideRenderedLine;
      this.lineNumber = lineNumber;
      this.ranges = ranges;
      this.continuesOnNextLine = continuesOnNextLine;
    }
  }
  class HorizontalRange {
    static from(ranges) {
      const result = new Array(ranges.length);
      for (let i2 = 0, len = ranges.length; i2 < len; i2++) {
        const range2 = ranges[i2];
        result[i2] = new HorizontalRange(range2.left, range2.width);
      }
      return result;
    }
    constructor(left, width2) {
      this._horizontalRangeBrand = void 0;
      this.left = Math.round(left);
      this.width = Math.round(width2);
    }
    toString() {
      return `[${this.left},${this.width}]`;
    }
  }
  class FloatHorizontalRange {
    constructor(left, width2) {
      this._floatHorizontalRangeBrand = void 0;
      this.left = left;
      this.width = width2;
    }
    toString() {
      return `[${this.left},${this.width}]`;
    }
    static compare(a, b) {
      return a.left - b.left;
    }
  }
  class HorizontalPosition {
    constructor(outsideRenderedLine, left) {
      this.outsideRenderedLine = outsideRenderedLine;
      this.originalLeft = left;
      this.left = Math.round(this.originalLeft);
    }
  }
  class VisibleRanges {
    constructor(outsideRenderedLine, ranges) {
      this.outsideRenderedLine = outsideRenderedLine;
      this.ranges = ranges;
    }
  }
  class RangeUtil {
    static _createRange() {
      if (!this._handyReadyRange) {
        this._handyReadyRange = document.createRange();
      }
      return this._handyReadyRange;
    }
    static _detachRange(range2, endNode) {
      range2.selectNodeContents(endNode);
    }
    static _readClientRects(startElement, startOffset, endElement, endOffset, endNode) {
      const range2 = this._createRange();
      try {
        range2.setStart(startElement, startOffset);
        range2.setEnd(endElement, endOffset);
        return range2.getClientRects();
      } catch (e) {
        return null;
      } finally {
        this._detachRange(range2, endNode);
      }
    }
    static _mergeAdjacentRanges(ranges) {
      if (ranges.length === 1) {
        return ranges;
      }
      ranges.sort(FloatHorizontalRange.compare);
      const result = [];
      let resultLen = 0;
      let prev = ranges[0];
      for (let i2 = 1, len = ranges.length; i2 < len; i2++) {
        const range2 = ranges[i2];
        if (prev.left + prev.width + 0.9 >= range2.left) {
          prev.width = Math.max(prev.width, range2.left + range2.width - prev.left);
        } else {
          result[resultLen++] = prev;
          prev = range2;
        }
      }
      result[resultLen++] = prev;
      return result;
    }
    static _createHorizontalRangesFromClientRects(clientRects, clientRectDeltaLeft, clientRectScale) {
      if (!clientRects || clientRects.length === 0) {
        return null;
      }
      const result = [];
      for (let i2 = 0, len = clientRects.length; i2 < len; i2++) {
        const clientRect = clientRects[i2];
        result[i2] = new FloatHorizontalRange(Math.max(0, (clientRect.left - clientRectDeltaLeft) / clientRectScale), clientRect.width / clientRectScale);
      }
      return this._mergeAdjacentRanges(result);
    }
    static readHorizontalRanges(domNode, startChildIndex, startOffset, endChildIndex, endOffset, context) {
      const min = 0;
      const max = domNode.children.length - 1;
      if (min > max) {
        return null;
      }
      startChildIndex = Math.min(max, Math.max(min, startChildIndex));
      endChildIndex = Math.min(max, Math.max(min, endChildIndex));
      if (startChildIndex === endChildIndex && startOffset === endOffset && startOffset === 0 && !domNode.children[startChildIndex].firstChild) {
        const clientRects2 = domNode.children[startChildIndex].getClientRects();
        context.markDidDomLayout();
        return this._createHorizontalRangesFromClientRects(clientRects2, context.clientRectDeltaLeft, context.clientRectScale);
      }
      if (startChildIndex !== endChildIndex) {
        if (endChildIndex > 0 && endOffset === 0) {
          endChildIndex--;
          endOffset = 1073741824;
        }
      }
      let startElement = domNode.children[startChildIndex].firstChild;
      let endElement = domNode.children[endChildIndex].firstChild;
      if (!startElement || !endElement) {
        if (!startElement && startOffset === 0 && startChildIndex > 0) {
          startElement = domNode.children[startChildIndex - 1].firstChild;
          startOffset = 1073741824;
        }
        if (!endElement && endOffset === 0 && endChildIndex > 0) {
          endElement = domNode.children[endChildIndex - 1].firstChild;
          endOffset = 1073741824;
        }
      }
      if (!startElement || !endElement) {
        return null;
      }
      startOffset = Math.min(startElement.textContent.length, Math.max(0, startOffset));
      endOffset = Math.min(endElement.textContent.length, Math.max(0, endOffset));
      const clientRects = this._readClientRects(startElement, startOffset, endElement, endOffset, context.endNode);
      context.markDidDomLayout();
      return this._createHorizontalRangesFromClientRects(clientRects, context.clientRectDeltaLeft, context.clientRectScale);
    }
  }
  class LineDecoration {
    constructor(startColumn, endColumn, className2, type) {
      this.startColumn = startColumn;
      this.endColumn = endColumn;
      this.className = className2;
      this.type = type;
      this._lineDecorationBrand = void 0;
    }
    static _equals(a, b) {
      return a.startColumn === b.startColumn && a.endColumn === b.endColumn && a.className === b.className && a.type === b.type;
    }
    static equalsArr(a, b) {
      const aLen = a.length;
      const bLen = b.length;
      if (aLen !== bLen) {
        return false;
      }
      for (let i2 = 0; i2 < aLen; i2++) {
        if (!LineDecoration._equals(a[i2], b[i2])) {
          return false;
        }
      }
      return true;
    }
    static extractWrapped(arr, startOffset, endOffset) {
      if (arr.length === 0) {
        return arr;
      }
      const startColumn = startOffset + 1;
      const endColumn = endOffset + 1;
      const lineLength = endOffset - startOffset;
      const r = [];
      let rLength = 0;
      for (const dec of arr) {
        if (dec.endColumn <= startColumn || dec.startColumn >= endColumn) {
          continue;
        }
        r[rLength++] = new LineDecoration(Math.max(1, dec.startColumn - startColumn + 1), Math.min(lineLength + 1, dec.endColumn - startColumn + 1), dec.className, dec.type);
      }
      return r;
    }
    static filter(lineDecorations, lineNumber, minLineColumn, maxLineColumn) {
      if (lineDecorations.length === 0) {
        return [];
      }
      const result = [];
      let resultLen = 0;
      for (let i2 = 0, len = lineDecorations.length; i2 < len; i2++) {
        const d = lineDecorations[i2];
        const range2 = d.range;
        if (range2.endLineNumber < lineNumber || range2.startLineNumber > lineNumber) {
          continue;
        }
        if (range2.isEmpty() && (d.type === 0 || d.type === 3)) {
          continue;
        }
        const startColumn = range2.startLineNumber === lineNumber ? range2.startColumn : minLineColumn;
        const endColumn = range2.endLineNumber === lineNumber ? range2.endColumn : maxLineColumn;
        result[resultLen++] = new LineDecoration(startColumn, endColumn, d.inlineClassName, d.type);
      }
      return result;
    }
    static _typeCompare(a, b) {
      const ORDER = [2, 0, 1, 3];
      return ORDER[a] - ORDER[b];
    }
    static compare(a, b) {
      if (a.startColumn !== b.startColumn) {
        return a.startColumn - b.startColumn;
      }
      if (a.endColumn !== b.endColumn) {
        return a.endColumn - b.endColumn;
      }
      const typeCmp = LineDecoration._typeCompare(a.type, b.type);
      if (typeCmp !== 0) {
        return typeCmp;
      }
      if (a.className !== b.className) {
        return a.className < b.className ? -1 : 1;
      }
      return 0;
    }
  }
  class DecorationSegment {
    constructor(startOffset, endOffset, className2, metadata) {
      this.startOffset = startOffset;
      this.endOffset = endOffset;
      this.className = className2;
      this.metadata = metadata;
    }
  }
  class Stack {
    constructor() {
      this.stopOffsets = [];
      this.classNames = [];
      this.metadata = [];
      this.count = 0;
    }
    static _metadata(metadata) {
      let result = 0;
      for (let i2 = 0, len = metadata.length; i2 < len; i2++) {
        result |= metadata[i2];
      }
      return result;
    }
    consumeLowerThan(maxStopOffset, nextStartOffset, result) {
      while (this.count > 0 && this.stopOffsets[0] < maxStopOffset) {
        let i2 = 0;
        while (i2 + 1 < this.count && this.stopOffsets[i2] === this.stopOffsets[i2 + 1]) {
          i2++;
        }
        result.push(new DecorationSegment(nextStartOffset, this.stopOffsets[i2], this.classNames.join(" "), Stack._metadata(this.metadata)));
        nextStartOffset = this.stopOffsets[i2] + 1;
        this.stopOffsets.splice(0, i2 + 1);
        this.classNames.splice(0, i2 + 1);
        this.metadata.splice(0, i2 + 1);
        this.count -= i2 + 1;
      }
      if (this.count > 0 && nextStartOffset < maxStopOffset) {
        result.push(new DecorationSegment(nextStartOffset, maxStopOffset - 1, this.classNames.join(" "), Stack._metadata(this.metadata)));
        nextStartOffset = maxStopOffset;
      }
      return nextStartOffset;
    }
    insert(stopOffset, className2, metadata) {
      if (this.count === 0 || this.stopOffsets[this.count - 1] <= stopOffset) {
        this.stopOffsets.push(stopOffset);
        this.classNames.push(className2);
        this.metadata.push(metadata);
      } else {
        for (let i2 = 0; i2 < this.count; i2++) {
          if (this.stopOffsets[i2] >= stopOffset) {
            this.stopOffsets.splice(i2, 0, stopOffset);
            this.classNames.splice(i2, 0, className2);
            this.metadata.splice(i2, 0, metadata);
            break;
          }
        }
      }
      this.count++;
      return;
    }
  }
  class LineDecorationsNormalizer {
    /**
     * Normalize line decorations. Overlapping decorations will generate multiple segments
     */
    static normalize(lineContent, lineDecorations) {
      if (lineDecorations.length === 0) {
        return [];
      }
      const result = [];
      const stack = new Stack();
      let nextStartOffset = 0;
      for (let i2 = 0, len = lineDecorations.length; i2 < len; i2++) {
        const d = lineDecorations[i2];
        let startColumn = d.startColumn;
        let endColumn = d.endColumn;
        const className2 = d.className;
        const metadata = d.type === 1 ? 2 : d.type === 2 ? 4 : 0;
        if (startColumn > 1) {
          const charCodeBefore = lineContent.charCodeAt(startColumn - 2);
          if (isHighSurrogate(charCodeBefore)) {
            startColumn--;
          }
        }
        if (endColumn > 1) {
          const charCodeBefore = lineContent.charCodeAt(endColumn - 2);
          if (isHighSurrogate(charCodeBefore)) {
            endColumn--;
          }
        }
        const currentStartOffset = startColumn - 1;
        const currentEndOffset = endColumn - 2;
        nextStartOffset = stack.consumeLowerThan(currentStartOffset, nextStartOffset, result);
        if (stack.count === 0) {
          nextStartOffset = currentStartOffset;
        }
        stack.insert(currentEndOffset, className2, metadata);
      }
      stack.consumeLowerThan(1073741824, nextStartOffset, result);
      return result;
    }
  }
  class LinePart {
    constructor(endIndex, type, metadata, containsRTL2) {
      this.endIndex = endIndex;
      this.type = type;
      this.metadata = metadata;
      this.containsRTL = containsRTL2;
      this._linePartBrand = void 0;
    }
    isWhitespace() {
      return this.metadata & 1 ? true : false;
    }
    isPseudoAfter() {
      return this.metadata & 4 ? true : false;
    }
  }
  class RenderLineInput {
    get isLTR() {
      return !this.containsRTL && this.textDirection !== TextDirection$1.RTL;
    }
    constructor(useMonospaceOptimizations, canUseHalfwidthRightwardsArrow, lineContent, continuesWithWrappedLine, isBasicASCII2, containsRTL2, fauxIndentLength, lineTokens, lineDecorations, tabSize, startVisibleColumn, spaceWidth, middotWidth, wsmiddotWidth, stopRenderingLineAfter, renderWhitespace, renderControlCharacters, fontLigatures, selectionsOnLine, textDirection, verticalScrollbarSize, renderNewLineWhenEmpty = false) {
      this.useMonospaceOptimizations = useMonospaceOptimizations;
      this.canUseHalfwidthRightwardsArrow = canUseHalfwidthRightwardsArrow;
      this.lineContent = lineContent;
      this.continuesWithWrappedLine = continuesWithWrappedLine;
      this.isBasicASCII = isBasicASCII2;
      this.containsRTL = containsRTL2;
      this.fauxIndentLength = fauxIndentLength;
      this.lineTokens = lineTokens;
      this.lineDecorations = lineDecorations.sort(LineDecoration.compare);
      this.tabSize = tabSize;
      this.startVisibleColumn = startVisibleColumn;
      this.spaceWidth = spaceWidth;
      this.stopRenderingLineAfter = stopRenderingLineAfter;
      this.renderWhitespace = renderWhitespace === "all" ? 4 : renderWhitespace === "boundary" ? 1 : renderWhitespace === "selection" ? 2 : renderWhitespace === "trailing" ? 3 : 0;
      this.renderControlCharacters = renderControlCharacters;
      this.fontLigatures = fontLigatures;
      this.selectionsOnLine = selectionsOnLine && selectionsOnLine.sort((a, b) => a.start < b.start ? -1 : 1);
      this.renderNewLineWhenEmpty = renderNewLineWhenEmpty;
      this.textDirection = textDirection;
      this.verticalScrollbarSize = verticalScrollbarSize;
      const wsmiddotDiff = Math.abs(wsmiddotWidth - spaceWidth);
      const middotDiff = Math.abs(middotWidth - spaceWidth);
      if (wsmiddotDiff < middotDiff) {
        this.renderSpaceWidth = wsmiddotWidth;
        this.renderSpaceCharCode = 11825;
      } else {
        this.renderSpaceWidth = middotWidth;
        this.renderSpaceCharCode = 183;
      }
    }
    sameSelection(otherSelections) {
      if (this.selectionsOnLine === null) {
        return otherSelections === null;
      }
      if (otherSelections === null) {
        return false;
      }
      if (otherSelections.length !== this.selectionsOnLine.length) {
        return false;
      }
      for (let i2 = 0; i2 < this.selectionsOnLine.length; i2++) {
        if (!this.selectionsOnLine[i2].equals(otherSelections[i2])) {
          return false;
        }
      }
      return true;
    }
    equals(other) {
      return this.useMonospaceOptimizations === other.useMonospaceOptimizations && this.canUseHalfwidthRightwardsArrow === other.canUseHalfwidthRightwardsArrow && this.lineContent === other.lineContent && this.continuesWithWrappedLine === other.continuesWithWrappedLine && this.isBasicASCII === other.isBasicASCII && this.containsRTL === other.containsRTL && this.fauxIndentLength === other.fauxIndentLength && this.tabSize === other.tabSize && this.startVisibleColumn === other.startVisibleColumn && this.spaceWidth === other.spaceWidth && this.renderSpaceWidth === other.renderSpaceWidth && this.renderSpaceCharCode === other.renderSpaceCharCode && this.stopRenderingLineAfter === other.stopRenderingLineAfter && this.renderWhitespace === other.renderWhitespace && this.renderControlCharacters === other.renderControlCharacters && this.fontLigatures === other.fontLigatures && LineDecoration.equalsArr(this.lineDecorations, other.lineDecorations) && this.lineTokens.equals(other.lineTokens) && this.sameSelection(other.selectionsOnLine) && this.textDirection === other.textDirection && this.verticalScrollbarSize === other.verticalScrollbarSize && this.renderNewLineWhenEmpty === other.renderNewLineWhenEmpty;
    }
  }
  class DomPosition {
    constructor(partIndex, charIndex) {
      this.partIndex = partIndex;
      this.charIndex = charIndex;
    }
  }
  class CharacterMapping {
    static getPartIndex(partData) {
      return (partData & 4294901760) >>> 16;
    }
    static getCharIndex(partData) {
      return (partData & 65535) >>> 0;
    }
    constructor(length, partCount) {
      this.length = length;
      this._data = new Uint32Array(this.length);
      this._horizontalOffset = new Uint32Array(this.length);
    }
    setColumnInfo(column, partIndex, charIndex, horizontalOffset) {
      const partData = (partIndex << 16 | charIndex << 0) >>> 0;
      this._data[column - 1] = partData;
      this._horizontalOffset[column - 1] = horizontalOffset;
    }
    getHorizontalOffset(column) {
      if (this._horizontalOffset.length === 0) {
        return 0;
      }
      return this._horizontalOffset[column - 1];
    }
    charOffsetToPartData(charOffset) {
      if (this.length === 0) {
        return 0;
      }
      if (charOffset < 0) {
        return this._data[0];
      }
      if (charOffset >= this.length) {
        return this._data[this.length - 1];
      }
      return this._data[charOffset];
    }
    getDomPosition(column) {
      const partData = this.charOffsetToPartData(column - 1);
      const partIndex = CharacterMapping.getPartIndex(partData);
      const charIndex = CharacterMapping.getCharIndex(partData);
      return new DomPosition(partIndex, charIndex);
    }
    getColumn(domPosition, partLength) {
      const charOffset = this.partDataToCharOffset(domPosition.partIndex, partLength, domPosition.charIndex);
      return charOffset + 1;
    }
    partDataToCharOffset(partIndex, partLength, charIndex) {
      if (this.length === 0) {
        return 0;
      }
      const searchEntry = (partIndex << 16 | charIndex << 0) >>> 0;
      let min = 0;
      let max = this.length - 1;
      while (min + 1 < max) {
        const mid = min + max >>> 1;
        const midEntry = this._data[mid];
        if (midEntry === searchEntry) {
          return mid;
        } else if (midEntry > searchEntry) {
          max = mid;
        } else {
          min = mid;
        }
      }
      if (min === max) {
        return min;
      }
      const minEntry = this._data[min];
      const maxEntry = this._data[max];
      if (minEntry === searchEntry) {
        return min;
      }
      if (maxEntry === searchEntry) {
        return max;
      }
      const minPartIndex = CharacterMapping.getPartIndex(minEntry);
      const minCharIndex = CharacterMapping.getCharIndex(minEntry);
      const maxPartIndex = CharacterMapping.getPartIndex(maxEntry);
      let maxCharIndex;
      if (minPartIndex !== maxPartIndex) {
        maxCharIndex = partLength;
      } else {
        maxCharIndex = CharacterMapping.getCharIndex(maxEntry);
      }
      const minEntryDistance = charIndex - minCharIndex;
      const maxEntryDistance = maxCharIndex - charIndex;
      if (minEntryDistance <= maxEntryDistance) {
        return min;
      }
      return max;
    }
  }
  class RenderLineOutput {
    constructor(characterMapping, containsForeignElements) {
      this._renderLineOutputBrand = void 0;
      this.characterMapping = characterMapping;
      this.containsForeignElements = containsForeignElements;
    }
  }
  function renderViewLine(input, sb) {
    if (input.lineContent.length === 0) {
      if (input.lineDecorations.length > 0) {
        sb.appendString(`<span>`);
        let beforeCount = 0;
        let afterCount = 0;
        let containsForeignElements = 0;
        for (const lineDecoration of input.lineDecorations) {
          if (lineDecoration.type === 1 || lineDecoration.type === 2) {
            sb.appendString(`<span class="`);
            sb.appendString(lineDecoration.className);
            sb.appendString(`"></span>`);
            if (lineDecoration.type === 1) {
              containsForeignElements |= 1;
              beforeCount++;
            }
            if (lineDecoration.type === 2) {
              containsForeignElements |= 2;
              afterCount++;
            }
          }
        }
        sb.appendString(`</span>`);
        const characterMapping = new CharacterMapping(1, beforeCount + afterCount);
        characterMapping.setColumnInfo(1, beforeCount, 0, 0);
        return new RenderLineOutput(characterMapping, containsForeignElements);
      }
      if (input.renderNewLineWhenEmpty) {
        sb.appendString("<span><span>\n</span></span>");
      } else {
        sb.appendString("<span><span></span></span>");
      }
      return new RenderLineOutput(
        new CharacterMapping(0, 0),
        0
        /* ForeignElementType.None */
      );
    }
    return _renderLine(resolveRenderLineInput(input), sb);
  }
  class RenderLineOutput2 {
    constructor(characterMapping, html2, containsForeignElements) {
      this.characterMapping = characterMapping;
      this.html = html2;
      this.containsForeignElements = containsForeignElements;
    }
  }
  function renderViewLine2(input) {
    const sb = new StringBuilder(1e4);
    const out = renderViewLine(input, sb);
    return new RenderLineOutput2(out.characterMapping, sb.build(), out.containsForeignElements);
  }
  class ResolvedRenderLineInput {
    constructor(fontIsMonospace, canUseHalfwidthRightwardsArrow, lineContent, len, isOverflowing, overflowingCharCount, parts, containsForeignElements, fauxIndentLength, tabSize, startVisibleColumn, spaceWidth, renderSpaceCharCode, renderWhitespace, renderControlCharacters) {
      this.fontIsMonospace = fontIsMonospace;
      this.canUseHalfwidthRightwardsArrow = canUseHalfwidthRightwardsArrow;
      this.lineContent = lineContent;
      this.len = len;
      this.isOverflowing = isOverflowing;
      this.overflowingCharCount = overflowingCharCount;
      this.parts = parts;
      this.containsForeignElements = containsForeignElements;
      this.fauxIndentLength = fauxIndentLength;
      this.tabSize = tabSize;
      this.startVisibleColumn = startVisibleColumn;
      this.spaceWidth = spaceWidth;
      this.renderSpaceCharCode = renderSpaceCharCode;
      this.renderWhitespace = renderWhitespace;
      this.renderControlCharacters = renderControlCharacters;
    }
  }
  function resolveRenderLineInput(input) {
    const lineContent = input.lineContent;
    let isOverflowing;
    let overflowingCharCount;
    let len;
    if (input.stopRenderingLineAfter !== -1 && input.stopRenderingLineAfter < lineContent.length) {
      isOverflowing = true;
      overflowingCharCount = lineContent.length - input.stopRenderingLineAfter;
      len = input.stopRenderingLineAfter;
    } else {
      isOverflowing = false;
      overflowingCharCount = 0;
      len = lineContent.length;
    }
    let tokens = transformAndRemoveOverflowing(lineContent, input.containsRTL, input.lineTokens, input.fauxIndentLength, len);
    if (input.renderControlCharacters && !input.isBasicASCII) {
      tokens = extractControlCharacters(lineContent, tokens);
    }
    if (input.renderWhitespace === 4 || input.renderWhitespace === 1 || input.renderWhitespace === 2 && !!input.selectionsOnLine || input.renderWhitespace === 3 && !input.continuesWithWrappedLine) {
      tokens = _applyRenderWhitespace(input, lineContent, len, tokens);
    }
    let containsForeignElements = 0;
    if (input.lineDecorations.length > 0) {
      for (let i2 = 0, len2 = input.lineDecorations.length; i2 < len2; i2++) {
        const lineDecoration = input.lineDecorations[i2];
        if (lineDecoration.type === 3) {
          containsForeignElements |= 1;
        } else if (lineDecoration.type === 1) {
          containsForeignElements |= 1;
        } else if (lineDecoration.type === 2) {
          containsForeignElements |= 2;
        }
      }
      tokens = _applyInlineDecorations(lineContent, len, tokens, input.lineDecorations);
    }
    if (!input.containsRTL) {
      tokens = splitLargeTokens(lineContent, tokens, !input.isBasicASCII || input.fontLigatures);
    } else {
      tokens = splitLeadingWhitespaceFromRTL(lineContent, tokens);
    }
    return new ResolvedRenderLineInput(input.useMonospaceOptimizations, input.canUseHalfwidthRightwardsArrow, lineContent, len, isOverflowing, overflowingCharCount, tokens, containsForeignElements, input.fauxIndentLength, input.tabSize, input.startVisibleColumn, input.spaceWidth, input.renderSpaceCharCode, input.renderWhitespace, input.renderControlCharacters);
  }
  function transformAndRemoveOverflowing(lineContent, lineContainsRTL, tokens, fauxIndentLength, len) {
    const result = [];
    let resultLen = 0;
    if (fauxIndentLength > 0) {
      result[resultLen++] = new LinePart(fauxIndentLength, "", 0, false);
    }
    let startOffset = fauxIndentLength;
    for (let tokenIndex = 0, tokensLen = tokens.getCount(); tokenIndex < tokensLen; tokenIndex++) {
      const endIndex = tokens.getEndOffset(tokenIndex);
      if (endIndex <= fauxIndentLength) {
        continue;
      }
      const type = tokens.getClassName(tokenIndex);
      if (endIndex >= len) {
        const tokenContainsRTL2 = lineContainsRTL ? containsRTL(lineContent.substring(startOffset, len)) : false;
        result[resultLen++] = new LinePart(len, type, 0, tokenContainsRTL2);
        break;
      }
      const tokenContainsRTL = lineContainsRTL ? containsRTL(lineContent.substring(startOffset, endIndex)) : false;
      result[resultLen++] = new LinePart(endIndex, type, 0, tokenContainsRTL);
      startOffset = endIndex;
    }
    return result;
  }
  function splitLargeTokens(lineContent, tokens, onlyAtSpaces) {
    let lastTokenEndIndex = 0;
    const result = [];
    let resultLen = 0;
    if (onlyAtSpaces) {
      for (let i2 = 0, len = tokens.length; i2 < len; i2++) {
        const token = tokens[i2];
        const tokenEndIndex = token.endIndex;
        if (lastTokenEndIndex + 50 < tokenEndIndex) {
          const tokenType = token.type;
          const tokenMetadata = token.metadata;
          const tokenContainsRTL = token.containsRTL;
          let lastSpaceOffset = -1;
          let currTokenStart = lastTokenEndIndex;
          for (let j = lastTokenEndIndex; j < tokenEndIndex; j++) {
            if (lineContent.charCodeAt(j) === 32) {
              lastSpaceOffset = j;
            }
            if (lastSpaceOffset !== -1 && j - currTokenStart >= 50) {
              result[resultLen++] = new LinePart(lastSpaceOffset + 1, tokenType, tokenMetadata, tokenContainsRTL);
              currTokenStart = lastSpaceOffset + 1;
              lastSpaceOffset = -1;
            }
          }
          if (currTokenStart !== tokenEndIndex) {
            result[resultLen++] = new LinePart(tokenEndIndex, tokenType, tokenMetadata, tokenContainsRTL);
          }
        } else {
          result[resultLen++] = token;
        }
        lastTokenEndIndex = tokenEndIndex;
      }
    } else {
      for (let i2 = 0, len = tokens.length; i2 < len; i2++) {
        const token = tokens[i2];
        const tokenEndIndex = token.endIndex;
        const diff = tokenEndIndex - lastTokenEndIndex;
        if (diff > 50) {
          const tokenType = token.type;
          const tokenMetadata = token.metadata;
          const tokenContainsRTL = token.containsRTL;
          const piecesCount = Math.ceil(
            diff / 50
            /* Constants.LongToken */
          );
          for (let j = 1; j < piecesCount; j++) {
            const pieceEndIndex = lastTokenEndIndex + j * 50;
            result[resultLen++] = new LinePart(pieceEndIndex, tokenType, tokenMetadata, tokenContainsRTL);
          }
          result[resultLen++] = new LinePart(tokenEndIndex, tokenType, tokenMetadata, tokenContainsRTL);
        } else {
          result[resultLen++] = token;
        }
        lastTokenEndIndex = tokenEndIndex;
      }
    }
    return result;
  }
  function splitLeadingWhitespaceFromRTL(lineContent, tokens) {
    if (tokens.length === 0) {
      return tokens;
    }
    const firstToken = tokens[0];
    if (!firstToken.containsRTL) {
      return tokens;
    }
    const firstTokenEndIndex = firstToken.endIndex;
    let firstNonWhitespaceIndex2 = 0;
    for (let i2 = 0; i2 < firstTokenEndIndex; i2++) {
      const charCode = lineContent.charCodeAt(i2);
      if (charCode !== 32 && charCode !== 9) {
        firstNonWhitespaceIndex2 = i2;
        break;
      }
    }
    if (firstNonWhitespaceIndex2 === 0) {
      return tokens;
    }
    const result = [];
    result.push(new LinePart(firstNonWhitespaceIndex2, firstToken.type, firstToken.metadata, false));
    result.push(new LinePart(firstTokenEndIndex, firstToken.type, firstToken.metadata, firstToken.containsRTL));
    for (let i2 = 1; i2 < tokens.length; i2++) {
      result.push(tokens[i2]);
    }
    return result;
  }
  function isControlCharacter(charCode) {
    if (charCode < 32) {
      return charCode !== 9;
    }
    if (charCode === 127) {
      return true;
    }
    if (charCode >= 8234 && charCode <= 8238 || charCode >= 8294 && charCode <= 8297 || charCode >= 8206 && charCode <= 8207 || charCode === 1564) {
      return true;
    }
    return false;
  }
  function extractControlCharacters(lineContent, tokens) {
    const result = [];
    let lastLinePart = new LinePart(0, "", 0, false);
    let charOffset = 0;
    for (const token of tokens) {
      const tokenEndIndex = token.endIndex;
      for (; charOffset < tokenEndIndex; charOffset++) {
        const charCode = lineContent.charCodeAt(charOffset);
        if (isControlCharacter(charCode)) {
          if (charOffset > lastLinePart.endIndex) {
            lastLinePart = new LinePart(charOffset, token.type, token.metadata, token.containsRTL);
            result.push(lastLinePart);
          }
          lastLinePart = new LinePart(charOffset + 1, "mtkcontrol", token.metadata, false);
          result.push(lastLinePart);
        }
      }
      if (charOffset > lastLinePart.endIndex) {
        lastLinePart = new LinePart(tokenEndIndex, token.type, token.metadata, token.containsRTL);
        result.push(lastLinePart);
      }
    }
    return result;
  }
  function _applyRenderWhitespace(input, lineContent, len, tokens) {
    const continuesWithWrappedLine = input.continuesWithWrappedLine;
    const fauxIndentLength = input.fauxIndentLength;
    const tabSize = input.tabSize;
    const startVisibleColumn = input.startVisibleColumn;
    const useMonospaceOptimizations = input.useMonospaceOptimizations;
    const selections = input.selectionsOnLine;
    const onlyBoundary = input.renderWhitespace === 1;
    const onlyTrailing = input.renderWhitespace === 3;
    const generateLinePartForEachWhitespace = input.renderSpaceWidth !== input.spaceWidth;
    const result = [];
    let resultLen = 0;
    let tokenIndex = 0;
    let tokenType = tokens[tokenIndex].type;
    let tokenContainsRTL = tokens[tokenIndex].containsRTL;
    let tokenEndIndex = tokens[tokenIndex].endIndex;
    const tokensLength = tokens.length;
    let lineIsEmptyOrWhitespace = false;
    let firstNonWhitespaceIndex$1 = firstNonWhitespaceIndex(lineContent);
    let lastNonWhitespaceIndex$1;
    if (firstNonWhitespaceIndex$1 === -1) {
      lineIsEmptyOrWhitespace = true;
      firstNonWhitespaceIndex$1 = len;
      lastNonWhitespaceIndex$1 = len;
    } else {
      lastNonWhitespaceIndex$1 = lastNonWhitespaceIndex(lineContent);
    }
    let wasInWhitespace = false;
    let currentSelectionIndex = 0;
    let currentSelection = selections && selections[currentSelectionIndex];
    let tmpIndent = startVisibleColumn % tabSize;
    for (let charIndex = fauxIndentLength; charIndex < len; charIndex++) {
      const chCode = lineContent.charCodeAt(charIndex);
      if (currentSelection && currentSelection.endExclusive <= charIndex) {
        currentSelectionIndex++;
        currentSelection = selections && selections[currentSelectionIndex];
      }
      let isInWhitespace;
      if (charIndex < firstNonWhitespaceIndex$1 || charIndex > lastNonWhitespaceIndex$1) {
        isInWhitespace = true;
      } else if (chCode === 9) {
        isInWhitespace = true;
      } else if (chCode === 32) {
        if (onlyBoundary) {
          if (wasInWhitespace) {
            isInWhitespace = true;
          } else {
            const nextChCode = charIndex + 1 < len ? lineContent.charCodeAt(charIndex + 1) : 0;
            isInWhitespace = nextChCode === 32 || nextChCode === 9;
          }
        } else {
          isInWhitespace = true;
        }
      } else {
        isInWhitespace = false;
      }
      if (isInWhitespace && selections) {
        isInWhitespace = !!currentSelection && currentSelection.start <= charIndex && charIndex < currentSelection.endExclusive;
      }
      if (isInWhitespace && onlyTrailing) {
        isInWhitespace = lineIsEmptyOrWhitespace || charIndex > lastNonWhitespaceIndex$1;
      }
      if (isInWhitespace && tokenContainsRTL) {
        if (charIndex >= firstNonWhitespaceIndex$1 && charIndex <= lastNonWhitespaceIndex$1) {
          isInWhitespace = false;
        }
      }
      if (wasInWhitespace) {
        if (!isInWhitespace || !useMonospaceOptimizations && tmpIndent >= tabSize) {
          if (generateLinePartForEachWhitespace) {
            const lastEndIndex = resultLen > 0 ? result[resultLen - 1].endIndex : fauxIndentLength;
            for (let i2 = lastEndIndex + 1; i2 <= charIndex; i2++) {
              result[resultLen++] = new LinePart(i2, "mtkw", 1, false);
            }
          } else {
            result[resultLen++] = new LinePart(charIndex, "mtkw", 1, false);
          }
          tmpIndent = tmpIndent % tabSize;
        }
      } else {
        if (charIndex === tokenEndIndex || isInWhitespace && charIndex > fauxIndentLength) {
          result[resultLen++] = new LinePart(charIndex, tokenType, 0, tokenContainsRTL);
          tmpIndent = tmpIndent % tabSize;
        }
      }
      if (chCode === 9) {
        tmpIndent = tabSize;
      } else if (isFullWidthCharacter(chCode)) {
        tmpIndent += 2;
      } else {
        tmpIndent++;
      }
      wasInWhitespace = isInWhitespace;
      while (charIndex === tokenEndIndex) {
        tokenIndex++;
        if (tokenIndex < tokensLength) {
          tokenType = tokens[tokenIndex].type;
          tokenContainsRTL = tokens[tokenIndex].containsRTL;
          tokenEndIndex = tokens[tokenIndex].endIndex;
        } else {
          break;
        }
      }
    }
    let generateWhitespace = false;
    if (wasInWhitespace) {
      if (continuesWithWrappedLine && onlyBoundary) {
        const lastCharCode = len > 0 ? lineContent.charCodeAt(len - 1) : 0;
        const prevCharCode = len > 1 ? lineContent.charCodeAt(len - 2) : 0;
        const isSingleTrailingSpace = lastCharCode === 32 && (prevCharCode !== 32 && prevCharCode !== 9);
        if (!isSingleTrailingSpace) {
          generateWhitespace = true;
        }
      } else {
        generateWhitespace = true;
      }
    }
    if (generateWhitespace) {
      if (generateLinePartForEachWhitespace) {
        const lastEndIndex = resultLen > 0 ? result[resultLen - 1].endIndex : fauxIndentLength;
        for (let i2 = lastEndIndex + 1; i2 <= len; i2++) {
          result[resultLen++] = new LinePart(i2, "mtkw", 1, false);
        }
      } else {
        result[resultLen++] = new LinePart(len, "mtkw", 1, false);
      }
    } else {
      result[resultLen++] = new LinePart(len, tokenType, 0, tokenContainsRTL);
    }
    return result;
  }
  function _applyInlineDecorations(lineContent, len, tokens, _lineDecorations) {
    _lineDecorations.sort(LineDecoration.compare);
    const lineDecorations = LineDecorationsNormalizer.normalize(lineContent, _lineDecorations);
    const lineDecorationsLen = lineDecorations.length;
    let lineDecorationIndex = 0;
    const result = [];
    let resultLen = 0;
    let lastResultEndIndex = 0;
    for (let tokenIndex = 0, len2 = tokens.length; tokenIndex < len2; tokenIndex++) {
      const token = tokens[tokenIndex];
      const tokenEndIndex = token.endIndex;
      const tokenType = token.type;
      const tokenMetadata = token.metadata;
      const tokenContainsRTL = token.containsRTL;
      while (lineDecorationIndex < lineDecorationsLen && lineDecorations[lineDecorationIndex].startOffset < tokenEndIndex) {
        const lineDecoration = lineDecorations[lineDecorationIndex];
        if (lineDecoration.startOffset > lastResultEndIndex) {
          lastResultEndIndex = lineDecoration.startOffset;
          result[resultLen++] = new LinePart(lastResultEndIndex, tokenType, tokenMetadata, tokenContainsRTL);
        }
        if (lineDecoration.endOffset + 1 <= tokenEndIndex) {
          lastResultEndIndex = lineDecoration.endOffset + 1;
          result[resultLen++] = new LinePart(lastResultEndIndex, tokenType + " " + lineDecoration.className, tokenMetadata | lineDecoration.metadata, tokenContainsRTL);
          lineDecorationIndex++;
        } else {
          lastResultEndIndex = tokenEndIndex;
          result[resultLen++] = new LinePart(lastResultEndIndex, tokenType + " " + lineDecoration.className, tokenMetadata | lineDecoration.metadata, tokenContainsRTL);
          break;
        }
      }
      if (tokenEndIndex > lastResultEndIndex) {
        lastResultEndIndex = tokenEndIndex;
        result[resultLen++] = new LinePart(lastResultEndIndex, tokenType, tokenMetadata, tokenContainsRTL);
      }
    }
    const lastTokenEndIndex = tokens[tokens.length - 1].endIndex;
    if (lineDecorationIndex < lineDecorationsLen && lineDecorations[lineDecorationIndex].startOffset === lastTokenEndIndex) {
      while (lineDecorationIndex < lineDecorationsLen && lineDecorations[lineDecorationIndex].startOffset === lastTokenEndIndex) {
        const lineDecoration = lineDecorations[lineDecorationIndex];
        result[resultLen++] = new LinePart(lastResultEndIndex, lineDecoration.className, lineDecoration.metadata, false);
        lineDecorationIndex++;
      }
    }
    return result;
  }
  function _renderLine(input, sb) {
    const fontIsMonospace = input.fontIsMonospace;
    const canUseHalfwidthRightwardsArrow = input.canUseHalfwidthRightwardsArrow;
    const containsForeignElements = input.containsForeignElements;
    const lineContent = input.lineContent;
    const len = input.len;
    const isOverflowing = input.isOverflowing;
    const overflowingCharCount = input.overflowingCharCount;
    const parts = input.parts;
    const fauxIndentLength = input.fauxIndentLength;
    const tabSize = input.tabSize;
    const startVisibleColumn = input.startVisibleColumn;
    const spaceWidth = input.spaceWidth;
    const renderSpaceCharCode = input.renderSpaceCharCode;
    const renderWhitespace = input.renderWhitespace;
    const renderControlCharacters = input.renderControlCharacters;
    const characterMapping = new CharacterMapping(len + 1, parts.length);
    let lastCharacterMappingDefined = false;
    let charIndex = 0;
    let visibleColumn = startVisibleColumn;
    let charOffsetInPart = 0;
    let charHorizontalOffset = 0;
    let partDisplacement = 0;
    sb.appendString("<span>");
    for (let partIndex = 0, tokensLen = parts.length; partIndex < tokensLen; partIndex++) {
      const part = parts[partIndex];
      const partEndIndex = part.endIndex;
      const partType = part.type;
      const partContainsRTL = part.containsRTL;
      const partRendersWhitespace = renderWhitespace !== 0 && part.isWhitespace();
      const partRendersWhitespaceWithWidth = partRendersWhitespace && !fontIsMonospace && (partType === "mtkw" || !containsForeignElements);
      const partIsEmptyAndHasPseudoAfter = charIndex === partEndIndex && part.isPseudoAfter();
      charOffsetInPart = 0;
      sb.appendString("<span ");
      if (partContainsRTL) {
        sb.appendString('dir="rtl" style="unicode-bidi:isolate" ');
      }
      sb.appendString('class="');
      sb.appendString(partRendersWhitespaceWithWidth ? "mtkz" : partType);
      sb.appendASCIICharCode(
        34
        /* CharCode.DoubleQuote */
      );
      if (partRendersWhitespace) {
        let partWidth = 0;
        {
          let _charIndex = charIndex;
          let _visibleColumn = visibleColumn;
          for (; _charIndex < partEndIndex; _charIndex++) {
            const charCode = lineContent.charCodeAt(_charIndex);
            const charWidth = (charCode === 9 ? tabSize - _visibleColumn % tabSize : 1) | 0;
            partWidth += charWidth;
            if (_charIndex >= fauxIndentLength) {
              _visibleColumn += charWidth;
            }
          }
        }
        if (partRendersWhitespaceWithWidth) {
          sb.appendString(' style="width:');
          sb.appendString(String(spaceWidth * partWidth));
          sb.appendString('px"');
        }
        sb.appendASCIICharCode(
          62
          /* CharCode.GreaterThan */
        );
        for (; charIndex < partEndIndex; charIndex++) {
          characterMapping.setColumnInfo(charIndex + 1, partIndex - partDisplacement, charOffsetInPart, charHorizontalOffset);
          partDisplacement = 0;
          const charCode = lineContent.charCodeAt(charIndex);
          let producedCharacters;
          let charWidth;
          if (charCode === 9) {
            producedCharacters = tabSize - visibleColumn % tabSize | 0;
            charWidth = producedCharacters;
            if (!canUseHalfwidthRightwardsArrow || charWidth > 1) {
              sb.appendCharCode(8594);
            } else {
              sb.appendCharCode(65515);
            }
            for (let space = 2; space <= charWidth; space++) {
              sb.appendCharCode(160);
            }
          } else {
            producedCharacters = 2;
            charWidth = 1;
            sb.appendCharCode(renderSpaceCharCode);
            sb.appendCharCode(8204);
          }
          charOffsetInPart += producedCharacters;
          charHorizontalOffset += charWidth;
          if (charIndex >= fauxIndentLength) {
            visibleColumn += charWidth;
          }
        }
      } else {
        sb.appendASCIICharCode(
          62
          /* CharCode.GreaterThan */
        );
        for (; charIndex < partEndIndex; charIndex++) {
          characterMapping.setColumnInfo(charIndex + 1, partIndex - partDisplacement, charOffsetInPart, charHorizontalOffset);
          partDisplacement = 0;
          const charCode = lineContent.charCodeAt(charIndex);
          let producedCharacters = 1;
          let charWidth = 1;
          switch (charCode) {
            case 9:
              producedCharacters = tabSize - visibleColumn % tabSize;
              charWidth = producedCharacters;
              for (let space = 1; space <= producedCharacters; space++) {
                sb.appendCharCode(160);
              }
              break;
            case 32:
              sb.appendCharCode(160);
              break;
            case 60:
              sb.appendString("&lt;");
              break;
            case 62:
              sb.appendString("&gt;");
              break;
            case 38:
              sb.appendString("&amp;");
              break;
            case 0:
              if (renderControlCharacters) {
                sb.appendCharCode(9216);
              } else {
                sb.appendString("&#00;");
              }
              break;
            case 65279:
            case 8232:
            case 8233:
            case 133:
              sb.appendCharCode(65533);
              break;
            default:
              if (isFullWidthCharacter(charCode)) {
                charWidth++;
              }
              if (renderControlCharacters && charCode < 32) {
                sb.appendCharCode(9216 + charCode);
              } else if (renderControlCharacters && charCode === 127) {
                sb.appendCharCode(9249);
              } else if (renderControlCharacters && isControlCharacter(charCode)) {
                sb.appendString("[U+");
                sb.appendString(to4CharHex(charCode));
                sb.appendString("]");
                producedCharacters = 8;
                charWidth = producedCharacters;
              } else {
                sb.appendCharCode(charCode);
              }
          }
          charOffsetInPart += producedCharacters;
          charHorizontalOffset += charWidth;
          if (charIndex >= fauxIndentLength) {
            visibleColumn += charWidth;
          }
        }
      }
      if (partIsEmptyAndHasPseudoAfter) {
        partDisplacement++;
      } else {
        partDisplacement = 0;
      }
      if (charIndex >= len && !lastCharacterMappingDefined && part.isPseudoAfter()) {
        lastCharacterMappingDefined = true;
        characterMapping.setColumnInfo(charIndex + 1, partIndex, charOffsetInPart, charHorizontalOffset);
      }
      sb.appendString("</span>");
    }
    if (!lastCharacterMappingDefined) {
      characterMapping.setColumnInfo(len + 1, parts.length - 1, charOffsetInPart, charHorizontalOffset);
    }
    if (isOverflowing) {
      sb.appendString('<span class="mtkoverflow">');
      sb.appendString(localize(796, "Show more ({0})", renderOverflowingCharCount(overflowingCharCount)));
      sb.appendString("</span>");
    }
    sb.appendString("</span>");
    return new RenderLineOutput(characterMapping, containsForeignElements);
  }
  function to4CharHex(n2) {
    return n2.toString(16).toUpperCase().padStart(4, "0");
  }
  function renderOverflowingCharCount(n2) {
    if (n2 < 1024) {
      return localize(797, "{0} chars", n2);
    }
    if (n2 < 1024 * 1024) {
      return `${(n2 / 1024).toFixed(1)} KB`;
    }
    return `${(n2 / 1024 / 1024).toFixed(1)} MB`;
  }
  var ColorScheme;
  (function(ColorScheme2) {
    ColorScheme2["DARK"] = "dark";
    ColorScheme2["LIGHT"] = "light";
    ColorScheme2["HIGH_CONTRAST_DARK"] = "hcDark";
    ColorScheme2["HIGH_CONTRAST_LIGHT"] = "hcLight";
  })(ColorScheme || (ColorScheme = {}));
  var ThemeTypeSelector;
  (function(ThemeTypeSelector2) {
    ThemeTypeSelector2["VS"] = "vs";
    ThemeTypeSelector2["VS_DARK"] = "vs-dark";
    ThemeTypeSelector2["HC_BLACK"] = "hc-black";
    ThemeTypeSelector2["HC_LIGHT"] = "hc-light";
  })(ThemeTypeSelector || (ThemeTypeSelector = {}));
  function isHighContrast(scheme) {
    return scheme === ColorScheme.HIGH_CONTRAST_DARK || scheme === ColorScheme.HIGH_CONTRAST_LIGHT;
  }
  function isDark(scheme) {
    return scheme === ColorScheme.DARK || scheme === ColorScheme.HIGH_CONTRAST_DARK;
  }
  const canUseFastRenderedViewLine = (function() {
    if (isNative) {
      return true;
    }
    if (isLinux || isFirefox$1 || isSafari$1) {
      return false;
    }
    return true;
  })();
  let monospaceAssumptionsAreValid = true;
  const _ViewLine = class _ViewLine {
    constructor(_viewGpuContext, options) {
      this._viewGpuContext = _viewGpuContext;
      this._options = options;
      this._isMaybeInvalid = true;
      this._renderedViewLine = null;
    }
    // --- begin IVisibleLineData
    getDomNode() {
      if (this._renderedViewLine && this._renderedViewLine.domNode) {
        return this._renderedViewLine.domNode.domNode;
      }
      return null;
    }
    setDomNode(domNode) {
      if (this._renderedViewLine) {
        this._renderedViewLine.domNode = createFastDomNode(domNode);
      } else {
        throw new Error("I have no rendered view line to set the dom node to...");
      }
    }
    onContentChanged() {
      this._isMaybeInvalid = true;
    }
    onTokensChanged() {
      this._isMaybeInvalid = true;
    }
    onDecorationsChanged() {
      this._isMaybeInvalid = true;
    }
    onOptionsChanged(newOptions) {
      this._isMaybeInvalid = true;
      this._options = newOptions;
    }
    onSelectionChanged() {
      if (isHighContrast(this._options.themeType) || this._renderedViewLine?.input.renderWhitespace === 2) {
        this._isMaybeInvalid = true;
        return true;
      }
      return false;
    }
    renderLine(lineNumber, deltaTop, lineHeight, viewportData, sb) {
      if (this._options.useGpu && this._viewGpuContext?.canRender(this._options, viewportData, lineNumber)) {
        this._renderedViewLine?.domNode?.domNode.remove();
        this._renderedViewLine = null;
        return false;
      }
      if (this._isMaybeInvalid === false) {
        return false;
      }
      this._isMaybeInvalid = false;
      const lineData = viewportData.getViewLineRenderingData(lineNumber);
      const options = this._options;
      const actualInlineDecorations = LineDecoration.filter(lineData.inlineDecorations, lineNumber, lineData.minColumn, lineData.maxColumn);
      const renderWhitespace = lineData.hasVariableFonts || options.experimentalWhitespaceRendering === "off" ? options.renderWhitespace : "none";
      const allowFastRendering = !lineData.hasVariableFonts;
      let selectionsOnLine = null;
      if (isHighContrast(options.themeType) || renderWhitespace === "selection") {
        const selections = viewportData.selections;
        for (const selection of selections) {
          if (selection.endLineNumber < lineNumber || selection.startLineNumber > lineNumber) {
            continue;
          }
          const startColumn = selection.startLineNumber === lineNumber ? selection.startColumn : lineData.minColumn;
          const endColumn = selection.endLineNumber === lineNumber ? selection.endColumn : lineData.maxColumn;
          if (startColumn < endColumn) {
            if (isHighContrast(options.themeType)) {
              actualInlineDecorations.push(new LineDecoration(
                startColumn,
                endColumn,
                "inline-selected-text",
                0
                /* InlineDecorationType.Regular */
              ));
            }
            if (renderWhitespace === "selection") {
              if (!selectionsOnLine) {
                selectionsOnLine = [];
              }
              selectionsOnLine.push(new OffsetRange(startColumn - 1, endColumn - 1));
            }
          }
        }
      }
      const renderLineInput = new RenderLineInput(options.useMonospaceOptimizations, options.canUseHalfwidthRightwardsArrow, lineData.content, lineData.continuesWithWrappedLine, lineData.isBasicASCII, lineData.containsRTL, lineData.minColumn - 1, lineData.tokens, actualInlineDecorations, lineData.tabSize, lineData.startVisibleColumn, options.spaceWidth, options.middotWidth, options.wsmiddotWidth, options.stopRenderingLineAfter, renderWhitespace, options.renderControlCharacters, options.fontLigatures !== EditorFontLigatures.OFF, selectionsOnLine, lineData.textDirection, options.verticalScrollbarSize);
      if (this._renderedViewLine && this._renderedViewLine.input.equals(renderLineInput)) {
        return false;
      }
      sb.appendString("<div ");
      if (lineData.textDirection === TextDirection$1.RTL) {
        sb.appendString('dir="rtl" ');
      } else if (lineData.containsRTL) {
        sb.appendString('dir="ltr" ');
      }
      sb.appendString('style="top:');
      sb.appendString(String(deltaTop));
      sb.appendString("px;height:");
      sb.appendString(String(lineHeight));
      sb.appendString("px;line-height:");
      sb.appendString(String(lineHeight));
      if (lineData.textDirection === TextDirection$1.RTL) {
        sb.appendString("px;padding-right:");
        sb.appendString(String(options.verticalScrollbarSize));
      }
      sb.appendString('px;" class="');
      sb.appendString(_ViewLine.CLASS_NAME);
      sb.appendString('">');
      const output = renderViewLine(renderLineInput, sb);
      sb.appendString("</div>");
      let renderedViewLine = null;
      if (allowFastRendering && monospaceAssumptionsAreValid && canUseFastRenderedViewLine && lineData.isBasicASCII && renderLineInput.isLTR && options.useMonospaceOptimizations && output.containsForeignElements === 0) {
        renderedViewLine = new FastRenderedViewLine(this._renderedViewLine ? this._renderedViewLine.domNode : null, renderLineInput, output.characterMapping);
      }
      if (!renderedViewLine) {
        renderedViewLine = createRenderedLine(this._renderedViewLine ? this._renderedViewLine.domNode : null, renderLineInput, output.characterMapping, output.containsForeignElements);
      }
      this._renderedViewLine = renderedViewLine;
      return true;
    }
    layoutLine(lineNumber, deltaTop, lineHeight) {
      if (this._renderedViewLine && this._renderedViewLine.domNode) {
        this._renderedViewLine.domNode.setTop(deltaTop);
        this._renderedViewLine.domNode.setHeight(lineHeight);
        this._renderedViewLine.domNode.setLineHeight(lineHeight);
      }
    }
    // --- end IVisibleLineData
    isRenderedRTL() {
      if (!this._renderedViewLine) {
        return false;
      }
      return this._renderedViewLine.input.textDirection === TextDirection$1.RTL;
    }
    getWidth(context) {
      if (!this._renderedViewLine) {
        return 0;
      }
      return this._renderedViewLine.getWidth(context);
    }
    getWidthIsFast() {
      if (!this._renderedViewLine) {
        return true;
      }
      return this._renderedViewLine.getWidthIsFast();
    }
    needsMonospaceFontCheck() {
      if (!this._renderedViewLine) {
        return false;
      }
      return this._renderedViewLine instanceof FastRenderedViewLine;
    }
    monospaceAssumptionsAreValid() {
      if (!this._renderedViewLine) {
        return monospaceAssumptionsAreValid;
      }
      if (this._renderedViewLine instanceof FastRenderedViewLine) {
        return this._renderedViewLine.monospaceAssumptionsAreValid();
      }
      return monospaceAssumptionsAreValid;
    }
    onMonospaceAssumptionsInvalidated() {
      if (this._renderedViewLine && this._renderedViewLine instanceof FastRenderedViewLine) {
        this._renderedViewLine = this._renderedViewLine.toSlowRenderedLine();
      }
    }
    getVisibleRangesForRange(lineNumber, startColumn, endColumn, context) {
      if (!this._renderedViewLine) {
        return null;
      }
      startColumn = Math.min(this._renderedViewLine.input.lineContent.length + 1, Math.max(1, startColumn));
      endColumn = Math.min(this._renderedViewLine.input.lineContent.length + 1, Math.max(1, endColumn));
      const stopRenderingLineAfter = this._renderedViewLine.input.stopRenderingLineAfter;
      if (stopRenderingLineAfter !== -1 && startColumn > stopRenderingLineAfter + 1 && endColumn > stopRenderingLineAfter + 1) {
        return new VisibleRanges(true, [new FloatHorizontalRange(this.getWidth(context), 0)]);
      }
      if (stopRenderingLineAfter !== -1 && startColumn > stopRenderingLineAfter + 1) {
        startColumn = stopRenderingLineAfter + 1;
      }
      if (stopRenderingLineAfter !== -1 && endColumn > stopRenderingLineAfter + 1) {
        endColumn = stopRenderingLineAfter + 1;
      }
      const horizontalRanges = this._renderedViewLine.getVisibleRangesForRange(lineNumber, startColumn, endColumn, context);
      if (horizontalRanges && horizontalRanges.length > 0) {
        return new VisibleRanges(false, horizontalRanges);
      }
      return null;
    }
    getColumnOfNodeOffset(spanNode, offset) {
      if (!this._renderedViewLine) {
        return 1;
      }
      return this._renderedViewLine.getColumnOfNodeOffset(spanNode, offset);
    }
  };
  _ViewLine.CLASS_NAME = "view-line";
  let ViewLine = _ViewLine;
  class FastRenderedViewLine {
    constructor(domNode, renderLineInput, characterMapping) {
      this._cachedWidth = -1;
      this.domNode = domNode;
      this.input = renderLineInput;
      const keyColumnCount = Math.floor(
        renderLineInput.lineContent.length / 300
        /* Constants.MaxMonospaceDistance */
      );
      if (keyColumnCount > 0) {
        this._keyColumnPixelOffsetCache = new Float32Array(keyColumnCount);
        for (let i2 = 0; i2 < keyColumnCount; i2++) {
          this._keyColumnPixelOffsetCache[i2] = -1;
        }
      } else {
        this._keyColumnPixelOffsetCache = null;
      }
      this._characterMapping = characterMapping;
      this._charWidth = renderLineInput.spaceWidth;
    }
    getWidth(context) {
      if (!this.domNode || this.input.lineContent.length < 300) {
        const horizontalOffset = this._characterMapping.getHorizontalOffset(this._characterMapping.length);
        return Math.round(this._charWidth * horizontalOffset);
      }
      if (this._cachedWidth === -1) {
        this._cachedWidth = this._getReadingTarget(this.domNode).offsetWidth;
        context?.markDidDomLayout();
      }
      return this._cachedWidth;
    }
    getWidthIsFast() {
      return this.input.lineContent.length < 300 || this._cachedWidth !== -1;
    }
    monospaceAssumptionsAreValid() {
      if (!this.domNode) {
        return monospaceAssumptionsAreValid;
      }
      if (this.input.lineContent.length < 300) {
        const expectedWidth = this.getWidth(null);
        const actualWidth = this.domNode.domNode.firstChild.offsetWidth;
        if (Math.abs(expectedWidth - actualWidth) >= 2) {
          console.warn(`monospace assumptions have been violated, therefore disabling monospace optimizations!`);
          monospaceAssumptionsAreValid = false;
        }
      }
      return monospaceAssumptionsAreValid;
    }
    toSlowRenderedLine() {
      return createRenderedLine(
        this.domNode,
        this.input,
        this._characterMapping,
        0
        /* ForeignElementType.None */
      );
    }
    getVisibleRangesForRange(lineNumber, startColumn, endColumn, context) {
      const startPosition = this._getColumnPixelOffset(lineNumber, startColumn, context);
      const endPosition = this._getColumnPixelOffset(lineNumber, endColumn, context);
      return [new FloatHorizontalRange(startPosition, endPosition - startPosition)];
    }
    _getColumnPixelOffset(lineNumber, column, context) {
      if (column <= 300) {
        const horizontalOffset2 = this._characterMapping.getHorizontalOffset(column);
        return this._charWidth * horizontalOffset2;
      }
      const keyColumnOrdinal = Math.floor(
        (column - 1) / 300
        /* Constants.MaxMonospaceDistance */
      ) - 1;
      const keyColumn = (keyColumnOrdinal + 1) * 300 + 1;
      let keyColumnPixelOffset = -1;
      if (this._keyColumnPixelOffsetCache) {
        keyColumnPixelOffset = this._keyColumnPixelOffsetCache[keyColumnOrdinal];
        if (keyColumnPixelOffset === -1) {
          keyColumnPixelOffset = this._actualReadPixelOffset(lineNumber, keyColumn, context);
          this._keyColumnPixelOffsetCache[keyColumnOrdinal] = keyColumnPixelOffset;
        }
      }
      if (keyColumnPixelOffset === -1) {
        const horizontalOffset2 = this._characterMapping.getHorizontalOffset(column);
        return this._charWidth * horizontalOffset2;
      }
      const keyColumnHorizontalOffset = this._characterMapping.getHorizontalOffset(keyColumn);
      const horizontalOffset = this._characterMapping.getHorizontalOffset(column);
      return keyColumnPixelOffset + this._charWidth * (horizontalOffset - keyColumnHorizontalOffset);
    }
    _getReadingTarget(myDomNode) {
      return myDomNode.domNode.firstChild;
    }
    _actualReadPixelOffset(lineNumber, column, context) {
      if (!this.domNode) {
        return -1;
      }
      const domPosition = this._characterMapping.getDomPosition(column);
      const r = RangeUtil.readHorizontalRanges(this._getReadingTarget(this.domNode), domPosition.partIndex, domPosition.charIndex, domPosition.partIndex, domPosition.charIndex, context);
      if (!r || r.length === 0) {
        return -1;
      }
      return r[0].left;
    }
    getColumnOfNodeOffset(spanNode, offset) {
      return getColumnOfNodeOffset(this._characterMapping, spanNode, offset);
    }
  }
  class RenderedViewLine {
    constructor(domNode, renderLineInput, characterMapping, containsForeignElements) {
      this.domNode = domNode;
      this.input = renderLineInput;
      this._characterMapping = characterMapping;
      this._isWhitespaceOnly = /^\s*$/.test(renderLineInput.lineContent);
      this._containsForeignElements = containsForeignElements;
      this._cachedWidth = -1;
      this._pixelOffsetCache = null;
      if (renderLineInput.isLTR) {
        this._pixelOffsetCache = new Float32Array(Math.max(2, this._characterMapping.length + 1));
        for (let column = 0, len = this._characterMapping.length; column <= len; column++) {
          this._pixelOffsetCache[column] = -1;
        }
      }
    }
    // --- Reading from the DOM methods
    _getReadingTarget(myDomNode) {
      return myDomNode.domNode.firstChild;
    }
    /**
     * Width of the line in pixels
     */
    getWidth(context) {
      if (!this.domNode) {
        return 0;
      }
      if (this._cachedWidth === -1) {
        this._cachedWidth = this._getReadingTarget(this.domNode).offsetWidth;
        context?.markDidDomLayout();
      }
      return this._cachedWidth;
    }
    getWidthIsFast() {
      if (this._cachedWidth === -1) {
        return false;
      }
      return true;
    }
    /**
     * Visible ranges for a model range
     */
    getVisibleRangesForRange(lineNumber, startColumn, endColumn, context) {
      if (!this.domNode) {
        return null;
      }
      if (this._pixelOffsetCache !== null) {
        const startOffset = this._readPixelOffset(this.domNode, lineNumber, startColumn, context);
        if (startOffset === -1) {
          return null;
        }
        const endOffset = this._readPixelOffset(this.domNode, lineNumber, endColumn, context);
        if (endOffset === -1) {
          return null;
        }
        return [new FloatHorizontalRange(startOffset, endOffset - startOffset)];
      }
      return this._readVisibleRangesForRange(this.domNode, lineNumber, startColumn, endColumn, context);
    }
    _readVisibleRangesForRange(domNode, lineNumber, startColumn, endColumn, context) {
      if (startColumn === endColumn) {
        const pixelOffset = this._readPixelOffset(domNode, lineNumber, startColumn, context);
        if (pixelOffset === -1) {
          return null;
        } else {
          return [new FloatHorizontalRange(pixelOffset, 0)];
        }
      } else {
        return this._readRawVisibleRangesForRange(domNode, startColumn, endColumn, context);
      }
    }
    _readPixelOffset(domNode, lineNumber, column, context) {
      if (this.input.isLTR && this._characterMapping.length === 0) {
        if (this._containsForeignElements === 0) {
          return 0;
        }
        if (this._containsForeignElements === 2) {
          return 0;
        }
        if (this._containsForeignElements === 1) {
          return this.getWidth(context);
        }
        const readingTarget = this._getReadingTarget(domNode);
        if (readingTarget.firstChild) {
          context.markDidDomLayout();
          return readingTarget.firstChild.offsetWidth;
        } else {
          return 0;
        }
      }
      if (this._pixelOffsetCache !== null) {
        const cachedPixelOffset = this._pixelOffsetCache[column];
        if (cachedPixelOffset !== -1) {
          return cachedPixelOffset;
        }
        const result = this._actualReadPixelOffset(domNode, lineNumber, column, context);
        this._pixelOffsetCache[column] = result;
        return result;
      }
      return this._actualReadPixelOffset(domNode, lineNumber, column, context);
    }
    _actualReadPixelOffset(domNode, lineNumber, column, context) {
      if (this._characterMapping.length === 0) {
        const r2 = RangeUtil.readHorizontalRanges(this._getReadingTarget(domNode), 0, 0, 0, 0, context);
        if (!r2 || r2.length === 0) {
          return -1;
        }
        return r2[0].left;
      }
      if (this.input.isLTR && column === this._characterMapping.length && this._isWhitespaceOnly && this._containsForeignElements === 0) {
        return this.getWidth(context);
      }
      const domPosition = this._characterMapping.getDomPosition(column);
      const r = RangeUtil.readHorizontalRanges(this._getReadingTarget(domNode), domPosition.partIndex, domPosition.charIndex, domPosition.partIndex, domPosition.charIndex, context);
      if (!r || r.length === 0) {
        return -1;
      }
      const result = r[0].left;
      if (this.input.isBasicASCII) {
        const horizontalOffset = this._characterMapping.getHorizontalOffset(column);
        const expectedResult = Math.round(this.input.spaceWidth * horizontalOffset);
        if (Math.abs(expectedResult - result) <= 1) {
          return expectedResult;
        }
      }
      return result;
    }
    _readRawVisibleRangesForRange(domNode, startColumn, endColumn, context) {
      if (this.input.isLTR && startColumn === 1 && endColumn === this._characterMapping.length) {
        return [new FloatHorizontalRange(0, this.getWidth(context))];
      }
      const startDomPosition = this._characterMapping.getDomPosition(startColumn);
      const endDomPosition = this._characterMapping.getDomPosition(endColumn);
      return RangeUtil.readHorizontalRanges(this._getReadingTarget(domNode), startDomPosition.partIndex, startDomPosition.charIndex, endDomPosition.partIndex, endDomPosition.charIndex, context);
    }
    /**
     * Returns the column for the text found at a specific offset inside a rendered dom node
     */
    getColumnOfNodeOffset(spanNode, offset) {
      return getColumnOfNodeOffset(this._characterMapping, spanNode, offset);
    }
  }
  class WebKitRenderedViewLine extends RenderedViewLine {
    _readVisibleRangesForRange(domNode, lineNumber, startColumn, endColumn, context) {
      const output = super._readVisibleRangesForRange(domNode, lineNumber, startColumn, endColumn, context);
      if (!output || output.length === 0 || startColumn === endColumn || startColumn === 1 && endColumn === this._characterMapping.length) {
        return output;
      }
      if (this.input.isLTR) {
        const endPixelOffset = this._readPixelOffset(domNode, lineNumber, endColumn, context);
        if (endPixelOffset !== -1) {
          const lastRange = output[output.length - 1];
          if (lastRange.left < endPixelOffset) {
            lastRange.width = endPixelOffset - lastRange.left;
          }
        }
      }
      return output;
    }
  }
  const createRenderedLine = (function() {
    if (isWebKit) {
      return createWebKitRenderedLine;
    }
    return createNormalRenderedLine;
  })();
  function createWebKitRenderedLine(domNode, renderLineInput, characterMapping, containsForeignElements) {
    return new WebKitRenderedViewLine(domNode, renderLineInput, characterMapping, containsForeignElements);
  }
  function createNormalRenderedLine(domNode, renderLineInput, characterMapping, containsForeignElements) {
    return new RenderedViewLine(domNode, renderLineInput, characterMapping, containsForeignElements);
  }
  function getColumnOfNodeOffset(characterMapping, spanNode, offset) {
    const spanNodeTextContentLength = spanNode.textContent.length;
    let spanIndex = -1;
    while (spanNode) {
      spanNode = spanNode.previousSibling;
      spanIndex++;
    }
    return characterMapping.getColumn(new DomPosition(spanIndex, offset), spanNodeTextContentLength);
  }
  class UnknownHitTestResult {
    constructor(hitTarget = null) {
      this.hitTarget = hitTarget;
      this.type = 0;
    }
  }
  class ContentHitTestResult {
    get hitTarget() {
      return this.spanNode;
    }
    constructor(position, spanNode, injectedText) {
      this.position = position;
      this.spanNode = spanNode;
      this.injectedText = injectedText;
      this.type = 1;
    }
  }
  var HitTestResult;
  (function(HitTestResult2) {
    function createFromDOMInfo(ctx, spanNode, offset) {
      const position = ctx.getPositionFromDOMInfo(spanNode, offset);
      if (position) {
        return new ContentHitTestResult(position, spanNode, null);
      }
      return new UnknownHitTestResult(spanNode);
    }
    HitTestResult2.createFromDOMInfo = createFromDOMInfo;
  })(HitTestResult || (HitTestResult = {}));
  class PointerHandlerLastRenderData {
    constructor(lastViewCursorsRenderData, lastTextareaPosition) {
      this.lastViewCursorsRenderData = lastViewCursorsRenderData;
      this.lastTextareaPosition = lastTextareaPosition;
    }
  }
  class MouseTarget {
    static _deduceRage(position, range2 = null) {
      if (!range2 && position) {
        return new Range$2(position.lineNumber, position.column, position.lineNumber, position.column);
      }
      return range2 ?? null;
    }
    static createUnknown(element, mouseColumn, position) {
      return { type: 0, element, mouseColumn, position, range: this._deduceRage(position) };
    }
    static createTextarea(element, mouseColumn) {
      return { type: 1, element, mouseColumn, position: null, range: null };
    }
    static createMargin(type, element, mouseColumn, position, range2, detail) {
      return { type, element, mouseColumn, position, range: range2, detail };
    }
    static createViewZone(type, element, mouseColumn, position, detail) {
      return { type, element, mouseColumn, position, range: this._deduceRage(position), detail };
    }
    static createContentText(element, mouseColumn, position, range2, detail) {
      return { type: 6, element, mouseColumn, position, range: this._deduceRage(position, range2), detail };
    }
    static createContentEmpty(element, mouseColumn, position, detail) {
      return { type: 7, element, mouseColumn, position, range: this._deduceRage(position), detail };
    }
    static createContentWidget(element, mouseColumn, detail) {
      return { type: 9, element, mouseColumn, position: null, range: null, detail };
    }
    static createScrollbar(element, mouseColumn, position) {
      return { type: 11, element, mouseColumn, position, range: this._deduceRage(position) };
    }
    static createOverlayWidget(element, mouseColumn, detail) {
      return { type: 12, element, mouseColumn, position: null, range: null, detail };
    }
    static createOutsideEditor(mouseColumn, position, outsidePosition, outsideDistance) {
      return { type: 13, element: null, mouseColumn, position, range: this._deduceRage(position), outsidePosition, outsideDistance };
    }
    static _typeToString(type) {
      if (type === 1) {
        return "TEXTAREA";
      }
      if (type === 2) {
        return "GUTTER_GLYPH_MARGIN";
      }
      if (type === 3) {
        return "GUTTER_LINE_NUMBERS";
      }
      if (type === 4) {
        return "GUTTER_LINE_DECORATIONS";
      }
      if (type === 5) {
        return "GUTTER_VIEW_ZONE";
      }
      if (type === 6) {
        return "CONTENT_TEXT";
      }
      if (type === 7) {
        return "CONTENT_EMPTY";
      }
      if (type === 8) {
        return "CONTENT_VIEW_ZONE";
      }
      if (type === 9) {
        return "CONTENT_WIDGET";
      }
      if (type === 10) {
        return "OVERVIEW_RULER";
      }
      if (type === 11) {
        return "SCROLLBAR";
      }
      if (type === 12) {
        return "OVERLAY_WIDGET";
      }
      return "UNKNOWN";
    }
    static toString(target) {
      return this._typeToString(target.type) + ": " + target.position + " - " + target.range + " - " + JSON.stringify(target.detail);
    }
  }
  class ElementPath {
    static isTextArea(path) {
      return path.length === 2 && path[0] === 3 && path[1] === 7;
    }
    static isChildOfViewLines(path) {
      return path.length >= 4 && path[0] === 3 && path[3] === 8;
    }
    static isStrictChildOfViewLines(path) {
      return path.length > 4 && path[0] === 3 && path[3] === 8;
    }
    static isChildOfScrollableElement(path) {
      return path.length >= 2 && path[0] === 3 && path[1] === 6;
    }
    static isChildOfMinimap(path) {
      return path.length >= 2 && path[0] === 3 && path[1] === 9;
    }
    static isChildOfContentWidgets(path) {
      return path.length >= 4 && path[0] === 3 && path[3] === 1;
    }
    static isChildOfOverflowGuard(path) {
      return path.length >= 1 && path[0] === 3;
    }
    static isChildOfOverflowingContentWidgets(path) {
      return path.length >= 1 && path[0] === 2;
    }
    static isChildOfOverlayWidgets(path) {
      return path.length >= 2 && path[0] === 3 && path[1] === 4;
    }
    static isChildOfOverflowingOverlayWidgets(path) {
      return path.length >= 1 && path[0] === 5;
    }
  }
  class HitTestContext {
    constructor(context, viewHelper, lastRenderData) {
      this.viewModel = context.viewModel;
      const options = context.configuration.options;
      this.layoutInfo = options.get(
        165
        /* EditorOption.layoutInfo */
      );
      this.viewDomNode = viewHelper.viewDomNode;
      this.viewLinesGpu = viewHelper.viewLinesGpu;
      this.lineHeight = options.get(
        75
        /* EditorOption.lineHeight */
      );
      this.stickyTabStops = options.get(
        132
        /* EditorOption.stickyTabStops */
      );
      this.typicalHalfwidthCharacterWidth = options.get(
        59
        /* EditorOption.fontInfo */
      ).typicalHalfwidthCharacterWidth;
      this.lastRenderData = lastRenderData;
      this._context = context;
      this._viewHelper = viewHelper;
    }
    getZoneAtCoord(mouseVerticalOffset) {
      return HitTestContext.getZoneAtCoord(this._context, mouseVerticalOffset);
    }
    static getZoneAtCoord(context, mouseVerticalOffset) {
      const viewZoneWhitespace = context.viewLayout.getWhitespaceAtVerticalOffset(mouseVerticalOffset);
      if (viewZoneWhitespace) {
        const viewZoneMiddle = viewZoneWhitespace.verticalOffset + viewZoneWhitespace.height / 2;
        const lineCount = context.viewModel.getLineCount();
        let positionBefore = null;
        let position;
        let positionAfter = null;
        if (viewZoneWhitespace.afterLineNumber !== lineCount) {
          positionAfter = new Position$1(viewZoneWhitespace.afterLineNumber + 1, 1);
        }
        if (viewZoneWhitespace.afterLineNumber > 0) {
          positionBefore = new Position$1(viewZoneWhitespace.afterLineNumber, context.viewModel.getLineMaxColumn(viewZoneWhitespace.afterLineNumber));
        }
        if (positionAfter === null) {
          position = positionBefore;
        } else if (positionBefore === null) {
          position = positionAfter;
        } else if (mouseVerticalOffset < viewZoneMiddle) {
          position = positionBefore;
        } else {
          position = positionAfter;
        }
        return {
          viewZoneId: viewZoneWhitespace.id,
          afterLineNumber: viewZoneWhitespace.afterLineNumber,
          positionBefore,
          positionAfter,
          position
        };
      }
      return null;
    }
    getFullLineRangeAtCoord(mouseVerticalOffset) {
      if (this._context.viewLayout.isAfterLines(mouseVerticalOffset)) {
        const lineNumber2 = this._context.viewModel.getLineCount();
        const maxLineColumn2 = this._context.viewModel.getLineMaxColumn(lineNumber2);
        return {
          range: new Range$2(lineNumber2, maxLineColumn2, lineNumber2, maxLineColumn2),
          isAfterLines: true
        };
      }
      const lineNumber = this._context.viewLayout.getLineNumberAtVerticalOffset(mouseVerticalOffset);
      const maxLineColumn = this._context.viewModel.getLineMaxColumn(lineNumber);
      return {
        range: new Range$2(lineNumber, 1, lineNumber, maxLineColumn),
        isAfterLines: false
      };
    }
    getLineNumberAtVerticalOffset(mouseVerticalOffset) {
      return this._context.viewLayout.getLineNumberAtVerticalOffset(mouseVerticalOffset);
    }
    isAfterLines(mouseVerticalOffset) {
      return this._context.viewLayout.isAfterLines(mouseVerticalOffset);
    }
    isInTopPadding(mouseVerticalOffset) {
      return this._context.viewLayout.isInTopPadding(mouseVerticalOffset);
    }
    isInBottomPadding(mouseVerticalOffset) {
      return this._context.viewLayout.isInBottomPadding(mouseVerticalOffset);
    }
    getVerticalOffsetForLineNumber(lineNumber) {
      return this._context.viewLayout.getVerticalOffsetForLineNumber(lineNumber);
    }
    findAttribute(element, attr) {
      return HitTestContext._findAttribute(element, attr, this._viewHelper.viewDomNode);
    }
    static _findAttribute(element, attr, stopAt) {
      while (element && element !== element.ownerDocument.body) {
        if (element.hasAttribute && element.hasAttribute(attr)) {
          return element.getAttribute(attr);
        }
        if (element === stopAt) {
          return null;
        }
        element = element.parentNode;
      }
      return null;
    }
    getLineWidth(lineNumber) {
      return this._viewHelper.getLineWidth(lineNumber);
    }
    isRtl(lineNumber) {
      return this.viewModel.getTextDirection(lineNumber) === TextDirection$1.RTL;
    }
    visibleRangeForPosition(lineNumber, column) {
      return this._viewHelper.visibleRangeForPosition(lineNumber, column);
    }
    getPositionFromDOMInfo(spanNode, offset) {
      return this._viewHelper.getPositionFromDOMInfo(spanNode, offset);
    }
    getCurrentScrollTop() {
      return this._context.viewLayout.getCurrentScrollTop();
    }
    getCurrentScrollLeft() {
      return this._context.viewLayout.getCurrentScrollLeft();
    }
  }
  class BareHitTestRequest {
    constructor(ctx, editorPos, pos, relativePos) {
      this.editorPos = editorPos;
      this.pos = pos;
      this.relativePos = relativePos;
      this.mouseVerticalOffset = Math.max(0, ctx.getCurrentScrollTop() + this.relativePos.y);
      this.mouseContentHorizontalOffset = ctx.getCurrentScrollLeft() + this.relativePos.x - ctx.layoutInfo.contentLeft;
      this.isInMarginArea = this.relativePos.x < ctx.layoutInfo.contentLeft && this.relativePos.x >= ctx.layoutInfo.glyphMarginLeft;
      this.isInContentArea = !this.isInMarginArea;
      this.mouseColumn = Math.max(0, MouseTargetFactory._getMouseColumn(this.mouseContentHorizontalOffset, ctx.typicalHalfwidthCharacterWidth));
    }
  }
  class HitTestRequest extends BareHitTestRequest {
    get target() {
      if (this._useHitTestTarget) {
        return this.hitTestResult.value.hitTarget;
      }
      return this._eventTarget;
    }
    get targetPath() {
      if (this._targetPathCacheElement !== this.target) {
        this._targetPathCacheElement = this.target;
        this._targetPathCacheValue = PartFingerprints.collect(this.target, this._ctx.viewDomNode);
      }
      return this._targetPathCacheValue;
    }
    constructor(ctx, editorPos, pos, relativePos, eventTarget) {
      super(ctx, editorPos, pos, relativePos);
      this.hitTestResult = new Lazy(() => MouseTargetFactory.doHitTest(this._ctx, this));
      this._targetPathCacheElement = null;
      this._targetPathCacheValue = new Uint8Array(0);
      this._ctx = ctx;
      this._eventTarget = eventTarget;
      const hasEventTarget = Boolean(this._eventTarget);
      this._useHitTestTarget = !hasEventTarget;
    }
    toString() {
      return `pos(${this.pos.x},${this.pos.y}), editorPos(${this.editorPos.x},${this.editorPos.y}), relativePos(${this.relativePos.x},${this.relativePos.y}), mouseVerticalOffset: ${this.mouseVerticalOffset}, mouseContentHorizontalOffset: ${this.mouseContentHorizontalOffset}
	target: ${this.target ? this.target.outerHTML : null}`;
    }
    get wouldBenefitFromHitTestTargetSwitch() {
      return !this._useHitTestTarget && this.hitTestResult.value.hitTarget !== null && this.target !== this.hitTestResult.value.hitTarget;
    }
    switchToHitTestTarget() {
      this._useHitTestTarget = true;
    }
    _getMouseColumn(position = null) {
      if (position && position.column < this._ctx.viewModel.getLineMaxColumn(position.lineNumber)) {
        return CursorColumns.visibleColumnFromColumn(this._ctx.viewModel.getLineContent(position.lineNumber), position.column, this._ctx.viewModel.model.getOptions().tabSize) + 1;
      }
      return this.mouseColumn;
    }
    fulfillUnknown(position = null) {
      return MouseTarget.createUnknown(this.target, this._getMouseColumn(position), position);
    }
    fulfillTextarea() {
      return MouseTarget.createTextarea(this.target, this._getMouseColumn());
    }
    fulfillMargin(type, position, range2, detail) {
      return MouseTarget.createMargin(type, this.target, this._getMouseColumn(position), position, range2, detail);
    }
    fulfillViewZone(type, position, detail) {
      return MouseTarget.createViewZone(type, this.target, this._getMouseColumn(), position, detail);
    }
    fulfillContentText(position, range2, detail) {
      return MouseTarget.createContentText(this.target, this._getMouseColumn(position), position, range2, detail);
    }
    fulfillContentEmpty(position, detail) {
      return MouseTarget.createContentEmpty(this.target, this._getMouseColumn(position), position, detail);
    }
    fulfillContentWidget(detail) {
      return MouseTarget.createContentWidget(this.target, this._getMouseColumn(), detail);
    }
    fulfillScrollbar(position) {
      return MouseTarget.createScrollbar(this.target, this._getMouseColumn(position), position);
    }
    fulfillOverlayWidget(detail) {
      return MouseTarget.createOverlayWidget(this.target, this._getMouseColumn(), detail);
    }
  }
  const EMPTY_CONTENT_AFTER_LINES = { isAfterLines: true };
  function createEmptyContentDataInLines(horizontalDistanceToText) {
    return {
      isAfterLines: false,
      horizontalDistanceToText
    };
  }
  class MouseTargetFactory {
    constructor(context, viewHelper) {
      this._context = context;
      this._viewHelper = viewHelper;
    }
    mouseTargetIsWidget(e) {
      const t = e.target;
      const path = PartFingerprints.collect(t, this._viewHelper.viewDomNode);
      if (ElementPath.isChildOfContentWidgets(path) || ElementPath.isChildOfOverflowingContentWidgets(path)) {
        return true;
      }
      if (ElementPath.isChildOfOverlayWidgets(path) || ElementPath.isChildOfOverflowingOverlayWidgets(path)) {
        return true;
      }
      return false;
    }
    createMouseTarget(lastRenderData, editorPos, pos, relativePos, target) {
      const ctx = new HitTestContext(this._context, this._viewHelper, lastRenderData);
      const request = new HitTestRequest(ctx, editorPos, pos, relativePos, target);
      try {
        const r = MouseTargetFactory._createMouseTarget(ctx, request);
        if (r.type === 6) {
          if (ctx.stickyTabStops && r.position !== null) {
            const position = MouseTargetFactory._snapToSoftTabBoundary(r.position, ctx.viewModel);
            const range2 = Range$2.fromPositions(position, position).plusRange(r.range);
            return request.fulfillContentText(position, range2, r.detail);
          }
        }
        return r;
      } catch (err) {
        return request.fulfillUnknown();
      }
    }
    static _createMouseTarget(ctx, request) {
      if (request.target === null) {
        return request.fulfillUnknown();
      }
      const resolvedRequest = request;
      let result = null;
      if (!ElementPath.isChildOfOverflowGuard(request.targetPath) && !ElementPath.isChildOfOverflowingContentWidgets(request.targetPath) && !ElementPath.isChildOfOverflowingOverlayWidgets(request.targetPath)) {
        result = result || request.fulfillUnknown();
      }
      result = result || MouseTargetFactory._hitTestContentWidget(ctx, resolvedRequest);
      result = result || MouseTargetFactory._hitTestOverlayWidget(ctx, resolvedRequest);
      result = result || MouseTargetFactory._hitTestMinimap(ctx, resolvedRequest);
      result = result || MouseTargetFactory._hitTestScrollbarSlider(ctx, resolvedRequest);
      result = result || MouseTargetFactory._hitTestViewZone(ctx, resolvedRequest);
      result = result || MouseTargetFactory._hitTestMargin(ctx, resolvedRequest);
      result = result || MouseTargetFactory._hitTestViewCursor(ctx, resolvedRequest);
      result = result || MouseTargetFactory._hitTestTextArea(ctx, resolvedRequest);
      result = result || MouseTargetFactory._hitTestViewLines(ctx, resolvedRequest);
      result = result || MouseTargetFactory._hitTestScrollbar(ctx, resolvedRequest);
      return result || request.fulfillUnknown();
    }
    static _hitTestContentWidget(ctx, request) {
      if (ElementPath.isChildOfContentWidgets(request.targetPath) || ElementPath.isChildOfOverflowingContentWidgets(request.targetPath)) {
        const widgetId = ctx.findAttribute(request.target, "widgetId");
        if (widgetId) {
          return request.fulfillContentWidget(widgetId);
        } else {
          return request.fulfillUnknown();
        }
      }
      return null;
    }
    static _hitTestOverlayWidget(ctx, request) {
      if (ElementPath.isChildOfOverlayWidgets(request.targetPath) || ElementPath.isChildOfOverflowingOverlayWidgets(request.targetPath)) {
        const widgetId = ctx.findAttribute(request.target, "widgetId");
        if (widgetId) {
          return request.fulfillOverlayWidget(widgetId);
        } else {
          return request.fulfillUnknown();
        }
      }
      return null;
    }
    static _hitTestViewCursor(ctx, request) {
      if (request.target) {
        const lastViewCursorsRenderData = ctx.lastRenderData.lastViewCursorsRenderData;
        for (const d of lastViewCursorsRenderData) {
          if (request.target === d.domNode) {
            return request.fulfillContentText(d.position, null, { mightBeForeignElement: false, injectedText: null });
          }
        }
      }
      if (request.isInContentArea) {
        const lastViewCursorsRenderData = ctx.lastRenderData.lastViewCursorsRenderData;
        const mouseContentHorizontalOffset = request.mouseContentHorizontalOffset;
        const mouseVerticalOffset = request.mouseVerticalOffset;
        for (const d of lastViewCursorsRenderData) {
          if (mouseContentHorizontalOffset < d.contentLeft) {
            continue;
          }
          if (mouseContentHorizontalOffset > d.contentLeft + d.width) {
            continue;
          }
          const cursorVerticalOffset = ctx.getVerticalOffsetForLineNumber(d.position.lineNumber);
          if (cursorVerticalOffset <= mouseVerticalOffset && mouseVerticalOffset <= cursorVerticalOffset + d.height) {
            return request.fulfillContentText(d.position, null, { mightBeForeignElement: false, injectedText: null });
          }
        }
      }
      return null;
    }
    static _hitTestViewZone(ctx, request) {
      const viewZoneData = ctx.getZoneAtCoord(request.mouseVerticalOffset);
      if (viewZoneData) {
        const mouseTargetType = request.isInContentArea ? 8 : 5;
        return request.fulfillViewZone(mouseTargetType, viewZoneData.position, viewZoneData);
      }
      return null;
    }
    static _hitTestTextArea(ctx, request) {
      if (ElementPath.isTextArea(request.targetPath)) {
        if (ctx.lastRenderData.lastTextareaPosition) {
          return request.fulfillContentText(ctx.lastRenderData.lastTextareaPosition, null, { mightBeForeignElement: false, injectedText: null });
        }
        return request.fulfillTextarea();
      }
      return null;
    }
    static _hitTestMargin(ctx, request) {
      if (request.isInMarginArea) {
        const res = ctx.getFullLineRangeAtCoord(request.mouseVerticalOffset);
        const pos = res.range.getStartPosition();
        let offset = Math.abs(request.relativePos.x);
        const detail = {
          isAfterLines: res.isAfterLines,
          glyphMarginLeft: ctx.layoutInfo.glyphMarginLeft,
          glyphMarginWidth: ctx.layoutInfo.glyphMarginWidth,
          lineNumbersWidth: ctx.layoutInfo.lineNumbersWidth,
          offsetX: offset
        };
        offset -= ctx.layoutInfo.glyphMarginLeft;
        if (offset <= ctx.layoutInfo.glyphMarginWidth) {
          const modelCoordinate = ctx.viewModel.coordinatesConverter.convertViewPositionToModelPosition(res.range.getStartPosition());
          const lanes = ctx.viewModel.glyphLanes.getLanesAtLine(modelCoordinate.lineNumber);
          detail.glyphMarginLane = lanes[Math.floor(offset / ctx.lineHeight)];
          return request.fulfillMargin(2, pos, res.range, detail);
        }
        offset -= ctx.layoutInfo.glyphMarginWidth;
        if (offset <= ctx.layoutInfo.lineNumbersWidth) {
          return request.fulfillMargin(3, pos, res.range, detail);
        }
        offset -= ctx.layoutInfo.lineNumbersWidth;
        return request.fulfillMargin(4, pos, res.range, detail);
      }
      return null;
    }
    static _hitTestViewLines(ctx, request) {
      if (!ElementPath.isChildOfViewLines(request.targetPath)) {
        return null;
      }
      if (ctx.isInTopPadding(request.mouseVerticalOffset)) {
        return request.fulfillContentEmpty(new Position$1(1, 1), EMPTY_CONTENT_AFTER_LINES);
      }
      if (ctx.isAfterLines(request.mouseVerticalOffset) || ctx.isInBottomPadding(request.mouseVerticalOffset)) {
        const lineCount = ctx.viewModel.getLineCount();
        const maxLineColumn = ctx.viewModel.getLineMaxColumn(lineCount);
        return request.fulfillContentEmpty(new Position$1(lineCount, maxLineColumn), EMPTY_CONTENT_AFTER_LINES);
      }
      if (ElementPath.isStrictChildOfViewLines(request.targetPath)) {
        const lineNumber = ctx.getLineNumberAtVerticalOffset(request.mouseVerticalOffset);
        const lineLength = ctx.viewModel.getLineLength(lineNumber);
        const lineWidth = ctx.getLineWidth(lineNumber);
        if (lineLength === 0) {
          const detail = createEmptyContentDataInLines(request.mouseContentHorizontalOffset - lineWidth);
          return request.fulfillContentEmpty(new Position$1(lineNumber, 1), detail);
        }
        const isRtl = ctx.isRtl(lineNumber);
        if (isRtl) {
          if (request.mouseContentHorizontalOffset + lineWidth <= ctx.layoutInfo.contentWidth - ctx.layoutInfo.verticalScrollbarWidth) {
            const detail = createEmptyContentDataInLines(request.mouseContentHorizontalOffset - lineWidth);
            const pos = new Position$1(lineNumber, ctx.viewModel.getLineMaxColumn(lineNumber));
            return request.fulfillContentEmpty(pos, detail);
          }
        } else if (request.mouseContentHorizontalOffset >= lineWidth) {
          const detail = createEmptyContentDataInLines(request.mouseContentHorizontalOffset - lineWidth);
          const pos = new Position$1(lineNumber, ctx.viewModel.getLineMaxColumn(lineNumber));
          return request.fulfillContentEmpty(pos, detail);
        }
      } else {
        if (ctx.viewLinesGpu) {
          const lineNumber = ctx.getLineNumberAtVerticalOffset(request.mouseVerticalOffset);
          if (ctx.viewModel.getLineLength(lineNumber) === 0) {
            const lineWidth2 = ctx.getLineWidth(lineNumber);
            const detail = createEmptyContentDataInLines(request.mouseContentHorizontalOffset - lineWidth2);
            return request.fulfillContentEmpty(new Position$1(lineNumber, 1), detail);
          }
          const lineWidth = ctx.getLineWidth(lineNumber);
          const isRtl = ctx.isRtl(lineNumber);
          if (isRtl) {
            if (request.mouseContentHorizontalOffset + lineWidth <= ctx.layoutInfo.contentWidth - ctx.layoutInfo.verticalScrollbarWidth) {
              const detail = createEmptyContentDataInLines(request.mouseContentHorizontalOffset - lineWidth);
              const pos = new Position$1(lineNumber, ctx.viewModel.getLineMaxColumn(lineNumber));
              return request.fulfillContentEmpty(pos, detail);
            }
          } else if (request.mouseContentHorizontalOffset >= lineWidth) {
            const detail = createEmptyContentDataInLines(request.mouseContentHorizontalOffset - lineWidth);
            const pos = new Position$1(lineNumber, ctx.viewModel.getLineMaxColumn(lineNumber));
            return request.fulfillContentEmpty(pos, detail);
          }
          const position = ctx.viewLinesGpu.getPositionAtCoordinate(lineNumber, request.mouseContentHorizontalOffset);
          if (position) {
            const detail = {
              injectedText: null,
              mightBeForeignElement: false
            };
            return request.fulfillContentText(position, Range$2.fromPositions(position, position), detail);
          }
        }
      }
      const hitTestResult = request.hitTestResult.value;
      if (hitTestResult.type === 1) {
        return MouseTargetFactory.createMouseTargetFromHitTestPosition(ctx, request, hitTestResult.spanNode, hitTestResult.position, hitTestResult.injectedText);
      }
      if (request.wouldBenefitFromHitTestTargetSwitch) {
        request.switchToHitTestTarget();
        return this._createMouseTarget(ctx, request);
      }
      return request.fulfillUnknown();
    }
    static _hitTestMinimap(ctx, request) {
      if (ElementPath.isChildOfMinimap(request.targetPath)) {
        const possibleLineNumber = ctx.getLineNumberAtVerticalOffset(request.mouseVerticalOffset);
        const maxColumn = ctx.viewModel.getLineMaxColumn(possibleLineNumber);
        return request.fulfillScrollbar(new Position$1(possibleLineNumber, maxColumn));
      }
      return null;
    }
    static _hitTestScrollbarSlider(ctx, request) {
      if (ElementPath.isChildOfScrollableElement(request.targetPath)) {
        if (request.target && request.target.nodeType === 1) {
          const className2 = request.target.className;
          if (className2 && /\b(slider|scrollbar)\b/.test(className2)) {
            const possibleLineNumber = ctx.getLineNumberAtVerticalOffset(request.mouseVerticalOffset);
            const maxColumn = ctx.viewModel.getLineMaxColumn(possibleLineNumber);
            return request.fulfillScrollbar(new Position$1(possibleLineNumber, maxColumn));
          }
        }
      }
      return null;
    }
    static _hitTestScrollbar(ctx, request) {
      if (ElementPath.isChildOfScrollableElement(request.targetPath)) {
        const possibleLineNumber = ctx.getLineNumberAtVerticalOffset(request.mouseVerticalOffset);
        const maxColumn = ctx.viewModel.getLineMaxColumn(possibleLineNumber);
        return request.fulfillScrollbar(new Position$1(possibleLineNumber, maxColumn));
      }
      return null;
    }
    getMouseColumn(relativePos) {
      const options = this._context.configuration.options;
      const layoutInfo = options.get(
        165
        /* EditorOption.layoutInfo */
      );
      const mouseContentHorizontalOffset = this._context.viewLayout.getCurrentScrollLeft() + relativePos.x - layoutInfo.contentLeft;
      return MouseTargetFactory._getMouseColumn(mouseContentHorizontalOffset, options.get(
        59
        /* EditorOption.fontInfo */
      ).typicalHalfwidthCharacterWidth);
    }
    static _getMouseColumn(mouseContentHorizontalOffset, typicalHalfwidthCharacterWidth) {
      if (mouseContentHorizontalOffset < 0) {
        return 1;
      }
      const chars = Math.round(mouseContentHorizontalOffset / typicalHalfwidthCharacterWidth);
      return chars + 1;
    }
    static createMouseTargetFromHitTestPosition(ctx, request, spanNode, pos, injectedText) {
      const lineNumber = pos.lineNumber;
      const column = pos.column;
      const lineWidth = ctx.getLineWidth(lineNumber);
      if (request.mouseContentHorizontalOffset > lineWidth) {
        const detail = createEmptyContentDataInLines(request.mouseContentHorizontalOffset - lineWidth);
        return request.fulfillContentEmpty(pos, detail);
      }
      const visibleRange = ctx.visibleRangeForPosition(lineNumber, column);
      if (!visibleRange) {
        return request.fulfillUnknown(pos);
      }
      const columnHorizontalOffset = visibleRange.left;
      if (Math.abs(request.mouseContentHorizontalOffset - columnHorizontalOffset) < 1) {
        return request.fulfillContentText(pos, null, { mightBeForeignElement: !!injectedText, injectedText });
      }
      const points = [];
      points.push({ offset: visibleRange.left, column });
      if (column > 1) {
        const visibleRange2 = ctx.visibleRangeForPosition(lineNumber, column - 1);
        if (visibleRange2) {
          points.push({ offset: visibleRange2.left, column: column - 1 });
        }
      }
      const lineMaxColumn = ctx.viewModel.getLineMaxColumn(lineNumber);
      if (column < lineMaxColumn) {
        const visibleRange2 = ctx.visibleRangeForPosition(lineNumber, column + 1);
        if (visibleRange2) {
          points.push({ offset: visibleRange2.left, column: column + 1 });
        }
      }
      points.sort((a, b) => a.offset - b.offset);
      const mouseCoordinates = request.pos.toClientCoordinates(getWindow(ctx.viewDomNode));
      const spanNodeClientRect = spanNode.getBoundingClientRect();
      const mouseIsOverSpanNode = spanNodeClientRect.left <= mouseCoordinates.clientX && mouseCoordinates.clientX <= spanNodeClientRect.right;
      let rng = null;
      for (let i2 = 1; i2 < points.length; i2++) {
        const prev = points[i2 - 1];
        const curr = points[i2];
        if (prev.offset <= request.mouseContentHorizontalOffset && request.mouseContentHorizontalOffset <= curr.offset) {
          rng = new Range$2(lineNumber, prev.column, lineNumber, curr.column);
          const prevDelta = Math.abs(prev.offset - request.mouseContentHorizontalOffset);
          const nextDelta = Math.abs(curr.offset - request.mouseContentHorizontalOffset);
          pos = prevDelta < nextDelta ? new Position$1(lineNumber, prev.column) : new Position$1(lineNumber, curr.column);
          break;
        }
      }
      return request.fulfillContentText(pos, rng, { mightBeForeignElement: !mouseIsOverSpanNode || !!injectedText, injectedText });
    }
    /**
     * Most probably WebKit browsers and Edge
     */
    static _doHitTestWithCaretRangeFromPoint(ctx, request) {
      const lineNumber = ctx.getLineNumberAtVerticalOffset(request.mouseVerticalOffset);
      const lineStartVerticalOffset = ctx.getVerticalOffsetForLineNumber(lineNumber);
      const lineEndVerticalOffset = lineStartVerticalOffset + ctx.lineHeight;
      const isBelowLastLine = lineNumber === ctx.viewModel.getLineCount() && request.mouseVerticalOffset > lineEndVerticalOffset;
      if (!isBelowLastLine) {
        const lineCenteredVerticalOffset = Math.floor((lineStartVerticalOffset + lineEndVerticalOffset) / 2);
        let adjustedPageY = request.pos.y + (lineCenteredVerticalOffset - request.mouseVerticalOffset);
        if (adjustedPageY <= request.editorPos.y) {
          adjustedPageY = request.editorPos.y + 1;
        }
        if (adjustedPageY >= request.editorPos.y + request.editorPos.height) {
          adjustedPageY = request.editorPos.y + request.editorPos.height - 1;
        }
        const adjustedPage = new PageCoordinates(request.pos.x, adjustedPageY);
        const r = this._actualDoHitTestWithCaretRangeFromPoint(ctx, adjustedPage.toClientCoordinates(getWindow(ctx.viewDomNode)));
        if (r.type === 1) {
          return r;
        }
      }
      return this._actualDoHitTestWithCaretRangeFromPoint(ctx, request.pos.toClientCoordinates(getWindow(ctx.viewDomNode)));
    }
    static _actualDoHitTestWithCaretRangeFromPoint(ctx, coords) {
      const shadowRoot = getShadowRoot(ctx.viewDomNode);
      let range2;
      if (shadowRoot) {
        if (typeof shadowRoot.caretRangeFromPoint === "undefined") {
          range2 = shadowCaretRangeFromPoint(shadowRoot, coords.clientX, coords.clientY);
        } else {
          range2 = shadowRoot.caretRangeFromPoint(coords.clientX, coords.clientY);
        }
      } else {
        range2 = ctx.viewDomNode.ownerDocument.caretRangeFromPoint(coords.clientX, coords.clientY);
      }
      if (!range2 || !range2.startContainer) {
        return new UnknownHitTestResult();
      }
      const startContainer = range2.startContainer;
      if (startContainer.nodeType === startContainer.TEXT_NODE) {
        const parent1 = startContainer.parentNode;
        const parent2 = parent1 ? parent1.parentNode : null;
        const parent3 = parent2 ? parent2.parentNode : null;
        const parent3ClassName = parent3 && parent3.nodeType === parent3.ELEMENT_NODE ? parent3.className : null;
        if (parent3ClassName === ViewLine.CLASS_NAME) {
          return HitTestResult.createFromDOMInfo(ctx, parent1, range2.startOffset);
        } else {
          return new UnknownHitTestResult(startContainer.parentNode);
        }
      } else if (startContainer.nodeType === startContainer.ELEMENT_NODE) {
        const parent1 = startContainer.parentNode;
        const parent2 = parent1 ? parent1.parentNode : null;
        const parent2ClassName = parent2 && parent2.nodeType === parent2.ELEMENT_NODE ? parent2.className : null;
        if (parent2ClassName === ViewLine.CLASS_NAME) {
          return HitTestResult.createFromDOMInfo(ctx, startContainer, startContainer.textContent.length);
        } else {
          return new UnknownHitTestResult(startContainer);
        }
      }
      return new UnknownHitTestResult();
    }
    /**
     * Most probably Gecko
     */
    static _doHitTestWithCaretPositionFromPoint(ctx, coords) {
      const hitResult = ctx.viewDomNode.ownerDocument.caretPositionFromPoint(coords.clientX, coords.clientY);
      if (hitResult.offsetNode.nodeType === hitResult.offsetNode.TEXT_NODE) {
        const parent1 = hitResult.offsetNode.parentNode;
        const parent2 = parent1 ? parent1.parentNode : null;
        const parent3 = parent2 ? parent2.parentNode : null;
        const parent3ClassName = parent3 && parent3.nodeType === parent3.ELEMENT_NODE ? parent3.className : null;
        if (parent3ClassName === ViewLine.CLASS_NAME) {
          return HitTestResult.createFromDOMInfo(ctx, hitResult.offsetNode.parentNode, hitResult.offset);
        } else {
          return new UnknownHitTestResult(hitResult.offsetNode.parentNode);
        }
      }
      if (hitResult.offsetNode.nodeType === hitResult.offsetNode.ELEMENT_NODE) {
        const parent1 = hitResult.offsetNode.parentNode;
        const parent1ClassName = parent1 && parent1.nodeType === parent1.ELEMENT_NODE ? parent1.className : null;
        const parent2 = parent1 ? parent1.parentNode : null;
        const parent2ClassName = parent2 && parent2.nodeType === parent2.ELEMENT_NODE ? parent2.className : null;
        if (parent1ClassName === ViewLine.CLASS_NAME) {
          const tokenSpan = hitResult.offsetNode.childNodes[Math.min(hitResult.offset, hitResult.offsetNode.childNodes.length - 1)];
          if (tokenSpan) {
            return HitTestResult.createFromDOMInfo(ctx, tokenSpan, 0);
          }
        } else if (parent2ClassName === ViewLine.CLASS_NAME) {
          return HitTestResult.createFromDOMInfo(ctx, hitResult.offsetNode, 0);
        }
      }
      return new UnknownHitTestResult(hitResult.offsetNode);
    }
    static _snapToSoftTabBoundary(position, viewModel) {
      const lineContent = viewModel.getLineContent(position.lineNumber);
      const { tabSize } = viewModel.model.getOptions();
      const newPosition = AtomicTabMoveOperations.atomicPosition(
        lineContent,
        position.column - 1,
        tabSize,
        2
        /* Direction.Nearest */
      );
      if (newPosition !== -1) {
        return new Position$1(position.lineNumber, newPosition + 1);
      }
      return position;
    }
    static doHitTest(ctx, request) {
      let result = new UnknownHitTestResult();
      if (typeof ctx.viewDomNode.ownerDocument.caretRangeFromPoint === "function") {
        result = this._doHitTestWithCaretRangeFromPoint(ctx, request);
      } else if (ctx.viewDomNode.ownerDocument.caretPositionFromPoint) {
        result = this._doHitTestWithCaretPositionFromPoint(ctx, request.pos.toClientCoordinates(getWindow(ctx.viewDomNode)));
      }
      if (result.type === 1) {
        const injectedText = ctx.viewModel.getInjectedTextAt(result.position);
        const normalizedPosition = ctx.viewModel.normalizePosition(
          result.position,
          2
          /* PositionAffinity.None */
        );
        if (injectedText || !normalizedPosition.equals(result.position)) {
          result = new ContentHitTestResult(normalizedPosition, result.spanNode, injectedText);
        }
      }
      return result;
    }
  }
  function shadowCaretRangeFromPoint(shadowRoot, x, y) {
    const range2 = document.createRange();
    let el = shadowRoot.elementFromPoint(x, y);
    if (el?.hasChildNodes()) {
      while (el && el.firstChild && el.firstChild.nodeType !== el.firstChild.TEXT_NODE && el.lastChild && el.lastChild.firstChild) {
        el = el.lastChild;
      }
      const rect = el.getBoundingClientRect();
      const elWindow = getWindow(el);
      const fontStyle = elWindow.getComputedStyle(el, null).getPropertyValue("font-style");
      const fontVariant = elWindow.getComputedStyle(el, null).getPropertyValue("font-variant");
      const fontWeight = elWindow.getComputedStyle(el, null).getPropertyValue("font-weight");
      const fontSize = elWindow.getComputedStyle(el, null).getPropertyValue("font-size");
      const lineHeight = elWindow.getComputedStyle(el, null).getPropertyValue("line-height");
      const fontFamily = elWindow.getComputedStyle(el, null).getPropertyValue("font-family");
      const font = `${fontStyle} ${fontVariant} ${fontWeight} ${fontSize}/${lineHeight} ${fontFamily}`;
      const text2 = el.innerText;
      let pixelCursor = rect.left;
      let offset = 0;
      let step;
      if (x > rect.left + rect.width) {
        offset = text2.length;
      } else {
        const charWidthReader = CharWidthReader.getInstance();
        for (let i2 = 0; i2 < text2.length + 1; i2++) {
          step = charWidthReader.getCharWidth(text2.charAt(i2), font) / 2;
          pixelCursor += step;
          if (x < pixelCursor) {
            offset = i2;
            break;
          }
          pixelCursor += step;
        }
      }
      range2.setStart(el.firstChild, offset);
      range2.setEnd(el.firstChild, offset);
    }
    return range2;
  }
  const _CharWidthReader = class _CharWidthReader {
    static getInstance() {
      if (!_CharWidthReader._INSTANCE) {
        _CharWidthReader._INSTANCE = new _CharWidthReader();
      }
      return _CharWidthReader._INSTANCE;
    }
    constructor() {
      this._cache = {};
      this._canvas = document.createElement("canvas");
    }
    getCharWidth(char, font) {
      const cacheKey = char + font;
      if (this._cache[cacheKey]) {
        return this._cache[cacheKey];
      }
      const context = this._canvas.getContext("2d");
      context.font = font;
      const metrics = context.measureText(char);
      const width2 = metrics.width;
      this._cache[cacheKey] = width2;
      return width2;
    }
  };
  _CharWidthReader._INSTANCE = null;
  let CharWidthReader = _CharWidthReader;
  function memoize(_target, key, descriptor) {
    let fnKey = null;
    let fn = null;
    if (typeof descriptor.value === "function") {
      fnKey = "value";
      fn = descriptor.value;
      if (fn.length !== 0) {
        console.warn("Memoize should only be used in functions with zero parameters");
      }
    } else if (typeof descriptor.get === "function") {
      fnKey = "get";
      fn = descriptor.get;
    }
    if (!fn) {
      throw new Error("not supported");
    }
    const memoizeKey = `$memoize$${key}`;
    descriptor[fnKey] = function(...args) {
      if (!this.hasOwnProperty(memoizeKey)) {
        Object.defineProperty(this, memoizeKey, {
          configurable: false,
          enumerable: false,
          writable: false,
          value: fn.apply(this, args)
        });
      }
      return this[memoizeKey];
    };
  }
  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 EventType;
  (function(EventType2) {
    EventType2.Tap = "-monaco-gesturetap";
    EventType2.Change = "-monaco-gesturechange";
    EventType2.Start = "-monaco-gesturestart";
    EventType2.End = "-monaco-gesturesend";
    EventType2.Contextmenu = "-monaco-gesturecontextmenu";
  })(EventType || (EventType = {}));
  const _Gesture = class _Gesture extends Disposable {
    // ms
    constructor() {
      super();
      this.dispatched = false;
      this.targets = new LinkedList();
      this.ignoreTargets = new LinkedList();
      this.activeTouches = {};
      this.handle = null;
      this._lastSetTapCountTime = 0;
      this._register(Event.runAndSubscribe(onDidRegisterWindow, ({ window: window2, disposables }) => {
        disposables.add(addDisposableListener(window2.document, "touchstart", (e) => this.onTouchStart(e), { passive: false }));
        disposables.add(addDisposableListener(window2.document, "touchend", (e) => this.onTouchEnd(window2, e)));
        disposables.add(addDisposableListener(window2.document, "touchmove", (e) => this.onTouchMove(e), { passive: false }));
      }, { window: mainWindow, disposables: this._store }));
    }
    static addTarget(element) {
      if (!_Gesture.isTouchDevice()) {
        return Disposable.None;
      }
      if (!_Gesture.INSTANCE) {
        _Gesture.INSTANCE = markAsSingleton(new _Gesture());
      }
      const remove = _Gesture.INSTANCE.targets.push(element);
      return toDisposable(remove);
    }
    static ignoreTarget(element) {
      if (!_Gesture.isTouchDevice()) {
        return Disposable.None;
      }
      if (!_Gesture.INSTANCE) {
        _Gesture.INSTANCE = markAsSingleton(new _Gesture());
      }
      const remove = _Gesture.INSTANCE.ignoreTargets.push(element);
      return toDisposable(remove);
    }
    static isTouchDevice() {
      return "ontouchstart" in mainWindow || navigator.maxTouchPoints > 0;
    }
    dispose() {
      if (this.handle) {
        this.handle.dispose();
        this.handle = null;
      }
      super.dispose();
    }
    onTouchStart(e) {
      const timestamp = Date.now();
      if (this.handle) {
        this.handle.dispose();
        this.handle = null;
      }
      for (let i2 = 0, len = e.targetTouches.length; i2 < len; i2++) {
        const touch = e.targetTouches.item(i2);
        this.activeTouches[touch.identifier] = {
          id: touch.identifier,
          initialTarget: touch.target,
          initialTimeStamp: timestamp,
          initialPageX: touch.pageX,
          initialPageY: touch.pageY,
          rollingTimestamps: [timestamp],
          rollingPageX: [touch.pageX],
          rollingPageY: [touch.pageY]
        };
        const evt = this.newGestureEvent(EventType.Start, touch.target);
        evt.pageX = touch.pageX;
        evt.pageY = touch.pageY;
        this.dispatchEvent(evt);
      }
      if (this.dispatched) {
        e.preventDefault();
        e.stopPropagation();
        this.dispatched = false;
      }
    }
    onTouchEnd(targetWindow, e) {
      const timestamp = Date.now();
      const activeTouchCount = Object.keys(this.activeTouches).length;
      for (let i2 = 0, len = e.changedTouches.length; i2 < len; i2++) {
        const touch = e.changedTouches.item(i2);
        if (!this.activeTouches.hasOwnProperty(String(touch.identifier))) {
          console.warn("move of an UNKNOWN touch", touch);
          continue;
        }
        const data = this.activeTouches[touch.identifier], holdTime = Date.now() - data.initialTimeStamp;
        if (holdTime < _Gesture.HOLD_DELAY && Math.abs(data.initialPageX - data.rollingPageX.at(-1)) < 30 && Math.abs(data.initialPageY - data.rollingPageY.at(-1)) < 30) {
          const evt = this.newGestureEvent(EventType.Tap, data.initialTarget);
          evt.pageX = data.rollingPageX.at(-1);
          evt.pageY = data.rollingPageY.at(-1);
          this.dispatchEvent(evt);
        } else if (holdTime >= _Gesture.HOLD_DELAY && Math.abs(data.initialPageX - data.rollingPageX.at(-1)) < 30 && Math.abs(data.initialPageY - data.rollingPageY.at(-1)) < 30) {
          const evt = this.newGestureEvent(EventType.Contextmenu, data.initialTarget);
          evt.pageX = data.rollingPageX.at(-1);
          evt.pageY = data.rollingPageY.at(-1);
          this.dispatchEvent(evt);
        } else if (activeTouchCount === 1) {
          const finalX = data.rollingPageX.at(-1);
          const finalY = data.rollingPageY.at(-1);
          const deltaT = data.rollingTimestamps.at(-1) - data.rollingTimestamps[0];
          const deltaX = finalX - data.rollingPageX[0];
          const deltaY = finalY - data.rollingPageY[0];
          const dispatchTo = [...this.targets].filter((t) => data.initialTarget instanceof Node && t.contains(data.initialTarget));
          this.inertia(
            targetWindow,
            dispatchTo,
            timestamp,
            // time now
            Math.abs(deltaX) / deltaT,
            // speed
            deltaX > 0 ? 1 : -1,
            // x direction
            finalX,
            // x now
            Math.abs(deltaY) / deltaT,
            // y speed
            deltaY > 0 ? 1 : -1,
            // y direction
            finalY
            // y now
          );
        }
        this.dispatchEvent(this.newGestureEvent(EventType.End, data.initialTarget));
        delete this.activeTouches[touch.identifier];
      }
      if (this.dispatched) {
        e.preventDefault();
        e.stopPropagation();
        this.dispatched = false;
      }
    }
    newGestureEvent(type, initialTarget) {
      const event = document.createEvent("CustomEvent");
      event.initEvent(type, false, true);
      event.initialTarget = initialTarget;
      event.tapCount = 0;
      return event;
    }
    dispatchEvent(event) {
      if (event.type === EventType.Tap) {
        const currentTime = (/* @__PURE__ */ new Date()).getTime();
        let setTapCount = 0;
        if (currentTime - this._lastSetTapCountTime > _Gesture.CLEAR_TAP_COUNT_TIME) {
          setTapCount = 1;
        } else {
          setTapCount = 2;
        }
        this._lastSetTapCountTime = currentTime;
        event.tapCount = setTapCount;
      } else if (event.type === EventType.Change || event.type === EventType.Contextmenu) {
        this._lastSetTapCountTime = 0;
      }
      if (event.initialTarget instanceof Node) {
        for (const ignoreTarget of this.ignoreTargets) {
          if (ignoreTarget.contains(event.initialTarget)) {
            return;
          }
        }
        const targets = [];
        for (const target of this.targets) {
          if (target.contains(event.initialTarget)) {
            let depth = 0;
            let now = event.initialTarget;
            while (now && now !== target) {
              depth++;
              now = now.parentElement;
            }
            targets.push([depth, target]);
          }
        }
        targets.sort((a, b) => a[0] - b[0]);
        for (const [_, target] of targets) {
          target.dispatchEvent(event);
          this.dispatched = true;
        }
      }
    }
    inertia(targetWindow, dispatchTo, t1, vX, dirX, x, vY, dirY, y) {
      this.handle = scheduleAtNextAnimationFrame(targetWindow, () => {
        const now = Date.now();
        const deltaT = now - t1;
        let delta_pos_x = 0, delta_pos_y = 0;
        let stopped = true;
        vX += _Gesture.SCROLL_FRICTION * deltaT;
        vY += _Gesture.SCROLL_FRICTION * deltaT;
        if (vX > 0) {
          stopped = false;
          delta_pos_x = dirX * vX * deltaT;
        }
        if (vY > 0) {
          stopped = false;
          delta_pos_y = dirY * vY * deltaT;
        }
        const evt = this.newGestureEvent(EventType.Change);
        evt.translationX = delta_pos_x;
        evt.translationY = delta_pos_y;
        dispatchTo.forEach((d) => d.dispatchEvent(evt));
        if (!stopped) {
          this.inertia(targetWindow, dispatchTo, now, vX, dirX, x + delta_pos_x, vY, dirY, y + delta_pos_y);
        }
      });
    }
    onTouchMove(e) {
      const timestamp = Date.now();
      for (let i2 = 0, len = e.changedTouches.length; i2 < len; i2++) {
        const touch = e.changedTouches.item(i2);
        if (!this.activeTouches.hasOwnProperty(String(touch.identifier))) {
          console.warn("end of an UNKNOWN touch", touch);
          continue;
        }
        const data = this.activeTouches[touch.identifier];
        const evt = this.newGestureEvent(EventType.Change, data.initialTarget);
        evt.translationX = touch.pageX - data.rollingPageX.at(-1);
        evt.translationY = touch.pageY - data.rollingPageY.at(-1);
        evt.pageX = touch.pageX;
        evt.pageY = touch.pageY;
        this.dispatchEvent(evt);
        if (data.rollingPageX.length > 3) {
          data.rollingPageX.shift();
          data.rollingPageY.shift();
          data.rollingTimestamps.shift();
        }
        data.rollingPageX.push(touch.pageX);
        data.rollingPageY.push(touch.pageY);
        data.rollingTimestamps.push(timestamp);
      }
      if (this.dispatched) {
        e.preventDefault();
        e.stopPropagation();
        this.dispatched = false;
      }
    }
  };
  _Gesture.SCROLL_FRICTION = -5e-3;
  _Gesture.HOLD_DELAY = 700;
  _Gesture.CLEAR_TAP_COUNT_TIME = 400;
  let Gesture = _Gesture;
  __decorate$32([
    memoize
  ], Gesture, "isTouchDevice", null);
  let Widget$1 = class Widget extends Disposable {
    onclick(domNode, listener) {
      this._register(addDisposableListener(domNode, EventType$1.CLICK, (e) => listener(new StandardMouseEvent(getWindow(domNode), e))));
    }
    onmousedown(domNode, listener) {
      this._register(addDisposableListener(domNode, EventType$1.MOUSE_DOWN, (e) => listener(new StandardMouseEvent(getWindow(domNode), e))));
    }
    onmouseover(domNode, listener) {
      this._register(addDisposableListener(domNode, EventType$1.MOUSE_OVER, (e) => listener(new StandardMouseEvent(getWindow(domNode), e))));
    }
    onmouseleave(domNode, listener) {
      this._register(addDisposableListener(domNode, EventType$1.MOUSE_LEAVE, (e) => listener(new StandardMouseEvent(getWindow(domNode), e))));
    }
    onkeydown(domNode, listener) {
      this._register(addDisposableListener(domNode, EventType$1.KEY_DOWN, (e) => listener(new StandardKeyboardEvent(e))));
    }
    onkeyup(domNode, listener) {
      this._register(addDisposableListener(domNode, EventType$1.KEY_UP, (e) => listener(new StandardKeyboardEvent(e))));
    }
    oninput(domNode, listener) {
      this._register(addDisposableListener(domNode, EventType$1.INPUT, listener));
    }
    onblur(domNode, listener) {
      this._register(addDisposableListener(domNode, EventType$1.BLUR, listener));
    }
    onfocus(domNode, listener) {
      this._register(addDisposableListener(domNode, EventType$1.FOCUS, listener));
    }
    ignoreGesture(domNode) {
      return Gesture.ignoreTarget(domNode);
    }
  };
  const ARROW_IMG_SIZE = 11;
  class ScrollbarArrow extends Widget$1 {
    constructor(opts) {
      super();
      this._onActivate = opts.onActivate;
      this.bgDomNode = document.createElement("div");
      this.bgDomNode.className = "arrow-background";
      this.bgDomNode.style.position = "absolute";
      this.bgDomNode.style.width = opts.bgWidth + "px";
      this.bgDomNode.style.height = opts.bgHeight + "px";
      if (typeof opts.top !== "undefined") {
        this.bgDomNode.style.top = "0px";
      }
      if (typeof opts.left !== "undefined") {
        this.bgDomNode.style.left = "0px";
      }
      if (typeof opts.bottom !== "undefined") {
        this.bgDomNode.style.bottom = "0px";
      }
      if (typeof opts.right !== "undefined") {
        this.bgDomNode.style.right = "0px";
      }
      this.domNode = document.createElement("div");
      this.domNode.className = opts.className;
      this.domNode.classList.add(...ThemeIcon.asClassNameArray(opts.icon));
      this.domNode.style.position = "absolute";
      this.domNode.style.width = ARROW_IMG_SIZE + "px";
      this.domNode.style.height = ARROW_IMG_SIZE + "px";
      if (typeof opts.top !== "undefined") {
        this.domNode.style.top = opts.top + "px";
      }
      if (typeof opts.left !== "undefined") {
        this.domNode.style.left = opts.left + "px";
      }
      if (typeof opts.bottom !== "undefined") {
        this.domNode.style.bottom = opts.bottom + "px";
      }
      if (typeof opts.right !== "undefined") {
        this.domNode.style.right = opts.right + "px";
      }
      this._pointerMoveMonitor = this._register(new GlobalPointerMoveMonitor());
      this._register(addStandardDisposableListener(this.bgDomNode, EventType$1.POINTER_DOWN, (e) => this._arrowPointerDown(e)));
      this._register(addStandardDisposableListener(this.domNode, EventType$1.POINTER_DOWN, (e) => this._arrowPointerDown(e)));
      this._pointerdownRepeatTimer = this._register(new WindowIntervalTimer());
      this._pointerdownScheduleRepeatTimer = this._register(new TimeoutTimer());
    }
    _arrowPointerDown(e) {
      if (!e.target || !(e.target instanceof Element)) {
        return;
      }
      const scheduleRepeater = () => {
        this._pointerdownRepeatTimer.cancelAndSet(() => this._onActivate(), 1e3 / 24, getWindow(e));
      };
      this._onActivate();
      this._pointerdownRepeatTimer.cancel();
      this._pointerdownScheduleRepeatTimer.cancelAndSet(scheduleRepeater, 200);
      this._pointerMoveMonitor.startMonitoring(e.target, e.pointerId, e.buttons, (pointerMoveData) => {
      }, () => {
        this._pointerdownRepeatTimer.cancel();
        this._pointerdownScheduleRepeatTimer.cancel();
      });
      e.preventDefault();
    }
  }
  class ScrollbarVisibilityController extends Disposable {
    constructor(visibility, visibleClassName, invisibleClassName) {
      super();
      this._visibility = visibility;
      this._visibleClassName = visibleClassName;
      this._invisibleClassName = invisibleClassName;
      this._domNode = null;
      this._isVisible = false;
      this._isNeeded = false;
      this._rawShouldBeVisible = false;
      this._shouldBeVisible = false;
      this._revealTimer = this._register(new TimeoutTimer());
    }
    setVisibility(visibility) {
      if (this._visibility !== visibility) {
        this._visibility = visibility;
        this._updateShouldBeVisible();
      }
    }
    // ----------------- Hide / Reveal
    setShouldBeVisible(rawShouldBeVisible) {
      this._rawShouldBeVisible = rawShouldBeVisible;
      this._updateShouldBeVisible();
    }
    _applyVisibilitySetting() {
      if (this._visibility === 2) {
        return false;
      }
      if (this._visibility === 3) {
        return true;
      }
      return this._rawShouldBeVisible;
    }
    _updateShouldBeVisible() {
      const shouldBeVisible = this._applyVisibilitySetting();
      if (this._shouldBeVisible !== shouldBeVisible) {
        this._shouldBeVisible = shouldBeVisible;
        this.ensureVisibility();
      }
    }
    setIsNeeded(isNeeded) {
      if (this._isNeeded !== isNeeded) {
        this._isNeeded = isNeeded;
        this.ensureVisibility();
      }
    }
    setDomNode(domNode) {
      this._domNode = domNode;
      this._domNode.setClassName(this._invisibleClassName);
      this.setShouldBeVisible(false);
    }
    ensureVisibility() {
      if (!this._isNeeded) {
        this._hide(false);
        return;
      }
      if (this._shouldBeVisible) {
        this._reveal();
      } else {
        this._hide(true);
      }
    }
    _reveal() {
      if (this._isVisible) {
        return;
      }
      this._isVisible = true;
      this._revealTimer.setIfNotSet(() => {
        this._domNode?.setClassName(this._visibleClassName);
      }, 0);
    }
    _hide(withFadeAway) {
      this._revealTimer.cancel();
      if (!this._isVisible) {
        return;
      }
      this._isVisible = false;
      this._domNode?.setClassName(this._invisibleClassName + (withFadeAway ? " fade" : ""));
    }
  }
  const POINTER_DRAG_RESET_DISTANCE$1 = 140;
  class AbstractScrollbar extends Widget$1 {
    constructor(opts) {
      super();
      this._lazyRender = opts.lazyRender;
      this._host = opts.host;
      this._scrollable = opts.scrollable;
      this._scrollByPage = opts.scrollByPage;
      this._scrollbarState = opts.scrollbarState;
      this._visibilityController = this._register(new ScrollbarVisibilityController(opts.visibility, "visible scrollbar " + opts.extraScrollbarClassName, "invisible scrollbar " + opts.extraScrollbarClassName));
      this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded());
      this._pointerMoveMonitor = this._register(new GlobalPointerMoveMonitor());
      this._shouldRender = true;
      this.domNode = createFastDomNode(document.createElement("div"));
      this.domNode.setAttribute("role", "presentation");
      this.domNode.setAttribute("aria-hidden", "true");
      this._visibilityController.setDomNode(this.domNode);
      this.domNode.setPosition("absolute");
      this._register(addDisposableListener(this.domNode.domNode, EventType$1.POINTER_DOWN, (e) => this._domNodePointerDown(e)));
    }
    // ----------------- creation
    /**
     * Creates the dom node for an arrow & adds it to the container
     */
    _createArrow(opts) {
      const arrow = this._register(new ScrollbarArrow(opts));
      this.domNode.domNode.appendChild(arrow.bgDomNode);
      this.domNode.domNode.appendChild(arrow.domNode);
    }
    /**
     * Creates the slider dom node, adds it to the container & hooks up the events
     */
    _createSlider(top, left, width2, height) {
      this.slider = createFastDomNode(document.createElement("div"));
      this.slider.setClassName("slider");
      this.slider.setPosition("absolute");
      this.slider.setTop(top);
      this.slider.setLeft(left);
      if (typeof width2 === "number") {
        this.slider.setWidth(width2);
      }
      if (typeof height === "number") {
        this.slider.setHeight(height);
      }
      this.slider.setLayerHinting(true);
      this.slider.setContain("strict");
      this.domNode.domNode.appendChild(this.slider.domNode);
      this._register(addDisposableListener(this.slider.domNode, EventType$1.POINTER_DOWN, (e) => {
        if (e.button === 0) {
          e.preventDefault();
          this._sliderPointerDown(e);
        }
      }));
      this.onclick(this.slider.domNode, (e) => {
        if (e.leftButton) {
          e.stopPropagation();
        }
      });
    }
    // ----------------- Update state
    _onElementSize(visibleSize) {
      if (this._scrollbarState.setVisibleSize(visibleSize)) {
        this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded());
        this._shouldRender = true;
        if (!this._lazyRender) {
          this.render();
        }
      }
      return this._shouldRender;
    }
    _onElementScrollSize(elementScrollSize) {
      if (this._scrollbarState.setScrollSize(elementScrollSize)) {
        this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded());
        this._shouldRender = true;
        if (!this._lazyRender) {
          this.render();
        }
      }
      return this._shouldRender;
    }
    _onElementScrollPosition(elementScrollPosition) {
      if (this._scrollbarState.setScrollPosition(elementScrollPosition)) {
        this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded());
        this._shouldRender = true;
        if (!this._lazyRender) {
          this.render();
        }
      }
      return this._shouldRender;
    }
    // ----------------- rendering
    beginReveal() {
      this._visibilityController.setShouldBeVisible(true);
    }
    beginHide() {
      this._visibilityController.setShouldBeVisible(false);
    }
    render() {
      if (!this._shouldRender) {
        return;
      }
      this._shouldRender = false;
      this._renderDomNode(this._scrollbarState.getRectangleLargeSize(), this._scrollbarState.getRectangleSmallSize());
      this._updateSlider(this._scrollbarState.getSliderSize(), this._scrollbarState.getArrowSize() + this._scrollbarState.getSliderPosition());
    }
    // ----------------- DOM events
    _domNodePointerDown(e) {
      if (e.target !== this.domNode.domNode) {
        return;
      }
      this._onPointerDown(e);
    }
    delegatePointerDown(e) {
      const domTop = this.domNode.domNode.getClientRects()[0].top;
      const sliderStart = domTop + this._scrollbarState.getSliderPosition();
      const sliderStop = domTop + this._scrollbarState.getSliderPosition() + this._scrollbarState.getSliderSize();
      const pointerPos = this._sliderPointerPosition(e);
      if (sliderStart <= pointerPos && pointerPos <= sliderStop) {
        if (e.button === 0) {
          e.preventDefault();
          this._sliderPointerDown(e);
        }
      } else {
        this._onPointerDown(e);
      }
    }
    _onPointerDown(e) {
      let offsetX;
      let offsetY;
      if (e.target === this.domNode.domNode && typeof e.offsetX === "number" && typeof e.offsetY === "number") {
        offsetX = e.offsetX;
        offsetY = e.offsetY;
      } else {
        const domNodePosition = getDomNodePagePosition(this.domNode.domNode);
        offsetX = e.pageX - domNodePosition.left;
        offsetY = e.pageY - domNodePosition.top;
      }
      const isMouse = e.pointerType === "mouse";
      const isLeftClick = e.button === 0;
      if (isLeftClick || !isMouse) {
        const offset = this._pointerDownRelativePosition(offsetX, offsetY);
        this._setDesiredScrollPositionNow(this._scrollByPage ? this._scrollbarState.getDesiredScrollPositionFromOffsetPaged(offset) : this._scrollbarState.getDesiredScrollPositionFromOffset(offset));
      }
      if (isLeftClick) {
        e.preventDefault();
        this._sliderPointerDown(e);
      }
    }
    _sliderPointerDown(e) {
      if (!e.target || !(e.target instanceof Element)) {
        return;
      }
      const initialPointerPosition = this._sliderPointerPosition(e);
      const initialPointerOrthogonalPosition = this._sliderOrthogonalPointerPosition(e);
      const initialScrollbarState = this._scrollbarState.clone();
      this.slider.toggleClassName("active", true);
      this._pointerMoveMonitor.startMonitoring(e.target, e.pointerId, e.buttons, (pointerMoveData) => {
        const pointerOrthogonalPosition = this._sliderOrthogonalPointerPosition(pointerMoveData);
        const pointerOrthogonalDelta = Math.abs(pointerOrthogonalPosition - initialPointerOrthogonalPosition);
        if (isWindows && pointerOrthogonalDelta > POINTER_DRAG_RESET_DISTANCE$1) {
          this._setDesiredScrollPositionNow(initialScrollbarState.getScrollPosition());
          return;
        }
        const pointerPosition = this._sliderPointerPosition(pointerMoveData);
        const pointerDelta = pointerPosition - initialPointerPosition;
        this._setDesiredScrollPositionNow(initialScrollbarState.getDesiredScrollPositionFromDelta(pointerDelta));
      }, () => {
        this.slider.toggleClassName("active", false);
        this._host.onDragEnd();
      });
      this._host.onDragStart();
    }
    _setDesiredScrollPositionNow(_desiredScrollPosition) {
      const desiredScrollPosition = {};
      this.writeScrollPosition(desiredScrollPosition, _desiredScrollPosition);
      this._scrollable.setScrollPositionNow(desiredScrollPosition);
    }
    updateScrollbarSize(scrollbarSize) {
      this._updateScrollbarSize(scrollbarSize);
      this._scrollbarState.setScrollbarSize(scrollbarSize);
      this._shouldRender = true;
      if (!this._lazyRender) {
        this.render();
      }
    }
    isNeeded() {
      return this._scrollbarState.isNeeded();
    }
  }
  const MINIMUM_SLIDER_SIZE = 20;
  class ScrollbarState {
    constructor(arrowSize, scrollbarSize, oppositeScrollbarSize, visibleSize, scrollSize, scrollPosition) {
      this._scrollbarSize = Math.round(scrollbarSize);
      this._oppositeScrollbarSize = Math.round(oppositeScrollbarSize);
      this._arrowSize = Math.round(arrowSize);
      this._visibleSize = visibleSize;
      this._scrollSize = scrollSize;
      this._scrollPosition = scrollPosition;
      this._computedAvailableSize = 0;
      this._computedIsNeeded = false;
      this._computedSliderSize = 0;
      this._computedSliderRatio = 0;
      this._computedSliderPosition = 0;
      this._refreshComputedValues();
    }
    clone() {
      return new ScrollbarState(this._arrowSize, this._scrollbarSize, this._oppositeScrollbarSize, this._visibleSize, this._scrollSize, this._scrollPosition);
    }
    setVisibleSize(visibleSize) {
      const iVisibleSize = Math.round(visibleSize);
      if (this._visibleSize !== iVisibleSize) {
        this._visibleSize = iVisibleSize;
        this._refreshComputedValues();
        return true;
      }
      return false;
    }
    setScrollSize(scrollSize) {
      const iScrollSize = Math.round(scrollSize);
      if (this._scrollSize !== iScrollSize) {
        this._scrollSize = iScrollSize;
        this._refreshComputedValues();
        return true;
      }
      return false;
    }
    setScrollPosition(scrollPosition) {
      const iScrollPosition = Math.round(scrollPosition);
      if (this._scrollPosition !== iScrollPosition) {
        this._scrollPosition = iScrollPosition;
        this._refreshComputedValues();
        return true;
      }
      return false;
    }
    setScrollbarSize(scrollbarSize) {
      this._scrollbarSize = Math.round(scrollbarSize);
    }
    setOppositeScrollbarSize(oppositeScrollbarSize) {
      this._oppositeScrollbarSize = Math.round(oppositeScrollbarSize);
    }
    static _computeValues(oppositeScrollbarSize, arrowSize, visibleSize, scrollSize, scrollPosition) {
      const computedAvailableSize = Math.max(0, visibleSize - oppositeScrollbarSize);
      const computedRepresentableSize = Math.max(0, computedAvailableSize - 2 * arrowSize);
      const computedIsNeeded = scrollSize > 0 && scrollSize > visibleSize;
      if (!computedIsNeeded) {
        return {
          computedAvailableSize: Math.round(computedAvailableSize),
          computedIsNeeded,
          computedSliderSize: Math.round(computedRepresentableSize),
          computedSliderRatio: 0,
          computedSliderPosition: 0
        };
      }
      const computedSliderSize = Math.round(Math.max(MINIMUM_SLIDER_SIZE, Math.floor(visibleSize * computedRepresentableSize / scrollSize)));
      const computedSliderRatio = (computedRepresentableSize - computedSliderSize) / (scrollSize - visibleSize);
      const computedSliderPosition = scrollPosition * computedSliderRatio;
      return {
        computedAvailableSize: Math.round(computedAvailableSize),
        computedIsNeeded,
        computedSliderSize: Math.round(computedSliderSize),
        computedSliderRatio,
        computedSliderPosition: Math.round(computedSliderPosition)
      };
    }
    _refreshComputedValues() {
      const r = ScrollbarState._computeValues(this._oppositeScrollbarSize, this._arrowSize, this._visibleSize, this._scrollSize, this._scrollPosition);
      this._computedAvailableSize = r.computedAvailableSize;
      this._computedIsNeeded = r.computedIsNeeded;
      this._computedSliderSize = r.computedSliderSize;
      this._computedSliderRatio = r.computedSliderRatio;
      this._computedSliderPosition = r.computedSliderPosition;
    }
    getArrowSize() {
      return this._arrowSize;
    }
    getScrollPosition() {
      return this._scrollPosition;
    }
    getRectangleLargeSize() {
      return this._computedAvailableSize;
    }
    getRectangleSmallSize() {
      return this._scrollbarSize;
    }
    isNeeded() {
      return this._computedIsNeeded;
    }
    getSliderSize() {
      return this._computedSliderSize;
    }
    getSliderPosition() {
      return this._computedSliderPosition;
    }
    /**
     * Compute a desired `scrollPosition` such that `offset` ends up in the center of the slider.
     * `offset` is based on the same coordinate system as the `sliderPosition`.
     */
    getDesiredScrollPositionFromOffset(offset) {
      if (!this._computedIsNeeded) {
        return 0;
      }
      const desiredSliderPosition = offset - this._arrowSize - this._computedSliderSize / 2;
      return Math.round(desiredSliderPosition / this._computedSliderRatio);
    }
    /**
     * Compute a desired `scrollPosition` from if offset is before or after the slider position.
     * If offset is before slider, treat as a page up (or left).  If after, page down (or right).
     * `offset` and `_computedSliderPosition` are based on the same coordinate system.
     * `_visibleSize` corresponds to a "page" of lines in the returned coordinate system.
     */
    getDesiredScrollPositionFromOffsetPaged(offset) {
      if (!this._computedIsNeeded) {
        return 0;
      }
      const correctedOffset = offset - this._arrowSize;
      let desiredScrollPosition = this._scrollPosition;
      if (correctedOffset < this._computedSliderPosition) {
        desiredScrollPosition -= this._visibleSize;
      } else {
        desiredScrollPosition += this._visibleSize;
      }
      return desiredScrollPosition;
    }
    /**
     * Compute a desired `scrollPosition` such that the slider moves by `delta`.
     */
    getDesiredScrollPositionFromDelta(delta) {
      if (!this._computedIsNeeded) {
        return 0;
      }
      const desiredSliderPosition = this._computedSliderPosition + delta;
      return Math.round(desiredSliderPosition / this._computedSliderRatio);
    }
  }
  class HorizontalScrollbar extends AbstractScrollbar {
    constructor(scrollable, options, host) {
      const scrollDimensions = scrollable.getScrollDimensions();
      const scrollPosition = scrollable.getCurrentScrollPosition();
      super({
        lazyRender: options.lazyRender,
        host,
        scrollbarState: new ScrollbarState(options.horizontalHasArrows ? options.arrowSize : 0, options.horizontal === 2 ? 0 : options.horizontalScrollbarSize, options.vertical === 2 ? 0 : options.verticalScrollbarSize, scrollDimensions.width, scrollDimensions.scrollWidth, scrollPosition.scrollLeft),
        visibility: options.horizontal,
        extraScrollbarClassName: "horizontal",
        scrollable,
        scrollByPage: options.scrollByPage
      });
      if (options.horizontalHasArrows) {
        const arrowDelta = (options.arrowSize - ARROW_IMG_SIZE) / 2;
        const scrollbarDelta = (options.horizontalScrollbarSize - ARROW_IMG_SIZE) / 2;
        this._createArrow({
          className: "scra",
          icon: Codicon.scrollbarButtonLeft,
          top: scrollbarDelta,
          left: arrowDelta,
          bottom: void 0,
          right: void 0,
          bgWidth: options.arrowSize,
          bgHeight: options.horizontalScrollbarSize,
          onActivate: () => this._host.onMouseWheel(new StandardWheelEvent(null, 1, 0))
        });
        this._createArrow({
          className: "scra",
          icon: Codicon.scrollbarButtonRight,
          top: scrollbarDelta,
          left: void 0,
          bottom: void 0,
          right: arrowDelta,
          bgWidth: options.arrowSize,
          bgHeight: options.horizontalScrollbarSize,
          onActivate: () => this._host.onMouseWheel(new StandardWheelEvent(null, -1, 0))
        });
      }
      this._createSlider(Math.floor((options.horizontalScrollbarSize - options.horizontalSliderSize) / 2), 0, void 0, options.horizontalSliderSize);
    }
    _updateSlider(sliderSize, sliderPosition) {
      this.slider.setWidth(sliderSize);
      this.slider.setLeft(sliderPosition);
    }
    _renderDomNode(largeSize, smallSize) {
      this.domNode.setWidth(largeSize);
      this.domNode.setHeight(smallSize);
      this.domNode.setLeft(0);
      this.domNode.setBottom(0);
    }
    onDidScroll(e) {
      this._shouldRender = this._onElementScrollSize(e.scrollWidth) || this._shouldRender;
      this._shouldRender = this._onElementScrollPosition(e.scrollLeft) || this._shouldRender;
      this._shouldRender = this._onElementSize(e.width) || this._shouldRender;
      return this._shouldRender;
    }
    _pointerDownRelativePosition(offsetX, offsetY) {
      return offsetX;
    }
    _sliderPointerPosition(e) {
      return e.pageX;
    }
    _sliderOrthogonalPointerPosition(e) {
      return e.pageY;
    }
    _updateScrollbarSize(size2) {
      this.slider.setHeight(size2);
    }
    writeScrollPosition(target, scrollPosition) {
      target.scrollLeft = scrollPosition;
    }
    updateOptions(options) {
      this.updateScrollbarSize(options.horizontal === 2 ? 0 : options.horizontalScrollbarSize);
      this._scrollbarState.setOppositeScrollbarSize(options.vertical === 2 ? 0 : options.verticalScrollbarSize);
      this._visibilityController.setVisibility(options.horizontal);
      this._scrollByPage = options.scrollByPage;
    }
  }
  class VerticalScrollbar extends AbstractScrollbar {
    constructor(scrollable, options, host) {
      const scrollDimensions = scrollable.getScrollDimensions();
      const scrollPosition = scrollable.getCurrentScrollPosition();
      super({
        lazyRender: options.lazyRender,
        host,
        scrollbarState: new ScrollbarState(
          options.verticalHasArrows ? options.arrowSize : 0,
          options.vertical === 2 ? 0 : options.verticalScrollbarSize,
          // give priority to vertical scroll bar over horizontal and let it scroll all the way to the bottom
          0,
          scrollDimensions.height,
          scrollDimensions.scrollHeight,
          scrollPosition.scrollTop
        ),
        visibility: options.vertical,
        extraScrollbarClassName: "vertical",
        scrollable,
        scrollByPage: options.scrollByPage
      });
      if (options.verticalHasArrows) {
        const arrowDelta = (options.arrowSize - ARROW_IMG_SIZE) / 2;
        const scrollbarDelta = (options.verticalScrollbarSize - ARROW_IMG_SIZE) / 2;
        this._createArrow({
          className: "scra",
          icon: Codicon.scrollbarButtonUp,
          top: arrowDelta,
          left: scrollbarDelta,
          bottom: void 0,
          right: void 0,
          bgWidth: options.verticalScrollbarSize,
          bgHeight: options.arrowSize,
          onActivate: () => this._host.onMouseWheel(new StandardWheelEvent(null, 0, 1))
        });
        this._createArrow({
          className: "scra",
          icon: Codicon.scrollbarButtonDown,
          top: void 0,
          left: scrollbarDelta,
          bottom: arrowDelta,
          right: void 0,
          bgWidth: options.verticalScrollbarSize,
          bgHeight: options.arrowSize,
          onActivate: () => this._host.onMouseWheel(new StandardWheelEvent(null, 0, -1))
        });
      }
      this._createSlider(0, Math.floor((options.verticalScrollbarSize - options.verticalSliderSize) / 2), options.verticalSliderSize, void 0);
    }
    _updateSlider(sliderSize, sliderPosition) {
      this.slider.setHeight(sliderSize);
      this.slider.setTop(sliderPosition);
    }
    _renderDomNode(largeSize, smallSize) {
      this.domNode.setWidth(smallSize);
      this.domNode.setHeight(largeSize);
      this.domNode.setRight(0);
      this.domNode.setTop(0);
    }
    onDidScroll(e) {
      this._shouldRender = this._onElementScrollSize(e.scrollHeight) || this._shouldRender;
      this._shouldRender = this._onElementScrollPosition(e.scrollTop) || this._shouldRender;
      this._shouldRender = this._onElementSize(e.height) || this._shouldRender;
      return this._shouldRender;
    }
    _pointerDownRelativePosition(offsetX, offsetY) {
      return offsetY;
    }
    _sliderPointerPosition(e) {
      return e.pageY;
    }
    _sliderOrthogonalPointerPosition(e) {
      return e.pageX;
    }
    _updateScrollbarSize(size2) {
      this.slider.setWidth(size2);
    }
    writeScrollPosition(target, scrollPosition) {
      target.scrollTop = scrollPosition;
    }
    updateOptions(options) {
      this.updateScrollbarSize(options.vertical === 2 ? 0 : options.verticalScrollbarSize);
      this._scrollbarState.setOppositeScrollbarSize(0);
      this._visibilityController.setVisibility(options.vertical);
      this._scrollByPage = options.scrollByPage;
    }
  }
  class ScrollState {
    constructor(_forceIntegerValues, width2, scrollWidth, scrollLeft, height, scrollHeight, scrollTop) {
      this._forceIntegerValues = _forceIntegerValues;
      this._scrollStateBrand = void 0;
      if (this._forceIntegerValues) {
        width2 = width2 | 0;
        scrollWidth = scrollWidth | 0;
        scrollLeft = scrollLeft | 0;
        height = height | 0;
        scrollHeight = scrollHeight | 0;
        scrollTop = scrollTop | 0;
      }
      this.rawScrollLeft = scrollLeft;
      this.rawScrollTop = scrollTop;
      if (width2 < 0) {
        width2 = 0;
      }
      if (scrollLeft + width2 > scrollWidth) {
        scrollLeft = scrollWidth - width2;
      }
      if (scrollLeft < 0) {
        scrollLeft = 0;
      }
      if (height < 0) {
        height = 0;
      }
      if (scrollTop + height > scrollHeight) {
        scrollTop = scrollHeight - height;
      }
      if (scrollTop < 0) {
        scrollTop = 0;
      }
      this.width = width2;
      this.scrollWidth = scrollWidth;
      this.scrollLeft = scrollLeft;
      this.height = height;
      this.scrollHeight = scrollHeight;
      this.scrollTop = scrollTop;
    }
    equals(other) {
      return this.rawScrollLeft === other.rawScrollLeft && this.rawScrollTop === other.rawScrollTop && this.width === other.width && this.scrollWidth === other.scrollWidth && this.scrollLeft === other.scrollLeft && this.height === other.height && this.scrollHeight === other.scrollHeight && this.scrollTop === other.scrollTop;
    }
    withScrollDimensions(update, useRawScrollPositions) {
      return new ScrollState(this._forceIntegerValues, typeof update.width !== "undefined" ? update.width : this.width, typeof update.scrollWidth !== "undefined" ? update.scrollWidth : this.scrollWidth, useRawScrollPositions ? this.rawScrollLeft : this.scrollLeft, typeof update.height !== "undefined" ? update.height : this.height, typeof update.scrollHeight !== "undefined" ? update.scrollHeight : this.scrollHeight, useRawScrollPositions ? this.rawScrollTop : this.scrollTop);
    }
    withScrollPosition(update) {
      return new ScrollState(this._forceIntegerValues, this.width, this.scrollWidth, typeof update.scrollLeft !== "undefined" ? update.scrollLeft : this.rawScrollLeft, this.height, this.scrollHeight, typeof update.scrollTop !== "undefined" ? update.scrollTop : this.rawScrollTop);
    }
    createScrollEvent(previous, inSmoothScrolling) {
      const widthChanged = this.width !== previous.width;
      const scrollWidthChanged = this.scrollWidth !== previous.scrollWidth;
      const scrollLeftChanged = this.scrollLeft !== previous.scrollLeft;
      const heightChanged = this.height !== previous.height;
      const scrollHeightChanged = this.scrollHeight !== previous.scrollHeight;
      const scrollTopChanged = this.scrollTop !== previous.scrollTop;
      return {
        inSmoothScrolling,
        oldWidth: previous.width,
        oldScrollWidth: previous.scrollWidth,
        oldScrollLeft: previous.scrollLeft,
        width: this.width,
        scrollWidth: this.scrollWidth,
        scrollLeft: this.scrollLeft,
        oldHeight: previous.height,
        oldScrollHeight: previous.scrollHeight,
        oldScrollTop: previous.scrollTop,
        height: this.height,
        scrollHeight: this.scrollHeight,
        scrollTop: this.scrollTop,
        widthChanged,
        scrollWidthChanged,
        scrollLeftChanged,
        heightChanged,
        scrollHeightChanged,
        scrollTopChanged
      };
    }
  }
  class Scrollable extends Disposable {
    constructor(options) {
      super();
      this._scrollableBrand = void 0;
      this._onScroll = this._register(new Emitter$1());
      this.onScroll = this._onScroll.event;
      this._smoothScrollDuration = options.smoothScrollDuration;
      this._scheduleAtNextAnimationFrame = options.scheduleAtNextAnimationFrame;
      this._state = new ScrollState(options.forceIntegerValues, 0, 0, 0, 0, 0, 0);
      this._smoothScrolling = null;
    }
    dispose() {
      if (this._smoothScrolling) {
        this._smoothScrolling.dispose();
        this._smoothScrolling = null;
      }
      super.dispose();
    }
    setSmoothScrollDuration(smoothScrollDuration) {
      this._smoothScrollDuration = smoothScrollDuration;
    }
    validateScrollPosition(scrollPosition) {
      return this._state.withScrollPosition(scrollPosition);
    }
    getScrollDimensions() {
      return this._state;
    }
    setScrollDimensions(dimensions, useRawScrollPositions) {
      const newState = this._state.withScrollDimensions(dimensions, useRawScrollPositions);
      this._setState(newState, Boolean(this._smoothScrolling));
      this._smoothScrolling?.acceptScrollDimensions(this._state);
    }
    /**
     * Returns the final scroll position that the instance will have once the smooth scroll animation concludes.
     * If no scroll animation is occurring, it will return the current scroll position instead.
     */
    getFutureScrollPosition() {
      if (this._smoothScrolling) {
        return this._smoothScrolling.to;
      }
      return this._state;
    }
    /**
     * Returns the current scroll position.
     * Note: This result might be an intermediate scroll position, as there might be an ongoing smooth scroll animation.
     */
    getCurrentScrollPosition() {
      return this._state;
    }
    setScrollPositionNow(update) {
      const newState = this._state.withScrollPosition(update);
      if (this._smoothScrolling) {
        this._smoothScrolling.dispose();
        this._smoothScrolling = null;
      }
      this._setState(newState, false);
    }
    setScrollPositionSmooth(update, reuseAnimation) {
      if (this._smoothScrollDuration === 0) {
        return this.setScrollPositionNow(update);
      }
      if (this._smoothScrolling) {
        update = {
          scrollLeft: typeof update.scrollLeft === "undefined" ? this._smoothScrolling.to.scrollLeft : update.scrollLeft,
          scrollTop: typeof update.scrollTop === "undefined" ? this._smoothScrolling.to.scrollTop : update.scrollTop
        };
        const validTarget = this._state.withScrollPosition(update);
        if (this._smoothScrolling.to.scrollLeft === validTarget.scrollLeft && this._smoothScrolling.to.scrollTop === validTarget.scrollTop) {
          return;
        }
        let newSmoothScrolling;
        if (reuseAnimation) {
          newSmoothScrolling = new SmoothScrollingOperation(this._smoothScrolling.from, validTarget, this._smoothScrolling.startTime, this._smoothScrolling.duration);
        } else {
          newSmoothScrolling = this._smoothScrolling.combine(this._state, validTarget, this._smoothScrollDuration);
        }
        this._smoothScrolling.dispose();
        this._smoothScrolling = newSmoothScrolling;
      } else {
        const validTarget = this._state.withScrollPosition(update);
        this._smoothScrolling = SmoothScrollingOperation.start(this._state, validTarget, this._smoothScrollDuration);
      }
      this._smoothScrolling.animationFrameDisposable = this._scheduleAtNextAnimationFrame(() => {
        if (!this._smoothScrolling) {
          return;
        }
        this._smoothScrolling.animationFrameDisposable = null;
        this._performSmoothScrolling();
      });
    }
    hasPendingScrollAnimation() {
      return Boolean(this._smoothScrolling);
    }
    _performSmoothScrolling() {
      if (!this._smoothScrolling) {
        return;
      }
      const update = this._smoothScrolling.tick();
      const newState = this._state.withScrollPosition(update);
      this._setState(newState, true);
      if (!this._smoothScrolling) {
        return;
      }
      if (update.isDone) {
        this._smoothScrolling.dispose();
        this._smoothScrolling = null;
        return;
      }
      this._smoothScrolling.animationFrameDisposable = this._scheduleAtNextAnimationFrame(() => {
        if (!this._smoothScrolling) {
          return;
        }
        this._smoothScrolling.animationFrameDisposable = null;
        this._performSmoothScrolling();
      });
    }
    _setState(newState, inSmoothScrolling) {
      const oldState = this._state;
      if (oldState.equals(newState)) {
        return;
      }
      this._state = newState;
      this._onScroll.fire(this._state.createScrollEvent(oldState, inSmoothScrolling));
    }
  }
  class SmoothScrollingUpdate {
    constructor(scrollLeft, scrollTop, isDone) {
      this.scrollLeft = scrollLeft;
      this.scrollTop = scrollTop;
      this.isDone = isDone;
    }
  }
  function createEaseOutCubic(from, to) {
    const delta = to - from;
    return function(completion) {
      return from + delta * easeOutCubic$1(completion);
    };
  }
  function createComposed(a, b, cut) {
    return function(completion) {
      if (completion < cut) {
        return a(completion / cut);
      }
      return b((completion - cut) / (1 - cut));
    };
  }
  class SmoothScrollingOperation {
    constructor(from, to, startTime, duration) {
      this.from = from;
      this.to = to;
      this.duration = duration;
      this.startTime = startTime;
      this.animationFrameDisposable = null;
      this._initAnimations();
    }
    _initAnimations() {
      this.scrollLeft = this._initAnimation(this.from.scrollLeft, this.to.scrollLeft, this.to.width);
      this.scrollTop = this._initAnimation(this.from.scrollTop, this.to.scrollTop, this.to.height);
    }
    _initAnimation(from, to, viewportSize) {
      const delta = Math.abs(from - to);
      if (delta > 2.5 * viewportSize) {
        let stop1, stop2;
        if (from < to) {
          stop1 = from + 0.75 * viewportSize;
          stop2 = to - 0.75 * viewportSize;
        } else {
          stop1 = from - 0.75 * viewportSize;
          stop2 = to + 0.75 * viewportSize;
        }
        return createComposed(createEaseOutCubic(from, stop1), createEaseOutCubic(stop2, to), 0.33);
      }
      return createEaseOutCubic(from, to);
    }
    dispose() {
      if (this.animationFrameDisposable !== null) {
        this.animationFrameDisposable.dispose();
        this.animationFrameDisposable = null;
      }
    }
    acceptScrollDimensions(state) {
      this.to = state.withScrollPosition(this.to);
      this._initAnimations();
    }
    tick() {
      return this._tick(Date.now());
    }
    _tick(now) {
      const completion = (now - this.startTime) / this.duration;
      if (completion < 1) {
        const newScrollLeft = this.scrollLeft(completion);
        const newScrollTop = this.scrollTop(completion);
        return new SmoothScrollingUpdate(newScrollLeft, newScrollTop, false);
      }
      return new SmoothScrollingUpdate(this.to.scrollLeft, this.to.scrollTop, true);
    }
    combine(from, to, duration) {
      return SmoothScrollingOperation.start(from, to, duration);
    }
    static start(from, to, duration) {
      duration = duration + 10;
      const startTime = Date.now() - 10;
      return new SmoothScrollingOperation(from, to, startTime, duration);
    }
  }
  function easeInCubic(t) {
    return Math.pow(t, 3);
  }
  function easeOutCubic$1(t) {
    return 1 - easeInCubic(1 - t);
  }
  const HIDE_TIMEOUT = 500;
  const SCROLL_WHEEL_SENSITIVITY = 50;
  class MouseWheelClassifierItem {
    constructor(timestamp, deltaX, deltaY) {
      this.timestamp = timestamp;
      this.deltaX = deltaX;
      this.deltaY = deltaY;
      this.score = 0;
    }
  }
  const _MouseWheelClassifier = class _MouseWheelClassifier {
    constructor() {
      this._capacity = 5;
      this._memory = [];
      this._front = -1;
      this._rear = -1;
    }
    isPhysicalMouseWheel() {
      if (this._front === -1 && this._rear === -1) {
        return false;
      }
      let remainingInfluence = 1;
      let score2 = 0;
      let iteration = 1;
      let index = this._rear;
      do {
        const influence = index === this._front ? remainingInfluence : Math.pow(2, -iteration);
        remainingInfluence -= influence;
        score2 += this._memory[index].score * influence;
        if (index === this._front) {
          break;
        }
        index = (this._capacity + index - 1) % this._capacity;
        iteration++;
      } while (true);
      return score2 <= 0.5;
    }
    acceptStandardWheelEvent(e) {
      if (isChrome$1) {
        const targetWindow = getWindow(e.browserEvent);
        const pageZoomFactor = getZoomFactor(targetWindow);
        this.accept(Date.now(), e.deltaX * pageZoomFactor, e.deltaY * pageZoomFactor);
      } else {
        this.accept(Date.now(), e.deltaX, e.deltaY);
      }
    }
    accept(timestamp, deltaX, deltaY) {
      let previousItem = null;
      const item = new MouseWheelClassifierItem(timestamp, deltaX, deltaY);
      if (this._front === -1 && this._rear === -1) {
        this._memory[0] = item;
        this._front = 0;
        this._rear = 0;
      } else {
        previousItem = this._memory[this._rear];
        this._rear = (this._rear + 1) % this._capacity;
        if (this._rear === this._front) {
          this._front = (this._front + 1) % this._capacity;
        }
        this._memory[this._rear] = item;
      }
      item.score = this._computeScore(item, previousItem);
    }
    /**
     * A score between 0 and 1 for `item`.
     *  - a score towards 0 indicates that the source appears to be a physical mouse wheel
     *  - a score towards 1 indicates that the source appears to be a touchpad or magic mouse, etc.
     */
    _computeScore(item, previousItem) {
      if (Math.abs(item.deltaX) > 0 && Math.abs(item.deltaY) > 0) {
        return 1;
      }
      let score2 = 0.5;
      if (!this._isAlmostInt(item.deltaX) || !this._isAlmostInt(item.deltaY)) {
        score2 += 0.25;
      }
      if (previousItem) {
        const absDeltaX = Math.abs(item.deltaX);
        const absDeltaY = Math.abs(item.deltaY);
        const absPreviousDeltaX = Math.abs(previousItem.deltaX);
        const absPreviousDeltaY = Math.abs(previousItem.deltaY);
        const minDeltaX = Math.max(Math.min(absDeltaX, absPreviousDeltaX), 1);
        const minDeltaY = Math.max(Math.min(absDeltaY, absPreviousDeltaY), 1);
        const maxDeltaX = Math.max(absDeltaX, absPreviousDeltaX);
        const maxDeltaY = Math.max(absDeltaY, absPreviousDeltaY);
        const isSameModulo = maxDeltaX % minDeltaX === 0 && maxDeltaY % minDeltaY === 0;
        if (isSameModulo) {
          score2 -= 0.5;
        }
      }
      return Math.min(Math.max(score2, 0), 1);
    }
    _isAlmostInt(value) {
      const epsilon = Number.EPSILON * 100;
      const delta = Math.abs(Math.round(value) - value);
      return delta < 0.01 + epsilon;
    }
  };
  _MouseWheelClassifier.INSTANCE = new _MouseWheelClassifier();
  let MouseWheelClassifier = _MouseWheelClassifier;
  class AbstractScrollableElement extends Widget$1 {
    get onScroll() {
      return this._onScroll.event;
    }
    get options() {
      return this._options;
    }
    constructor(element, options, scrollable) {
      super();
      this._inertialTimeout = null;
      this._inertialSpeed = { X: 0, Y: 0 };
      this._onScroll = this._register(new Emitter$1());
      this._onWillScroll = this._register(new Emitter$1());
      element.style.overflow = "hidden";
      this._options = resolveOptions$1(options);
      this._scrollable = scrollable;
      this._register(this._scrollable.onScroll((e) => {
        this._onWillScroll.fire(e);
        this._onDidScroll(e);
        this._onScroll.fire(e);
      }));
      const scrollbarHost = {
        onMouseWheel: (mouseWheelEvent) => this._onMouseWheel(mouseWheelEvent),
        onDragStart: () => this._onDragStart(),
        onDragEnd: () => this._onDragEnd()
      };
      this._verticalScrollbar = this._register(new VerticalScrollbar(this._scrollable, this._options, scrollbarHost));
      this._horizontalScrollbar = this._register(new HorizontalScrollbar(this._scrollable, this._options, scrollbarHost));
      this._domNode = document.createElement("div");
      this._domNode.className = "monaco-scrollable-element " + this._options.className;
      this._domNode.setAttribute("role", "presentation");
      this._domNode.style.position = "relative";
      this._domNode.style.overflow = "hidden";
      this._domNode.appendChild(element);
      this._domNode.appendChild(this._horizontalScrollbar.domNode.domNode);
      this._domNode.appendChild(this._verticalScrollbar.domNode.domNode);
      if (this._options.useShadows) {
        this._leftShadowDomNode = createFastDomNode(document.createElement("div"));
        this._leftShadowDomNode.setClassName("shadow");
        this._domNode.appendChild(this._leftShadowDomNode.domNode);
        this._topShadowDomNode = createFastDomNode(document.createElement("div"));
        this._topShadowDomNode.setClassName("shadow");
        this._domNode.appendChild(this._topShadowDomNode.domNode);
        this._topLeftShadowDomNode = createFastDomNode(document.createElement("div"));
        this._topLeftShadowDomNode.setClassName("shadow");
        this._domNode.appendChild(this._topLeftShadowDomNode.domNode);
      } else {
        this._leftShadowDomNode = null;
        this._topShadowDomNode = null;
        this._topLeftShadowDomNode = null;
      }
      this._listenOnDomNode = this._options.listenOnDomNode || this._domNode;
      this._mouseWheelToDispose = [];
      this._setListeningToMouseWheel(this._options.handleMouseWheel);
      this.onmouseover(this._listenOnDomNode, (e) => this._onMouseOver(e));
      this.onmouseleave(this._listenOnDomNode, (e) => this._onMouseLeave(e));
      this._hideTimeout = this._register(new TimeoutTimer());
      this._isDragging = false;
      this._mouseIsOver = false;
      this._shouldRender = true;
      this._revealOnScroll = true;
    }
    dispose() {
      this._mouseWheelToDispose = dispose(this._mouseWheelToDispose);
      if (this._inertialTimeout) {
        this._inertialTimeout.dispose();
        this._inertialTimeout = null;
      }
      super.dispose();
    }
    /**
     * Get the generated 'scrollable' dom node
     */
    getDomNode() {
      return this._domNode;
    }
    getOverviewRulerLayoutInfo() {
      return {
        parent: this._domNode,
        insertBefore: this._verticalScrollbar.domNode.domNode
      };
    }
    /**
     * Delegate a pointer down event to the vertical scrollbar.
     * This is to help with clicking somewhere else and having the scrollbar react.
     */
    delegateVerticalScrollbarPointerDown(browserEvent) {
      this._verticalScrollbar.delegatePointerDown(browserEvent);
    }
    getScrollDimensions() {
      return this._scrollable.getScrollDimensions();
    }
    setScrollDimensions(dimensions) {
      this._scrollable.setScrollDimensions(dimensions, false);
    }
    /**
     * Update the class name of the scrollable element.
     */
    updateClassName(newClassName) {
      this._options.className = newClassName;
      if (isMacintosh) {
        this._options.className += " mac";
      }
      this._domNode.className = "monaco-scrollable-element " + this._options.className;
    }
    /**
     * Update configuration options for the scrollbar.
     */
    updateOptions(newOptions) {
      if (typeof newOptions.handleMouseWheel !== "undefined") {
        this._options.handleMouseWheel = newOptions.handleMouseWheel;
        this._setListeningToMouseWheel(this._options.handleMouseWheel);
      }
      if (typeof newOptions.mouseWheelScrollSensitivity !== "undefined") {
        this._options.mouseWheelScrollSensitivity = newOptions.mouseWheelScrollSensitivity;
      }
      if (typeof newOptions.fastScrollSensitivity !== "undefined") {
        this._options.fastScrollSensitivity = newOptions.fastScrollSensitivity;
      }
      if (typeof newOptions.scrollPredominantAxis !== "undefined") {
        this._options.scrollPredominantAxis = newOptions.scrollPredominantAxis;
      }
      if (typeof newOptions.horizontal !== "undefined") {
        this._options.horizontal = newOptions.horizontal;
      }
      if (typeof newOptions.vertical !== "undefined") {
        this._options.vertical = newOptions.vertical;
      }
      if (typeof newOptions.horizontalScrollbarSize !== "undefined") {
        this._options.horizontalScrollbarSize = newOptions.horizontalScrollbarSize;
      }
      if (typeof newOptions.verticalScrollbarSize !== "undefined") {
        this._options.verticalScrollbarSize = newOptions.verticalScrollbarSize;
      }
      if (typeof newOptions.scrollByPage !== "undefined") {
        this._options.scrollByPage = newOptions.scrollByPage;
      }
      this._horizontalScrollbar.updateOptions(this._options);
      this._verticalScrollbar.updateOptions(this._options);
      if (!this._options.lazyRender) {
        this._render();
      }
    }
    delegateScrollFromMouseWheelEvent(browserEvent) {
      this._onMouseWheel(new StandardWheelEvent(browserEvent));
    }
    async _periodicSync() {
      let scheduleAgain = false;
      if (this._inertialSpeed.X !== 0 || this._inertialSpeed.Y !== 0) {
        this._scrollable.setScrollPositionNow({
          scrollTop: this._scrollable.getCurrentScrollPosition().scrollTop - this._inertialSpeed.Y * 100,
          scrollLeft: this._scrollable.getCurrentScrollPosition().scrollLeft - this._inertialSpeed.X * 100
        });
        this._inertialSpeed.X *= 0.9;
        this._inertialSpeed.Y *= 0.9;
        if (Math.abs(this._inertialSpeed.X) < 0.01) {
          this._inertialSpeed.X = 0;
        }
        if (Math.abs(this._inertialSpeed.Y) < 0.01) {
          this._inertialSpeed.Y = 0;
        }
        scheduleAgain = this._inertialSpeed.X !== 0 || this._inertialSpeed.Y !== 0;
      }
      if (scheduleAgain) {
        if (!this._inertialTimeout) {
          this._inertialTimeout = new TimeoutTimer();
        }
        this._inertialTimeout.cancelAndSet(() => this._periodicSync(), 1e3 / 60);
      } else {
        this._inertialTimeout?.dispose();
        this._inertialTimeout = null;
      }
    }
    // -------------------- mouse wheel scrolling --------------------
    _setListeningToMouseWheel(shouldListen) {
      const isListening = this._mouseWheelToDispose.length > 0;
      if (isListening === shouldListen) {
        return;
      }
      this._mouseWheelToDispose = dispose(this._mouseWheelToDispose);
      if (shouldListen) {
        const onMouseWheel = (browserEvent) => {
          this._onMouseWheel(new StandardWheelEvent(browserEvent));
        };
        this._mouseWheelToDispose.push(addDisposableListener(this._listenOnDomNode, EventType$1.MOUSE_WHEEL, onMouseWheel, { passive: false }));
      }
    }
    _onMouseWheel(e) {
      if (e.browserEvent?.defaultPrevented) {
        return;
      }
      const classifier = MouseWheelClassifier.INSTANCE;
      {
        classifier.acceptStandardWheelEvent(e);
      }
      let didScroll = false;
      if (e.deltaY || e.deltaX) {
        let deltaY = e.deltaY * this._options.mouseWheelScrollSensitivity;
        let deltaX = e.deltaX * this._options.mouseWheelScrollSensitivity;
        if (this._options.scrollPredominantAxis) {
          if (this._options.scrollYToX && deltaX + deltaY === 0) {
            deltaX = deltaY = 0;
          } else if (Math.abs(deltaY) >= Math.abs(deltaX)) {
            deltaX = 0;
          } else {
            deltaY = 0;
          }
        }
        if (this._options.flipAxes) {
          [deltaY, deltaX] = [deltaX, deltaY];
        }
        const shiftConvert = !isMacintosh && e.browserEvent && e.browserEvent.shiftKey;
        if ((this._options.scrollYToX || shiftConvert) && !deltaX) {
          deltaX = deltaY;
          deltaY = 0;
        }
        if (e.browserEvent && e.browserEvent.altKey) {
          deltaX = deltaX * this._options.fastScrollSensitivity;
          deltaY = deltaY * this._options.fastScrollSensitivity;
        }
        const futureScrollPosition = this._scrollable.getFutureScrollPosition();
        let desiredScrollPosition = {};
        if (deltaY) {
          const deltaScrollTop = SCROLL_WHEEL_SENSITIVITY * deltaY;
          const desiredScrollTop = futureScrollPosition.scrollTop - (deltaScrollTop < 0 ? Math.floor(deltaScrollTop) : Math.ceil(deltaScrollTop));
          this._verticalScrollbar.writeScrollPosition(desiredScrollPosition, desiredScrollTop);
        }
        if (deltaX) {
          const deltaScrollLeft = SCROLL_WHEEL_SENSITIVITY * deltaX;
          const desiredScrollLeft = futureScrollPosition.scrollLeft - (deltaScrollLeft < 0 ? Math.floor(deltaScrollLeft) : Math.ceil(deltaScrollLeft));
          this._horizontalScrollbar.writeScrollPosition(desiredScrollPosition, desiredScrollLeft);
        }
        desiredScrollPosition = this._scrollable.validateScrollPosition(desiredScrollPosition);
        if (this._options.inertialScroll && (deltaX || deltaY) && !classifier.isPhysicalMouseWheel()) {
          let startPeriodic = false;
          if (this._inertialSpeed.X === 0 && this._inertialSpeed.Y === 0) {
            startPeriodic = true;
          }
          this._inertialSpeed.Y = (deltaY < 0 ? -1 : 1) * Math.abs(deltaY) ** 1.02;
          this._inertialSpeed.X = (deltaX < 0 ? -1 : 1) * Math.abs(deltaX) ** 1.02;
          if (startPeriodic) {
            this._periodicSync();
          }
        }
        if (futureScrollPosition.scrollLeft !== desiredScrollPosition.scrollLeft || futureScrollPosition.scrollTop !== desiredScrollPosition.scrollTop) {
          const canPerformSmoothScroll = this._options.mouseWheelSmoothScroll && classifier.isPhysicalMouseWheel();
          if (canPerformSmoothScroll) {
            this._scrollable.setScrollPositionSmooth(desiredScrollPosition);
          } else {
            this._scrollable.setScrollPositionNow(desiredScrollPosition);
          }
          didScroll = true;
        }
      }
      let consumeMouseWheel = didScroll;
      if (!consumeMouseWheel && this._options.alwaysConsumeMouseWheel) {
        consumeMouseWheel = true;
      }
      if (!consumeMouseWheel && this._options.consumeMouseWheelIfScrollbarIsNeeded && (this._verticalScrollbar.isNeeded() || this._horizontalScrollbar.isNeeded())) {
        consumeMouseWheel = true;
      }
      if (consumeMouseWheel) {
        e.preventDefault();
        e.stopPropagation();
      }
    }
    _onDidScroll(e) {
      this._shouldRender = this._horizontalScrollbar.onDidScroll(e) || this._shouldRender;
      this._shouldRender = this._verticalScrollbar.onDidScroll(e) || this._shouldRender;
      if (this._options.useShadows) {
        this._shouldRender = true;
      }
      if (this._revealOnScroll) {
        this._reveal();
      }
      if (!this._options.lazyRender) {
        this._render();
      }
    }
    /**
     * Render / mutate the DOM now.
     * Should be used together with the ctor option `lazyRender`.
     */
    renderNow() {
      if (!this._options.lazyRender) {
        throw new Error("Please use `lazyRender` together with `renderNow`!");
      }
      this._render();
    }
    _render() {
      if (!this._shouldRender) {
        return;
      }
      this._shouldRender = false;
      this._horizontalScrollbar.render();
      this._verticalScrollbar.render();
      if (this._options.useShadows) {
        const scrollState = this._scrollable.getCurrentScrollPosition();
        const enableTop = scrollState.scrollTop > 0;
        const enableLeft = scrollState.scrollLeft > 0;
        const leftClassName = enableLeft ? " left" : "";
        const topClassName = enableTop ? " top" : "";
        const topLeftClassName = enableLeft || enableTop ? " top-left-corner" : "";
        this._leftShadowDomNode.setClassName(`shadow${leftClassName}`);
        this._topShadowDomNode.setClassName(`shadow${topClassName}`);
        this._topLeftShadowDomNode.setClassName(`shadow${topLeftClassName}${topClassName}${leftClassName}`);
      }
    }
    // -------------------- fade in / fade out --------------------
    _onDragStart() {
      this._isDragging = true;
      this._reveal();
    }
    _onDragEnd() {
      this._isDragging = false;
      this._hide();
    }
    _onMouseLeave(e) {
      this._mouseIsOver = false;
      this._hide();
    }
    _onMouseOver(e) {
      this._mouseIsOver = true;
      this._reveal();
    }
    _reveal() {
      this._verticalScrollbar.beginReveal();
      this._horizontalScrollbar.beginReveal();
      this._scheduleHide();
    }
    _hide() {
      if (!this._mouseIsOver && !this._isDragging) {
        this._verticalScrollbar.beginHide();
        this._horizontalScrollbar.beginHide();
      }
    }
    _scheduleHide() {
      if (!this._mouseIsOver && !this._isDragging) {
        this._hideTimeout.cancelAndSet(() => this._hide(), HIDE_TIMEOUT);
      }
    }
  }
  class ScrollableElement extends AbstractScrollableElement {
    constructor(element, options) {
      options = options || {};
      options.mouseWheelSmoothScroll = false;
      const scrollable = new Scrollable({
        forceIntegerValues: true,
        smoothScrollDuration: 0,
        scheduleAtNextAnimationFrame: (callback) => scheduleAtNextAnimationFrame(getWindow(element), callback)
      });
      super(element, options, scrollable);
      this._register(scrollable);
    }
    setScrollPosition(update) {
      this._scrollable.setScrollPositionNow(update);
    }
  }
  class SmoothScrollableElement extends AbstractScrollableElement {
    constructor(element, options, scrollable) {
      super(element, options, scrollable);
    }
    setScrollPosition(update) {
      if (update.reuseAnimation) {
        this._scrollable.setScrollPositionSmooth(update, update.reuseAnimation);
      } else {
        this._scrollable.setScrollPositionNow(update);
      }
    }
    getScrollPosition() {
      return this._scrollable.getCurrentScrollPosition();
    }
  }
  class DomScrollableElement extends AbstractScrollableElement {
    constructor(element, options) {
      options = options || {};
      options.mouseWheelSmoothScroll = false;
      const scrollable = new Scrollable({
        forceIntegerValues: false,
        // See https://github.com/microsoft/vscode/issues/139877
        smoothScrollDuration: 0,
        scheduleAtNextAnimationFrame: (callback) => scheduleAtNextAnimationFrame(getWindow(element), callback)
      });
      super(element, options, scrollable);
      this._register(scrollable);
      this._element = element;
      this._register(this.onScroll((e) => {
        if (e.scrollTopChanged) {
          this._element.scrollTop = e.scrollTop;
        }
        if (e.scrollLeftChanged) {
          this._element.scrollLeft = e.scrollLeft;
        }
      }));
      this.scanDomNode();
    }
    setScrollPosition(update) {
      this._scrollable.setScrollPositionNow(update);
    }
    getScrollPosition() {
      return this._scrollable.getCurrentScrollPosition();
    }
    scanDomNode() {
      this.setScrollDimensions({
        width: this._element.clientWidth,
        scrollWidth: this._element.scrollWidth,
        height: this._element.clientHeight,
        scrollHeight: this._element.scrollHeight
      });
      this.setScrollPosition({
        scrollLeft: this._element.scrollLeft,
        scrollTop: this._element.scrollTop
      });
    }
  }
  function resolveOptions$1(opts) {
    const result = {
      lazyRender: typeof opts.lazyRender !== "undefined" ? opts.lazyRender : false,
      className: typeof opts.className !== "undefined" ? opts.className : "",
      useShadows: typeof opts.useShadows !== "undefined" ? opts.useShadows : true,
      handleMouseWheel: typeof opts.handleMouseWheel !== "undefined" ? opts.handleMouseWheel : true,
      flipAxes: typeof opts.flipAxes !== "undefined" ? opts.flipAxes : false,
      consumeMouseWheelIfScrollbarIsNeeded: typeof opts.consumeMouseWheelIfScrollbarIsNeeded !== "undefined" ? opts.consumeMouseWheelIfScrollbarIsNeeded : false,
      alwaysConsumeMouseWheel: typeof opts.alwaysConsumeMouseWheel !== "undefined" ? opts.alwaysConsumeMouseWheel : false,
      scrollYToX: typeof opts.scrollYToX !== "undefined" ? opts.scrollYToX : false,
      mouseWheelScrollSensitivity: typeof opts.mouseWheelScrollSensitivity !== "undefined" ? opts.mouseWheelScrollSensitivity : 1,
      fastScrollSensitivity: typeof opts.fastScrollSensitivity !== "undefined" ? opts.fastScrollSensitivity : 5,
      scrollPredominantAxis: typeof opts.scrollPredominantAxis !== "undefined" ? opts.scrollPredominantAxis : true,
      mouseWheelSmoothScroll: typeof opts.mouseWheelSmoothScroll !== "undefined" ? opts.mouseWheelSmoothScroll : true,
      inertialScroll: typeof opts.inertialScroll !== "undefined" ? opts.inertialScroll : false,
      arrowSize: typeof opts.arrowSize !== "undefined" ? opts.arrowSize : 11,
      listenOnDomNode: typeof opts.listenOnDomNode !== "undefined" ? opts.listenOnDomNode : null,
      horizontal: typeof opts.horizontal !== "undefined" ? opts.horizontal : 1,
      horizontalScrollbarSize: typeof opts.horizontalScrollbarSize !== "undefined" ? opts.horizontalScrollbarSize : 10,
      horizontalSliderSize: typeof opts.horizontalSliderSize !== "undefined" ? opts.horizontalSliderSize : 0,
      horizontalHasArrows: typeof opts.horizontalHasArrows !== "undefined" ? opts.horizontalHasArrows : false,
      vertical: typeof opts.vertical !== "undefined" ? opts.vertical : 1,
      verticalScrollbarSize: typeof opts.verticalScrollbarSize !== "undefined" ? opts.verticalScrollbarSize : 10,
      verticalHasArrows: typeof opts.verticalHasArrows !== "undefined" ? opts.verticalHasArrows : false,
      verticalSliderSize: typeof opts.verticalSliderSize !== "undefined" ? opts.verticalSliderSize : 0,
      scrollByPage: typeof opts.scrollByPage !== "undefined" ? opts.scrollByPage : false
    };
    result.horizontalSliderSize = typeof opts.horizontalSliderSize !== "undefined" ? opts.horizontalSliderSize : result.horizontalScrollbarSize;
    result.verticalSliderSize = typeof opts.verticalSliderSize !== "undefined" ? opts.verticalSliderSize : result.verticalScrollbarSize;
    if (isMacintosh) {
      result.className += " mac";
    }
    return result;
  }
  class DragScrolling extends Disposable {
    constructor(_context, _viewHelper, _mouseTargetFactory, _dispatchMouse) {
      super();
      this._context = _context;
      this._viewHelper = _viewHelper;
      this._mouseTargetFactory = _mouseTargetFactory;
      this._dispatchMouse = _dispatchMouse;
      this._operation = null;
    }
    dispose() {
      super.dispose();
      this.stop();
    }
    start(position, mouseEvent) {
      if (this._operation) {
        this._operation.setPosition(position, mouseEvent);
      } else {
        this._operation = this._createDragScrollingOperation(position, mouseEvent);
      }
    }
    stop() {
      if (this._operation) {
        this._operation.dispose();
        this._operation = null;
      }
    }
  }
  class DragScrollingOperation extends Disposable {
    constructor(_context, _viewHelper, _mouseTargetFactory, _dispatchMouse, position, mouseEvent) {
      super();
      this._context = _context;
      this._viewHelper = _viewHelper;
      this._mouseTargetFactory = _mouseTargetFactory;
      this._dispatchMouse = _dispatchMouse;
      this._position = position;
      this._mouseEvent = mouseEvent;
      this._lastTime = Date.now();
      this._animationFrameDisposable = scheduleAtNextAnimationFrame(getWindow(mouseEvent.browserEvent), () => this._execute());
    }
    dispose() {
      this._animationFrameDisposable.dispose();
      super.dispose();
    }
    setPosition(position, mouseEvent) {
      this._position = position;
      this._mouseEvent = mouseEvent;
    }
    /**
     * update internal state and return elapsed ms since last time
     */
    _tick() {
      const now = Date.now();
      const elapsed = now - this._lastTime;
      this._lastTime = now;
      return elapsed;
    }
  }
  class TopBottomDragScrolling extends DragScrolling {
    _createDragScrollingOperation(position, mouseEvent) {
      return new TopBottomDragScrollingOperation(this._context, this._viewHelper, this._mouseTargetFactory, this._dispatchMouse, position, mouseEvent);
    }
  }
  class TopBottomDragScrollingOperation extends DragScrollingOperation {
    /**
     * get the number of lines per second to auto-scroll
     */
    _getScrollSpeed() {
      const lineHeight = this._context.configuration.options.get(
        75
        /* EditorOption.lineHeight */
      );
      const viewportInLines = this._context.configuration.options.get(
        165
        /* EditorOption.layoutInfo */
      ).height / lineHeight;
      const outsideDistanceInLines = this._position.outsideDistance / lineHeight;
      if (outsideDistanceInLines <= 1.5) {
        return Math.max(30, viewportInLines * (1 + outsideDistanceInLines));
      }
      if (outsideDistanceInLines <= 3) {
        return Math.max(60, viewportInLines * (2 + outsideDistanceInLines));
      }
      return Math.max(200, viewportInLines * (7 + outsideDistanceInLines));
    }
    _execute() {
      const lineHeight = this._context.configuration.options.get(
        75
        /* EditorOption.lineHeight */
      );
      const scrollSpeedInLines = this._getScrollSpeed();
      const elapsed = this._tick();
      const scrollInPixels = scrollSpeedInLines * (elapsed / 1e3) * lineHeight;
      const scrollValue = this._position.outsidePosition === "above" ? -scrollInPixels : scrollInPixels;
      this._context.viewModel.viewLayout.deltaScrollNow(0, scrollValue);
      this._viewHelper.renderNow();
      const viewportData = this._context.viewLayout.getLinesViewportData();
      const edgeLineNumber = this._position.outsidePosition === "above" ? viewportData.startLineNumber : viewportData.endLineNumber;
      let mouseTarget;
      {
        const editorPos = createEditorPagePosition(this._viewHelper.viewDomNode);
        const horizontalScrollbarHeight = this._context.configuration.options.get(
          165
          /* EditorOption.layoutInfo */
        ).horizontalScrollbarHeight;
        const pos = new PageCoordinates(this._mouseEvent.pos.x, editorPos.y + editorPos.height - horizontalScrollbarHeight - 0.1);
        const relativePos = createCoordinatesRelativeToEditor(this._viewHelper.viewDomNode, editorPos, pos);
        mouseTarget = this._mouseTargetFactory.createMouseTarget(this._viewHelper.getLastRenderData(), editorPos, pos, relativePos, null);
      }
      if (!mouseTarget.position || mouseTarget.position.lineNumber !== edgeLineNumber) {
        if (this._position.outsidePosition === "above") {
          mouseTarget = MouseTarget.createOutsideEditor(this._position.mouseColumn, new Position$1(edgeLineNumber, 1), "above", this._position.outsideDistance);
        } else {
          mouseTarget = MouseTarget.createOutsideEditor(this._position.mouseColumn, new Position$1(edgeLineNumber, this._context.viewModel.getLineMaxColumn(edgeLineNumber)), "below", this._position.outsideDistance);
        }
      }
      this._dispatchMouse(
        mouseTarget,
        true,
        2
        /* NavigationCommandRevealType.None */
      );
      this._animationFrameDisposable = scheduleAtNextAnimationFrame(getWindow(mouseTarget.element), () => this._execute());
    }
  }
  class LeftRightDragScrolling extends DragScrolling {
    _createDragScrollingOperation(position, mouseEvent) {
      return new LeftRightDragScrollingOperation(this._context, this._viewHelper, this._mouseTargetFactory, this._dispatchMouse, position, mouseEvent);
    }
  }
  class LeftRightDragScrollingOperation extends DragScrollingOperation {
    /**
     * get the number of cols per second to auto-scroll
     */
    _getScrollSpeed() {
      const charWidth = this._context.configuration.options.get(
        59
        /* EditorOption.fontInfo */
      ).typicalFullwidthCharacterWidth;
      const viewportInChars = this._context.configuration.options.get(
        165
        /* EditorOption.layoutInfo */
      ).contentWidth / charWidth;
      const outsideDistanceInChars = this._position.outsideDistance / charWidth;
      if (outsideDistanceInChars <= 1.5) {
        return Math.max(30, viewportInChars * (1 + outsideDistanceInChars));
      }
      if (outsideDistanceInChars <= 3) {
        return Math.max(60, viewportInChars * (2 + outsideDistanceInChars));
      }
      return Math.max(200, viewportInChars * (7 + outsideDistanceInChars));
    }
    _execute() {
      const charWidth = this._context.configuration.options.get(
        59
        /* EditorOption.fontInfo */
      ).typicalFullwidthCharacterWidth;
      const scrollSpeedInChars = this._getScrollSpeed();
      const elapsed = this._tick();
      const scrollInPixels = scrollSpeedInChars * (elapsed / 1e3) * charWidth * 0.5;
      const scrollValue = this._position.outsidePosition === "left" ? -scrollInPixels : scrollInPixels;
      this._context.viewModel.viewLayout.deltaScrollNow(scrollValue, 0);
      this._viewHelper.renderNow();
      if (!this._position.position) {
        return;
      }
      const edgeLineNumber = this._position.position.lineNumber;
      let mouseTarget;
      {
        const editorPos = createEditorPagePosition(this._viewHelper.viewDomNode);
        const horizontalScrollbarHeight = this._context.configuration.options.get(
          165
          /* EditorOption.layoutInfo */
        ).horizontalScrollbarHeight;
        const pos = new PageCoordinates(this._mouseEvent.pos.x, editorPos.y + editorPos.height - horizontalScrollbarHeight - 0.1);
        const relativePos = createCoordinatesRelativeToEditor(this._viewHelper.viewDomNode, editorPos, pos);
        mouseTarget = this._mouseTargetFactory.createMouseTarget(this._viewHelper.getLastRenderData(), editorPos, pos, relativePos, null);
      }
      if (this._position.outsidePosition === "left") {
        mouseTarget = MouseTarget.createOutsideEditor(mouseTarget.mouseColumn, new Position$1(edgeLineNumber, mouseTarget.mouseColumn), "left", this._position.outsideDistance);
      } else {
        mouseTarget = MouseTarget.createOutsideEditor(mouseTarget.mouseColumn, new Position$1(edgeLineNumber, mouseTarget.mouseColumn), "right", this._position.outsideDistance);
      }
      this._dispatchMouse(
        mouseTarget,
        true,
        2
        /* NavigationCommandRevealType.None */
      );
      this._animationFrameDisposable = scheduleAtNextAnimationFrame(getWindow(mouseTarget.element), () => this._execute());
    }
  }
  class MouseHandler extends ViewEventHandler {
    constructor(context, viewController, viewHelper) {
      super();
      this._mouseLeaveMonitor = null;
      this._context = context;
      this.viewController = viewController;
      this.viewHelper = viewHelper;
      this.mouseTargetFactory = new MouseTargetFactory(this._context, viewHelper);
      this._mouseDownOperation = this._register(new MouseDownOperation(this._context, this.viewController, this.viewHelper, this.mouseTargetFactory, (e, testEventTarget) => this._createMouseTarget(e, testEventTarget), (e) => this._getMouseColumn(e)));
      this.lastMouseLeaveTime = -1;
      this._height = this._context.configuration.options.get(
        165
        /* EditorOption.layoutInfo */
      ).height;
      const mouseEvents = new EditorMouseEventFactory(this.viewHelper.viewDomNode);
      this._register(mouseEvents.onContextMenu(this.viewHelper.viewDomNode, (e) => this._onContextMenu(e, true)));
      this._register(mouseEvents.onMouseMove(this.viewHelper.viewDomNode, (e) => {
        this._onMouseMove(e);
        if (!this._mouseLeaveMonitor) {
          this._mouseLeaveMonitor = addDisposableListener(this.viewHelper.viewDomNode.ownerDocument, "mousemove", (e2) => {
            if (!this.viewHelper.viewDomNode.contains(e2.target)) {
              this._onMouseLeave(new EditorMouseEvent(e2, false, this.viewHelper.viewDomNode));
            }
          });
        }
      }));
      this._register(mouseEvents.onMouseUp(this.viewHelper.viewDomNode, (e) => this._onMouseUp(e)));
      this._register(mouseEvents.onMouseLeave(this.viewHelper.viewDomNode, (e) => this._onMouseLeave(e)));
      let capturePointerId = 0;
      this._register(mouseEvents.onPointerDown(this.viewHelper.viewDomNode, (e, pointerId) => {
        capturePointerId = pointerId;
      }));
      this._register(addDisposableListener(this.viewHelper.viewDomNode, EventType$1.POINTER_UP, (e) => {
        this._mouseDownOperation.onPointerUp();
      }));
      this._register(mouseEvents.onMouseDown(this.viewHelper.viewDomNode, (e) => this._onMouseDown(e, capturePointerId)));
      this._setupMouseWheelZoomListener();
      this._context.addEventHandler(this);
    }
    _setupMouseWheelZoomListener() {
      const classifier = MouseWheelClassifier.INSTANCE;
      let prevMouseWheelTime = 0;
      let gestureStartZoomLevel = EditorZoom.getZoomLevel();
      let gestureHasZoomModifiers = false;
      let gestureAccumulatedDelta = 0;
      const onMouseWheel = (browserEvent) => {
        this.viewController.emitMouseWheel(browserEvent);
        if (!this._context.configuration.options.get(
          84
          /* EditorOption.mouseWheelZoom */
        )) {
          return;
        }
        const e = new StandardWheelEvent(browserEvent);
        classifier.acceptStandardWheelEvent(e);
        if (classifier.isPhysicalMouseWheel()) {
          if (hasMouseWheelZoomModifiers(browserEvent)) {
            const zoomLevel = EditorZoom.getZoomLevel();
            const delta = e.deltaY > 0 ? 1 : -1;
            EditorZoom.setZoomLevel(zoomLevel + delta);
            e.preventDefault();
            e.stopPropagation();
          }
        } else {
          if (Date.now() - prevMouseWheelTime > 50) {
            gestureStartZoomLevel = EditorZoom.getZoomLevel();
            gestureHasZoomModifiers = hasMouseWheelZoomModifiers(browserEvent);
            gestureAccumulatedDelta = 0;
          }
          prevMouseWheelTime = Date.now();
          gestureAccumulatedDelta += e.deltaY;
          if (gestureHasZoomModifiers) {
            EditorZoom.setZoomLevel(gestureStartZoomLevel + gestureAccumulatedDelta / 5);
            e.preventDefault();
            e.stopPropagation();
          }
        }
      };
      this._register(addDisposableListener(this.viewHelper.viewDomNode, EventType$1.MOUSE_WHEEL, onMouseWheel, { capture: true, passive: false }));
      function hasMouseWheelZoomModifiers(browserEvent) {
        return isMacintosh ? (browserEvent.metaKey || browserEvent.ctrlKey) && !browserEvent.shiftKey && !browserEvent.altKey : browserEvent.ctrlKey && !browserEvent.metaKey && !browserEvent.shiftKey && !browserEvent.altKey;
      }
    }
    dispose() {
      this._context.removeEventHandler(this);
      if (this._mouseLeaveMonitor) {
        this._mouseLeaveMonitor.dispose();
        this._mouseLeaveMonitor = null;
      }
      super.dispose();
    }
    // --- begin event handlers
    onConfigurationChanged(e) {
      if (e.hasChanged(
        165
        /* EditorOption.layoutInfo */
      )) {
        const height = this._context.configuration.options.get(
          165
          /* EditorOption.layoutInfo */
        ).height;
        if (this._height !== height) {
          this._height = height;
          this._mouseDownOperation.onHeightChanged();
        }
      }
      return false;
    }
    onCursorStateChanged(e) {
      this._mouseDownOperation.onCursorStateChanged(e);
      return false;
    }
    onFocusChanged(e) {
      return false;
    }
    // --- end event handlers
    getTargetAtClientPoint(clientX, clientY) {
      const clientPos = new ClientCoordinates(clientX, clientY);
      const pos = clientPos.toPageCoordinates(getWindow(this.viewHelper.viewDomNode));
      const editorPos = createEditorPagePosition(this.viewHelper.viewDomNode);
      if (pos.y < editorPos.y || pos.y > editorPos.y + editorPos.height || pos.x < editorPos.x || pos.x > editorPos.x + editorPos.width) {
        return null;
      }
      const relativePos = createCoordinatesRelativeToEditor(this.viewHelper.viewDomNode, editorPos, pos);
      return this.mouseTargetFactory.createMouseTarget(this.viewHelper.getLastRenderData(), editorPos, pos, relativePos, null);
    }
    _createMouseTarget(e, testEventTarget) {
      let target = e.target;
      if (!this.viewHelper.viewDomNode.contains(target)) {
        const shadowRoot = getShadowRoot(this.viewHelper.viewDomNode);
        if (shadowRoot) {
          const potentialTarget = shadowRoot.elementsFromPoint(e.posx, e.posy).find((el) => this.viewHelper.viewDomNode.contains(el)) ?? null;
          target = potentialTarget;
        }
      }
      return this.mouseTargetFactory.createMouseTarget(this.viewHelper.getLastRenderData(), e.editorPos, e.pos, e.relativePos, testEventTarget ? target : null);
    }
    _getMouseColumn(e) {
      return this.mouseTargetFactory.getMouseColumn(e.relativePos);
    }
    _onContextMenu(e, testEventTarget) {
      this.viewController.emitContextMenu({
        event: e,
        target: this._createMouseTarget(e, testEventTarget)
      });
    }
    _onMouseMove(e) {
      const targetIsWidget = this.mouseTargetFactory.mouseTargetIsWidget(e);
      if (!targetIsWidget) {
        e.preventDefault();
      }
      if (this._mouseDownOperation.isActive()) {
        return;
      }
      const actualMouseMoveTime = e.timestamp;
      if (actualMouseMoveTime < this.lastMouseLeaveTime) {
        return;
      }
      this.viewController.emitMouseMove({
        event: e,
        target: this._createMouseTarget(e, true)
      });
    }
    _onMouseLeave(e) {
      if (this._mouseLeaveMonitor) {
        this._mouseLeaveMonitor.dispose();
        this._mouseLeaveMonitor = null;
      }
      this.lastMouseLeaveTime = (/* @__PURE__ */ new Date()).getTime();
      this.viewController.emitMouseLeave({
        event: e,
        target: null
      });
    }
    _onMouseUp(e) {
      this.viewController.emitMouseUp({
        event: e,
        target: this._createMouseTarget(e, true)
      });
    }
    _onMouseDown(e, pointerId) {
      const t = this._createMouseTarget(e, true);
      const targetIsContent = t.type === 6 || t.type === 7;
      const targetIsGutter = t.type === 2 || t.type === 3 || t.type === 4;
      const targetIsLineNumbers = t.type === 3;
      const selectOnLineNumbers = this._context.configuration.options.get(
        125
        /* EditorOption.selectOnLineNumbers */
      );
      const targetIsViewZone = t.type === 8 || t.type === 5;
      const targetIsWidget = t.type === 9;
      let shouldHandle = e.leftButton || e.middleButton;
      if (isMacintosh && e.leftButton && e.ctrlKey) {
        shouldHandle = false;
      }
      const focus = () => {
        e.preventDefault();
        this.viewHelper.focusTextArea();
      };
      if (shouldHandle && (targetIsContent || targetIsLineNumbers && selectOnLineNumbers)) {
        focus();
        this._mouseDownOperation.start(t.type, e, pointerId);
      } else if (targetIsGutter) {
        e.preventDefault();
      } else if (targetIsViewZone) {
        const viewZoneData = t.detail;
        if (shouldHandle && this.viewHelper.shouldSuppressMouseDownOnViewZone(viewZoneData.viewZoneId)) {
          focus();
          this._mouseDownOperation.start(t.type, e, pointerId);
          e.preventDefault();
        }
      } else if (targetIsWidget && this.viewHelper.shouldSuppressMouseDownOnWidget(t.detail)) {
        focus();
        e.preventDefault();
      }
      this.viewController.emitMouseDown({
        event: e,
        target: t
      });
    }
  }
  class MouseDownOperation extends Disposable {
    constructor(_context, _viewController, _viewHelper, _mouseTargetFactory, createMouseTarget, getMouseColumn) {
      super();
      this._context = _context;
      this._viewController = _viewController;
      this._viewHelper = _viewHelper;
      this._mouseTargetFactory = _mouseTargetFactory;
      this._createMouseTarget = createMouseTarget;
      this._getMouseColumn = getMouseColumn;
      this._mouseMoveMonitor = this._register(new GlobalEditorPointerMoveMonitor(this._viewHelper.viewDomNode));
      this._topBottomDragScrolling = this._register(new TopBottomDragScrolling(this._context, this._viewHelper, this._mouseTargetFactory, (position, inSelectionMode, revealType) => this._dispatchMouse(position, inSelectionMode, revealType)));
      this._leftRightDragScrolling = this._register(new LeftRightDragScrolling(this._context, this._viewHelper, this._mouseTargetFactory, (position, inSelectionMode, revealType) => this._dispatchMouse(position, inSelectionMode, revealType)));
      this._mouseState = new MouseDownState();
      this._currentSelection = new Selection$1(1, 1, 1, 1);
      this._isActive = false;
      this._lastMouseEvent = null;
    }
    dispose() {
      super.dispose();
    }
    isActive() {
      return this._isActive;
    }
    _onMouseDownThenMove(e) {
      this._lastMouseEvent = e;
      this._mouseState.setModifiers(e);
      const position = this._findMousePosition(e, false);
      if (!position) {
        return;
      }
      if (this._mouseState.isDragAndDrop) {
        this._viewController.emitMouseDrag({
          event: e,
          target: position
        });
      } else {
        if (position.type === 13) {
          if (position.outsidePosition === "above" || position.outsidePosition === "below") {
            this._topBottomDragScrolling.start(position, e);
            this._leftRightDragScrolling.stop();
          } else {
            this._leftRightDragScrolling.start(position, e);
            this._topBottomDragScrolling.stop();
          }
        } else {
          this._topBottomDragScrolling.stop();
          this._leftRightDragScrolling.stop();
          this._dispatchMouse(
            position,
            true,
            1
            /* NavigationCommandRevealType.Minimal */
          );
        }
      }
    }
    start(targetType, e, pointerId) {
      this._lastMouseEvent = e;
      this._mouseState.setStartedOnLineNumbers(
        targetType === 3
        /* MouseTargetType.GUTTER_LINE_NUMBERS */
      );
      this._mouseState.setStartButtons(e);
      this._mouseState.setModifiers(e);
      const position = this._findMousePosition(e, true);
      if (!position || !position.position) {
        return;
      }
      this._mouseState.trySetCount(e.detail, position.position);
      e.detail = this._mouseState.count;
      const options = this._context.configuration.options;
      if (!options.get(
        104
        /* EditorOption.readOnly */
      ) && options.get(
        42
        /* EditorOption.dragAndDrop */
      ) && !options.get(
        28
        /* EditorOption.columnSelection */
      ) && !this._mouseState.altKey && e.detail < 2 && !this._isActive && !this._currentSelection.isEmpty() && position.type === 6 && position.position && this._currentSelection.containsPosition(position.position)) {
        this._mouseState.isDragAndDrop = true;
        this._isActive = true;
        this._mouseMoveMonitor.startMonitoring(this._viewHelper.viewLinesDomNode, pointerId, e.buttons, (e2) => this._onMouseDownThenMove(e2), (browserEvent) => {
          const position2 = this._findMousePosition(this._lastMouseEvent, false);
          if (isKeyboardEvent(browserEvent)) {
            this._viewController.emitMouseDropCanceled();
          } else {
            this._viewController.emitMouseDrop({
              event: this._lastMouseEvent,
              target: position2 ? this._createMouseTarget(this._lastMouseEvent, true) : null
              // Ignoring because position is unknown, e.g., Content View Zone
            });
          }
          this._stop();
        });
        return;
      }
      this._mouseState.isDragAndDrop = false;
      this._dispatchMouse(
        position,
        e.shiftKey,
        1
        /* NavigationCommandRevealType.Minimal */
      );
      if (!this._isActive) {
        this._isActive = true;
        this._mouseMoveMonitor.startMonitoring(this._viewHelper.viewLinesDomNode, pointerId, e.buttons, (e2) => this._onMouseDownThenMove(e2), () => this._stop());
      }
    }
    _stop() {
      this._isActive = false;
      this._topBottomDragScrolling.stop();
      this._leftRightDragScrolling.stop();
    }
    onHeightChanged() {
      this._mouseMoveMonitor.stopMonitoring();
    }
    onPointerUp() {
      this._mouseMoveMonitor.stopMonitoring();
    }
    onCursorStateChanged(e) {
      this._currentSelection = e.selections[0];
    }
    _getPositionOutsideEditor(e) {
      const editorContent = e.editorPos;
      const model = this._context.viewModel;
      const viewLayout = this._context.viewLayout;
      const mouseColumn = this._getMouseColumn(e);
      if (e.posy < editorContent.y) {
        const outsideDistance = editorContent.y - e.posy;
        const verticalOffset = Math.max(viewLayout.getCurrentScrollTop() - outsideDistance, 0);
        const viewZoneData = HitTestContext.getZoneAtCoord(this._context, verticalOffset);
        if (viewZoneData) {
          const newPosition = this._helpPositionJumpOverViewZone(viewZoneData);
          if (newPosition) {
            return MouseTarget.createOutsideEditor(mouseColumn, newPosition, "above", outsideDistance);
          }
        }
        const aboveLineNumber = viewLayout.getLineNumberAtVerticalOffset(verticalOffset);
        return MouseTarget.createOutsideEditor(mouseColumn, new Position$1(aboveLineNumber, 1), "above", outsideDistance);
      }
      if (e.posy > editorContent.y + editorContent.height) {
        const outsideDistance = e.posy - editorContent.y - editorContent.height;
        const verticalOffset = viewLayout.getCurrentScrollTop() + e.relativePos.y;
        const viewZoneData = HitTestContext.getZoneAtCoord(this._context, verticalOffset);
        if (viewZoneData) {
          const newPosition = this._helpPositionJumpOverViewZone(viewZoneData);
          if (newPosition) {
            return MouseTarget.createOutsideEditor(mouseColumn, newPosition, "below", outsideDistance);
          }
        }
        const belowLineNumber = viewLayout.getLineNumberAtVerticalOffset(verticalOffset);
        return MouseTarget.createOutsideEditor(mouseColumn, new Position$1(belowLineNumber, model.getLineMaxColumn(belowLineNumber)), "below", outsideDistance);
      }
      const possibleLineNumber = viewLayout.getLineNumberAtVerticalOffset(viewLayout.getCurrentScrollTop() + e.relativePos.y);
      const layoutInfo = this._context.configuration.options.get(
        165
        /* EditorOption.layoutInfo */
      );
      const xLeftBoundary = layoutInfo.contentLeft;
      if (e.relativePos.x <= xLeftBoundary) {
        const outsideDistance = xLeftBoundary - e.relativePos.x;
        return MouseTarget.createOutsideEditor(mouseColumn, new Position$1(possibleLineNumber, 1), "left", outsideDistance);
      }
      const contentRight = layoutInfo.minimap.minimapLeft === 0 ? layoutInfo.width - layoutInfo.verticalScrollbarWidth : layoutInfo.minimap.minimapLeft;
      const xRightBoundary = contentRight;
      if (e.relativePos.x >= xRightBoundary) {
        const outsideDistance = e.relativePos.x - xRightBoundary;
        return MouseTarget.createOutsideEditor(mouseColumn, new Position$1(possibleLineNumber, model.getLineMaxColumn(possibleLineNumber)), "right", outsideDistance);
      }
      return null;
    }
    _findMousePosition(e, testEventTarget) {
      const positionOutsideEditor = this._getPositionOutsideEditor(e);
      if (positionOutsideEditor) {
        return positionOutsideEditor;
      }
      const t = this._createMouseTarget(e, testEventTarget);
      const hintedPosition = t.position;
      if (!hintedPosition) {
        return null;
      }
      if (t.type === 8 || t.type === 5) {
        const newPosition = this._helpPositionJumpOverViewZone(t.detail);
        if (newPosition) {
          return MouseTarget.createViewZone(t.type, t.element, t.mouseColumn, newPosition, t.detail);
        }
      }
      return t;
    }
    _helpPositionJumpOverViewZone(viewZoneData) {
      const selectionStart = new Position$1(this._currentSelection.selectionStartLineNumber, this._currentSelection.selectionStartColumn);
      const positionBefore = viewZoneData.positionBefore;
      const positionAfter = viewZoneData.positionAfter;
      if (positionBefore && positionAfter) {
        if (positionBefore.isBefore(selectionStart)) {
          return positionBefore;
        } else {
          return positionAfter;
        }
      }
      return null;
    }
    _dispatchMouse(position, inSelectionMode, revealType) {
      if (!position.position) {
        return;
      }
      this._viewController.dispatchMouse({
        position: position.position,
        mouseColumn: position.mouseColumn,
        startedOnLineNumbers: this._mouseState.startedOnLineNumbers,
        revealType,
        inSelectionMode,
        mouseDownCount: this._mouseState.count,
        altKey: this._mouseState.altKey,
        ctrlKey: this._mouseState.ctrlKey,
        metaKey: this._mouseState.metaKey,
        shiftKey: this._mouseState.shiftKey,
        leftButton: this._mouseState.leftButton,
        middleButton: this._mouseState.middleButton,
        onInjectedText: position.type === 6 && position.detail.injectedText !== null
      });
    }
  }
  const _MouseDownState = class _MouseDownState {
    // ms
    get altKey() {
      return this._altKey;
    }
    get ctrlKey() {
      return this._ctrlKey;
    }
    get metaKey() {
      return this._metaKey;
    }
    get shiftKey() {
      return this._shiftKey;
    }
    get leftButton() {
      return this._leftButton;
    }
    get middleButton() {
      return this._middleButton;
    }
    get startedOnLineNumbers() {
      return this._startedOnLineNumbers;
    }
    constructor() {
      this._altKey = false;
      this._ctrlKey = false;
      this._metaKey = false;
      this._shiftKey = false;
      this._leftButton = false;
      this._middleButton = false;
      this._startedOnLineNumbers = false;
      this._lastMouseDownPosition = null;
      this._lastMouseDownPositionEqualCount = 0;
      this._lastMouseDownCount = 0;
      this._lastSetMouseDownCountTime = 0;
      this.isDragAndDrop = false;
    }
    get count() {
      return this._lastMouseDownCount;
    }
    setModifiers(source) {
      this._altKey = source.altKey;
      this._ctrlKey = source.ctrlKey;
      this._metaKey = source.metaKey;
      this._shiftKey = source.shiftKey;
    }
    setStartButtons(source) {
      this._leftButton = source.leftButton;
      this._middleButton = source.middleButton;
    }
    setStartedOnLineNumbers(startedOnLineNumbers) {
      this._startedOnLineNumbers = startedOnLineNumbers;
    }
    trySetCount(setMouseDownCount, newMouseDownPosition) {
      const currentTime = (/* @__PURE__ */ new Date()).getTime();
      if (currentTime - this._lastSetMouseDownCountTime > _MouseDownState.CLEAR_MOUSE_DOWN_COUNT_TIME) {
        setMouseDownCount = 1;
      }
      this._lastSetMouseDownCountTime = currentTime;
      if (setMouseDownCount > this._lastMouseDownCount + 1) {
        setMouseDownCount = this._lastMouseDownCount + 1;
      }
      if (this._lastMouseDownPosition && this._lastMouseDownPosition.equals(newMouseDownPosition)) {
        this._lastMouseDownPositionEqualCount++;
      } else {
        this._lastMouseDownPositionEqualCount = 1;
      }
      this._lastMouseDownPosition = newMouseDownPosition;
      this._lastMouseDownCount = Math.min(setMouseDownCount, this._lastMouseDownPositionEqualCount);
    }
  };
  _MouseDownState.CLEAR_MOUSE_DOWN_COUNT_TIME = 400;
  let MouseDownState = _MouseDownState;
  class DomEmitter {
    get event() {
      return this.emitter.event;
    }
    constructor(element, type, useCapture) {
      const fn = (e) => this.emitter.fire(e);
      this.emitter = new Emitter$1({
        onWillAddFirstListener: () => element.addEventListener(type, fn, useCapture),
        onDidRemoveLastListener: () => element.removeEventListener(type, fn, useCapture)
      });
    }
    dispose() {
      this.emitter.dispose();
    }
  }
  function getDataToCopy(viewModel, modelSelections, emptySelectionClipboard, copyWithSyntaxHighlighting) {
    const rawTextToCopy = viewModel.getPlainTextToCopy(modelSelections, emptySelectionClipboard, isWindows);
    const newLineCharacter = viewModel.model.getEOL();
    const isFromEmptySelection = emptySelectionClipboard && modelSelections.length === 1 && modelSelections[0].isEmpty();
    const multicursorText = Array.isArray(rawTextToCopy) ? rawTextToCopy : null;
    const text2 = Array.isArray(rawTextToCopy) ? rawTextToCopy.join(newLineCharacter) : rawTextToCopy;
    let html2 = void 0;
    let mode = null;
    if (CopyOptions.forceCopyWithSyntaxHighlighting || copyWithSyntaxHighlighting && text2.length < 65536) {
      const richText = viewModel.getRichTextToCopy(modelSelections, emptySelectionClipboard);
      if (richText) {
        html2 = richText.html;
        mode = richText.mode;
      }
    }
    const dataToCopy = {
      isFromEmptySelection,
      multicursorText,
      text: text2,
      html: html2,
      mode
    };
    return dataToCopy;
  }
  const _InMemoryClipboardMetadataManager = class _InMemoryClipboardMetadataManager {
    constructor() {
      this._lastState = null;
    }
    set(lastCopiedValue, data) {
      this._lastState = { lastCopiedValue, data };
    }
    get(pastedText) {
      if (this._lastState && this._lastState.lastCopiedValue === pastedText) {
        return this._lastState.data;
      }
      this._lastState = null;
      return null;
    }
  };
  _InMemoryClipboardMetadataManager.INSTANCE = new _InMemoryClipboardMetadataManager();
  let InMemoryClipboardMetadataManager = _InMemoryClipboardMetadataManager;
  const CopyOptions = {
    forceCopyWithSyntaxHighlighting: false
  };
  const ClipboardEventUtils = {
    getTextData(clipboardData) {
      const text2 = clipboardData.getData(Mimes.text);
      let metadata = null;
      const rawmetadata = clipboardData.getData("vscode-editor-data");
      if (typeof rawmetadata === "string") {
        try {
          metadata = JSON.parse(rawmetadata);
          if (metadata.version !== 1) {
            metadata = null;
          }
        } catch (err) {
        }
      }
      if (text2.length === 0 && metadata === null && clipboardData.files.length > 0) {
        const files = Array.prototype.slice.call(clipboardData.files, 0);
        return [files.map((file) => file.name).join("\n"), null];
      }
      return [text2, metadata];
    },
    setTextData(clipboardData, text2, html2, metadata) {
      clipboardData.setData(Mimes.text, text2);
      if (typeof html2 === "string") {
        clipboardData.setData("text/html", html2);
      }
      clipboardData.setData("vscode-editor-data", JSON.stringify(metadata));
    }
  };
  const _TextAreaState = class _TextAreaState {
    constructor(value, selectionStart, selectionEnd, selection, newlineCountBeforeSelection) {
      this.value = value;
      this.selectionStart = selectionStart;
      this.selectionEnd = selectionEnd;
      this.selection = selection;
      this.newlineCountBeforeSelection = newlineCountBeforeSelection;
    }
    toString() {
      return `[ <${this.value}>, selectionStart: ${this.selectionStart}, selectionEnd: ${this.selectionEnd}]`;
    }
    static readFromTextArea(textArea, previousState) {
      const value = textArea.getValue();
      const selectionStart = textArea.getSelectionStart();
      const selectionEnd = textArea.getSelectionEnd();
      let newlineCountBeforeSelection = void 0;
      if (previousState) {
        const valueBeforeSelectionStart = value.substring(0, selectionStart);
        const previousValueBeforeSelectionStart = previousState.value.substring(0, previousState.selectionStart);
        if (valueBeforeSelectionStart === previousValueBeforeSelectionStart) {
          newlineCountBeforeSelection = previousState.newlineCountBeforeSelection;
        }
      }
      return new _TextAreaState(value, selectionStart, selectionEnd, null, newlineCountBeforeSelection);
    }
    collapseSelection() {
      if (this.selectionStart === this.value.length) {
        return this;
      }
      return new _TextAreaState(this.value, this.value.length, this.value.length, null, void 0);
    }
    isWrittenToTextArea(textArea, select) {
      const valuesEqual = this.value === textArea.getValue();
      if (!select) {
        return valuesEqual;
      }
      const selectionsEqual = this.selectionStart === textArea.getSelectionStart() && this.selectionEnd === textArea.getSelectionEnd();
      return selectionsEqual && valuesEqual;
    }
    writeToTextArea(reason, textArea, select) {
      textArea.setValue(reason, this.value);
      if (select) {
        textArea.setSelectionRange(reason, this.selectionStart, this.selectionEnd);
      }
    }
    deduceEditorPosition(offset) {
      if (offset <= this.selectionStart) {
        const str = this.value.substring(offset, this.selectionStart);
        return this._finishDeduceEditorPosition(this.selection?.getStartPosition() ?? null, str, -1);
      }
      if (offset >= this.selectionEnd) {
        const str = this.value.substring(this.selectionEnd, offset);
        return this._finishDeduceEditorPosition(this.selection?.getEndPosition() ?? null, str, 1);
      }
      const str1 = this.value.substring(this.selectionStart, offset);
      if (str1.indexOf(String.fromCharCode(8230)) === -1) {
        return this._finishDeduceEditorPosition(this.selection?.getStartPosition() ?? null, str1, 1);
      }
      const str2 = this.value.substring(offset, this.selectionEnd);
      return this._finishDeduceEditorPosition(this.selection?.getEndPosition() ?? null, str2, -1);
    }
    _finishDeduceEditorPosition(anchor, deltaText, signum) {
      let lineFeedCnt = 0;
      let lastLineFeedIndex = -1;
      while ((lastLineFeedIndex = deltaText.indexOf("\n", lastLineFeedIndex + 1)) !== -1) {
        lineFeedCnt++;
      }
      return [anchor, signum * deltaText.length, lineFeedCnt];
    }
    static deduceInput(previousState, currentState, couldBeEmojiInput) {
      if (!previousState) {
        return {
          text: "",
          replacePrevCharCnt: 0,
          replaceNextCharCnt: 0,
          positionDelta: 0
        };
      }
      const prefixLength = Math.min(commonPrefixLength(previousState.value, currentState.value), previousState.selectionStart, currentState.selectionStart);
      const suffixLength = Math.min(commonSuffixLength(previousState.value, currentState.value), previousState.value.length - previousState.selectionEnd, currentState.value.length - currentState.selectionEnd);
      previousState.value.substring(prefixLength, previousState.value.length - suffixLength);
      const currentValue = currentState.value.substring(prefixLength, currentState.value.length - suffixLength);
      const previousSelectionStart = previousState.selectionStart - prefixLength;
      const previousSelectionEnd = previousState.selectionEnd - prefixLength;
      const currentSelectionStart = currentState.selectionStart - prefixLength;
      const currentSelectionEnd = currentState.selectionEnd - prefixLength;
      if (currentSelectionStart === currentSelectionEnd) {
        const replacePreviousCharacters2 = previousState.selectionStart - prefixLength;
        return {
          text: currentValue,
          replacePrevCharCnt: replacePreviousCharacters2,
          replaceNextCharCnt: 0,
          positionDelta: 0
        };
      }
      const replacePreviousCharacters = previousSelectionEnd - previousSelectionStart;
      return {
        text: currentValue,
        replacePrevCharCnt: replacePreviousCharacters,
        replaceNextCharCnt: 0,
        positionDelta: 0
      };
    }
    static deduceAndroidCompositionInput(previousState, currentState) {
      if (!previousState) {
        return {
          text: "",
          replacePrevCharCnt: 0,
          replaceNextCharCnt: 0,
          positionDelta: 0
        };
      }
      if (previousState.value === currentState.value) {
        return {
          text: "",
          replacePrevCharCnt: 0,
          replaceNextCharCnt: 0,
          positionDelta: currentState.selectionEnd - previousState.selectionEnd
        };
      }
      const prefixLength = Math.min(commonPrefixLength(previousState.value, currentState.value), previousState.selectionEnd);
      const suffixLength = Math.min(commonSuffixLength(previousState.value, currentState.value), previousState.value.length - previousState.selectionEnd);
      const previousValue = previousState.value.substring(prefixLength, previousState.value.length - suffixLength);
      const currentValue = currentState.value.substring(prefixLength, currentState.value.length - suffixLength);
      previousState.selectionStart - prefixLength;
      const previousSelectionEnd = previousState.selectionEnd - prefixLength;
      currentState.selectionStart - prefixLength;
      const currentSelectionEnd = currentState.selectionEnd - prefixLength;
      return {
        text: currentValue,
        replacePrevCharCnt: previousSelectionEnd,
        replaceNextCharCnt: previousValue.length - previousSelectionEnd,
        positionDelta: currentSelectionEnd - currentValue.length
      };
    }
    static fromScreenReaderContentState(screenReaderContentState) {
      return new _TextAreaState(screenReaderContentState.value, screenReaderContentState.selectionStart, screenReaderContentState.selectionEnd, screenReaderContentState.selection, screenReaderContentState.newlineCountBeforeSelection);
    }
  };
  _TextAreaState.EMPTY = new _TextAreaState("", 0, 0, null, void 0);
  let TextAreaState = _TextAreaState;
  const generateUuid = (function() {
    if (typeof crypto.randomUUID === "function") {
      return crypto.randomUUID.bind(crypto);
    }
    const _data = new Uint8Array(16);
    const _hex = [];
    for (let i2 = 0; i2 < 256; i2++) {
      _hex.push(i2.toString(16).padStart(2, "0"));
    }
    return function generateUuid2() {
      crypto.getRandomValues(_data);
      _data[6] = _data[6] & 15 | 64;
      _data[8] = _data[8] & 63 | 128;
      let i2 = 0;
      let result = "";
      result += _hex[_data[i2++]];
      result += _hex[_data[i2++]];
      result += _hex[_data[i2++]];
      result += _hex[_data[i2++]];
      result += "-";
      result += _hex[_data[i2++]];
      result += _hex[_data[i2++]];
      result += "-";
      result += _hex[_data[i2++]];
      result += _hex[_data[i2++]];
      result += "-";
      result += _hex[_data[i2++]];
      result += _hex[_data[i2++]];
      result += "-";
      result += _hex[_data[i2++]];
      result += _hex[_data[i2++]];
      result += _hex[_data[i2++]];
      result += _hex[_data[i2++]];
      result += _hex[_data[i2++]];
      result += _hex[_data[i2++]];
      return result;
    };
  })();
  function prefixedUuid(namespace) {
    return `${namespace}-${generateUuid()}`;
  }
  var __decorate$31 = 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);
    };
  };
  var TextAreaSyntethicEvents;
  (function(TextAreaSyntethicEvents2) {
    TextAreaSyntethicEvents2.Tap = "-monaco-textarea-synthetic-tap";
  })(TextAreaSyntethicEvents || (TextAreaSyntethicEvents = {}));
  class CompositionContext {
    constructor() {
      this._lastTypeTextLength = 0;
    }
    handleCompositionUpdate(text2) {
      text2 = text2 || "";
      const typeInput = {
        text: text2,
        replacePrevCharCnt: this._lastTypeTextLength,
        replaceNextCharCnt: 0,
        positionDelta: 0
      };
      this._lastTypeTextLength = text2.length;
      return typeInput;
    }
  }
  let TextAreaInput = class TextAreaInput extends Disposable {
    get textAreaState() {
      return this._textAreaState;
    }
    constructor(_host, _textArea, _OS, _browser, _accessibilityService, _logService) {
      super();
      this._host = _host;
      this._textArea = _textArea;
      this._OS = _OS;
      this._browser = _browser;
      this._accessibilityService = _accessibilityService;
      this._logService = _logService;
      this._onFocus = this._register(new Emitter$1());
      this.onFocus = this._onFocus.event;
      this._onBlur = this._register(new Emitter$1());
      this.onBlur = this._onBlur.event;
      this._onKeyDown = this._register(new Emitter$1());
      this.onKeyDown = this._onKeyDown.event;
      this._onKeyUp = this._register(new Emitter$1());
      this.onKeyUp = this._onKeyUp.event;
      this._onCut = this._register(new Emitter$1());
      this.onCut = this._onCut.event;
      this._onPaste = this._register(new Emitter$1());
      this.onPaste = this._onPaste.event;
      this._onType = this._register(new Emitter$1());
      this.onType = this._onType.event;
      this._onCompositionStart = this._register(new Emitter$1());
      this.onCompositionStart = this._onCompositionStart.event;
      this._onCompositionUpdate = this._register(new Emitter$1());
      this.onCompositionUpdate = this._onCompositionUpdate.event;
      this._onCompositionEnd = this._register(new Emitter$1());
      this.onCompositionEnd = this._onCompositionEnd.event;
      this._onSelectionChangeRequest = this._register(new Emitter$1());
      this.onSelectionChangeRequest = this._onSelectionChangeRequest.event;
      this._asyncFocusGainWriteScreenReaderContent = this._register(new MutableDisposable());
      this._asyncTriggerCut = this._register(new RunOnceScheduler(() => this._onCut.fire(), 0));
      this._textAreaState = TextAreaState.EMPTY;
      this._selectionChangeListener = null;
      if (this._accessibilityService.isScreenReaderOptimized()) {
        this.writeNativeTextAreaContent("ctor");
      }
      this._register(Event.runAndSubscribe(this._accessibilityService.onDidChangeScreenReaderOptimized, () => {
        if (this._accessibilityService.isScreenReaderOptimized() && !this._asyncFocusGainWriteScreenReaderContent.value) {
          this._asyncFocusGainWriteScreenReaderContent.value = this._register(new RunOnceScheduler(() => this.writeNativeTextAreaContent("asyncFocusGain"), 0));
        } else {
          this._asyncFocusGainWriteScreenReaderContent.clear();
        }
      }));
      this._hasFocus = false;
      this._currentComposition = null;
      let lastKeyDown = null;
      this._register(this._textArea.onKeyDown((_e2) => {
        const e = new StandardKeyboardEvent(_e2);
        if (e.keyCode === 114 || this._currentComposition && e.keyCode === 1) {
          e.stopPropagation();
        }
        if (e.equals(
          9
          /* KeyCode.Escape */
        )) {
          e.preventDefault();
        }
        lastKeyDown = e;
        this._onKeyDown.fire(e);
      }));
      this._register(this._textArea.onKeyUp((_e2) => {
        const e = new StandardKeyboardEvent(_e2);
        this._onKeyUp.fire(e);
      }));
      this._register(this._textArea.onCompositionStart((e) => {
        const currentComposition = new CompositionContext();
        if (this._currentComposition) {
          this._currentComposition = currentComposition;
          return;
        }
        this._currentComposition = currentComposition;
        if (this._OS === 2 && lastKeyDown && lastKeyDown.equals(
          114
          /* KeyCode.KEY_IN_COMPOSITION */
        ) && this._textAreaState.selectionStart === this._textAreaState.selectionEnd && this._textAreaState.selectionStart > 0 && this._textAreaState.value.substr(this._textAreaState.selectionStart - 1, 1) === e.data && (lastKeyDown.code === "ArrowRight" || lastKeyDown.code === "ArrowLeft")) {
          currentComposition.handleCompositionUpdate("x");
          this._onCompositionStart.fire({ data: e.data });
          return;
        }
        if (this._browser.isAndroid) {
          this._onCompositionStart.fire({ data: e.data });
          return;
        }
        this._onCompositionStart.fire({ data: e.data });
      }));
      this._register(this._textArea.onCompositionUpdate((e) => {
        const currentComposition = this._currentComposition;
        if (!currentComposition) {
          return;
        }
        if (this._browser.isAndroid) {
          const newState = TextAreaState.readFromTextArea(this._textArea, this._textAreaState);
          const typeInput2 = TextAreaState.deduceAndroidCompositionInput(this._textAreaState, newState);
          this._textAreaState = newState;
          this._onType.fire(typeInput2);
          this._onCompositionUpdate.fire(e);
          return;
        }
        const typeInput = currentComposition.handleCompositionUpdate(e.data);
        this._textAreaState = TextAreaState.readFromTextArea(this._textArea, this._textAreaState);
        this._onType.fire(typeInput);
        this._onCompositionUpdate.fire(e);
      }));
      this._register(this._textArea.onCompositionEnd((e) => {
        const currentComposition = this._currentComposition;
        if (!currentComposition) {
          return;
        }
        this._currentComposition = null;
        if (this._browser.isAndroid) {
          const newState = TextAreaState.readFromTextArea(this._textArea, this._textAreaState);
          const typeInput2 = TextAreaState.deduceAndroidCompositionInput(this._textAreaState, newState);
          this._textAreaState = newState;
          this._onType.fire(typeInput2);
          this._onCompositionEnd.fire();
          return;
        }
        const typeInput = currentComposition.handleCompositionUpdate(e.data);
        this._textAreaState = TextAreaState.readFromTextArea(this._textArea, this._textAreaState);
        this._onType.fire(typeInput);
        this._onCompositionEnd.fire();
      }));
      this._register(this._textArea.onInput((e) => {
        this._textArea.setIgnoreSelectionChangeTime("received input event");
        if (this._currentComposition) {
          return;
        }
        const newState = TextAreaState.readFromTextArea(this._textArea, this._textAreaState);
        const typeInput = TextAreaState.deduceInput(
          this._textAreaState,
          newState,
          /*couldBeEmojiInput*/
          this._OS === 2
          /* OperatingSystem.Macintosh */
        );
        if (typeInput.replacePrevCharCnt === 0 && typeInput.text.length === 1) {
          if (isHighSurrogate(typeInput.text.charCodeAt(0)) || typeInput.text.charCodeAt(0) === 127) {
            return;
          }
        }
        this._textAreaState = newState;
        if (typeInput.text !== "" || typeInput.replacePrevCharCnt !== 0 || typeInput.replaceNextCharCnt !== 0 || typeInput.positionDelta !== 0) {
          if (e.inputType === "insertFromPaste") {
            this._onPaste.fire({
              text: typeInput.text,
              metadata: InMemoryClipboardMetadataManager.INSTANCE.get(typeInput.text)
            });
          } else {
            this._onType.fire(typeInput);
          }
        }
      }));
      this._register(this._textArea.onCut((e) => {
        this._logService.trace(`TextAreaInput#onCut`, e);
        this._textArea.setIgnoreSelectionChangeTime("received cut event");
        this._ensureClipboardGetsEditorSelection(e);
        this._asyncTriggerCut.schedule();
      }));
      this._register(this._textArea.onCopy((e) => {
        this._logService.trace(`TextAreaInput#onCopy`, e);
        this._ensureClipboardGetsEditorSelection(e);
      }));
      this._register(this._textArea.onPaste((e) => {
        this._logService.trace(`TextAreaInput#onPaste`, e);
        this._textArea.setIgnoreSelectionChangeTime("received paste event");
        e.preventDefault();
        if (!e.clipboardData) {
          return;
        }
        let [text2, metadata] = ClipboardEventUtils.getTextData(e.clipboardData);
        this._logService.trace(`TextAreaInput#onPaste with id : `, metadata?.id, " with text.length: ", text2.length);
        if (!text2) {
          return;
        }
        metadata = metadata || InMemoryClipboardMetadataManager.INSTANCE.get(text2);
        this._logService.trace(`TextAreaInput#onPaste (before onPaste)`);
        this._onPaste.fire({
          text: text2,
          metadata
        });
      }));
      this._register(this._textArea.onFocus(() => {
        const hadFocus = this._hasFocus;
        this._setHasFocus(true);
        if (this._accessibilityService.isScreenReaderOptimized() && this._browser.isSafari && !hadFocus && this._hasFocus) {
          if (!this._asyncFocusGainWriteScreenReaderContent.value) {
            this._asyncFocusGainWriteScreenReaderContent.value = new RunOnceScheduler(() => this.writeNativeTextAreaContent("asyncFocusGain"), 0);
          }
          this._asyncFocusGainWriteScreenReaderContent.value.schedule();
        }
      }));
      this._register(this._textArea.onBlur(() => {
        if (this._currentComposition) {
          this._currentComposition = null;
          this.writeNativeTextAreaContent("blurWithoutCompositionEnd");
          this._onCompositionEnd.fire();
        }
        this._setHasFocus(false);
      }));
      this._register(this._textArea.onSyntheticTap(() => {
        if (this._browser.isAndroid && this._currentComposition) {
          this._currentComposition = null;
          this.writeNativeTextAreaContent("tapWithoutCompositionEnd");
          this._onCompositionEnd.fire();
        }
      }));
    }
    _installSelectionChangeListener() {
      let previousSelectionChangeEventTime = 0;
      return addDisposableListener(this._textArea.ownerDocument, "selectionchange", (e) => {
        inputLatency.onSelectionChange();
        if (!this._hasFocus) {
          return;
        }
        if (this._currentComposition) {
          return;
        }
        if (!this._browser.isChrome) {
          return;
        }
        const now = Date.now();
        const delta1 = now - previousSelectionChangeEventTime;
        previousSelectionChangeEventTime = now;
        if (delta1 < 5) {
          return;
        }
        const delta2 = now - this._textArea.getIgnoreSelectionChangeTime();
        this._textArea.resetSelectionChangeTime();
        if (delta2 < 100) {
          return;
        }
        if (!this._textAreaState.selection) {
          return;
        }
        const newValue = this._textArea.getValue();
        if (this._textAreaState.value !== newValue) {
          return;
        }
        const newSelectionStart = this._textArea.getSelectionStart();
        const newSelectionEnd = this._textArea.getSelectionEnd();
        if (this._textAreaState.selectionStart === newSelectionStart && this._textAreaState.selectionEnd === newSelectionEnd) {
          return;
        }
        const _newSelectionStartPosition = this._textAreaState.deduceEditorPosition(newSelectionStart);
        const newSelectionStartPosition = this._host.deduceModelPosition(_newSelectionStartPosition[0], _newSelectionStartPosition[1], _newSelectionStartPosition[2]);
        const _newSelectionEndPosition = this._textAreaState.deduceEditorPosition(newSelectionEnd);
        const newSelectionEndPosition = this._host.deduceModelPosition(_newSelectionEndPosition[0], _newSelectionEndPosition[1], _newSelectionEndPosition[2]);
        const newSelection = new Selection$1(newSelectionStartPosition.lineNumber, newSelectionStartPosition.column, newSelectionEndPosition.lineNumber, newSelectionEndPosition.column);
        this._onSelectionChangeRequest.fire(newSelection);
      });
    }
    dispose() {
      super.dispose();
      if (this._selectionChangeListener) {
        this._selectionChangeListener.dispose();
        this._selectionChangeListener = null;
      }
    }
    focusTextArea() {
      this._setHasFocus(true);
      this.refreshFocusState();
    }
    isFocused() {
      return this._hasFocus;
    }
    refreshFocusState() {
      this._setHasFocus(this._textArea.hasFocus());
    }
    _setHasFocus(newHasFocus) {
      if (this._hasFocus === newHasFocus) {
        return;
      }
      this._hasFocus = newHasFocus;
      if (this._selectionChangeListener) {
        this._selectionChangeListener.dispose();
        this._selectionChangeListener = null;
      }
      if (this._hasFocus) {
        this._selectionChangeListener = this._installSelectionChangeListener();
      }
      if (this._hasFocus) {
        this.writeNativeTextAreaContent("focusgain");
      }
      if (this._hasFocus) {
        this._onFocus.fire();
      } else {
        this._onBlur.fire();
      }
    }
    _setAndWriteTextAreaState(reason, textAreaState) {
      if (!this._hasFocus) {
        textAreaState = textAreaState.collapseSelection();
      }
      if (!textAreaState.isWrittenToTextArea(this._textArea, this._hasFocus)) {
        this._logService.trace(`writeTextAreaState(reason: ${reason})`);
      }
      textAreaState.writeToTextArea(reason, this._textArea, this._hasFocus);
      this._textAreaState = textAreaState;
    }
    writeNativeTextAreaContent(reason) {
      if (!this._accessibilityService.isScreenReaderOptimized() && reason === "render" || this._currentComposition) {
        return;
      }
      this._setAndWriteTextAreaState(reason, this._host.getScreenReaderContent());
    }
    _ensureClipboardGetsEditorSelection(e) {
      const dataToCopy = this._host.getDataToCopy();
      let id = void 0;
      if (this._logService.getLevel() === LogLevel.Trace) {
        id = generateUuid();
      }
      const storedMetadata = {
        version: 1,
        id,
        isFromEmptySelection: dataToCopy.isFromEmptySelection,
        multicursorText: dataToCopy.multicursorText,
        mode: dataToCopy.mode
      };
      InMemoryClipboardMetadataManager.INSTANCE.set(
        // When writing "LINE\r\n" to the clipboard and then pasting,
        // Firefox pastes "LINE\n", so let's work around this quirk
        this._browser.isFirefox ? dataToCopy.text.replace(/\r\n/g, "\n") : dataToCopy.text,
        storedMetadata
      );
      e.preventDefault();
      if (e.clipboardData) {
        ClipboardEventUtils.setTextData(e.clipboardData, dataToCopy.text, dataToCopy.html, storedMetadata);
      }
      this._logService.trace("TextAreaEditContextInput#_ensureClipboardGetsEditorSelection with id : ", id, " with text.length: ", dataToCopy.text.length);
    }
  };
  TextAreaInput = __decorate$31([
    __param$2X(4, IAccessibilityService),
    __param$2X(5, ILogService)
  ], TextAreaInput);
  class TextAreaWrapper extends Disposable {
    get ownerDocument() {
      return this._actual.ownerDocument;
    }
    constructor(_actual) {
      super();
      this._actual = _actual;
      this._onSyntheticTap = this._register(new Emitter$1());
      this.onSyntheticTap = this._onSyntheticTap.event;
      this._ignoreSelectionChangeTime = 0;
      this.onKeyDown = this._register(new DomEmitter(this._actual, "keydown")).event;
      this.onKeyPress = this._register(new DomEmitter(this._actual, "keypress")).event;
      this.onKeyUp = this._register(new DomEmitter(this._actual, "keyup")).event;
      this.onCompositionStart = this._register(new DomEmitter(this._actual, "compositionstart")).event;
      this.onCompositionUpdate = this._register(new DomEmitter(this._actual, "compositionupdate")).event;
      this.onCompositionEnd = this._register(new DomEmitter(this._actual, "compositionend")).event;
      this.onBeforeInput = this._register(new DomEmitter(this._actual, "beforeinput")).event;
      this.onInput = this._register(new DomEmitter(this._actual, "input")).event;
      this.onCut = this._register(new DomEmitter(this._actual, "cut")).event;
      this.onCopy = this._register(new DomEmitter(this._actual, "copy")).event;
      this.onPaste = this._register(new DomEmitter(this._actual, "paste")).event;
      this.onFocus = this._register(new DomEmitter(this._actual, "focus")).event;
      this.onBlur = this._register(new DomEmitter(this._actual, "blur")).event;
      this._register(this.onKeyDown(() => inputLatency.onKeyDown()));
      this._register(this.onBeforeInput(() => inputLatency.onBeforeInput()));
      this._register(this.onInput(() => inputLatency.onInput()));
      this._register(this.onKeyUp(() => inputLatency.onKeyUp()));
      this._register(addDisposableListener(this._actual, TextAreaSyntethicEvents.Tap, () => this._onSyntheticTap.fire()));
    }
    hasFocus() {
      const shadowRoot = getShadowRoot(this._actual);
      if (shadowRoot) {
        return shadowRoot.activeElement === this._actual;
      } else if (this._actual.isConnected) {
        return getActiveElement() === this._actual;
      } else {
        return false;
      }
    }
    setIgnoreSelectionChangeTime(reason) {
      this._ignoreSelectionChangeTime = Date.now();
    }
    getIgnoreSelectionChangeTime() {
      return this._ignoreSelectionChangeTime;
    }
    resetSelectionChangeTime() {
      this._ignoreSelectionChangeTime = 0;
    }
    getValue() {
      return this._actual.value;
    }
    setValue(reason, value) {
      const textArea = this._actual;
      if (textArea.value === value) {
        return;
      }
      this.setIgnoreSelectionChangeTime("setValue");
      textArea.value = value;
    }
    getSelectionStart() {
      return this._actual.selectionDirection === "backward" ? this._actual.selectionEnd : this._actual.selectionStart;
    }
    getSelectionEnd() {
      return this._actual.selectionDirection === "backward" ? this._actual.selectionStart : this._actual.selectionEnd;
    }
    setSelectionRange(reason, selectionStart, selectionEnd) {
      const textArea = this._actual;
      let activeElement = null;
      const shadowRoot = getShadowRoot(textArea);
      if (shadowRoot) {
        activeElement = shadowRoot.activeElement;
      } else {
        activeElement = getActiveElement();
      }
      const activeWindow = getWindow(activeElement);
      const currentIsFocused = activeElement === textArea;
      const currentSelectionStart = textArea.selectionStart;
      const currentSelectionEnd = textArea.selectionEnd;
      if (currentIsFocused && currentSelectionStart === selectionStart && currentSelectionEnd === selectionEnd) {
        if (isFirefox$1 && activeWindow.parent !== activeWindow) {
          textArea.focus();
        }
        return;
      }
      if (currentIsFocused) {
        this.setIgnoreSelectionChangeTime("setSelectionRange");
        textArea.setSelectionRange(selectionStart, selectionEnd);
        if (isFirefox$1 && activeWindow.parent !== activeWindow) {
          textArea.focus();
        }
        return;
      }
      try {
        const scrollState = saveParentsScrollTop(textArea);
        this.setIgnoreSelectionChangeTime("setSelectionRange");
        textArea.focus();
        textArea.setSelectionRange(selectionStart, selectionEnd);
        restoreParentsScrollTop(textArea, scrollState);
      } catch (e) {
      }
    }
  }
  class PointerEventHandler extends MouseHandler {
    constructor(context, viewController, viewHelper) {
      super(context, viewController, viewHelper);
      this._register(Gesture.addTarget(this.viewHelper.linesContentDomNode));
      this._register(addDisposableListener(this.viewHelper.linesContentDomNode, EventType.Tap, (e) => this.onTap(e)));
      this._register(addDisposableListener(this.viewHelper.linesContentDomNode, EventType.Change, (e) => this.onChange(e)));
      this._register(addDisposableListener(this.viewHelper.linesContentDomNode, EventType.Contextmenu, (e) => this._onContextMenu(new EditorMouseEvent(e, false, this.viewHelper.viewDomNode), false)));
      this._lastPointerType = "mouse";
      this._register(addDisposableListener(this.viewHelper.linesContentDomNode, "pointerdown", (e) => {
        const pointerType = e.pointerType;
        if (pointerType === "mouse") {
          this._lastPointerType = "mouse";
          return;
        } else if (pointerType === "touch") {
          this._lastPointerType = "touch";
        } else {
          this._lastPointerType = "pen";
        }
      }));
      const pointerEvents = new EditorPointerEventFactory(this.viewHelper.viewDomNode);
      this._register(pointerEvents.onPointerMove(this.viewHelper.viewDomNode, (e) => this._onMouseMove(e)));
      this._register(pointerEvents.onPointerUp(this.viewHelper.viewDomNode, (e) => this._onMouseUp(e)));
      this._register(pointerEvents.onPointerLeave(this.viewHelper.viewDomNode, (e) => this._onMouseLeave(e)));
      this._register(pointerEvents.onPointerDown(this.viewHelper.viewDomNode, (e, pointerId) => this._onMouseDown(e, pointerId)));
    }
    onTap(event) {
      if (!event.initialTarget || !this.viewHelper.linesContentDomNode.contains(event.initialTarget)) {
        return;
      }
      event.preventDefault();
      this.viewHelper.focusTextArea();
      this._dispatchGesture(
        event,
        /*inSelectionMode*/
        false
      );
    }
    onChange(event) {
      if (this._lastPointerType === "touch") {
        this._context.viewModel.viewLayout.deltaScrollNow(-event.translationX, -event.translationY);
      }
      if (this._lastPointerType === "pen") {
        this._dispatchGesture(
          event,
          /*inSelectionMode*/
          true
        );
      }
    }
    _dispatchGesture(event, inSelectionMode) {
      const target = this._createMouseTarget(new EditorMouseEvent(event, false, this.viewHelper.viewDomNode), false);
      if (target.position) {
        this.viewController.dispatchMouse({
          position: target.position,
          mouseColumn: target.position.column,
          startedOnLineNumbers: false,
          revealType: 1,
          mouseDownCount: event.tapCount,
          inSelectionMode,
          altKey: false,
          ctrlKey: false,
          metaKey: false,
          shiftKey: false,
          leftButton: false,
          middleButton: false,
          onInjectedText: target.type === 6 && target.detail.injectedText !== null
        });
      }
    }
    _onMouseDown(e, pointerId) {
      if (e.browserEvent.pointerType === "touch") {
        return;
      }
      super._onMouseDown(e, pointerId);
    }
  }
  class TouchHandler extends MouseHandler {
    constructor(context, viewController, viewHelper) {
      super(context, viewController, viewHelper);
      this._register(Gesture.addTarget(this.viewHelper.linesContentDomNode));
      this._register(addDisposableListener(this.viewHelper.linesContentDomNode, EventType.Tap, (e) => this.onTap(e)));
      this._register(addDisposableListener(this.viewHelper.linesContentDomNode, EventType.Change, (e) => this.onChange(e)));
      this._register(addDisposableListener(this.viewHelper.linesContentDomNode, EventType.Contextmenu, (e) => this._onContextMenu(new EditorMouseEvent(e, false, this.viewHelper.viewDomNode), false)));
    }
    onTap(event) {
      event.preventDefault();
      this.viewHelper.focusTextArea();
      const target = this._createMouseTarget(new EditorMouseEvent(event, false, this.viewHelper.viewDomNode), false);
      if (target.position) {
        const event2 = document.createEvent("CustomEvent");
        event2.initEvent(TextAreaSyntethicEvents.Tap, false, true);
        this.viewHelper.dispatchTextAreaEvent(event2);
        this.viewController.moveTo(
          target.position,
          1
          /* NavigationCommandRevealType.Minimal */
        );
      }
    }
    onChange(e) {
      this._context.viewModel.viewLayout.deltaScrollNow(-e.translationX, -e.translationY);
    }
  }
  class PointerHandler extends Disposable {
    constructor(context, viewController, viewHelper) {
      super();
      const isPhone = isIOS || isAndroid && isMobile;
      if (isPhone && BrowserFeatures.pointerEvents) {
        this.handler = this._register(new PointerEventHandler(context, viewController, viewHelper));
      } else if (mainWindow.TouchEvent) {
        this.handler = this._register(new TouchHandler(context, viewController, viewHelper));
      } else {
        this.handler = this._register(new MouseHandler(context, viewController, viewHelper));
      }
    }
    getTargetAtClientPoint(clientX, clientY) {
      return this.handler.getTargetAtClientPoint(clientX, clientY);
    }
  }
  class ViewController {
    constructor(configuration, viewModel, userInputEvents, commandDelegate) {
      this.configuration = configuration;
      this.viewModel = viewModel;
      this.userInputEvents = userInputEvents;
      this.commandDelegate = commandDelegate;
    }
    paste(text2, pasteOnNewLine, multicursorText, mode) {
      this.commandDelegate.paste(text2, pasteOnNewLine, multicursorText, mode);
    }
    type(text2) {
      this.commandDelegate.type(text2);
    }
    compositionType(text2, replacePrevCharCnt, replaceNextCharCnt, positionDelta) {
      this.commandDelegate.compositionType(text2, replacePrevCharCnt, replaceNextCharCnt, positionDelta);
    }
    compositionStart() {
      this.commandDelegate.startComposition();
    }
    compositionEnd() {
      this.commandDelegate.endComposition();
    }
    cut() {
      this.commandDelegate.cut();
    }
    setSelection(modelSelection) {
      CoreNavigationCommands.SetSelection.runCoreEditorCommand(this.viewModel, {
        source: "keyboard",
        selection: modelSelection
      });
    }
    _validateViewColumn(viewPosition) {
      const minColumn = this.viewModel.getLineMinColumn(viewPosition.lineNumber);
      if (viewPosition.column < minColumn) {
        return new Position$1(viewPosition.lineNumber, minColumn);
      }
      return viewPosition;
    }
    _hasMulticursorModifier(data) {
      switch (this.configuration.options.get(
        86
        /* EditorOption.multiCursorModifier */
      )) {
        case "altKey":
          return data.altKey;
        case "ctrlKey":
          return data.ctrlKey;
        case "metaKey":
          return data.metaKey;
        default:
          return false;
      }
    }
    _hasNonMulticursorModifier(data) {
      switch (this.configuration.options.get(
        86
        /* EditorOption.multiCursorModifier */
      )) {
        case "altKey":
          return data.ctrlKey || data.metaKey;
        case "ctrlKey":
          return data.altKey || data.metaKey;
        case "metaKey":
          return data.ctrlKey || data.altKey;
        default:
          return false;
      }
    }
    dispatchMouse(data) {
      const options = this.configuration.options;
      const selectionClipboardIsOn = isLinux && options.get(
        121
        /* EditorOption.selectionClipboard */
      );
      const columnSelection = options.get(
        28
        /* EditorOption.columnSelection */
      );
      const scrollOnMiddleClick = options.get(
        171
        /* EditorOption.scrollOnMiddleClick */
      );
      if (data.middleButton && !selectionClipboardIsOn) {
        if (scrollOnMiddleClick) ;
        else {
          this._columnSelect(data.position, data.mouseColumn, data.inSelectionMode);
        }
      } else if (data.startedOnLineNumbers) {
        if (this._hasMulticursorModifier(data)) {
          if (data.inSelectionMode) {
            this._lastCursorLineSelect(data.position, data.revealType);
          } else {
            this._createCursor(data.position, true);
          }
        } else {
          if (data.inSelectionMode) {
            this._lineSelectDrag(data.position, data.revealType);
          } else {
            this._lineSelect(data.position, data.revealType);
          }
        }
      } else if (data.mouseDownCount >= 4) {
        this._selectAll();
      } else if (data.mouseDownCount === 3) {
        if (this._hasMulticursorModifier(data)) {
          if (data.inSelectionMode) {
            this._lastCursorLineSelectDrag(data.position, data.revealType);
          } else {
            this._lastCursorLineSelect(data.position, data.revealType);
          }
        } else {
          if (data.inSelectionMode) {
            this._lineSelectDrag(data.position, data.revealType);
          } else {
            this._lineSelect(data.position, data.revealType);
          }
        }
      } else if (data.mouseDownCount === 2) {
        if (!data.onInjectedText) {
          if (this._hasMulticursorModifier(data)) {
            this._lastCursorWordSelect(data.position, data.revealType);
          } else {
            if (data.inSelectionMode) {
              this._wordSelectDrag(data.position, data.revealType);
            } else {
              this._wordSelect(data.position, data.revealType);
            }
          }
        }
      } else {
        if (this._hasMulticursorModifier(data)) {
          if (!this._hasNonMulticursorModifier(data)) {
            if (data.shiftKey) {
              this._columnSelect(data.position, data.mouseColumn, true);
            } else {
              if (data.inSelectionMode) {
                this._lastCursorMoveToSelect(data.position, data.revealType);
              } else {
                this._createCursor(data.position, false);
              }
            }
          }
        } else {
          if (data.inSelectionMode) {
            if (data.altKey) {
              this._columnSelect(data.position, data.mouseColumn, true);
            } else {
              if (columnSelection) {
                this._columnSelect(data.position, data.mouseColumn, true);
              } else {
                this._moveToSelect(data.position, data.revealType);
              }
            }
          } else {
            this.moveTo(data.position, data.revealType);
          }
        }
      }
    }
    _usualArgs(viewPosition, revealType) {
      viewPosition = this._validateViewColumn(viewPosition);
      return {
        source: "mouse",
        position: this._convertViewToModelPosition(viewPosition),
        viewPosition,
        revealType
      };
    }
    moveTo(viewPosition, revealType) {
      CoreNavigationCommands.MoveTo.runCoreEditorCommand(this.viewModel, this._usualArgs(viewPosition, revealType));
    }
    _moveToSelect(viewPosition, revealType) {
      CoreNavigationCommands.MoveToSelect.runCoreEditorCommand(this.viewModel, this._usualArgs(viewPosition, revealType));
    }
    _columnSelect(viewPosition, mouseColumn, doColumnSelect) {
      viewPosition = this._validateViewColumn(viewPosition);
      CoreNavigationCommands.ColumnSelect.runCoreEditorCommand(this.viewModel, {
        source: "mouse",
        position: this._convertViewToModelPosition(viewPosition),
        viewPosition,
        mouseColumn,
        doColumnSelect
      });
    }
    _createCursor(viewPosition, wholeLine) {
      viewPosition = this._validateViewColumn(viewPosition);
      CoreNavigationCommands.CreateCursor.runCoreEditorCommand(this.viewModel, {
        source: "mouse",
        position: this._convertViewToModelPosition(viewPosition),
        viewPosition,
        wholeLine
      });
    }
    _lastCursorMoveToSelect(viewPosition, revealType) {
      CoreNavigationCommands.LastCursorMoveToSelect.runCoreEditorCommand(this.viewModel, this._usualArgs(viewPosition, revealType));
    }
    _wordSelect(viewPosition, revealType) {
      CoreNavigationCommands.WordSelect.runCoreEditorCommand(this.viewModel, this._usualArgs(viewPosition, revealType));
    }
    _wordSelectDrag(viewPosition, revealType) {
      CoreNavigationCommands.WordSelectDrag.runCoreEditorCommand(this.viewModel, this._usualArgs(viewPosition, revealType));
    }
    _lastCursorWordSelect(viewPosition, revealType) {
      CoreNavigationCommands.LastCursorWordSelect.runCoreEditorCommand(this.viewModel, this._usualArgs(viewPosition, revealType));
    }
    _lineSelect(viewPosition, revealType) {
      CoreNavigationCommands.LineSelect.runCoreEditorCommand(this.viewModel, this._usualArgs(viewPosition, revealType));
    }
    _lineSelectDrag(viewPosition, revealType) {
      CoreNavigationCommands.LineSelectDrag.runCoreEditorCommand(this.viewModel, this._usualArgs(viewPosition, revealType));
    }
    _lastCursorLineSelect(viewPosition, revealType) {
      CoreNavigationCommands.LastCursorLineSelect.runCoreEditorCommand(this.viewModel, this._usualArgs(viewPosition, revealType));
    }
    _lastCursorLineSelectDrag(viewPosition, revealType) {
      CoreNavigationCommands.LastCursorLineSelectDrag.runCoreEditorCommand(this.viewModel, this._usualArgs(viewPosition, revealType));
    }
    _selectAll() {
      CoreNavigationCommands.SelectAll.runCoreEditorCommand(this.viewModel, { source: "mouse" });
    }
    // ----------------------
    _convertViewToModelPosition(viewPosition) {
      return this.viewModel.coordinatesConverter.convertViewPositionToModelPosition(viewPosition);
    }
    emitKeyDown(e) {
      this.userInputEvents.emitKeyDown(e);
    }
    emitKeyUp(e) {
      this.userInputEvents.emitKeyUp(e);
    }
    emitContextMenu(e) {
      this.userInputEvents.emitContextMenu(e);
    }
    emitMouseMove(e) {
      this.userInputEvents.emitMouseMove(e);
    }
    emitMouseLeave(e) {
      this.userInputEvents.emitMouseLeave(e);
    }
    emitMouseUp(e) {
      this.userInputEvents.emitMouseUp(e);
    }
    emitMouseDown(e) {
      this.userInputEvents.emitMouseDown(e);
    }
    emitMouseDrag(e) {
      this.userInputEvents.emitMouseDrag(e);
    }
    emitMouseDrop(e) {
      this.userInputEvents.emitMouseDrop(e);
    }
    emitMouseDropCanceled() {
      this.userInputEvents.emitMouseDropCanceled();
    }
    emitMouseWheel(e) {
      this.userInputEvents.emitMouseWheel(e);
    }
  }
  function createTrustedTypesPolicy(policyName, policyOptions) {
    const monacoEnvironment2 = getMonacoEnvironment();
    if (monacoEnvironment2?.createTrustedTypesPolicy) {
      try {
        return monacoEnvironment2.createTrustedTypesPolicy(policyName, policyOptions);
      } catch (err) {
        onUnexpectedError(err);
        return void 0;
      }
    }
    try {
      return globalThis.trustedTypes?.createPolicy(policyName, policyOptions);
    } catch (err) {
      onUnexpectedError(err);
      return void 0;
    }
  }
  class RenderedLinesCollection {
    constructor(_lineFactory) {
      this._lineFactory = _lineFactory;
      this._set(1, []);
    }
    flush() {
      this._set(1, []);
    }
    _set(rendLineNumberStart, lines) {
      this._lines = lines;
      this._rendLineNumberStart = rendLineNumberStart;
    }
    _get() {
      return {
        rendLineNumberStart: this._rendLineNumberStart,
        lines: this._lines
      };
    }
    /**
     * @returns Inclusive line number that is inside this collection
     */
    getStartLineNumber() {
      return this._rendLineNumberStart;
    }
    /**
     * @returns Inclusive line number that is inside this collection
     */
    getEndLineNumber() {
      return this._rendLineNumberStart + this._lines.length - 1;
    }
    getCount() {
      return this._lines.length;
    }
    getLine(lineNumber) {
      const lineIndex = lineNumber - this._rendLineNumberStart;
      if (lineIndex < 0 || lineIndex >= this._lines.length) {
        throw new BugIndicatingError("Illegal value for lineNumber");
      }
      return this._lines[lineIndex];
    }
    /**
     * @returns Lines that were removed from this collection
     */
    onLinesDeleted(deleteFromLineNumber, deleteToLineNumber) {
      if (this.getCount() === 0) {
        return null;
      }
      const startLineNumber = this.getStartLineNumber();
      const endLineNumber = this.getEndLineNumber();
      if (deleteToLineNumber < startLineNumber) {
        const deleteCnt = deleteToLineNumber - deleteFromLineNumber + 1;
        this._rendLineNumberStart -= deleteCnt;
        return null;
      }
      if (deleteFromLineNumber > endLineNumber) {
        return null;
      }
      let deleteStartIndex = 0;
      let deleteCount = 0;
      for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
        const lineIndex = lineNumber - this._rendLineNumberStart;
        if (deleteFromLineNumber <= lineNumber && lineNumber <= deleteToLineNumber) {
          if (deleteCount === 0) {
            deleteStartIndex = lineIndex;
            deleteCount = 1;
          } else {
            deleteCount++;
          }
        }
      }
      if (deleteFromLineNumber < startLineNumber) {
        let deleteAboveCount = 0;
        if (deleteToLineNumber < startLineNumber) {
          deleteAboveCount = deleteToLineNumber - deleteFromLineNumber + 1;
        } else {
          deleteAboveCount = startLineNumber - deleteFromLineNumber;
        }
        this._rendLineNumberStart -= deleteAboveCount;
      }
      const deleted = this._lines.splice(deleteStartIndex, deleteCount);
      return deleted;
    }
    onLinesChanged(changeFromLineNumber, changeCount) {
      const changeToLineNumber = changeFromLineNumber + changeCount - 1;
      if (this.getCount() === 0) {
        return false;
      }
      const startLineNumber = this.getStartLineNumber();
      const endLineNumber = this.getEndLineNumber();
      let someoneNotified = false;
      for (let changedLineNumber = changeFromLineNumber; changedLineNumber <= changeToLineNumber; changedLineNumber++) {
        if (changedLineNumber >= startLineNumber && changedLineNumber <= endLineNumber) {
          this._lines[changedLineNumber - this._rendLineNumberStart].onContentChanged();
          someoneNotified = true;
        }
      }
      return someoneNotified;
    }
    onLinesInserted(insertFromLineNumber, insertToLineNumber) {
      if (this.getCount() === 0) {
        return null;
      }
      const insertCnt = insertToLineNumber - insertFromLineNumber + 1;
      const startLineNumber = this.getStartLineNumber();
      const endLineNumber = this.getEndLineNumber();
      if (insertFromLineNumber <= startLineNumber) {
        this._rendLineNumberStart += insertCnt;
        return null;
      }
      if (insertFromLineNumber > endLineNumber) {
        return null;
      }
      if (insertCnt + insertFromLineNumber > endLineNumber) {
        const deleted = this._lines.splice(insertFromLineNumber - this._rendLineNumberStart, endLineNumber - insertFromLineNumber + 1);
        return deleted;
      }
      const newLines = [];
      for (let i2 = 0; i2 < insertCnt; i2++) {
        newLines[i2] = this._lineFactory.createLine();
      }
      const insertIndex = insertFromLineNumber - this._rendLineNumberStart;
      const beforeLines = this._lines.slice(0, insertIndex);
      const afterLines = this._lines.slice(insertIndex, this._lines.length - insertCnt);
      const deletedLines = this._lines.slice(this._lines.length - insertCnt, this._lines.length);
      this._lines = beforeLines.concat(newLines).concat(afterLines);
      return deletedLines;
    }
    onTokensChanged(ranges) {
      if (this.getCount() === 0) {
        return false;
      }
      const startLineNumber = this.getStartLineNumber();
      const endLineNumber = this.getEndLineNumber();
      let notifiedSomeone = false;
      for (let i2 = 0, len = ranges.length; i2 < len; i2++) {
        const rng = ranges[i2];
        if (rng.toLineNumber < startLineNumber || rng.fromLineNumber > endLineNumber) {
          continue;
        }
        const from = Math.max(startLineNumber, rng.fromLineNumber);
        const to = Math.min(endLineNumber, rng.toLineNumber);
        for (let lineNumber = from; lineNumber <= to; lineNumber++) {
          const lineIndex = lineNumber - this._rendLineNumberStart;
          this._lines[lineIndex].onTokensChanged();
          notifiedSomeone = true;
        }
      }
      return notifiedSomeone;
    }
  }
  class VisibleLinesCollection {
    constructor(_viewContext, _lineFactory) {
      this._viewContext = _viewContext;
      this._lineFactory = _lineFactory;
      this.domNode = this._createDomNode();
      this._linesCollection = new RenderedLinesCollection(this._lineFactory);
    }
    _createDomNode() {
      const domNode = createFastDomNode(document.createElement("div"));
      domNode.setClassName("view-layer");
      domNode.setPosition("absolute");
      domNode.domNode.setAttribute("role", "presentation");
      domNode.domNode.setAttribute("aria-hidden", "true");
      return domNode;
    }
    // ---- begin view event handlers
    onConfigurationChanged(e) {
      if (e.hasChanged(
        165
        /* EditorOption.layoutInfo */
      )) {
        return true;
      }
      return false;
    }
    onFlushed(e, flushDom) {
      if (flushDom) {
        const start = this._linesCollection.getStartLineNumber();
        const end = this._linesCollection.getEndLineNumber();
        for (let i2 = start; i2 <= end; i2++) {
          this._linesCollection.getLine(i2).getDomNode()?.remove();
        }
      }
      this._linesCollection.flush();
      return true;
    }
    onLinesChanged(e) {
      return this._linesCollection.onLinesChanged(e.fromLineNumber, e.count);
    }
    onLinesDeleted(e) {
      const deleted = this._linesCollection.onLinesDeleted(e.fromLineNumber, e.toLineNumber);
      if (deleted) {
        for (let i2 = 0, len = deleted.length; i2 < len; i2++) {
          const lineDomNode = deleted[i2].getDomNode();
          lineDomNode?.remove();
        }
      }
      return true;
    }
    onLinesInserted(e) {
      const deleted = this._linesCollection.onLinesInserted(e.fromLineNumber, e.toLineNumber);
      if (deleted) {
        for (let i2 = 0, len = deleted.length; i2 < len; i2++) {
          const lineDomNode = deleted[i2].getDomNode();
          lineDomNode?.remove();
        }
      }
      return true;
    }
    onScrollChanged(e) {
      return e.scrollTopChanged;
    }
    onTokensChanged(e) {
      return this._linesCollection.onTokensChanged(e.ranges);
    }
    onZonesChanged(e) {
      return true;
    }
    // ---- end view event handlers
    getStartLineNumber() {
      return this._linesCollection.getStartLineNumber();
    }
    getEndLineNumber() {
      return this._linesCollection.getEndLineNumber();
    }
    getVisibleLine(lineNumber) {
      return this._linesCollection.getLine(lineNumber);
    }
    renderLines(viewportData) {
      const inp = this._linesCollection._get();
      const renderer = new ViewLayerRenderer(this.domNode.domNode, this._lineFactory, viewportData, this._viewContext);
      const ctx = {
        rendLineNumberStart: inp.rendLineNumberStart,
        lines: inp.lines,
        linesLength: inp.lines.length
      };
      const resCtx = renderer.render(ctx, viewportData.startLineNumber, viewportData.endLineNumber, viewportData.relativeVerticalOffset);
      this._linesCollection._set(resCtx.rendLineNumberStart, resCtx.lines);
    }
  }
  const _ViewLayerRenderer = class _ViewLayerRenderer {
    constructor(_domNode, _lineFactory, _viewportData, _viewContext) {
      this._domNode = _domNode;
      this._lineFactory = _lineFactory;
      this._viewportData = _viewportData;
      this._viewContext = _viewContext;
    }
    render(inContext, startLineNumber, stopLineNumber, deltaTop) {
      const ctx = {
        rendLineNumberStart: inContext.rendLineNumberStart,
        lines: inContext.lines.slice(0),
        linesLength: inContext.linesLength
      };
      if (ctx.rendLineNumberStart + ctx.linesLength - 1 < startLineNumber || stopLineNumber < ctx.rendLineNumberStart) {
        ctx.rendLineNumberStart = startLineNumber;
        ctx.linesLength = stopLineNumber - startLineNumber + 1;
        ctx.lines = [];
        for (let x = startLineNumber; x <= stopLineNumber; x++) {
          ctx.lines[x - startLineNumber] = this._lineFactory.createLine();
        }
        this._finishRendering(ctx, true, deltaTop);
        return ctx;
      }
      this._renderUntouchedLines(ctx, Math.max(startLineNumber - ctx.rendLineNumberStart, 0), Math.min(stopLineNumber - ctx.rendLineNumberStart, ctx.linesLength - 1), deltaTop, startLineNumber);
      if (ctx.rendLineNumberStart > startLineNumber) {
        const fromLineNumber = startLineNumber;
        const toLineNumber = Math.min(stopLineNumber, ctx.rendLineNumberStart - 1);
        if (fromLineNumber <= toLineNumber) {
          this._insertLinesBefore(ctx, fromLineNumber, toLineNumber, deltaTop, startLineNumber);
          ctx.linesLength += toLineNumber - fromLineNumber + 1;
        }
      } else if (ctx.rendLineNumberStart < startLineNumber) {
        const removeCnt = Math.min(ctx.linesLength, startLineNumber - ctx.rendLineNumberStart);
        if (removeCnt > 0) {
          this._removeLinesBefore(ctx, removeCnt);
          ctx.linesLength -= removeCnt;
        }
      }
      ctx.rendLineNumberStart = startLineNumber;
      if (ctx.rendLineNumberStart + ctx.linesLength - 1 < stopLineNumber) {
        const fromLineNumber = ctx.rendLineNumberStart + ctx.linesLength;
        const toLineNumber = stopLineNumber;
        if (fromLineNumber <= toLineNumber) {
          this._insertLinesAfter(ctx, fromLineNumber, toLineNumber, deltaTop, startLineNumber);
          ctx.linesLength += toLineNumber - fromLineNumber + 1;
        }
      } else if (ctx.rendLineNumberStart + ctx.linesLength - 1 > stopLineNumber) {
        const fromLineNumber = Math.max(0, stopLineNumber - ctx.rendLineNumberStart + 1);
        const toLineNumber = ctx.linesLength - 1;
        const removeCnt = toLineNumber - fromLineNumber + 1;
        if (removeCnt > 0) {
          this._removeLinesAfter(ctx, removeCnt);
          ctx.linesLength -= removeCnt;
        }
      }
      this._finishRendering(ctx, false, deltaTop);
      return ctx;
    }
    _renderUntouchedLines(ctx, startIndex, endIndex, deltaTop, deltaLN) {
      const rendLineNumberStart = ctx.rendLineNumberStart;
      const lines = ctx.lines;
      for (let i2 = startIndex; i2 <= endIndex; i2++) {
        const lineNumber = rendLineNumberStart + i2;
        lines[i2].layoutLine(lineNumber, deltaTop[lineNumber - deltaLN], this._lineHeightForLineNumber(lineNumber));
      }
    }
    _insertLinesBefore(ctx, fromLineNumber, toLineNumber, deltaTop, deltaLN) {
      const newLines = [];
      let newLinesLen = 0;
      for (let lineNumber = fromLineNumber; lineNumber <= toLineNumber; lineNumber++) {
        newLines[newLinesLen++] = this._lineFactory.createLine();
      }
      ctx.lines = newLines.concat(ctx.lines);
    }
    _removeLinesBefore(ctx, removeCount) {
      for (let i2 = 0; i2 < removeCount; i2++) {
        const lineDomNode = ctx.lines[i2].getDomNode();
        lineDomNode?.remove();
      }
      ctx.lines.splice(0, removeCount);
    }
    _insertLinesAfter(ctx, fromLineNumber, toLineNumber, deltaTop, deltaLN) {
      const newLines = [];
      let newLinesLen = 0;
      for (let lineNumber = fromLineNumber; lineNumber <= toLineNumber; lineNumber++) {
        newLines[newLinesLen++] = this._lineFactory.createLine();
      }
      ctx.lines = ctx.lines.concat(newLines);
    }
    _removeLinesAfter(ctx, removeCount) {
      const removeIndex = ctx.linesLength - removeCount;
      for (let i2 = 0; i2 < removeCount; i2++) {
        const lineDomNode = ctx.lines[removeIndex + i2].getDomNode();
        lineDomNode?.remove();
      }
      ctx.lines.splice(removeIndex, removeCount);
    }
    _finishRenderingNewLines(ctx, domNodeIsEmpty, newLinesHTML, wasNew) {
      if (_ViewLayerRenderer._ttPolicy) {
        newLinesHTML = _ViewLayerRenderer._ttPolicy.createHTML(newLinesHTML);
      }
      const lastChild = this._domNode.lastChild;
      if (domNodeIsEmpty || !lastChild) {
        this._domNode.innerHTML = newLinesHTML;
      } else {
        lastChild.insertAdjacentHTML("afterend", newLinesHTML);
      }
      let currChild = this._domNode.lastChild;
      for (let i2 = ctx.linesLength - 1; i2 >= 0; i2--) {
        const line = ctx.lines[i2];
        if (wasNew[i2]) {
          line.setDomNode(currChild);
          currChild = currChild.previousSibling;
        }
      }
    }
    _finishRenderingInvalidLines(ctx, invalidLinesHTML, wasInvalid) {
      const hugeDomNode = document.createElement("div");
      if (_ViewLayerRenderer._ttPolicy) {
        invalidLinesHTML = _ViewLayerRenderer._ttPolicy.createHTML(invalidLinesHTML);
      }
      hugeDomNode.innerHTML = invalidLinesHTML;
      for (let i2 = 0; i2 < ctx.linesLength; i2++) {
        const line = ctx.lines[i2];
        if (wasInvalid[i2]) {
          const source = hugeDomNode.firstChild;
          const lineDomNode = line.getDomNode();
          lineDomNode.replaceWith(source);
          line.setDomNode(source);
        }
      }
    }
    _finishRendering(ctx, domNodeIsEmpty, deltaTop) {
      const sb = _ViewLayerRenderer._sb;
      const linesLength = ctx.linesLength;
      const lines = ctx.lines;
      const rendLineNumberStart = ctx.rendLineNumberStart;
      const wasNew = [];
      {
        sb.reset();
        let hadNewLine = false;
        for (let i2 = 0; i2 < linesLength; i2++) {
          const line = lines[i2];
          wasNew[i2] = false;
          const lineDomNode = line.getDomNode();
          if (lineDomNode) {
            continue;
          }
          const renderedLineNumber = i2 + rendLineNumberStart;
          const renderResult = line.renderLine(renderedLineNumber, deltaTop[i2], this._lineHeightForLineNumber(renderedLineNumber), this._viewportData, sb);
          if (!renderResult) {
            continue;
          }
          wasNew[i2] = true;
          hadNewLine = true;
        }
        if (hadNewLine) {
          this._finishRenderingNewLines(ctx, domNodeIsEmpty, sb.build(), wasNew);
        }
      }
      {
        sb.reset();
        let hadInvalidLine = false;
        const wasInvalid = [];
        for (let i2 = 0; i2 < linesLength; i2++) {
          const line = lines[i2];
          wasInvalid[i2] = false;
          if (wasNew[i2]) {
            continue;
          }
          const renderedLineNumber = i2 + rendLineNumberStart;
          const renderResult = line.renderLine(renderedLineNumber, deltaTop[i2], this._lineHeightForLineNumber(renderedLineNumber), this._viewportData, sb);
          if (!renderResult) {
            continue;
          }
          wasInvalid[i2] = true;
          hadInvalidLine = true;
        }
        if (hadInvalidLine) {
          this._finishRenderingInvalidLines(ctx, sb.build(), wasInvalid);
        }
      }
    }
    _lineHeightForLineNumber(lineNumber) {
      return this._viewContext.viewLayout.getLineHeightForLineNumber(lineNumber);
    }
  };
  _ViewLayerRenderer._ttPolicy = createTrustedTypesPolicy("editorViewLayer", { createHTML: (value) => value });
  _ViewLayerRenderer._sb = new StringBuilder(1e5);
  let ViewLayerRenderer = _ViewLayerRenderer;
  class ViewOverlays extends ViewPart {
    constructor(context) {
      super(context);
      this._dynamicOverlays = [];
      this._isFocused = false;
      this._visibleLines = new VisibleLinesCollection(this._context, {
        createLine: () => new ViewOverlayLine(this._dynamicOverlays)
      });
      this.domNode = this._visibleLines.domNode;
      const options = this._context.configuration.options;
      const fontInfo = options.get(
        59
        /* EditorOption.fontInfo */
      );
      applyFontInfo(this.domNode, fontInfo);
      this.domNode.setClassName("view-overlays");
    }
    shouldRender() {
      if (super.shouldRender()) {
        return true;
      }
      for (let i2 = 0, len = this._dynamicOverlays.length; i2 < len; i2++) {
        const dynamicOverlay = this._dynamicOverlays[i2];
        if (dynamicOverlay.shouldRender()) {
          return true;
        }
      }
      return false;
    }
    dispose() {
      super.dispose();
      for (let i2 = 0, len = this._dynamicOverlays.length; i2 < len; i2++) {
        const dynamicOverlay = this._dynamicOverlays[i2];
        dynamicOverlay.dispose();
      }
      this._dynamicOverlays = [];
    }
    getDomNode() {
      return this.domNode;
    }
    addDynamicOverlay(overlay) {
      this._dynamicOverlays.push(overlay);
    }
    // ----- event handlers
    onConfigurationChanged(e) {
      this._visibleLines.onConfigurationChanged(e);
      const options = this._context.configuration.options;
      const fontInfo = options.get(
        59
        /* EditorOption.fontInfo */
      );
      applyFontInfo(this.domNode, fontInfo);
      return true;
    }
    onFlushed(e) {
      return this._visibleLines.onFlushed(e);
    }
    onFocusChanged(e) {
      this._isFocused = e.isFocused;
      return true;
    }
    onLinesChanged(e) {
      return this._visibleLines.onLinesChanged(e);
    }
    onLinesDeleted(e) {
      return this._visibleLines.onLinesDeleted(e);
    }
    onLinesInserted(e) {
      return this._visibleLines.onLinesInserted(e);
    }
    onScrollChanged(e) {
      return this._visibleLines.onScrollChanged(e) || true;
    }
    onTokensChanged(e) {
      return this._visibleLines.onTokensChanged(e);
    }
    onZonesChanged(e) {
      return this._visibleLines.onZonesChanged(e);
    }
    // ----- end event handlers
    prepareRender(ctx) {
      const toRender = this._dynamicOverlays.filter((overlay) => overlay.shouldRender());
      for (let i2 = 0, len = toRender.length; i2 < len; i2++) {
        const dynamicOverlay = toRender[i2];
        dynamicOverlay.prepareRender(ctx);
        dynamicOverlay.onDidRender();
      }
    }
    render(ctx) {
      this._viewOverlaysRender(ctx);
      this.domNode.toggleClassName("focused", this._isFocused);
    }
    _viewOverlaysRender(ctx) {
      this._visibleLines.renderLines(ctx.viewportData);
    }
  }
  class ViewOverlayLine {
    constructor(dynamicOverlays) {
      this._dynamicOverlays = dynamicOverlays;
      this._domNode = null;
      this._renderedContent = null;
    }
    getDomNode() {
      if (!this._domNode) {
        return null;
      }
      return this._domNode.domNode;
    }
    setDomNode(domNode) {
      this._domNode = createFastDomNode(domNode);
    }
    onContentChanged() {
    }
    onTokensChanged() {
    }
    renderLine(lineNumber, deltaTop, lineHeight, viewportData, sb) {
      let result = "";
      for (let i2 = 0, len = this._dynamicOverlays.length; i2 < len; i2++) {
        const dynamicOverlay = this._dynamicOverlays[i2];
        result += dynamicOverlay.render(viewportData.startLineNumber, lineNumber);
      }
      if (this._renderedContent === result) {
        return false;
      }
      this._renderedContent = result;
      sb.appendString('<div style="top:');
      sb.appendString(String(deltaTop));
      sb.appendString("px;height:");
      sb.appendString(String(lineHeight));
      sb.appendString("px;line-height:");
      sb.appendString(String(lineHeight));
      sb.appendString('px;">');
      sb.appendString(result);
      sb.appendString("</div>");
      return true;
    }
    layoutLine(lineNumber, deltaTop, lineHeight) {
      if (this._domNode) {
        this._domNode.setTop(deltaTop);
        this._domNode.setHeight(lineHeight);
        this._domNode.setLineHeight(lineHeight);
      }
    }
  }
  class ContentViewOverlays extends ViewOverlays {
    constructor(context) {
      super(context);
      const options = this._context.configuration.options;
      const layoutInfo = options.get(
        165
        /* EditorOption.layoutInfo */
      );
      this._contentWidth = layoutInfo.contentWidth;
      this.domNode.setHeight(0);
    }
    // --- begin event handlers
    onConfigurationChanged(e) {
      const options = this._context.configuration.options;
      const layoutInfo = options.get(
        165
        /* EditorOption.layoutInfo */
      );
      this._contentWidth = layoutInfo.contentWidth;
      return super.onConfigurationChanged(e) || true;
    }
    onScrollChanged(e) {
      return super.onScrollChanged(e) || e.scrollWidthChanged;
    }
    // --- end event handlers
    _viewOverlaysRender(ctx) {
      super._viewOverlaysRender(ctx);
      this.domNode.setWidth(Math.max(ctx.scrollWidth, this._contentWidth));
    }
  }
  class MarginViewOverlays extends ViewOverlays {
    constructor(context) {
      super(context);
      const options = this._context.configuration.options;
      const layoutInfo = options.get(
        165
        /* EditorOption.layoutInfo */
      );
      this._contentLeft = layoutInfo.contentLeft;
      this.domNode.setClassName("margin-view-overlays");
      this.domNode.setWidth(1);
      applyFontInfo(this.domNode, options.get(
        59
        /* EditorOption.fontInfo */
      ));
    }
    onConfigurationChanged(e) {
      const options = this._context.configuration.options;
      applyFontInfo(this.domNode, options.get(
        59
        /* EditorOption.fontInfo */
      ));
      const layoutInfo = options.get(
        165
        /* EditorOption.layoutInfo */
      );
      this._contentLeft = layoutInfo.contentLeft;
      return super.onConfigurationChanged(e) || true;
    }
    onScrollChanged(e) {
      return super.onScrollChanged(e) || e.scrollHeightChanged;
    }
    _viewOverlaysRender(ctx) {
      super._viewOverlaysRender(ctx);
      const height = Math.min(ctx.scrollHeight, 1e6);
      this.domNode.setHeight(height);
      this.domNode.setWidth(this._contentLeft);
    }
  }
  class ViewUserInputEvents {
    constructor(coordinatesConverter) {
      this.onKeyDown = null;
      this.onKeyUp = null;
      this.onContextMenu = null;
      this.onMouseMove = null;
      this.onMouseLeave = null;
      this.onMouseDown = null;
      this.onMouseUp = null;
      this.onMouseDrag = null;
      this.onMouseDrop = null;
      this.onMouseDropCanceled = null;
      this.onMouseWheel = null;
      this._coordinatesConverter = coordinatesConverter;
    }
    emitKeyDown(e) {
      this.onKeyDown?.(e);
    }
    emitKeyUp(e) {
      this.onKeyUp?.(e);
    }
    emitContextMenu(e) {
      this.onContextMenu?.(this._convertViewToModelMouseEvent(e));
    }
    emitMouseMove(e) {
      this.onMouseMove?.(this._convertViewToModelMouseEvent(e));
    }
    emitMouseLeave(e) {
      this.onMouseLeave?.(this._convertViewToModelMouseEvent(e));
    }
    emitMouseDown(e) {
      this.onMouseDown?.(this._convertViewToModelMouseEvent(e));
    }
    emitMouseUp(e) {
      this.onMouseUp?.(this._convertViewToModelMouseEvent(e));
    }
    emitMouseDrag(e) {
      this.onMouseDrag?.(this._convertViewToModelMouseEvent(e));
    }
    emitMouseDrop(e) {
      this.onMouseDrop?.(this._convertViewToModelMouseEvent(e));
    }
    emitMouseDropCanceled() {
      this.onMouseDropCanceled?.();
    }
    emitMouseWheel(e) {
      this.onMouseWheel?.(e);
    }
    _convertViewToModelMouseEvent(e) {
      if (e.target) {
        return {
          event: e.event,
          target: this._convertViewToModelMouseTarget(e.target)
        };
      }
      return e;
    }
    _convertViewToModelMouseTarget(target) {
      return ViewUserInputEvents.convertViewToModelMouseTarget(target, this._coordinatesConverter);
    }
    static convertViewToModelMouseTarget(target, coordinatesConverter) {
      const result = { ...target };
      if (result.position) {
        result.position = coordinatesConverter.convertViewPositionToModelPosition(result.position);
      }
      if (result.range) {
        result.range = coordinatesConverter.convertViewRangeToModelRange(result.range);
      }
      if (result.type === 5 || result.type === 8) {
        result.detail = this.convertViewToModelViewZoneData(result.detail, coordinatesConverter);
      }
      return result;
    }
    static convertViewToModelViewZoneData(data, coordinatesConverter) {
      return {
        viewZoneId: data.viewZoneId,
        positionBefore: data.positionBefore ? coordinatesConverter.convertViewPositionToModelPosition(data.positionBefore) : data.positionBefore,
        positionAfter: data.positionAfter ? coordinatesConverter.convertViewPositionToModelPosition(data.positionAfter) : data.positionAfter,
        position: coordinatesConverter.convertViewPositionToModelPosition(data.position),
        afterLineNumber: coordinatesConverter.convertViewPositionToModelPosition(new Position$1(data.afterLineNumber, 1)).lineNumber
      };
    }
  }
  class BlockDecorations extends ViewPart {
    constructor(context) {
      super(context);
      this.blocks = [];
      this.contentWidth = -1;
      this.contentLeft = 0;
      this.domNode = createFastDomNode(document.createElement("div"));
      this.domNode.setAttribute("role", "presentation");
      this.domNode.setAttribute("aria-hidden", "true");
      this.domNode.setClassName("blockDecorations-container");
      this.update();
    }
    update() {
      let didChange = false;
      const options = this._context.configuration.options;
      const layoutInfo = options.get(
        165
        /* EditorOption.layoutInfo */
      );
      const newContentWidth = layoutInfo.contentWidth - layoutInfo.verticalScrollbarWidth;
      if (this.contentWidth !== newContentWidth) {
        this.contentWidth = newContentWidth;
        didChange = true;
      }
      const newContentLeft = layoutInfo.contentLeft;
      if (this.contentLeft !== newContentLeft) {
        this.contentLeft = newContentLeft;
        didChange = true;
      }
      return didChange;
    }
    dispose() {
      super.dispose();
    }
    // --- begin event handlers
    onConfigurationChanged(e) {
      return this.update();
    }
    onScrollChanged(e) {
      return e.scrollTopChanged || e.scrollLeftChanged;
    }
    onDecorationsChanged(e) {
      return true;
    }
    onZonesChanged(e) {
      return true;
    }
    // --- end event handlers
    prepareRender(ctx) {
    }
    render(ctx) {
      let count = 0;
      const decorations = ctx.getDecorationsInViewport();
      for (const decoration2 of decorations) {
        if (!decoration2.options.blockClassName) {
          continue;
        }
        let block2 = this.blocks[count];
        if (!block2) {
          block2 = this.blocks[count] = createFastDomNode(document.createElement("div"));
          this.domNode.appendChild(block2);
        }
        let top;
        let bottom;
        if (decoration2.options.blockIsAfterEnd) {
          top = ctx.getVerticalOffsetAfterLineNumber(decoration2.range.endLineNumber, false);
          bottom = ctx.getVerticalOffsetAfterLineNumber(decoration2.range.endLineNumber, true);
        } else {
          top = ctx.getVerticalOffsetForLineNumber(decoration2.range.startLineNumber, true);
          bottom = decoration2.range.isEmpty() && !decoration2.options.blockDoesNotCollapse ? ctx.getVerticalOffsetForLineNumber(decoration2.range.startLineNumber, false) : ctx.getVerticalOffsetAfterLineNumber(decoration2.range.endLineNumber, true);
        }
        const [paddingTop, paddingRight, paddingBottom, paddingLeft] = decoration2.options.blockPadding ?? [0, 0, 0, 0];
        block2.setClassName("blockDecorations-block " + decoration2.options.blockClassName);
        block2.setLeft(this.contentLeft - paddingLeft);
        block2.setWidth(this.contentWidth + paddingLeft + paddingRight);
        block2.setTop(top - ctx.scrollTop - paddingTop);
        block2.setHeight(bottom - top + paddingTop + paddingBottom);
        count++;
      }
      for (let i2 = count; i2 < this.blocks.length; i2++) {
        this.blocks[i2].domNode.remove();
      }
      this.blocks.length = count;
    }
  }
  class ViewContentWidgets extends ViewPart {
    constructor(context, viewDomNode) {
      super(context);
      this._viewDomNode = viewDomNode;
      this._widgets = {};
      this.domNode = createFastDomNode(document.createElement("div"));
      PartFingerprints.write(
        this.domNode,
        1
        /* PartFingerprint.ContentWidgets */
      );
      this.domNode.setClassName("contentWidgets");
      this.domNode.setPosition("absolute");
      this.domNode.setTop(0);
      this.overflowingContentWidgetsDomNode = createFastDomNode(document.createElement("div"));
      PartFingerprints.write(
        this.overflowingContentWidgetsDomNode,
        2
        /* PartFingerprint.OverflowingContentWidgets */
      );
      this.overflowingContentWidgetsDomNode.setClassName("overflowingContentWidgets");
    }
    dispose() {
      super.dispose();
      this._widgets = {};
    }
    // --- begin event handlers
    onConfigurationChanged(e) {
      const keys = Object.keys(this._widgets);
      for (const widgetId of keys) {
        this._widgets[widgetId].onConfigurationChanged(e);
      }
      return true;
    }
    onDecorationsChanged(e) {
      return true;
    }
    onFlushed(e) {
      return true;
    }
    onLineMappingChanged(e) {
      this._updateAnchorsViewPositions();
      return true;
    }
    onLinesChanged(e) {
      this._updateAnchorsViewPositions();
      return true;
    }
    onLinesDeleted(e) {
      this._updateAnchorsViewPositions();
      return true;
    }
    onLinesInserted(e) {
      this._updateAnchorsViewPositions();
      return true;
    }
    onScrollChanged(e) {
      return true;
    }
    onZonesChanged(e) {
      return true;
    }
    // ---- end view event handlers
    _updateAnchorsViewPositions() {
      const keys = Object.keys(this._widgets);
      for (const widgetId of keys) {
        this._widgets[widgetId].updateAnchorViewPosition();
      }
    }
    addWidget(_widget) {
      const myWidget = new Widget(this._context, this._viewDomNode, _widget);
      this._widgets[myWidget.id] = myWidget;
      if (myWidget.allowEditorOverflow) {
        this.overflowingContentWidgetsDomNode.appendChild(myWidget.domNode);
      } else {
        this.domNode.appendChild(myWidget.domNode);
      }
      this.setShouldRender();
    }
    setWidgetPosition(widget, primaryAnchor, secondaryAnchor, preference, affinity) {
      const myWidget = this._widgets[widget.getId()];
      myWidget.setPosition(primaryAnchor, secondaryAnchor, preference, affinity);
      this.setShouldRender();
    }
    removeWidget(widget) {
      const widgetId = widget.getId();
      if (this._widgets.hasOwnProperty(widgetId)) {
        const myWidget = this._widgets[widgetId];
        delete this._widgets[widgetId];
        const domNode = myWidget.domNode.domNode;
        domNode.remove();
        domNode.removeAttribute("monaco-visible-content-widget");
        this.setShouldRender();
      }
    }
    shouldSuppressMouseDownOnWidget(widgetId) {
      if (this._widgets.hasOwnProperty(widgetId)) {
        return this._widgets[widgetId].suppressMouseDown;
      }
      return false;
    }
    onBeforeRender(viewportData) {
      const keys = Object.keys(this._widgets);
      for (const widgetId of keys) {
        this._widgets[widgetId].onBeforeRender(viewportData);
      }
    }
    prepareRender(ctx) {
      const keys = Object.keys(this._widgets);
      for (const widgetId of keys) {
        this._widgets[widgetId].prepareRender(ctx);
      }
    }
    render(ctx) {
      const keys = Object.keys(this._widgets);
      for (const widgetId of keys) {
        this._widgets[widgetId].render(ctx);
      }
    }
  }
  class Widget {
    constructor(context, viewDomNode, actual) {
      this._primaryAnchor = new PositionPair(null, null);
      this._secondaryAnchor = new PositionPair(null, null);
      this._context = context;
      this._viewDomNode = viewDomNode;
      this._actual = actual;
      const options = this._context.configuration.options;
      const layoutInfo = options.get(
        165
        /* EditorOption.layoutInfo */
      );
      const allowOverflow = options.get(
        4
        /* EditorOption.allowOverflow */
      );
      this.domNode = createFastDomNode(this._actual.getDomNode());
      this.id = this._actual.getId();
      this.allowEditorOverflow = (this._actual.allowEditorOverflow || false) && allowOverflow;
      this.suppressMouseDown = this._actual.suppressMouseDown || false;
      this._fixedOverflowWidgets = options.get(
        51
        /* EditorOption.fixedOverflowWidgets */
      );
      this._contentWidth = layoutInfo.contentWidth;
      this._contentLeft = layoutInfo.contentLeft;
      this._affinity = null;
      this._preference = [];
      this._cachedDomNodeOffsetWidth = -1;
      this._cachedDomNodeOffsetHeight = -1;
      this._maxWidth = this._getMaxWidth();
      this._isVisible = false;
      this._renderData = null;
      this.domNode.setPosition(this._fixedOverflowWidgets && this.allowEditorOverflow ? "fixed" : "absolute");
      this.domNode.setDisplay("none");
      this.domNode.setVisibility("hidden");
      this.domNode.setAttribute("widgetId", this.id);
      this.domNode.setMaxWidth(this._maxWidth);
    }
    onConfigurationChanged(e) {
      const options = this._context.configuration.options;
      if (e.hasChanged(
        165
        /* EditorOption.layoutInfo */
      )) {
        const layoutInfo = options.get(
          165
          /* EditorOption.layoutInfo */
        );
        this._contentLeft = layoutInfo.contentLeft;
        this._contentWidth = layoutInfo.contentWidth;
        this._maxWidth = this._getMaxWidth();
      }
    }
    updateAnchorViewPosition() {
      this._setPosition(this._affinity, this._primaryAnchor.modelPosition, this._secondaryAnchor.modelPosition);
    }
    _setPosition(affinity, primaryAnchor, secondaryAnchor) {
      this._affinity = affinity;
      this._primaryAnchor = getValidPositionPair(primaryAnchor, this._context.viewModel, this._affinity);
      this._secondaryAnchor = getValidPositionPair(secondaryAnchor, this._context.viewModel, this._affinity);
      function getValidPositionPair(position, viewModel, affinity2) {
        if (!position) {
          return new PositionPair(null, null);
        }
        const validModelPosition = viewModel.model.validatePosition(position);
        if (viewModel.coordinatesConverter.modelPositionIsVisible(validModelPosition)) {
          const viewPosition = viewModel.coordinatesConverter.convertModelPositionToViewPosition(validModelPosition, affinity2 ?? void 0);
          return new PositionPair(position, viewPosition);
        }
        return new PositionPair(position, null);
      }
    }
    _getMaxWidth() {
      const elDocument = this.domNode.domNode.ownerDocument;
      const elWindow = elDocument.defaultView;
      return this.allowEditorOverflow ? elWindow?.innerWidth || elDocument.documentElement.offsetWidth || elDocument.body.offsetWidth : this._contentWidth;
    }
    setPosition(primaryAnchor, secondaryAnchor, preference, affinity) {
      this._setPosition(affinity, primaryAnchor, secondaryAnchor);
      this._preference = preference;
      if (this._primaryAnchor.viewPosition && this._preference && this._preference.length > 0) {
        this.domNode.setDisplay("block");
      } else {
        this.domNode.setDisplay("none");
      }
      this._cachedDomNodeOffsetWidth = -1;
      this._cachedDomNodeOffsetHeight = -1;
    }
    _layoutBoxInViewport(anchor, width2, height, ctx) {
      const aboveLineTop = anchor.top;
      const heightAvailableAboveLine = aboveLineTop;
      const underLineTop = anchor.top + anchor.height;
      const heightAvailableUnderLine = ctx.viewportHeight - underLineTop;
      const aboveTop = aboveLineTop - height;
      const fitsAbove = heightAvailableAboveLine >= height;
      const belowTop = underLineTop;
      const fitsBelow = heightAvailableUnderLine >= height;
      let left = anchor.left;
      if (left + width2 > ctx.scrollLeft + ctx.viewportWidth) {
        left = ctx.scrollLeft + ctx.viewportWidth - width2;
      }
      if (left < ctx.scrollLeft) {
        left = ctx.scrollLeft;
      }
      return { fitsAbove, aboveTop, fitsBelow, belowTop, left };
    }
    _layoutHorizontalSegmentInPage(windowSize, domNodePosition, left, width2) {
      const LEFT_PADDING = 15;
      const RIGHT_PADDING = 15;
      const MIN_LIMIT = Math.max(LEFT_PADDING, domNodePosition.left - width2);
      const MAX_LIMIT = Math.min(domNodePosition.left + domNodePosition.width + width2, windowSize.width - RIGHT_PADDING);
      const elDocument = this._viewDomNode.domNode.ownerDocument;
      const elWindow = elDocument.defaultView;
      let absoluteLeft = domNodePosition.left + left - (elWindow?.scrollX ?? 0);
      if (absoluteLeft + width2 > MAX_LIMIT) {
        const delta = absoluteLeft - (MAX_LIMIT - width2);
        absoluteLeft -= delta;
        left -= delta;
      }
      if (absoluteLeft < MIN_LIMIT) {
        const delta = absoluteLeft - MIN_LIMIT;
        absoluteLeft -= delta;
        left -= delta;
      }
      return [left, absoluteLeft];
    }
    _layoutBoxInPage(anchor, width2, height, ctx) {
      const aboveTop = anchor.top - height;
      const belowTop = anchor.top + anchor.height;
      const domNodePosition = getDomNodePagePosition(this._viewDomNode.domNode);
      const elDocument = this._viewDomNode.domNode.ownerDocument;
      const elWindow = elDocument.defaultView;
      const absoluteAboveTop = domNodePosition.top + aboveTop - (elWindow?.scrollY ?? 0);
      const absoluteBelowTop = domNodePosition.top + belowTop - (elWindow?.scrollY ?? 0);
      const windowSize = getClientArea(elDocument.body);
      const [left, absoluteAboveLeft] = this._layoutHorizontalSegmentInPage(windowSize, domNodePosition, anchor.left - ctx.scrollLeft + this._contentLeft, width2);
      const TOP_PADDING = 22;
      const BOTTOM_PADDING = 22;
      const fitsAbove = absoluteAboveTop >= TOP_PADDING;
      const fitsBelow = absoluteBelowTop + height <= windowSize.height - BOTTOM_PADDING;
      if (this._fixedOverflowWidgets) {
        return {
          fitsAbove,
          aboveTop: Math.max(absoluteAboveTop, TOP_PADDING),
          fitsBelow,
          belowTop: absoluteBelowTop,
          left: absoluteAboveLeft
        };
      }
      return { fitsAbove, aboveTop, fitsBelow, belowTop, left };
    }
    _prepareRenderWidgetAtExactPositionOverflowing(topLeft) {
      return new Coordinate(topLeft.top, topLeft.left + this._contentLeft);
    }
    /**
     * Compute the coordinates above and below the primary and secondary anchors.
     * The content widget *must* touch the primary anchor.
     * The content widget should touch if possible the secondary anchor.
     */
    _getAnchorsCoordinates(ctx) {
      const primary = getCoordinates(this._primaryAnchor.viewPosition, this._affinity);
      const secondaryViewPosition = this._secondaryAnchor.viewPosition?.lineNumber === this._primaryAnchor.viewPosition?.lineNumber ? this._secondaryAnchor.viewPosition : null;
      const secondary = getCoordinates(secondaryViewPosition, this._affinity);
      return { primary, secondary };
      function getCoordinates(position, affinity) {
        if (!position) {
          return null;
        }
        const horizontalPosition = ctx.visibleRangeForPosition(position);
        if (!horizontalPosition) {
          return null;
        }
        const left = position.column === 1 && affinity === 3 ? 0 : horizontalPosition.left;
        const top = ctx.getVerticalOffsetForLineNumber(position.lineNumber) - ctx.scrollTop;
        const lineHeight = ctx.getLineHeightForLineNumber(position.lineNumber);
        return new AnchorCoordinate(top, left, lineHeight);
      }
    }
    _reduceAnchorCoordinates(primary, secondary, width2) {
      if (!secondary) {
        return primary;
      }
      const fontInfo = this._context.configuration.options.get(
        59
        /* EditorOption.fontInfo */
      );
      let left = secondary.left;
      if (left < primary.left) {
        left = Math.max(left, primary.left - width2 + fontInfo.typicalFullwidthCharacterWidth);
      } else {
        left = Math.min(left, primary.left + width2 - fontInfo.typicalFullwidthCharacterWidth);
      }
      return new AnchorCoordinate(primary.top, left, primary.height);
    }
    _prepareRenderWidget(ctx) {
      if (!this._preference || this._preference.length === 0) {
        return null;
      }
      const { primary, secondary } = this._getAnchorsCoordinates(ctx);
      if (!primary) {
        return {
          kind: "offViewport",
          preserveFocus: this.domNode.domNode.contains(this.domNode.domNode.ownerDocument.activeElement)
        };
      }
      if (this._cachedDomNodeOffsetWidth === -1 || this._cachedDomNodeOffsetHeight === -1) {
        let preferredDimensions = null;
        if (typeof this._actual.beforeRender === "function") {
          preferredDimensions = safeInvoke(this._actual.beforeRender, this._actual);
        }
        if (preferredDimensions) {
          this._cachedDomNodeOffsetWidth = preferredDimensions.width;
          this._cachedDomNodeOffsetHeight = preferredDimensions.height;
        } else {
          const domNode = this.domNode.domNode;
          const clientRect = domNode.getBoundingClientRect();
          this._cachedDomNodeOffsetWidth = Math.round(clientRect.width);
          this._cachedDomNodeOffsetHeight = Math.round(clientRect.height);
        }
      }
      const anchor = this._reduceAnchorCoordinates(primary, secondary, this._cachedDomNodeOffsetWidth);
      let placement;
      if (this.allowEditorOverflow) {
        placement = this._layoutBoxInPage(anchor, this._cachedDomNodeOffsetWidth, this._cachedDomNodeOffsetHeight, ctx);
      } else {
        placement = this._layoutBoxInViewport(anchor, this._cachedDomNodeOffsetWidth, this._cachedDomNodeOffsetHeight, ctx);
      }
      for (let pass = 1; pass <= 2; pass++) {
        for (const pref of this._preference) {
          if (pref === 1) {
            if (!placement) {
              return null;
            }
            if (pass === 2 || placement.fitsAbove) {
              return {
                kind: "inViewport",
                coordinate: new Coordinate(placement.aboveTop, placement.left),
                position: 1
                /* ContentWidgetPositionPreference.ABOVE */
              };
            }
          } else if (pref === 2) {
            if (!placement) {
              return null;
            }
            if (pass === 2 || placement.fitsBelow) {
              return {
                kind: "inViewport",
                coordinate: new Coordinate(placement.belowTop, placement.left),
                position: 2
                /* ContentWidgetPositionPreference.BELOW */
              };
            }
          } else {
            if (this.allowEditorOverflow) {
              return {
                kind: "inViewport",
                coordinate: this._prepareRenderWidgetAtExactPositionOverflowing(new Coordinate(anchor.top, anchor.left)),
                position: 0
                /* ContentWidgetPositionPreference.EXACT */
              };
            } else {
              return {
                kind: "inViewport",
                coordinate: new Coordinate(anchor.top, anchor.left),
                position: 0
                /* ContentWidgetPositionPreference.EXACT */
              };
            }
          }
        }
      }
      return null;
    }
    /**
     * On this first pass, we ensure that the content widget (if it is in the viewport) has the max width set correctly.
     */
    onBeforeRender(viewportData) {
      if (!this._primaryAnchor.viewPosition || !this._preference) {
        return;
      }
      if (this._primaryAnchor.viewPosition.lineNumber < viewportData.startLineNumber || this._primaryAnchor.viewPosition.lineNumber > viewportData.endLineNumber) {
        return;
      }
      this.domNode.setMaxWidth(this._maxWidth);
    }
    prepareRender(ctx) {
      this._renderData = this._prepareRenderWidget(ctx);
    }
    render(ctx) {
      if (!this._renderData || this._renderData.kind === "offViewport") {
        if (this._isVisible) {
          this.domNode.removeAttribute("monaco-visible-content-widget");
          this._isVisible = false;
          if (this._renderData?.kind === "offViewport" && this._renderData.preserveFocus) {
            this.domNode.setTop(-1e3);
          } else {
            this.domNode.setVisibility("hidden");
          }
        }
        if (typeof this._actual.afterRender === "function") {
          safeInvoke(this._actual.afterRender, this._actual, null, null);
        }
        return;
      }
      if (this.allowEditorOverflow) {
        this.domNode.setTop(this._renderData.coordinate.top);
        this.domNode.setLeft(this._renderData.coordinate.left);
      } else {
        this.domNode.setTop(this._renderData.coordinate.top + ctx.scrollTop - ctx.bigNumbersDelta);
        this.domNode.setLeft(this._renderData.coordinate.left);
      }
      if (!this._isVisible) {
        this.domNode.setVisibility("inherit");
        this.domNode.setAttribute("monaco-visible-content-widget", "true");
        this._isVisible = true;
      }
      if (typeof this._actual.afterRender === "function") {
        safeInvoke(this._actual.afterRender, this._actual, this._renderData.position, this._renderData.coordinate);
      }
    }
  }
  class PositionPair {
    constructor(modelPosition, viewPosition) {
      this.modelPosition = modelPosition;
      this.viewPosition = viewPosition;
    }
  }
  class Coordinate {
    constructor(top, left) {
      this.top = top;
      this.left = left;
      this._coordinateBrand = void 0;
    }
  }
  class AnchorCoordinate {
    constructor(top, left, height) {
      this.top = top;
      this.left = left;
      this.height = height;
      this._anchorCoordinateBrand = void 0;
    }
  }
  function safeInvoke(fn, thisArg, ...args) {
    try {
      return fn.call(thisArg, ...args);
    } catch {
      return null;
    }
  }
  class DynamicViewOverlay extends ViewEventHandler {
  }
  const IThemeService = createDecorator("themeService");
  function themeColorFromId(id) {
    return { id };
  }
  function getThemeTypeSelector(type) {
    switch (type) {
      case ColorScheme.DARK:
        return ThemeTypeSelector.VS_DARK;
      case ColorScheme.HIGH_CONTRAST_DARK:
        return ThemeTypeSelector.HC_BLACK;
      case ColorScheme.HIGH_CONTRAST_LIGHT:
        return ThemeTypeSelector.HC_LIGHT;
      default:
        return ThemeTypeSelector.VS;
    }
  }
  const Extensions$3 = {
    ThemingContribution: "base.contributions.theming"
  };
  class ThemingRegistry extends Disposable {
    constructor() {
      super();
      this.themingParticipants = [];
      this.themingParticipants = [];
      this.onThemingParticipantAddedEmitter = this._register(new Emitter$1());
    }
    onColorThemeChange(participant) {
      this.themingParticipants.push(participant);
      this.onThemingParticipantAddedEmitter.fire(participant);
      return toDisposable(() => {
        const idx = this.themingParticipants.indexOf(participant);
        this.themingParticipants.splice(idx, 1);
      });
    }
    getThemingParticipants() {
      return this.themingParticipants;
    }
  }
  const themingRegistry$1 = new ThemingRegistry();
  Registry.add(Extensions$3.ThemingContribution, themingRegistry$1);
  function registerThemingParticipant(participant) {
    return themingRegistry$1.onColorThemeChange(participant);
  }
  class Themable extends Disposable {
    constructor(themeService) {
      super();
      this.themeService = themeService;
      this.theme = themeService.getColorTheme();
      this._register(this.themeService.onDidColorThemeChange((theme) => this.onThemeChange(theme)));
    }
    onThemeChange(theme) {
      this.theme = theme;
      this.updateStyles();
    }
    updateStyles() {
    }
  }
  const editorLineHighlight = registerColor("editor.lineHighlightBackground", null, localize(610, "Background color for the highlight of line at the cursor position."));
  const editorLineHighlightBorder = registerColor("editor.lineHighlightBorder", { dark: "#282828", light: "#eeeeee", hcDark: "#f38518", hcLight: contrastBorder }, localize(611, "Background color for the border around the line at the cursor position."));
  registerColor("editor.rangeHighlightBackground", { dark: "#ffffff0b", light: "#fdff0033", hcDark: null, hcLight: null }, localize(612, "Background color of highlighted ranges, like by quick open and find features. The color must not be opaque so as not to hide underlying decorations."), true);
  registerColor("editor.rangeHighlightBorder", { dark: null, light: null, hcDark: activeContrastBorder, hcLight: activeContrastBorder }, localize(613, "Background color of the border around highlighted ranges."));
  registerColor("editor.symbolHighlightBackground", { dark: editorFindMatchHighlight, light: editorFindMatchHighlight, hcDark: null, hcLight: null }, localize(614, "Background color of highlighted symbol, like for go to definition or go next/previous symbol. The color must not be opaque so as not to hide underlying decorations."), true);
  registerColor("editor.symbolHighlightBorder", { dark: null, light: null, hcDark: activeContrastBorder, hcLight: activeContrastBorder }, localize(615, "Background color of the border around highlighted symbols."));
  const editorCursorForeground = registerColor("editorCursor.foreground", { dark: "#AEAFAD", light: Color.black, hcDark: Color.white, hcLight: "#0F4A85" }, localize(616, "Color of the editor cursor."));
  const editorCursorBackground = registerColor("editorCursor.background", null, localize(617, "The background color of the editor cursor. Allows customizing the color of a character overlapped by a block cursor."));
  const editorMultiCursorPrimaryForeground = registerColor("editorMultiCursor.primary.foreground", editorCursorForeground, localize(618, "Color of the primary editor cursor when multiple cursors are present."));
  const editorMultiCursorPrimaryBackground = registerColor("editorMultiCursor.primary.background", editorCursorBackground, localize(619, "The background color of the primary editor cursor when multiple cursors are present. Allows customizing the color of a character overlapped by a block cursor."));
  const editorMultiCursorSecondaryForeground = registerColor("editorMultiCursor.secondary.foreground", editorCursorForeground, localize(620, "Color of secondary editor cursors when multiple cursors are present."));
  const editorMultiCursorSecondaryBackground = registerColor("editorMultiCursor.secondary.background", editorCursorBackground, localize(621, "The background color of secondary editor cursors when multiple cursors are present. Allows customizing the color of a character overlapped by a block cursor."));
  const editorWhitespaces = registerColor("editorWhitespace.foreground", { dark: "#e3e4e229", light: "#33333333", hcDark: "#e3e4e229", hcLight: "#CCCCCC" }, localize(622, "Color of whitespace characters in the editor."));
  const editorLineNumbers = registerColor("editorLineNumber.foreground", { dark: "#858585", light: "#237893", hcDark: Color.white, hcLight: "#292929" }, localize(623, "Color of editor line numbers."));
  const deprecatedEditorIndentGuides = registerColor("editorIndentGuide.background", editorWhitespaces, localize(624, "Color of the editor indentation guides."), false, localize(625, "'editorIndentGuide.background' is deprecated. Use 'editorIndentGuide.background1' instead."));
  const deprecatedEditorActiveIndentGuides = registerColor("editorIndentGuide.activeBackground", editorWhitespaces, localize(626, "Color of the active editor indentation guides."), false, localize(627, "'editorIndentGuide.activeBackground' is deprecated. Use 'editorIndentGuide.activeBackground1' instead."));
  const editorIndentGuide1 = registerColor("editorIndentGuide.background1", deprecatedEditorIndentGuides, localize(628, "Color of the editor indentation guides (1)."));
  const editorIndentGuide2 = registerColor("editorIndentGuide.background2", "#00000000", localize(629, "Color of the editor indentation guides (2)."));
  const editorIndentGuide3 = registerColor("editorIndentGuide.background3", "#00000000", localize(630, "Color of the editor indentation guides (3)."));
  const editorIndentGuide4 = registerColor("editorIndentGuide.background4", "#00000000", localize(631, "Color of the editor indentation guides (4)."));
  const editorIndentGuide5 = registerColor("editorIndentGuide.background5", "#00000000", localize(632, "Color of the editor indentation guides (5)."));
  const editorIndentGuide6 = registerColor("editorIndentGuide.background6", "#00000000", localize(633, "Color of the editor indentation guides (6)."));
  const editorActiveIndentGuide1 = registerColor("editorIndentGuide.activeBackground1", deprecatedEditorActiveIndentGuides, localize(634, "Color of the active editor indentation guides (1)."));
  const editorActiveIndentGuide2 = registerColor("editorIndentGuide.activeBackground2", "#00000000", localize(635, "Color of the active editor indentation guides (2)."));
  const editorActiveIndentGuide3 = registerColor("editorIndentGuide.activeBackground3", "#00000000", localize(636, "Color of the active editor indentation guides (3)."));
  const editorActiveIndentGuide4 = registerColor("editorIndentGuide.activeBackground4", "#00000000", localize(637, "Color of the active editor indentation guides (4)."));
  const editorActiveIndentGuide5 = registerColor("editorIndentGuide.activeBackground5", "#00000000", localize(638, "Color of the active editor indentation guides (5)."));
  const editorActiveIndentGuide6 = registerColor("editorIndentGuide.activeBackground6", "#00000000", localize(639, "Color of the active editor indentation guides (6)."));
  const deprecatedEditorActiveLineNumber = registerColor("editorActiveLineNumber.foreground", { dark: "#c6c6c6", light: "#0B216F", hcDark: activeContrastBorder, hcLight: activeContrastBorder }, localize(640, "Color of editor active line number"), false, localize(641, "Id is deprecated. Use 'editorLineNumber.activeForeground' instead."));
  registerColor("editorLineNumber.activeForeground", deprecatedEditorActiveLineNumber, localize(642, "Color of editor active line number"));
  const editorDimmedLineNumber = registerColor("editorLineNumber.dimmedForeground", null, localize(643, "Color of the final editor line when editor.renderFinalNewline is set to dimmed."));
  const editorRuler = registerColor("editorRuler.foreground", { dark: "#5A5A5A", light: Color.lightgrey, hcDark: Color.white, hcLight: "#292929" }, localize(644, "Color of the editor rulers."));
  registerColor("editorCodeLens.foreground", { dark: "#999999", light: "#919191", hcDark: "#999999", hcLight: "#292929" }, localize(645, "Foreground color of editor CodeLens"));
  registerColor("editorBracketMatch.background", { dark: "#0064001a", light: "#0064001a", hcDark: "#0064001a", hcLight: "#0000" }, localize(646, "Background color behind matching brackets"));
  registerColor("editorBracketMatch.border", { dark: "#888", light: "#B9B9B9", hcDark: contrastBorder, hcLight: contrastBorder }, localize(647, "Color for matching brackets boxes"));
  const editorOverviewRulerBorder = registerColor("editorOverviewRuler.border", { dark: "#7f7f7f4d", light: "#7f7f7f4d", hcDark: "#7f7f7f4d", hcLight: "#666666" }, localize(648, "Color of the overview ruler border."));
  const editorOverviewRulerBackground = registerColor("editorOverviewRuler.background", null, localize(649, "Background color of the editor overview ruler."));
  registerColor("editorGutter.background", editorBackground, localize(650, "Background color of the editor gutter. The gutter contains the glyph margins and the line numbers."));
  registerColor("editorUnnecessaryCode.border", { dark: null, light: null, hcDark: Color.fromHex("#fff").transparent(0.8), hcLight: contrastBorder }, localize(651, "Border color of unnecessary (unused) source code in the editor."));
  const editorUnnecessaryCodeOpacity = registerColor("editorUnnecessaryCode.opacity", { dark: Color.fromHex("#000a"), light: Color.fromHex("#0007"), hcDark: null, hcLight: null }, localize(652, `Opacity of unnecessary (unused) source code in the editor. For example, "#000000c0" will render the code with 75% opacity. For high contrast themes, use the  'editorUnnecessaryCode.border' theme color to underline unnecessary code instead of fading it out.`));
  registerColor("editorGhostText.border", { dark: null, light: null, hcDark: Color.fromHex("#fff").transparent(0.8), hcLight: Color.fromHex("#292929").transparent(0.8) }, localize(653, "Border color of ghost text in the editor."));
  const ghostTextForeground = registerColor("editorGhostText.foreground", { dark: Color.fromHex("#ffffff56"), light: Color.fromHex("#0007"), hcDark: null, hcLight: null }, localize(654, "Foreground color of the ghost text in the editor."));
  registerColor("editorGhostText.background", null, localize(655, "Background color of the ghost text in the editor."));
  const rulerRangeDefault = new Color(new RGBA(0, 122, 204, 0.6));
  const overviewRulerRangeHighlight = registerColor("editorOverviewRuler.rangeHighlightForeground", rulerRangeDefault, localize(656, "Overview ruler marker color for range highlights. The color must not be opaque so as not to hide underlying decorations."), true);
  const overviewRulerError = registerColor("editorOverviewRuler.errorForeground", { dark: new Color(new RGBA(255, 18, 18, 0.7)), light: new Color(new RGBA(255, 18, 18, 0.7)), hcDark: new Color(new RGBA(255, 50, 50, 1)), hcLight: "#B5200D" }, localize(657, "Overview ruler marker color for errors."));
  const overviewRulerWarning = registerColor("editorOverviewRuler.warningForeground", { dark: editorWarningForeground, light: editorWarningForeground, hcDark: editorWarningBorder, hcLight: editorWarningBorder }, localize(658, "Overview ruler marker color for warnings."));
  const overviewRulerInfo = registerColor("editorOverviewRuler.infoForeground", { dark: editorInfoForeground, light: editorInfoForeground, hcDark: editorInfoBorder, hcLight: editorInfoBorder }, localize(659, "Overview ruler marker color for infos."));
  const editorBracketHighlightingForeground1 = registerColor("editorBracketHighlight.foreground1", { dark: "#FFD700", light: "#0431FAFF", hcDark: "#FFD700", hcLight: "#0431FAFF" }, localize(660, "Foreground color of brackets (1). Requires enabling bracket pair colorization."));
  const editorBracketHighlightingForeground2 = registerColor("editorBracketHighlight.foreground2", { dark: "#DA70D6", light: "#319331FF", hcDark: "#DA70D6", hcLight: "#319331FF" }, localize(661, "Foreground color of brackets (2). Requires enabling bracket pair colorization."));
  const editorBracketHighlightingForeground3 = registerColor("editorBracketHighlight.foreground3", { dark: "#179FFF", light: "#7B3814FF", hcDark: "#87CEFA", hcLight: "#7B3814FF" }, localize(662, "Foreground color of brackets (3). Requires enabling bracket pair colorization."));
  const editorBracketHighlightingForeground4 = registerColor("editorBracketHighlight.foreground4", "#00000000", localize(663, "Foreground color of brackets (4). Requires enabling bracket pair colorization."));
  const editorBracketHighlightingForeground5 = registerColor("editorBracketHighlight.foreground5", "#00000000", localize(664, "Foreground color of brackets (5). Requires enabling bracket pair colorization."));
  const editorBracketHighlightingForeground6 = registerColor("editorBracketHighlight.foreground6", "#00000000", localize(665, "Foreground color of brackets (6). Requires enabling bracket pair colorization."));
  const editorBracketHighlightingUnexpectedBracketForeground = registerColor("editorBracketHighlight.unexpectedBracket.foreground", { dark: new Color(new RGBA(255, 18, 18, 0.8)), light: new Color(new RGBA(255, 18, 18, 0.8)), hcDark: new Color(new RGBA(255, 50, 50, 1)), hcLight: "#B5200D" }, localize(666, "Foreground color of unexpected brackets."));
  const editorBracketPairGuideBackground1 = registerColor("editorBracketPairGuide.background1", "#00000000", localize(667, "Background color of inactive bracket pair guides (1). Requires enabling bracket pair guides."));
  const editorBracketPairGuideBackground2 = registerColor("editorBracketPairGuide.background2", "#00000000", localize(668, "Background color of inactive bracket pair guides (2). Requires enabling bracket pair guides."));
  const editorBracketPairGuideBackground3 = registerColor("editorBracketPairGuide.background3", "#00000000", localize(669, "Background color of inactive bracket pair guides (3). Requires enabling bracket pair guides."));
  const editorBracketPairGuideBackground4 = registerColor("editorBracketPairGuide.background4", "#00000000", localize(670, "Background color of inactive bracket pair guides (4). Requires enabling bracket pair guides."));
  const editorBracketPairGuideBackground5 = registerColor("editorBracketPairGuide.background5", "#00000000", localize(671, "Background color of inactive bracket pair guides (5). Requires enabling bracket pair guides."));
  const editorBracketPairGuideBackground6 = registerColor("editorBracketPairGuide.background6", "#00000000", localize(672, "Background color of inactive bracket pair guides (6). Requires enabling bracket pair guides."));
  const editorBracketPairGuideActiveBackground1 = registerColor("editorBracketPairGuide.activeBackground1", "#00000000", localize(673, "Background color of active bracket pair guides (1). Requires enabling bracket pair guides."));
  const editorBracketPairGuideActiveBackground2 = registerColor("editorBracketPairGuide.activeBackground2", "#00000000", localize(674, "Background color of active bracket pair guides (2). Requires enabling bracket pair guides."));
  const editorBracketPairGuideActiveBackground3 = registerColor("editorBracketPairGuide.activeBackground3", "#00000000", localize(675, "Background color of active bracket pair guides (3). Requires enabling bracket pair guides."));
  const editorBracketPairGuideActiveBackground4 = registerColor("editorBracketPairGuide.activeBackground4", "#00000000", localize(676, "Background color of active bracket pair guides (4). Requires enabling bracket pair guides."));
  const editorBracketPairGuideActiveBackground5 = registerColor("editorBracketPairGuide.activeBackground5", "#00000000", localize(677, "Background color of active bracket pair guides (5). Requires enabling bracket pair guides."));
  const editorBracketPairGuideActiveBackground6 = registerColor("editorBracketPairGuide.activeBackground6", "#00000000", localize(678, "Background color of active bracket pair guides (6). Requires enabling bracket pair guides."));
  registerColor("editorUnicodeHighlight.border", editorWarningForeground, localize(679, "Border color used to highlight unicode characters."));
  registerColor("editorUnicodeHighlight.background", editorWarningBackground, localize(680, "Background color used to highlight unicode characters."));
  registerThemingParticipant((theme, collector) => {
    const background = theme.getColor(editorBackground);
    const lineHighlight = theme.getColor(editorLineHighlight);
    const imeBackground = lineHighlight && !lineHighlight.isTransparent() ? lineHighlight : background;
    if (imeBackground) {
      collector.addRule(`.monaco-editor .inputarea.ime-input { background-color: ${imeBackground}; }`);
    }
  });
  class AbstractLineHighlightOverlay extends DynamicViewOverlay {
    constructor(context) {
      super();
      this._context = context;
      const options = this._context.configuration.options;
      const layoutInfo = options.get(
        165
        /* EditorOption.layoutInfo */
      );
      this._renderLineHighlight = options.get(
        110
        /* EditorOption.renderLineHighlight */
      );
      this._renderLineHighlightOnlyWhenFocus = options.get(
        111
        /* EditorOption.renderLineHighlightOnlyWhenFocus */
      );
      this._wordWrap = layoutInfo.isViewportWrapping;
      this._contentLeft = layoutInfo.contentLeft;
      this._contentWidth = layoutInfo.contentWidth;
      this._selectionIsEmpty = true;
      this._focused = false;
      this._cursorLineNumbers = [1];
      this._selections = [new Selection$1(1, 1, 1, 1)];
      this._renderData = null;
      this._context.addEventHandler(this);
    }
    dispose() {
      this._context.removeEventHandler(this);
      super.dispose();
    }
    _readFromSelections() {
      let hasChanged = false;
      const lineNumbers = /* @__PURE__ */ new Set();
      for (const selection of this._selections) {
        lineNumbers.add(selection.positionLineNumber);
      }
      const cursorsLineNumbers = Array.from(lineNumbers);
      cursorsLineNumbers.sort((a, b) => a - b);
      if (!equals$1(this._cursorLineNumbers, cursorsLineNumbers)) {
        this._cursorLineNumbers = cursorsLineNumbers;
        hasChanged = true;
      }
      const selectionIsEmpty = this._selections.every((s) => s.isEmpty());
      if (this._selectionIsEmpty !== selectionIsEmpty) {
        this._selectionIsEmpty = selectionIsEmpty;
        hasChanged = true;
      }
      return hasChanged;
    }
    // --- begin event handlers
    onThemeChanged(e) {
      return this._readFromSelections();
    }
    onConfigurationChanged(e) {
      const options = this._context.configuration.options;
      const layoutInfo = options.get(
        165
        /* EditorOption.layoutInfo */
      );
      this._renderLineHighlight = options.get(
        110
        /* EditorOption.renderLineHighlight */
      );
      this._renderLineHighlightOnlyWhenFocus = options.get(
        111
        /* EditorOption.renderLineHighlightOnlyWhenFocus */
      );
      this._wordWrap = layoutInfo.isViewportWrapping;
      this._contentLeft = layoutInfo.contentLeft;
      this._contentWidth = layoutInfo.contentWidth;
      return true;
    }
    onCursorStateChanged(e) {
      this._selections = e.selections;
      return this._readFromSelections();
    }
    onFlushed(e) {
      return true;
    }
    onLinesDeleted(e) {
      return true;
    }
    onLinesInserted(e) {
      return true;
    }
    onScrollChanged(e) {
      return e.scrollWidthChanged || e.scrollTopChanged;
    }
    onZonesChanged(e) {
      return true;
    }
    onFocusChanged(e) {
      if (!this._renderLineHighlightOnlyWhenFocus) {
        return false;
      }
      this._focused = e.isFocused;
      return true;
    }
    // --- end event handlers
    prepareRender(ctx) {
      if (!this._shouldRenderThis()) {
        this._renderData = null;
        return;
      }
      const visibleStartLineNumber = ctx.visibleRange.startLineNumber;
      const visibleEndLineNumber = ctx.visibleRange.endLineNumber;
      const renderData = [];
      for (let lineNumber = visibleStartLineNumber; lineNumber <= visibleEndLineNumber; lineNumber++) {
        const lineIndex = lineNumber - visibleStartLineNumber;
        renderData[lineIndex] = "";
      }
      if (this._wordWrap) {
        const renderedLineWrapped = this._renderOne(ctx, false);
        for (const cursorLineNumber of this._cursorLineNumbers) {
          const coordinatesConverter = this._context.viewModel.coordinatesConverter;
          const modelLineNumber = coordinatesConverter.convertViewPositionToModelPosition(new Position$1(cursorLineNumber, 1)).lineNumber;
          const firstViewLineNumber = coordinatesConverter.convertModelPositionToViewPosition(new Position$1(modelLineNumber, 1)).lineNumber;
          const lastViewLineNumber = coordinatesConverter.convertModelPositionToViewPosition(new Position$1(modelLineNumber, this._context.viewModel.model.getLineMaxColumn(modelLineNumber))).lineNumber;
          const firstLine = Math.max(firstViewLineNumber, visibleStartLineNumber);
          const lastLine = Math.min(lastViewLineNumber, visibleEndLineNumber);
          for (let lineNumber = firstLine; lineNumber <= lastLine; lineNumber++) {
            const lineIndex = lineNumber - visibleStartLineNumber;
            renderData[lineIndex] = renderedLineWrapped;
          }
        }
      }
      const renderedLineExact = this._renderOne(ctx, true);
      for (const cursorLineNumber of this._cursorLineNumbers) {
        if (cursorLineNumber < visibleStartLineNumber || cursorLineNumber > visibleEndLineNumber) {
          continue;
        }
        const lineIndex = cursorLineNumber - visibleStartLineNumber;
        renderData[lineIndex] = renderedLineExact;
      }
      this._renderData = renderData;
    }
    render(startLineNumber, lineNumber) {
      if (!this._renderData) {
        return "";
      }
      const lineIndex = lineNumber - startLineNumber;
      if (lineIndex >= this._renderData.length) {
        return "";
      }
      return this._renderData[lineIndex];
    }
    _shouldRenderInMargin() {
      return (this._renderLineHighlight === "gutter" || this._renderLineHighlight === "all") && (!this._renderLineHighlightOnlyWhenFocus || this._focused);
    }
    _shouldRenderInContent() {
      return (this._renderLineHighlight === "line" || this._renderLineHighlight === "all") && this._selectionIsEmpty && (!this._renderLineHighlightOnlyWhenFocus || this._focused);
    }
  }
  class CurrentLineHighlightOverlay extends AbstractLineHighlightOverlay {
    _renderOne(ctx, exact) {
      const className2 = "current-line" + (this._shouldRenderInMargin() ? " current-line-both" : "") + (exact ? " current-line-exact" : "");
      return `<div class="${className2}" style="width:${Math.max(ctx.scrollWidth, this._contentWidth)}px;"></div>`;
    }
    _shouldRenderThis() {
      return this._shouldRenderInContent();
    }
    _shouldRenderOther() {
      return this._shouldRenderInMargin();
    }
  }
  class CurrentLineMarginHighlightOverlay extends AbstractLineHighlightOverlay {
    _renderOne(ctx, exact) {
      const className2 = "current-line" + (this._shouldRenderInMargin() ? " current-line-margin" : "") + (this._shouldRenderOther() ? " current-line-margin-both" : "") + (this._shouldRenderInMargin() && exact ? " current-line-exact-margin" : "");
      return `<div class="${className2}" style="width:${this._contentLeft}px"></div>`;
    }
    _shouldRenderThis() {
      return true;
    }
    _shouldRenderOther() {
      return this._shouldRenderInContent();
    }
  }
  registerThemingParticipant((theme, collector) => {
    const lineHighlight = theme.getColor(editorLineHighlight);
    if (lineHighlight) {
      collector.addRule(`.monaco-editor .view-overlays .current-line { background-color: ${lineHighlight}; }`);
      collector.addRule(`.monaco-editor .margin-view-overlays .current-line-margin { background-color: ${lineHighlight}; border: none; }`);
    }
    if (!lineHighlight || lineHighlight.isTransparent() || theme.defines(editorLineHighlightBorder)) {
      const lineHighlightBorder = theme.getColor(editorLineHighlightBorder);
      if (lineHighlightBorder) {
        collector.addRule(`.monaco-editor .view-overlays .current-line-exact { border: 2px solid ${lineHighlightBorder}; }`);
        collector.addRule(`.monaco-editor .margin-view-overlays .current-line-exact-margin { border: 2px solid ${lineHighlightBorder}; }`);
        if (isHighContrast(theme.type)) {
          collector.addRule(`.monaco-editor .view-overlays .current-line-exact { border-width: 1px; }`);
          collector.addRule(`.monaco-editor .margin-view-overlays .current-line-exact-margin { border-width: 1px; }`);
        }
      }
    }
  });
  class DecorationsOverlay extends DynamicViewOverlay {
    constructor(context) {
      super();
      this._context = context;
      const options = this._context.configuration.options;
      this._typicalHalfwidthCharacterWidth = options.get(
        59
        /* EditorOption.fontInfo */
      ).typicalHalfwidthCharacterWidth;
      this._renderResult = null;
      this._context.addEventHandler(this);
    }
    dispose() {
      this._context.removeEventHandler(this);
      this._renderResult = null;
      super.dispose();
    }
    // --- begin event handlers
    onConfigurationChanged(e) {
      const options = this._context.configuration.options;
      this._typicalHalfwidthCharacterWidth = options.get(
        59
        /* EditorOption.fontInfo */
      ).typicalHalfwidthCharacterWidth;
      return true;
    }
    onDecorationsChanged(e) {
      return true;
    }
    onFlushed(e) {
      return true;
    }
    onLinesChanged(e) {
      return true;
    }
    onLinesDeleted(e) {
      return true;
    }
    onLinesInserted(e) {
      return true;
    }
    onScrollChanged(e) {
      return e.scrollTopChanged || e.scrollWidthChanged;
    }
    onZonesChanged(e) {
      return true;
    }
    // --- end event handlers
    prepareRender(ctx) {
      const _decorations = ctx.getDecorationsInViewport();
      let decorations = [];
      let decorationsLen = 0;
      for (let i2 = 0, len = _decorations.length; i2 < len; i2++) {
        const d = _decorations[i2];
        if (d.options.className) {
          decorations[decorationsLen++] = d;
        }
      }
      decorations = decorations.sort((a, b) => {
        if (a.options.zIndex < b.options.zIndex) {
          return -1;
        }
        if (a.options.zIndex > b.options.zIndex) {
          return 1;
        }
        const aClassName = a.options.className;
        const bClassName = b.options.className;
        if (aClassName < bClassName) {
          return -1;
        }
        if (aClassName > bClassName) {
          return 1;
        }
        return Range$2.compareRangesUsingStarts(a.range, b.range);
      });
      const visibleStartLineNumber = ctx.visibleRange.startLineNumber;
      const visibleEndLineNumber = ctx.visibleRange.endLineNumber;
      const output = [];
      for (let lineNumber = visibleStartLineNumber; lineNumber <= visibleEndLineNumber; lineNumber++) {
        const lineIndex = lineNumber - visibleStartLineNumber;
        output[lineIndex] = "";
      }
      this._renderWholeLineDecorations(ctx, decorations, output);
      this._renderNormalDecorations(ctx, decorations, output);
      this._renderResult = output;
    }
    _renderWholeLineDecorations(ctx, decorations, output) {
      const visibleStartLineNumber = ctx.visibleRange.startLineNumber;
      const visibleEndLineNumber = ctx.visibleRange.endLineNumber;
      for (let i2 = 0, lenI = decorations.length; i2 < lenI; i2++) {
        const d = decorations[i2];
        if (!d.options.isWholeLine) {
          continue;
        }
        const decorationOutput = '<div class="cdr ' + d.options.className + '" style="left:0;width:100%;"></div>';
        const startLineNumber = Math.max(d.range.startLineNumber, visibleStartLineNumber);
        const endLineNumber = Math.min(d.range.endLineNumber, visibleEndLineNumber);
        for (let j = startLineNumber; j <= endLineNumber; j++) {
          const lineIndex = j - visibleStartLineNumber;
          output[lineIndex] += decorationOutput;
        }
      }
    }
    _renderNormalDecorations(ctx, decorations, output) {
      const visibleStartLineNumber = ctx.visibleRange.startLineNumber;
      let prevClassName = null;
      let prevShowIfCollapsed = false;
      let prevRange = null;
      let prevShouldFillLineOnLineBreak = false;
      for (let i2 = 0, lenI = decorations.length; i2 < lenI; i2++) {
        const d = decorations[i2];
        if (d.options.isWholeLine) {
          continue;
        }
        const className2 = d.options.className;
        const showIfCollapsed = Boolean(d.options.showIfCollapsed);
        let range2 = d.range;
        if (showIfCollapsed && range2.endColumn === 1 && range2.endLineNumber !== range2.startLineNumber) {
          range2 = new Range$2(range2.startLineNumber, range2.startColumn, range2.endLineNumber - 1, this._context.viewModel.getLineMaxColumn(range2.endLineNumber - 1));
        }
        if (prevClassName === className2 && prevShowIfCollapsed === showIfCollapsed && Range$2.areIntersectingOrTouching(prevRange, range2)) {
          prevRange = Range$2.plusRange(prevRange, range2);
          continue;
        }
        if (prevClassName !== null) {
          this._renderNormalDecoration(ctx, prevRange, prevClassName, prevShouldFillLineOnLineBreak, prevShowIfCollapsed, visibleStartLineNumber, output);
        }
        prevClassName = className2;
        prevShowIfCollapsed = showIfCollapsed;
        prevRange = range2;
        prevShouldFillLineOnLineBreak = d.options.shouldFillLineOnLineBreak ?? false;
      }
      if (prevClassName !== null) {
        this._renderNormalDecoration(ctx, prevRange, prevClassName, prevShouldFillLineOnLineBreak, prevShowIfCollapsed, visibleStartLineNumber, output);
      }
    }
    _renderNormalDecoration(ctx, range2, className2, shouldFillLineOnLineBreak, showIfCollapsed, visibleStartLineNumber, output) {
      const linesVisibleRanges = ctx.linesVisibleRangesForRange(
        range2,
        /*TODO@Alex*/
        className2 === "findMatch"
      );
      if (!linesVisibleRanges) {
        return;
      }
      for (let j = 0, lenJ = linesVisibleRanges.length; j < lenJ; j++) {
        const lineVisibleRanges = linesVisibleRanges[j];
        if (lineVisibleRanges.outsideRenderedLine) {
          continue;
        }
        const lineIndex = lineVisibleRanges.lineNumber - visibleStartLineNumber;
        if (showIfCollapsed && lineVisibleRanges.ranges.length === 1) {
          const singleVisibleRange = lineVisibleRanges.ranges[0];
          if (singleVisibleRange.width < this._typicalHalfwidthCharacterWidth) {
            const center = Math.round(singleVisibleRange.left + singleVisibleRange.width / 2);
            const left = Math.max(0, Math.round(center - this._typicalHalfwidthCharacterWidth / 2));
            lineVisibleRanges.ranges[0] = new HorizontalRange(left, this._typicalHalfwidthCharacterWidth);
          }
        }
        for (let k = 0, lenK = lineVisibleRanges.ranges.length; k < lenK; k++) {
          const expandToLeft = shouldFillLineOnLineBreak && lineVisibleRanges.continuesOnNextLine && lenK === 1;
          const visibleRange = lineVisibleRanges.ranges[k];
          const decorationOutput = '<div class="cdr ' + className2 + '" style="left:' + String(visibleRange.left) + "px;width:" + (expandToLeft ? "100%;" : String(visibleRange.width) + "px;") + '"></div>';
          output[lineIndex] += decorationOutput;
        }
      }
    }
    render(startLineNumber, lineNumber) {
      if (!this._renderResult) {
        return "";
      }
      const lineIndex = lineNumber - startLineNumber;
      if (lineIndex < 0 || lineIndex >= this._renderResult.length) {
        return "";
      }
      return this._renderResult[lineIndex];
    }
  }
  class EditorScrollbar extends ViewPart {
    constructor(context, linesContent, viewDomNode, overflowGuardDomNode) {
      super(context);
      const options = this._context.configuration.options;
      const scrollbar = options.get(
        117
        /* EditorOption.scrollbar */
      );
      const mouseWheelScrollSensitivity = options.get(
        83
        /* EditorOption.mouseWheelScrollSensitivity */
      );
      const fastScrollSensitivity = options.get(
        49
        /* EditorOption.fastScrollSensitivity */
      );
      const scrollPredominantAxis = options.get(
        120
        /* EditorOption.scrollPredominantAxis */
      );
      const inertialScroll = options.get(
        158
        /* EditorOption.inertialScroll */
      );
      const scrollbarOptions = {
        listenOnDomNode: viewDomNode.domNode,
        className: "editor-scrollable " + getThemeTypeSelector(context.theme.type),
        useShadows: false,
        lazyRender: true,
        vertical: scrollbar.vertical,
        horizontal: scrollbar.horizontal,
        verticalHasArrows: scrollbar.verticalHasArrows,
        horizontalHasArrows: scrollbar.horizontalHasArrows,
        verticalScrollbarSize: scrollbar.verticalScrollbarSize,
        verticalSliderSize: scrollbar.verticalSliderSize,
        horizontalScrollbarSize: scrollbar.horizontalScrollbarSize,
        horizontalSliderSize: scrollbar.horizontalSliderSize,
        handleMouseWheel: scrollbar.handleMouseWheel,
        alwaysConsumeMouseWheel: scrollbar.alwaysConsumeMouseWheel,
        arrowSize: scrollbar.arrowSize,
        mouseWheelScrollSensitivity,
        fastScrollSensitivity,
        scrollPredominantAxis,
        scrollByPage: scrollbar.scrollByPage,
        inertialScroll
      };
      this.scrollbar = this._register(new SmoothScrollableElement(linesContent.domNode, scrollbarOptions, this._context.viewLayout.getScrollable()));
      PartFingerprints.write(
        this.scrollbar.getDomNode(),
        6
        /* PartFingerprint.ScrollableElement */
      );
      this.scrollbarDomNode = createFastDomNode(this.scrollbar.getDomNode());
      this.scrollbarDomNode.setPosition("absolute");
      this._setLayout();
      const onBrowserDesperateReveal = (domNode, lookAtScrollTop, lookAtScrollLeft) => {
        const newScrollPosition = {};
        {
          const deltaTop = domNode.scrollTop;
          if (deltaTop) {
            newScrollPosition.scrollTop = this._context.viewLayout.getCurrentScrollTop() + deltaTop;
            domNode.scrollTop = 0;
          }
        }
        if (lookAtScrollLeft) {
          const deltaLeft = domNode.scrollLeft;
          if (deltaLeft) {
            newScrollPosition.scrollLeft = this._context.viewLayout.getCurrentScrollLeft() + deltaLeft;
            domNode.scrollLeft = 0;
          }
        }
        this._context.viewModel.viewLayout.setScrollPosition(
          newScrollPosition,
          1
          /* ScrollType.Immediate */
        );
      };
      this._register(addDisposableListener(viewDomNode.domNode, "scroll", (e) => onBrowserDesperateReveal(viewDomNode.domNode, true, true)));
      this._register(addDisposableListener(linesContent.domNode, "scroll", (e) => onBrowserDesperateReveal(linesContent.domNode, true, false)));
      this._register(addDisposableListener(overflowGuardDomNode.domNode, "scroll", (e) => onBrowserDesperateReveal(overflowGuardDomNode.domNode, true, false)));
      this._register(addDisposableListener(this.scrollbarDomNode.domNode, "scroll", (e) => onBrowserDesperateReveal(this.scrollbarDomNode.domNode, true, false)));
    }
    dispose() {
      super.dispose();
    }
    _setLayout() {
      const options = this._context.configuration.options;
      const layoutInfo = options.get(
        165
        /* EditorOption.layoutInfo */
      );
      this.scrollbarDomNode.setLeft(layoutInfo.contentLeft);
      const minimap = options.get(
        81
        /* EditorOption.minimap */
      );
      const side = minimap.side;
      if (side === "right") {
        this.scrollbarDomNode.setWidth(layoutInfo.contentWidth + layoutInfo.minimap.minimapWidth);
      } else {
        this.scrollbarDomNode.setWidth(layoutInfo.contentWidth);
      }
      this.scrollbarDomNode.setHeight(layoutInfo.height);
    }
    getOverviewRulerLayoutInfo() {
      return this.scrollbar.getOverviewRulerLayoutInfo();
    }
    getDomNode() {
      return this.scrollbarDomNode;
    }
    delegateVerticalScrollbarPointerDown(browserEvent) {
      this.scrollbar.delegateVerticalScrollbarPointerDown(browserEvent);
    }
    delegateScrollFromMouseWheelEvent(browserEvent) {
      this.scrollbar.delegateScrollFromMouseWheelEvent(browserEvent);
    }
    // --- begin event handlers
    onConfigurationChanged(e) {
      if (e.hasChanged(
        117
        /* EditorOption.scrollbar */
      ) || e.hasChanged(
        83
        /* EditorOption.mouseWheelScrollSensitivity */
      ) || e.hasChanged(
        49
        /* EditorOption.fastScrollSensitivity */
      )) {
        const options = this._context.configuration.options;
        const scrollbar = options.get(
          117
          /* EditorOption.scrollbar */
        );
        const mouseWheelScrollSensitivity = options.get(
          83
          /* EditorOption.mouseWheelScrollSensitivity */
        );
        const fastScrollSensitivity = options.get(
          49
          /* EditorOption.fastScrollSensitivity */
        );
        const scrollPredominantAxis = options.get(
          120
          /* EditorOption.scrollPredominantAxis */
        );
        const newOpts = {
          vertical: scrollbar.vertical,
          horizontal: scrollbar.horizontal,
          verticalScrollbarSize: scrollbar.verticalScrollbarSize,
          horizontalScrollbarSize: scrollbar.horizontalScrollbarSize,
          scrollByPage: scrollbar.scrollByPage,
          handleMouseWheel: scrollbar.handleMouseWheel,
          mouseWheelScrollSensitivity,
          fastScrollSensitivity,
          scrollPredominantAxis
        };
        this.scrollbar.updateOptions(newOpts);
      }
      if (e.hasChanged(
        165
        /* EditorOption.layoutInfo */
      )) {
        this._setLayout();
      }
      return true;
    }
    onScrollChanged(e) {
      return true;
    }
    onThemeChanged(e) {
      this.scrollbar.updateClassName("editor-scrollable " + getThemeTypeSelector(this._context.theme.type));
      return true;
    }
    // --- end event handlers
    prepareRender(ctx) {
    }
    render(ctx) {
      this.scrollbar.renderNow();
    }
  }
  class DecorationToRender {
    constructor(startLineNumber, endLineNumber, className2, tooltip, zIndex) {
      this.startLineNumber = startLineNumber;
      this.endLineNumber = endLineNumber;
      this.className = className2;
      this.tooltip = tooltip;
      this._decorationToRenderBrand = void 0;
      this.zIndex = zIndex ?? 0;
    }
  }
  class LineDecorationToRender {
    constructor(className2, zIndex, tooltip) {
      this.className = className2;
      this.zIndex = zIndex;
      this.tooltip = tooltip;
    }
  }
  class VisibleLineDecorationsToRender {
    constructor() {
      this.decorations = [];
    }
    add(decoration2) {
      this.decorations.push(decoration2);
    }
    getDecorations() {
      return this.decorations;
    }
  }
  class DedupOverlay extends DynamicViewOverlay {
    /**
     * Returns an array with an element for each visible line number.
     */
    _render(visibleStartLineNumber, visibleEndLineNumber, decorations) {
      const output = [];
      for (let lineNumber = visibleStartLineNumber; lineNumber <= visibleEndLineNumber; lineNumber++) {
        const lineIndex = lineNumber - visibleStartLineNumber;
        output[lineIndex] = new VisibleLineDecorationsToRender();
      }
      if (decorations.length === 0) {
        return output;
      }
      decorations.sort((a, b) => {
        if (a.className === b.className) {
          if (a.startLineNumber === b.startLineNumber) {
            return a.endLineNumber - b.endLineNumber;
          }
          return a.startLineNumber - b.startLineNumber;
        }
        return a.className < b.className ? -1 : 1;
      });
      let prevClassName = null;
      let prevEndLineIndex = 0;
      for (let i2 = 0, len = decorations.length; i2 < len; i2++) {
        const d = decorations[i2];
        const className2 = d.className;
        const zIndex = d.zIndex;
        let startLineIndex = Math.max(d.startLineNumber, visibleStartLineNumber) - visibleStartLineNumber;
        const endLineIndex = Math.min(d.endLineNumber, visibleEndLineNumber) - visibleStartLineNumber;
        if (prevClassName === className2) {
          startLineIndex = Math.max(prevEndLineIndex + 1, startLineIndex);
          prevEndLineIndex = Math.max(prevEndLineIndex, endLineIndex);
        } else {
          prevClassName = className2;
          prevEndLineIndex = endLineIndex;
        }
        for (let i3 = startLineIndex; i3 <= prevEndLineIndex; i3++) {
          output[i3].add(new LineDecorationToRender(className2, zIndex, d.tooltip));
        }
      }
      return output;
    }
  }
  class GlyphMarginWidgets extends ViewPart {
    constructor(context) {
      super(context);
      this._widgets = {};
      this._context = context;
      const options = this._context.configuration.options;
      const layoutInfo = options.get(
        165
        /* EditorOption.layoutInfo */
      );
      this.domNode = createFastDomNode(document.createElement("div"));
      this.domNode.setClassName("glyph-margin-widgets");
      this.domNode.setPosition("absolute");
      this.domNode.setTop(0);
      this._lineHeight = options.get(
        75
        /* EditorOption.lineHeight */
      );
      this._glyphMargin = options.get(
        66
        /* EditorOption.glyphMargin */
      );
      this._glyphMarginLeft = layoutInfo.glyphMarginLeft;
      this._glyphMarginWidth = layoutInfo.glyphMarginWidth;
      this._glyphMarginDecorationLaneCount = layoutInfo.glyphMarginDecorationLaneCount;
      this._managedDomNodes = [];
      this._decorationGlyphsToRender = [];
    }
    dispose() {
      this._managedDomNodes = [];
      this._decorationGlyphsToRender = [];
      this._widgets = {};
      super.dispose();
    }
    getWidgets() {
      return Object.values(this._widgets);
    }
    // --- begin event handlers
    onConfigurationChanged(e) {
      const options = this._context.configuration.options;
      const layoutInfo = options.get(
        165
        /* EditorOption.layoutInfo */
      );
      this._lineHeight = options.get(
        75
        /* EditorOption.lineHeight */
      );
      this._glyphMargin = options.get(
        66
        /* EditorOption.glyphMargin */
      );
      this._glyphMarginLeft = layoutInfo.glyphMarginLeft;
      this._glyphMarginWidth = layoutInfo.glyphMarginWidth;
      this._glyphMarginDecorationLaneCount = layoutInfo.glyphMarginDecorationLaneCount;
      return true;
    }
    onDecorationsChanged(e) {
      return true;
    }
    onFlushed(e) {
      return true;
    }
    onLinesChanged(e) {
      return true;
    }
    onLinesDeleted(e) {
      return true;
    }
    onLinesInserted(e) {
      return true;
    }
    onScrollChanged(e) {
      return e.scrollTopChanged;
    }
    onZonesChanged(e) {
      return true;
    }
    // --- end event handlers
    // --- begin widget management
    addWidget(widget) {
      const domNode = createFastDomNode(widget.getDomNode());
      this._widgets[widget.getId()] = {
        widget,
        preference: widget.getPosition(),
        domNode,
        renderInfo: null
      };
      domNode.setPosition("absolute");
      domNode.setDisplay("none");
      domNode.setAttribute("widgetId", widget.getId());
      this.domNode.appendChild(domNode);
      this.setShouldRender();
    }
    setWidgetPosition(widget, preference) {
      const myWidget = this._widgets[widget.getId()];
      if (myWidget.preference.lane === preference.lane && myWidget.preference.zIndex === preference.zIndex && Range$2.equalsRange(myWidget.preference.range, preference.range)) {
        return false;
      }
      myWidget.preference = preference;
      this.setShouldRender();
      return true;
    }
    removeWidget(widget) {
      const widgetId = widget.getId();
      if (this._widgets[widgetId]) {
        const widgetData = this._widgets[widgetId];
        const domNode = widgetData.domNode.domNode;
        delete this._widgets[widgetId];
        domNode.remove();
        this.setShouldRender();
      }
    }
    // --- end widget management
    _collectDecorationBasedGlyphRenderRequest(ctx, requests) {
      const visibleStartLineNumber = ctx.visibleRange.startLineNumber;
      const visibleEndLineNumber = ctx.visibleRange.endLineNumber;
      const decorations = ctx.getDecorationsInViewport();
      for (const d of decorations) {
        const glyphMarginClassName = d.options.glyphMarginClassName;
        if (!glyphMarginClassName) {
          continue;
        }
        const startLineNumber = Math.max(d.range.startLineNumber, visibleStartLineNumber);
        const endLineNumber = Math.min(d.range.endLineNumber, visibleEndLineNumber);
        const lane = d.options.glyphMargin?.position ?? GlyphMarginLane$1.Center;
        const zIndex = d.options.zIndex ?? 0;
        for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
          const modelPosition = this._context.viewModel.coordinatesConverter.convertViewPositionToModelPosition(new Position$1(lineNumber, 0));
          const laneIndex = this._context.viewModel.glyphLanes.getLanesAtLine(modelPosition.lineNumber).indexOf(lane);
          requests.push(new DecorationBasedGlyphRenderRequest(lineNumber, laneIndex, zIndex, glyphMarginClassName));
        }
      }
    }
    _collectWidgetBasedGlyphRenderRequest(ctx, requests) {
      const visibleStartLineNumber = ctx.visibleRange.startLineNumber;
      const visibleEndLineNumber = ctx.visibleRange.endLineNumber;
      for (const widget of Object.values(this._widgets)) {
        const range2 = widget.preference.range;
        const { startLineNumber, endLineNumber } = this._context.viewModel.coordinatesConverter.convertModelRangeToViewRange(Range$2.lift(range2));
        if (!startLineNumber || !endLineNumber || endLineNumber < visibleStartLineNumber || startLineNumber > visibleEndLineNumber) {
          continue;
        }
        const widgetLineNumber = Math.max(startLineNumber, visibleStartLineNumber);
        const modelPosition = this._context.viewModel.coordinatesConverter.convertViewPositionToModelPosition(new Position$1(widgetLineNumber, 0));
        const laneIndex = this._context.viewModel.glyphLanes.getLanesAtLine(modelPosition.lineNumber).indexOf(widget.preference.lane);
        requests.push(new WidgetBasedGlyphRenderRequest(widgetLineNumber, laneIndex, widget.preference.zIndex, widget));
      }
    }
    _collectSortedGlyphRenderRequests(ctx) {
      const requests = [];
      this._collectDecorationBasedGlyphRenderRequest(ctx, requests);
      this._collectWidgetBasedGlyphRenderRequest(ctx, requests);
      requests.sort((a, b) => {
        if (a.lineNumber === b.lineNumber) {
          if (a.laneIndex === b.laneIndex) {
            if (a.zIndex === b.zIndex) {
              if (b.type === a.type) {
                if (a.type === 0 && b.type === 0) {
                  return a.className < b.className ? -1 : 1;
                }
                return 0;
              }
              return b.type - a.type;
            }
            return b.zIndex - a.zIndex;
          }
          return a.laneIndex - b.laneIndex;
        }
        return a.lineNumber - b.lineNumber;
      });
      return requests;
    }
    /**
     * Will store render information in each widget's renderInfo and in `_decorationGlyphsToRender`.
     */
    prepareRender(ctx) {
      if (!this._glyphMargin) {
        this._decorationGlyphsToRender = [];
        return;
      }
      for (const widget of Object.values(this._widgets)) {
        widget.renderInfo = null;
      }
      const requests = new ArrayQueue(this._collectSortedGlyphRenderRequests(ctx));
      const decorationGlyphsToRender = [];
      while (requests.length > 0) {
        const first2 = requests.peek();
        if (!first2) {
          break;
        }
        const requestsAtLocation = requests.takeWhile((el) => el.lineNumber === first2.lineNumber && el.laneIndex === first2.laneIndex);
        if (!requestsAtLocation || requestsAtLocation.length === 0) {
          break;
        }
        const winner = requestsAtLocation[0];
        if (winner.type === 0) {
          const classNames2 = [];
          for (const request of requestsAtLocation) {
            if (request.zIndex !== winner.zIndex || request.type !== winner.type) {
              break;
            }
            if (classNames2.length === 0 || classNames2[classNames2.length - 1] !== request.className) {
              classNames2.push(request.className);
            }
          }
          decorationGlyphsToRender.push(winner.accept(classNames2.join(" ")));
        } else {
          winner.widget.renderInfo = {
            lineNumber: winner.lineNumber,
            laneIndex: winner.laneIndex
          };
        }
      }
      this._decorationGlyphsToRender = decorationGlyphsToRender;
    }
    render(ctx) {
      if (!this._glyphMargin) {
        for (const widget of Object.values(this._widgets)) {
          widget.domNode.setDisplay("none");
        }
        while (this._managedDomNodes.length > 0) {
          const domNode = this._managedDomNodes.pop();
          domNode?.domNode.remove();
        }
        return;
      }
      const width2 = Math.round(this._glyphMarginWidth / this._glyphMarginDecorationLaneCount);
      for (const widget of Object.values(this._widgets)) {
        if (!widget.renderInfo) {
          widget.domNode.setDisplay("none");
        } else {
          const top = ctx.viewportData.relativeVerticalOffset[widget.renderInfo.lineNumber - ctx.viewportData.startLineNumber];
          const left = this._glyphMarginLeft + widget.renderInfo.laneIndex * this._lineHeight;
          widget.domNode.setDisplay("block");
          widget.domNode.setTop(top);
          widget.domNode.setLeft(left);
          widget.domNode.setWidth(width2);
          widget.domNode.setHeight(this._lineHeight);
        }
      }
      for (let i2 = 0; i2 < this._decorationGlyphsToRender.length; i2++) {
        const dec = this._decorationGlyphsToRender[i2];
        const decLineNumber = dec.lineNumber;
        const top = ctx.viewportData.relativeVerticalOffset[decLineNumber - ctx.viewportData.startLineNumber];
        const left = this._glyphMarginLeft + dec.laneIndex * this._lineHeight;
        let domNode;
        if (i2 < this._managedDomNodes.length) {
          domNode = this._managedDomNodes[i2];
        } else {
          domNode = createFastDomNode(document.createElement("div"));
          this._managedDomNodes.push(domNode);
          this.domNode.appendChild(domNode);
        }
        const lineHeight = this._context.viewLayout.getLineHeightForLineNumber(decLineNumber);
        domNode.setClassName(`cgmr codicon ` + dec.combinedClassName);
        domNode.setPosition(`absolute`);
        domNode.setTop(top);
        domNode.setLeft(left);
        domNode.setWidth(width2);
        domNode.setHeight(lineHeight);
      }
      while (this._managedDomNodes.length > this._decorationGlyphsToRender.length) {
        const domNode = this._managedDomNodes.pop();
        domNode?.domNode.remove();
      }
    }
  }
  class DecorationBasedGlyphRenderRequest {
    constructor(lineNumber, laneIndex, zIndex, className2) {
      this.lineNumber = lineNumber;
      this.laneIndex = laneIndex;
      this.zIndex = zIndex;
      this.className = className2;
      this.type = 0;
    }
    accept(combinedClassName) {
      return new DecorationBasedGlyph(this.lineNumber, this.laneIndex, combinedClassName);
    }
  }
  class WidgetBasedGlyphRenderRequest {
    constructor(lineNumber, laneIndex, zIndex, widget) {
      this.lineNumber = lineNumber;
      this.laneIndex = laneIndex;
      this.zIndex = zIndex;
      this.widget = widget;
      this.type = 1;
    }
  }
  class DecorationBasedGlyph {
    constructor(lineNumber, laneIndex, combinedClassName) {
      this.lineNumber = lineNumber;
      this.laneIndex = laneIndex;
      this.combinedClassName = combinedClassName;
    }
  }
  function findLast(array2, predicate, fromIndex = array2.length - 1) {
    const idx = findLastIdx(array2, predicate, fromIndex);
    if (idx === -1) {
      return void 0;
    }
    return array2[idx];
  }
  function findLastIdx(array2, predicate, fromIndex = array2.length - 1) {
    for (let i2 = fromIndex; i2 >= 0; i2--) {
      const element = array2[i2];
      if (predicate(element, i2)) {
        return i2;
      }
    }
    return -1;
  }
  function findLastMonotonous(array2, predicate) {
    const idx = findLastIdxMonotonous(array2, predicate);
    return idx === -1 ? void 0 : array2[idx];
  }
  function findLastIdxMonotonous(array2, predicate, startIdx = 0, endIdxEx = array2.length) {
    let i2 = startIdx;
    let j = endIdxEx;
    while (i2 < j) {
      const k = Math.floor((i2 + j) / 2);
      if (predicate(array2[k])) {
        i2 = k + 1;
      } else {
        j = k;
      }
    }
    return i2 - 1;
  }
  function findFirstMonotonous(array2, predicate) {
    const idx = findFirstIdxMonotonousOrArrLen(array2, predicate);
    return idx === array2.length ? void 0 : array2[idx];
  }
  function findFirstIdxMonotonousOrArrLen(array2, predicate, startIdx = 0, endIdxEx = array2.length) {
    let i2 = startIdx;
    let j = endIdxEx;
    while (i2 < j) {
      const k = Math.floor((i2 + j) / 2);
      if (predicate(array2[k])) {
        j = k;
      } else {
        i2 = k + 1;
      }
    }
    return i2;
  }
  const _MonotonousArray = class _MonotonousArray {
    constructor(_array) {
      this._array = _array;
      this._findLastMonotonousLastIdx = 0;
    }
    /**
     * The predicate must be monotonous, i.e. `arr.map(predicate)` must be like `[true, ..., true, false, ..., false]`!
     * For subsequent calls, current predicate must be weaker than (or equal to) the previous predicate, i.e. more entries must be `true`.
     */
    findLastMonotonous(predicate) {
      if (_MonotonousArray.assertInvariants) {
        if (this._prevFindLastPredicate) {
          for (const item of this._array) {
            if (this._prevFindLastPredicate(item) && !predicate(item)) {
              throw new Error("MonotonousArray: current predicate must be weaker than (or equal to) the previous predicate.");
            }
          }
        }
        this._prevFindLastPredicate = predicate;
      }
      const idx = findLastIdxMonotonous(this._array, predicate, this._findLastMonotonousLastIdx);
      this._findLastMonotonousLastIdx = idx + 1;
      return idx === -1 ? void 0 : this._array[idx];
    }
  };
  _MonotonousArray.assertInvariants = false;
  let MonotonousArray = _MonotonousArray;
  function findFirstMax(array2, comparator) {
    if (array2.length === 0) {
      return void 0;
    }
    let max = array2[0];
    for (let i2 = 1; i2 < array2.length; i2++) {
      const item = array2[i2];
      if (comparator(item, max) > 0) {
        max = item;
      }
    }
    return max;
  }
  function findLastMax(array2, comparator) {
    if (array2.length === 0) {
      return void 0;
    }
    let max = array2[0];
    for (let i2 = 1; i2 < array2.length; i2++) {
      const item = array2[i2];
      if (comparator(item, max) >= 0) {
        max = item;
      }
    }
    return max;
  }
  function findFirstMin(array2, comparator) {
    return findFirstMax(array2, (a, b) => -comparator(a, b));
  }
  function findMaxIdx(array2, comparator) {
    if (array2.length === 0) {
      return -1;
    }
    let maxIdx = 0;
    for (let i2 = 1; i2 < array2.length; i2++) {
      const item = array2[i2];
      if (comparator(item, array2[maxIdx]) > 0) {
        maxIdx = i2;
      }
    }
    return maxIdx;
  }
  function mapFindFirst(items, mapFn) {
    for (const value of items) {
      const mapped = mapFn(value);
      if (mapped !== void 0) {
        return mapped;
      }
    }
    return void 0;
  }
  class TextModelPart extends Disposable {
    constructor() {
      super(...arguments);
      this._isDisposed = false;
    }
    dispose() {
      super.dispose();
      this._isDisposed = true;
    }
    assertNotDisposed() {
      if (this._isDisposed) {
        throw new Error("TextModelPart is disposed!");
      }
    }
  }
  function computeIndentLevel(line, tabSize) {
    let indent = 0;
    let i2 = 0;
    const len = line.length;
    while (i2 < len) {
      const chCode = line.charCodeAt(i2);
      if (chCode === 32) {
        indent++;
      } else if (chCode === 9) {
        indent = indent - indent % tabSize + tabSize;
      } else {
        break;
      }
      i2++;
    }
    if (i2 === len) {
      return -1;
    }
    return indent;
  }
  var HorizontalGuidesState;
  (function(HorizontalGuidesState2) {
    HorizontalGuidesState2[HorizontalGuidesState2["Disabled"] = 0] = "Disabled";
    HorizontalGuidesState2[HorizontalGuidesState2["EnabledForActive"] = 1] = "EnabledForActive";
    HorizontalGuidesState2[HorizontalGuidesState2["Enabled"] = 2] = "Enabled";
  })(HorizontalGuidesState || (HorizontalGuidesState = {}));
  class IndentGuide {
    constructor(visibleColumn, column, className2, horizontalLine, forWrappedLinesAfterColumn, forWrappedLinesBeforeOrAtColumn) {
      this.visibleColumn = visibleColumn;
      this.column = column;
      this.className = className2;
      this.horizontalLine = horizontalLine;
      this.forWrappedLinesAfterColumn = forWrappedLinesAfterColumn;
      this.forWrappedLinesBeforeOrAtColumn = forWrappedLinesBeforeOrAtColumn;
      if (visibleColumn !== -1 === (column !== -1)) {
        throw new Error();
      }
    }
  }
  class IndentGuideHorizontalLine {
    constructor(top, endColumn) {
      this.top = top;
      this.endColumn = endColumn;
    }
  }
  class GuidesTextModelPart extends TextModelPart {
    constructor(textModel, languageConfigurationService) {
      super();
      this.textModel = textModel;
      this.languageConfigurationService = languageConfigurationService;
    }
    getLanguageConfiguration(languageId) {
      return this.languageConfigurationService.getLanguageConfiguration(languageId);
    }
    _computeIndentLevel(lineIndex) {
      return computeIndentLevel(this.textModel.getLineContent(lineIndex + 1), this.textModel.getOptions().tabSize);
    }
    getActiveIndentGuide(lineNumber, minLineNumber, maxLineNumber) {
      this.assertNotDisposed();
      const lineCount = this.textModel.getLineCount();
      if (lineNumber < 1 || lineNumber > lineCount) {
        throw new BugIndicatingError("Illegal value for lineNumber");
      }
      const foldingRules = this.getLanguageConfiguration(this.textModel.getLanguageId()).foldingRules;
      const offSide = Boolean(foldingRules && foldingRules.offSide);
      let up_aboveContentLineIndex = -2;
      let up_aboveContentLineIndent = -1;
      let up_belowContentLineIndex = -2;
      let up_belowContentLineIndent = -1;
      const up_resolveIndents = (lineNumber2) => {
        if (up_aboveContentLineIndex !== -1 && (up_aboveContentLineIndex === -2 || up_aboveContentLineIndex > lineNumber2 - 1)) {
          up_aboveContentLineIndex = -1;
          up_aboveContentLineIndent = -1;
          for (let lineIndex = lineNumber2 - 2; lineIndex >= 0; lineIndex--) {
            const indent2 = this._computeIndentLevel(lineIndex);
            if (indent2 >= 0) {
              up_aboveContentLineIndex = lineIndex;
              up_aboveContentLineIndent = indent2;
              break;
            }
          }
        }
        if (up_belowContentLineIndex === -2) {
          up_belowContentLineIndex = -1;
          up_belowContentLineIndent = -1;
          for (let lineIndex = lineNumber2; lineIndex < lineCount; lineIndex++) {
            const indent2 = this._computeIndentLevel(lineIndex);
            if (indent2 >= 0) {
              up_belowContentLineIndex = lineIndex;
              up_belowContentLineIndent = indent2;
              break;
            }
          }
        }
      };
      let down_aboveContentLineIndex = -2;
      let down_aboveContentLineIndent = -1;
      let down_belowContentLineIndex = -2;
      let down_belowContentLineIndent = -1;
      const down_resolveIndents = (lineNumber2) => {
        if (down_aboveContentLineIndex === -2) {
          down_aboveContentLineIndex = -1;
          down_aboveContentLineIndent = -1;
          for (let lineIndex = lineNumber2 - 2; lineIndex >= 0; lineIndex--) {
            const indent2 = this._computeIndentLevel(lineIndex);
            if (indent2 >= 0) {
              down_aboveContentLineIndex = lineIndex;
              down_aboveContentLineIndent = indent2;
              break;
            }
          }
        }
        if (down_belowContentLineIndex !== -1 && (down_belowContentLineIndex === -2 || down_belowContentLineIndex < lineNumber2 - 1)) {
          down_belowContentLineIndex = -1;
          down_belowContentLineIndent = -1;
          for (let lineIndex = lineNumber2; lineIndex < lineCount; lineIndex++) {
            const indent2 = this._computeIndentLevel(lineIndex);
            if (indent2 >= 0) {
              down_belowContentLineIndex = lineIndex;
              down_belowContentLineIndent = indent2;
              break;
            }
          }
        }
      };
      let startLineNumber = 0;
      let goUp = true;
      let endLineNumber = 0;
      let goDown = true;
      let indent = 0;
      let initialIndent = 0;
      for (let distance = 0; goUp || goDown; distance++) {
        const upLineNumber = lineNumber - distance;
        const downLineNumber = lineNumber + distance;
        if (distance > 1 && (upLineNumber < 1 || upLineNumber < minLineNumber)) {
          goUp = false;
        }
        if (distance > 1 && (downLineNumber > lineCount || downLineNumber > maxLineNumber)) {
          goDown = false;
        }
        if (distance > 5e4) {
          goUp = false;
          goDown = false;
        }
        let upLineIndentLevel = -1;
        if (goUp && upLineNumber >= 1) {
          const currentIndent = this._computeIndentLevel(upLineNumber - 1);
          if (currentIndent >= 0) {
            up_belowContentLineIndex = upLineNumber - 1;
            up_belowContentLineIndent = currentIndent;
            upLineIndentLevel = Math.ceil(currentIndent / this.textModel.getOptions().indentSize);
          } else {
            up_resolveIndents(upLineNumber);
            upLineIndentLevel = this._getIndentLevelForWhitespaceLine(offSide, up_aboveContentLineIndent, up_belowContentLineIndent);
          }
        }
        let downLineIndentLevel = -1;
        if (goDown && downLineNumber <= lineCount) {
          const currentIndent = this._computeIndentLevel(downLineNumber - 1);
          if (currentIndent >= 0) {
            down_aboveContentLineIndex = downLineNumber - 1;
            down_aboveContentLineIndent = currentIndent;
            downLineIndentLevel = Math.ceil(currentIndent / this.textModel.getOptions().indentSize);
          } else {
            down_resolveIndents(downLineNumber);
            downLineIndentLevel = this._getIndentLevelForWhitespaceLine(offSide, down_aboveContentLineIndent, down_belowContentLineIndent);
          }
        }
        if (distance === 0) {
          initialIndent = upLineIndentLevel;
          continue;
        }
        if (distance === 1) {
          if (downLineNumber <= lineCount && downLineIndentLevel >= 0 && initialIndent + 1 === downLineIndentLevel) {
            goUp = false;
            startLineNumber = downLineNumber;
            endLineNumber = downLineNumber;
            indent = downLineIndentLevel;
            continue;
          }
          if (upLineNumber >= 1 && upLineIndentLevel >= 0 && upLineIndentLevel - 1 === initialIndent) {
            goDown = false;
            startLineNumber = upLineNumber;
            endLineNumber = upLineNumber;
            indent = upLineIndentLevel;
            continue;
          }
          startLineNumber = lineNumber;
          endLineNumber = lineNumber;
          indent = initialIndent;
          if (indent === 0) {
            return { startLineNumber, endLineNumber, indent };
          }
        }
        if (goUp) {
          if (upLineIndentLevel >= indent) {
            startLineNumber = upLineNumber;
          } else {
            goUp = false;
          }
        }
        if (goDown) {
          if (downLineIndentLevel >= indent) {
            endLineNumber = downLineNumber;
          } else {
            goDown = false;
          }
        }
      }
      return { startLineNumber, endLineNumber, indent };
    }
    getLinesBracketGuides(startLineNumber, endLineNumber, activePosition, options) {
      const result = [];
      for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
        result.push([]);
      }
      const includeSingleLinePairs = true;
      const bracketPairs = this.textModel.bracketPairs.getBracketPairsInRangeWithMinIndentation(new Range$2(startLineNumber, 1, endLineNumber, this.textModel.getLineMaxColumn(endLineNumber))).toArray();
      let activeBracketPairRange = void 0;
      if (activePosition && bracketPairs.length > 0) {
        const bracketsContainingActivePosition = (startLineNumber <= activePosition.lineNumber && activePosition.lineNumber <= endLineNumber ? bracketPairs : this.textModel.bracketPairs.getBracketPairsInRange(Range$2.fromPositions(activePosition)).toArray()).filter((bp) => Range$2.strictContainsPosition(bp.range, activePosition));
        activeBracketPairRange = findLast(bracketsContainingActivePosition, (i2) => includeSingleLinePairs)?.range;
      }
      const independentColorPoolPerBracketType = this.textModel.getOptions().bracketPairColorizationOptions.independentColorPoolPerBracketType;
      const colorProvider = new BracketPairGuidesClassNames();
      for (const pair of bracketPairs) {
        if (!pair.closingBracketRange) {
          continue;
        }
        const isActive = activeBracketPairRange && pair.range.equalsRange(activeBracketPairRange);
        if (!isActive && !options.includeInactive) {
          continue;
        }
        const className2 = colorProvider.getInlineClassName(pair.nestingLevel, pair.nestingLevelOfEqualBracketType, independentColorPoolPerBracketType) + (options.highlightActive && isActive ? " " + colorProvider.activeClassName : "");
        const start = pair.openingBracketRange.getStartPosition();
        const end = pair.closingBracketRange.getStartPosition();
        const horizontalGuides = options.horizontalGuides === HorizontalGuidesState.Enabled || options.horizontalGuides === HorizontalGuidesState.EnabledForActive && isActive;
        if (pair.range.startLineNumber === pair.range.endLineNumber) {
          if (horizontalGuides) {
            result[pair.range.startLineNumber - startLineNumber].push(new IndentGuide(-1, pair.openingBracketRange.getEndPosition().column, className2, new IndentGuideHorizontalLine(false, end.column), -1, -1));
          }
          continue;
        }
        const endVisibleColumn = this.getVisibleColumnFromPosition(end);
        const startVisibleColumn = this.getVisibleColumnFromPosition(pair.openingBracketRange.getStartPosition());
        const guideVisibleColumn = Math.min(startVisibleColumn, endVisibleColumn, pair.minVisibleColumnIndentation + 1);
        let renderHorizontalEndLineAtTheBottom = false;
        const firstNonWsIndex = firstNonWhitespaceIndex(this.textModel.getLineContent(pair.closingBracketRange.startLineNumber));
        const hasTextBeforeClosingBracket = firstNonWsIndex < pair.closingBracketRange.startColumn - 1;
        if (hasTextBeforeClosingBracket) {
          renderHorizontalEndLineAtTheBottom = true;
        }
        const visibleGuideStartLineNumber = Math.max(start.lineNumber, startLineNumber);
        const visibleGuideEndLineNumber = Math.min(end.lineNumber, endLineNumber);
        const offset = renderHorizontalEndLineAtTheBottom ? 1 : 0;
        for (let l = visibleGuideStartLineNumber; l < visibleGuideEndLineNumber + offset; l++) {
          result[l - startLineNumber].push(new IndentGuide(guideVisibleColumn, -1, className2, null, l === start.lineNumber ? start.column : -1, l === end.lineNumber ? end.column : -1));
        }
        if (horizontalGuides) {
          if (start.lineNumber >= startLineNumber && startVisibleColumn > guideVisibleColumn) {
            result[start.lineNumber - startLineNumber].push(new IndentGuide(guideVisibleColumn, -1, className2, new IndentGuideHorizontalLine(false, start.column), -1, -1));
          }
          if (end.lineNumber <= endLineNumber && endVisibleColumn > guideVisibleColumn) {
            result[end.lineNumber - startLineNumber].push(new IndentGuide(guideVisibleColumn, -1, className2, new IndentGuideHorizontalLine(!renderHorizontalEndLineAtTheBottom, end.column), -1, -1));
          }
        }
      }
      for (const guides of result) {
        guides.sort((a, b) => a.visibleColumn - b.visibleColumn);
      }
      return result;
    }
    getVisibleColumnFromPosition(position) {
      return CursorColumns.visibleColumnFromColumn(this.textModel.getLineContent(position.lineNumber), position.column, this.textModel.getOptions().tabSize) + 1;
    }
    getLinesIndentGuides(startLineNumber, endLineNumber) {
      this.assertNotDisposed();
      const lineCount = this.textModel.getLineCount();
      if (startLineNumber < 1 || startLineNumber > lineCount) {
        throw new Error("Illegal value for startLineNumber");
      }
      if (endLineNumber < 1 || endLineNumber > lineCount) {
        throw new Error("Illegal value for endLineNumber");
      }
      const options = this.textModel.getOptions();
      const foldingRules = this.getLanguageConfiguration(this.textModel.getLanguageId()).foldingRules;
      const offSide = Boolean(foldingRules && foldingRules.offSide);
      const result = new Array(endLineNumber - startLineNumber + 1);
      let aboveContentLineIndex = -2;
      let aboveContentLineIndent = -1;
      let belowContentLineIndex = -2;
      let belowContentLineIndent = -1;
      for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
        const resultIndex = lineNumber - startLineNumber;
        const currentIndent = this._computeIndentLevel(lineNumber - 1);
        if (currentIndent >= 0) {
          aboveContentLineIndex = lineNumber - 1;
          aboveContentLineIndent = currentIndent;
          result[resultIndex] = Math.ceil(currentIndent / options.indentSize);
          continue;
        }
        if (aboveContentLineIndex === -2) {
          aboveContentLineIndex = -1;
          aboveContentLineIndent = -1;
          for (let lineIndex = lineNumber - 2; lineIndex >= 0; lineIndex--) {
            const indent = this._computeIndentLevel(lineIndex);
            if (indent >= 0) {
              aboveContentLineIndex = lineIndex;
              aboveContentLineIndent = indent;
              break;
            }
          }
        }
        if (belowContentLineIndex !== -1 && (belowContentLineIndex === -2 || belowContentLineIndex < lineNumber - 1)) {
          belowContentLineIndex = -1;
          belowContentLineIndent = -1;
          for (let lineIndex = lineNumber; lineIndex < lineCount; lineIndex++) {
            const indent = this._computeIndentLevel(lineIndex);
            if (indent >= 0) {
              belowContentLineIndex = lineIndex;
              belowContentLineIndent = indent;
              break;
            }
          }
        }
        result[resultIndex] = this._getIndentLevelForWhitespaceLine(offSide, aboveContentLineIndent, belowContentLineIndent);
      }
      return result;
    }
    _getIndentLevelForWhitespaceLine(offSide, aboveContentLineIndent, belowContentLineIndent) {
      const options = this.textModel.getOptions();
      if (aboveContentLineIndent === -1 || belowContentLineIndent === -1) {
        return 0;
      } else if (aboveContentLineIndent < belowContentLineIndent) {
        return 1 + Math.floor(aboveContentLineIndent / options.indentSize);
      } else if (aboveContentLineIndent === belowContentLineIndent) {
        return Math.ceil(belowContentLineIndent / options.indentSize);
      } else {
        if (offSide) {
          return Math.ceil(belowContentLineIndent / options.indentSize);
        } else {
          return 1 + Math.floor(belowContentLineIndent / options.indentSize);
        }
      }
    }
  }
  class BracketPairGuidesClassNames {
    constructor() {
      this.activeClassName = "indent-active";
    }
    getInlineClassName(nestingLevel, nestingLevelOfEqualBracketType, independentColorPoolPerBracketType) {
      return this.getInlineClassNameOfLevel(independentColorPoolPerBracketType ? nestingLevelOfEqualBracketType : nestingLevel);
    }
    getInlineClassNameOfLevel(level) {
      return `bracket-indent-guide lvl-${level % 30}`;
    }
  }
  class IndentGuidesOverlay extends DynamicViewOverlay {
    constructor(context) {
      super();
      this._context = context;
      this._primaryPosition = null;
      const options = this._context.configuration.options;
      const wrappingInfo = options.get(
        166
        /* EditorOption.wrappingInfo */
      );
      const fontInfo = options.get(
        59
        /* EditorOption.fontInfo */
      );
      this._spaceWidth = fontInfo.spaceWidth;
      this._maxIndentLeft = wrappingInfo.wrappingColumn === -1 ? -1 : wrappingInfo.wrappingColumn * fontInfo.typicalHalfwidthCharacterWidth;
      this._bracketPairGuideOptions = options.get(
        22
        /* EditorOption.guides */
      );
      this._renderResult = null;
      this._context.addEventHandler(this);
    }
    dispose() {
      this._context.removeEventHandler(this);
      this._renderResult = null;
      super.dispose();
    }
    // --- begin event handlers
    onConfigurationChanged(e) {
      const options = this._context.configuration.options;
      const wrappingInfo = options.get(
        166
        /* EditorOption.wrappingInfo */
      );
      const fontInfo = options.get(
        59
        /* EditorOption.fontInfo */
      );
      this._spaceWidth = fontInfo.spaceWidth;
      this._maxIndentLeft = wrappingInfo.wrappingColumn === -1 ? -1 : wrappingInfo.wrappingColumn * fontInfo.typicalHalfwidthCharacterWidth;
      this._bracketPairGuideOptions = options.get(
        22
        /* EditorOption.guides */
      );
      return true;
    }
    onCursorStateChanged(e) {
      const selection = e.selections[0];
      const newPosition = selection.getPosition();
      if (!this._primaryPosition?.equals(newPosition)) {
        this._primaryPosition = newPosition;
        return true;
      }
      return false;
    }
    onDecorationsChanged(e) {
      return true;
    }
    onFlushed(e) {
      return true;
    }
    onLinesChanged(e) {
      return true;
    }
    onLinesDeleted(e) {
      return true;
    }
    onLinesInserted(e) {
      return true;
    }
    onScrollChanged(e) {
      return e.scrollTopChanged;
    }
    onZonesChanged(e) {
      return true;
    }
    onLanguageConfigurationChanged(e) {
      return true;
    }
    // --- end event handlers
    prepareRender(ctx) {
      if (!this._bracketPairGuideOptions.indentation && this._bracketPairGuideOptions.bracketPairs === false) {
        this._renderResult = null;
        return;
      }
      const visibleStartLineNumber = ctx.visibleRange.startLineNumber;
      const visibleEndLineNumber = ctx.visibleRange.endLineNumber;
      const scrollWidth = ctx.scrollWidth;
      const activeCursorPosition = this._primaryPosition;
      const indents = this.getGuidesByLine(visibleStartLineNumber, Math.min(visibleEndLineNumber + 1, this._context.viewModel.getLineCount()), activeCursorPosition);
      const output = [];
      for (let lineNumber = visibleStartLineNumber; lineNumber <= visibleEndLineNumber; lineNumber++) {
        const lineIndex = lineNumber - visibleStartLineNumber;
        const indent = indents[lineIndex];
        let result = "";
        const leftOffset = ctx.visibleRangeForPosition(new Position$1(lineNumber, 1))?.left ?? 0;
        for (const guide of indent) {
          const left = guide.column === -1 ? leftOffset + (guide.visibleColumn - 1) * this._spaceWidth : ctx.visibleRangeForPosition(new Position$1(lineNumber, guide.column)).left;
          if (left > scrollWidth || this._maxIndentLeft > 0 && left > this._maxIndentLeft) {
            break;
          }
          const className2 = guide.horizontalLine ? guide.horizontalLine.top ? "horizontal-top" : "horizontal-bottom" : "vertical";
          const width2 = guide.horizontalLine ? (ctx.visibleRangeForPosition(new Position$1(lineNumber, guide.horizontalLine.endColumn))?.left ?? left + this._spaceWidth) - left : this._spaceWidth;
          result += `<div class="core-guide ${guide.className} ${className2}" style="left:${left}px;width:${width2}px"></div>`;
        }
        output[lineIndex] = result;
      }
      this._renderResult = output;
    }
    getGuidesByLine(visibleStartLineNumber, visibleEndLineNumber, activeCursorPosition) {
      const bracketGuides = this._bracketPairGuideOptions.bracketPairs !== false ? this._context.viewModel.getBracketGuidesInRangeByLine(visibleStartLineNumber, visibleEndLineNumber, activeCursorPosition, {
        highlightActive: this._bracketPairGuideOptions.highlightActiveBracketPair,
        horizontalGuides: this._bracketPairGuideOptions.bracketPairsHorizontal === true ? HorizontalGuidesState.Enabled : this._bracketPairGuideOptions.bracketPairsHorizontal === "active" ? HorizontalGuidesState.EnabledForActive : HorizontalGuidesState.Disabled,
        includeInactive: this._bracketPairGuideOptions.bracketPairs === true
      }) : null;
      const indentGuides = this._bracketPairGuideOptions.indentation ? this._context.viewModel.getLinesIndentGuides(visibleStartLineNumber, visibleEndLineNumber) : null;
      let activeIndentStartLineNumber = 0;
      let activeIndentEndLineNumber = 0;
      let activeIndentLevel = 0;
      if (this._bracketPairGuideOptions.highlightActiveIndentation !== false && activeCursorPosition) {
        const activeIndentInfo = this._context.viewModel.getActiveIndentGuide(activeCursorPosition.lineNumber, visibleStartLineNumber, visibleEndLineNumber);
        activeIndentStartLineNumber = activeIndentInfo.startLineNumber;
        activeIndentEndLineNumber = activeIndentInfo.endLineNumber;
        activeIndentLevel = activeIndentInfo.indent;
      }
      const { indentSize } = this._context.viewModel.model.getOptions();
      const result = [];
      for (let lineNumber = visibleStartLineNumber; lineNumber <= visibleEndLineNumber; lineNumber++) {
        const lineGuides = new Array();
        result.push(lineGuides);
        const bracketGuidesInLine = bracketGuides ? bracketGuides[lineNumber - visibleStartLineNumber] : [];
        const bracketGuidesInLineQueue = new ArrayQueue(bracketGuidesInLine);
        const indentGuidesInLine = indentGuides ? indentGuides[lineNumber - visibleStartLineNumber] : 0;
        for (let indentLvl = 1; indentLvl <= indentGuidesInLine; indentLvl++) {
          const indentGuide = (indentLvl - 1) * indentSize + 1;
          const isActive = (
            // Disable active indent guide if there are bracket guides.
            (this._bracketPairGuideOptions.highlightActiveIndentation === "always" || bracketGuidesInLine.length === 0) && activeIndentStartLineNumber <= lineNumber && lineNumber <= activeIndentEndLineNumber && indentLvl === activeIndentLevel
          );
          lineGuides.push(...bracketGuidesInLineQueue.takeWhile((g) => g.visibleColumn < indentGuide) || []);
          const peeked = bracketGuidesInLineQueue.peek();
          if (!peeked || peeked.visibleColumn !== indentGuide || peeked.horizontalLine) {
            lineGuides.push(new IndentGuide(indentGuide, -1, `core-guide-indent lvl-${(indentLvl - 1) % 30}` + (isActive ? " indent-active" : ""), null, -1, -1));
          }
        }
        lineGuides.push(...bracketGuidesInLineQueue.takeWhile((g) => true) || []);
      }
      return result;
    }
    render(startLineNumber, lineNumber) {
      if (!this._renderResult) {
        return "";
      }
      const lineIndex = lineNumber - startLineNumber;
      if (lineIndex < 0 || lineIndex >= this._renderResult.length) {
        return "";
      }
      return this._renderResult[lineIndex];
    }
  }
  function transparentToUndefined(color) {
    if (color && color.isTransparent()) {
      return void 0;
    }
    return color;
  }
  registerThemingParticipant((theme, collector) => {
    const colors = [
      { bracketColor: editorBracketHighlightingForeground1, guideColor: editorBracketPairGuideBackground1, guideColorActive: editorBracketPairGuideActiveBackground1 },
      { bracketColor: editorBracketHighlightingForeground2, guideColor: editorBracketPairGuideBackground2, guideColorActive: editorBracketPairGuideActiveBackground2 },
      { bracketColor: editorBracketHighlightingForeground3, guideColor: editorBracketPairGuideBackground3, guideColorActive: editorBracketPairGuideActiveBackground3 },
      { bracketColor: editorBracketHighlightingForeground4, guideColor: editorBracketPairGuideBackground4, guideColorActive: editorBracketPairGuideActiveBackground4 },
      { bracketColor: editorBracketHighlightingForeground5, guideColor: editorBracketPairGuideBackground5, guideColorActive: editorBracketPairGuideActiveBackground5 },
      { bracketColor: editorBracketHighlightingForeground6, guideColor: editorBracketPairGuideBackground6, guideColorActive: editorBracketPairGuideActiveBackground6 }
    ];
    const colorProvider = new BracketPairGuidesClassNames();
    const indentColors = [
      { indentColor: editorIndentGuide1, indentColorActive: editorActiveIndentGuide1 },
      { indentColor: editorIndentGuide2, indentColorActive: editorActiveIndentGuide2 },
      { indentColor: editorIndentGuide3, indentColorActive: editorActiveIndentGuide3 },
      { indentColor: editorIndentGuide4, indentColorActive: editorActiveIndentGuide4 },
      { indentColor: editorIndentGuide5, indentColorActive: editorActiveIndentGuide5 },
      { indentColor: editorIndentGuide6, indentColorActive: editorActiveIndentGuide6 }
    ];
    const colorValues = colors.map((c) => {
      const bracketColor = theme.getColor(c.bracketColor);
      const guideColor = theme.getColor(c.guideColor);
      const guideColorActive = theme.getColor(c.guideColorActive);
      const effectiveGuideColor = transparentToUndefined(transparentToUndefined(guideColor) ?? bracketColor?.transparent(0.3));
      const effectiveGuideColorActive = transparentToUndefined(transparentToUndefined(guideColorActive) ?? bracketColor);
      if (!effectiveGuideColor || !effectiveGuideColorActive) {
        return void 0;
      }
      return {
        guideColor: effectiveGuideColor,
        guideColorActive: effectiveGuideColorActive
      };
    }).filter(isDefined);
    const indentColorValues = indentColors.map((c) => {
      const indentColor = theme.getColor(c.indentColor);
      const indentColorActive = theme.getColor(c.indentColorActive);
      const effectiveIndentColor = transparentToUndefined(indentColor);
      const effectiveIndentColorActive = transparentToUndefined(indentColorActive);
      if (!effectiveIndentColor || !effectiveIndentColorActive) {
        return void 0;
      }
      return {
        indentColor: effectiveIndentColor,
        indentColorActive: effectiveIndentColorActive
      };
    }).filter(isDefined);
    if (colorValues.length > 0) {
      for (let level = 0; level < 30; level++) {
        const colors2 = colorValues[level % colorValues.length];
        collector.addRule(`.monaco-editor .${colorProvider.getInlineClassNameOfLevel(level).replace(/ /g, ".")} { --guide-color: ${colors2.guideColor}; --guide-color-active: ${colors2.guideColorActive}; }`);
      }
      collector.addRule(`.monaco-editor .vertical { box-shadow: 1px 0 0 0 var(--guide-color) inset; }`);
      collector.addRule(`.monaco-editor .horizontal-top { border-top: 1px solid var(--guide-color); }`);
      collector.addRule(`.monaco-editor .horizontal-bottom { border-bottom: 1px solid var(--guide-color); }`);
      collector.addRule(`.monaco-editor .vertical.${colorProvider.activeClassName} { box-shadow: 1px 0 0 0 var(--guide-color-active) inset; }`);
      collector.addRule(`.monaco-editor .horizontal-top.${colorProvider.activeClassName} { border-top: 1px solid var(--guide-color-active); }`);
      collector.addRule(`.monaco-editor .horizontal-bottom.${colorProvider.activeClassName} { border-bottom: 1px solid var(--guide-color-active); }`);
    }
    if (indentColorValues.length > 0) {
      for (let level = 0; level < 30; level++) {
        const colors2 = indentColorValues[level % indentColorValues.length];
        collector.addRule(`.monaco-editor .lines-content .core-guide-indent.lvl-${level} { --indent-color: ${colors2.indentColor}; --indent-color-active: ${colors2.indentColorActive}; }`);
      }
      collector.addRule(`.monaco-editor .lines-content .core-guide-indent { box-shadow: 1px 0 0 0 var(--indent-color) inset; }`);
      collector.addRule(`.monaco-editor .lines-content .core-guide-indent.indent-active { box-shadow: 1px 0 0 0 var(--indent-color-active) inset; }`);
    }
  });
  const _LineNumbersOverlay = class _LineNumbersOverlay extends DynamicViewOverlay {
    constructor(context) {
      super();
      this._context = context;
      this._readConfig();
      this._lastCursorModelPosition = new Position$1(1, 1);
      this._renderResult = null;
      this._activeModelLineNumber = 1;
      this._context.addEventHandler(this);
    }
    _readConfig() {
      const options = this._context.configuration.options;
      this._lineHeight = options.get(
        75
        /* EditorOption.lineHeight */
      );
      const lineNumbers = options.get(
        76
        /* EditorOption.lineNumbers */
      );
      this._renderLineNumbers = lineNumbers.renderType;
      this._renderCustomLineNumbers = lineNumbers.renderFn;
      this._renderFinalNewline = options.get(
        109
        /* EditorOption.renderFinalNewline */
      );
      const layoutInfo = options.get(
        165
        /* EditorOption.layoutInfo */
      );
      this._lineNumbersLeft = layoutInfo.lineNumbersLeft;
      this._lineNumbersWidth = layoutInfo.lineNumbersWidth;
    }
    dispose() {
      this._context.removeEventHandler(this);
      this._renderResult = null;
      super.dispose();
    }
    // --- begin event handlers
    onConfigurationChanged(e) {
      this._readConfig();
      return true;
    }
    onCursorStateChanged(e) {
      const primaryViewPosition = e.selections[0].getPosition();
      this._lastCursorModelPosition = this._context.viewModel.coordinatesConverter.convertViewPositionToModelPosition(primaryViewPosition);
      let shouldRender = false;
      if (this._activeModelLineNumber !== this._lastCursorModelPosition.lineNumber) {
        this._activeModelLineNumber = this._lastCursorModelPosition.lineNumber;
        shouldRender = true;
      }
      if (this._renderLineNumbers === 2 || this._renderLineNumbers === 3) {
        shouldRender = true;
      }
      return shouldRender;
    }
    onFlushed(e) {
      return true;
    }
    onLinesChanged(e) {
      return true;
    }
    onLinesDeleted(e) {
      return true;
    }
    onLinesInserted(e) {
      return true;
    }
    onScrollChanged(e) {
      return e.scrollTopChanged;
    }
    onZonesChanged(e) {
      return true;
    }
    onDecorationsChanged(e) {
      return e.affectsLineNumber;
    }
    // --- end event handlers
    _getLineRenderLineNumber(viewLineNumber) {
      const modelPosition = this._context.viewModel.coordinatesConverter.convertViewPositionToModelPosition(new Position$1(viewLineNumber, 1));
      if (modelPosition.column !== 1) {
        return "";
      }
      const modelLineNumber = modelPosition.lineNumber;
      if (this._renderCustomLineNumbers) {
        return this._renderCustomLineNumbers(modelLineNumber);
      }
      if (this._renderLineNumbers === 2) {
        const diff = Math.abs(this._lastCursorModelPosition.lineNumber - modelLineNumber);
        if (diff === 0) {
          return '<span class="relative-current-line-number">' + modelLineNumber + "</span>";
        }
        return String(diff);
      }
      if (this._renderLineNumbers === 3) {
        if (this._lastCursorModelPosition.lineNumber === modelLineNumber) {
          return String(modelLineNumber);
        }
        if (modelLineNumber % 10 === 0) {
          return String(modelLineNumber);
        }
        const finalLineNumber = this._context.viewModel.getLineCount();
        if (modelLineNumber === finalLineNumber) {
          return String(modelLineNumber);
        }
        return "";
      }
      return String(modelLineNumber);
    }
    prepareRender(ctx) {
      if (this._renderLineNumbers === 0) {
        this._renderResult = null;
        return;
      }
      const lineHeightClassName = isLinux ? this._lineHeight % 2 === 0 ? " lh-even" : " lh-odd" : "";
      const visibleStartLineNumber = ctx.visibleRange.startLineNumber;
      const visibleEndLineNumber = ctx.visibleRange.endLineNumber;
      const lineNoDecorations = this._context.viewModel.getDecorationsInViewport(ctx.visibleRange).filter((d) => !!d.options.lineNumberClassName);
      lineNoDecorations.sort((a, b) => Range$2.compareRangesUsingEnds(a.range, b.range));
      let decorationStartIndex = 0;
      const lineCount = this._context.viewModel.getLineCount();
      const output = [];
      for (let lineNumber = visibleStartLineNumber; lineNumber <= visibleEndLineNumber; lineNumber++) {
        const lineIndex = lineNumber - visibleStartLineNumber;
        const modelLineNumber = this._context.viewModel.coordinatesConverter.convertViewPositionToModelPosition(new Position$1(lineNumber, 1)).lineNumber;
        let renderLineNumber = this._getLineRenderLineNumber(lineNumber);
        let extraClassNames = "";
        while (decorationStartIndex < lineNoDecorations.length && lineNoDecorations[decorationStartIndex].range.endLineNumber < lineNumber) {
          decorationStartIndex++;
        }
        for (let i2 = decorationStartIndex; i2 < lineNoDecorations.length; i2++) {
          const { range: range2, options } = lineNoDecorations[i2];
          if (range2.startLineNumber <= lineNumber) {
            extraClassNames += " " + options.lineNumberClassName;
          }
        }
        if (!renderLineNumber && !extraClassNames) {
          output[lineIndex] = "";
          continue;
        }
        if (lineNumber === lineCount && this._context.viewModel.getLineLength(lineNumber) === 0) {
          if (this._renderFinalNewline === "off") {
            renderLineNumber = "";
          }
          if (this._renderFinalNewline === "dimmed") {
            extraClassNames += " dimmed-line-number";
          }
        }
        if (modelLineNumber === this._activeModelLineNumber) {
          extraClassNames += " active-line-number";
        }
        output[lineIndex] = `<div class="${_LineNumbersOverlay.CLASS_NAME}${lineHeightClassName}${extraClassNames}" style="left:${this._lineNumbersLeft}px;width:${this._lineNumbersWidth}px;">${renderLineNumber}</div>`;
      }
      this._renderResult = output;
    }
    render(startLineNumber, lineNumber) {
      if (!this._renderResult) {
        return "";
      }
      const lineIndex = lineNumber - startLineNumber;
      if (lineIndex < 0 || lineIndex >= this._renderResult.length) {
        return "";
      }
      return this._renderResult[lineIndex];
    }
  };
  _LineNumbersOverlay.CLASS_NAME = "line-numbers";
  let LineNumbersOverlay = _LineNumbersOverlay;
  registerThemingParticipant((theme, collector) => {
    const editorLineNumbersColor = theme.getColor(editorLineNumbers);
    const editorDimmedLineNumberColor = theme.getColor(editorDimmedLineNumber);
    if (editorDimmedLineNumberColor) {
      collector.addRule(`.monaco-editor .line-numbers.dimmed-line-number { color: ${editorDimmedLineNumberColor}; }`);
    } else if (editorLineNumbersColor) {
      collector.addRule(`.monaco-editor .line-numbers.dimmed-line-number { color: ${editorLineNumbersColor.transparent(0.4)}; }`);
    }
  });
  const MOUSE_CURSOR_TEXT_CSS_CLASS_NAME = `monaco-mouse-cursor-text`;
  class DomReadingContext {
    get didDomLayout() {
      return this._didDomLayout;
    }
    readClientRect() {
      if (!this._clientRectRead) {
        this._clientRectRead = true;
        const rect = this._domNode.getBoundingClientRect();
        this.markDidDomLayout();
        this._clientRectDeltaLeft = rect.left;
        this._clientRectScale = rect.width / this._domNode.offsetWidth;
      }
    }
    get clientRectDeltaLeft() {
      if (!this._clientRectRead) {
        this.readClientRect();
      }
      return this._clientRectDeltaLeft;
    }
    get clientRectScale() {
      if (!this._clientRectRead) {
        this.readClientRect();
      }
      return this._clientRectScale;
    }
    constructor(_domNode, endNode) {
      this._domNode = _domNode;
      this.endNode = endNode;
      this._didDomLayout = false;
      this._clientRectDeltaLeft = 0;
      this._clientRectScale = 1;
      this._clientRectRead = false;
    }
    markDidDomLayout() {
      this._didDomLayout = true;
    }
  }
  class ViewLineOptions {
    constructor(config, themeType) {
      this.themeType = themeType;
      const options = config.options;
      const fontInfo = options.get(
        59
        /* EditorOption.fontInfo */
      );
      this.renderWhitespace = options.get(
        113
        /* EditorOption.renderWhitespace */
      );
      this.experimentalWhitespaceRendering = options.get(
        47
        /* EditorOption.experimentalWhitespaceRendering */
      );
      this.renderControlCharacters = options.get(
        108
        /* EditorOption.renderControlCharacters */
      );
      this.spaceWidth = fontInfo.spaceWidth;
      this.middotWidth = fontInfo.middotWidth;
      this.wsmiddotWidth = fontInfo.wsmiddotWidth;
      this.useMonospaceOptimizations = fontInfo.isMonospace && !options.get(
        40
        /* EditorOption.disableMonospaceOptimizations */
      );
      this.canUseHalfwidthRightwardsArrow = fontInfo.canUseHalfwidthRightwardsArrow;
      this.lineHeight = options.get(
        75
        /* EditorOption.lineHeight */
      );
      this.stopRenderingLineAfter = options.get(
        133
        /* EditorOption.stopRenderingLineAfter */
      );
      this.fontLigatures = options.get(
        60
        /* EditorOption.fontLigatures */
      );
      this.verticalScrollbarSize = options.get(
        117
        /* EditorOption.scrollbar */
      ).verticalScrollbarSize;
      this.useGpu = options.get(
        46
        /* EditorOption.experimentalGpuAcceleration */
      ) === "on";
    }
    equals(other) {
      return this.themeType === other.themeType && this.renderWhitespace === other.renderWhitespace && this.experimentalWhitespaceRendering === other.experimentalWhitespaceRendering && this.renderControlCharacters === other.renderControlCharacters && this.spaceWidth === other.spaceWidth && this.middotWidth === other.middotWidth && this.wsmiddotWidth === other.wsmiddotWidth && this.useMonospaceOptimizations === other.useMonospaceOptimizations && this.canUseHalfwidthRightwardsArrow === other.canUseHalfwidthRightwardsArrow && this.lineHeight === other.lineHeight && this.stopRenderingLineAfter === other.stopRenderingLineAfter && this.fontLigatures === other.fontLigatures && this.verticalScrollbarSize === other.verticalScrollbarSize && this.useGpu === other.useGpu;
    }
  }
  class LastRenderedData {
    constructor() {
      this._currentVisibleRange = new Range$2(1, 1, 1, 1);
    }
    getCurrentVisibleRange() {
      return this._currentVisibleRange;
    }
    setCurrentVisibleRange(currentVisibleRange) {
      this._currentVisibleRange = currentVisibleRange;
    }
  }
  class HorizontalRevealRangeRequest {
    constructor(minimalReveal, lineNumber, startColumn, endColumn, startScrollTop, stopScrollTop, scrollType) {
      this.minimalReveal = minimalReveal;
      this.lineNumber = lineNumber;
      this.startColumn = startColumn;
      this.endColumn = endColumn;
      this.startScrollTop = startScrollTop;
      this.stopScrollTop = stopScrollTop;
      this.scrollType = scrollType;
      this.type = "range";
      this.minLineNumber = lineNumber;
      this.maxLineNumber = lineNumber;
    }
  }
  class HorizontalRevealSelectionsRequest {
    constructor(minimalReveal, selections, startScrollTop, stopScrollTop, scrollType) {
      this.minimalReveal = minimalReveal;
      this.selections = selections;
      this.startScrollTop = startScrollTop;
      this.stopScrollTop = stopScrollTop;
      this.scrollType = scrollType;
      this.type = "selections";
      let minLineNumber = selections[0].startLineNumber;
      let maxLineNumber = selections[0].endLineNumber;
      for (let i2 = 1, len = selections.length; i2 < len; i2++) {
        const selection = selections[i2];
        minLineNumber = Math.min(minLineNumber, selection.startLineNumber);
        maxLineNumber = Math.max(maxLineNumber, selection.endLineNumber);
      }
      this.minLineNumber = minLineNumber;
      this.maxLineNumber = maxLineNumber;
    }
  }
  const _ViewLines = class _ViewLines extends ViewPart {
    constructor(context, viewGpuContext, linesContent) {
      super(context);
      const conf = this._context.configuration;
      const options = this._context.configuration.options;
      const fontInfo = options.get(
        59
        /* EditorOption.fontInfo */
      );
      const wrappingInfo = options.get(
        166
        /* EditorOption.wrappingInfo */
      );
      this._lineHeight = options.get(
        75
        /* EditorOption.lineHeight */
      );
      this._typicalHalfwidthCharacterWidth = fontInfo.typicalHalfwidthCharacterWidth;
      this._isViewportWrapping = wrappingInfo.isViewportWrapping;
      this._revealHorizontalRightPadding = options.get(
        114
        /* EditorOption.revealHorizontalRightPadding */
      );
      this._cursorSurroundingLines = options.get(
        35
        /* EditorOption.cursorSurroundingLines */
      );
      this._cursorSurroundingLinesStyle = options.get(
        36
        /* EditorOption.cursorSurroundingLinesStyle */
      );
      this._canUseLayerHinting = !options.get(
        39
        /* EditorOption.disableLayerHinting */
      );
      this._viewLineOptions = new ViewLineOptions(conf, this._context.theme.type);
      this._linesContent = linesContent;
      this._textRangeRestingSpot = document.createElement("div");
      this._visibleLines = new VisibleLinesCollection(this._context, {
        createLine: () => new ViewLine(viewGpuContext, this._viewLineOptions)
      });
      this.domNode = this._visibleLines.domNode;
      PartFingerprints.write(
        this.domNode,
        8
        /* PartFingerprint.ViewLines */
      );
      this.domNode.setClassName(`view-lines ${MOUSE_CURSOR_TEXT_CSS_CLASS_NAME}`);
      applyFontInfo(this.domNode, fontInfo);
      this._maxLineWidth = 0;
      this._asyncUpdateLineWidths = new RunOnceScheduler(() => {
        this._updateLineWidthsSlow();
      }, 200);
      this._asyncCheckMonospaceFontAssumptions = new RunOnceScheduler(() => {
        this._checkMonospaceFontAssumptions();
      }, 2e3);
      this._lastRenderedData = new LastRenderedData();
      this._horizontalRevealRequest = null;
      this._stickyScrollEnabled = options.get(
        131
        /* EditorOption.stickyScroll */
      ).enabled;
      this._maxNumberStickyLines = options.get(
        131
        /* EditorOption.stickyScroll */
      ).maxLineCount;
    }
    dispose() {
      this._asyncUpdateLineWidths.dispose();
      this._asyncCheckMonospaceFontAssumptions.dispose();
      super.dispose();
    }
    getDomNode() {
      return this.domNode;
    }
    // ---- begin view event handlers
    onConfigurationChanged(e) {
      this._visibleLines.onConfigurationChanged(e);
      if (e.hasChanged(
        166
        /* EditorOption.wrappingInfo */
      )) {
        this._maxLineWidth = 0;
      }
      const options = this._context.configuration.options;
      const fontInfo = options.get(
        59
        /* EditorOption.fontInfo */
      );
      const wrappingInfo = options.get(
        166
        /* EditorOption.wrappingInfo */
      );
      this._lineHeight = options.get(
        75
        /* EditorOption.lineHeight */
      );
      this._typicalHalfwidthCharacterWidth = fontInfo.typicalHalfwidthCharacterWidth;
      this._isViewportWrapping = wrappingInfo.isViewportWrapping;
      this._revealHorizontalRightPadding = options.get(
        114
        /* EditorOption.revealHorizontalRightPadding */
      );
      this._cursorSurroundingLines = options.get(
        35
        /* EditorOption.cursorSurroundingLines */
      );
      this._cursorSurroundingLinesStyle = options.get(
        36
        /* EditorOption.cursorSurroundingLinesStyle */
      );
      this._canUseLayerHinting = !options.get(
        39
        /* EditorOption.disableLayerHinting */
      );
      this._stickyScrollEnabled = options.get(
        131
        /* EditorOption.stickyScroll */
      ).enabled;
      this._maxNumberStickyLines = options.get(
        131
        /* EditorOption.stickyScroll */
      ).maxLineCount;
      applyFontInfo(this.domNode, fontInfo);
      this._onOptionsMaybeChanged();
      if (e.hasChanged(
        165
        /* EditorOption.layoutInfo */
      )) {
        this._maxLineWidth = 0;
      }
      return true;
    }
    _onOptionsMaybeChanged() {
      const conf = this._context.configuration;
      const newViewLineOptions = new ViewLineOptions(conf, this._context.theme.type);
      if (!this._viewLineOptions.equals(newViewLineOptions)) {
        this._viewLineOptions = newViewLineOptions;
        const startLineNumber = this._visibleLines.getStartLineNumber();
        const endLineNumber = this._visibleLines.getEndLineNumber();
        for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
          const line = this._visibleLines.getVisibleLine(lineNumber);
          line.onOptionsChanged(this._viewLineOptions);
        }
        return true;
      }
      return false;
    }
    onCursorStateChanged(e) {
      const rendStartLineNumber = this._visibleLines.getStartLineNumber();
      const rendEndLineNumber = this._visibleLines.getEndLineNumber();
      let r = false;
      for (let lineNumber = rendStartLineNumber; lineNumber <= rendEndLineNumber; lineNumber++) {
        r = this._visibleLines.getVisibleLine(lineNumber).onSelectionChanged() || r;
      }
      return r;
    }
    onDecorationsChanged(e) {
      {
        const rendStartLineNumber = this._visibleLines.getStartLineNumber();
        const rendEndLineNumber = this._visibleLines.getEndLineNumber();
        for (let lineNumber = rendStartLineNumber; lineNumber <= rendEndLineNumber; lineNumber++) {
          this._visibleLines.getVisibleLine(lineNumber).onDecorationsChanged();
        }
      }
      return true;
    }
    onFlushed(e) {
      const shouldRender = this._visibleLines.onFlushed(e, this._viewLineOptions.useGpu);
      this._maxLineWidth = 0;
      return shouldRender;
    }
    onLinesChanged(e) {
      return this._visibleLines.onLinesChanged(e);
    }
    onLinesDeleted(e) {
      return this._visibleLines.onLinesDeleted(e);
    }
    onLinesInserted(e) {
      return this._visibleLines.onLinesInserted(e);
    }
    onRevealRangeRequest(e) {
      const desiredScrollTop = this._computeScrollTopToRevealRange(this._context.viewLayout.getFutureViewport(), e.source, e.minimalReveal, e.range, e.selections, e.verticalType);
      if (desiredScrollTop === -1) {
        return false;
      }
      let newScrollPosition = this._context.viewLayout.validateScrollPosition({ scrollTop: desiredScrollTop });
      if (e.revealHorizontal) {
        if (e.range && e.range.startLineNumber !== e.range.endLineNumber) {
          newScrollPosition = {
            scrollTop: newScrollPosition.scrollTop,
            scrollLeft: 0
          };
        } else if (e.range) {
          this._horizontalRevealRequest = new HorizontalRevealRangeRequest(e.minimalReveal, e.range.startLineNumber, e.range.startColumn, e.range.endColumn, this._context.viewLayout.getCurrentScrollTop(), newScrollPosition.scrollTop, e.scrollType);
        } else if (e.selections && e.selections.length > 0) {
          this._horizontalRevealRequest = new HorizontalRevealSelectionsRequest(e.minimalReveal, e.selections, this._context.viewLayout.getCurrentScrollTop(), newScrollPosition.scrollTop, e.scrollType);
        }
      } else {
        this._horizontalRevealRequest = null;
      }
      const scrollTopDelta = Math.abs(this._context.viewLayout.getCurrentScrollTop() - newScrollPosition.scrollTop);
      const scrollType = scrollTopDelta <= this._lineHeight ? 1 : e.scrollType;
      this._context.viewModel.viewLayout.setScrollPosition(newScrollPosition, scrollType);
      return true;
    }
    onScrollChanged(e) {
      if (this._horizontalRevealRequest && e.scrollLeftChanged) {
        this._horizontalRevealRequest = null;
      }
      if (this._horizontalRevealRequest && e.scrollTopChanged) {
        const min = Math.min(this._horizontalRevealRequest.startScrollTop, this._horizontalRevealRequest.stopScrollTop);
        const max = Math.max(this._horizontalRevealRequest.startScrollTop, this._horizontalRevealRequest.stopScrollTop);
        if (e.scrollTop < min || e.scrollTop > max) {
          this._horizontalRevealRequest = null;
        }
      }
      this.domNode.setWidth(e.scrollWidth);
      return this._visibleLines.onScrollChanged(e) || true;
    }
    onTokensChanged(e) {
      return this._visibleLines.onTokensChanged(e);
    }
    onZonesChanged(e) {
      this._context.viewModel.viewLayout.setMaxLineWidth(this._maxLineWidth);
      return this._visibleLines.onZonesChanged(e);
    }
    onThemeChanged(e) {
      return this._onOptionsMaybeChanged();
    }
    // ---- end view event handlers
    // ----------- HELPERS FOR OTHERS
    getPositionFromDOMInfo(spanNode, offset) {
      const viewLineDomNode = this._getViewLineDomNode(spanNode);
      if (viewLineDomNode === null) {
        return null;
      }
      const lineNumber = this._getLineNumberFor(viewLineDomNode);
      if (lineNumber === -1) {
        return null;
      }
      if (lineNumber < 1 || lineNumber > this._context.viewModel.getLineCount()) {
        return null;
      }
      if (this._context.viewModel.getLineMaxColumn(lineNumber) === 1) {
        return new Position$1(lineNumber, 1);
      }
      const rendStartLineNumber = this._visibleLines.getStartLineNumber();
      const rendEndLineNumber = this._visibleLines.getEndLineNumber();
      if (lineNumber < rendStartLineNumber || lineNumber > rendEndLineNumber) {
        return null;
      }
      let column = this._visibleLines.getVisibleLine(lineNumber).getColumnOfNodeOffset(spanNode, offset);
      const minColumn = this._context.viewModel.getLineMinColumn(lineNumber);
      if (column < minColumn) {
        column = minColumn;
      }
      return new Position$1(lineNumber, column);
    }
    _getViewLineDomNode(node) {
      while (node && node.nodeType === 1) {
        if (node.className === ViewLine.CLASS_NAME) {
          return node;
        }
        node = node.parentElement;
      }
      return null;
    }
    /**
     * @returns the line number of this view line dom node.
     */
    _getLineNumberFor(domNode) {
      const startLineNumber = this._visibleLines.getStartLineNumber();
      const endLineNumber = this._visibleLines.getEndLineNumber();
      for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
        const line = this._visibleLines.getVisibleLine(lineNumber);
        if (domNode === line.getDomNode()) {
          return lineNumber;
        }
      }
      return -1;
    }
    getLineWidth(lineNumber) {
      const rendStartLineNumber = this._visibleLines.getStartLineNumber();
      const rendEndLineNumber = this._visibleLines.getEndLineNumber();
      if (lineNumber < rendStartLineNumber || lineNumber > rendEndLineNumber) {
        return -1;
      }
      const context = new DomReadingContext(this.domNode.domNode, this._textRangeRestingSpot);
      const result = this._visibleLines.getVisibleLine(lineNumber).getWidth(context);
      this._updateLineWidthsSlowIfDomDidLayout(context);
      return result;
    }
    linesVisibleRangesForRange(_range, includeNewLines) {
      if (this.shouldRender()) {
        return null;
      }
      const originalEndLineNumber = _range.endLineNumber;
      const range2 = Range$2.intersectRanges(_range, this._lastRenderedData.getCurrentVisibleRange());
      if (!range2) {
        return null;
      }
      const visibleRanges = [];
      let visibleRangesLen = 0;
      const domReadingContext = new DomReadingContext(this.domNode.domNode, this._textRangeRestingSpot);
      let nextLineModelLineNumber = 0;
      if (includeNewLines) {
        nextLineModelLineNumber = this._context.viewModel.coordinatesConverter.convertViewPositionToModelPosition(new Position$1(range2.startLineNumber, 1)).lineNumber;
      }
      const rendStartLineNumber = this._visibleLines.getStartLineNumber();
      const rendEndLineNumber = this._visibleLines.getEndLineNumber();
      for (let lineNumber = range2.startLineNumber; lineNumber <= range2.endLineNumber; lineNumber++) {
        if (lineNumber < rendStartLineNumber || lineNumber > rendEndLineNumber) {
          continue;
        }
        const startColumn = lineNumber === range2.startLineNumber ? range2.startColumn : 1;
        const continuesInNextLine = lineNumber !== originalEndLineNumber;
        const endColumn = continuesInNextLine ? this._context.viewModel.getLineMaxColumn(lineNumber) : range2.endColumn;
        const visibleLine = this._visibleLines.getVisibleLine(lineNumber);
        const visibleRangesForLine = visibleLine.getVisibleRangesForRange(lineNumber, startColumn, endColumn, domReadingContext);
        if (!visibleRangesForLine) {
          continue;
        }
        if (includeNewLines && lineNumber < originalEndLineNumber) {
          const currentLineModelLineNumber = nextLineModelLineNumber;
          nextLineModelLineNumber = this._context.viewModel.coordinatesConverter.convertViewPositionToModelPosition(new Position$1(lineNumber + 1, 1)).lineNumber;
          if (currentLineModelLineNumber !== nextLineModelLineNumber) {
            const floatHorizontalRange = visibleRangesForLine.ranges[visibleRangesForLine.ranges.length - 1];
            floatHorizontalRange.width += this._typicalHalfwidthCharacterWidth;
            if (this._context.viewModel.getTextDirection(currentLineModelLineNumber) === TextDirection$1.RTL) {
              floatHorizontalRange.left -= this._typicalHalfwidthCharacterWidth;
            }
          }
        }
        visibleRanges[visibleRangesLen++] = new LineVisibleRanges(visibleRangesForLine.outsideRenderedLine, lineNumber, HorizontalRange.from(visibleRangesForLine.ranges), continuesInNextLine);
      }
      this._updateLineWidthsSlowIfDomDidLayout(domReadingContext);
      if (visibleRangesLen === 0) {
        return null;
      }
      return visibleRanges;
    }
    _visibleRangesForLineRange(lineNumber, startColumn, endColumn) {
      if (this.shouldRender()) {
        return null;
      }
      if (lineNumber < this._visibleLines.getStartLineNumber() || lineNumber > this._visibleLines.getEndLineNumber()) {
        return null;
      }
      const domReadingContext = new DomReadingContext(this.domNode.domNode, this._textRangeRestingSpot);
      const result = this._visibleLines.getVisibleLine(lineNumber).getVisibleRangesForRange(lineNumber, startColumn, endColumn, domReadingContext);
      this._updateLineWidthsSlowIfDomDidLayout(domReadingContext);
      return result;
    }
    _lineIsRenderedRTL(lineNumber) {
      if (lineNumber < this._visibleLines.getStartLineNumber() || lineNumber > this._visibleLines.getEndLineNumber()) {
        return false;
      }
      const visibleLine = this._visibleLines.getVisibleLine(lineNumber);
      return visibleLine.isRenderedRTL();
    }
    visibleRangeForPosition(position) {
      const visibleRanges = this._visibleRangesForLineRange(position.lineNumber, position.column, position.column);
      if (!visibleRanges) {
        return null;
      }
      return new HorizontalPosition(visibleRanges.outsideRenderedLine, visibleRanges.ranges[0].left);
    }
    /**
     * Updates the max line width if it is fast to compute.
     * Returns true if all lines were taken into account.
     * Returns false if some lines need to be reevaluated (in a slow fashion).
     */
    _updateLineWidthsFast() {
      return this._updateLineWidths(true);
    }
    _updateLineWidthsSlow() {
      this._updateLineWidths(false);
    }
    /**
     * Update the line widths using DOM layout information after someone else
     * has caused a synchronous layout.
     */
    _updateLineWidthsSlowIfDomDidLayout(domReadingContext) {
      if (!domReadingContext.didDomLayout) {
        return;
      }
      if (this._asyncUpdateLineWidths.isScheduled()) {
        return;
      }
      this._asyncUpdateLineWidths.cancel();
      this._updateLineWidthsSlow();
    }
    _updateLineWidths(fast) {
      const rendStartLineNumber = this._visibleLines.getStartLineNumber();
      const rendEndLineNumber = this._visibleLines.getEndLineNumber();
      let localMaxLineWidth = 1;
      let allWidthsComputed = true;
      for (let lineNumber = rendStartLineNumber; lineNumber <= rendEndLineNumber; lineNumber++) {
        const visibleLine = this._visibleLines.getVisibleLine(lineNumber);
        if (fast && !visibleLine.getWidthIsFast()) {
          allWidthsComputed = false;
          continue;
        }
        localMaxLineWidth = Math.max(localMaxLineWidth, visibleLine.getWidth(null));
      }
      if (allWidthsComputed && rendStartLineNumber === 1 && rendEndLineNumber === this._context.viewModel.getLineCount()) {
        this._maxLineWidth = 0;
      }
      this._ensureMaxLineWidth(localMaxLineWidth);
      return allWidthsComputed;
    }
    _checkMonospaceFontAssumptions() {
      let longestLineNumber = -1;
      let longestWidth = -1;
      const rendStartLineNumber = this._visibleLines.getStartLineNumber();
      const rendEndLineNumber = this._visibleLines.getEndLineNumber();
      for (let lineNumber = rendStartLineNumber; lineNumber <= rendEndLineNumber; lineNumber++) {
        const visibleLine = this._visibleLines.getVisibleLine(lineNumber);
        if (visibleLine.needsMonospaceFontCheck()) {
          const lineWidth = visibleLine.getWidth(null);
          if (lineWidth > longestWidth) {
            longestWidth = lineWidth;
            longestLineNumber = lineNumber;
          }
        }
      }
      if (longestLineNumber === -1) {
        return;
      }
      if (!this._visibleLines.getVisibleLine(longestLineNumber).monospaceAssumptionsAreValid()) {
        for (let lineNumber = rendStartLineNumber; lineNumber <= rendEndLineNumber; lineNumber++) {
          const visibleLine = this._visibleLines.getVisibleLine(lineNumber);
          visibleLine.onMonospaceAssumptionsInvalidated();
        }
      }
    }
    prepareRender() {
      throw new Error("Not supported");
    }
    render() {
      throw new Error("Not supported");
    }
    renderText(viewportData) {
      this._visibleLines.renderLines(viewportData);
      this._lastRenderedData.setCurrentVisibleRange(viewportData.visibleRange);
      this.domNode.setWidth(this._context.viewLayout.getScrollWidth());
      this.domNode.setHeight(Math.min(this._context.viewLayout.getScrollHeight(), 1e6));
      if (this._horizontalRevealRequest) {
        const horizontalRevealRequest = this._horizontalRevealRequest;
        if (viewportData.startLineNumber <= horizontalRevealRequest.minLineNumber && horizontalRevealRequest.maxLineNumber <= viewportData.endLineNumber) {
          this._horizontalRevealRequest = null;
          this.onDidRender();
          const newScrollLeft = this._computeScrollLeftToReveal(horizontalRevealRequest);
          if (newScrollLeft) {
            if (!this._isViewportWrapping && !newScrollLeft.hasRTL) {
              this._ensureMaxLineWidth(newScrollLeft.maxHorizontalOffset);
            }
            this._context.viewModel.viewLayout.setScrollPosition({
              scrollLeft: newScrollLeft.scrollLeft
            }, horizontalRevealRequest.scrollType);
          }
        }
      }
      if (!this._updateLineWidthsFast()) {
        this._asyncUpdateLineWidths.schedule();
      } else {
        this._asyncUpdateLineWidths.cancel();
      }
      if (isLinux && !this._asyncCheckMonospaceFontAssumptions.isScheduled()) {
        const rendStartLineNumber = this._visibleLines.getStartLineNumber();
        const rendEndLineNumber = this._visibleLines.getEndLineNumber();
        for (let lineNumber = rendStartLineNumber; lineNumber <= rendEndLineNumber; lineNumber++) {
          const visibleLine = this._visibleLines.getVisibleLine(lineNumber);
          if (visibleLine.needsMonospaceFontCheck()) {
            this._asyncCheckMonospaceFontAssumptions.schedule();
            break;
          }
        }
      }
      this._linesContent.setLayerHinting(this._canUseLayerHinting);
      this._linesContent.setContain("strict");
      const adjustedScrollTop = this._context.viewLayout.getCurrentScrollTop() - viewportData.bigNumbersDelta;
      this._linesContent.setTop(-adjustedScrollTop);
      this._linesContent.setLeft(-this._context.viewLayout.getCurrentScrollLeft());
    }
    // --- width
    _ensureMaxLineWidth(lineWidth) {
      const iLineWidth = Math.ceil(lineWidth);
      if (this._maxLineWidth < iLineWidth) {
        this._maxLineWidth = iLineWidth;
        this._context.viewModel.viewLayout.setMaxLineWidth(this._maxLineWidth);
      }
    }
    _computeScrollTopToRevealRange(viewport, source, minimalReveal, range2, selections, verticalType) {
      const viewportStartY = viewport.top;
      const viewportHeight = viewport.height;
      const viewportEndY = viewportStartY + viewportHeight;
      let boxIsSingleRange;
      let boxStartY;
      let boxEndY;
      if (selections && selections.length > 0) {
        let minLineNumber = selections[0].startLineNumber;
        let maxLineNumber = selections[0].endLineNumber;
        for (let i2 = 1, len = selections.length; i2 < len; i2++) {
          const selection = selections[i2];
          minLineNumber = Math.min(minLineNumber, selection.startLineNumber);
          maxLineNumber = Math.max(maxLineNumber, selection.endLineNumber);
        }
        boxIsSingleRange = false;
        boxStartY = this._context.viewLayout.getVerticalOffsetForLineNumber(minLineNumber);
        boxEndY = this._context.viewLayout.getVerticalOffsetForLineNumber(maxLineNumber) + this._lineHeight;
      } else if (range2) {
        boxIsSingleRange = true;
        boxStartY = this._context.viewLayout.getVerticalOffsetForLineNumber(range2.startLineNumber);
        boxEndY = this._context.viewLayout.getVerticalOffsetForLineNumber(range2.endLineNumber) + this._lineHeight;
      } else {
        return -1;
      }
      const shouldIgnoreScrollOff = (source === "mouse" || minimalReveal) && this._cursorSurroundingLinesStyle === "default";
      let paddingTop = 0;
      let paddingBottom = 0;
      if (!shouldIgnoreScrollOff) {
        const maxLinesInViewport = viewportHeight / this._lineHeight;
        const surroundingLines = Math.max(this._cursorSurroundingLines, this._stickyScrollEnabled ? this._maxNumberStickyLines : 0);
        const context = Math.min(maxLinesInViewport / 2, surroundingLines);
        paddingTop = context * this._lineHeight;
        paddingBottom = Math.max(0, context - 1) * this._lineHeight;
      } else {
        if (!minimalReveal) {
          paddingTop = this._lineHeight;
        }
      }
      if (!minimalReveal) {
        if (verticalType === 0 || verticalType === 4) {
          paddingBottom += this._lineHeight;
        }
      }
      boxStartY -= paddingTop;
      boxEndY += paddingBottom;
      let newScrollTop;
      if (boxEndY - boxStartY > viewportHeight) {
        if (!boxIsSingleRange) {
          return -1;
        }
        newScrollTop = boxStartY;
      } else if (verticalType === 5 || verticalType === 6) {
        if (verticalType === 6 && viewportStartY <= boxStartY && boxEndY <= viewportEndY) {
          newScrollTop = viewportStartY;
        } else {
          const desiredGapAbove = Math.max(5 * this._lineHeight, viewportHeight * 0.2);
          const desiredScrollTop = boxStartY - desiredGapAbove;
          const minScrollTop = boxEndY - viewportHeight;
          newScrollTop = Math.max(minScrollTop, desiredScrollTop);
        }
      } else if (verticalType === 1 || verticalType === 2) {
        if (verticalType === 2 && viewportStartY <= boxStartY && boxEndY <= viewportEndY) {
          newScrollTop = viewportStartY;
        } else {
          const boxMiddleY = (boxStartY + boxEndY) / 2;
          newScrollTop = Math.max(0, boxMiddleY - viewportHeight / 2);
        }
      } else {
        newScrollTop = this._computeMinimumScrolling(
          viewportStartY,
          viewportEndY,
          boxStartY,
          boxEndY,
          verticalType === 3,
          verticalType === 4
          /* viewEvents.VerticalRevealType.Bottom */
        );
      }
      return newScrollTop;
    }
    _computeScrollLeftToReveal(horizontalRevealRequest) {
      const viewport = this._context.viewLayout.getCurrentViewport();
      const layoutInfo = this._context.configuration.options.get(
        165
        /* EditorOption.layoutInfo */
      );
      const viewportStartX = viewport.left;
      const viewportEndX = viewportStartX + viewport.width - layoutInfo.verticalScrollbarWidth;
      let boxStartX = 1073741824;
      let boxEndX = 0;
      let hasRTL = false;
      if (horizontalRevealRequest.type === "range") {
        hasRTL = this._lineIsRenderedRTL(horizontalRevealRequest.lineNumber);
        const visibleRanges = this._visibleRangesForLineRange(horizontalRevealRequest.lineNumber, horizontalRevealRequest.startColumn, horizontalRevealRequest.endColumn);
        if (!visibleRanges) {
          return null;
        }
        for (const visibleRange of visibleRanges.ranges) {
          boxStartX = Math.min(boxStartX, Math.round(visibleRange.left));
          boxEndX = Math.max(boxEndX, Math.round(visibleRange.left + visibleRange.width));
        }
      } else {
        for (const selection of horizontalRevealRequest.selections) {
          if (selection.startLineNumber !== selection.endLineNumber) {
            return null;
          }
          const visibleRanges = this._visibleRangesForLineRange(selection.startLineNumber, selection.startColumn, selection.endColumn);
          hasRTL ||= this._lineIsRenderedRTL(selection.startLineNumber);
          if (!visibleRanges) {
            return null;
          }
          for (const visibleRange of visibleRanges.ranges) {
            boxStartX = Math.min(boxStartX, Math.round(visibleRange.left));
            boxEndX = Math.max(boxEndX, Math.round(visibleRange.left + visibleRange.width));
          }
        }
      }
      if (!horizontalRevealRequest.minimalReveal) {
        boxStartX = Math.max(0, boxStartX - _ViewLines.HORIZONTAL_EXTRA_PX);
        boxEndX += this._revealHorizontalRightPadding;
      }
      if (horizontalRevealRequest.type === "selections" && boxEndX - boxStartX > viewport.width) {
        return null;
      }
      const newScrollLeft = this._computeMinimumScrolling(viewportStartX, viewportEndX, boxStartX, boxEndX);
      return {
        scrollLeft: newScrollLeft,
        maxHorizontalOffset: boxEndX,
        hasRTL
      };
    }
    _computeMinimumScrolling(viewportStart, viewportEnd, boxStart, boxEnd, revealAtStart, revealAtEnd) {
      viewportStart = viewportStart | 0;
      viewportEnd = viewportEnd | 0;
      boxStart = boxStart | 0;
      boxEnd = boxEnd | 0;
      revealAtStart = !!revealAtStart;
      revealAtEnd = !!revealAtEnd;
      const viewportLength = viewportEnd - viewportStart;
      const boxLength = boxEnd - boxStart;
      if (boxLength < viewportLength) {
        if (revealAtStart) {
          return boxStart;
        }
        if (revealAtEnd) {
          return Math.max(0, boxEnd - viewportLength);
        }
        if (boxStart < viewportStart) {
          return boxStart;
        } else if (boxEnd > viewportEnd) {
          return Math.max(0, boxEnd - viewportLength);
        }
      } else {
        return boxStart;
      }
      return viewportStart;
    }
  };
  _ViewLines.HORIZONTAL_EXTRA_PX = 30;
  let ViewLines = _ViewLines;
  class LinesDecorationsOverlay extends DedupOverlay {
    constructor(context) {
      super();
      this._context = context;
      const options = this._context.configuration.options;
      const layoutInfo = options.get(
        165
        /* EditorOption.layoutInfo */
      );
      this._decorationsLeft = layoutInfo.decorationsLeft;
      this._decorationsWidth = layoutInfo.decorationsWidth;
      this._renderResult = null;
      this._context.addEventHandler(this);
    }
    dispose() {
      this._context.removeEventHandler(this);
      this._renderResult = null;
      super.dispose();
    }
    // --- begin event handlers
    onConfigurationChanged(e) {
      const options = this._context.configuration.options;
      const layoutInfo = options.get(
        165
        /* EditorOption.layoutInfo */
      );
      this._decorationsLeft = layoutInfo.decorationsLeft;
      this._decorationsWidth = layoutInfo.decorationsWidth;
      return true;
    }
    onDecorationsChanged(e) {
      return true;
    }
    onFlushed(e) {
      return true;
    }
    onLinesChanged(e) {
      return true;
    }
    onLinesDeleted(e) {
      return true;
    }
    onLinesInserted(e) {
      return true;
    }
    onScrollChanged(e) {
      return e.scrollTopChanged;
    }
    onZonesChanged(e) {
      return true;
    }
    // --- end event handlers
    _getDecorations(ctx) {
      const decorations = ctx.getDecorationsInViewport();
      const r = [];
      let rLen = 0;
      for (let i2 = 0, len = decorations.length; i2 < len; i2++) {
        const d = decorations[i2];
        const linesDecorationsClassName = d.options.linesDecorationsClassName;
        const zIndex = d.options.zIndex;
        if (linesDecorationsClassName) {
          r[rLen++] = new DecorationToRender(d.range.startLineNumber, d.range.endLineNumber, linesDecorationsClassName, d.options.linesDecorationsTooltip ?? null, zIndex);
        }
        const firstLineDecorationClassName = d.options.firstLineDecorationClassName;
        if (firstLineDecorationClassName) {
          r[rLen++] = new DecorationToRender(d.range.startLineNumber, d.range.startLineNumber, firstLineDecorationClassName, d.options.linesDecorationsTooltip ?? null, zIndex);
        }
      }
      return r;
    }
    prepareRender(ctx) {
      const visibleStartLineNumber = ctx.visibleRange.startLineNumber;
      const visibleEndLineNumber = ctx.visibleRange.endLineNumber;
      const toRender = this._render(visibleStartLineNumber, visibleEndLineNumber, this._getDecorations(ctx));
      const left = this._decorationsLeft.toString();
      const width2 = this._decorationsWidth.toString();
      const common = '" style="left:' + left + "px;width:" + width2 + 'px;"></div>';
      const output = [];
      for (let lineNumber = visibleStartLineNumber; lineNumber <= visibleEndLineNumber; lineNumber++) {
        const lineIndex = lineNumber - visibleStartLineNumber;
        const decorations = toRender[lineIndex].getDecorations();
        let lineOutput = "";
        for (const decoration2 of decorations) {
          let addition = '<div class="cldr ' + decoration2.className;
          if (decoration2.tooltip !== null) {
            addition += '" title="' + decoration2.tooltip;
          }
          addition += common;
          lineOutput += addition;
        }
        output[lineIndex] = lineOutput;
      }
      this._renderResult = output;
    }
    render(startLineNumber, lineNumber) {
      if (!this._renderResult) {
        return "";
      }
      return this._renderResult[lineNumber - startLineNumber];
    }
  }
  const _Margin = class _Margin extends ViewPart {
    constructor(context) {
      super(context);
      const options = this._context.configuration.options;
      const layoutInfo = options.get(
        165
        /* EditorOption.layoutInfo */
      );
      this._canUseLayerHinting = !options.get(
        39
        /* EditorOption.disableLayerHinting */
      );
      this._contentLeft = layoutInfo.contentLeft;
      this._glyphMarginLeft = layoutInfo.glyphMarginLeft;
      this._glyphMarginWidth = layoutInfo.glyphMarginWidth;
      this._domNode = createFastDomNode(document.createElement("div"));
      this._domNode.setClassName(_Margin.OUTER_CLASS_NAME);
      this._domNode.setPosition("absolute");
      this._domNode.setAttribute("role", "presentation");
      this._domNode.setAttribute("aria-hidden", "true");
      this._glyphMarginBackgroundDomNode = createFastDomNode(document.createElement("div"));
      this._glyphMarginBackgroundDomNode.setClassName(_Margin.CLASS_NAME);
      this._domNode.appendChild(this._glyphMarginBackgroundDomNode);
    }
    dispose() {
      super.dispose();
    }
    getDomNode() {
      return this._domNode;
    }
    // --- begin event handlers
    onConfigurationChanged(e) {
      const options = this._context.configuration.options;
      const layoutInfo = options.get(
        165
        /* EditorOption.layoutInfo */
      );
      this._canUseLayerHinting = !options.get(
        39
        /* EditorOption.disableLayerHinting */
      );
      this._contentLeft = layoutInfo.contentLeft;
      this._glyphMarginLeft = layoutInfo.glyphMarginLeft;
      this._glyphMarginWidth = layoutInfo.glyphMarginWidth;
      return true;
    }
    onScrollChanged(e) {
      return super.onScrollChanged(e) || e.scrollTopChanged;
    }
    // --- end event handlers
    prepareRender(ctx) {
    }
    render(ctx) {
      this._domNode.setLayerHinting(this._canUseLayerHinting);
      this._domNode.setContain("strict");
      const adjustedScrollTop = ctx.scrollTop - ctx.bigNumbersDelta;
      this._domNode.setTop(-adjustedScrollTop);
      const height = Math.min(ctx.scrollHeight, 1e6);
      this._domNode.setHeight(height);
      this._domNode.setWidth(this._contentLeft);
      this._glyphMarginBackgroundDomNode.setLeft(this._glyphMarginLeft);
      this._glyphMarginBackgroundDomNode.setWidth(this._glyphMarginWidth);
      this._glyphMarginBackgroundDomNode.setHeight(height);
    }
  };
  _Margin.CLASS_NAME = "glyph-margin";
  _Margin.OUTER_CLASS_NAME = "margin";
  let Margin = _Margin;
  class MarginViewLineDecorationsOverlay extends DedupOverlay {
    constructor(context) {
      super();
      this._context = context;
      this._renderResult = null;
      this._context.addEventHandler(this);
    }
    dispose() {
      this._context.removeEventHandler(this);
      this._renderResult = null;
      super.dispose();
    }
    // --- begin event handlers
    onConfigurationChanged(e) {
      return true;
    }
    onDecorationsChanged(e) {
      return true;
    }
    onFlushed(e) {
      return true;
    }
    onLinesChanged(e) {
      return true;
    }
    onLinesDeleted(e) {
      return true;
    }
    onLinesInserted(e) {
      return true;
    }
    onScrollChanged(e) {
      return e.scrollTopChanged;
    }
    onZonesChanged(e) {
      return true;
    }
    // --- end event handlers
    _getDecorations(ctx) {
      const decorations = ctx.getDecorationsInViewport();
      const r = [];
      let rLen = 0;
      for (let i2 = 0, len = decorations.length; i2 < len; i2++) {
        const d = decorations[i2];
        const marginClassName = d.options.marginClassName;
        const zIndex = d.options.zIndex;
        if (marginClassName) {
          r[rLen++] = new DecorationToRender(d.range.startLineNumber, d.range.endLineNumber, marginClassName, null, zIndex);
        }
      }
      return r;
    }
    prepareRender(ctx) {
      const visibleStartLineNumber = ctx.visibleRange.startLineNumber;
      const visibleEndLineNumber = ctx.visibleRange.endLineNumber;
      const toRender = this._render(visibleStartLineNumber, visibleEndLineNumber, this._getDecorations(ctx));
      const output = [];
      for (let lineNumber = visibleStartLineNumber; lineNumber <= visibleEndLineNumber; lineNumber++) {
        const lineIndex = lineNumber - visibleStartLineNumber;
        const decorations = toRender[lineIndex].getDecorations();
        let lineOutput = "";
        for (const decoration2 of decorations) {
          lineOutput += '<div class="cmdr ' + decoration2.className + '" style=""></div>';
        }
        output[lineIndex] = lineOutput;
      }
      this._renderResult = output;
    }
    render(startLineNumber, lineNumber) {
      if (!this._renderResult) {
        return "";
      }
      return this._renderResult[lineNumber - startLineNumber];
    }
  }
  const _RGBA8 = class _RGBA8 {
    constructor(r, g, b, a) {
      this._rgba8Brand = void 0;
      this.r = _RGBA8._clamp(r);
      this.g = _RGBA8._clamp(g);
      this.b = _RGBA8._clamp(b);
      this.a = _RGBA8._clamp(a);
    }
    equals(other) {
      return this.r === other.r && this.g === other.g && this.b === other.b && this.a === other.a;
    }
    static _clamp(c) {
      if (c < 0) {
        return 0;
      }
      if (c > 255) {
        return 255;
      }
      return c | 0;
    }
  };
  _RGBA8.Empty = new _RGBA8(0, 0, 0, 0);
  let RGBA8 = _RGBA8;
  let TokenizationRegistry$1 = class TokenizationRegistry {
    constructor() {
      this._tokenizationSupports = /* @__PURE__ */ new Map();
      this._factories = /* @__PURE__ */ new Map();
      this._onDidChange = new Emitter$1();
      this.onDidChange = this._onDidChange.event;
      this._colorMap = null;
    }
    handleChange(languageIds) {
      this._onDidChange.fire({
        changedLanguages: languageIds,
        changedColorMap: false
      });
    }
    register(languageId, support) {
      this._tokenizationSupports.set(languageId, support);
      this.handleChange([languageId]);
      return toDisposable(() => {
        if (this._tokenizationSupports.get(languageId) !== support) {
          return;
        }
        this._tokenizationSupports.delete(languageId);
        this.handleChange([languageId]);
      });
    }
    get(languageId) {
      return this._tokenizationSupports.get(languageId) || null;
    }
    registerFactory(languageId, factory) {
      this._factories.get(languageId)?.dispose();
      const myData = new TokenizationSupportFactoryData(this, languageId, factory);
      this._factories.set(languageId, myData);
      return toDisposable(() => {
        const v = this._factories.get(languageId);
        if (!v || v !== myData) {
          return;
        }
        this._factories.delete(languageId);
        v.dispose();
      });
    }
    async getOrCreate(languageId) {
      const tokenizationSupport = this.get(languageId);
      if (tokenizationSupport) {
        return tokenizationSupport;
      }
      const factory = this._factories.get(languageId);
      if (!factory || factory.isResolved) {
        return null;
      }
      await factory.resolve();
      return this.get(languageId);
    }
    isResolved(languageId) {
      const tokenizationSupport = this.get(languageId);
      if (tokenizationSupport) {
        return true;
      }
      const factory = this._factories.get(languageId);
      if (!factory || factory.isResolved) {
        return true;
      }
      return false;
    }
    setColorMap(colorMap) {
      this._colorMap = colorMap;
      this._onDidChange.fire({
        changedLanguages: Array.from(this._tokenizationSupports.keys()),
        changedColorMap: true
      });
    }
    getColorMap() {
      return this._colorMap;
    }
    getDefaultBackground() {
      if (this._colorMap && this._colorMap.length > 2) {
        return this._colorMap[
          2
          /* ColorId.DefaultBackground */
        ];
      }
      return null;
    }
  };
  class TokenizationSupportFactoryData extends Disposable {
    get isResolved() {
      return this._isResolved;
    }
    constructor(_registry2, _languageId, _factory) {
      super();
      this._registry = _registry2;
      this._languageId = _languageId;
      this._factory = _factory;
      this._isDisposed = false;
      this._resolvePromise = null;
      this._isResolved = false;
    }
    dispose() {
      this._isDisposed = true;
      super.dispose();
    }
    async resolve() {
      if (!this._resolvePromise) {
        this._resolvePromise = this._create();
      }
      return this._resolvePromise;
    }
    async _create() {
      const value = await this._factory.tokenizationSupport;
      this._isResolved = true;
      if (value && !this._isDisposed) {
        this._register(this._registry.register(this._languageId, value));
      }
    }
  }
  let Token$2 = class Token {
    constructor(offset, type, language2) {
      this.offset = offset;
      this.type = type;
      this.language = language2;
      this._tokenBrand = void 0;
    }
    toString() {
      return "(" + this.offset + ", " + this.type + ")";
    }
  };
  class TokenizationResult {
    constructor(tokens, endState) {
      this.tokens = tokens;
      this.endState = endState;
      this._tokenizationResultBrand = void 0;
    }
  }
  class EncodedTokenizationResult {
    constructor(tokens, endState) {
      this.tokens = tokens;
      this.endState = endState;
      this._encodedTokenizationResultBrand = void 0;
    }
  }
  var HoverVerbosityAction$1;
  (function(HoverVerbosityAction2) {
    HoverVerbosityAction2[HoverVerbosityAction2["Increase"] = 0] = "Increase";
    HoverVerbosityAction2[HoverVerbosityAction2["Decrease"] = 1] = "Decrease";
  })(HoverVerbosityAction$1 || (HoverVerbosityAction$1 = {}));
  var CompletionItemKinds;
  (function(CompletionItemKinds2) {
    const byKind = /* @__PURE__ */ new Map();
    byKind.set(0, Codicon.symbolMethod);
    byKind.set(1, Codicon.symbolFunction);
    byKind.set(2, Codicon.symbolConstructor);
    byKind.set(3, Codicon.symbolField);
    byKind.set(4, Codicon.symbolVariable);
    byKind.set(5, Codicon.symbolClass);
    byKind.set(6, Codicon.symbolStruct);
    byKind.set(7, Codicon.symbolInterface);
    byKind.set(8, Codicon.symbolModule);
    byKind.set(9, Codicon.symbolProperty);
    byKind.set(10, Codicon.symbolEvent);
    byKind.set(11, Codicon.symbolOperator);
    byKind.set(12, Codicon.symbolUnit);
    byKind.set(13, Codicon.symbolValue);
    byKind.set(15, Codicon.symbolEnum);
    byKind.set(14, Codicon.symbolConstant);
    byKind.set(15, Codicon.symbolEnum);
    byKind.set(16, Codicon.symbolEnumMember);
    byKind.set(17, Codicon.symbolKeyword);
    byKind.set(28, Codicon.symbolSnippet);
    byKind.set(18, Codicon.symbolText);
    byKind.set(19, Codicon.symbolColor);
    byKind.set(20, Codicon.symbolFile);
    byKind.set(21, Codicon.symbolReference);
    byKind.set(22, Codicon.symbolCustomColor);
    byKind.set(23, Codicon.symbolFolder);
    byKind.set(24, Codicon.symbolTypeParameter);
    byKind.set(25, Codicon.account);
    byKind.set(26, Codicon.issues);
    byKind.set(27, Codicon.tools);
    function toIcon(kind) {
      let codicon = byKind.get(kind);
      if (!codicon) {
        console.info("No codicon found for CompletionItemKind " + kind);
        codicon = Codicon.symbolProperty;
      }
      return codicon;
    }
    CompletionItemKinds2.toIcon = toIcon;
    function toLabel(kind) {
      switch (kind) {
        case 0:
          return localize(728, "Method");
        case 1:
          return localize(729, "Function");
        case 2:
          return localize(730, "Constructor");
        case 3:
          return localize(731, "Field");
        case 4:
          return localize(732, "Variable");
        case 5:
          return localize(733, "Class");
        case 6:
          return localize(734, "Struct");
        case 7:
          return localize(735, "Interface");
        case 8:
          return localize(736, "Module");
        case 9:
          return localize(737, "Property");
        case 10:
          return localize(738, "Event");
        case 11:
          return localize(739, "Operator");
        case 12:
          return localize(740, "Unit");
        case 13:
          return localize(741, "Value");
        case 14:
          return localize(742, "Constant");
        case 15:
          return localize(743, "Enum");
        case 16:
          return localize(744, "Enum Member");
        case 17:
          return localize(745, "Keyword");
        case 18:
          return localize(746, "Text");
        case 19:
          return localize(747, "Color");
        case 20:
          return localize(748, "File");
        case 21:
          return localize(749, "Reference");
        case 22:
          return localize(750, "Custom Color");
        case 23:
          return localize(751, "Folder");
        case 24:
          return localize(752, "Type Parameter");
        case 25:
          return localize(753, "User");
        case 26:
          return localize(754, "Issue");
        case 27:
          return localize(755, "Tool");
        case 28:
          return localize(756, "Snippet");
        default:
          return "";
      }
    }
    CompletionItemKinds2.toLabel = toLabel;
    const data = /* @__PURE__ */ new Map();
    data.set(
      "method",
      0
      /* CompletionItemKind.Method */
    );
    data.set(
      "function",
      1
      /* CompletionItemKind.Function */
    );
    data.set(
      "constructor",
      2
      /* CompletionItemKind.Constructor */
    );
    data.set(
      "field",
      3
      /* CompletionItemKind.Field */
    );
    data.set(
      "variable",
      4
      /* CompletionItemKind.Variable */
    );
    data.set(
      "class",
      5
      /* CompletionItemKind.Class */
    );
    data.set(
      "struct",
      6
      /* CompletionItemKind.Struct */
    );
    data.set(
      "interface",
      7
      /* CompletionItemKind.Interface */
    );
    data.set(
      "module",
      8
      /* CompletionItemKind.Module */
    );
    data.set(
      "property",
      9
      /* CompletionItemKind.Property */
    );
    data.set(
      "event",
      10
      /* CompletionItemKind.Event */
    );
    data.set(
      "operator",
      11
      /* CompletionItemKind.Operator */
    );
    data.set(
      "unit",
      12
      /* CompletionItemKind.Unit */
    );
    data.set(
      "value",
      13
      /* CompletionItemKind.Value */
    );
    data.set(
      "constant",
      14
      /* CompletionItemKind.Constant */
    );
    data.set(
      "enum",
      15
      /* CompletionItemKind.Enum */
    );
    data.set(
      "enum-member",
      16
      /* CompletionItemKind.EnumMember */
    );
    data.set(
      "enumMember",
      16
      /* CompletionItemKind.EnumMember */
    );
    data.set(
      "keyword",
      17
      /* CompletionItemKind.Keyword */
    );
    data.set(
      "snippet",
      28
      /* CompletionItemKind.Snippet */
    );
    data.set(
      "text",
      18
      /* CompletionItemKind.Text */
    );
    data.set(
      "color",
      19
      /* CompletionItemKind.Color */
    );
    data.set(
      "file",
      20
      /* CompletionItemKind.File */
    );
    data.set(
      "reference",
      21
      /* CompletionItemKind.Reference */
    );
    data.set(
      "customcolor",
      22
      /* CompletionItemKind.Customcolor */
    );
    data.set(
      "folder",
      23
      /* CompletionItemKind.Folder */
    );
    data.set(
      "type-parameter",
      24
      /* CompletionItemKind.TypeParameter */
    );
    data.set(
      "typeParameter",
      24
      /* CompletionItemKind.TypeParameter */
    );
    data.set(
      "account",
      25
      /* CompletionItemKind.User */
    );
    data.set(
      "issue",
      26
      /* CompletionItemKind.Issue */
    );
    data.set(
      "tool",
      27
      /* CompletionItemKind.Tool */
    );
    function fromString(value, strict) {
      let res = data.get(value);
      if (typeof res === "undefined" && !strict) {
        res = 9;
      }
      return res;
    }
    CompletionItemKinds2.fromString = fromString;
  })(CompletionItemKinds || (CompletionItemKinds = {}));
  var InlineCompletionTriggerKind$1;
  (function(InlineCompletionTriggerKind2) {
    InlineCompletionTriggerKind2[InlineCompletionTriggerKind2["Automatic"] = 0] = "Automatic";
    InlineCompletionTriggerKind2[InlineCompletionTriggerKind2["Explicit"] = 1] = "Explicit";
  })(InlineCompletionTriggerKind$1 || (InlineCompletionTriggerKind$1 = {}));
  class SelectedSuggestionInfo {
    constructor(range2, text2, completionKind, isSnippetText) {
      this.range = range2;
      this.text = text2;
      this.completionKind = completionKind;
      this.isSnippetText = isSnippetText;
    }
    equals(other) {
      return Range$2.lift(this.range).equalsRange(other.range) && this.text === other.text && this.completionKind === other.completionKind && this.isSnippetText === other.isSnippetText;
    }
  }
  var InlineCompletionHintStyle$1;
  (function(InlineCompletionHintStyle2) {
    InlineCompletionHintStyle2[InlineCompletionHintStyle2["Code"] = 1] = "Code";
    InlineCompletionHintStyle2[InlineCompletionHintStyle2["Label"] = 2] = "Label";
  })(InlineCompletionHintStyle$1 || (InlineCompletionHintStyle$1 = {}));
  class ProviderId {
    static fromExtensionId(extensionId) {
      return new ProviderId(extensionId, void 0, void 0);
    }
    constructor(extensionId, extensionVersion, providerId) {
      this.extensionId = extensionId;
      this.extensionVersion = extensionVersion;
      this.providerId = providerId;
    }
    toString() {
      let result = "";
      if (this.extensionId) {
        result += this.extensionId;
      }
      if (this.extensionVersion) {
        result += `@${this.extensionVersion}`;
      }
      if (this.providerId) {
        result += `:${this.providerId}`;
      }
      if (result.length === 0) {
        result = "unknown";
      }
      return result;
    }
    toStringWithoutVersion() {
      let result = "";
      if (this.extensionId) {
        result += this.extensionId;
      }
      if (this.providerId) {
        result += `:${this.providerId}`;
      }
      return result;
    }
  }
  var InlineCompletionEndOfLifeReasonKind$1;
  (function(InlineCompletionEndOfLifeReasonKind2) {
    InlineCompletionEndOfLifeReasonKind2[InlineCompletionEndOfLifeReasonKind2["Accepted"] = 0] = "Accepted";
    InlineCompletionEndOfLifeReasonKind2[InlineCompletionEndOfLifeReasonKind2["Rejected"] = 1] = "Rejected";
    InlineCompletionEndOfLifeReasonKind2[InlineCompletionEndOfLifeReasonKind2["Ignored"] = 2] = "Ignored";
  })(InlineCompletionEndOfLifeReasonKind$1 || (InlineCompletionEndOfLifeReasonKind$1 = {}));
  var DocumentPasteTriggerKind;
  (function(DocumentPasteTriggerKind2) {
    DocumentPasteTriggerKind2[DocumentPasteTriggerKind2["Automatic"] = 0] = "Automatic";
    DocumentPasteTriggerKind2[DocumentPasteTriggerKind2["PasteAs"] = 1] = "PasteAs";
  })(DocumentPasteTriggerKind || (DocumentPasteTriggerKind = {}));
  var SignatureHelpTriggerKind$1;
  (function(SignatureHelpTriggerKind2) {
    SignatureHelpTriggerKind2[SignatureHelpTriggerKind2["Invoke"] = 1] = "Invoke";
    SignatureHelpTriggerKind2[SignatureHelpTriggerKind2["TriggerCharacter"] = 2] = "TriggerCharacter";
    SignatureHelpTriggerKind2[SignatureHelpTriggerKind2["ContentChange"] = 3] = "ContentChange";
  })(SignatureHelpTriggerKind$1 || (SignatureHelpTriggerKind$1 = {}));
  var DocumentHighlightKind$1;
  (function(DocumentHighlightKind2) {
    DocumentHighlightKind2[DocumentHighlightKind2["Text"] = 0] = "Text";
    DocumentHighlightKind2[DocumentHighlightKind2["Read"] = 1] = "Read";
    DocumentHighlightKind2[DocumentHighlightKind2["Write"] = 2] = "Write";
  })(DocumentHighlightKind$1 || (DocumentHighlightKind$1 = {}));
  function isLocationLink(thing) {
    return !!thing && URI.isUri(thing.uri) && Range$2.isIRange(thing.range) && (Range$2.isIRange(thing.originSelectionRange) || Range$2.isIRange(thing.targetSelectionRange));
  }
  const symbolKindNames = {
    [
      17
      /* SymbolKind.Array */
    ]: localize(757, "array"),
    [
      16
      /* SymbolKind.Boolean */
    ]: localize(758, "boolean"),
    [
      4
      /* SymbolKind.Class */
    ]: localize(759, "class"),
    [
      13
      /* SymbolKind.Constant */
    ]: localize(760, "constant"),
    [
      8
      /* SymbolKind.Constructor */
    ]: localize(761, "constructor"),
    [
      9
      /* SymbolKind.Enum */
    ]: localize(762, "enumeration"),
    [
      21
      /* SymbolKind.EnumMember */
    ]: localize(763, "enumeration member"),
    [
      23
      /* SymbolKind.Event */
    ]: localize(764, "event"),
    [
      7
      /* SymbolKind.Field */
    ]: localize(765, "field"),
    [
      0
      /* SymbolKind.File */
    ]: localize(766, "file"),
    [
      11
      /* SymbolKind.Function */
    ]: localize(767, "function"),
    [
      10
      /* SymbolKind.Interface */
    ]: localize(768, "interface"),
    [
      19
      /* SymbolKind.Key */
    ]: localize(769, "key"),
    [
      5
      /* SymbolKind.Method */
    ]: localize(770, "method"),
    [
      1
      /* SymbolKind.Module */
    ]: localize(771, "module"),
    [
      2
      /* SymbolKind.Namespace */
    ]: localize(772, "namespace"),
    [
      20
      /* SymbolKind.Null */
    ]: localize(773, "null"),
    [
      15
      /* SymbolKind.Number */
    ]: localize(774, "number"),
    [
      18
      /* SymbolKind.Object */
    ]: localize(775, "object"),
    [
      24
      /* SymbolKind.Operator */
    ]: localize(776, "operator"),
    [
      3
      /* SymbolKind.Package */
    ]: localize(777, "package"),
    [
      6
      /* SymbolKind.Property */
    ]: localize(778, "property"),
    [
      14
      /* SymbolKind.String */
    ]: localize(779, "string"),
    [
      22
      /* SymbolKind.Struct */
    ]: localize(780, "struct"),
    [
      25
      /* SymbolKind.TypeParameter */
    ]: localize(781, "type parameter"),
    [
      12
      /* SymbolKind.Variable */
    ]: localize(782, "variable")
  };
  function getAriaLabelForSymbol(symbolName, kind) {
    return localize(783, "{0} ({1})", symbolName, symbolKindNames[kind]);
  }
  var SymbolKinds;
  (function(SymbolKinds2) {
    const byKind = /* @__PURE__ */ new Map();
    byKind.set(0, Codicon.symbolFile);
    byKind.set(1, Codicon.symbolModule);
    byKind.set(2, Codicon.symbolNamespace);
    byKind.set(3, Codicon.symbolPackage);
    byKind.set(4, Codicon.symbolClass);
    byKind.set(5, Codicon.symbolMethod);
    byKind.set(6, Codicon.symbolProperty);
    byKind.set(7, Codicon.symbolField);
    byKind.set(8, Codicon.symbolConstructor);
    byKind.set(9, Codicon.symbolEnum);
    byKind.set(10, Codicon.symbolInterface);
    byKind.set(11, Codicon.symbolFunction);
    byKind.set(12, Codicon.symbolVariable);
    byKind.set(13, Codicon.symbolConstant);
    byKind.set(14, Codicon.symbolString);
    byKind.set(15, Codicon.symbolNumber);
    byKind.set(16, Codicon.symbolBoolean);
    byKind.set(17, Codicon.symbolArray);
    byKind.set(18, Codicon.symbolObject);
    byKind.set(19, Codicon.symbolKey);
    byKind.set(20, Codicon.symbolNull);
    byKind.set(21, Codicon.symbolEnumMember);
    byKind.set(22, Codicon.symbolStruct);
    byKind.set(23, Codicon.symbolEvent);
    byKind.set(24, Codicon.symbolOperator);
    byKind.set(25, Codicon.symbolTypeParameter);
    function toIcon(kind) {
      let icon = byKind.get(kind);
      if (!icon) {
        console.info("No codicon found for SymbolKind " + kind);
        icon = Codicon.symbolProperty;
      }
      return icon;
    }
    SymbolKinds2.toIcon = toIcon;
    const byCompletionKind = /* @__PURE__ */ new Map();
    byCompletionKind.set(
      0,
      20
      /* CompletionItemKind.File */
    );
    byCompletionKind.set(
      1,
      8
      /* CompletionItemKind.Module */
    );
    byCompletionKind.set(
      2,
      8
      /* CompletionItemKind.Module */
    );
    byCompletionKind.set(
      3,
      8
      /* CompletionItemKind.Module */
    );
    byCompletionKind.set(
      4,
      5
      /* CompletionItemKind.Class */
    );
    byCompletionKind.set(
      5,
      0
      /* CompletionItemKind.Method */
    );
    byCompletionKind.set(
      6,
      9
      /* CompletionItemKind.Property */
    );
    byCompletionKind.set(
      7,
      3
      /* CompletionItemKind.Field */
    );
    byCompletionKind.set(
      8,
      2
      /* CompletionItemKind.Constructor */
    );
    byCompletionKind.set(
      9,
      15
      /* CompletionItemKind.Enum */
    );
    byCompletionKind.set(
      10,
      7
      /* CompletionItemKind.Interface */
    );
    byCompletionKind.set(
      11,
      1
      /* CompletionItemKind.Function */
    );
    byCompletionKind.set(
      12,
      4
      /* CompletionItemKind.Variable */
    );
    byCompletionKind.set(
      13,
      14
      /* CompletionItemKind.Constant */
    );
    byCompletionKind.set(
      14,
      18
      /* CompletionItemKind.Text */
    );
    byCompletionKind.set(
      15,
      13
      /* CompletionItemKind.Value */
    );
    byCompletionKind.set(
      16,
      13
      /* CompletionItemKind.Value */
    );
    byCompletionKind.set(
      17,
      13
      /* CompletionItemKind.Value */
    );
    byCompletionKind.set(
      18,
      13
      /* CompletionItemKind.Value */
    );
    byCompletionKind.set(
      19,
      17
      /* CompletionItemKind.Keyword */
    );
    byCompletionKind.set(
      20,
      13
      /* CompletionItemKind.Value */
    );
    byCompletionKind.set(
      21,
      16
      /* CompletionItemKind.EnumMember */
    );
    byCompletionKind.set(
      22,
      6
      /* CompletionItemKind.Struct */
    );
    byCompletionKind.set(
      23,
      10
      /* CompletionItemKind.Event */
    );
    byCompletionKind.set(
      24,
      11
      /* CompletionItemKind.Operator */
    );
    byCompletionKind.set(
      25,
      24
      /* CompletionItemKind.TypeParameter */
    );
    function toCompletionKind(kind) {
      let completionKind = byCompletionKind.get(kind);
      if (completionKind === void 0) {
        console.info("No completion kind found for SymbolKind " + kind);
        completionKind = 20;
      }
      return completionKind;
    }
    SymbolKinds2.toCompletionKind = toCompletionKind;
  })(SymbolKinds || (SymbolKinds = {}));
  const _FoldingRangeKind = class _FoldingRangeKind {
    /**
     * Returns a {@link FoldingRangeKind} for the given value.
     *
     * @param value of the kind.
     */
    static fromValue(value) {
      switch (value) {
        case "comment":
          return _FoldingRangeKind.Comment;
        case "imports":
          return _FoldingRangeKind.Imports;
        case "region":
          return _FoldingRangeKind.Region;
      }
      return new _FoldingRangeKind(value);
    }
    /**
     * Creates a new {@link FoldingRangeKind}.
     *
     * @param value of the kind.
     */
    constructor(value) {
      this.value = value;
    }
  };
  _FoldingRangeKind.Comment = new _FoldingRangeKind("comment");
  _FoldingRangeKind.Imports = new _FoldingRangeKind("imports");
  _FoldingRangeKind.Region = new _FoldingRangeKind("region");
  let FoldingRangeKind = _FoldingRangeKind;
  var NewSymbolNameTag$1;
  (function(NewSymbolNameTag2) {
    NewSymbolNameTag2[NewSymbolNameTag2["AIGenerated"] = 1] = "AIGenerated";
  })(NewSymbolNameTag$1 || (NewSymbolNameTag$1 = {}));
  var NewSymbolNameTriggerKind$1;
  (function(NewSymbolNameTriggerKind2) {
    NewSymbolNameTriggerKind2[NewSymbolNameTriggerKind2["Invoke"] = 0] = "Invoke";
    NewSymbolNameTriggerKind2[NewSymbolNameTriggerKind2["Automatic"] = 1] = "Automatic";
  })(NewSymbolNameTriggerKind$1 || (NewSymbolNameTriggerKind$1 = {}));
  var Command;
  (function(Command2) {
    function is(obj) {
      if (!obj || typeof obj !== "object") {
        return false;
      }
      return typeof obj.id === "string" && typeof obj.title === "string";
    }
    Command2.is = is;
  })(Command || (Command = {}));
  var InlayHintKind$1;
  (function(InlayHintKind2) {
    InlayHintKind2[InlayHintKind2["Type"] = 1] = "Type";
    InlayHintKind2[InlayHintKind2["Parameter"] = 2] = "Parameter";
  })(InlayHintKind$1 || (InlayHintKind$1 = {}));
  class LazyTokenizationSupport {
    constructor(createSupport) {
      this.createSupport = createSupport;
      this._tokenizationSupport = null;
    }
    dispose() {
      if (this._tokenizationSupport) {
        this._tokenizationSupport.then((support) => {
          if (support) {
            support.dispose();
          }
        });
      }
    }
    get tokenizationSupport() {
      if (!this._tokenizationSupport) {
        this._tokenizationSupport = this.createSupport();
      }
      return this._tokenizationSupport;
    }
  }
  const TokenizationRegistry = new TokenizationRegistry$1();
  const _MinimapTokensColorTracker = class _MinimapTokensColorTracker extends Disposable {
    static getInstance() {
      if (!this._INSTANCE) {
        this._INSTANCE = markAsSingleton(new _MinimapTokensColorTracker());
      }
      return this._INSTANCE;
    }
    constructor() {
      super();
      this._onDidChange = new Emitter$1();
      this.onDidChange = this._onDidChange.event;
      this._updateColorMap();
      this._register(TokenizationRegistry.onDidChange((e) => {
        if (e.changedColorMap) {
          this._updateColorMap();
        }
      }));
    }
    _updateColorMap() {
      const colorMap = TokenizationRegistry.getColorMap();
      if (!colorMap) {
        this._colors = [RGBA8.Empty];
        this._backgroundIsLight = true;
        return;
      }
      this._colors = [RGBA8.Empty];
      for (let colorId = 1; colorId < colorMap.length; colorId++) {
        const source = colorMap[colorId].rgba;
        this._colors[colorId] = new RGBA8(source.r, source.g, source.b, Math.round(source.a * 255));
      }
      const backgroundLuminosity = colorMap[
        2
        /* ColorId.DefaultBackground */
      ].getRelativeLuminance();
      this._backgroundIsLight = backgroundLuminosity >= 0.5;
      this._onDidChange.fire(void 0);
    }
    getColor(colorId) {
      if (colorId < 1 || colorId >= this._colors.length) {
        colorId = 2;
      }
      return this._colors[colorId];
    }
    backgroundIsLight() {
      return this._backgroundIsLight;
    }
  };
  _MinimapTokensColorTracker._INSTANCE = null;
  let MinimapTokensColorTracker = _MinimapTokensColorTracker;
  const allCharCodes = (() => {
    const v = [];
    for (let i2 = 32; i2 <= 126; i2++) {
      v.push(i2);
    }
    v.push(
      65533
      /* Constants.UNKNOWN_CODE */
    );
    return v;
  })();
  const getCharIndex = (chCode, fontScale) => {
    chCode -= 32;
    if (chCode < 0 || chCode > 96) {
      if (fontScale <= 2) {
        return (chCode + 96) % 96;
      }
      return 96 - 1;
    }
    return chCode;
  };
  class MinimapCharRenderer {
    constructor(charData, scale) {
      this.scale = scale;
      this._minimapCharRendererBrand = void 0;
      this.charDataNormal = MinimapCharRenderer.soften(charData, 12 / 15);
      this.charDataLight = MinimapCharRenderer.soften(charData, 50 / 60);
    }
    static soften(input, ratio) {
      const result = new Uint8ClampedArray(input.length);
      for (let i2 = 0, len = input.length; i2 < len; i2++) {
        result[i2] = toUint8(input[i2] * ratio);
      }
      return result;
    }
    renderChar(target, dx, dy, chCode, color, foregroundAlpha, backgroundColor, backgroundAlpha, fontScale, useLighterFont, force1pxHeight) {
      const charWidth = 1 * this.scale;
      const charHeight = 2 * this.scale;
      const renderHeight = force1pxHeight ? 1 : charHeight;
      if (dx + charWidth > target.width || dy + renderHeight > target.height) {
        console.warn("bad render request outside image data");
        return;
      }
      const charData = useLighterFont ? this.charDataLight : this.charDataNormal;
      const charIndex = getCharIndex(chCode, fontScale);
      const destWidth = target.width * 4;
      const backgroundR = backgroundColor.r;
      const backgroundG = backgroundColor.g;
      const backgroundB = backgroundColor.b;
      const deltaR = color.r - backgroundR;
      const deltaG = color.g - backgroundG;
      const deltaB = color.b - backgroundB;
      const destAlpha = Math.max(foregroundAlpha, backgroundAlpha);
      const dest = target.data;
      let sourceOffset = charIndex * charWidth * charHeight;
      let row = dy * destWidth + dx * 4;
      for (let y = 0; y < renderHeight; y++) {
        let column = row;
        for (let x = 0; x < charWidth; x++) {
          const c = charData[sourceOffset++] / 255 * (foregroundAlpha / 255);
          dest[column++] = backgroundR + deltaR * c;
          dest[column++] = backgroundG + deltaG * c;
          dest[column++] = backgroundB + deltaB * c;
          dest[column++] = destAlpha;
        }
        row += destWidth;
      }
    }
    blockRenderChar(target, dx, dy, color, foregroundAlpha, backgroundColor, backgroundAlpha, force1pxHeight) {
      const charWidth = 1 * this.scale;
      const charHeight = 2 * this.scale;
      const renderHeight = force1pxHeight ? 1 : charHeight;
      if (dx + charWidth > target.width || dy + renderHeight > target.height) {
        console.warn("bad render request outside image data");
        return;
      }
      const destWidth = target.width * 4;
      const c = 0.5 * (foregroundAlpha / 255);
      const backgroundR = backgroundColor.r;
      const backgroundG = backgroundColor.g;
      const backgroundB = backgroundColor.b;
      const deltaR = color.r - backgroundR;
      const deltaG = color.g - backgroundG;
      const deltaB = color.b - backgroundB;
      const colorR = backgroundR + deltaR * c;
      const colorG = backgroundG + deltaG * c;
      const colorB = backgroundB + deltaB * c;
      const destAlpha = Math.max(foregroundAlpha, backgroundAlpha);
      const dest = target.data;
      let row = dy * destWidth + dx * 4;
      for (let y = 0; y < renderHeight; y++) {
        let column = row;
        for (let x = 0; x < charWidth; x++) {
          dest[column++] = colorR;
          dest[column++] = colorG;
          dest[column++] = colorB;
          dest[column++] = destAlpha;
        }
        row += destWidth;
      }
    }
  }
  const charTable = {
    "0": 0,
    "1": 1,
    "2": 2,
    "3": 3,
    "4": 4,
    "5": 5,
    "6": 6,
    "7": 7,
    "8": 8,
    "9": 9,
    A: 10,
    B: 11,
    C: 12,
    D: 13,
    E: 14,
    F: 15
  };
  const decodeData = (str) => {
    const output = new Uint8ClampedArray(str.length / 2);
    for (let i2 = 0; i2 < str.length; i2 += 2) {
      output[i2 >> 1] = charTable[str[i2]] << 4 | charTable[str[i2 + 1]] & 15;
    }
    return output;
  };
  const prebakedMiniMaps = {
    1: createSingleCallFunction(() => decodeData("0000511D6300CF609C709645A78432005642574171487021003C451900274D35D762755E8B629C5BA856AF57BA649530C167D1512A272A3F6038604460398526BCA2A968DB6F8957C768BE5FBE2FB467CF5D8D5B795DC7625B5DFF50DE64C466DB2FC47CD860A65E9A2EB96CB54CE06DA763AB2EA26860524D3763536601005116008177A8705E53AB738E6A982F88BAA35B5F5B626D9C636B449B737E5B7B678598869A662F6B5B8542706C704C80736A607578685B70594A49715A4522E792")),
    2: createSingleCallFunction(() => decodeData("000000000000000055394F383D2800008B8B1F210002000081B1CBCBCC820000847AAF6B9AAF2119BE08B8881AD60000A44FD07DCCF107015338130C00000000385972265F390B406E2437634B4B48031B12B8A0847000001E15B29A402F0000000000004B33460B00007A752C2A0000000000004D3900000084394B82013400ABA5CFC7AD9C0302A45A3E5A98AB000089A43382D97900008BA54AA087A70A0248A6A7AE6DBE0000BF6F94987EA40A01A06DCFA7A7A9030496C32F77891D0000A99FB1A0AFA80603B29AB9CA75930D010C0948354D3900000C0948354F37460D0028BE673D8400000000AF9D7B6E00002B007AA8933400007AA642675C2700007984CFB9C3985B768772A8A6B7B20000CAAECAAFC4B700009F94A6009F840009D09F9BA4CA9C0000CC8FC76DC87F0000C991C472A2000000A894A48CA7B501079BA2C9C69BA20000B19A5D3FA89000005CA6009DA2960901B0A7F0669FB200009D009E00B7890000DAD0F5D092820000D294D4C48BD10000B5A7A4A3B1A50402CAB6CBA6A2000000B5A7A4A3B1A8044FCDADD19D9CB00000B7778F7B8AAE0803C9AB5D3F5D3F00009EA09EA0BAB006039EA0989A8C7900009B9EF4D6B7C00000A9A7816CACA80000ABAC84705D3F000096DA635CDC8C00006F486F266F263D4784006124097B00374F6D2D6D2D6D4A3A95872322000000030000000000008D8939130000000000002E22A5C9CBC70600AB25C0B5C9B400061A2DB04CA67001082AA6BEBEBFC606002321DACBC19E03087AA08B6768380000282FBAC0B8CA7A88AD25BBA5A29900004C396C5894A6000040485A6E356E9442A32CD17EADA70000B4237923628600003E2DE9C1D7B500002F25BBA5A2990000231DB6AFB4A804023025C0B5CAB588062B2CBDBEC0C706882435A75CA20000002326BD6A82A908048B4B9A5A668000002423A09CB4BB060025259C9D8A7900001C1FCAB2C7C700002A2A9387ABA200002626A4A47D6E9D14333163A0C87500004B6F9C2D643A257049364936493647358A34438355497F1A0000A24C1D590000D38DFFBDD4CD3126"))
  };
  class MinimapCharRendererFactory {
    /**
     * Creates a new character renderer factory with the given scale.
     */
    static create(scale, fontFamily) {
      if (this.lastCreated && scale === this.lastCreated.scale && fontFamily === this.lastFontFamily) {
        return this.lastCreated;
      }
      let factory;
      if (prebakedMiniMaps[scale]) {
        factory = new MinimapCharRenderer(prebakedMiniMaps[scale](), scale);
      } else {
        factory = MinimapCharRendererFactory.createFromSampleData(MinimapCharRendererFactory.createSampleData(fontFamily).data, scale);
      }
      this.lastFontFamily = fontFamily;
      this.lastCreated = factory;
      return factory;
    }
    /**
     * Creates the font sample data, writing to a canvas.
     */
    static createSampleData(fontFamily) {
      const canvas = document.createElement("canvas");
      const ctx = canvas.getContext("2d");
      canvas.style.height = `${16}px`;
      canvas.height = 16;
      canvas.width = 96 * 10;
      canvas.style.width = 96 * 10 + "px";
      ctx.fillStyle = "#ffffff";
      ctx.font = `bold ${16}px ${fontFamily}`;
      ctx.textBaseline = "middle";
      let x = 0;
      for (const code of allCharCodes) {
        ctx.fillText(String.fromCharCode(code), x, 16 / 2);
        x += 10;
      }
      return ctx.getImageData(
        0,
        0,
        96 * 10,
        16
        /* Constants.SAMPLED_CHAR_HEIGHT */
      );
    }
    /**
     * Creates a character renderer from the canvas sample data.
     */
    static createFromSampleData(source, scale) {
      const expectedLength = 16 * 10 * 4 * 96;
      if (source.length !== expectedLength) {
        throw new Error("Unexpected source in MinimapCharRenderer");
      }
      const charData = MinimapCharRendererFactory._downsample(source, scale);
      return new MinimapCharRenderer(charData, scale);
    }
    static _downsampleChar(source, sourceOffset, dest, destOffset, scale) {
      const width2 = 1 * scale;
      const height = 2 * scale;
      let targetIndex = destOffset;
      let brightest = 0;
      for (let y = 0; y < height; y++) {
        const sourceY1 = y / height * 16;
        const sourceY2 = (y + 1) / height * 16;
        for (let x = 0; x < width2; x++) {
          const sourceX1 = x / width2 * 10;
          const sourceX2 = (x + 1) / width2 * 10;
          let value = 0;
          let samples = 0;
          for (let sy = sourceY1; sy < sourceY2; sy++) {
            const sourceRow = sourceOffset + Math.floor(sy) * 3840;
            const yBalance = 1 - (sy - Math.floor(sy));
            for (let sx = sourceX1; sx < sourceX2; sx++) {
              const xBalance = 1 - (sx - Math.floor(sx));
              const sourceIndex = sourceRow + Math.floor(sx) * 4;
              const weight2 = xBalance * yBalance;
              samples += weight2;
              value += source[sourceIndex] * source[sourceIndex + 3] / 255 * weight2;
            }
          }
          const final = value / samples;
          brightest = Math.max(brightest, final);
          dest[targetIndex++] = toUint8(final);
        }
      }
      return brightest;
    }
    static _downsample(data, scale) {
      const pixelsPerCharacter = 2 * scale * 1 * scale;
      const resultLen = pixelsPerCharacter * 96;
      const result = new Uint8ClampedArray(resultLen);
      let resultOffset = 0;
      let sourceOffset = 0;
      let brightest = 0;
      for (let charIndex = 0; charIndex < 96; charIndex++) {
        brightest = Math.max(brightest, this._downsampleChar(data, sourceOffset, result, resultOffset, scale));
        resultOffset += pixelsPerCharacter;
        sourceOffset += 10 * 4;
      }
      if (brightest > 0) {
        const adjust = 255 / brightest;
        for (let i2 = 0; i2 < resultLen; i2++) {
          result[i2] *= adjust;
        }
      }
      return result;
    }
  }
  const DEFAULT_FONT_FAMILY = isWindows ? '"Segoe WPC", "Segoe UI", sans-serif' : isMacintosh ? "-apple-system, BlinkMacSystemFont, sans-serif" : 'system-ui, "Ubuntu", "Droid Sans", sans-serif';
  class ViewModelDecoration {
    constructor(range2, options) {
      this._viewModelDecorationBrand = void 0;
      this.range = range2;
      this.options = options;
    }
  }
  function isModelDecorationVisible(model, decoration2) {
    if (decoration2.options.hideInCommentTokens && isModelDecorationInComment(model, decoration2)) {
      return false;
    }
    if (decoration2.options.hideInStringTokens && isModelDecorationInString(model, decoration2)) {
      return false;
    }
    return true;
  }
  function isModelDecorationInComment(model, decoration2) {
    return testTokensInRange(
      model,
      decoration2.range,
      (tokenType) => tokenType === 1
      /* StandardTokenType.Comment */
    );
  }
  function isModelDecorationInString(model, decoration2) {
    return testTokensInRange(
      model,
      decoration2.range,
      (tokenType) => tokenType === 2
      /* StandardTokenType.String */
    );
  }
  function testTokensInRange(model, range2, callback) {
    for (let lineNumber = range2.startLineNumber; lineNumber <= range2.endLineNumber; lineNumber++) {
      const lineTokens = model.tokenization.getLineTokens(lineNumber);
      const isFirstLine = lineNumber === range2.startLineNumber;
      const isEndLine = lineNumber === range2.endLineNumber;
      let tokenIdx = isFirstLine ? lineTokens.findTokenIndexAtOffset(range2.startColumn - 1) : 0;
      while (tokenIdx < lineTokens.getCount()) {
        if (isEndLine) {
          const startOffset = lineTokens.getStartOffset(tokenIdx);
          if (startOffset > range2.endColumn - 1) {
            break;
          }
        }
        const callbackResult = callback(lineTokens.getStandardTokenType(tokenIdx));
        if (!callbackResult) {
          return false;
        }
        tokenIdx++;
      }
    }
    return true;
  }
  const POINTER_DRAG_RESET_DISTANCE = 140;
  const GUTTER_DECORATION_WIDTH = 2;
  class MinimapOptions {
    constructor(configuration, theme, tokensColorTracker) {
      const options = configuration.options;
      const pixelRatio = options.get(
        163
        /* EditorOption.pixelRatio */
      );
      const layoutInfo = options.get(
        165
        /* EditorOption.layoutInfo */
      );
      const minimapLayout = layoutInfo.minimap;
      const fontInfo = options.get(
        59
        /* EditorOption.fontInfo */
      );
      const minimapOpts = options.get(
        81
        /* EditorOption.minimap */
      );
      this.renderMinimap = minimapLayout.renderMinimap;
      this.size = minimapOpts.size;
      this.minimapHeightIsEditorHeight = minimapLayout.minimapHeightIsEditorHeight;
      this.scrollBeyondLastLine = options.get(
        119
        /* EditorOption.scrollBeyondLastLine */
      );
      this.paddingTop = options.get(
        96
        /* EditorOption.padding */
      ).top;
      this.paddingBottom = options.get(
        96
        /* EditorOption.padding */
      ).bottom;
      this.showSlider = minimapOpts.showSlider;
      this.autohide = minimapOpts.autohide;
      this.pixelRatio = pixelRatio;
      this.typicalHalfwidthCharacterWidth = fontInfo.typicalHalfwidthCharacterWidth;
      this.lineHeight = options.get(
        75
        /* EditorOption.lineHeight */
      );
      this.minimapLeft = minimapLayout.minimapLeft;
      this.minimapWidth = minimapLayout.minimapWidth;
      this.minimapHeight = layoutInfo.height;
      this.canvasInnerWidth = minimapLayout.minimapCanvasInnerWidth;
      this.canvasInnerHeight = minimapLayout.minimapCanvasInnerHeight;
      this.canvasOuterWidth = minimapLayout.minimapCanvasOuterWidth;
      this.canvasOuterHeight = minimapLayout.minimapCanvasOuterHeight;
      this.isSampling = minimapLayout.minimapIsSampling;
      this.editorHeight = layoutInfo.height;
      this.fontScale = minimapLayout.minimapScale;
      this.minimapLineHeight = minimapLayout.minimapLineHeight;
      this.minimapCharWidth = 1 * this.fontScale;
      this.sectionHeaderFontFamily = DEFAULT_FONT_FAMILY;
      this.sectionHeaderFontSize = minimapOpts.sectionHeaderFontSize * pixelRatio;
      this.sectionHeaderLetterSpacing = minimapOpts.sectionHeaderLetterSpacing;
      this.sectionHeaderFontColor = MinimapOptions._getSectionHeaderColor(theme, tokensColorTracker.getColor(
        1
        /* ColorId.DefaultForeground */
      ));
      this.charRenderer = createSingleCallFunction(() => MinimapCharRendererFactory.create(this.fontScale, fontInfo.fontFamily));
      this.defaultBackgroundColor = tokensColorTracker.getColor(
        2
        /* ColorId.DefaultBackground */
      );
      this.backgroundColor = MinimapOptions._getMinimapBackground(theme, this.defaultBackgroundColor);
      this.foregroundAlpha = MinimapOptions._getMinimapForegroundOpacity(theme);
    }
    static _getMinimapBackground(theme, defaultBackgroundColor) {
      const themeColor = theme.getColor(minimapBackground);
      if (themeColor) {
        return new RGBA8(themeColor.rgba.r, themeColor.rgba.g, themeColor.rgba.b, Math.round(255 * themeColor.rgba.a));
      }
      return defaultBackgroundColor;
    }
    static _getMinimapForegroundOpacity(theme) {
      const themeColor = theme.getColor(minimapForegroundOpacity);
      if (themeColor) {
        return RGBA8._clamp(Math.round(255 * themeColor.rgba.a));
      }
      return 255;
    }
    static _getSectionHeaderColor(theme, defaultForegroundColor) {
      const themeColor = theme.getColor(editorForeground);
      if (themeColor) {
        return new RGBA8(themeColor.rgba.r, themeColor.rgba.g, themeColor.rgba.b, Math.round(255 * themeColor.rgba.a));
      }
      return defaultForegroundColor;
    }
    equals(other) {
      return this.renderMinimap === other.renderMinimap && this.size === other.size && this.minimapHeightIsEditorHeight === other.minimapHeightIsEditorHeight && this.scrollBeyondLastLine === other.scrollBeyondLastLine && this.paddingTop === other.paddingTop && this.paddingBottom === other.paddingBottom && this.showSlider === other.showSlider && this.autohide === other.autohide && this.pixelRatio === other.pixelRatio && this.typicalHalfwidthCharacterWidth === other.typicalHalfwidthCharacterWidth && this.lineHeight === other.lineHeight && this.minimapLeft === other.minimapLeft && this.minimapWidth === other.minimapWidth && this.minimapHeight === other.minimapHeight && this.canvasInnerWidth === other.canvasInnerWidth && this.canvasInnerHeight === other.canvasInnerHeight && this.canvasOuterWidth === other.canvasOuterWidth && this.canvasOuterHeight === other.canvasOuterHeight && this.isSampling === other.isSampling && this.editorHeight === other.editorHeight && this.fontScale === other.fontScale && this.minimapLineHeight === other.minimapLineHeight && this.minimapCharWidth === other.minimapCharWidth && this.sectionHeaderFontSize === other.sectionHeaderFontSize && this.sectionHeaderLetterSpacing === other.sectionHeaderLetterSpacing && this.defaultBackgroundColor && this.defaultBackgroundColor.equals(other.defaultBackgroundColor) && this.backgroundColor && this.backgroundColor.equals(other.backgroundColor) && this.foregroundAlpha === other.foregroundAlpha;
    }
  }
  class MinimapLayout {
    constructor(scrollTop, scrollHeight, sliderNeeded, _computedSliderRatio, sliderTop, sliderHeight, topPaddingLineCount, startLineNumber, endLineNumber) {
      this.scrollTop = scrollTop;
      this.scrollHeight = scrollHeight;
      this.sliderNeeded = sliderNeeded;
      this._computedSliderRatio = _computedSliderRatio;
      this.sliderTop = sliderTop;
      this.sliderHeight = sliderHeight;
      this.topPaddingLineCount = topPaddingLineCount;
      this.startLineNumber = startLineNumber;
      this.endLineNumber = endLineNumber;
    }
    /**
     * Compute a desired `scrollPosition` such that the slider moves by `delta`.
     */
    getDesiredScrollTopFromDelta(delta) {
      return Math.round(this.scrollTop + delta / this._computedSliderRatio);
    }
    getDesiredScrollTopFromTouchLocation(pageY) {
      return Math.round((pageY - this.sliderHeight / 2) / this._computedSliderRatio);
    }
    /**
     * Intersect a line range with `this.startLineNumber` and `this.endLineNumber`.
     */
    intersectWithViewport(range2) {
      const startLineNumber = Math.max(this.startLineNumber, range2.startLineNumber);
      const endLineNumber = Math.min(this.endLineNumber, range2.endLineNumber);
      if (startLineNumber > endLineNumber) {
        return null;
      }
      return [startLineNumber, endLineNumber];
    }
    /**
     * Get the inner minimap y coordinate for a line number.
     */
    getYForLineNumber(lineNumber, minimapLineHeight) {
      return +(lineNumber - this.startLineNumber + this.topPaddingLineCount) * minimapLineHeight;
    }
    static create(options, viewportStartLineNumber, viewportEndLineNumber, viewportStartLineNumberVerticalOffset, viewportHeight, viewportContainsWhitespaceGaps, lineCount, realLineCount, scrollTop, scrollHeight, previousLayout) {
      const pixelRatio = options.pixelRatio;
      const minimapLineHeight = options.minimapLineHeight;
      const minimapLinesFitting = Math.floor(options.canvasInnerHeight / minimapLineHeight);
      const lineHeight = options.lineHeight;
      if (options.minimapHeightIsEditorHeight) {
        let logicalScrollHeight = realLineCount * options.lineHeight + options.paddingTop + options.paddingBottom;
        if (options.scrollBeyondLastLine) {
          logicalScrollHeight += Math.max(0, viewportHeight - options.lineHeight - options.paddingBottom);
        }
        const sliderHeight2 = Math.max(1, Math.floor(viewportHeight * viewportHeight / logicalScrollHeight));
        const maxMinimapSliderTop2 = Math.max(0, options.minimapHeight - sliderHeight2);
        const computedSliderRatio2 = maxMinimapSliderTop2 / (scrollHeight - viewportHeight);
        const sliderTop2 = scrollTop * computedSliderRatio2;
        const sliderNeeded = maxMinimapSliderTop2 > 0;
        const maxLinesFitting = Math.floor(options.canvasInnerHeight / options.minimapLineHeight);
        const topPaddingLineCount = Math.floor(options.paddingTop / options.lineHeight);
        return new MinimapLayout(scrollTop, scrollHeight, sliderNeeded, computedSliderRatio2, sliderTop2, sliderHeight2, topPaddingLineCount, 1, Math.min(lineCount, maxLinesFitting));
      }
      let sliderHeight;
      if (viewportContainsWhitespaceGaps && viewportEndLineNumber !== lineCount) {
        const viewportLineCount = viewportEndLineNumber - viewportStartLineNumber + 1;
        sliderHeight = Math.floor(viewportLineCount * minimapLineHeight / pixelRatio);
      } else {
        const expectedViewportLineCount = viewportHeight / lineHeight;
        sliderHeight = Math.floor(expectedViewportLineCount * minimapLineHeight / pixelRatio);
      }
      const extraLinesAtTheTop = Math.floor(options.paddingTop / lineHeight);
      let extraLinesAtTheBottom = Math.floor(options.paddingBottom / lineHeight);
      if (options.scrollBeyondLastLine) {
        const expectedViewportLineCount = viewportHeight / lineHeight;
        extraLinesAtTheBottom = Math.max(extraLinesAtTheBottom, expectedViewportLineCount - 1);
      }
      let maxMinimapSliderTop;
      if (extraLinesAtTheBottom > 0) {
        const expectedViewportLineCount = viewportHeight / lineHeight;
        maxMinimapSliderTop = (extraLinesAtTheTop + lineCount + extraLinesAtTheBottom - expectedViewportLineCount - 1) * minimapLineHeight / pixelRatio;
      } else {
        maxMinimapSliderTop = Math.max(0, (extraLinesAtTheTop + lineCount) * minimapLineHeight / pixelRatio - sliderHeight);
      }
      maxMinimapSliderTop = Math.min(options.minimapHeight - sliderHeight, maxMinimapSliderTop);
      const computedSliderRatio = maxMinimapSliderTop / (scrollHeight - viewportHeight);
      const sliderTop = scrollTop * computedSliderRatio;
      if (minimapLinesFitting >= extraLinesAtTheTop + lineCount + extraLinesAtTheBottom) {
        const sliderNeeded = maxMinimapSliderTop > 0;
        return new MinimapLayout(scrollTop, scrollHeight, sliderNeeded, computedSliderRatio, sliderTop, sliderHeight, extraLinesAtTheTop, 1, lineCount);
      } else {
        let consideringStartLineNumber;
        if (viewportStartLineNumber > 1) {
          consideringStartLineNumber = viewportStartLineNumber + extraLinesAtTheTop;
        } else {
          consideringStartLineNumber = Math.max(1, scrollTop / lineHeight);
        }
        let topPaddingLineCount;
        let startLineNumber = Math.max(1, Math.floor(consideringStartLineNumber - sliderTop * pixelRatio / minimapLineHeight));
        if (startLineNumber < extraLinesAtTheTop) {
          topPaddingLineCount = extraLinesAtTheTop - startLineNumber + 1;
          startLineNumber = 1;
        } else {
          topPaddingLineCount = 0;
          startLineNumber = Math.max(1, startLineNumber - extraLinesAtTheTop);
        }
        if (previousLayout && previousLayout.scrollHeight === scrollHeight) {
          if (previousLayout.scrollTop > scrollTop) {
            startLineNumber = Math.min(startLineNumber, previousLayout.startLineNumber);
            topPaddingLineCount = Math.max(topPaddingLineCount, previousLayout.topPaddingLineCount);
          }
          if (previousLayout.scrollTop < scrollTop) {
            startLineNumber = Math.max(startLineNumber, previousLayout.startLineNumber);
            topPaddingLineCount = Math.min(topPaddingLineCount, previousLayout.topPaddingLineCount);
          }
        }
        const endLineNumber = Math.min(lineCount, startLineNumber - topPaddingLineCount + minimapLinesFitting - 1);
        const partialLine = (scrollTop - viewportStartLineNumberVerticalOffset) / lineHeight;
        let sliderTopAligned;
        if (scrollTop >= options.paddingTop) {
          sliderTopAligned = (viewportStartLineNumber - startLineNumber + topPaddingLineCount + partialLine) * minimapLineHeight / pixelRatio;
        } else {
          sliderTopAligned = scrollTop / options.paddingTop * (topPaddingLineCount + partialLine) * minimapLineHeight / pixelRatio;
        }
        return new MinimapLayout(scrollTop, scrollHeight, true, computedSliderRatio, sliderTopAligned, sliderHeight, topPaddingLineCount, startLineNumber, endLineNumber);
      }
    }
  }
  const _MinimapLine = class _MinimapLine {
    constructor(dy) {
      this.dy = dy;
    }
    onContentChanged() {
      this.dy = -1;
    }
    onTokensChanged() {
      this.dy = -1;
    }
  };
  _MinimapLine.INVALID = new _MinimapLine(-1);
  let MinimapLine = _MinimapLine;
  class RenderData {
    constructor(renderedLayout, imageData, lines) {
      this.renderedLayout = renderedLayout;
      this._imageData = imageData;
      this._renderedLines = new RenderedLinesCollection({
        createLine: () => MinimapLine.INVALID
      });
      this._renderedLines._set(renderedLayout.startLineNumber, lines);
    }
    /**
     * Check if the current RenderData matches accurately the new desired layout and no painting is needed.
     */
    linesEquals(layout2) {
      if (!this.scrollEquals(layout2)) {
        return false;
      }
      const tmp = this._renderedLines._get();
      const lines = tmp.lines;
      for (let i2 = 0, len = lines.length; i2 < len; i2++) {
        if (lines[i2].dy === -1) {
          return false;
        }
      }
      return true;
    }
    /**
     * Check if the current RenderData matches the new layout's scroll position
     */
    scrollEquals(layout2) {
      return this.renderedLayout.startLineNumber === layout2.startLineNumber && this.renderedLayout.endLineNumber === layout2.endLineNumber;
    }
    _get() {
      const tmp = this._renderedLines._get();
      return {
        imageData: this._imageData,
        rendLineNumberStart: tmp.rendLineNumberStart,
        lines: tmp.lines
      };
    }
    onLinesChanged(changeFromLineNumber, changeCount) {
      return this._renderedLines.onLinesChanged(changeFromLineNumber, changeCount);
    }
    onLinesDeleted(deleteFromLineNumber, deleteToLineNumber) {
      this._renderedLines.onLinesDeleted(deleteFromLineNumber, deleteToLineNumber);
    }
    onLinesInserted(insertFromLineNumber, insertToLineNumber) {
      this._renderedLines.onLinesInserted(insertFromLineNumber, insertToLineNumber);
    }
    onTokensChanged(ranges) {
      return this._renderedLines.onTokensChanged(ranges);
    }
  }
  class MinimapBuffers {
    constructor(ctx, WIDTH, HEIGHT, background) {
      this._backgroundFillData = MinimapBuffers._createBackgroundFillData(WIDTH, HEIGHT, background);
      this._buffers = [
        ctx.createImageData(WIDTH, HEIGHT),
        ctx.createImageData(WIDTH, HEIGHT)
      ];
      this._lastUsedBuffer = 0;
    }
    getBuffer() {
      this._lastUsedBuffer = 1 - this._lastUsedBuffer;
      const result = this._buffers[this._lastUsedBuffer];
      result.data.set(this._backgroundFillData);
      return result;
    }
    static _createBackgroundFillData(WIDTH, HEIGHT, background) {
      const backgroundR = background.r;
      const backgroundG = background.g;
      const backgroundB = background.b;
      const backgroundA = background.a;
      const result = new Uint8ClampedArray(WIDTH * HEIGHT * 4);
      let offset = 0;
      for (let i2 = 0; i2 < HEIGHT; i2++) {
        for (let j = 0; j < WIDTH; j++) {
          result[offset] = backgroundR;
          result[offset + 1] = backgroundG;
          result[offset + 2] = backgroundB;
          result[offset + 3] = backgroundA;
          offset += 4;
        }
      }
      return result;
    }
  }
  class MinimapSamplingState {
    static compute(options, viewLineCount, oldSamplingState) {
      if (options.renderMinimap === 0 || !options.isSampling) {
        return [null, []];
      }
      const { minimapLineCount } = EditorLayoutInfoComputer.computeContainedMinimapLineCount({
        viewLineCount,
        scrollBeyondLastLine: options.scrollBeyondLastLine,
        paddingTop: options.paddingTop,
        paddingBottom: options.paddingBottom,
        height: options.editorHeight,
        lineHeight: options.lineHeight,
        pixelRatio: options.pixelRatio
      });
      const ratio = viewLineCount / minimapLineCount;
      const halfRatio = ratio / 2;
      if (!oldSamplingState || oldSamplingState.minimapLines.length === 0) {
        const result2 = [];
        result2[0] = 1;
        if (minimapLineCount > 1) {
          for (let i2 = 0, lastIndex = minimapLineCount - 1; i2 < lastIndex; i2++) {
            result2[i2] = Math.round(i2 * ratio + halfRatio);
          }
          result2[minimapLineCount - 1] = viewLineCount;
        }
        return [new MinimapSamplingState(ratio, result2), []];
      }
      const oldMinimapLines = oldSamplingState.minimapLines;
      const oldLength = oldMinimapLines.length;
      const result = [];
      let oldIndex = 0;
      let oldDeltaLineCount = 0;
      let minViewLineNumber = 1;
      const MAX_EVENT_COUNT = 10;
      let events = [];
      let lastEvent = null;
      for (let i2 = 0; i2 < minimapLineCount; i2++) {
        const fromViewLineNumber = Math.max(minViewLineNumber, Math.round(i2 * ratio));
        const toViewLineNumber = Math.max(fromViewLineNumber, Math.round((i2 + 1) * ratio));
        while (oldIndex < oldLength && oldMinimapLines[oldIndex] < fromViewLineNumber) {
          if (events.length < MAX_EVENT_COUNT) {
            const oldMinimapLineNumber = oldIndex + 1 + oldDeltaLineCount;
            if (lastEvent && lastEvent.type === "deleted" && lastEvent._oldIndex === oldIndex - 1) {
              lastEvent.deleteToLineNumber++;
            } else {
              lastEvent = { type: "deleted", _oldIndex: oldIndex, deleteFromLineNumber: oldMinimapLineNumber, deleteToLineNumber: oldMinimapLineNumber };
              events.push(lastEvent);
            }
            oldDeltaLineCount--;
          }
          oldIndex++;
        }
        let selectedViewLineNumber;
        if (oldIndex < oldLength && oldMinimapLines[oldIndex] <= toViewLineNumber) {
          selectedViewLineNumber = oldMinimapLines[oldIndex];
          oldIndex++;
        } else {
          if (i2 === 0) {
            selectedViewLineNumber = 1;
          } else if (i2 + 1 === minimapLineCount) {
            selectedViewLineNumber = viewLineCount;
          } else {
            selectedViewLineNumber = Math.round(i2 * ratio + halfRatio);
          }
          if (events.length < MAX_EVENT_COUNT) {
            const oldMinimapLineNumber = oldIndex + 1 + oldDeltaLineCount;
            if (lastEvent && lastEvent.type === "inserted" && lastEvent._i === i2 - 1) {
              lastEvent.insertToLineNumber++;
            } else {
              lastEvent = { type: "inserted", _i: i2, insertFromLineNumber: oldMinimapLineNumber, insertToLineNumber: oldMinimapLineNumber };
              events.push(lastEvent);
            }
            oldDeltaLineCount++;
          }
        }
        result[i2] = selectedViewLineNumber;
        minViewLineNumber = selectedViewLineNumber;
      }
      if (events.length < MAX_EVENT_COUNT) {
        while (oldIndex < oldLength) {
          const oldMinimapLineNumber = oldIndex + 1 + oldDeltaLineCount;
          if (lastEvent && lastEvent.type === "deleted" && lastEvent._oldIndex === oldIndex - 1) {
            lastEvent.deleteToLineNumber++;
          } else {
            lastEvent = { type: "deleted", _oldIndex: oldIndex, deleteFromLineNumber: oldMinimapLineNumber, deleteToLineNumber: oldMinimapLineNumber };
            events.push(lastEvent);
          }
          oldDeltaLineCount--;
          oldIndex++;
        }
      } else {
        events = [{ type: "flush" }];
      }
      return [new MinimapSamplingState(ratio, result), events];
    }
    constructor(samplingRatio, minimapLines) {
      this.samplingRatio = samplingRatio;
      this.minimapLines = minimapLines;
    }
    modelLineToMinimapLine(lineNumber) {
      return Math.min(this.minimapLines.length, Math.max(1, Math.round(lineNumber / this.samplingRatio)));
    }
    /**
     * Will return null if the model line ranges are not intersecting with a sampled model line.
     */
    modelLineRangeToMinimapLineRange(fromLineNumber, toLineNumber) {
      let fromLineIndex = this.modelLineToMinimapLine(fromLineNumber) - 1;
      while (fromLineIndex > 0 && this.minimapLines[fromLineIndex - 1] >= fromLineNumber) {
        fromLineIndex--;
      }
      let toLineIndex = this.modelLineToMinimapLine(toLineNumber) - 1;
      while (toLineIndex + 1 < this.minimapLines.length && this.minimapLines[toLineIndex + 1] <= toLineNumber) {
        toLineIndex++;
      }
      if (fromLineIndex === toLineIndex) {
        const sampledLineNumber = this.minimapLines[fromLineIndex];
        if (sampledLineNumber < fromLineNumber || sampledLineNumber > toLineNumber) {
          return null;
        }
      }
      return [fromLineIndex + 1, toLineIndex + 1];
    }
    /**
     * Will always return a range, even if it is not intersecting with a sampled model line.
     */
    decorationLineRangeToMinimapLineRange(startLineNumber, endLineNumber) {
      let minimapLineStart = this.modelLineToMinimapLine(startLineNumber);
      let minimapLineEnd = this.modelLineToMinimapLine(endLineNumber);
      if (startLineNumber !== endLineNumber && minimapLineEnd === minimapLineStart) {
        if (minimapLineEnd === this.minimapLines.length) {
          if (minimapLineStart > 1) {
            minimapLineStart--;
          }
        } else {
          minimapLineEnd++;
        }
      }
      return [minimapLineStart, minimapLineEnd];
    }
    onLinesDeleted(e) {
      const deletedLineCount = e.toLineNumber - e.fromLineNumber + 1;
      let changeStartIndex = this.minimapLines.length;
      let changeEndIndex = 0;
      for (let i2 = this.minimapLines.length - 1; i2 >= 0; i2--) {
        if (this.minimapLines[i2] < e.fromLineNumber) {
          break;
        }
        if (this.minimapLines[i2] <= e.toLineNumber) {
          this.minimapLines[i2] = Math.max(1, e.fromLineNumber - 1);
          changeStartIndex = Math.min(changeStartIndex, i2);
          changeEndIndex = Math.max(changeEndIndex, i2);
        } else {
          this.minimapLines[i2] -= deletedLineCount;
        }
      }
      return [changeStartIndex, changeEndIndex];
    }
    onLinesInserted(e) {
      const insertedLineCount = e.toLineNumber - e.fromLineNumber + 1;
      for (let i2 = this.minimapLines.length - 1; i2 >= 0; i2--) {
        if (this.minimapLines[i2] < e.fromLineNumber) {
          break;
        }
        this.minimapLines[i2] += insertedLineCount;
      }
    }
  }
  class Minimap extends ViewPart {
    constructor(context) {
      super(context);
      this._sectionHeaderCache = new LRUCache(10, 1.5);
      this.tokensColorTracker = MinimapTokensColorTracker.getInstance();
      this._selections = [];
      this._minimapSelections = null;
      this.options = new MinimapOptions(this._context.configuration, this._context.theme, this.tokensColorTracker);
      const [samplingState] = MinimapSamplingState.compute(this.options, this._context.viewModel.getLineCount(), null);
      this._samplingState = samplingState;
      this._shouldCheckSampling = false;
      this._actual = new InnerMinimap(context.theme, this);
    }
    dispose() {
      this._actual.dispose();
      super.dispose();
    }
    getDomNode() {
      return this._actual.getDomNode();
    }
    _onOptionsMaybeChanged() {
      const opts = new MinimapOptions(this._context.configuration, this._context.theme, this.tokensColorTracker);
      if (this.options.equals(opts)) {
        return false;
      }
      this.options = opts;
      this._recreateLineSampling();
      this._actual.onDidChangeOptions();
      return true;
    }
    // ---- begin view event handlers
    onConfigurationChanged(e) {
      return this._onOptionsMaybeChanged();
    }
    onCursorStateChanged(e) {
      this._selections = e.selections;
      this._minimapSelections = null;
      return this._actual.onSelectionChanged();
    }
    onDecorationsChanged(e) {
      if (e.affectsMinimap) {
        return this._actual.onDecorationsChanged();
      }
      return false;
    }
    onFlushed(e) {
      if (this._samplingState) {
        this._shouldCheckSampling = true;
      }
      return this._actual.onFlushed();
    }
    onLinesChanged(e) {
      if (this._samplingState) {
        const minimapLineRange = this._samplingState.modelLineRangeToMinimapLineRange(e.fromLineNumber, e.fromLineNumber + e.count - 1);
        if (minimapLineRange) {
          return this._actual.onLinesChanged(minimapLineRange[0], minimapLineRange[1] - minimapLineRange[0] + 1);
        } else {
          return false;
        }
      } else {
        return this._actual.onLinesChanged(e.fromLineNumber, e.count);
      }
    }
    onLinesDeleted(e) {
      if (this._samplingState) {
        const [changeStartIndex, changeEndIndex] = this._samplingState.onLinesDeleted(e);
        if (changeStartIndex <= changeEndIndex) {
          this._actual.onLinesChanged(changeStartIndex + 1, changeEndIndex - changeStartIndex + 1);
        }
        this._shouldCheckSampling = true;
        return true;
      } else {
        return this._actual.onLinesDeleted(e.fromLineNumber, e.toLineNumber);
      }
    }
    onLinesInserted(e) {
      if (this._samplingState) {
        this._samplingState.onLinesInserted(e);
        this._shouldCheckSampling = true;
        return true;
      } else {
        return this._actual.onLinesInserted(e.fromLineNumber, e.toLineNumber);
      }
    }
    onScrollChanged(e) {
      return this._actual.onScrollChanged(e);
    }
    onThemeChanged(e) {
      this._actual.onThemeChanged();
      this._onOptionsMaybeChanged();
      return true;
    }
    onTokensChanged(e) {
      if (this._samplingState) {
        const ranges = [];
        for (const range2 of e.ranges) {
          const minimapLineRange = this._samplingState.modelLineRangeToMinimapLineRange(range2.fromLineNumber, range2.toLineNumber);
          if (minimapLineRange) {
            ranges.push({ fromLineNumber: minimapLineRange[0], toLineNumber: minimapLineRange[1] });
          }
        }
        if (ranges.length) {
          return this._actual.onTokensChanged(ranges);
        } else {
          return false;
        }
      } else {
        return this._actual.onTokensChanged(e.ranges);
      }
    }
    onTokensColorsChanged(e) {
      this._onOptionsMaybeChanged();
      return this._actual.onTokensColorsChanged();
    }
    onZonesChanged(e) {
      return this._actual.onZonesChanged();
    }
    // --- end event handlers
    prepareRender(ctx) {
      if (this._shouldCheckSampling) {
        this._shouldCheckSampling = false;
        this._recreateLineSampling();
      }
    }
    render(ctx) {
      let viewportStartLineNumber = ctx.visibleRange.startLineNumber;
      let viewportEndLineNumber = ctx.visibleRange.endLineNumber;
      if (this._samplingState) {
        viewportStartLineNumber = this._samplingState.modelLineToMinimapLine(viewportStartLineNumber);
        viewportEndLineNumber = this._samplingState.modelLineToMinimapLine(viewportEndLineNumber);
      }
      const minimapCtx = {
        viewportContainsWhitespaceGaps: ctx.viewportData.whitespaceViewportData.length > 0,
        scrollWidth: ctx.scrollWidth,
        scrollHeight: ctx.scrollHeight,
        viewportStartLineNumber,
        viewportEndLineNumber,
        viewportStartLineNumberVerticalOffset: ctx.getVerticalOffsetForLineNumber(viewportStartLineNumber),
        scrollTop: ctx.scrollTop,
        scrollLeft: ctx.scrollLeft,
        viewportWidth: ctx.viewportWidth,
        viewportHeight: ctx.viewportHeight
      };
      this._actual.render(minimapCtx);
    }
    //#region IMinimapModel
    _recreateLineSampling() {
      this._minimapSelections = null;
      const wasSampling = Boolean(this._samplingState);
      const [samplingState, events] = MinimapSamplingState.compute(this.options, this._context.viewModel.getLineCount(), this._samplingState);
      this._samplingState = samplingState;
      if (wasSampling && this._samplingState) {
        for (const event of events) {
          switch (event.type) {
            case "deleted":
              this._actual.onLinesDeleted(event.deleteFromLineNumber, event.deleteToLineNumber);
              break;
            case "inserted":
              this._actual.onLinesInserted(event.insertFromLineNumber, event.insertToLineNumber);
              break;
            case "flush":
              this._actual.onFlushed();
              break;
          }
        }
      }
    }
    getLineCount() {
      if (this._samplingState) {
        return this._samplingState.minimapLines.length;
      }
      return this._context.viewModel.getLineCount();
    }
    getRealLineCount() {
      return this._context.viewModel.getLineCount();
    }
    getLineContent(lineNumber) {
      if (this._samplingState) {
        return this._context.viewModel.getLineContent(this._samplingState.minimapLines[lineNumber - 1]);
      }
      return this._context.viewModel.getLineContent(lineNumber);
    }
    getLineMaxColumn(lineNumber) {
      if (this._samplingState) {
        return this._context.viewModel.getLineMaxColumn(this._samplingState.minimapLines[lineNumber - 1]);
      }
      return this._context.viewModel.getLineMaxColumn(lineNumber);
    }
    getMinimapLinesRenderingData(startLineNumber, endLineNumber, needed) {
      if (this._samplingState) {
        const result = [];
        for (let lineIndex = 0, lineCount = endLineNumber - startLineNumber + 1; lineIndex < lineCount; lineIndex++) {
          if (needed[lineIndex]) {
            result[lineIndex] = this._context.viewModel.getViewLineData(this._samplingState.minimapLines[startLineNumber + lineIndex - 1]);
          } else {
            result[lineIndex] = null;
          }
        }
        return result;
      }
      return this._context.viewModel.getMinimapLinesRenderingData(startLineNumber, endLineNumber, needed).data;
    }
    getSelections() {
      if (this._minimapSelections === null) {
        if (this._samplingState) {
          this._minimapSelections = [];
          for (const selection of this._selections) {
            const [minimapLineStart, minimapLineEnd] = this._samplingState.decorationLineRangeToMinimapLineRange(selection.startLineNumber, selection.endLineNumber);
            this._minimapSelections.push(new Selection$1(minimapLineStart, selection.startColumn, minimapLineEnd, selection.endColumn));
          }
        } else {
          this._minimapSelections = this._selections;
        }
      }
      return this._minimapSelections;
    }
    getMinimapDecorationsInViewport(startLineNumber, endLineNumber) {
      return this._getMinimapDecorationsInViewport(startLineNumber, endLineNumber).filter((decoration2) => !decoration2.options.minimap?.sectionHeaderStyle);
    }
    getSectionHeaderDecorationsInViewport(startLineNumber, endLineNumber) {
      const headerHeightInMinimapLines = this.options.sectionHeaderFontSize / this.options.minimapLineHeight;
      startLineNumber = Math.floor(Math.max(1, startLineNumber - headerHeightInMinimapLines));
      return this._getMinimapDecorationsInViewport(startLineNumber, endLineNumber).filter((decoration2) => !!decoration2.options.minimap?.sectionHeaderStyle);
    }
    _getMinimapDecorationsInViewport(startLineNumber, endLineNumber) {
      let visibleRange;
      if (this._samplingState) {
        const modelStartLineNumber = this._samplingState.minimapLines[startLineNumber - 1];
        const modelEndLineNumber = this._samplingState.minimapLines[endLineNumber - 1];
        visibleRange = new Range$2(modelStartLineNumber, 1, modelEndLineNumber, this._context.viewModel.getLineMaxColumn(modelEndLineNumber));
      } else {
        visibleRange = new Range$2(startLineNumber, 1, endLineNumber, this._context.viewModel.getLineMaxColumn(endLineNumber));
      }
      const decorations = this._context.viewModel.getMinimapDecorationsInRange(visibleRange);
      if (this._samplingState) {
        const result = [];
        for (const decoration2 of decorations) {
          if (!decoration2.options.minimap) {
            continue;
          }
          const range2 = decoration2.range;
          const minimapStartLineNumber = this._samplingState.modelLineToMinimapLine(range2.startLineNumber);
          const minimapEndLineNumber = this._samplingState.modelLineToMinimapLine(range2.endLineNumber);
          result.push(new ViewModelDecoration(new Range$2(minimapStartLineNumber, range2.startColumn, minimapEndLineNumber, range2.endColumn), decoration2.options));
        }
        return result;
      }
      return decorations;
    }
    getSectionHeaderText(decoration2, fitWidth) {
      const headerText = decoration2.options.minimap?.sectionHeaderText;
      if (!headerText) {
        return null;
      }
      const cachedText = this._sectionHeaderCache.get(headerText);
      if (cachedText) {
        return cachedText;
      }
      const fittedText = fitWidth(headerText);
      this._sectionHeaderCache.set(headerText, fittedText);
      return fittedText;
    }
    getOptions() {
      return this._context.viewModel.model.getOptions();
    }
    revealLineNumber(lineNumber) {
      if (this._samplingState) {
        lineNumber = this._samplingState.minimapLines[lineNumber - 1];
      }
      this._context.viewModel.revealRange(
        "mouse",
        false,
        new Range$2(lineNumber, 1, lineNumber, 1),
        1,
        0
        /* ScrollType.Smooth */
      );
    }
    setScrollTop(scrollTop) {
      this._context.viewModel.viewLayout.setScrollPosition(
        {
          scrollTop
        },
        1
        /* ScrollType.Immediate */
      );
    }
  }
  class InnerMinimap extends Disposable {
    constructor(theme, model) {
      super();
      this._renderDecorations = false;
      this._gestureInProgress = false;
      this._isMouseOverMinimap = false;
      this._theme = theme;
      this._model = model;
      this._lastRenderData = null;
      this._buffers = null;
      this._selectionColor = this._theme.getColor(minimapSelection);
      this._domNode = createFastDomNode(document.createElement("div"));
      PartFingerprints.write(
        this._domNode,
        9
        /* PartFingerprint.Minimap */
      );
      this._domNode.setClassName(this._getMinimapDomNodeClassName());
      this._domNode.setPosition("absolute");
      this._domNode.setAttribute("role", "presentation");
      this._domNode.setAttribute("aria-hidden", "true");
      this._shadow = createFastDomNode(document.createElement("div"));
      this._shadow.setClassName("minimap-shadow-hidden");
      this._domNode.appendChild(this._shadow);
      this._canvas = createFastDomNode(document.createElement("canvas"));
      this._canvas.setPosition("absolute");
      this._canvas.setLeft(0);
      this._domNode.appendChild(this._canvas);
      this._decorationsCanvas = createFastDomNode(document.createElement("canvas"));
      this._decorationsCanvas.setPosition("absolute");
      this._decorationsCanvas.setClassName("minimap-decorations-layer");
      this._decorationsCanvas.setLeft(0);
      this._domNode.appendChild(this._decorationsCanvas);
      this._slider = createFastDomNode(document.createElement("div"));
      this._slider.setPosition("absolute");
      this._slider.setClassName("minimap-slider");
      this._slider.setLayerHinting(true);
      this._slider.setContain("strict");
      this._domNode.appendChild(this._slider);
      this._sliderHorizontal = createFastDomNode(document.createElement("div"));
      this._sliderHorizontal.setPosition("absolute");
      this._sliderHorizontal.setClassName("minimap-slider-horizontal");
      this._slider.appendChild(this._sliderHorizontal);
      this._applyLayout();
      this._hideDelayedScheduler = this._register(new RunOnceScheduler(() => this._hideImmediatelyIfMouseIsOutside(), 500));
      this._register(addStandardDisposableListener(this._domNode.domNode, EventType$1.MOUSE_OVER, () => {
        this._isMouseOverMinimap = true;
      }));
      this._register(addStandardDisposableListener(this._domNode.domNode, EventType$1.MOUSE_LEAVE, () => {
        this._isMouseOverMinimap = false;
      }));
      this._pointerDownListener = addStandardDisposableListener(this._domNode.domNode, EventType$1.POINTER_DOWN, (e) => {
        e.preventDefault();
        const isMouse = e.pointerType === "mouse";
        const isLeftClick = e.button === 0;
        const renderMinimap = this._model.options.renderMinimap;
        if (renderMinimap === 0) {
          return;
        }
        if (!this._lastRenderData) {
          return;
        }
        if (this._model.options.size !== "proportional") {
          if (isLeftClick && this._lastRenderData) {
            const position = getDomNodePagePosition(this._slider.domNode);
            const initialPosY = position.top + position.height / 2;
            this._startSliderDragging(e, initialPosY, this._lastRenderData.renderedLayout);
          }
          return;
        }
        if (isLeftClick || !isMouse) {
          const minimapLineHeight = this._model.options.minimapLineHeight;
          const internalOffsetY = this._model.options.canvasInnerHeight / this._model.options.canvasOuterHeight * e.offsetY;
          const lineIndex = Math.floor(internalOffsetY / minimapLineHeight);
          let lineNumber = lineIndex + this._lastRenderData.renderedLayout.startLineNumber - this._lastRenderData.renderedLayout.topPaddingLineCount;
          lineNumber = Math.min(lineNumber, this._model.getLineCount());
          this._model.revealLineNumber(lineNumber);
        }
      });
      this._sliderPointerMoveMonitor = new GlobalPointerMoveMonitor();
      this._sliderPointerDownListener = addStandardDisposableListener(this._slider.domNode, EventType$1.POINTER_DOWN, (e) => {
        e.preventDefault();
        e.stopPropagation();
        if (e.button === 0 && this._lastRenderData) {
          this._startSliderDragging(e, e.pageY, this._lastRenderData.renderedLayout);
        }
      });
      this._gestureDisposable = Gesture.addTarget(this._domNode.domNode);
      this._sliderTouchStartListener = addDisposableListener(this._domNode.domNode, EventType.Start, (e) => {
        e.preventDefault();
        e.stopPropagation();
        if (this._lastRenderData) {
          this._slider.toggleClassName("active", true);
          this._gestureInProgress = true;
          this.scrollDueToTouchEvent(e);
        }
      }, { passive: false });
      this._sliderTouchMoveListener = addDisposableListener(this._domNode.domNode, EventType.Change, (e) => {
        e.preventDefault();
        e.stopPropagation();
        if (this._lastRenderData && this._gestureInProgress) {
          this.scrollDueToTouchEvent(e);
        }
      }, { passive: false });
      this._sliderTouchEndListener = addStandardDisposableListener(this._domNode.domNode, EventType.End, (e) => {
        e.preventDefault();
        e.stopPropagation();
        this._gestureInProgress = false;
        this._slider.toggleClassName("active", false);
      });
    }
    _hideSoon() {
      this._hideDelayedScheduler.cancel();
      this._hideDelayedScheduler.schedule();
    }
    _hideImmediatelyIfMouseIsOutside() {
      if (this._isMouseOverMinimap) {
        this._hideSoon();
        return;
      }
      this._domNode.toggleClassName("active", false);
    }
    _startSliderDragging(e, initialPosY, initialSliderState) {
      if (!e.target || !(e.target instanceof Element)) {
        return;
      }
      const initialPosX = e.pageX;
      this._slider.toggleClassName("active", true);
      const handlePointerMove = (posy, posx) => {
        const minimapPosition = getDomNodePagePosition(this._domNode.domNode);
        const pointerOrthogonalDelta = Math.min(Math.abs(posx - initialPosX), Math.abs(posx - minimapPosition.left), Math.abs(posx - minimapPosition.left - minimapPosition.width));
        if (isWindows && pointerOrthogonalDelta > POINTER_DRAG_RESET_DISTANCE) {
          this._model.setScrollTop(initialSliderState.scrollTop);
          return;
        }
        const pointerDelta = posy - initialPosY;
        this._model.setScrollTop(initialSliderState.getDesiredScrollTopFromDelta(pointerDelta));
      };
      if (e.pageY !== initialPosY) {
        handlePointerMove(e.pageY, initialPosX);
      }
      this._sliderPointerMoveMonitor.startMonitoring(e.target, e.pointerId, e.buttons, (pointerMoveData) => handlePointerMove(pointerMoveData.pageY, pointerMoveData.pageX), () => {
        this._slider.toggleClassName("active", false);
      });
    }
    scrollDueToTouchEvent(touch) {
      const startY = this._domNode.domNode.getBoundingClientRect().top;
      const scrollTop = this._lastRenderData.renderedLayout.getDesiredScrollTopFromTouchLocation(touch.pageY - startY);
      this._model.setScrollTop(scrollTop);
    }
    dispose() {
      this._pointerDownListener.dispose();
      this._sliderPointerMoveMonitor.dispose();
      this._sliderPointerDownListener.dispose();
      this._gestureDisposable.dispose();
      this._sliderTouchStartListener.dispose();
      this._sliderTouchMoveListener.dispose();
      this._sliderTouchEndListener.dispose();
      super.dispose();
    }
    _getMinimapDomNodeClassName() {
      const class_ = ["minimap"];
      if (this._model.options.showSlider === "always") {
        class_.push("slider-always");
      } else {
        class_.push("slider-mouseover");
      }
      if (this._model.options.autohide === "mouseover") {
        class_.push("minimap-autohide-mouseover");
      } else if (this._model.options.autohide === "scroll") {
        class_.push("minimap-autohide-scroll");
      }
      return class_.join(" ");
    }
    getDomNode() {
      return this._domNode;
    }
    _applyLayout() {
      this._domNode.setLeft(this._model.options.minimapLeft);
      this._domNode.setWidth(this._model.options.minimapWidth);
      this._domNode.setHeight(this._model.options.minimapHeight);
      this._shadow.setHeight(this._model.options.minimapHeight);
      this._canvas.setWidth(this._model.options.canvasOuterWidth);
      this._canvas.setHeight(this._model.options.canvasOuterHeight);
      this._canvas.domNode.width = this._model.options.canvasInnerWidth;
      this._canvas.domNode.height = this._model.options.canvasInnerHeight;
      this._decorationsCanvas.setWidth(this._model.options.canvasOuterWidth);
      this._decorationsCanvas.setHeight(this._model.options.canvasOuterHeight);
      this._decorationsCanvas.domNode.width = this._model.options.canvasInnerWidth;
      this._decorationsCanvas.domNode.height = this._model.options.canvasInnerHeight;
      this._slider.setWidth(this._model.options.minimapWidth);
    }
    _getBuffer() {
      if (!this._buffers) {
        if (this._model.options.canvasInnerWidth > 0 && this._model.options.canvasInnerHeight > 0) {
          this._buffers = new MinimapBuffers(this._canvas.domNode.getContext("2d"), this._model.options.canvasInnerWidth, this._model.options.canvasInnerHeight, this._model.options.backgroundColor);
        }
      }
      return this._buffers ? this._buffers.getBuffer() : null;
    }
    // ---- begin view event handlers
    onDidChangeOptions() {
      this._lastRenderData = null;
      this._buffers = null;
      this._applyLayout();
      this._domNode.setClassName(this._getMinimapDomNodeClassName());
    }
    onSelectionChanged() {
      this._renderDecorations = true;
      return true;
    }
    onDecorationsChanged() {
      this._renderDecorations = true;
      return true;
    }
    onFlushed() {
      this._lastRenderData = null;
      return true;
    }
    onLinesChanged(changeFromLineNumber, changeCount) {
      if (this._lastRenderData) {
        return this._lastRenderData.onLinesChanged(changeFromLineNumber, changeCount);
      }
      return false;
    }
    onLinesDeleted(deleteFromLineNumber, deleteToLineNumber) {
      this._lastRenderData?.onLinesDeleted(deleteFromLineNumber, deleteToLineNumber);
      return true;
    }
    onLinesInserted(insertFromLineNumber, insertToLineNumber) {
      this._lastRenderData?.onLinesInserted(insertFromLineNumber, insertToLineNumber);
      return true;
    }
    onScrollChanged(e) {
      if (this._model.options.autohide === "scroll" && (e.scrollTopChanged || e.scrollHeightChanged)) {
        this._domNode.toggleClassName("active", true);
        this._hideSoon();
      }
      this._renderDecorations = true;
      return true;
    }
    onThemeChanged() {
      this._selectionColor = this._theme.getColor(minimapSelection);
      this._renderDecorations = true;
      return true;
    }
    onTokensChanged(ranges) {
      if (this._lastRenderData) {
        return this._lastRenderData.onTokensChanged(ranges);
      }
      return false;
    }
    onTokensColorsChanged() {
      this._lastRenderData = null;
      this._buffers = null;
      return true;
    }
    onZonesChanged() {
      this._lastRenderData = null;
      return true;
    }
    // --- end event handlers
    render(renderingCtx) {
      const renderMinimap = this._model.options.renderMinimap;
      if (renderMinimap === 0) {
        this._shadow.setClassName("minimap-shadow-hidden");
        this._sliderHorizontal.setWidth(0);
        this._sliderHorizontal.setHeight(0);
        return;
      }
      if (renderingCtx.scrollLeft + renderingCtx.viewportWidth >= renderingCtx.scrollWidth) {
        this._shadow.setClassName("minimap-shadow-hidden");
      } else {
        this._shadow.setClassName("minimap-shadow-visible");
      }
      const layout2 = MinimapLayout.create(this._model.options, renderingCtx.viewportStartLineNumber, renderingCtx.viewportEndLineNumber, renderingCtx.viewportStartLineNumberVerticalOffset, renderingCtx.viewportHeight, renderingCtx.viewportContainsWhitespaceGaps, this._model.getLineCount(), this._model.getRealLineCount(), renderingCtx.scrollTop, renderingCtx.scrollHeight, this._lastRenderData ? this._lastRenderData.renderedLayout : null);
      this._slider.setDisplay(layout2.sliderNeeded ? "block" : "none");
      this._slider.setTop(layout2.sliderTop);
      this._slider.setHeight(layout2.sliderHeight);
      this._sliderHorizontal.setLeft(0);
      this._sliderHorizontal.setWidth(this._model.options.minimapWidth);
      this._sliderHorizontal.setTop(0);
      this._sliderHorizontal.setHeight(layout2.sliderHeight);
      this.renderDecorations(layout2);
      this._lastRenderData = this.renderLines(layout2);
    }
    renderDecorations(layout2) {
      if (this._renderDecorations) {
        this._renderDecorations = false;
        const selections = this._model.getSelections();
        selections.sort(Range$2.compareRangesUsingStarts);
        const decorations = this._model.getMinimapDecorationsInViewport(layout2.startLineNumber, layout2.endLineNumber);
        decorations.sort((a, b) => (a.options.zIndex || 0) - (b.options.zIndex || 0));
        const { canvasInnerWidth, canvasInnerHeight } = this._model.options;
        const minimapLineHeight = this._model.options.minimapLineHeight;
        const minimapCharWidth = this._model.options.minimapCharWidth;
        const tabSize = this._model.getOptions().tabSize;
        const canvasContext = this._decorationsCanvas.domNode.getContext("2d");
        canvasContext.clearRect(0, 0, canvasInnerWidth, canvasInnerHeight);
        const highlightedLines = new ContiguousLineMap(layout2.startLineNumber, layout2.endLineNumber, false);
        this._renderSelectionLineHighlights(canvasContext, selections, highlightedLines, layout2, minimapLineHeight);
        this._renderDecorationsLineHighlights(canvasContext, decorations, highlightedLines, layout2, minimapLineHeight);
        const lineOffsetMap = new ContiguousLineMap(layout2.startLineNumber, layout2.endLineNumber, null);
        this._renderSelectionsHighlights(canvasContext, selections, lineOffsetMap, layout2, minimapLineHeight, tabSize, minimapCharWidth, canvasInnerWidth);
        this._renderDecorationsHighlights(canvasContext, decorations, lineOffsetMap, layout2, minimapLineHeight, tabSize, minimapCharWidth, canvasInnerWidth);
        this._renderSectionHeaders(layout2);
      }
    }
    _renderSelectionLineHighlights(canvasContext, selections, highlightedLines, layout2, minimapLineHeight) {
      if (!this._selectionColor || this._selectionColor.isTransparent()) {
        return;
      }
      canvasContext.fillStyle = this._selectionColor.transparent(0.5).toString();
      let y1 = 0;
      let y2 = 0;
      for (const selection of selections) {
        const intersection2 = layout2.intersectWithViewport(selection);
        if (!intersection2) {
          continue;
        }
        const [startLineNumber, endLineNumber] = intersection2;
        for (let line = startLineNumber; line <= endLineNumber; line++) {
          highlightedLines.set(line, true);
        }
        const yy1 = layout2.getYForLineNumber(startLineNumber, minimapLineHeight);
        const yy2 = layout2.getYForLineNumber(endLineNumber, minimapLineHeight);
        if (y2 >= yy1) {
          y2 = yy2;
        } else {
          if (y2 > y1) {
            canvasContext.fillRect(MINIMAP_GUTTER_WIDTH, y1, canvasContext.canvas.width, y2 - y1);
          }
          y1 = yy1;
          y2 = yy2;
        }
      }
      if (y2 > y1) {
        canvasContext.fillRect(MINIMAP_GUTTER_WIDTH, y1, canvasContext.canvas.width, y2 - y1);
      }
    }
    _renderDecorationsLineHighlights(canvasContext, decorations, highlightedLines, layout2, minimapLineHeight) {
      const highlightColors = /* @__PURE__ */ new Map();
      for (let i2 = decorations.length - 1; i2 >= 0; i2--) {
        const decoration2 = decorations[i2];
        const minimapOptions = decoration2.options.minimap;
        if (!minimapOptions || minimapOptions.position !== 1) {
          continue;
        }
        const intersection2 = layout2.intersectWithViewport(decoration2.range);
        if (!intersection2) {
          continue;
        }
        const [startLineNumber, endLineNumber] = intersection2;
        const decorationColor = minimapOptions.getColor(this._theme.value);
        if (!decorationColor || decorationColor.isTransparent()) {
          continue;
        }
        let highlightColor = highlightColors.get(decorationColor.toString());
        if (!highlightColor) {
          highlightColor = decorationColor.transparent(0.5).toString();
          highlightColors.set(decorationColor.toString(), highlightColor);
        }
        canvasContext.fillStyle = highlightColor;
        for (let line = startLineNumber; line <= endLineNumber; line++) {
          if (highlightedLines.has(line)) {
            continue;
          }
          highlightedLines.set(line, true);
          const y = layout2.getYForLineNumber(startLineNumber, minimapLineHeight);
          canvasContext.fillRect(MINIMAP_GUTTER_WIDTH, y, canvasContext.canvas.width, minimapLineHeight);
        }
      }
    }
    _renderSelectionsHighlights(canvasContext, selections, lineOffsetMap, layout2, lineHeight, tabSize, characterWidth, canvasInnerWidth) {
      if (!this._selectionColor || this._selectionColor.isTransparent()) {
        return;
      }
      for (const selection of selections) {
        const intersection2 = layout2.intersectWithViewport(selection);
        if (!intersection2) {
          continue;
        }
        const [startLineNumber, endLineNumber] = intersection2;
        for (let line = startLineNumber; line <= endLineNumber; line++) {
          this.renderDecorationOnLine(canvasContext, lineOffsetMap, selection, this._selectionColor, layout2, line, lineHeight, lineHeight, tabSize, characterWidth, canvasInnerWidth);
        }
      }
    }
    _renderDecorationsHighlights(canvasContext, decorations, lineOffsetMap, layout2, minimapLineHeight, tabSize, characterWidth, canvasInnerWidth) {
      for (const decoration2 of decorations) {
        const minimapOptions = decoration2.options.minimap;
        if (!minimapOptions) {
          continue;
        }
        const intersection2 = layout2.intersectWithViewport(decoration2.range);
        if (!intersection2) {
          continue;
        }
        const [startLineNumber, endLineNumber] = intersection2;
        const decorationColor = minimapOptions.getColor(this._theme.value);
        if (!decorationColor || decorationColor.isTransparent()) {
          continue;
        }
        for (let line = startLineNumber; line <= endLineNumber; line++) {
          switch (minimapOptions.position) {
            case 1:
              this.renderDecorationOnLine(canvasContext, lineOffsetMap, decoration2.range, decorationColor, layout2, line, minimapLineHeight, minimapLineHeight, tabSize, characterWidth, canvasInnerWidth);
              continue;
            case 2: {
              const y = layout2.getYForLineNumber(line, minimapLineHeight);
              const x = 2;
              this.renderDecoration(canvasContext, decorationColor, x, y, GUTTER_DECORATION_WIDTH, minimapLineHeight);
              continue;
            }
          }
        }
      }
    }
    renderDecorationOnLine(canvasContext, lineOffsetMap, decorationRange, decorationColor, layout2, lineNumber, height, minimapLineHeight, tabSize, charWidth, canvasInnerWidth) {
      const y = layout2.getYForLineNumber(lineNumber, minimapLineHeight);
      if (y + height < 0 || y > this._model.options.canvasInnerHeight) {
        return;
      }
      const { startLineNumber, endLineNumber } = decorationRange;
      const startColumn = startLineNumber === lineNumber ? decorationRange.startColumn : 1;
      const endColumn = endLineNumber === lineNumber ? decorationRange.endColumn : this._model.getLineMaxColumn(lineNumber);
      const x1 = this.getXOffsetForPosition(lineOffsetMap, lineNumber, startColumn, tabSize, charWidth, canvasInnerWidth);
      const x2 = this.getXOffsetForPosition(lineOffsetMap, lineNumber, endColumn, tabSize, charWidth, canvasInnerWidth);
      this.renderDecoration(canvasContext, decorationColor, x1, y, x2 - x1, height);
    }
    getXOffsetForPosition(lineOffsetMap, lineNumber, column, tabSize, charWidth, canvasInnerWidth) {
      if (column === 1) {
        return MINIMAP_GUTTER_WIDTH;
      }
      const minimumXOffset = (column - 1) * charWidth;
      if (minimumXOffset >= canvasInnerWidth) {
        return canvasInnerWidth;
      }
      let lineIndexToXOffset = lineOffsetMap.get(lineNumber);
      if (!lineIndexToXOffset) {
        const lineData = this._model.getLineContent(lineNumber);
        lineIndexToXOffset = [MINIMAP_GUTTER_WIDTH];
        let prevx = MINIMAP_GUTTER_WIDTH;
        for (let i2 = 1; i2 < lineData.length + 1; i2++) {
          const charCode = lineData.charCodeAt(i2 - 1);
          const dx = charCode === 9 ? tabSize * charWidth : isFullWidthCharacter(charCode) ? 2 * charWidth : charWidth;
          const x = prevx + dx;
          if (x >= canvasInnerWidth) {
            lineIndexToXOffset[i2] = canvasInnerWidth;
            break;
          }
          lineIndexToXOffset[i2] = x;
          prevx = x;
        }
        lineOffsetMap.set(lineNumber, lineIndexToXOffset);
      }
      if (column - 1 < lineIndexToXOffset.length) {
        return lineIndexToXOffset[column - 1];
      }
      return canvasInnerWidth;
    }
    renderDecoration(canvasContext, decorationColor, x, y, width2, height) {
      canvasContext.fillStyle = decorationColor && decorationColor.toString() || "";
      canvasContext.fillRect(x, y, width2, height);
    }
    _renderSectionHeaders(layout2) {
      const minimapLineHeight = this._model.options.minimapLineHeight;
      const sectionHeaderFontSize = this._model.options.sectionHeaderFontSize;
      const sectionHeaderLetterSpacing = this._model.options.sectionHeaderLetterSpacing;
      const backgroundFillHeight = sectionHeaderFontSize * 1.5;
      const { canvasInnerWidth } = this._model.options;
      const backgroundColor = this._model.options.backgroundColor;
      const backgroundFill = `rgb(${backgroundColor.r} ${backgroundColor.g} ${backgroundColor.b} / .7)`;
      const foregroundColor = this._model.options.sectionHeaderFontColor;
      const foregroundFill = `rgb(${foregroundColor.r} ${foregroundColor.g} ${foregroundColor.b})`;
      const separatorStroke = foregroundFill;
      const canvasContext = this._decorationsCanvas.domNode.getContext("2d");
      canvasContext.letterSpacing = sectionHeaderLetterSpacing + "px";
      canvasContext.font = "500 " + sectionHeaderFontSize + "px " + this._model.options.sectionHeaderFontFamily;
      canvasContext.strokeStyle = separatorStroke;
      canvasContext.lineWidth = 0.4;
      const decorations = this._model.getSectionHeaderDecorationsInViewport(layout2.startLineNumber, layout2.endLineNumber);
      decorations.sort((a, b) => a.range.startLineNumber - b.range.startLineNumber);
      const fitWidth = InnerMinimap._fitSectionHeader.bind(null, canvasContext, canvasInnerWidth - MINIMAP_GUTTER_WIDTH);
      for (const decoration2 of decorations) {
        const y = layout2.getYForLineNumber(decoration2.range.startLineNumber, minimapLineHeight) + sectionHeaderFontSize;
        const backgroundFillY = y - sectionHeaderFontSize;
        const separatorY = backgroundFillY + 2;
        const headerText = this._model.getSectionHeaderText(decoration2, fitWidth);
        InnerMinimap._renderSectionLabel(canvasContext, headerText, decoration2.options.minimap?.sectionHeaderStyle === 2, backgroundFill, foregroundFill, canvasInnerWidth, backgroundFillY, backgroundFillHeight, y, separatorY);
      }
    }
    static _fitSectionHeader(target, maxWidth, headerText) {
      if (!headerText) {
        return headerText;
      }
      const ellipsis = "…";
      const width2 = target.measureText(headerText).width;
      const ellipsisWidth = target.measureText(ellipsis).width;
      if (width2 <= maxWidth || width2 <= ellipsisWidth) {
        return headerText;
      }
      const len = headerText.length;
      const averageCharWidth = width2 / headerText.length;
      const maxCharCount = Math.floor((maxWidth - ellipsisWidth) / averageCharWidth) - 1;
      let halfCharCount = Math.ceil(maxCharCount / 2);
      while (halfCharCount > 0 && /\s/.test(headerText[halfCharCount - 1])) {
        --halfCharCount;
      }
      return headerText.substring(0, halfCharCount) + ellipsis + headerText.substring(len - (maxCharCount - halfCharCount));
    }
    static _renderSectionLabel(target, headerText, hasSeparatorLine, backgroundFill, foregroundFill, minimapWidth, backgroundFillY, backgroundFillHeight, textY, separatorY) {
      if (headerText) {
        target.fillStyle = backgroundFill;
        target.fillRect(0, backgroundFillY, minimapWidth, backgroundFillHeight);
        target.fillStyle = foregroundFill;
        target.fillText(headerText, MINIMAP_GUTTER_WIDTH, textY);
      }
      if (hasSeparatorLine) {
        target.beginPath();
        target.moveTo(0, separatorY);
        target.lineTo(minimapWidth, separatorY);
        target.closePath();
        target.stroke();
      }
    }
    renderLines(layout2) {
      const startLineNumber = layout2.startLineNumber;
      const endLineNumber = layout2.endLineNumber;
      const minimapLineHeight = this._model.options.minimapLineHeight;
      if (this._lastRenderData && this._lastRenderData.linesEquals(layout2)) {
        const _lastData = this._lastRenderData._get();
        return new RenderData(layout2, _lastData.imageData, _lastData.lines);
      }
      const imageData = this._getBuffer();
      if (!imageData) {
        return null;
      }
      const [_dirtyY1, _dirtyY2, needed] = InnerMinimap._renderUntouchedLines(imageData, layout2.topPaddingLineCount, startLineNumber, endLineNumber, minimapLineHeight, this._lastRenderData);
      const lineInfo = this._model.getMinimapLinesRenderingData(startLineNumber, endLineNumber, needed);
      const tabSize = this._model.getOptions().tabSize;
      const defaultBackground = this._model.options.defaultBackgroundColor;
      const background = this._model.options.backgroundColor;
      const foregroundAlpha = this._model.options.foregroundAlpha;
      const tokensColorTracker = this._model.tokensColorTracker;
      const useLighterFont = tokensColorTracker.backgroundIsLight();
      const renderMinimap = this._model.options.renderMinimap;
      const charRenderer = this._model.options.charRenderer();
      const fontScale = this._model.options.fontScale;
      const minimapCharWidth = this._model.options.minimapCharWidth;
      const baseCharHeight = renderMinimap === 1 ? 2 : 2 + 1;
      const renderMinimapLineHeight = baseCharHeight * fontScale;
      const innerLinePadding = minimapLineHeight > renderMinimapLineHeight ? Math.floor((minimapLineHeight - renderMinimapLineHeight) / 2) : 0;
      const backgroundA = background.a / 255;
      const renderBackground = new RGBA8(Math.round((background.r - defaultBackground.r) * backgroundA + defaultBackground.r), Math.round((background.g - defaultBackground.g) * backgroundA + defaultBackground.g), Math.round((background.b - defaultBackground.b) * backgroundA + defaultBackground.b), 255);
      let dy = layout2.topPaddingLineCount * minimapLineHeight;
      const renderedLines = [];
      for (let lineIndex = 0, lineCount = endLineNumber - startLineNumber + 1; lineIndex < lineCount; lineIndex++) {
        if (needed[lineIndex]) {
          InnerMinimap._renderLine(imageData, renderBackground, background.a, useLighterFont, renderMinimap, minimapCharWidth, tokensColorTracker, foregroundAlpha, charRenderer, dy, innerLinePadding, tabSize, lineInfo[lineIndex], fontScale, minimapLineHeight);
        }
        renderedLines[lineIndex] = new MinimapLine(dy);
        dy += minimapLineHeight;
      }
      const dirtyY1 = _dirtyY1 === -1 ? 0 : _dirtyY1;
      const dirtyY2 = _dirtyY2 === -1 ? imageData.height : _dirtyY2;
      const dirtyHeight = dirtyY2 - dirtyY1;
      const ctx = this._canvas.domNode.getContext("2d");
      ctx.putImageData(imageData, 0, 0, 0, dirtyY1, imageData.width, dirtyHeight);
      return new RenderData(layout2, imageData, renderedLines);
    }
    static _renderUntouchedLines(target, topPaddingLineCount, startLineNumber, endLineNumber, minimapLineHeight, lastRenderData) {
      const needed = [];
      if (!lastRenderData) {
        for (let i2 = 0, len = endLineNumber - startLineNumber + 1; i2 < len; i2++) {
          needed[i2] = true;
        }
        return [-1, -1, needed];
      }
      const _lastData = lastRenderData._get();
      const lastTargetData = _lastData.imageData.data;
      const lastStartLineNumber = _lastData.rendLineNumberStart;
      const lastLines = _lastData.lines;
      const lastLinesLength = lastLines.length;
      const WIDTH = target.width;
      const targetData = target.data;
      const maxDestPixel = (endLineNumber - startLineNumber + 1) * minimapLineHeight * WIDTH * 4;
      let dirtyPixel1 = -1;
      let dirtyPixel2 = -1;
      let copySourceStart = -1;
      let copySourceEnd = -1;
      let copyDestStart = -1;
      let copyDestEnd = -1;
      let dest_dy = topPaddingLineCount * minimapLineHeight;
      for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
        const lineIndex = lineNumber - startLineNumber;
        const lastLineIndex = lineNumber - lastStartLineNumber;
        const source_dy = lastLineIndex >= 0 && lastLineIndex < lastLinesLength ? lastLines[lastLineIndex].dy : -1;
        if (source_dy === -1) {
          needed[lineIndex] = true;
          dest_dy += minimapLineHeight;
          continue;
        }
        const sourceStart = source_dy * WIDTH * 4;
        const sourceEnd = (source_dy + minimapLineHeight) * WIDTH * 4;
        const destStart = dest_dy * WIDTH * 4;
        const destEnd = (dest_dy + minimapLineHeight) * WIDTH * 4;
        if (copySourceEnd === sourceStart && copyDestEnd === destStart) {
          copySourceEnd = sourceEnd;
          copyDestEnd = destEnd;
        } else {
          if (copySourceStart !== -1) {
            targetData.set(lastTargetData.subarray(copySourceStart, copySourceEnd), copyDestStart);
            if (dirtyPixel1 === -1 && copySourceStart === 0 && copySourceStart === copyDestStart) {
              dirtyPixel1 = copySourceEnd;
            }
            if (dirtyPixel2 === -1 && copySourceEnd === maxDestPixel && copySourceStart === copyDestStart) {
              dirtyPixel2 = copySourceStart;
            }
          }
          copySourceStart = sourceStart;
          copySourceEnd = sourceEnd;
          copyDestStart = destStart;
          copyDestEnd = destEnd;
        }
        needed[lineIndex] = false;
        dest_dy += minimapLineHeight;
      }
      if (copySourceStart !== -1) {
        targetData.set(lastTargetData.subarray(copySourceStart, copySourceEnd), copyDestStart);
        if (dirtyPixel1 === -1 && copySourceStart === 0 && copySourceStart === copyDestStart) {
          dirtyPixel1 = copySourceEnd;
        }
        if (dirtyPixel2 === -1 && copySourceEnd === maxDestPixel && copySourceStart === copyDestStart) {
          dirtyPixel2 = copySourceStart;
        }
      }
      const dirtyY1 = dirtyPixel1 === -1 ? -1 : dirtyPixel1 / (WIDTH * 4);
      const dirtyY2 = dirtyPixel2 === -1 ? -1 : dirtyPixel2 / (WIDTH * 4);
      return [dirtyY1, dirtyY2, needed];
    }
    static _renderLine(target, backgroundColor, backgroundAlpha, useLighterFont, renderMinimap, charWidth, colorTracker, foregroundAlpha, minimapCharRenderer, dy, innerLinePadding, tabSize, lineData, fontScale, minimapLineHeight) {
      const content = lineData.content;
      const tokens = lineData.tokens;
      const maxDx = target.width - charWidth;
      const force1pxHeight = minimapLineHeight === 1;
      let dx = MINIMAP_GUTTER_WIDTH;
      let charIndex = 0;
      let tabsCharDelta = 0;
      for (let tokenIndex = 0, tokensLen = tokens.getCount(); tokenIndex < tokensLen; tokenIndex++) {
        const tokenEndIndex = tokens.getEndOffset(tokenIndex);
        const tokenColorId = tokens.getForeground(tokenIndex);
        const tokenColor = colorTracker.getColor(tokenColorId);
        for (; charIndex < tokenEndIndex; charIndex++) {
          if (dx > maxDx) {
            return;
          }
          const charCode = content.charCodeAt(charIndex);
          if (charCode === 9) {
            const insertSpacesCount = tabSize - (charIndex + tabsCharDelta) % tabSize;
            tabsCharDelta += insertSpacesCount - 1;
            dx += insertSpacesCount * charWidth;
          } else if (charCode === 32) {
            dx += charWidth;
          } else {
            const count = isFullWidthCharacter(charCode) ? 2 : 1;
            for (let i2 = 0; i2 < count; i2++) {
              if (renderMinimap === 2) {
                minimapCharRenderer.blockRenderChar(target, dx, dy + innerLinePadding, tokenColor, foregroundAlpha, backgroundColor, backgroundAlpha, force1pxHeight);
              } else {
                minimapCharRenderer.renderChar(target, dx, dy + innerLinePadding, charCode, tokenColor, foregroundAlpha, backgroundColor, backgroundAlpha, fontScale, useLighterFont, force1pxHeight);
              }
              dx += charWidth;
              if (dx > maxDx) {
                return;
              }
            }
          }
        }
      }
    }
  }
  class ContiguousLineMap {
    constructor(startLineNumber, endLineNumber, defaultValue) {
      this._startLineNumber = startLineNumber;
      this._endLineNumber = endLineNumber;
      this._defaultValue = defaultValue;
      this._values = [];
      for (let i2 = 0, count = this._endLineNumber - this._startLineNumber + 1; i2 < count; i2++) {
        this._values[i2] = defaultValue;
      }
    }
    has(lineNumber) {
      return this.get(lineNumber) !== this._defaultValue;
    }
    set(lineNumber, value) {
      if (lineNumber < this._startLineNumber || lineNumber > this._endLineNumber) {
        return;
      }
      this._values[lineNumber - this._startLineNumber] = value;
    }
    get(lineNumber) {
      if (lineNumber < this._startLineNumber || lineNumber > this._endLineNumber) {
        return this._defaultValue;
      }
      return this._values[lineNumber - this._startLineNumber];
    }
  }
  class ViewOverlayWidgets extends ViewPart {
    constructor(context, viewDomNode) {
      super(context);
      this._viewDomNode = viewDomNode;
      const options = this._context.configuration.options;
      const layoutInfo = options.get(
        165
        /* EditorOption.layoutInfo */
      );
      this._widgets = {};
      this._verticalScrollbarWidth = layoutInfo.verticalScrollbarWidth;
      this._minimapWidth = layoutInfo.minimap.minimapWidth;
      this._horizontalScrollbarHeight = layoutInfo.horizontalScrollbarHeight;
      this._editorHeight = layoutInfo.height;
      this._editorWidth = layoutInfo.width;
      this._viewDomNodeRect = { top: 0, left: 0, width: 0, height: 0 };
      this._domNode = createFastDomNode(document.createElement("div"));
      PartFingerprints.write(
        this._domNode,
        4
        /* PartFingerprint.OverlayWidgets */
      );
      this._domNode.setClassName("overlayWidgets");
      this.overflowingOverlayWidgetsDomNode = createFastDomNode(document.createElement("div"));
      PartFingerprints.write(
        this.overflowingOverlayWidgetsDomNode,
        5
        /* PartFingerprint.OverflowingOverlayWidgets */
      );
      this.overflowingOverlayWidgetsDomNode.setClassName("overflowingOverlayWidgets");
    }
    dispose() {
      super.dispose();
      this._widgets = {};
    }
    getDomNode() {
      return this._domNode;
    }
    // ---- begin view event handlers
    onConfigurationChanged(e) {
      const options = this._context.configuration.options;
      const layoutInfo = options.get(
        165
        /* EditorOption.layoutInfo */
      );
      this._verticalScrollbarWidth = layoutInfo.verticalScrollbarWidth;
      this._minimapWidth = layoutInfo.minimap.minimapWidth;
      this._horizontalScrollbarHeight = layoutInfo.horizontalScrollbarHeight;
      this._editorHeight = layoutInfo.height;
      this._editorWidth = layoutInfo.width;
      return true;
    }
    // ---- end view event handlers
    _widgetCanOverflow(widget) {
      const options = this._context.configuration.options;
      const allowOverflow = options.get(
        4
        /* EditorOption.allowOverflow */
      );
      return (widget.allowEditorOverflow || false) && allowOverflow;
    }
    addWidget(widget) {
      const domNode = createFastDomNode(widget.getDomNode());
      this._widgets[widget.getId()] = {
        widget,
        preference: null,
        domNode
      };
      domNode.setPosition("absolute");
      domNode.setAttribute("widgetId", widget.getId());
      if (this._widgetCanOverflow(widget)) {
        this.overflowingOverlayWidgetsDomNode.appendChild(domNode);
      } else {
        this._domNode.appendChild(domNode);
      }
      this.setShouldRender();
      this._updateMaxMinWidth();
    }
    setWidgetPosition(widget, position) {
      const widgetData = this._widgets[widget.getId()];
      const preference = position ? position.preference : null;
      const stack = position?.stackOridinal;
      if (widgetData.preference === preference && widgetData.stack === stack) {
        this._updateMaxMinWidth();
        return false;
      }
      widgetData.preference = preference;
      widgetData.stack = stack;
      this.setShouldRender();
      this._updateMaxMinWidth();
      return true;
    }
    removeWidget(widget) {
      const widgetId = widget.getId();
      if (this._widgets.hasOwnProperty(widgetId)) {
        const widgetData = this._widgets[widgetId];
        const domNode = widgetData.domNode.domNode;
        delete this._widgets[widgetId];
        domNode.remove();
        this.setShouldRender();
        this._updateMaxMinWidth();
      }
    }
    _updateMaxMinWidth() {
      let maxMinWidth = 0;
      const keys = Object.keys(this._widgets);
      for (let i2 = 0, len = keys.length; i2 < len; i2++) {
        const widgetId = keys[i2];
        const widget = this._widgets[widgetId];
        const widgetMinWidthInPx = widget.widget.getMinContentWidthInPx?.();
        if (typeof widgetMinWidthInPx !== "undefined") {
          maxMinWidth = Math.max(maxMinWidth, widgetMinWidthInPx);
        }
      }
      this._context.viewLayout.setOverlayWidgetsMinWidth(maxMinWidth);
    }
    _renderWidget(widgetData, stackCoordinates) {
      const domNode = widgetData.domNode;
      if (widgetData.preference === null) {
        domNode.setTop("");
        return;
      }
      const maxRight = 2 * this._verticalScrollbarWidth + this._minimapWidth;
      if (widgetData.preference === 0 || widgetData.preference === 1) {
        if (widgetData.preference === 1) {
          const widgetHeight = domNode.domNode.clientHeight;
          domNode.setTop(this._editorHeight - widgetHeight - 2 * this._horizontalScrollbarHeight);
        } else {
          domNode.setTop(0);
        }
        if (widgetData.stack !== void 0) {
          domNode.setTop(stackCoordinates[widgetData.preference]);
          stackCoordinates[widgetData.preference] += domNode.domNode.clientWidth;
        } else {
          domNode.setRight(maxRight);
        }
      } else if (widgetData.preference === 2) {
        domNode.domNode.style.right = "50%";
        if (widgetData.stack !== void 0) {
          domNode.setTop(stackCoordinates[
            2
            /* OverlayWidgetPositionPreference.TOP_CENTER */
          ]);
          stackCoordinates[
            2
            /* OverlayWidgetPositionPreference.TOP_CENTER */
          ] += domNode.domNode.clientHeight;
        } else {
          domNode.setTop(0);
        }
      } else {
        const { top, left } = widgetData.preference;
        const fixedOverflowWidgets = this._context.configuration.options.get(
          51
          /* EditorOption.fixedOverflowWidgets */
        );
        if (fixedOverflowWidgets && this._widgetCanOverflow(widgetData.widget)) {
          const editorBoundingBox = this._viewDomNodeRect;
          domNode.setTop(top + editorBoundingBox.top);
          domNode.setLeft(left + editorBoundingBox.left);
          domNode.setPosition("fixed");
        } else {
          domNode.setTop(top);
          domNode.setLeft(left);
          domNode.setPosition("absolute");
        }
      }
    }
    prepareRender(ctx) {
      this._viewDomNodeRect = getDomNodePagePosition(this._viewDomNode.domNode);
    }
    render(ctx) {
      this._domNode.setWidth(this._editorWidth);
      const keys = Object.keys(this._widgets);
      const stackCoordinates = Array.from({ length: 2 + 1 }, () => 0);
      keys.sort((a, b) => (this._widgets[a].stack || 0) - (this._widgets[b].stack || 0));
      for (let i2 = 0, len = keys.length; i2 < len; i2++) {
        const widgetId = keys[i2];
        this._renderWidget(this._widgets[widgetId], stackCoordinates);
      }
    }
  }
  class Viewport {
    constructor(top, left, width2, height) {
      this._viewportBrand = void 0;
      this.top = top | 0;
      this.left = left | 0;
      this.width = width2 | 0;
      this.height = height | 0;
    }
  }
  class MinimapLinesRenderingData {
    constructor(tabSize, data) {
      this.tabSize = tabSize;
      this.data = data;
    }
  }
  class ViewLineData {
    constructor(content, continuesWithWrappedLine, minColumn, maxColumn, startVisibleColumn, tokens, inlineDecorations) {
      this._viewLineDataBrand = void 0;
      this.content = content;
      this.continuesWithWrappedLine = continuesWithWrappedLine;
      this.minColumn = minColumn;
      this.maxColumn = maxColumn;
      this.startVisibleColumn = startVisibleColumn;
      this.tokens = tokens;
      this.inlineDecorations = inlineDecorations;
    }
  }
  class ViewLineRenderingData {
    constructor(minColumn, maxColumn, content, continuesWithWrappedLine, mightContainRTL, mightContainNonBasicASCII, tokens, inlineDecorations, tabSize, startVisibleColumn, textDirection, hasVariableFonts) {
      this.minColumn = minColumn;
      this.maxColumn = maxColumn;
      this.content = content;
      this.continuesWithWrappedLine = continuesWithWrappedLine;
      this.isBasicASCII = ViewLineRenderingData.isBasicASCII(content, mightContainNonBasicASCII);
      this.containsRTL = ViewLineRenderingData.containsRTL(content, this.isBasicASCII, mightContainRTL);
      this.tokens = tokens;
      this.inlineDecorations = inlineDecorations;
      this.tabSize = tabSize;
      this.startVisibleColumn = startVisibleColumn;
      this.textDirection = textDirection;
      this.hasVariableFonts = hasVariableFonts;
    }
    static isBasicASCII(lineContent, mightContainNonBasicASCII) {
      if (mightContainNonBasicASCII) {
        return isBasicASCII(lineContent);
      }
      return true;
    }
    static containsRTL(lineContent, isBasicASCII2, mightContainRTL) {
      if (!isBasicASCII2 && mightContainRTL) {
        return containsRTL(lineContent);
      }
      return false;
    }
  }
  class OverviewRulerDecorationsGroup {
    constructor(color, zIndex, data) {
      this.color = color;
      this.zIndex = zIndex;
      this.data = data;
    }
    static compareByRenderingProps(a, b) {
      if (a.zIndex === b.zIndex) {
        if (a.color < b.color) {
          return -1;
        }
        if (a.color > b.color) {
          return 1;
        }
        return 0;
      }
      return a.zIndex - b.zIndex;
    }
    static equals(a, b) {
      return a.color === b.color && a.zIndex === b.zIndex && equals$1(a.data, b.data);
    }
    static equalsArr(a, b) {
      return equals$1(a, b, OverviewRulerDecorationsGroup.equals);
    }
  }
  class Settings {
    constructor(config, theme) {
      const options = config.options;
      this.lineHeight = options.get(
        75
        /* EditorOption.lineHeight */
      );
      this.pixelRatio = options.get(
        163
        /* EditorOption.pixelRatio */
      );
      this.overviewRulerLanes = options.get(
        95
        /* EditorOption.overviewRulerLanes */
      );
      this.renderBorder = options.get(
        94
        /* EditorOption.overviewRulerBorder */
      );
      const borderColor = theme.getColor(editorOverviewRulerBorder);
      this.borderColor = borderColor ? borderColor.toString() : null;
      this.hideCursor = options.get(
        68
        /* EditorOption.hideCursorInOverviewRuler */
      );
      const cursorColorSingle = theme.getColor(editorCursorForeground);
      this.cursorColorSingle = cursorColorSingle ? cursorColorSingle.transparent(0.7).toString() : null;
      const cursorColorPrimary = theme.getColor(editorMultiCursorPrimaryForeground);
      this.cursorColorPrimary = cursorColorPrimary ? cursorColorPrimary.transparent(0.7).toString() : null;
      const cursorColorSecondary = theme.getColor(editorMultiCursorSecondaryForeground);
      this.cursorColorSecondary = cursorColorSecondary ? cursorColorSecondary.transparent(0.7).toString() : null;
      this.themeType = theme.type;
      const minimapOpts = options.get(
        81
        /* EditorOption.minimap */
      );
      const minimapEnabled = minimapOpts.enabled;
      const minimapSide = minimapOpts.side;
      const themeColor = theme.getColor(editorOverviewRulerBackground);
      const defaultBackground = TokenizationRegistry.getDefaultBackground();
      if (themeColor) {
        this.backgroundColor = themeColor;
      } else if (minimapEnabled && minimapSide === "right") {
        this.backgroundColor = defaultBackground;
      } else {
        this.backgroundColor = null;
      }
      const layoutInfo = options.get(
        165
        /* EditorOption.layoutInfo */
      );
      const position = layoutInfo.overviewRuler;
      this.top = position.top;
      this.right = position.right;
      this.domWidth = position.width;
      this.domHeight = position.height;
      if (this.overviewRulerLanes === 0) {
        this.canvasWidth = 0;
        this.canvasHeight = 0;
      } else {
        this.canvasWidth = this.domWidth * this.pixelRatio | 0;
        this.canvasHeight = this.domHeight * this.pixelRatio | 0;
      }
      const [x, w] = this._initLanes(1, this.canvasWidth, this.overviewRulerLanes);
      this.x = x;
      this.w = w;
    }
    _initLanes(canvasLeftOffset, canvasWidth, laneCount) {
      const remainingWidth = canvasWidth - canvasLeftOffset;
      if (laneCount >= 3) {
        const leftWidth = Math.floor(remainingWidth / 3);
        const rightWidth = Math.floor(remainingWidth / 3);
        const centerWidth = remainingWidth - leftWidth - rightWidth;
        const leftOffset = canvasLeftOffset;
        const centerOffset = leftOffset + leftWidth;
        const rightOffset = leftOffset + leftWidth + centerWidth;
        return [
          [
            0,
            leftOffset,
            // Left
            centerOffset,
            // Center
            leftOffset,
            // Left | Center
            rightOffset,
            // Right
            leftOffset,
            // Left | Right
            centerOffset,
            // Center | Right
            leftOffset
            // Left | Center | Right
          ],
          [
            0,
            leftWidth,
            // Left
            centerWidth,
            // Center
            leftWidth + centerWidth,
            // Left | Center
            rightWidth,
            // Right
            leftWidth + centerWidth + rightWidth,
            // Left | Right
            centerWidth + rightWidth,
            // Center | Right
            leftWidth + centerWidth + rightWidth
            // Left | Center | Right
          ]
        ];
      } else if (laneCount === 2) {
        const leftWidth = Math.floor(remainingWidth / 2);
        const rightWidth = remainingWidth - leftWidth;
        const leftOffset = canvasLeftOffset;
        const rightOffset = leftOffset + leftWidth;
        return [
          [
            0,
            leftOffset,
            // Left
            leftOffset,
            // Center
            leftOffset,
            // Left | Center
            rightOffset,
            // Right
            leftOffset,
            // Left | Right
            leftOffset,
            // Center | Right
            leftOffset
            // Left | Center | Right
          ],
          [
            0,
            leftWidth,
            // Left
            leftWidth,
            // Center
            leftWidth,
            // Left | Center
            rightWidth,
            // Right
            leftWidth + rightWidth,
            // Left | Right
            leftWidth + rightWidth,
            // Center | Right
            leftWidth + rightWidth
            // Left | Center | Right
          ]
        ];
      } else {
        const offset = canvasLeftOffset;
        const width2 = remainingWidth;
        return [
          [
            0,
            offset,
            // Left
            offset,
            // Center
            offset,
            // Left | Center
            offset,
            // Right
            offset,
            // Left | Right
            offset,
            // Center | Right
            offset
            // Left | Center | Right
          ],
          [
            0,
            width2,
            // Left
            width2,
            // Center
            width2,
            // Left | Center
            width2,
            // Right
            width2,
            // Left | Right
            width2,
            // Center | Right
            width2
            // Left | Center | Right
          ]
        ];
      }
    }
    equals(other) {
      return this.lineHeight === other.lineHeight && this.pixelRatio === other.pixelRatio && this.overviewRulerLanes === other.overviewRulerLanes && this.renderBorder === other.renderBorder && this.borderColor === other.borderColor && this.hideCursor === other.hideCursor && this.cursorColorSingle === other.cursorColorSingle && this.cursorColorPrimary === other.cursorColorPrimary && this.cursorColorSecondary === other.cursorColorSecondary && this.themeType === other.themeType && Color.equals(this.backgroundColor, other.backgroundColor) && this.top === other.top && this.right === other.right && this.domWidth === other.domWidth && this.domHeight === other.domHeight && this.canvasWidth === other.canvasWidth && this.canvasHeight === other.canvasHeight;
    }
  }
  class DecorationsOverviewRuler extends ViewPart {
    constructor(context) {
      super(context);
      this._actualShouldRender = 0;
      this._renderedDecorations = [];
      this._renderedCursorPositions = [];
      this._domNode = createFastDomNode(document.createElement("canvas"));
      this._domNode.setClassName("decorationsOverviewRuler");
      this._domNode.setPosition("absolute");
      this._domNode.setLayerHinting(true);
      this._domNode.setContain("strict");
      this._domNode.setAttribute("aria-hidden", "true");
      this._updateSettings(false);
      this._tokensColorTrackerListener = TokenizationRegistry.onDidChange((e) => {
        if (e.changedColorMap) {
          this._updateSettings(true);
        }
      });
      this._cursorPositions = [{ position: new Position$1(1, 1), color: this._settings.cursorColorSingle }];
    }
    dispose() {
      super.dispose();
      this._tokensColorTrackerListener.dispose();
    }
    _updateSettings(renderNow) {
      const newSettings = new Settings(this._context.configuration, this._context.theme);
      if (this._settings && this._settings.equals(newSettings)) {
        return false;
      }
      this._settings = newSettings;
      this._domNode.setTop(this._settings.top);
      this._domNode.setRight(this._settings.right);
      this._domNode.setWidth(this._settings.domWidth);
      this._domNode.setHeight(this._settings.domHeight);
      this._domNode.domNode.width = this._settings.canvasWidth;
      this._domNode.domNode.height = this._settings.canvasHeight;
      if (renderNow) {
        this._render();
      }
      return true;
    }
    // ---- begin view event handlers
    _markRenderingIsNeeded() {
      this._actualShouldRender = 2;
      return true;
    }
    _markRenderingIsMaybeNeeded() {
      this._actualShouldRender = 1;
      return true;
    }
    onConfigurationChanged(e) {
      return this._updateSettings(false) ? this._markRenderingIsNeeded() : false;
    }
    onCursorStateChanged(e) {
      this._cursorPositions = [];
      for (let i2 = 0, len = e.selections.length; i2 < len; i2++) {
        let color = this._settings.cursorColorSingle;
        if (len > 1) {
          color = i2 === 0 ? this._settings.cursorColorPrimary : this._settings.cursorColorSecondary;
        }
        this._cursorPositions.push({ position: e.selections[i2].getPosition(), color });
      }
      this._cursorPositions.sort((a, b) => Position$1.compare(a.position, b.position));
      return this._markRenderingIsMaybeNeeded();
    }
    onDecorationsChanged(e) {
      if (e.affectsOverviewRuler) {
        return this._markRenderingIsMaybeNeeded();
      }
      return false;
    }
    onFlushed(e) {
      return this._markRenderingIsNeeded();
    }
    onScrollChanged(e) {
      return e.scrollHeightChanged ? this._markRenderingIsNeeded() : false;
    }
    onZonesChanged(e) {
      return this._markRenderingIsNeeded();
    }
    onThemeChanged(e) {
      return this._updateSettings(false) ? this._markRenderingIsNeeded() : false;
    }
    // ---- end view event handlers
    getDomNode() {
      return this._domNode.domNode;
    }
    prepareRender(ctx) {
    }
    render(editorCtx) {
      this._render();
      this._actualShouldRender = 0;
    }
    _render() {
      const backgroundColor = this._settings.backgroundColor;
      if (this._settings.overviewRulerLanes === 0) {
        this._domNode.setBackgroundColor(backgroundColor ? Color.Format.CSS.formatHexA(backgroundColor) : "");
        this._domNode.setDisplay("none");
        return;
      }
      const decorations = this._context.viewModel.getAllOverviewRulerDecorations(this._context.theme);
      decorations.sort(OverviewRulerDecorationsGroup.compareByRenderingProps);
      if (this._actualShouldRender === 1 && !OverviewRulerDecorationsGroup.equalsArr(this._renderedDecorations, decorations)) {
        this._actualShouldRender = 2;
      }
      if (this._actualShouldRender === 1 && !equals$1(this._renderedCursorPositions, this._cursorPositions, (a, b) => a.position.lineNumber === b.position.lineNumber && a.color === b.color)) {
        this._actualShouldRender = 2;
      }
      if (this._actualShouldRender === 1) {
        return;
      }
      this._renderedDecorations = decorations;
      this._renderedCursorPositions = this._cursorPositions;
      this._domNode.setDisplay("block");
      const canvasWidth = this._settings.canvasWidth;
      const canvasHeight = this._settings.canvasHeight;
      const lineHeight = this._settings.lineHeight;
      const viewLayout = this._context.viewLayout;
      const outerHeight = this._context.viewLayout.getScrollHeight();
      const heightRatio = canvasHeight / outerHeight;
      const minDecorationHeight = 6 * this._settings.pixelRatio | 0;
      const halfMinDecorationHeight = minDecorationHeight / 2 | 0;
      const canvasCtx = this._domNode.domNode.getContext("2d");
      if (backgroundColor) {
        if (backgroundColor.isOpaque()) {
          canvasCtx.fillStyle = Color.Format.CSS.formatHexA(backgroundColor);
          canvasCtx.fillRect(0, 0, canvasWidth, canvasHeight);
        } else {
          canvasCtx.clearRect(0, 0, canvasWidth, canvasHeight);
          canvasCtx.fillStyle = Color.Format.CSS.formatHexA(backgroundColor);
          canvasCtx.fillRect(0, 0, canvasWidth, canvasHeight);
        }
      } else {
        canvasCtx.clearRect(0, 0, canvasWidth, canvasHeight);
      }
      const x = this._settings.x;
      const w = this._settings.w;
      for (const decorationGroup of decorations) {
        const color = decorationGroup.color;
        const decorationGroupData = decorationGroup.data;
        canvasCtx.fillStyle = color;
        let prevLane = 0;
        let prevY1 = 0;
        let prevY2 = 0;
        for (let i2 = 0, len = decorationGroupData.length / 3; i2 < len; i2++) {
          const lane = decorationGroupData[3 * i2];
          const startLineNumber = decorationGroupData[3 * i2 + 1];
          const endLineNumber = decorationGroupData[3 * i2 + 2];
          let y1 = viewLayout.getVerticalOffsetForLineNumber(startLineNumber) * heightRatio | 0;
          let y2 = (viewLayout.getVerticalOffsetForLineNumber(endLineNumber) + lineHeight) * heightRatio | 0;
          const height = y2 - y1;
          if (height < minDecorationHeight) {
            let yCenter = (y1 + y2) / 2 | 0;
            if (yCenter < halfMinDecorationHeight) {
              yCenter = halfMinDecorationHeight;
            } else if (yCenter + halfMinDecorationHeight > canvasHeight) {
              yCenter = canvasHeight - halfMinDecorationHeight;
            }
            y1 = yCenter - halfMinDecorationHeight;
            y2 = yCenter + halfMinDecorationHeight;
          }
          if (y1 > prevY2 + 1 || lane !== prevLane) {
            if (i2 !== 0) {
              canvasCtx.fillRect(x[prevLane], prevY1, w[prevLane], prevY2 - prevY1);
            }
            prevLane = lane;
            prevY1 = y1;
            prevY2 = y2;
          } else {
            if (y2 > prevY2) {
              prevY2 = y2;
            }
          }
        }
        canvasCtx.fillRect(x[prevLane], prevY1, w[prevLane], prevY2 - prevY1);
      }
      if (!this._settings.hideCursor) {
        const cursorHeight = 2 * this._settings.pixelRatio | 0;
        const halfCursorHeight = cursorHeight / 2 | 0;
        const cursorX = this._settings.x[
          7
          /* OverviewRulerLane.Full */
        ];
        const cursorW = this._settings.w[
          7
          /* OverviewRulerLane.Full */
        ];
        let prevY1 = -100;
        let prevY2 = -100;
        let prevColor = null;
        for (let i2 = 0, len = this._cursorPositions.length; i2 < len; i2++) {
          const color = this._cursorPositions[i2].color;
          if (!color) {
            continue;
          }
          const cursor = this._cursorPositions[i2].position;
          let yCenter = viewLayout.getVerticalOffsetForLineNumber(cursor.lineNumber) * heightRatio | 0;
          if (yCenter < halfCursorHeight) {
            yCenter = halfCursorHeight;
          } else if (yCenter + halfCursorHeight > canvasHeight) {
            yCenter = canvasHeight - halfCursorHeight;
          }
          const y1 = yCenter - halfCursorHeight;
          const y2 = y1 + cursorHeight;
          if (y1 > prevY2 + 1 || color !== prevColor) {
            if (i2 !== 0 && prevColor) {
              canvasCtx.fillRect(cursorX, prevY1, cursorW, prevY2 - prevY1);
            }
            prevY1 = y1;
            prevY2 = y2;
          } else {
            if (y2 > prevY2) {
              prevY2 = y2;
            }
          }
          prevColor = color;
          canvasCtx.fillStyle = color;
        }
        if (prevColor) {
          canvasCtx.fillRect(cursorX, prevY1, cursorW, prevY2 - prevY1);
        }
      }
      if (this._settings.renderBorder && this._settings.borderColor && this._settings.overviewRulerLanes > 0) {
        canvasCtx.beginPath();
        canvasCtx.lineWidth = 1;
        canvasCtx.strokeStyle = this._settings.borderColor;
        canvasCtx.moveTo(0, 0);
        canvasCtx.lineTo(0, canvasHeight);
        canvasCtx.moveTo(1, 0);
        canvasCtx.lineTo(canvasWidth, 0);
        canvasCtx.stroke();
      }
    }
  }
  class ColorZone {
    constructor(from, to, colorId) {
      this._colorZoneBrand = void 0;
      this.from = from | 0;
      this.to = to | 0;
      this.colorId = colorId | 0;
    }
    static compare(a, b) {
      if (a.colorId === b.colorId) {
        if (a.from === b.from) {
          return a.to - b.to;
        }
        return a.from - b.from;
      }
      return a.colorId - b.colorId;
    }
  }
  class OverviewRulerZone {
    constructor(startLineNumber, endLineNumber, heightInLines, color) {
      this._overviewRulerZoneBrand = void 0;
      this.startLineNumber = startLineNumber;
      this.endLineNumber = endLineNumber;
      this.heightInLines = heightInLines;
      this.color = color;
      this._colorZone = null;
    }
    static compare(a, b) {
      if (a.color === b.color) {
        if (a.startLineNumber === b.startLineNumber) {
          if (a.heightInLines === b.heightInLines) {
            return a.endLineNumber - b.endLineNumber;
          }
          return a.heightInLines - b.heightInLines;
        }
        return a.startLineNumber - b.startLineNumber;
      }
      return a.color < b.color ? -1 : 1;
    }
    setColorZone(colorZone) {
      this._colorZone = colorZone;
    }
    getColorZones() {
      return this._colorZone;
    }
  }
  class OverviewZoneManager {
    constructor(getVerticalOffsetForLine) {
      this._getVerticalOffsetForLine = getVerticalOffsetForLine;
      this._zones = [];
      this._colorZonesInvalid = false;
      this._lineHeight = 0;
      this._domWidth = 0;
      this._domHeight = 0;
      this._outerHeight = 0;
      this._pixelRatio = 1;
      this._lastAssignedId = 0;
      this._color2Id = /* @__PURE__ */ Object.create(null);
      this._id2Color = [];
    }
    getId2Color() {
      return this._id2Color;
    }
    setZones(newZones) {
      this._zones = newZones;
      this._zones.sort(OverviewRulerZone.compare);
    }
    setLineHeight(lineHeight) {
      if (this._lineHeight === lineHeight) {
        return false;
      }
      this._lineHeight = lineHeight;
      this._colorZonesInvalid = true;
      return true;
    }
    setPixelRatio(pixelRatio) {
      this._pixelRatio = pixelRatio;
      this._colorZonesInvalid = true;
    }
    getDOMWidth() {
      return this._domWidth;
    }
    getCanvasWidth() {
      return this._domWidth * this._pixelRatio;
    }
    setDOMWidth(width2) {
      if (this._domWidth === width2) {
        return false;
      }
      this._domWidth = width2;
      this._colorZonesInvalid = true;
      return true;
    }
    getDOMHeight() {
      return this._domHeight;
    }
    getCanvasHeight() {
      return this._domHeight * this._pixelRatio;
    }
    setDOMHeight(height) {
      if (this._domHeight === height) {
        return false;
      }
      this._domHeight = height;
      this._colorZonesInvalid = true;
      return true;
    }
    getOuterHeight() {
      return this._outerHeight;
    }
    setOuterHeight(outerHeight) {
      if (this._outerHeight === outerHeight) {
        return false;
      }
      this._outerHeight = outerHeight;
      this._colorZonesInvalid = true;
      return true;
    }
    resolveColorZones() {
      const colorZonesInvalid = this._colorZonesInvalid;
      const lineHeight = Math.floor(this._lineHeight);
      const totalHeight = Math.floor(this.getCanvasHeight());
      const outerHeight = Math.floor(this._outerHeight);
      const heightRatio = totalHeight / outerHeight;
      const halfMinimumHeight = Math.floor(4 * this._pixelRatio / 2);
      const allColorZones = [];
      for (let i2 = 0, len = this._zones.length; i2 < len; i2++) {
        const zone = this._zones[i2];
        if (!colorZonesInvalid) {
          const colorZone2 = zone.getColorZones();
          if (colorZone2) {
            allColorZones.push(colorZone2);
            continue;
          }
        }
        const offset1 = this._getVerticalOffsetForLine(zone.startLineNumber);
        const offset2 = zone.heightInLines === 0 ? this._getVerticalOffsetForLine(zone.endLineNumber) + lineHeight : offset1 + zone.heightInLines * lineHeight;
        const y1 = Math.floor(heightRatio * offset1);
        const y2 = Math.floor(heightRatio * offset2);
        let ycenter = Math.floor((y1 + y2) / 2);
        let halfHeight = y2 - ycenter;
        if (halfHeight < halfMinimumHeight) {
          halfHeight = halfMinimumHeight;
        }
        if (ycenter - halfHeight < 0) {
          ycenter = halfHeight;
        }
        if (ycenter + halfHeight > totalHeight) {
          ycenter = totalHeight - halfHeight;
        }
        const color = zone.color;
        let colorId = this._color2Id[color];
        if (!colorId) {
          colorId = ++this._lastAssignedId;
          this._color2Id[color] = colorId;
          this._id2Color[colorId] = color;
        }
        const colorZone = new ColorZone(ycenter - halfHeight, ycenter + halfHeight, colorId);
        zone.setColorZone(colorZone);
        allColorZones.push(colorZone);
      }
      this._colorZonesInvalid = false;
      allColorZones.sort(ColorZone.compare);
      return allColorZones;
    }
  }
  class OverviewRuler extends ViewEventHandler {
    constructor(context, cssClassName) {
      super();
      this._context = context;
      const options = this._context.configuration.options;
      this._domNode = createFastDomNode(document.createElement("canvas"));
      this._domNode.setClassName(cssClassName);
      this._domNode.setPosition("absolute");
      this._domNode.setLayerHinting(true);
      this._domNode.setContain("strict");
      this._zoneManager = new OverviewZoneManager((lineNumber) => this._context.viewLayout.getVerticalOffsetForLineNumber(lineNumber));
      this._zoneManager.setDOMWidth(0);
      this._zoneManager.setDOMHeight(0);
      this._zoneManager.setOuterHeight(this._context.viewLayout.getScrollHeight());
      this._zoneManager.setLineHeight(options.get(
        75
        /* EditorOption.lineHeight */
      ));
      this._zoneManager.setPixelRatio(options.get(
        163
        /* EditorOption.pixelRatio */
      ));
      this._context.addEventHandler(this);
    }
    dispose() {
      this._context.removeEventHandler(this);
      super.dispose();
    }
    // ---- begin view event handlers
    onConfigurationChanged(e) {
      const options = this._context.configuration.options;
      if (e.hasChanged(
        75
        /* EditorOption.lineHeight */
      )) {
        this._zoneManager.setLineHeight(options.get(
          75
          /* EditorOption.lineHeight */
        ));
        this._render();
      }
      if (e.hasChanged(
        163
        /* EditorOption.pixelRatio */
      )) {
        this._zoneManager.setPixelRatio(options.get(
          163
          /* EditorOption.pixelRatio */
        ));
        this._domNode.setWidth(this._zoneManager.getDOMWidth());
        this._domNode.setHeight(this._zoneManager.getDOMHeight());
        this._domNode.domNode.width = this._zoneManager.getCanvasWidth();
        this._domNode.domNode.height = this._zoneManager.getCanvasHeight();
        this._render();
      }
      return true;
    }
    onFlushed(e) {
      this._render();
      return true;
    }
    onScrollChanged(e) {
      if (e.scrollHeightChanged) {
        this._zoneManager.setOuterHeight(e.scrollHeight);
        this._render();
      }
      return true;
    }
    onZonesChanged(e) {
      this._render();
      return true;
    }
    // ---- end view event handlers
    getDomNode() {
      return this._domNode.domNode;
    }
    setLayout(position) {
      this._domNode.setTop(position.top);
      this._domNode.setRight(position.right);
      let hasChanged = false;
      hasChanged = this._zoneManager.setDOMWidth(position.width) || hasChanged;
      hasChanged = this._zoneManager.setDOMHeight(position.height) || hasChanged;
      if (hasChanged) {
        this._domNode.setWidth(this._zoneManager.getDOMWidth());
        this._domNode.setHeight(this._zoneManager.getDOMHeight());
        this._domNode.domNode.width = this._zoneManager.getCanvasWidth();
        this._domNode.domNode.height = this._zoneManager.getCanvasHeight();
        this._render();
      }
    }
    setZones(zones) {
      this._zoneManager.setZones(zones);
      this._render();
    }
    _render() {
      if (this._zoneManager.getOuterHeight() === 0) {
        return false;
      }
      const width2 = this._zoneManager.getCanvasWidth();
      const height = this._zoneManager.getCanvasHeight();
      const colorZones = this._zoneManager.resolveColorZones();
      const id2Color = this._zoneManager.getId2Color();
      const ctx = this._domNode.domNode.getContext("2d");
      ctx.clearRect(0, 0, width2, height);
      if (colorZones.length > 0) {
        this._renderOneLane(ctx, colorZones, id2Color, width2);
      }
      return true;
    }
    _renderOneLane(ctx, colorZones, id2Color, width2) {
      let currentColorId = 0;
      let currentFrom = 0;
      let currentTo = 0;
      for (const zone of colorZones) {
        const zoneColorId = zone.colorId;
        const zoneFrom = zone.from;
        const zoneTo = zone.to;
        if (zoneColorId !== currentColorId) {
          ctx.fillRect(0, currentFrom, width2, currentTo - currentFrom);
          currentColorId = zoneColorId;
          ctx.fillStyle = id2Color[currentColorId];
          currentFrom = zoneFrom;
          currentTo = zoneTo;
        } else {
          if (currentTo >= zoneFrom) {
            currentTo = Math.max(currentTo, zoneTo);
          } else {
            ctx.fillRect(0, currentFrom, width2, currentTo - currentFrom);
            currentFrom = zoneFrom;
            currentTo = zoneTo;
          }
        }
      }
      ctx.fillRect(0, currentFrom, width2, currentTo - currentFrom);
    }
  }
  class Rulers extends ViewPart {
    constructor(context) {
      super(context);
      this.domNode = createFastDomNode(document.createElement("div"));
      this.domNode.setAttribute("role", "presentation");
      this.domNode.setAttribute("aria-hidden", "true");
      this.domNode.setClassName("view-rulers");
      this._renderedRulers = [];
      const options = this._context.configuration.options;
      this._rulers = options.get(
        116
        /* EditorOption.rulers */
      );
      this._typicalHalfwidthCharacterWidth = options.get(
        59
        /* EditorOption.fontInfo */
      ).typicalHalfwidthCharacterWidth;
    }
    dispose() {
      super.dispose();
    }
    // --- begin event handlers
    onConfigurationChanged(e) {
      const options = this._context.configuration.options;
      this._rulers = options.get(
        116
        /* EditorOption.rulers */
      );
      this._typicalHalfwidthCharacterWidth = options.get(
        59
        /* EditorOption.fontInfo */
      ).typicalHalfwidthCharacterWidth;
      return true;
    }
    onScrollChanged(e) {
      return e.scrollHeightChanged;
    }
    // --- end event handlers
    prepareRender(ctx) {
    }
    _ensureRulersCount() {
      const currentCount = this._renderedRulers.length;
      const desiredCount = this._rulers.length;
      if (currentCount === desiredCount) {
        return;
      }
      if (currentCount < desiredCount) {
        const { tabSize } = this._context.viewModel.model.getOptions();
        const rulerWidth = tabSize;
        let addCount = desiredCount - currentCount;
        while (addCount > 0) {
          const node = createFastDomNode(document.createElement("div"));
          node.setClassName("view-ruler");
          node.setWidth(rulerWidth);
          this.domNode.appendChild(node);
          this._renderedRulers.push(node);
          addCount--;
        }
        return;
      }
      let removeCount = currentCount - desiredCount;
      while (removeCount > 0) {
        const node = this._renderedRulers.pop();
        this.domNode.removeChild(node);
        removeCount--;
      }
    }
    render(ctx) {
      this._ensureRulersCount();
      for (let i2 = 0, len = this._rulers.length; i2 < len; i2++) {
        const node = this._renderedRulers[i2];
        const ruler = this._rulers[i2];
        node.setBoxShadow(ruler.color ? `1px 0 0 0 ${ruler.color} inset` : ``);
        node.setHeight(Math.min(ctx.scrollHeight, 1e6));
        node.setLeft(ruler.column * this._typicalHalfwidthCharacterWidth);
      }
    }
  }
  class ScrollDecorationViewPart extends ViewPart {
    constructor(context) {
      super(context);
      this._scrollTop = 0;
      this._width = 0;
      this._updateWidth();
      this._shouldShow = false;
      const options = this._context.configuration.options;
      const scrollbar = options.get(
        117
        /* EditorOption.scrollbar */
      );
      this._useShadows = scrollbar.useShadows;
      this._domNode = createFastDomNode(document.createElement("div"));
      this._domNode.setAttribute("role", "presentation");
      this._domNode.setAttribute("aria-hidden", "true");
    }
    dispose() {
      super.dispose();
    }
    _updateShouldShow() {
      const newShouldShow = this._useShadows && this._scrollTop > 0;
      if (this._shouldShow !== newShouldShow) {
        this._shouldShow = newShouldShow;
        return true;
      }
      return false;
    }
    getDomNode() {
      return this._domNode;
    }
    _updateWidth() {
      const options = this._context.configuration.options;
      const layoutInfo = options.get(
        165
        /* EditorOption.layoutInfo */
      );
      if (layoutInfo.minimap.renderMinimap === 0 || layoutInfo.minimap.minimapWidth > 0 && layoutInfo.minimap.minimapLeft === 0) {
        this._width = layoutInfo.width;
      } else {
        this._width = layoutInfo.width - layoutInfo.verticalScrollbarWidth;
      }
    }
    // --- begin event handlers
    onConfigurationChanged(e) {
      const options = this._context.configuration.options;
      const scrollbar = options.get(
        117
        /* EditorOption.scrollbar */
      );
      this._useShadows = scrollbar.useShadows;
      this._updateWidth();
      this._updateShouldShow();
      return true;
    }
    onScrollChanged(e) {
      this._scrollTop = e.scrollTop;
      return this._updateShouldShow();
    }
    // --- end event handlers
    prepareRender(ctx) {
    }
    render(ctx) {
      this._domNode.setWidth(this._width);
      this._domNode.setClassName(this._shouldShow ? "scroll-decoration" : "");
    }
  }
  class HorizontalRangeWithStyle {
    constructor(other) {
      this.left = other.left;
      this.width = other.width;
      this.startStyle = null;
      this.endStyle = null;
    }
  }
  class LineVisibleRangesWithStyle {
    constructor(lineNumber, ranges) {
      this.lineNumber = lineNumber;
      this.ranges = ranges;
    }
  }
  function toStyledRange(item) {
    return new HorizontalRangeWithStyle(item);
  }
  function toStyled(item) {
    return new LineVisibleRangesWithStyle(item.lineNumber, item.ranges.map(toStyledRange));
  }
  const _SelectionsOverlay = class _SelectionsOverlay extends DynamicViewOverlay {
    constructor(context) {
      super();
      this._previousFrameVisibleRangesWithStyle = [];
      this._context = context;
      const options = this._context.configuration.options;
      this._roundedSelection = options.get(
        115
        /* EditorOption.roundedSelection */
      );
      this._typicalHalfwidthCharacterWidth = options.get(
        59
        /* EditorOption.fontInfo */
      ).typicalHalfwidthCharacterWidth;
      this._selections = [];
      this._renderResult = null;
      this._context.addEventHandler(this);
    }
    dispose() {
      this._context.removeEventHandler(this);
      this._renderResult = null;
      super.dispose();
    }
    // --- begin event handlers
    onConfigurationChanged(e) {
      const options = this._context.configuration.options;
      this._roundedSelection = options.get(
        115
        /* EditorOption.roundedSelection */
      );
      this._typicalHalfwidthCharacterWidth = options.get(
        59
        /* EditorOption.fontInfo */
      ).typicalHalfwidthCharacterWidth;
      return true;
    }
    onCursorStateChanged(e) {
      this._selections = e.selections.slice(0);
      return true;
    }
    onDecorationsChanged(e) {
      return true;
    }
    onFlushed(e) {
      return true;
    }
    onLinesChanged(e) {
      return true;
    }
    onLinesDeleted(e) {
      return true;
    }
    onLinesInserted(e) {
      return true;
    }
    onScrollChanged(e) {
      return e.scrollTopChanged;
    }
    onZonesChanged(e) {
      return true;
    }
    // --- end event handlers
    _visibleRangesHaveGaps(linesVisibleRanges) {
      for (let i2 = 0, len = linesVisibleRanges.length; i2 < len; i2++) {
        const lineVisibleRanges = linesVisibleRanges[i2];
        if (lineVisibleRanges.ranges.length > 1) {
          return true;
        }
      }
      return false;
    }
    _enrichVisibleRangesWithStyle(viewport, linesVisibleRanges, previousFrame) {
      const epsilon = this._typicalHalfwidthCharacterWidth / 4;
      let previousFrameTop = null;
      let previousFrameBottom = null;
      if (previousFrame && previousFrame.length > 0 && linesVisibleRanges.length > 0) {
        const topLineNumber = linesVisibleRanges[0].lineNumber;
        if (topLineNumber === viewport.startLineNumber) {
          for (let i2 = 0; !previousFrameTop && i2 < previousFrame.length; i2++) {
            if (previousFrame[i2].lineNumber === topLineNumber) {
              previousFrameTop = previousFrame[i2].ranges[0];
            }
          }
        }
        const bottomLineNumber = linesVisibleRanges[linesVisibleRanges.length - 1].lineNumber;
        if (bottomLineNumber === viewport.endLineNumber) {
          for (let i2 = previousFrame.length - 1; !previousFrameBottom && i2 >= 0; i2--) {
            if (previousFrame[i2].lineNumber === bottomLineNumber) {
              previousFrameBottom = previousFrame[i2].ranges[0];
            }
          }
        }
        if (previousFrameTop && !previousFrameTop.startStyle) {
          previousFrameTop = null;
        }
        if (previousFrameBottom && !previousFrameBottom.startStyle) {
          previousFrameBottom = null;
        }
      }
      for (let i2 = 0, len = linesVisibleRanges.length; i2 < len; i2++) {
        const curLineRange = linesVisibleRanges[i2].ranges[0];
        const curLeft = curLineRange.left;
        const curRight = curLineRange.left + curLineRange.width;
        const startStyle = {
          top: 0,
          bottom: 0
          /* CornerStyle.EXTERN */
        };
        const endStyle = {
          top: 0,
          bottom: 0
          /* CornerStyle.EXTERN */
        };
        if (i2 > 0) {
          const prevLeft = linesVisibleRanges[i2 - 1].ranges[0].left;
          const prevRight = linesVisibleRanges[i2 - 1].ranges[0].left + linesVisibleRanges[i2 - 1].ranges[0].width;
          if (abs(curLeft - prevLeft) < epsilon) {
            startStyle.top = 2;
          } else if (curLeft > prevLeft) {
            startStyle.top = 1;
          }
          if (abs(curRight - prevRight) < epsilon) {
            endStyle.top = 2;
          } else if (prevLeft < curRight && curRight < prevRight) {
            endStyle.top = 1;
          }
        } else if (previousFrameTop) {
          startStyle.top = previousFrameTop.startStyle.top;
          endStyle.top = previousFrameTop.endStyle.top;
        }
        if (i2 + 1 < len) {
          const nextLeft = linesVisibleRanges[i2 + 1].ranges[0].left;
          const nextRight = linesVisibleRanges[i2 + 1].ranges[0].left + linesVisibleRanges[i2 + 1].ranges[0].width;
          if (abs(curLeft - nextLeft) < epsilon) {
            startStyle.bottom = 2;
          } else if (nextLeft < curLeft && curLeft < nextRight) {
            startStyle.bottom = 1;
          }
          if (abs(curRight - nextRight) < epsilon) {
            endStyle.bottom = 2;
          } else if (curRight < nextRight) {
            endStyle.bottom = 1;
          }
        } else if (previousFrameBottom) {
          startStyle.bottom = previousFrameBottom.startStyle.bottom;
          endStyle.bottom = previousFrameBottom.endStyle.bottom;
        }
        curLineRange.startStyle = startStyle;
        curLineRange.endStyle = endStyle;
      }
    }
    _getVisibleRangesWithStyle(selection, ctx, previousFrame) {
      const _linesVisibleRanges = ctx.linesVisibleRangesForRange(selection, true) || [];
      const linesVisibleRanges = _linesVisibleRanges.map(toStyled);
      const visibleRangesHaveGaps = this._visibleRangesHaveGaps(linesVisibleRanges);
      if (!visibleRangesHaveGaps && this._roundedSelection) {
        this._enrichVisibleRangesWithStyle(ctx.visibleRange, linesVisibleRanges, previousFrame);
      }
      return linesVisibleRanges;
    }
    _createSelectionPiece(top, bottom, className2, left, width2) {
      return '<div class="cslr ' + className2 + '" style="top:' + top.toString() + "px;bottom:" + bottom.toString() + "px;left:" + left.toString() + "px;width:" + width2.toString() + 'px;"></div>';
    }
    _actualRenderOneSelection(output2, visibleStartLineNumber, hasMultipleSelections, visibleRanges) {
      if (visibleRanges.length === 0) {
        return;
      }
      const visibleRangesHaveStyle = !!visibleRanges[0].ranges[0].startStyle;
      const firstLineNumber = visibleRanges[0].lineNumber;
      const lastLineNumber = visibleRanges[visibleRanges.length - 1].lineNumber;
      for (let i2 = 0, len = visibleRanges.length; i2 < len; i2++) {
        const lineVisibleRanges = visibleRanges[i2];
        const lineNumber = lineVisibleRanges.lineNumber;
        const lineIndex = lineNumber - visibleStartLineNumber;
        const top = hasMultipleSelections ? lineNumber === firstLineNumber ? 1 : 0 : 0;
        const bottom = hasMultipleSelections ? lineNumber !== firstLineNumber && lineNumber === lastLineNumber ? 1 : 0 : 0;
        let innerCornerOutput = "";
        let restOfSelectionOutput = "";
        for (let j = 0, lenJ = lineVisibleRanges.ranges.length; j < lenJ; j++) {
          const visibleRange = lineVisibleRanges.ranges[j];
          if (visibleRangesHaveStyle) {
            const startStyle = visibleRange.startStyle;
            const endStyle = visibleRange.endStyle;
            if (startStyle.top === 1 || startStyle.bottom === 1) {
              innerCornerOutput += this._createSelectionPiece(top, bottom, _SelectionsOverlay.SELECTION_CLASS_NAME, visibleRange.left - _SelectionsOverlay.ROUNDED_PIECE_WIDTH, _SelectionsOverlay.ROUNDED_PIECE_WIDTH);
              let className3 = _SelectionsOverlay.EDITOR_BACKGROUND_CLASS_NAME;
              if (startStyle.top === 1) {
                className3 += " " + _SelectionsOverlay.SELECTION_TOP_RIGHT;
              }
              if (startStyle.bottom === 1) {
                className3 += " " + _SelectionsOverlay.SELECTION_BOTTOM_RIGHT;
              }
              innerCornerOutput += this._createSelectionPiece(top, bottom, className3, visibleRange.left - _SelectionsOverlay.ROUNDED_PIECE_WIDTH, _SelectionsOverlay.ROUNDED_PIECE_WIDTH);
            }
            if (endStyle.top === 1 || endStyle.bottom === 1) {
              innerCornerOutput += this._createSelectionPiece(top, bottom, _SelectionsOverlay.SELECTION_CLASS_NAME, visibleRange.left + visibleRange.width, _SelectionsOverlay.ROUNDED_PIECE_WIDTH);
              let className3 = _SelectionsOverlay.EDITOR_BACKGROUND_CLASS_NAME;
              if (endStyle.top === 1) {
                className3 += " " + _SelectionsOverlay.SELECTION_TOP_LEFT;
              }
              if (endStyle.bottom === 1) {
                className3 += " " + _SelectionsOverlay.SELECTION_BOTTOM_LEFT;
              }
              innerCornerOutput += this._createSelectionPiece(top, bottom, className3, visibleRange.left + visibleRange.width, _SelectionsOverlay.ROUNDED_PIECE_WIDTH);
            }
          }
          let className2 = _SelectionsOverlay.SELECTION_CLASS_NAME;
          if (visibleRangesHaveStyle) {
            const startStyle = visibleRange.startStyle;
            const endStyle = visibleRange.endStyle;
            if (startStyle.top === 0) {
              className2 += " " + _SelectionsOverlay.SELECTION_TOP_LEFT;
            }
            if (startStyle.bottom === 0) {
              className2 += " " + _SelectionsOverlay.SELECTION_BOTTOM_LEFT;
            }
            if (endStyle.top === 0) {
              className2 += " " + _SelectionsOverlay.SELECTION_TOP_RIGHT;
            }
            if (endStyle.bottom === 0) {
              className2 += " " + _SelectionsOverlay.SELECTION_BOTTOM_RIGHT;
            }
          }
          restOfSelectionOutput += this._createSelectionPiece(top, bottom, className2, visibleRange.left, visibleRange.width);
        }
        output2[lineIndex][0] += innerCornerOutput;
        output2[lineIndex][1] += restOfSelectionOutput;
      }
    }
    prepareRender(ctx) {
      const output = [];
      const visibleStartLineNumber = ctx.visibleRange.startLineNumber;
      const visibleEndLineNumber = ctx.visibleRange.endLineNumber;
      for (let lineNumber = visibleStartLineNumber; lineNumber <= visibleEndLineNumber; lineNumber++) {
        const lineIndex = lineNumber - visibleStartLineNumber;
        output[lineIndex] = ["", ""];
      }
      const thisFrameVisibleRangesWithStyle = [];
      for (let i2 = 0, len = this._selections.length; i2 < len; i2++) {
        const selection = this._selections[i2];
        if (selection.isEmpty()) {
          thisFrameVisibleRangesWithStyle[i2] = null;
          continue;
        }
        const visibleRangesWithStyle = this._getVisibleRangesWithStyle(selection, ctx, this._previousFrameVisibleRangesWithStyle[i2]);
        thisFrameVisibleRangesWithStyle[i2] = visibleRangesWithStyle;
        this._actualRenderOneSelection(output, visibleStartLineNumber, this._selections.length > 1, visibleRangesWithStyle);
      }
      this._previousFrameVisibleRangesWithStyle = thisFrameVisibleRangesWithStyle;
      this._renderResult = output.map(([internalCorners, restOfSelection]) => internalCorners + restOfSelection);
    }
    render(startLineNumber, lineNumber) {
      if (!this._renderResult) {
        return "";
      }
      const lineIndex = lineNumber - startLineNumber;
      if (lineIndex < 0 || lineIndex >= this._renderResult.length) {
        return "";
      }
      return this._renderResult[lineIndex];
    }
  };
  _SelectionsOverlay.SELECTION_CLASS_NAME = "selected-text";
  _SelectionsOverlay.SELECTION_TOP_LEFT = "top-left-radius";
  _SelectionsOverlay.SELECTION_BOTTOM_LEFT = "bottom-left-radius";
  _SelectionsOverlay.SELECTION_TOP_RIGHT = "top-right-radius";
  _SelectionsOverlay.SELECTION_BOTTOM_RIGHT = "bottom-right-radius";
  _SelectionsOverlay.EDITOR_BACKGROUND_CLASS_NAME = "monaco-editor-background";
  _SelectionsOverlay.ROUNDED_PIECE_WIDTH = 10;
  let SelectionsOverlay = _SelectionsOverlay;
  registerThemingParticipant((theme, collector) => {
    const editorSelectionForegroundColor = theme.getColor(editorSelectionForeground);
    if (editorSelectionForegroundColor && !editorSelectionForegroundColor.isTransparent()) {
      collector.addRule(`.monaco-editor .view-line span.inline-selected-text { color: ${editorSelectionForegroundColor}; }`);
    }
  });
  function abs(n2) {
    return n2 < 0 ? -n2 : n2;
  }
  class ViewCursorRenderData {
    constructor(top, left, paddingLeft, width2, height, textContent, textContentClassName) {
      this.top = top;
      this.left = left;
      this.paddingLeft = paddingLeft;
      this.width = width2;
      this.height = height;
      this.textContent = textContent;
      this.textContentClassName = textContentClassName;
    }
  }
  var CursorPlurality;
  (function(CursorPlurality2) {
    CursorPlurality2[CursorPlurality2["Single"] = 0] = "Single";
    CursorPlurality2[CursorPlurality2["MultiPrimary"] = 1] = "MultiPrimary";
    CursorPlurality2[CursorPlurality2["MultiSecondary"] = 2] = "MultiSecondary";
  })(CursorPlurality || (CursorPlurality = {}));
  class ViewCursor {
    constructor(context, plurality) {
      this._context = context;
      const options = this._context.configuration.options;
      const fontInfo = options.get(
        59
        /* EditorOption.fontInfo */
      );
      this._cursorStyle = options.get(
        161
        /* EditorOption.effectiveCursorStyle */
      );
      this._typicalHalfwidthCharacterWidth = fontInfo.typicalHalfwidthCharacterWidth;
      this._lineCursorWidth = Math.min(options.get(
        37
        /* EditorOption.cursorWidth */
      ), this._typicalHalfwidthCharacterWidth);
      this._lineCursorHeight = options.get(
        38
        /* EditorOption.cursorHeight */
      );
      this._isVisible = true;
      this._domNode = createFastDomNode(document.createElement("div"));
      this._domNode.setClassName(`cursor ${MOUSE_CURSOR_TEXT_CSS_CLASS_NAME}`);
      this._domNode.setHeight(this._context.viewLayout.getLineHeightForLineNumber(1));
      this._domNode.setTop(0);
      this._domNode.setLeft(0);
      applyFontInfo(this._domNode, fontInfo);
      this._domNode.setDisplay("none");
      this._position = new Position$1(1, 1);
      this._pluralityClass = "";
      this.setPlurality(plurality);
      this._lastRenderedContent = "";
      this._renderData = null;
    }
    getDomNode() {
      return this._domNode;
    }
    getPosition() {
      return this._position;
    }
    setPlurality(plurality) {
      switch (plurality) {
        default:
        case CursorPlurality.Single:
          this._pluralityClass = "";
          break;
        case CursorPlurality.MultiPrimary:
          this._pluralityClass = "cursor-primary";
          break;
        case CursorPlurality.MultiSecondary:
          this._pluralityClass = "cursor-secondary";
          break;
      }
    }
    show() {
      if (!this._isVisible) {
        this._domNode.setVisibility("inherit");
        this._isVisible = true;
      }
    }
    hide() {
      if (this._isVisible) {
        this._domNode.setVisibility("hidden");
        this._isVisible = false;
      }
    }
    onConfigurationChanged(e) {
      const options = this._context.configuration.options;
      const fontInfo = options.get(
        59
        /* EditorOption.fontInfo */
      );
      this._cursorStyle = options.get(
        161
        /* EditorOption.effectiveCursorStyle */
      );
      this._typicalHalfwidthCharacterWidth = fontInfo.typicalHalfwidthCharacterWidth;
      this._lineCursorWidth = Math.min(options.get(
        37
        /* EditorOption.cursorWidth */
      ), this._typicalHalfwidthCharacterWidth);
      this._lineCursorHeight = options.get(
        38
        /* EditorOption.cursorHeight */
      );
      applyFontInfo(this._domNode, fontInfo);
      return true;
    }
    onCursorPositionChanged(position, pauseAnimation) {
      if (pauseAnimation) {
        this._domNode.domNode.style.transitionProperty = "none";
      } else {
        this._domNode.domNode.style.transitionProperty = "";
      }
      this._position = position;
      return true;
    }
    /**
     * If `this._position` is inside a grapheme, returns the position where the grapheme starts.
     * Also returns the next grapheme.
     */
    _getGraphemeAwarePosition() {
      const { lineNumber, column } = this._position;
      const lineContent = this._context.viewModel.getLineContent(lineNumber);
      const [startOffset, endOffset] = getCharContainingOffset(lineContent, column - 1);
      return [new Position$1(lineNumber, startOffset + 1), lineContent.substring(startOffset, endOffset)];
    }
    _prepareRender(ctx) {
      let textContent = "";
      let textContentClassName = "";
      const [position, nextGrapheme] = this._getGraphemeAwarePosition();
      const lineHeight = this._context.viewLayout.getLineHeightForLineNumber(position.lineNumber);
      const lineCursorHeight = this._lineCursorHeight === 0 ? lineHeight : Math.min(lineHeight, this._lineCursorHeight);
      const lineHeightAdjustment = (lineHeight - lineCursorHeight) / 2;
      if (this._cursorStyle === TextEditorCursorStyle$1.Line || this._cursorStyle === TextEditorCursorStyle$1.LineThin) {
        const visibleRange = ctx.visibleRangeForPosition(position);
        if (!visibleRange || visibleRange.outsideRenderedLine) {
          return null;
        }
        const window2 = getWindow(this._domNode.domNode);
        let width3;
        if (this._cursorStyle === TextEditorCursorStyle$1.Line) {
          width3 = computeScreenAwareSize(window2, this._lineCursorWidth > 0 ? this._lineCursorWidth : 2);
          if (width3 > 2) {
            textContent = nextGrapheme;
            textContentClassName = this._getTokenClassName(position);
          }
        } else {
          width3 = computeScreenAwareSize(window2, 1);
        }
        let left = visibleRange.left;
        let paddingLeft = 0;
        if (width3 >= 2 && left >= 1) {
          paddingLeft = 1;
          left -= paddingLeft;
        }
        const top2 = ctx.getVerticalOffsetForLineNumber(position.lineNumber) - ctx.bigNumbersDelta + lineHeightAdjustment;
        return new ViewCursorRenderData(top2, left, paddingLeft, width3, lineCursorHeight, textContent, textContentClassName);
      }
      const visibleRangeForCharacter = ctx.linesVisibleRangesForRange(new Range$2(position.lineNumber, position.column, position.lineNumber, position.column + nextGrapheme.length), false);
      if (!visibleRangeForCharacter || visibleRangeForCharacter.length === 0) {
        return null;
      }
      const firstVisibleRangeForCharacter = visibleRangeForCharacter[0];
      if (firstVisibleRangeForCharacter.outsideRenderedLine || firstVisibleRangeForCharacter.ranges.length === 0) {
        return null;
      }
      const range2 = firstVisibleRangeForCharacter.ranges[0];
      const width2 = nextGrapheme === "	" ? this._typicalHalfwidthCharacterWidth : range2.width < 1 ? this._typicalHalfwidthCharacterWidth : range2.width;
      if (this._cursorStyle === TextEditorCursorStyle$1.Block) {
        textContent = nextGrapheme;
        textContentClassName = this._getTokenClassName(position);
      }
      let top = ctx.getVerticalOffsetForLineNumber(position.lineNumber) - ctx.bigNumbersDelta;
      let height = lineHeight;
      if (this._cursorStyle === TextEditorCursorStyle$1.Underline || this._cursorStyle === TextEditorCursorStyle$1.UnderlineThin) {
        top += lineHeight - 2;
        height = 2;
      }
      return new ViewCursorRenderData(top, range2.left, 0, width2, height, textContent, textContentClassName);
    }
    _getTokenClassName(position) {
      const lineData = this._context.viewModel.getViewLineData(position.lineNumber);
      const tokenIndex = lineData.tokens.findTokenIndexAtOffset(position.column - 1);
      return lineData.tokens.getClassName(tokenIndex);
    }
    prepareRender(ctx) {
      this._renderData = this._prepareRender(ctx);
    }
    render(ctx) {
      if (!this._renderData) {
        this._domNode.setDisplay("none");
        return null;
      }
      if (this._lastRenderedContent !== this._renderData.textContent) {
        this._lastRenderedContent = this._renderData.textContent;
        this._domNode.domNode.textContent = this._lastRenderedContent;
      }
      this._domNode.setClassName(`cursor ${this._pluralityClass} ${MOUSE_CURSOR_TEXT_CSS_CLASS_NAME} ${this._renderData.textContentClassName}`);
      this._domNode.setDisplay("block");
      this._domNode.setTop(this._renderData.top);
      this._domNode.setLeft(this._renderData.left);
      this._domNode.setPaddingLeft(this._renderData.paddingLeft);
      this._domNode.setWidth(this._renderData.width);
      this._domNode.setLineHeight(this._renderData.height);
      this._domNode.setHeight(this._renderData.height);
      return {
        domNode: this._domNode.domNode,
        position: this._position,
        contentLeft: this._renderData.left,
        height: this._renderData.height,
        width: 2
      };
    }
  }
  const _ViewCursors = class _ViewCursors extends ViewPart {
    constructor(context) {
      super(context);
      const options = this._context.configuration.options;
      this._readOnly = options.get(
        104
        /* EditorOption.readOnly */
      );
      this._cursorBlinking = options.get(
        32
        /* EditorOption.cursorBlinking */
      );
      this._cursorStyle = options.get(
        161
        /* EditorOption.effectiveCursorStyle */
      );
      this._cursorSmoothCaretAnimation = options.get(
        33
        /* EditorOption.cursorSmoothCaretAnimation */
      );
      this._editContextEnabled = options.get(
        170
        /* EditorOption.effectiveEditContext */
      );
      this._selectionIsEmpty = true;
      this._isComposingInput = false;
      this._isVisible = false;
      this._primaryCursor = new ViewCursor(this._context, CursorPlurality.Single);
      this._secondaryCursors = [];
      this._renderData = [];
      this._domNode = createFastDomNode(document.createElement("div"));
      this._domNode.setAttribute("role", "presentation");
      this._domNode.setAttribute("aria-hidden", "true");
      this._updateDomClassName();
      this._domNode.appendChild(this._primaryCursor.getDomNode());
      this._startCursorBlinkAnimation = new TimeoutTimer();
      this._cursorFlatBlinkInterval = new WindowIntervalTimer();
      this._blinkingEnabled = false;
      this._editorHasFocus = false;
      this._updateBlinking();
    }
    dispose() {
      super.dispose();
      this._startCursorBlinkAnimation.dispose();
      this._cursorFlatBlinkInterval.dispose();
    }
    getDomNode() {
      return this._domNode;
    }
    // --- begin event handlers
    onCompositionStart(e) {
      this._isComposingInput = true;
      this._updateBlinking();
      return true;
    }
    onCompositionEnd(e) {
      this._isComposingInput = false;
      this._updateBlinking();
      return true;
    }
    onConfigurationChanged(e) {
      const options = this._context.configuration.options;
      this._readOnly = options.get(
        104
        /* EditorOption.readOnly */
      );
      this._cursorBlinking = options.get(
        32
        /* EditorOption.cursorBlinking */
      );
      this._cursorStyle = options.get(
        161
        /* EditorOption.effectiveCursorStyle */
      );
      this._cursorSmoothCaretAnimation = options.get(
        33
        /* EditorOption.cursorSmoothCaretAnimation */
      );
      this._editContextEnabled = options.get(
        170
        /* EditorOption.effectiveEditContext */
      );
      this._updateBlinking();
      this._updateDomClassName();
      this._primaryCursor.onConfigurationChanged(e);
      for (let i2 = 0, len = this._secondaryCursors.length; i2 < len; i2++) {
        this._secondaryCursors[i2].onConfigurationChanged(e);
      }
      return true;
    }
    _onCursorPositionChanged(position, secondaryPositions, reason) {
      const pauseAnimation = this._secondaryCursors.length !== secondaryPositions.length || this._cursorSmoothCaretAnimation === "explicit" && reason !== 3;
      this._primaryCursor.setPlurality(secondaryPositions.length ? CursorPlurality.MultiPrimary : CursorPlurality.Single);
      this._primaryCursor.onCursorPositionChanged(position, pauseAnimation);
      this._updateBlinking();
      if (this._secondaryCursors.length < secondaryPositions.length) {
        const addCnt = secondaryPositions.length - this._secondaryCursors.length;
        for (let i2 = 0; i2 < addCnt; i2++) {
          const newCursor = new ViewCursor(this._context, CursorPlurality.MultiSecondary);
          this._domNode.domNode.insertBefore(newCursor.getDomNode().domNode, this._primaryCursor.getDomNode().domNode.nextSibling);
          this._secondaryCursors.push(newCursor);
        }
      } else if (this._secondaryCursors.length > secondaryPositions.length) {
        const removeCnt = this._secondaryCursors.length - secondaryPositions.length;
        for (let i2 = 0; i2 < removeCnt; i2++) {
          this._domNode.removeChild(this._secondaryCursors[0].getDomNode());
          this._secondaryCursors.splice(0, 1);
        }
      }
      for (let i2 = 0; i2 < secondaryPositions.length; i2++) {
        this._secondaryCursors[i2].onCursorPositionChanged(secondaryPositions[i2], pauseAnimation);
      }
    }
    onCursorStateChanged(e) {
      const positions = [];
      for (let i2 = 0, len = e.selections.length; i2 < len; i2++) {
        positions[i2] = e.selections[i2].getPosition();
      }
      this._onCursorPositionChanged(positions[0], positions.slice(1), e.reason);
      const selectionIsEmpty = e.selections[0].isEmpty();
      if (this._selectionIsEmpty !== selectionIsEmpty) {
        this._selectionIsEmpty = selectionIsEmpty;
        this._updateDomClassName();
      }
      return true;
    }
    onDecorationsChanged(e) {
      return true;
    }
    onFlushed(e) {
      return true;
    }
    onFocusChanged(e) {
      this._editorHasFocus = e.isFocused;
      this._updateBlinking();
      return false;
    }
    onLinesChanged(e) {
      return true;
    }
    onLinesDeleted(e) {
      return true;
    }
    onLinesInserted(e) {
      return true;
    }
    onScrollChanged(e) {
      return true;
    }
    onTokensChanged(e) {
      const shouldRender = (position) => {
        for (let i2 = 0, len = e.ranges.length; i2 < len; i2++) {
          if (e.ranges[i2].fromLineNumber <= position.lineNumber && position.lineNumber <= e.ranges[i2].toLineNumber) {
            return true;
          }
        }
        return false;
      };
      if (shouldRender(this._primaryCursor.getPosition())) {
        return true;
      }
      for (const secondaryCursor of this._secondaryCursors) {
        if (shouldRender(secondaryCursor.getPosition())) {
          return true;
        }
      }
      return false;
    }
    onZonesChanged(e) {
      return true;
    }
    // --- end event handlers
    // ---- blinking logic
    _getCursorBlinking() {
      if (this._isComposingInput && !this._editContextEnabled) {
        return 0;
      }
      if (!this._editorHasFocus) {
        return 0;
      }
      if (this._readOnly) {
        return 5;
      }
      return this._cursorBlinking;
    }
    _updateBlinking() {
      this._startCursorBlinkAnimation.cancel();
      this._cursorFlatBlinkInterval.cancel();
      const blinkingStyle = this._getCursorBlinking();
      const isHidden = blinkingStyle === 0;
      const isSolid = blinkingStyle === 5;
      if (isHidden) {
        this._hide();
      } else {
        this._show();
      }
      this._blinkingEnabled = false;
      this._updateDomClassName();
      if (!isHidden && !isSolid) {
        if (blinkingStyle === 1) {
          this._cursorFlatBlinkInterval.cancelAndSet(() => {
            if (this._isVisible) {
              this._hide();
            } else {
              this._show();
            }
          }, _ViewCursors.BLINK_INTERVAL, getWindow(this._domNode.domNode));
        } else {
          this._startCursorBlinkAnimation.setIfNotSet(() => {
            this._blinkingEnabled = true;
            this._updateDomClassName();
          }, _ViewCursors.BLINK_INTERVAL);
        }
      }
    }
    // --- end blinking logic
    _updateDomClassName() {
      this._domNode.setClassName(this._getClassName());
    }
    _getClassName() {
      let result = "cursors-layer";
      if (!this._selectionIsEmpty) {
        result += " has-selection";
      }
      switch (this._cursorStyle) {
        case TextEditorCursorStyle$1.Line:
          result += " cursor-line-style";
          break;
        case TextEditorCursorStyle$1.Block:
          result += " cursor-block-style";
          break;
        case TextEditorCursorStyle$1.Underline:
          result += " cursor-underline-style";
          break;
        case TextEditorCursorStyle$1.LineThin:
          result += " cursor-line-thin-style";
          break;
        case TextEditorCursorStyle$1.BlockOutline:
          result += " cursor-block-outline-style";
          break;
        case TextEditorCursorStyle$1.UnderlineThin:
          result += " cursor-underline-thin-style";
          break;
        default:
          result += " cursor-line-style";
      }
      if (this._blinkingEnabled) {
        switch (this._getCursorBlinking()) {
          case 1:
            result += " cursor-blink";
            break;
          case 2:
            result += " cursor-smooth";
            break;
          case 3:
            result += " cursor-phase";
            break;
          case 4:
            result += " cursor-expand";
            break;
          case 5:
            result += " cursor-solid";
            break;
          default:
            result += " cursor-solid";
        }
      } else {
        result += " cursor-solid";
      }
      if (this._cursorSmoothCaretAnimation === "on" || this._cursorSmoothCaretAnimation === "explicit") {
        result += " cursor-smooth-caret-animation";
      }
      return result;
    }
    _show() {
      this._primaryCursor.show();
      for (let i2 = 0, len = this._secondaryCursors.length; i2 < len; i2++) {
        this._secondaryCursors[i2].show();
      }
      this._isVisible = true;
    }
    _hide() {
      this._primaryCursor.hide();
      for (let i2 = 0, len = this._secondaryCursors.length; i2 < len; i2++) {
        this._secondaryCursors[i2].hide();
      }
      this._isVisible = false;
    }
    // ---- IViewPart implementation
    prepareRender(ctx) {
      this._primaryCursor.prepareRender(ctx);
      for (let i2 = 0, len = this._secondaryCursors.length; i2 < len; i2++) {
        this._secondaryCursors[i2].prepareRender(ctx);
      }
    }
    render(ctx) {
      const renderData = [];
      let renderDataLen = 0;
      const primaryRenderData = this._primaryCursor.render(ctx);
      if (primaryRenderData) {
        renderData[renderDataLen++] = primaryRenderData;
      }
      for (let i2 = 0, len = this._secondaryCursors.length; i2 < len; i2++) {
        const secondaryRenderData = this._secondaryCursors[i2].render(ctx);
        if (secondaryRenderData) {
          renderData[renderDataLen++] = secondaryRenderData;
        }
      }
      this._renderData = renderData;
    }
    getLastRenderData() {
      return this._renderData;
    }
  };
  _ViewCursors.BLINK_INTERVAL = 500;
  let ViewCursors = _ViewCursors;
  registerThemingParticipant((theme, collector) => {
    const cursorThemes = [
      { class: ".cursor", foreground: editorCursorForeground, background: editorCursorBackground },
      { class: ".cursor-primary", foreground: editorMultiCursorPrimaryForeground, background: editorMultiCursorPrimaryBackground },
      { class: ".cursor-secondary", foreground: editorMultiCursorSecondaryForeground, background: editorMultiCursorSecondaryBackground }
    ];
    for (const cursorTheme of cursorThemes) {
      const caret2 = theme.getColor(cursorTheme.foreground);
      if (caret2) {
        let caretBackground = theme.getColor(cursorTheme.background);
        if (!caretBackground) {
          caretBackground = caret2.opposite();
        }
        collector.addRule(`.monaco-editor .cursors-layer ${cursorTheme.class} { background-color: ${caret2}; border-color: ${caret2}; color: ${caretBackground}; }`);
        if (isHighContrast(theme.type)) {
          collector.addRule(`.monaco-editor .cursors-layer.has-selection ${cursorTheme.class} { border-left: 1px solid ${caretBackground}; border-right: 1px solid ${caretBackground}; }`);
        }
      }
    }
  });
  const invalidFunc$1 = () => {
    throw new Error(`Invalid change accessor`);
  };
  class ViewZones extends ViewPart {
    constructor(context) {
      super(context);
      const options = this._context.configuration.options;
      const layoutInfo = options.get(
        165
        /* EditorOption.layoutInfo */
      );
      this._lineHeight = options.get(
        75
        /* EditorOption.lineHeight */
      );
      this._contentWidth = layoutInfo.contentWidth;
      this._contentLeft = layoutInfo.contentLeft;
      this.domNode = createFastDomNode(document.createElement("div"));
      this.domNode.setClassName("view-zones");
      this.domNode.setPosition("absolute");
      this.domNode.setAttribute("role", "presentation");
      this.domNode.setAttribute("aria-hidden", "true");
      this.marginDomNode = createFastDomNode(document.createElement("div"));
      this.marginDomNode.setClassName("margin-view-zones");
      this.marginDomNode.setPosition("absolute");
      this.marginDomNode.setAttribute("role", "presentation");
      this.marginDomNode.setAttribute("aria-hidden", "true");
      this._zones = {};
    }
    dispose() {
      super.dispose();
      this._zones = {};
    }
    // ---- begin view event handlers
    _recomputeWhitespacesProps() {
      const whitespaces = this._context.viewLayout.getWhitespaces();
      const oldWhitespaces = /* @__PURE__ */ new Map();
      for (const whitespace of whitespaces) {
        oldWhitespaces.set(whitespace.id, whitespace);
      }
      let hadAChange = false;
      this._context.viewModel.changeWhitespace((whitespaceAccessor) => {
        const keys = Object.keys(this._zones);
        for (let i2 = 0, len = keys.length; i2 < len; i2++) {
          const id = keys[i2];
          const zone = this._zones[id];
          const props = this._computeWhitespaceProps(zone.delegate);
          zone.isInHiddenArea = props.isInHiddenArea;
          const oldWhitespace = oldWhitespaces.get(id);
          if (oldWhitespace && (oldWhitespace.afterLineNumber !== props.afterViewLineNumber || oldWhitespace.height !== props.heightInPx)) {
            whitespaceAccessor.changeOneWhitespace(id, props.afterViewLineNumber, props.heightInPx);
            this._safeCallOnComputedHeight(zone.delegate, props.heightInPx);
            hadAChange = true;
          }
        }
      });
      return hadAChange;
    }
    onConfigurationChanged(e) {
      const options = this._context.configuration.options;
      const layoutInfo = options.get(
        165
        /* EditorOption.layoutInfo */
      );
      this._lineHeight = options.get(
        75
        /* EditorOption.lineHeight */
      );
      this._contentWidth = layoutInfo.contentWidth;
      this._contentLeft = layoutInfo.contentLeft;
      if (e.hasChanged(
        75
        /* EditorOption.lineHeight */
      )) {
        this._recomputeWhitespacesProps();
      }
      return true;
    }
    onLineMappingChanged(e) {
      return this._recomputeWhitespacesProps();
    }
    onLinesDeleted(e) {
      return true;
    }
    onScrollChanged(e) {
      return e.scrollTopChanged || e.scrollWidthChanged;
    }
    onZonesChanged(e) {
      return true;
    }
    onLinesInserted(e) {
      return true;
    }
    // ---- end view event handlers
    _getZoneOrdinal(zone) {
      return zone.ordinal ?? zone.afterColumn ?? 1e4;
    }
    _computeWhitespaceProps(zone) {
      if (zone.afterLineNumber === 0) {
        return {
          isInHiddenArea: false,
          afterViewLineNumber: 0,
          heightInPx: this._heightInPixels(zone),
          minWidthInPx: this._minWidthInPixels(zone)
        };
      }
      let zoneAfterModelPosition;
      if (typeof zone.afterColumn !== "undefined") {
        zoneAfterModelPosition = this._context.viewModel.model.validatePosition({
          lineNumber: zone.afterLineNumber,
          column: zone.afterColumn
        });
      } else {
        const validAfterLineNumber = this._context.viewModel.model.validatePosition({
          lineNumber: zone.afterLineNumber,
          column: 1
        }).lineNumber;
        zoneAfterModelPosition = new Position$1(validAfterLineNumber, this._context.viewModel.model.getLineMaxColumn(validAfterLineNumber));
      }
      let zoneBeforeModelPosition;
      if (zoneAfterModelPosition.column === this._context.viewModel.model.getLineMaxColumn(zoneAfterModelPosition.lineNumber)) {
        zoneBeforeModelPosition = this._context.viewModel.model.validatePosition({
          lineNumber: zoneAfterModelPosition.lineNumber + 1,
          column: 1
        });
      } else {
        zoneBeforeModelPosition = this._context.viewModel.model.validatePosition({
          lineNumber: zoneAfterModelPosition.lineNumber,
          column: zoneAfterModelPosition.column + 1
        });
      }
      const viewPosition = this._context.viewModel.coordinatesConverter.convertModelPositionToViewPosition(zoneAfterModelPosition, zone.afterColumnAffinity, true);
      const isVisible = zone.showInHiddenAreas || this._context.viewModel.coordinatesConverter.modelPositionIsVisible(zoneBeforeModelPosition);
      return {
        isInHiddenArea: !isVisible,
        afterViewLineNumber: viewPosition.lineNumber,
        heightInPx: isVisible ? this._heightInPixels(zone) : 0,
        minWidthInPx: this._minWidthInPixels(zone)
      };
    }
    changeViewZones(callback) {
      let zonesHaveChanged = false;
      this._context.viewModel.changeWhitespace((whitespaceAccessor) => {
        const changeAccessor = {
          addZone: (zone) => {
            zonesHaveChanged = true;
            return this._addZone(whitespaceAccessor, zone);
          },
          removeZone: (id) => {
            if (!id) {
              return;
            }
            zonesHaveChanged = this._removeZone(whitespaceAccessor, id) || zonesHaveChanged;
          },
          layoutZone: (id) => {
            if (!id) {
              return;
            }
            zonesHaveChanged = this._layoutZone(whitespaceAccessor, id) || zonesHaveChanged;
          }
        };
        safeInvoke1Arg(callback, changeAccessor);
        changeAccessor.addZone = invalidFunc$1;
        changeAccessor.removeZone = invalidFunc$1;
        changeAccessor.layoutZone = invalidFunc$1;
      });
      return zonesHaveChanged;
    }
    _addZone(whitespaceAccessor, zone) {
      const props = this._computeWhitespaceProps(zone);
      const whitespaceId = whitespaceAccessor.insertWhitespace(props.afterViewLineNumber, this._getZoneOrdinal(zone), props.heightInPx, props.minWidthInPx);
      const myZone = {
        whitespaceId,
        delegate: zone,
        isInHiddenArea: props.isInHiddenArea,
        isVisible: false,
        domNode: createFastDomNode(zone.domNode),
        marginDomNode: zone.marginDomNode ? createFastDomNode(zone.marginDomNode) : null
      };
      this._safeCallOnComputedHeight(myZone.delegate, props.heightInPx);
      myZone.domNode.setPosition("absolute");
      myZone.domNode.domNode.style.width = "100%";
      myZone.domNode.setDisplay("none");
      myZone.domNode.setAttribute("monaco-view-zone", myZone.whitespaceId);
      this.domNode.appendChild(myZone.domNode);
      if (myZone.marginDomNode) {
        myZone.marginDomNode.setPosition("absolute");
        myZone.marginDomNode.domNode.style.width = "100%";
        myZone.marginDomNode.setDisplay("none");
        myZone.marginDomNode.setAttribute("monaco-view-zone", myZone.whitespaceId);
        this.marginDomNode.appendChild(myZone.marginDomNode);
      }
      this._zones[myZone.whitespaceId] = myZone;
      this.setShouldRender();
      return myZone.whitespaceId;
    }
    _removeZone(whitespaceAccessor, id) {
      if (this._zones.hasOwnProperty(id)) {
        const zone = this._zones[id];
        delete this._zones[id];
        whitespaceAccessor.removeWhitespace(zone.whitespaceId);
        zone.domNode.removeAttribute("monaco-visible-view-zone");
        zone.domNode.removeAttribute("monaco-view-zone");
        zone.domNode.domNode.remove();
        if (zone.marginDomNode) {
          zone.marginDomNode.removeAttribute("monaco-visible-view-zone");
          zone.marginDomNode.removeAttribute("monaco-view-zone");
          zone.marginDomNode.domNode.remove();
        }
        this.setShouldRender();
        return true;
      }
      return false;
    }
    _layoutZone(whitespaceAccessor, id) {
      if (this._zones.hasOwnProperty(id)) {
        const zone = this._zones[id];
        const props = this._computeWhitespaceProps(zone.delegate);
        zone.isInHiddenArea = props.isInHiddenArea;
        whitespaceAccessor.changeOneWhitespace(zone.whitespaceId, props.afterViewLineNumber, props.heightInPx);
        this._safeCallOnComputedHeight(zone.delegate, props.heightInPx);
        this.setShouldRender();
        return true;
      }
      return false;
    }
    shouldSuppressMouseDownOnViewZone(id) {
      if (this._zones.hasOwnProperty(id)) {
        const zone = this._zones[id];
        return Boolean(zone.delegate.suppressMouseDown);
      }
      return false;
    }
    _heightInPixels(zone) {
      if (typeof zone.heightInPx === "number") {
        return zone.heightInPx;
      }
      if (typeof zone.heightInLines === "number") {
        return this._lineHeight * zone.heightInLines;
      }
      return this._lineHeight;
    }
    _minWidthInPixels(zone) {
      if (typeof zone.minWidthInPx === "number") {
        return zone.minWidthInPx;
      }
      return 0;
    }
    _safeCallOnComputedHeight(zone, height) {
      if (typeof zone.onComputedHeight === "function") {
        try {
          zone.onComputedHeight(height);
        } catch (e) {
          onUnexpectedError(e);
        }
      }
    }
    _safeCallOnDomNodeTop(zone, top) {
      if (typeof zone.onDomNodeTop === "function") {
        try {
          zone.onDomNodeTop(top);
        } catch (e) {
          onUnexpectedError(e);
        }
      }
    }
    prepareRender(ctx) {
    }
    render(ctx) {
      const visibleWhitespaces = ctx.viewportData.whitespaceViewportData;
      const visibleZones = {};
      let hasVisibleZone = false;
      for (const visibleWhitespace of visibleWhitespaces) {
        if (this._zones[visibleWhitespace.id].isInHiddenArea) {
          continue;
        }
        visibleZones[visibleWhitespace.id] = visibleWhitespace;
        hasVisibleZone = true;
      }
      const keys = Object.keys(this._zones);
      for (let i2 = 0, len = keys.length; i2 < len; i2++) {
        const id = keys[i2];
        const zone = this._zones[id];
        let newTop = 0;
        let newHeight = 0;
        let newDisplay = "none";
        if (visibleZones.hasOwnProperty(id)) {
          newTop = visibleZones[id].verticalOffset - ctx.bigNumbersDelta;
          newHeight = visibleZones[id].height;
          newDisplay = "block";
          if (!zone.isVisible) {
            zone.domNode.setAttribute("monaco-visible-view-zone", "true");
            zone.isVisible = true;
          }
          this._safeCallOnDomNodeTop(zone.delegate, ctx.getScrolledTopFromAbsoluteTop(visibleZones[id].verticalOffset));
        } else {
          if (zone.isVisible) {
            zone.domNode.removeAttribute("monaco-visible-view-zone");
            zone.isVisible = false;
          }
          this._safeCallOnDomNodeTop(zone.delegate, ctx.getScrolledTopFromAbsoluteTop(-1e6));
        }
        zone.domNode.setTop(newTop);
        zone.domNode.setHeight(newHeight);
        zone.domNode.setDisplay(newDisplay);
        if (zone.marginDomNode) {
          zone.marginDomNode.setTop(newTop);
          zone.marginDomNode.setHeight(newHeight);
          zone.marginDomNode.setDisplay(newDisplay);
        }
      }
      if (hasVisibleZone) {
        this.domNode.setWidth(Math.max(ctx.scrollWidth, this._contentWidth));
        this.marginDomNode.setWidth(this._contentLeft);
      }
    }
  }
  function safeInvoke1Arg(func, arg1) {
    try {
      return func(arg1);
    } catch (e) {
      onUnexpectedError(e);
      return void 0;
    }
  }
  class WhitespaceOverlay extends DynamicViewOverlay {
    constructor(context) {
      super();
      this._context = context;
      this._options = new WhitespaceOptions(this._context.configuration);
      this._selection = [];
      this._renderResult = null;
      this._context.addEventHandler(this);
    }
    dispose() {
      this._context.removeEventHandler(this);
      this._renderResult = null;
      super.dispose();
    }
    // --- begin event handlers
    onConfigurationChanged(e) {
      const newOptions = new WhitespaceOptions(this._context.configuration);
      if (this._options.equals(newOptions)) {
        return e.hasChanged(
          165
          /* EditorOption.layoutInfo */
        );
      }
      this._options = newOptions;
      return true;
    }
    onCursorStateChanged(e) {
      this._selection = e.selections;
      if (this._options.renderWhitespace === "selection") {
        return true;
      }
      return false;
    }
    onDecorationsChanged(e) {
      return true;
    }
    onFlushed(e) {
      return true;
    }
    onLinesChanged(e) {
      return true;
    }
    onLinesDeleted(e) {
      return true;
    }
    onLinesInserted(e) {
      return true;
    }
    onScrollChanged(e) {
      return e.scrollTopChanged;
    }
    onZonesChanged(e) {
      return true;
    }
    // --- end event handlers
    prepareRender(ctx) {
      if (this._options.renderWhitespace === "none") {
        this._renderResult = null;
        return;
      }
      const startLineNumber = ctx.visibleRange.startLineNumber;
      const endLineNumber = ctx.visibleRange.endLineNumber;
      const lineCount = endLineNumber - startLineNumber + 1;
      const needed = new Array(lineCount);
      for (let i2 = 0; i2 < lineCount; i2++) {
        needed[i2] = true;
      }
      this._renderResult = [];
      for (let lineNumber = ctx.viewportData.startLineNumber; lineNumber <= ctx.viewportData.endLineNumber; lineNumber++) {
        const lineIndex = lineNumber - ctx.viewportData.startLineNumber;
        const lineData = this._context.viewModel.getViewLineRenderingData(lineNumber);
        let selectionsOnLine = null;
        if (this._options.renderWhitespace === "selection") {
          const selections = this._selection;
          for (const selection of selections) {
            if (selection.endLineNumber < lineNumber || selection.startLineNumber > lineNumber) {
              continue;
            }
            const startColumn = selection.startLineNumber === lineNumber ? selection.startColumn : lineData.minColumn;
            const endColumn = selection.endLineNumber === lineNumber ? selection.endColumn : lineData.maxColumn;
            if (startColumn < endColumn) {
              if (!selectionsOnLine) {
                selectionsOnLine = [];
              }
              selectionsOnLine.push(new OffsetRange(startColumn - 1, endColumn - 1));
            }
          }
        }
        this._renderResult[lineIndex] = this._applyRenderWhitespace(ctx, lineNumber, selectionsOnLine, lineData);
      }
    }
    _applyRenderWhitespace(ctx, lineNumber, selections, lineData) {
      if (lineData.hasVariableFonts) {
        return "";
      }
      if (this._options.renderWhitespace === "selection" && !selections) {
        return "";
      }
      if (this._options.renderWhitespace === "trailing" && lineData.continuesWithWrappedLine) {
        return "";
      }
      const color = this._context.theme.getColor(editorWhitespaces);
      const USE_SVG = this._options.renderWithSVG;
      const lineContent = lineData.content;
      const len = this._options.stopRenderingLineAfter === -1 ? lineContent.length : Math.min(this._options.stopRenderingLineAfter, lineContent.length);
      const continuesWithWrappedLine = lineData.continuesWithWrappedLine;
      const fauxIndentLength = lineData.minColumn - 1;
      const onlyBoundary = this._options.renderWhitespace === "boundary";
      const onlyTrailing = this._options.renderWhitespace === "trailing";
      const lineHeight = ctx.getLineHeightForLineNumber(lineNumber);
      const middotWidth = this._options.middotWidth;
      const wsmiddotWidth = this._options.wsmiddotWidth;
      const spaceWidth = this._options.spaceWidth;
      const wsmiddotDiff = Math.abs(wsmiddotWidth - spaceWidth);
      const middotDiff = Math.abs(middotWidth - spaceWidth);
      const renderSpaceCharCode = wsmiddotDiff < middotDiff ? 11825 : 183;
      const canUseHalfwidthRightwardsArrow = this._options.canUseHalfwidthRightwardsArrow;
      let result = "";
      let lineIsEmptyOrWhitespace = false;
      let firstNonWhitespaceIndex$1 = firstNonWhitespaceIndex(lineContent);
      let lastNonWhitespaceIndex$1;
      if (firstNonWhitespaceIndex$1 === -1) {
        lineIsEmptyOrWhitespace = true;
        firstNonWhitespaceIndex$1 = len;
        lastNonWhitespaceIndex$1 = len;
      } else {
        lastNonWhitespaceIndex$1 = lastNonWhitespaceIndex(lineContent);
      }
      let currentSelectionIndex = 0;
      let currentSelection = selections && selections[currentSelectionIndex];
      let maxLeft = 0;
      for (let charIndex = fauxIndentLength; charIndex < len; charIndex++) {
        const chCode = lineContent.charCodeAt(charIndex);
        if (currentSelection && currentSelection.endExclusive <= charIndex) {
          currentSelectionIndex++;
          currentSelection = selections && selections[currentSelectionIndex];
        }
        if (chCode !== 9 && chCode !== 32) {
          continue;
        }
        if (onlyTrailing && !lineIsEmptyOrWhitespace && charIndex <= lastNonWhitespaceIndex$1) {
          continue;
        }
        if (onlyBoundary && charIndex >= firstNonWhitespaceIndex$1 && charIndex <= lastNonWhitespaceIndex$1 && chCode === 32) {
          const prevChCode = charIndex - 1 >= 0 ? lineContent.charCodeAt(charIndex - 1) : 0;
          const nextChCode = charIndex + 1 < len ? lineContent.charCodeAt(charIndex + 1) : 0;
          if (prevChCode !== 32 && nextChCode !== 32) {
            continue;
          }
        }
        if (onlyBoundary && continuesWithWrappedLine && charIndex === len - 1) {
          const prevCharCode = charIndex - 1 >= 0 ? lineContent.charCodeAt(charIndex - 1) : 0;
          const isSingleTrailingSpace = chCode === 32 && (prevCharCode !== 32 && prevCharCode !== 9);
          if (isSingleTrailingSpace) {
            continue;
          }
        }
        if (selections && !(currentSelection && currentSelection.start <= charIndex && charIndex < currentSelection.endExclusive)) {
          continue;
        }
        const visibleRange = ctx.visibleRangeForPosition(new Position$1(lineNumber, charIndex + 1));
        if (!visibleRange) {
          continue;
        }
        if (USE_SVG) {
          maxLeft = Math.max(maxLeft, visibleRange.left);
          if (chCode === 9) {
            result += this._renderArrow(lineHeight, spaceWidth, visibleRange.left);
          } else {
            result += `<circle cx="${(visibleRange.left + spaceWidth / 2).toFixed(2)}" cy="${(lineHeight / 2).toFixed(2)}" r="${(spaceWidth / 7).toFixed(2)}" />`;
          }
        } else {
          if (chCode === 9) {
            result += `<div class="mwh" style="left:${visibleRange.left}px;height:${lineHeight}px;">${canUseHalfwidthRightwardsArrow ? String.fromCharCode(65515) : String.fromCharCode(8594)}</div>`;
          } else {
            result += `<div class="mwh" style="left:${visibleRange.left}px;height:${lineHeight}px;">${String.fromCharCode(renderSpaceCharCode)}</div>`;
          }
        }
      }
      if (USE_SVG) {
        maxLeft = Math.round(maxLeft + spaceWidth);
        return `<svg style="bottom:0;position:absolute;width:${maxLeft}px;height:${lineHeight}px" viewBox="0 0 ${maxLeft} ${lineHeight}" xmlns="http://www.w3.org/2000/svg" fill="${color}">` + result + `</svg>`;
      }
      return result;
    }
    _renderArrow(lineHeight, spaceWidth, left) {
      const strokeWidth = spaceWidth / 7;
      const width2 = spaceWidth;
      const dy = lineHeight / 2;
      const dx = left;
      const p1 = { x: 0, y: strokeWidth / 2 };
      const p2 = { x: 100 / 125 * width2, y: p1.y };
      const p3 = { x: p2.x - 0.2 * p2.x, y: p2.y + 0.2 * p2.x };
      const p4 = { x: p3.x + 0.1 * p2.x, y: p3.y + 0.1 * p2.x };
      const p5 = { x: p4.x + 0.35 * p2.x, y: p4.y - 0.35 * p2.x };
      const p6 = { x: p5.x, y: -p5.y };
      const p7 = { x: p4.x, y: -p4.y };
      const p8 = { x: p3.x, y: -p3.y };
      const p9 = { x: p2.x, y: -p2.y };
      const p10 = { x: p1.x, y: -p1.y };
      const p = [p1, p2, p3, p4, p5, p6, p7, p8, p9, p10];
      const parts = p.map((p11) => `${(dx + p11.x).toFixed(2)} ${(dy + p11.y).toFixed(2)}`).join(" L ");
      return `<path d="M ${parts}" />`;
    }
    render(startLineNumber, lineNumber) {
      if (!this._renderResult) {
        return "";
      }
      const lineIndex = lineNumber - startLineNumber;
      if (lineIndex < 0 || lineIndex >= this._renderResult.length) {
        return "";
      }
      return this._renderResult[lineIndex];
    }
  }
  class WhitespaceOptions {
    constructor(config) {
      const options = config.options;
      const fontInfo = options.get(
        59
        /* EditorOption.fontInfo */
      );
      const experimentalWhitespaceRendering = options.get(
        47
        /* EditorOption.experimentalWhitespaceRendering */
      );
      if (experimentalWhitespaceRendering === "off") {
        this.renderWhitespace = "none";
        this.renderWithSVG = false;
      } else if (experimentalWhitespaceRendering === "svg") {
        this.renderWhitespace = options.get(
          113
          /* EditorOption.renderWhitespace */
        );
        this.renderWithSVG = true;
      } else {
        this.renderWhitespace = options.get(
          113
          /* EditorOption.renderWhitespace */
        );
        this.renderWithSVG = false;
      }
      this.spaceWidth = fontInfo.spaceWidth;
      this.middotWidth = fontInfo.middotWidth;
      this.wsmiddotWidth = fontInfo.wsmiddotWidth;
      this.canUseHalfwidthRightwardsArrow = fontInfo.canUseHalfwidthRightwardsArrow;
      this.lineHeight = options.get(
        75
        /* EditorOption.lineHeight */
      );
      this.stopRenderingLineAfter = options.get(
        133
        /* EditorOption.stopRenderingLineAfter */
      );
    }
    equals(other) {
      return this.renderWhitespace === other.renderWhitespace && this.renderWithSVG === other.renderWithSVG && this.spaceWidth === other.spaceWidth && this.middotWidth === other.middotWidth && this.wsmiddotWidth === other.wsmiddotWidth && this.canUseHalfwidthRightwardsArrow === other.canUseHalfwidthRightwardsArrow && this.lineHeight === other.lineHeight && this.stopRenderingLineAfter === other.stopRenderingLineAfter;
    }
  }
  class ViewportData {
    constructor(selections, partialData, whitespaceViewportData, model) {
      this.selections = selections;
      this.startLineNumber = partialData.startLineNumber | 0;
      this.endLineNumber = partialData.endLineNumber | 0;
      this.relativeVerticalOffset = partialData.relativeVerticalOffset;
      this.bigNumbersDelta = partialData.bigNumbersDelta | 0;
      this.lineHeight = partialData.lineHeight | 0;
      this.whitespaceViewportData = whitespaceViewportData;
      this._model = model;
      this.visibleRange = new Range$2(partialData.startLineNumber, this._model.getLineMinColumn(partialData.startLineNumber), partialData.endLineNumber, this._model.getLineMaxColumn(partialData.endLineNumber));
    }
    getViewLineRenderingData(lineNumber) {
      return this._model.getViewportViewLineRenderingData(this.visibleRange, lineNumber);
    }
    getDecorationsInViewport() {
      return this._model.getDecorationsInViewport(this.visibleRange);
    }
  }
  class EditorTheme {
    get type() {
      return this._theme.type;
    }
    get value() {
      return this._theme;
    }
    constructor(theme) {
      this._theme = theme;
    }
    update(theme) {
      this._theme = theme;
    }
    getColor(color) {
      return this._theme.getColor(color);
    }
  }
  class ViewContext {
    constructor(configuration, theme, model) {
      this.configuration = configuration;
      this.theme = new EditorTheme(theme);
      this.viewModel = model;
      this.viewLayout = model.viewLayout;
    }
    addEventHandler(eventHandler) {
      this.viewModel.addViewEventHandler(eventHandler);
    }
    removeEventHandler(eventHandler) {
      this.viewModel.removeViewEventHandler(eventHandler);
    }
  }
  const quadVertices = new Float32Array([
    1,
    0,
    1,
    1,
    0,
    1,
    0,
    0,
    0,
    1,
    1,
    0
  ]);
  function ensureNonNullable(value) {
    if (!value) {
      throw new Error(`Value "${value}" cannot be null`);
    }
    return value;
  }
  function observeDevicePixelDimensions(element, parentWindow, callback) {
    let observer = new parentWindow.ResizeObserver((entries2) => {
      const entry = entries2.find((entry2) => entry2.target === element);
      if (!entry) {
        return;
      }
      if (!("devicePixelContentBoxSize" in entry)) {
        observer?.disconnect();
        observer = void 0;
        return;
      }
      const width2 = entry.devicePixelContentBoxSize[0].inlineSize;
      const height = entry.devicePixelContentBoxSize[0].blockSize;
      if (width2 > 0 && height > 0) {
        callback(width2, height);
      }
    });
    try {
      observer.observe(element, { box: ["device-pixel-content-box"] });
    } catch {
      observer.disconnect();
      observer = void 0;
      throw new BugIndicatingError("Could not observe device pixel dimensions");
    }
    return toDisposable(() => observer?.disconnect());
  }
  var __decorate$30 = 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;
  };
  let nextId = 0;
  class GlyphRasterizer extends Disposable {
    get cacheKey() {
      return `${this.fontFamily}_${this.fontSize}px`;
    }
    constructor(fontSize, fontFamily, devicePixelRatio, _decorationStyleCache) {
      super();
      this.fontSize = fontSize;
      this.fontFamily = fontFamily;
      this.devicePixelRatio = devicePixelRatio;
      this._decorationStyleCache = _decorationStyleCache;
      this.id = nextId++;
      this._workGlyph = {
        source: null,
        boundingBox: {
          left: 0,
          bottom: 0,
          right: 0,
          top: 0
        },
        originOffset: {
          x: 0,
          y: 0
        },
        fontBoundingBoxAscent: 0,
        fontBoundingBoxDescent: 0
      };
      this._workGlyphConfig = { chars: void 0, tokenMetadata: 0, decorationStyleSetId: 0 };
      this._antiAliasing = isMacintosh ? "greyscale" : "subpixel";
      const devicePixelFontSize = Math.ceil(this.fontSize * devicePixelRatio);
      this._canvas = new OffscreenCanvas(devicePixelFontSize * 3, devicePixelFontSize * 3);
      this._ctx = ensureNonNullable(this._canvas.getContext("2d", {
        willReadFrequently: true,
        alpha: this._antiAliasing === "greyscale"
      }));
      this._ctx.textBaseline = "top";
      this._ctx.fillStyle = "#FFFFFF";
      this._ctx.font = `${devicePixelFontSize}px ${this.fontFamily}`;
      this._textMetrics = this._ctx.measureText("A");
    }
    /**
     * Rasterizes a glyph. Note that the returned object is reused across different glyphs and
     * therefore is only safe for synchronous access.
     */
    rasterizeGlyph(chars, tokenMetadata, decorationStyleSetId, colorMap) {
      if (chars === "") {
        return {
          source: this._canvas,
          boundingBox: { top: 0, left: 0, bottom: -1, right: -1 },
          originOffset: { x: 0, y: 0 },
          fontBoundingBoxAscent: 0,
          fontBoundingBoxDescent: 0
        };
      }
      if (this._workGlyphConfig.chars === chars && this._workGlyphConfig.tokenMetadata === tokenMetadata && this._workGlyphConfig.decorationStyleSetId === decorationStyleSetId) {
        return this._workGlyph;
      }
      this._workGlyphConfig.chars = chars;
      this._workGlyphConfig.tokenMetadata = tokenMetadata;
      this._workGlyphConfig.decorationStyleSetId = decorationStyleSetId;
      return this._rasterizeGlyph(chars, tokenMetadata, decorationStyleSetId, colorMap);
    }
    _rasterizeGlyph(chars, tokenMetadata, decorationStyleSetId, colorMap) {
      const devicePixelFontSize = Math.ceil(this.fontSize * this.devicePixelRatio);
      const canvasDim = devicePixelFontSize * 3;
      if (this._canvas.width !== canvasDim) {
        this._canvas.width = canvasDim;
        this._canvas.height = canvasDim;
      }
      this._ctx.save();
      const xSubPixelXOffset = (tokenMetadata & 15) / 10;
      const bgId = TokenMetadata.getBackground(tokenMetadata);
      const bg = colorMap[bgId];
      const decorationStyleSet = this._decorationStyleCache.getStyleSet(decorationStyleSetId);
      if (this._antiAliasing === "subpixel") {
        this._ctx.fillStyle = bg;
        this._ctx.fillRect(0, 0, this._canvas.width, this._canvas.height);
      } else {
        this._ctx.clearRect(0, 0, this._canvas.width, this._canvas.height);
      }
      const fontSb = new StringBuilder(200);
      const fontStyle = TokenMetadata.getFontStyle(tokenMetadata);
      if (fontStyle & 1) {
        fontSb.appendString("italic ");
      }
      if (decorationStyleSet?.bold !== void 0) {
        if (decorationStyleSet.bold) {
          fontSb.appendString("bold ");
        }
      } else if (fontStyle & 2) {
        fontSb.appendString("bold ");
      }
      fontSb.appendString(`${devicePixelFontSize}px ${this.fontFamily}`);
      this._ctx.font = fontSb.build();
      const originX = devicePixelFontSize;
      const originY = devicePixelFontSize;
      if (decorationStyleSet?.color !== void 0) {
        this._ctx.fillStyle = `#${decorationStyleSet.color.toString(16).padStart(8, "0")}`;
      } else {
        this._ctx.fillStyle = colorMap[TokenMetadata.getForeground(tokenMetadata)];
      }
      this._ctx.textBaseline = "top";
      if (decorationStyleSet?.opacity !== void 0) {
        this._ctx.globalAlpha = decorationStyleSet.opacity;
      }
      this._ctx.fillText(chars, originX + xSubPixelXOffset, originY);
      this._ctx.restore();
      const imageData = this._ctx.getImageData(0, 0, this._canvas.width, this._canvas.height);
      if (this._antiAliasing === "subpixel") {
        const bgR = parseInt(bg.substring(1, 3), 16);
        const bgG = parseInt(bg.substring(3, 5), 16);
        const bgB = parseInt(bg.substring(5, 7), 16);
        this._clearColor(imageData, bgR, bgG, bgB);
        this._ctx.putImageData(imageData, 0, 0);
      }
      this._findGlyphBoundingBox(imageData, this._workGlyph.boundingBox);
      this._workGlyph.source = this._canvas;
      this._workGlyph.originOffset.x = this._workGlyph.boundingBox.left - originX;
      this._workGlyph.originOffset.y = this._workGlyph.boundingBox.top - originY;
      this._workGlyph.fontBoundingBoxAscent = this._textMetrics.fontBoundingBoxAscent;
      this._workGlyph.fontBoundingBoxDescent = this._textMetrics.fontBoundingBoxDescent;
      return this._workGlyph;
    }
    _clearColor(imageData, r, g, b) {
      for (let offset = 0; offset < imageData.data.length; offset += 4) {
        if (imageData.data[offset] === r && imageData.data[offset + 1] === g && imageData.data[offset + 2] === b) {
          imageData.data[offset + 3] = 0;
        }
      }
    }
    // TODO: Does this even need to happen when measure text is used?
    _findGlyphBoundingBox(imageData, outBoundingBox) {
      const height = this._canvas.height;
      const width2 = this._canvas.width;
      let found = false;
      for (let y = 0; y < height; y++) {
        for (let x = 0; x < width2; x++) {
          const alphaOffset = y * width2 * 4 + x * 4 + 3;
          if (imageData.data[alphaOffset] !== 0) {
            outBoundingBox.top = y;
            found = true;
            break;
          }
        }
        if (found) {
          break;
        }
      }
      outBoundingBox.left = 0;
      found = false;
      for (let x = 0; x < width2; x++) {
        for (let y = 0; y < height; y++) {
          const alphaOffset = y * width2 * 4 + x * 4 + 3;
          if (imageData.data[alphaOffset] !== 0) {
            outBoundingBox.left = x;
            found = true;
            break;
          }
        }
        if (found) {
          break;
        }
      }
      outBoundingBox.right = width2;
      found = false;
      for (let x = width2 - 1; x >= outBoundingBox.left; x--) {
        for (let y = 0; y < height; y++) {
          const alphaOffset = y * width2 * 4 + x * 4 + 3;
          if (imageData.data[alphaOffset] !== 0) {
            outBoundingBox.right = x;
            found = true;
            break;
          }
        }
        if (found) {
          break;
        }
      }
      outBoundingBox.bottom = outBoundingBox.top;
      found = false;
      for (let y = height - 1; y >= 0; y--) {
        for (let x = 0; x < width2; x++) {
          const alphaOffset = y * width2 * 4 + x * 4 + 3;
          if (imageData.data[alphaOffset] !== 0) {
            outBoundingBox.bottom = y;
            found = true;
            break;
          }
        }
        if (found) {
          break;
        }
      }
    }
    getTextMetrics(text2) {
      return this._ctx.measureText(text2);
    }
  }
  __decorate$30([
    memoize
  ], GlyphRasterizer.prototype, "cacheKey", null);
  var __decorate$2$ = 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$2W = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  let TaskQueue = class TaskQueue extends Disposable {
    constructor(_logService) {
      super();
      this._logService = _logService;
      this._tasks = [];
      this._i = 0;
      this._register(toDisposable(() => this.clear()));
    }
    enqueue(task) {
      this._tasks.push(task);
      this._start();
    }
    clear() {
      if (this._idleCallback) {
        this._cancelCallback(this._idleCallback);
        this._idleCallback = void 0;
      }
      this._i = 0;
      this._tasks.length = 0;
    }
    _start() {
      if (!this._idleCallback) {
        this._idleCallback = this._requestCallback(this._process.bind(this));
      }
    }
    _process(deadline) {
      this._idleCallback = void 0;
      let taskDuration = 0;
      let longestTask = 0;
      let lastDeadlineRemaining = deadline.timeRemaining();
      let deadlineRemaining = 0;
      while (this._i < this._tasks.length) {
        taskDuration = Date.now();
        if (!this._tasks[this._i]()) {
          this._i++;
        }
        taskDuration = Math.max(1, Date.now() - taskDuration);
        longestTask = Math.max(taskDuration, longestTask);
        deadlineRemaining = deadline.timeRemaining();
        if (longestTask * 1.5 > deadlineRemaining) {
          if (lastDeadlineRemaining - taskDuration < -20) {
            this._logService.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(lastDeadlineRemaining - taskDuration))}ms`);
          }
          this._start();
          return;
        }
        lastDeadlineRemaining = deadlineRemaining;
      }
      this.clear();
    }
  };
  TaskQueue = __decorate$2$([
    __param$2W(0, ILogService)
  ], TaskQueue);
  class PriorityTaskQueue extends TaskQueue {
    _requestCallback(callback) {
      return getActiveWindow().setTimeout(() => callback(this._createDeadline(16)));
    }
    _cancelCallback(identifier) {
      getActiveWindow().clearTimeout(identifier);
    }
    _createDeadline(duration) {
      const end = Date.now() + duration;
      return {
        timeRemaining: () => Math.max(0, end - Date.now())
      };
    }
  }
  class IdleTaskQueueInternal extends TaskQueue {
    _requestCallback(callback) {
      return getActiveWindow().requestIdleCallback(callback);
    }
    _cancelCallback(identifier) {
      getActiveWindow().cancelIdleCallback(identifier);
    }
  }
  const IdleTaskQueue = "requestIdleCallback" in getActiveWindow() ? IdleTaskQueueInternal : PriorityTaskQueue;
  class TextureAtlasShelfAllocator {
    constructor(_canvas, _textureIndex) {
      this._canvas = _canvas;
      this._textureIndex = _textureIndex;
      this._currentRow = {
        x: 0,
        y: 0,
        h: 0
      };
      this._allocatedGlyphs = /* @__PURE__ */ new Set();
      this._nextIndex = 0;
      this._ctx = ensureNonNullable(this._canvas.getContext("2d", {
        willReadFrequently: true
      }));
    }
    allocate(rasterizedGlyph) {
      const glyphWidth = rasterizedGlyph.boundingBox.right - rasterizedGlyph.boundingBox.left + 1;
      const glyphHeight = rasterizedGlyph.boundingBox.bottom - rasterizedGlyph.boundingBox.top + 1;
      if (glyphWidth > this._canvas.width || glyphHeight > this._canvas.height) {
        throw new BugIndicatingError("Glyph is too large for the atlas page");
      }
      if (rasterizedGlyph.boundingBox.right - rasterizedGlyph.boundingBox.left + 1 > this._canvas.width - this._currentRow.x) {
        this._currentRow.x = 0;
        this._currentRow.y += this._currentRow.h;
        this._currentRow.h = 1;
      }
      if (this._currentRow.y + rasterizedGlyph.boundingBox.bottom - rasterizedGlyph.boundingBox.top + 1 > this._canvas.height) {
        return void 0;
      }
      this._ctx.drawImage(
        rasterizedGlyph.source,
        // source
        rasterizedGlyph.boundingBox.left,
        rasterizedGlyph.boundingBox.top,
        glyphWidth,
        glyphHeight,
        // destination
        this._currentRow.x,
        this._currentRow.y,
        glyphWidth,
        glyphHeight
      );
      const glyph = {
        pageIndex: this._textureIndex,
        glyphIndex: this._nextIndex++,
        x: this._currentRow.x,
        y: this._currentRow.y,
        w: glyphWidth,
        h: glyphHeight,
        originOffsetX: rasterizedGlyph.originOffset.x,
        originOffsetY: rasterizedGlyph.originOffset.y,
        fontBoundingBoxAscent: rasterizedGlyph.fontBoundingBoxAscent,
        fontBoundingBoxDescent: rasterizedGlyph.fontBoundingBoxDescent
      };
      this._currentRow.x += glyphWidth;
      this._currentRow.h = Math.max(this._currentRow.h, glyphHeight);
      this._allocatedGlyphs.add(glyph);
      return glyph;
    }
    getUsagePreview() {
      const w = this._canvas.width;
      const h2 = this._canvas.height;
      const canvas = new OffscreenCanvas(w, h2);
      const ctx = ensureNonNullable(canvas.getContext("2d"));
      ctx.fillStyle = "#808080";
      ctx.fillRect(0, 0, w, h2);
      const rowHeight = /* @__PURE__ */ new Map();
      const rowWidth = /* @__PURE__ */ new Map();
      for (const g of this._allocatedGlyphs) {
        rowHeight.set(g.y, Math.max(rowHeight.get(g.y) ?? 0, g.h));
        rowWidth.set(g.y, Math.max(rowWidth.get(g.y) ?? 0, g.x + g.w));
      }
      for (const g of this._allocatedGlyphs) {
        ctx.fillStyle = "#4040FF";
        ctx.fillRect(g.x, g.y, g.w, g.h);
        ctx.fillStyle = "#FF0000";
        ctx.fillRect(g.x, g.y + g.h, g.w, rowHeight.get(g.y) - g.h);
      }
      for (const [rowY, rowW] of rowWidth.entries()) {
        if (rowY !== this._currentRow.y) {
          ctx.fillStyle = "#FF0000";
          ctx.fillRect(rowW, rowY, w - rowW, rowHeight.get(rowY));
        }
      }
      return canvas.convertToBlob();
    }
    getStats() {
      const w = this._canvas.width;
      const h2 = this._canvas.height;
      let usedPixels = 0;
      let wastedPixels = 0;
      const totalPixels = w * h2;
      const rowHeight = /* @__PURE__ */ new Map();
      const rowWidth = /* @__PURE__ */ new Map();
      for (const g of this._allocatedGlyphs) {
        rowHeight.set(g.y, Math.max(rowHeight.get(g.y) ?? 0, g.h));
        rowWidth.set(g.y, Math.max(rowWidth.get(g.y) ?? 0, g.x + g.w));
      }
      for (const g of this._allocatedGlyphs) {
        usedPixels += g.w * g.h;
        wastedPixels += g.w * (rowHeight.get(g.y) - g.h);
      }
      for (const [rowY, rowW] of rowWidth.entries()) {
        if (rowY !== this._currentRow.y) {
          wastedPixels += (w - rowW) * rowHeight.get(rowY);
        }
      }
      return [
        `page${this._textureIndex}:`,
        `     Total: ${totalPixels} (${w}x${h2})`,
        `      Used: ${usedPixels} (${(usedPixels / totalPixels * 100).toPrecision(2)}%)`,
        `    Wasted: ${wastedPixels} (${(wastedPixels / totalPixels * 100).toPrecision(2)}%)`,
        `Efficiency: ${(usedPixels / (usedPixels + wastedPixels) * 100).toPrecision(2)}%`
      ].join("\n");
    }
  }
  class TextureAtlasSlabAllocator {
    constructor(_canvas, _textureIndex, options) {
      this._canvas = _canvas;
      this._textureIndex = _textureIndex;
      this._slabs = [];
      this._activeSlabsByDims = new NKeyMap();
      this._unusedRects = [];
      this._openRegionsByHeight = /* @__PURE__ */ new Map();
      this._openRegionsByWidth = /* @__PURE__ */ new Map();
      this._allocatedGlyphs = /* @__PURE__ */ new Set();
      this._nextIndex = 0;
      this._ctx = ensureNonNullable(this._canvas.getContext("2d", {
        willReadFrequently: true
      }));
      this._slabW = Math.min(options?.slabW ?? 64 << Math.max(Math.floor(getActiveWindow().devicePixelRatio) - 1, 0), this._canvas.width);
      this._slabH = Math.min(options?.slabH ?? this._slabW, this._canvas.height);
      this._slabsPerRow = Math.floor(this._canvas.width / this._slabW);
      this._slabsPerColumn = Math.floor(this._canvas.height / this._slabH);
    }
    allocate(rasterizedGlyph) {
      const glyphWidth = rasterizedGlyph.boundingBox.right - rasterizedGlyph.boundingBox.left + 1;
      const glyphHeight = rasterizedGlyph.boundingBox.bottom - rasterizedGlyph.boundingBox.top + 1;
      if (glyphWidth > this._canvas.width || glyphHeight > this._canvas.height) {
        throw new BugIndicatingError("Glyph is too large for the atlas page");
      }
      if (glyphWidth > this._slabW || glyphHeight > this._slabH) {
        if (this._allocatedGlyphs.size > 0) {
          return void 0;
        }
        let sizeCandidate = this._canvas.width;
        while (glyphWidth < sizeCandidate / 2 && glyphHeight < sizeCandidate / 2) {
          sizeCandidate /= 2;
        }
        this._slabW = sizeCandidate;
        this._slabH = sizeCandidate;
        this._slabsPerRow = Math.floor(this._canvas.width / this._slabW);
        this._slabsPerColumn = Math.floor(this._canvas.height / this._slabH);
      }
      const desiredSlabSize = {
        // Nearest square number
        // TODO: This can probably be optimized
        // w: 1 << Math.ceil(Math.sqrt(glyphWidth)),
        // h: 1 << Math.ceil(Math.sqrt(glyphHeight)),
        // Nearest x px
        // w: Math.ceil(glyphWidth / nearestXPixels) * nearestXPixels,
        // h: Math.ceil(glyphHeight / nearestXPixels) * nearestXPixels,
        // Round odd numbers up
        // w: glyphWidth % 0 === 1 ? glyphWidth + 1 : glyphWidth,
        // h: glyphHeight % 0 === 1 ? glyphHeight + 1 : glyphHeight,
        // Exact number only
        w: glyphWidth,
        h: glyphHeight
      };
      let slab = this._activeSlabsByDims.get(desiredSlabSize.w, desiredSlabSize.h);
      if (slab) {
        const glyphsPerSlab = Math.floor(this._slabW / slab.entryW) * Math.floor(this._slabH / slab.entryH);
        if (slab.count >= glyphsPerSlab) {
          slab = void 0;
        }
      }
      let dx;
      let dy;
      if (!slab) {
        if (glyphWidth < glyphHeight) {
          const openRegions = this._openRegionsByWidth.get(glyphWidth);
          if (openRegions?.length) {
            for (let i2 = openRegions.length - 1; i2 >= 0; i2--) {
              const r = openRegions[i2];
              if (r.w >= glyphWidth && r.h >= glyphHeight) {
                dx = r.x;
                dy = r.y;
                if (glyphWidth < r.w) {
                  this._unusedRects.push({
                    x: r.x + glyphWidth,
                    y: r.y,
                    w: r.w - glyphWidth,
                    h: glyphHeight
                  });
                }
                r.y += glyphHeight;
                r.h -= glyphHeight;
                if (r.h === 0) {
                  if (i2 === openRegions.length - 1) {
                    openRegions.pop();
                  } else {
                    this._unusedRects.splice(i2, 1);
                  }
                }
                break;
              }
            }
          }
        } else {
          const openRegions = this._openRegionsByHeight.get(glyphHeight);
          if (openRegions?.length) {
            for (let i2 = openRegions.length - 1; i2 >= 0; i2--) {
              const r = openRegions[i2];
              if (r.w >= glyphWidth && r.h >= glyphHeight) {
                dx = r.x;
                dy = r.y;
                if (glyphHeight < r.h) {
                  this._unusedRects.push({
                    x: r.x,
                    y: r.y + glyphHeight,
                    w: glyphWidth,
                    h: r.h - glyphHeight
                  });
                }
                r.x += glyphWidth;
                r.w -= glyphWidth;
                if (r.h === 0) {
                  if (i2 === openRegions.length - 1) {
                    openRegions.pop();
                  } else {
                    this._unusedRects.splice(i2, 1);
                  }
                }
                break;
              }
            }
          }
        }
      }
      if (dx === void 0 || dy === void 0) {
        if (!slab) {
          if (this._slabs.length >= this._slabsPerRow * this._slabsPerColumn) {
            return void 0;
          }
          slab = {
            x: Math.floor(this._slabs.length % this._slabsPerRow) * this._slabW,
            y: Math.floor(this._slabs.length / this._slabsPerRow) * this._slabH,
            entryW: desiredSlabSize.w,
            entryH: desiredSlabSize.h,
            count: 0
          };
          const unusedW = this._slabW % slab.entryW;
          const unusedH = this._slabH % slab.entryH;
          if (unusedW) {
            addEntryToMapArray(this._openRegionsByWidth, unusedW, {
              x: slab.x + this._slabW - unusedW,
              w: unusedW,
              y: slab.y,
              h: this._slabH - (unusedH ?? 0)
            });
          }
          if (unusedH) {
            addEntryToMapArray(this._openRegionsByHeight, unusedH, {
              x: slab.x,
              w: this._slabW,
              y: slab.y + this._slabH - unusedH,
              h: unusedH
            });
          }
          this._slabs.push(slab);
          this._activeSlabsByDims.set(slab, desiredSlabSize.w, desiredSlabSize.h);
        }
        const glyphsPerRow = Math.floor(this._slabW / slab.entryW);
        dx = slab.x + Math.floor(slab.count % glyphsPerRow) * slab.entryW;
        dy = slab.y + Math.floor(slab.count / glyphsPerRow) * slab.entryH;
        slab.count++;
      }
      this._ctx.drawImage(
        rasterizedGlyph.source,
        // source
        rasterizedGlyph.boundingBox.left,
        rasterizedGlyph.boundingBox.top,
        glyphWidth,
        glyphHeight,
        // destination
        dx,
        dy,
        glyphWidth,
        glyphHeight
      );
      const glyph = {
        pageIndex: this._textureIndex,
        glyphIndex: this._nextIndex++,
        x: dx,
        y: dy,
        w: glyphWidth,
        h: glyphHeight,
        originOffsetX: rasterizedGlyph.originOffset.x,
        originOffsetY: rasterizedGlyph.originOffset.y,
        fontBoundingBoxAscent: rasterizedGlyph.fontBoundingBoxAscent,
        fontBoundingBoxDescent: rasterizedGlyph.fontBoundingBoxDescent
      };
      this._allocatedGlyphs.add(glyph);
      return glyph;
    }
    getUsagePreview() {
      const w = this._canvas.width;
      const h2 = this._canvas.height;
      const canvas = new OffscreenCanvas(w, h2);
      const ctx = ensureNonNullable(canvas.getContext("2d"));
      ctx.fillStyle = "#808080";
      ctx.fillRect(0, 0, w, h2);
      let slabEntryPixels = 0;
      let usedPixels = 0;
      let restrictedPixels = 0;
      const slabW = 64 << Math.floor(getActiveWindow().devicePixelRatio) - 1;
      const slabH = slabW;
      for (const slab of this._slabs) {
        let x = 0;
        let y = 0;
        for (let i2 = 0; i2 < slab.count; i2++) {
          if (x + slab.entryW > slabW) {
            x = 0;
            y += slab.entryH;
          }
          ctx.fillStyle = "#FF0000";
          ctx.fillRect(slab.x + x, slab.y + y, slab.entryW, slab.entryH);
          slabEntryPixels += slab.entryW * slab.entryH;
          x += slab.entryW;
        }
        const entriesPerRow = Math.floor(slabW / slab.entryW);
        const entriesPerCol = Math.floor(slabH / slab.entryH);
        slab.entryW * entriesPerRow * slab.entryH * entriesPerCol;
      }
      for (const g of this._allocatedGlyphs) {
        usedPixels += g.w * g.h;
        ctx.fillStyle = "#4040FF";
        ctx.fillRect(g.x, g.y, g.w, g.h);
      }
      const unusedRegions = Array.from(this._openRegionsByWidth.values()).flat().concat(Array.from(this._openRegionsByHeight.values()).flat());
      for (const r of unusedRegions) {
        ctx.fillStyle = "#FF000088";
        ctx.fillRect(r.x, r.y, r.w, r.h);
        restrictedPixels += r.w * r.h;
      }
      ctx.globalAlpha = 0.5;
      ctx.drawImage(this._canvas, 0, 0);
      ctx.globalAlpha = 1;
      return canvas.convertToBlob();
    }
    getStats() {
      const w = this._canvas.width;
      const h2 = this._canvas.height;
      let slabEntryPixels = 0;
      let usedPixels = 0;
      let slabEdgePixels = 0;
      let wastedPixels = 0;
      let restrictedPixels = 0;
      const totalPixels = w * h2;
      const slabW = 64 << Math.floor(getActiveWindow().devicePixelRatio) - 1;
      const slabH = slabW;
      for (const slab of this._slabs) {
        let x = 0;
        let y = 0;
        for (let i2 = 0; i2 < slab.count; i2++) {
          if (x + slab.entryW > slabW) {
            x = 0;
            y += slab.entryH;
          }
          slabEntryPixels += slab.entryW * slab.entryH;
          x += slab.entryW;
        }
        const entriesPerRow = Math.floor(slabW / slab.entryW);
        const entriesPerCol = Math.floor(slabH / slab.entryH);
        const thisSlabPixels = slab.entryW * entriesPerRow * slab.entryH * entriesPerCol;
        slabEdgePixels += slabW * slabH - thisSlabPixels;
      }
      for (const g of this._allocatedGlyphs) {
        usedPixels += g.w * g.h;
      }
      const unusedRegions = Array.from(this._openRegionsByWidth.values()).flat().concat(Array.from(this._openRegionsByHeight.values()).flat());
      for (const r of unusedRegions) {
        restrictedPixels += r.w * r.h;
      }
      const edgeUsedPixels = slabEdgePixels - restrictedPixels;
      wastedPixels = slabEntryPixels - (usedPixels - edgeUsedPixels);
      const efficiency = usedPixels / (usedPixels + wastedPixels + restrictedPixels);
      return [
        `page[${this._textureIndex}]:`,
        `     Total: ${totalPixels}px (${w}x${h2})`,
        `      Used: ${usedPixels}px (${(usedPixels / totalPixels * 100).toFixed(2)}%)`,
        `    Wasted: ${wastedPixels}px (${(wastedPixels / totalPixels * 100).toFixed(2)}%)`,
        `Restricted: ${restrictedPixels}px (${(restrictedPixels / totalPixels * 100).toFixed(2)}%) (hard to allocate)`,
        `Efficiency: ${efficiency === 1 ? "100" : (efficiency * 100).toFixed(2)}%`,
        `     Slabs: ${this._slabs.length} of ${Math.floor(this._canvas.width / slabW) * Math.floor(this._canvas.height / slabH)}`
      ].join("\n");
    }
  }
  function addEntryToMapArray(map, key, entry) {
    let list2 = map.get(key);
    if (!list2) {
      list2 = [];
      map.set(key, list2);
    }
    list2.push(entry);
  }
  var __decorate$2_ = 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$2V = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  var TextureAtlasPage_1;
  let TextureAtlasPage = (_e = class extends Disposable {
    get version() {
      return this._version;
    }
    get usedArea() {
      return this._usedArea;
    }
    get source() {
      return this._canvas;
    }
    get glyphs() {
      return this._glyphInOrderSet.values();
    }
    constructor(textureIndex, pageSize, allocatorType, _logService, themeService) {
      super();
      this._logService = _logService;
      this._version = 0;
      this._usedArea = { left: 0, top: 0, right: 0, bottom: 0 };
      this._glyphMap = new NKeyMap();
      this._glyphInOrderSet = /* @__PURE__ */ new Set();
      this._canvas = new OffscreenCanvas(pageSize, pageSize);
      this._colorMap = themeService.getColorTheme().tokenColorMap;
      switch (allocatorType) {
        case "shelf":
          this._allocator = new TextureAtlasShelfAllocator(this._canvas, textureIndex);
          break;
        case "slab":
          this._allocator = new TextureAtlasSlabAllocator(this._canvas, textureIndex);
          break;
        default:
          this._allocator = allocatorType(this._canvas, textureIndex);
          break;
      }
      this._register(toDisposable(() => {
        this._canvas.width = 1;
        this._canvas.height = 1;
      }));
    }
    getGlyph(rasterizer, chars, tokenMetadata, decorationStyleSetId) {
      return this._glyphMap.get(chars, tokenMetadata, decorationStyleSetId, rasterizer.cacheKey) ?? this._createGlyph(rasterizer, chars, tokenMetadata, decorationStyleSetId);
    }
    _createGlyph(rasterizer, chars, tokenMetadata, decorationStyleSetId) {
      if (this._glyphInOrderSet.size >= TextureAtlasPage_1.maximumGlyphCount) {
        return void 0;
      }
      const rasterizedGlyph = rasterizer.rasterizeGlyph(chars, tokenMetadata, decorationStyleSetId, this._colorMap);
      const glyph = this._allocator.allocate(rasterizedGlyph);
      if (glyph === void 0) {
        return void 0;
      }
      this._glyphMap.set(glyph, chars, tokenMetadata, decorationStyleSetId, rasterizer.cacheKey);
      this._glyphInOrderSet.add(glyph);
      this._version++;
      this._usedArea.right = Math.max(this._usedArea.right, glyph.x + glyph.w - 1);
      this._usedArea.bottom = Math.max(this._usedArea.bottom, glyph.y + glyph.h - 1);
      if (this._logService.getLevel() === LogLevel.Trace) {
        this._logService.trace("New glyph", {
          chars,
          tokenMetadata,
          decorationStyleSetId,
          rasterizedGlyph,
          glyph
        });
      }
      return glyph;
    }
    getUsagePreview() {
      return this._allocator.getUsagePreview();
    }
    getStats() {
      return this._allocator.getStats();
    }
  }, TextureAtlasPage_1 = _e, _e.maximumGlyphCount = 5e3, _e);
  TextureAtlasPage = TextureAtlasPage_1 = __decorate$2_([
    __param$2V(3, ILogService),
    __param$2V(4, IThemeService)
  ], TextureAtlasPage);
  var __decorate$2Z = 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$2U = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  var TextureAtlas_1;
  let TextureAtlas = (_f = class extends Disposable {
    get pages() {
      return this._pages;
    }
    constructor(_maxTextureSize, options, _decorationStyleCache, _themeService, _instantiationService) {
      super();
      this._maxTextureSize = _maxTextureSize;
      this._decorationStyleCache = _decorationStyleCache;
      this._themeService = _themeService;
      this._instantiationService = _instantiationService;
      this._warmUpTask = this._register(new MutableDisposable());
      this._warmedUpRasterizers = /* @__PURE__ */ new Set();
      this._pages = [];
      this._glyphPageIndex = new NKeyMap();
      this._onDidDeleteGlyphs = this._register(new Emitter$1());
      this.onDidDeleteGlyphs = this._onDidDeleteGlyphs.event;
      this._allocatorType = options?.allocatorType ?? "slab";
      this._register(Event.runAndSubscribe(this._themeService.onDidColorThemeChange, () => {
        if (this._colorMap) {
          this.clear();
        }
        this._colorMap = this._themeService.getColorTheme().tokenColorMap;
      }));
      const dprFactor = Math.max(1, Math.floor(getActiveWindow().devicePixelRatio));
      this.pageSize = Math.min(1024 * dprFactor, this._maxTextureSize);
      this._initFirstPage();
      this._register(toDisposable(() => dispose(this._pages)));
    }
    _initFirstPage() {
      const firstPage = this._instantiationService.createInstance(TextureAtlasPage, 0, this.pageSize, this._allocatorType);
      this._pages.push(firstPage);
      const nullRasterizer = new GlyphRasterizer(1, "", 1, this._decorationStyleCache);
      firstPage.getGlyph(nullRasterizer, "", 0, 0);
      nullRasterizer.dispose();
    }
    clear() {
      for (const page of this._pages) {
        page.dispose();
      }
      this._pages.length = 0;
      this._glyphPageIndex.clear();
      this._warmedUpRasterizers.clear();
      this._warmUpTask.clear();
      this._initFirstPage();
      this._onDidDeleteGlyphs.fire();
    }
    getGlyph(rasterizer, chars, tokenMetadata, decorationStyleSetId, x) {
      tokenMetadata &= -2048;
      tokenMetadata |= Math.floor(x % 1 * 10);
      if (!this._warmedUpRasterizers.has(rasterizer.id)) {
        this._warmUpAtlas(rasterizer);
        this._warmedUpRasterizers.add(rasterizer.id);
      }
      return this._tryGetGlyph(this._glyphPageIndex.get(chars, tokenMetadata, decorationStyleSetId, rasterizer.cacheKey) ?? 0, rasterizer, chars, tokenMetadata, decorationStyleSetId);
    }
    _tryGetGlyph(pageIndex, rasterizer, chars, tokenMetadata, decorationStyleSetId) {
      this._glyphPageIndex.set(pageIndex, chars, tokenMetadata, decorationStyleSetId, rasterizer.cacheKey);
      return this._pages[pageIndex].getGlyph(rasterizer, chars, tokenMetadata, decorationStyleSetId) ?? (pageIndex + 1 < this._pages.length ? this._tryGetGlyph(pageIndex + 1, rasterizer, chars, tokenMetadata, decorationStyleSetId) : void 0) ?? this._getGlyphFromNewPage(rasterizer, chars, tokenMetadata, decorationStyleSetId);
    }
    _getGlyphFromNewPage(rasterizer, chars, tokenMetadata, decorationStyleSetId) {
      if (this._pages.length >= TextureAtlas_1.maximumPageCount) {
        throw new Error(`Attempt to create a texture atlas page past the limit ${TextureAtlas_1.maximumPageCount}`);
      }
      this._pages.push(this._instantiationService.createInstance(TextureAtlasPage, this._pages.length, this.pageSize, this._allocatorType));
      this._glyphPageIndex.set(this._pages.length - 1, chars, tokenMetadata, decorationStyleSetId, rasterizer.cacheKey);
      return this._pages[this._pages.length - 1].getGlyph(rasterizer, chars, tokenMetadata, decorationStyleSetId);
    }
    getStats() {
      return this._pages.map((e) => e.getStats());
    }
    /**
     * Warms up the atlas by rasterizing all printable ASCII characters for each token color. This
     * is distrubuted over multiple idle callbacks to avoid blocking the main thread.
     */
    _warmUpAtlas(rasterizer) {
      const colorMap = this._colorMap;
      if (!colorMap) {
        throw new BugIndicatingError("Cannot warm atlas without color map");
      }
      this._warmUpTask.value?.clear();
      const taskQueue = this._warmUpTask.value = this._instantiationService.createInstance(IdleTaskQueue);
      for (let code = 65; code <= 90; code++) {
        for (const fgColor of colorMap.keys()) {
          taskQueue.enqueue(() => {
            for (let x = 0; x < 1; x += 0.1) {
              this.getGlyph(rasterizer, String.fromCharCode(code), fgColor << 15 & 16744448, 0, x);
            }
          });
        }
      }
      for (let code = 97; code <= 122; code++) {
        for (const fgColor of colorMap.keys()) {
          taskQueue.enqueue(() => {
            for (let x = 0; x < 1; x += 0.1) {
              this.getGlyph(rasterizer, String.fromCharCode(code), fgColor << 15 & 16744448, 0, x);
            }
          });
        }
      }
      for (let code = 33; code <= 126; code++) {
        for (const fgColor of colorMap.keys()) {
          taskQueue.enqueue(() => {
            for (let x = 0; x < 1; x += 0.1) {
              this.getGlyph(rasterizer, String.fromCharCode(code), fgColor << 15 & 16744448, 0, x);
            }
          });
        }
      }
    }
  }, TextureAtlas_1 = _f, _f.maximumPageCount = 16, _f);
  TextureAtlas = TextureAtlas_1 = __decorate$2Z([
    __param$2U(3, IThemeService),
    __param$2U(4, IInstantiationService)
  ], TextureAtlas);
  var Severity$1;
  (function(Severity2) {
    Severity2[Severity2["Ignore"] = 0] = "Ignore";
    Severity2[Severity2["Info"] = 1] = "Info";
    Severity2[Severity2["Warning"] = 2] = "Warning";
    Severity2[Severity2["Error"] = 3] = "Error";
  })(Severity$1 || (Severity$1 = {}));
  (function(Severity2) {
    const _error = "error";
    const _warning = "warning";
    const _warn = "warn";
    const _info = "info";
    const _ignore = "ignore";
    function fromValue(value) {
      if (!value) {
        return Severity2.Ignore;
      }
      if (equalsIgnoreCase(_error, value)) {
        return Severity2.Error;
      }
      if (equalsIgnoreCase(_warning, value) || equalsIgnoreCase(_warn, value)) {
        return Severity2.Warning;
      }
      if (equalsIgnoreCase(_info, value)) {
        return Severity2.Info;
      }
      return Severity2.Ignore;
    }
    Severity2.fromValue = fromValue;
    function toString(severity) {
      switch (severity) {
        case Severity2.Error:
          return _error;
        case Severity2.Warning:
          return _warning;
        case Severity2.Info:
          return _info;
        default:
          return _ignore;
      }
    }
    Severity2.toString = toString;
  })(Severity$1 || (Severity$1 = {}));
  const Severity$2 = Severity$1;
  var Severity = Severity$2;
  const INotificationService = createDecorator("notificationService");
  class NoOpNotification {
  }
  var GPULifecycle;
  (function(GPULifecycle2) {
    async function requestDevice(fallback2) {
      try {
        if (!navigator.gpu) {
          throw new Error("This browser does not support WebGPU");
        }
        const adapter = await navigator.gpu.requestAdapter();
        if (!adapter) {
          throw new Error("This browser supports WebGPU but it appears to be disabled");
        }
        return wrapDestroyableInDisposable(await adapter.requestDevice());
      } catch (e) {
        if (fallback2) {
          fallback2(e.message);
        }
        throw e;
      }
    }
    GPULifecycle2.requestDevice = requestDevice;
    function createBuffer(device, descriptor, initialValues) {
      const buffer = device.createBuffer(descriptor);
      if (initialValues) {
        device.queue.writeBuffer(buffer, 0, isFunction(initialValues) ? initialValues() : initialValues);
      }
      return wrapDestroyableInDisposable(buffer);
    }
    GPULifecycle2.createBuffer = createBuffer;
    function createTexture(device, descriptor) {
      return wrapDestroyableInDisposable(device.createTexture(descriptor));
    }
    GPULifecycle2.createTexture = createTexture;
  })(GPULifecycle || (GPULifecycle = {}));
  function wrapDestroyableInDisposable(value) {
    return {
      object: value,
      dispose: () => value.destroy()
    };
  }
  class BufferDirtyTracker {
    get dataOffset() {
      return this._startIndex;
    }
    get dirtySize() {
      if (this._startIndex === void 0 || this._endIndex === void 0) {
        return void 0;
      }
      return this._endIndex - this._startIndex + 1;
    }
    get isDirty() {
      return this._startIndex !== void 0;
    }
    /**
     * Flag the index(es) as modified. Returns the index flagged.
     * @param index An index to flag.
     * @param length An optional length to flag. Defaults to 1.
     */
    flag(index, length = 1) {
      this._flag(index);
      if (length > 1) {
        this._flag(index + length - 1);
      }
      return index;
    }
    _flag(index) {
      if (this._startIndex === void 0 || index < this._startIndex) {
        this._startIndex = index;
      }
      if (this._endIndex === void 0 || index > this._endIndex) {
        this._endIndex = index;
      }
    }
    clear() {
      this._startIndex = void 0;
      this._endIndex = void 0;
    }
  }
  function createObjectCollectionBuffer(propertySpecs, capacity) {
    return new ObjectCollectionBuffer(propertySpecs, capacity);
  }
  class ObjectCollectionBuffer extends Disposable {
    get entryCount() {
      return this._entries.size;
    }
    get dirtyTracker() {
      return this._dirtyTracker;
    }
    constructor(propertySpecs, capacity) {
      super();
      this.propertySpecs = propertySpecs;
      this.capacity = capacity;
      this._dirtyTracker = new BufferDirtyTracker();
      this._propertySpecsMap = /* @__PURE__ */ new Map();
      this._entries = new LinkedList();
      this._onDidChange = this._register(new Emitter$1());
      this._onDidChangeBuffer = this._register(new Emitter$1());
      this.onDidChangeBuffer = this._onDidChangeBuffer.event;
      this.view = new Float32Array(capacity * propertySpecs.length);
      this.buffer = this.view.buffer;
      this._entrySize = propertySpecs.length;
      for (let i2 = 0; i2 < propertySpecs.length; i2++) {
        const spec = {
          offset: i2,
          ...propertySpecs[i2]
        };
        this._propertySpecsMap.set(spec.name, spec);
      }
      this._register(toDisposable(() => dispose(this._entries)));
    }
    createEntry(data) {
      if (this._entries.size === this.capacity) {
        this._expandBuffer();
        this._onDidChangeBuffer.fire();
      }
      const value = new ObjectCollectionBufferEntry(this.view, this._propertySpecsMap, this._dirtyTracker, this._entries.size, data);
      const removeFromEntries = this._entries.push(value);
      const listeners = [];
      listeners.push(Event.forward(value.onDidChange, this._onDidChange));
      listeners.push(value.onWillDispose(() => {
        const deletedEntryIndex = value.i;
        removeFromEntries();
        this.view.set(this.view.subarray(deletedEntryIndex * this._entrySize + 2, this._entries.size * this._entrySize + 2), deletedEntryIndex * this._entrySize);
        for (const entry of this._entries) {
          if (entry.i > deletedEntryIndex) {
            entry.i--;
          }
        }
        this._dirtyTracker.flag(deletedEntryIndex, (this._entries.size - deletedEntryIndex) * this._entrySize);
        dispose(listeners);
      }));
      return value;
    }
    _expandBuffer() {
      this.capacity *= 2;
      const newView = new Float32Array(this.capacity * this._entrySize);
      newView.set(this.view);
      this.view = newView;
      this.buffer = this.view.buffer;
    }
  }
  class ObjectCollectionBufferEntry extends Disposable {
    constructor(_view, _propertySpecsMap, _dirtyTracker, i2, data) {
      super();
      this._view = _view;
      this._propertySpecsMap = _propertySpecsMap;
      this._dirtyTracker = _dirtyTracker;
      this.i = i2;
      this._onDidChange = this._register(new Emitter$1());
      this.onDidChange = this._onDidChange.event;
      this._onWillDispose = this._register(new Emitter$1());
      this.onWillDispose = this._onWillDispose.event;
      for (const propertySpec of this._propertySpecsMap.values()) {
        this._view[this.i * this._propertySpecsMap.size + propertySpec.offset] = data[propertySpec.name];
      }
      this._dirtyTracker.flag(this.i * this._propertySpecsMap.size, this._propertySpecsMap.size);
    }
    dispose() {
      this._onWillDispose.fire();
      super.dispose();
    }
    setRaw(data) {
      if (data.length !== this._propertySpecsMap.size) {
        throw new Error(`Data length ${data.length} does not match the number of properties in the collection (${this._propertySpecsMap.size})`);
      }
      this._view.set(data, this.i * this._propertySpecsMap.size);
      this._dirtyTracker.flag(this.i * this._propertySpecsMap.size, this._propertySpecsMap.size);
    }
  }
  const rectangleRendererWgsl = (
    /*wgsl*/
    `

struct Vertex {
	@location(0) position: vec2f,
};

struct LayoutInfo {
	canvasDims: vec2f,
	viewportOffset: vec2f,
	viewportDims: vec2f,
}

struct ScrollOffset {
	offset: vec2f,
}

struct Shape {
	position: vec2f,
	size: vec2f,
	color: vec4f,
};

struct VSOutput {
	@builtin(position) position: vec4f,
	@location(1)       color:    vec4f,
};

// Uniforms
@group(0) @binding(${1}) var<uniform>       layoutInfo:      LayoutInfo;

// Storage buffers
@group(0) @binding(${0})            var<storage, read> shapes:          array<Shape>;
@group(0) @binding(${2})      var<uniform>       scrollOffset:    ScrollOffset;

@vertex fn vs(
	vert: Vertex,
	@builtin(instance_index) instanceIndex: u32,
	@builtin(vertex_index) vertexIndex : u32
) -> VSOutput {
	let shape = shapes[instanceIndex];

	var vsOut: VSOutput;
	vsOut.position = vec4f(
		(
			// Top left corner
			vec2f(-1,  1) +
			// Convert pixel position to clipspace
			vec2f( 2, -2) / layoutInfo.canvasDims *
			// Shape position and size
			(layoutInfo.viewportOffset - scrollOffset.offset + shape.position + vert.position * shape.size)
		),
		0.0,
		1.0
	);
	vsOut.color = shape.color;
	return vsOut;
}

@fragment fn fs(vsOut: VSOutput) -> @location(0) vec4f {
	return vsOut.color;
}
`
  );
  class RectangleRenderer extends ViewEventHandler {
    constructor(_context, _contentLeft, _devicePixelRatio, _canvas, _ctx, device) {
      super();
      this._context = _context;
      this._contentLeft = _contentLeft;
      this._devicePixelRatio = _devicePixelRatio;
      this._canvas = _canvas;
      this._ctx = _ctx;
      this._shapeBindBuffer = this._register(new MutableDisposable());
      this._initialized = false;
      this._shapeCollection = this._register(createObjectCollectionBuffer([
        { name: "x" },
        { name: "y" },
        { name: "width" },
        { name: "height" },
        { name: "red" },
        { name: "green" },
        { name: "blue" },
        { name: "alpha" }
      ], 32));
      this._context.addEventHandler(this);
      this._initWebgpu(device);
    }
    async _initWebgpu(device) {
      this._device = await device;
      if (this._store.isDisposed) {
        return;
      }
      const presentationFormat = navigator.gpu.getPreferredCanvasFormat();
      this._ctx.configure({
        device: this._device,
        format: presentationFormat,
        alphaMode: "premultiplied"
      });
      this._renderPassColorAttachment = {
        view: null,
        // Will be filled at render time
        loadOp: "load",
        storeOp: "store"
      };
      this._renderPassDescriptor = {
        label: "Monaco rectangle renderer render pass",
        colorAttachments: [this._renderPassColorAttachment]
      };
      let layoutInfoUniformBuffer;
      {
        const bufferValues = new Float32Array(
          6
          /* Info.FloatsPerEntry */
        );
        const updateBufferValues = (canvasDevicePixelWidth = this._canvas.width, canvasDevicePixelHeight = this._canvas.height) => {
          bufferValues[
            0
            /* Info.Offset_CanvasWidth____ */
          ] = canvasDevicePixelWidth;
          bufferValues[
            1
            /* Info.Offset_CanvasHeight___ */
          ] = canvasDevicePixelHeight;
          bufferValues[
            2
            /* Info.Offset_ViewportOffsetX */
          ] = Math.ceil(this._context.configuration.options.get(
            165
            /* EditorOption.layoutInfo */
          ).contentLeft * getActiveWindow().devicePixelRatio);
          bufferValues[
            3
            /* Info.Offset_ViewportOffsetY */
          ] = 0;
          bufferValues[
            4
            /* Info.Offset_ViewportWidth__ */
          ] = bufferValues[
            0
            /* Info.Offset_CanvasWidth____ */
          ] - bufferValues[
            2
            /* Info.Offset_ViewportOffsetX */
          ];
          bufferValues[
            5
            /* Info.Offset_ViewportHeight_ */
          ] = bufferValues[
            1
            /* Info.Offset_CanvasHeight___ */
          ] - bufferValues[
            3
            /* Info.Offset_ViewportOffsetY */
          ];
          return bufferValues;
        };
        layoutInfoUniformBuffer = this._register(GPULifecycle.createBuffer(this._device, {
          label: "Monaco rectangle renderer uniform buffer",
          size: 24,
          usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
        }, () => updateBufferValues())).object;
        this._register(observeDevicePixelDimensions(this._canvas, getActiveWindow(), (w, h2) => {
          this._device.queue.writeBuffer(layoutInfoUniformBuffer, 0, updateBufferValues(w, h2));
        }));
      }
      const scrollOffsetBufferSize = 2;
      this._scrollOffsetBindBuffer = this._register(GPULifecycle.createBuffer(this._device, {
        label: "Monaco rectangle renderer scroll offset buffer",
        size: scrollOffsetBufferSize * Float32Array.BYTES_PER_ELEMENT,
        usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
      })).object;
      this._scrollOffsetValueBuffer = new Float32Array(scrollOffsetBufferSize);
      const createShapeBindBuffer = () => {
        return GPULifecycle.createBuffer(this._device, {
          label: "Monaco rectangle renderer shape buffer",
          size: this._shapeCollection.buffer.byteLength,
          usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST
        });
      };
      this._shapeBindBuffer.value = createShapeBindBuffer();
      this._register(Event.runAndSubscribe(this._shapeCollection.onDidChangeBuffer, () => {
        this._shapeBindBuffer.value = createShapeBindBuffer();
        if (this._pipeline) {
          this._updateBindGroup(this._pipeline, layoutInfoUniformBuffer);
        }
      }));
      this._vertexBuffer = this._register(GPULifecycle.createBuffer(this._device, {
        label: "Monaco rectangle renderer vertex buffer",
        size: quadVertices.byteLength,
        usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST
      }, quadVertices)).object;
      const module = this._device.createShaderModule({
        label: "Monaco rectangle renderer shader module",
        code: rectangleRendererWgsl
      });
      this._pipeline = this._device.createRenderPipeline({
        label: "Monaco rectangle renderer render pipeline",
        layout: "auto",
        vertex: {
          module,
          buffers: [
            {
              arrayStride: 2 * Float32Array.BYTES_PER_ELEMENT,
              // 2 floats, 4 bytes each
              attributes: [
                { shaderLocation: 0, offset: 0, format: "float32x2" }
                // position
              ]
            }
          ]
        },
        fragment: {
          module,
          targets: [
            {
              format: presentationFormat,
              blend: {
                color: {
                  srcFactor: "src-alpha",
                  dstFactor: "one-minus-src-alpha"
                },
                alpha: {
                  srcFactor: "src-alpha",
                  dstFactor: "one-minus-src-alpha"
                }
              }
            }
          ]
        }
      });
      this._updateBindGroup(this._pipeline, layoutInfoUniformBuffer);
      this._initialized = true;
    }
    _updateBindGroup(pipeline, layoutInfoUniformBuffer) {
      this._bindGroup = this._device.createBindGroup({
        label: "Monaco rectangle renderer bind group",
        layout: pipeline.getBindGroupLayout(0),
        entries: [
          { binding: 0, resource: { buffer: this._shapeBindBuffer.value.object } },
          { binding: 1, resource: { buffer: layoutInfoUniformBuffer } },
          { binding: 2, resource: { buffer: this._scrollOffsetBindBuffer } }
        ]
      });
    }
    register(x, y, width2, height, red, green, blue, alpha) {
      return this._shapeCollection.createEntry({ x, y, width: width2, height, red, green, blue, alpha });
    }
    // #region Event handlers
    onScrollChanged(e) {
      if (this._device) {
        const dpr = getActiveWindow().devicePixelRatio;
        this._scrollOffsetValueBuffer[0] = this._context.viewLayout.getCurrentScrollLeft() * dpr;
        this._scrollOffsetValueBuffer[1] = this._context.viewLayout.getCurrentScrollTop() * dpr;
        this._device.queue.writeBuffer(this._scrollOffsetBindBuffer, 0, this._scrollOffsetValueBuffer);
      }
      return true;
    }
    // #endregion
    _update() {
      if (!this._device) {
        return;
      }
      const shapes = this._shapeCollection;
      if (shapes.dirtyTracker.isDirty) {
        this._device.queue.writeBuffer(this._shapeBindBuffer.value.object, 0, shapes.buffer, shapes.dirtyTracker.dataOffset, shapes.dirtyTracker.dirtySize * shapes.view.BYTES_PER_ELEMENT);
        shapes.dirtyTracker.clear();
      }
    }
    draw(viewportData) {
      if (!this._initialized) {
        return;
      }
      this._update();
      const encoder = this._device.createCommandEncoder({ label: "Monaco rectangle renderer command encoder" });
      this._renderPassColorAttachment.view = this._ctx.getCurrentTexture().createView();
      const pass = encoder.beginRenderPass(this._renderPassDescriptor);
      pass.setPipeline(this._pipeline);
      pass.setVertexBuffer(0, this._vertexBuffer);
      pass.setBindGroup(0, this._bindGroup);
      const contentLeft = Math.ceil(this._contentLeft.get() * this._devicePixelRatio.get());
      pass.setScissorRect(contentLeft, 0, this._canvas.width - contentLeft, this._canvas.height);
      pass.draw(quadVertices.length / 2, this._shapeCollection.entryCount);
      pass.end();
      const commandBuffer = encoder.finish();
      this._device.queue.submit([commandBuffer]);
    }
  }
  class DecorationCssRuleExtractor extends Disposable {
    constructor() {
      super();
      this._ruleCache = /* @__PURE__ */ new Map();
      this._container = $$l("div.monaco-decoration-css-rule-extractor");
      this._dummyElement = $$l("span");
      this._container.appendChild(this._dummyElement);
      this._register(toDisposable(() => this._container.remove()));
    }
    getStyleRules(canvas, decorationClassName) {
      const existing = this._ruleCache.get(decorationClassName);
      if (existing) {
        return existing;
      }
      this._dummyElement.className = decorationClassName;
      canvas.appendChild(this._container);
      const rules = this._getStyleRules(decorationClassName);
      this._ruleCache.set(decorationClassName, rules);
      canvas.removeChild(this._container);
      return rules;
    }
    _getStyleRules(className2) {
      const rules = [];
      const doc = getActiveDocument();
      const stylesheets = [...doc.styleSheets];
      for (let i2 = 0; i2 < stylesheets.length; i2++) {
        const stylesheet = stylesheets[i2];
        for (const rule of stylesheet.cssRules) {
          if (rule instanceof CSSImportRule) {
            if (rule.styleSheet) {
              stylesheets.push(rule.styleSheet);
            }
          } else if (rule instanceof CSSStyleRule) {
            const searchTerm = `.${className2}`;
            const index = rule.selectorText.indexOf(searchTerm);
            if (index !== -1) {
              const endOfResult = index + searchTerm.length;
              if (rule.selectorText.length === endOfResult || rule.selectorText.substring(endOfResult, endOfResult + 1).match(/[ :]/)) {
                rules.push(rule);
              }
            }
          }
        }
      }
      return rules;
    }
  }
  class DecorationStyleCache {
    constructor() {
      this._nextId = 1;
      this._cacheById = /* @__PURE__ */ new Map();
      this._cacheByStyle = new NKeyMap();
    }
    getOrCreateEntry(color, bold, opacity) {
      if (color === void 0 && bold === void 0 && opacity === void 0) {
        return 0;
      }
      const result = this._cacheByStyle.get(color ?? 0, bold ? 1 : 0, opacity === void 0 ? "" : opacity.toFixed(2));
      if (result) {
        return result.id;
      }
      const id = this._nextId++;
      const entry = {
        id,
        color,
        bold,
        opacity
      };
      this._cacheById.set(id, entry);
      this._cacheByStyle.set(entry, color ?? 0, bold ? 1 : 0, opacity === void 0 ? "" : opacity.toFixed(2));
      return id;
    }
    getStyleSet(id) {
      if (id === 0) {
        return void 0;
      }
      return this._cacheById.get(id);
    }
  }
  var __decorate$2Y = 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$2T = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  var ViewGpuContext_1;
  let ViewGpuContext = (_g = class extends Disposable {
    static get decorationCssRuleExtractor() {
      return ViewGpuContext_1._decorationCssRuleExtractor;
    }
    static get decorationStyleCache() {
      return ViewGpuContext_1._decorationStyleCache;
    }
    /**
     * The shared texture atlas to use across all views.
     *
     * @throws if called before the GPU device is resolved
     */
    static get atlas() {
      if (!ViewGpuContext_1._atlas) {
        throw new BugIndicatingError("Cannot call ViewGpuContext.textureAtlas before device is resolved");
      }
      return ViewGpuContext_1._atlas;
    }
    /**
     * The shared texture atlas to use across all views. This is a convenience alias for
     * {@link ViewGpuContext.atlas}.
     *
     * @throws if called before the GPU device is resolved
     */
    get atlas() {
      return ViewGpuContext_1.atlas;
    }
    constructor(context, _instantiationService, _notificationService, configurationService) {
      super();
      this._instantiationService = _instantiationService;
      this._notificationService = _notificationService;
      this.configurationService = configurationService;
      this.maxGpuCols = 2e3;
      this.canvas = createFastDomNode(document.createElement("canvas"));
      this.canvas.setClassName("editorCanvas");
      this._register(Event.runAndSubscribe(configurationService.onDidChangeConfiguration, (e) => {
        if (!e || e.affectsConfiguration("editor.scrollbar.verticalScrollbarSize")) {
          const verticalScrollbarSize = configurationService.getValue("editor").scrollbar?.verticalScrollbarSize ?? 14;
          this.canvas.domNode.style.boxSizing = "border-box";
          this.canvas.domNode.style.paddingRight = `${verticalScrollbarSize}px`;
        }
      }));
      this.ctx = ensureNonNullable(this.canvas.domNode.getContext("webgpu"));
      if (!ViewGpuContext_1.device) {
        ViewGpuContext_1.device = GPULifecycle.requestDevice((message) => {
          const choices = [{
            label: localize(78, "Use DOM-based rendering"),
            run: () => this.configurationService.updateValue("editor.experimentalGpuAcceleration", "off")
          }];
          this._notificationService.prompt(Severity.Warning, message, choices);
        }).then((ref) => {
          ViewGpuContext_1.deviceSync = ref.object;
          if (!ViewGpuContext_1._atlas) {
            ViewGpuContext_1._atlas = this._instantiationService.createInstance(TextureAtlas, ref.object.limits.maxTextureDimension2D, void 0, ViewGpuContext_1.decorationStyleCache);
          }
          return ref.object;
        });
      }
      const dprObs = observableValue(this, getActiveWindow().devicePixelRatio);
      this._register(addDisposableListener(getActiveWindow(), "resize", () => {
        dprObs.set(getActiveWindow().devicePixelRatio, void 0);
      }));
      this.devicePixelRatio = dprObs;
      this._register(runOnChange(this.devicePixelRatio, () => ViewGpuContext_1.atlas?.clear()));
      const canvasDevicePixelDimensions = observableValue(this, { width: this.canvas.domNode.width, height: this.canvas.domNode.height });
      this._register(observeDevicePixelDimensions(this.canvas.domNode, getActiveWindow(), (width2, height) => {
        this.canvas.domNode.width = width2;
        this.canvas.domNode.height = height;
        canvasDevicePixelDimensions.set({ width: width2, height }, void 0);
      }));
      this.canvasDevicePixelDimensions = canvasDevicePixelDimensions;
      const contentLeft = observableValue(this, 0);
      this._register(this.configurationService.onDidChangeConfiguration((e) => {
        contentLeft.set(context.configuration.options.get(
          165
          /* EditorOption.layoutInfo */
        ).contentLeft, void 0);
      }));
      this.contentLeft = contentLeft;
      this.rectangleRenderer = this._instantiationService.createInstance(RectangleRenderer, context, this.contentLeft, this.devicePixelRatio, this.canvas.domNode, this.ctx, ViewGpuContext_1.device);
    }
    /**
     * This method determines which lines can be and are allowed to be rendered using the GPU
     * renderer. Eventually this should trend all lines, except maybe exceptional cases like
     * decorations that use class names.
     */
    canRender(options, viewportData, lineNumber) {
      const data = viewportData.getViewLineRenderingData(lineNumber);
      if (data.containsRTL || data.maxColumn > this.maxGpuCols) {
        return false;
      }
      if (data.inlineDecorations.length > 0) {
        let supported = true;
        for (const decoration2 of data.inlineDecorations) {
          if (decoration2.type !== 0) {
            supported = false;
            break;
          }
          const styleRules = ViewGpuContext_1._decorationCssRuleExtractor.getStyleRules(this.canvas.domNode, decoration2.inlineClassName);
          supported &&= styleRules.every((rule) => {
            if (rule.selectorText.includes(":")) {
              return false;
            }
            for (const r of rule.style) {
              if (!supportsCssRule(r, rule.style)) {
                return false;
              }
            }
            return true;
          });
          if (!supported) {
            break;
          }
        }
        return supported;
      }
      return true;
    }
    /**
     * Like {@link canRender} but returns detailed information about why the line cannot be rendered.
     */
    canRenderDetailed(options, viewportData, lineNumber) {
      const data = viewportData.getViewLineRenderingData(lineNumber);
      const reasons = [];
      if (data.containsRTL) {
        reasons.push("containsRTL");
      }
      if (data.maxColumn > this.maxGpuCols) {
        reasons.push("maxColumn > maxGpuCols");
      }
      if (data.inlineDecorations.length > 0) {
        let supported = true;
        const problemTypes = [];
        const problemSelectors = [];
        const problemRules = [];
        for (const decoration2 of data.inlineDecorations) {
          if (decoration2.type !== 0) {
            problemTypes.push(decoration2.type);
            supported = false;
            continue;
          }
          const styleRules = ViewGpuContext_1._decorationCssRuleExtractor.getStyleRules(this.canvas.domNode, decoration2.inlineClassName);
          supported &&= styleRules.every((rule) => {
            if (rule.selectorText.includes(":")) {
              problemSelectors.push(rule.selectorText);
              return false;
            }
            for (const r of rule.style) {
              if (!supportsCssRule(r, rule.style)) {
                problemRules.push(`${r}: ${rule.style[r]}`);
                return false;
              }
            }
            return true;
          });
          if (!supported) {
            continue;
          }
        }
        if (problemTypes.length > 0) {
          reasons.push(`inlineDecorations with unsupported types (${problemTypes.map((e) => `\`${e}\``).join(", ")})`);
        }
        if (problemRules.length > 0) {
          reasons.push(`inlineDecorations with unsupported CSS rules (${problemRules.map((e) => `\`${e}\``).join(", ")})`);
        }
        if (problemSelectors.length > 0) {
          reasons.push(`inlineDecorations with unsupported CSS selectors (${problemSelectors.map((e) => `\`${e}\``).join(", ")})`);
        }
      }
      return reasons;
    }
  }, ViewGpuContext_1 = _g, _g._decorationCssRuleExtractor = new DecorationCssRuleExtractor(), _g._decorationStyleCache = new DecorationStyleCache(), _g);
  ViewGpuContext = ViewGpuContext_1 = __decorate$2Y([
    __param$2T(1, IInstantiationService),
    __param$2T(2, INotificationService),
    __param$2T(3, IConfigurationService)
  ], ViewGpuContext);
  const gpuSupportedDecorationCssRules = [
    "color",
    "font-weight",
    "opacity"
  ];
  function supportsCssRule(rule, style) {
    if (!gpuSupportedDecorationCssRules.includes(rule)) {
      return false;
    }
    switch (rule) {
      default:
        return true;
    }
  }
  function createContentSegmenter(lineData, options) {
    if (lineData.isBasicASCII && options.useMonospaceOptimizations) {
      return new AsciiContentSegmenter(lineData);
    }
    return new GraphemeContentSegmenter(lineData);
  }
  class AsciiContentSegmenter {
    constructor(lineData) {
      this._content = lineData.content;
    }
    getSegmentAtIndex(index) {
      return this._content[index];
    }
  }
  class GraphemeContentSegmenter {
    constructor(lineData) {
      this._segments = [];
      const content = lineData.content;
      const segmenter = safeIntl.Segmenter(void 0, { granularity: "grapheme" }).value;
      const segmentedContent = Array.from(segmenter.segment(content));
      let segmenterIndex = 0;
      for (let x = 0; x < content.length; x++) {
        const segment = segmentedContent[segmenterIndex];
        if (!segment) {
          break;
        }
        if (segment.index !== x) {
          this._segments.push(void 0);
          continue;
        }
        segmenterIndex++;
        this._segments.push(segment);
      }
    }
    getSegmentAtIndex(index) {
      return this._segments[index]?.segment;
    }
  }
  class BaseRenderStrategy extends ViewEventHandler {
    get glyphRasterizer() {
      return this._glyphRasterizer.value;
    }
    constructor(_context, _viewGpuContext, _device, _glyphRasterizer) {
      super();
      this._context = _context;
      this._viewGpuContext = _viewGpuContext;
      this._device = _device;
      this._glyphRasterizer = _glyphRasterizer;
      this._context.addEventHandler(this);
    }
  }
  const fullFileRenderStrategyWgsl = (
    /*wgsl*/
    `
struct GlyphInfo {
	position: vec2f,
	size: vec2f,
	origin: vec2f,
};

struct Vertex {
	@location(0) position: vec2f,
};

struct Cell {
	position: vec2f,
	unused1: vec2f,
	glyphIndex: f32,
	textureIndex: f32
};

struct LayoutInfo {
	canvasDims: vec2f,
	viewportOffset: vec2f,
	viewportDims: vec2f,
}

struct ScrollOffset {
	offset: vec2f
}

struct VSOutput {
	@builtin(position) position:   vec4f,
	@location(1)       layerIndex: f32,
	@location(0)       texcoord:   vec2f,
};

// Uniforms
@group(0) @binding(${4})       var<uniform>       layoutInfo:      LayoutInfo;
@group(0) @binding(${5})  var<uniform>       atlasDims:       vec2f;
@group(0) @binding(${6})            var<uniform>       scrollOffset:    ScrollOffset;

// Storage buffers
@group(0) @binding(${0})               var<storage, read> glyphInfo:       array<array<GlyphInfo, ${TextureAtlasPage.maximumGlyphCount}>, ${TextureAtlas.maximumPageCount}>;
@group(0) @binding(${1})                   var<storage, read> cells:           array<Cell>;

@vertex fn vs(
	vert: Vertex,
	@builtin(instance_index) instanceIndex: u32,
	@builtin(vertex_index) vertexIndex : u32
) -> VSOutput {
	let cell = cells[instanceIndex];
	var glyph = glyphInfo[u32(cell.textureIndex)][u32(cell.glyphIndex)];

	var vsOut: VSOutput;
	// Multiple vert.position by 2,-2 to get it into clipspace which ranged from -1 to 1
	vsOut.position = vec4f(
		// Make everything relative to top left instead of center
		vec2f(-1, 1) +
		((vert.position * vec2f(2, -2)) / layoutInfo.canvasDims) * glyph.size +
		((cell.position * vec2f(2, -2)) / layoutInfo.canvasDims) +
		((glyph.origin * vec2f(2, -2)) / layoutInfo.canvasDims) +
		(((layoutInfo.viewportOffset - scrollOffset.offset * vec2(1, -1)) * 2) / layoutInfo.canvasDims),
		0.0,
		1.0
	);

	vsOut.layerIndex = cell.textureIndex;
	// Textures are flipped from natural direction on the y-axis, so flip it back
	vsOut.texcoord = vert.position;
	vsOut.texcoord = (
		// Glyph offset (0-1)
		(glyph.position / atlasDims) +
		// Glyph coordinate (0-1)
		(vsOut.texcoord * (glyph.size / atlasDims))
	);

	return vsOut;
}

@group(0) @binding(${2}) var ourSampler: sampler;
@group(0) @binding(${3})        var ourTexture: texture_2d_array<f32>;

@fragment fn fs(vsOut: VSOutput) -> @location(0) vec4f {
	return textureSample(ourTexture, ourSampler, vsOut.texcoord, u32(vsOut.layerIndex));
}
`
  );
  const _ViewportRenderStrategy = class _ViewportRenderStrategy extends BaseRenderStrategy {
    get bindGroupEntries() {
      return [
        { binding: 1, resource: { buffer: this._cellBindBuffer } },
        { binding: 6, resource: { buffer: this._scrollOffsetBindBuffer } }
      ];
    }
    constructor(context, viewGpuContext, device, glyphRasterizer) {
      super(context, viewGpuContext, device, glyphRasterizer);
      this.type = "viewport";
      this.wgsl = fullFileRenderStrategyWgsl;
      this._cellBindBufferLineCapacity = 63;
      this._activeDoubleBufferIndex = 0;
      this._visibleObjectCount = 0;
      this._scrollInitialized = false;
      this._onDidChangeBindGroupEntries = this._register(new Emitter$1());
      this.onDidChangeBindGroupEntries = this._onDidChangeBindGroupEntries.event;
      this._rebuildCellBuffer(this._cellBindBufferLineCapacity);
      const scrollOffsetBufferSize = 2;
      this._scrollOffsetBindBuffer = this._register(GPULifecycle.createBuffer(this._device, {
        label: "Monaco scroll offset buffer",
        size: scrollOffsetBufferSize * Float32Array.BYTES_PER_ELEMENT,
        usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
      })).object;
      this._scrollOffsetValueBuffer = new Float32Array(scrollOffsetBufferSize);
    }
    _rebuildCellBuffer(lineCount) {
      this._cellBindBuffer?.destroy();
      const lineCountWithIncrement = (Math.floor(
        lineCount / 32
        /* Constants.CellBindBufferCapacityIncrement */
      ) + 1) * 32;
      const bufferSize = lineCountWithIncrement * _ViewportRenderStrategy.maxSupportedColumns * 6 * Float32Array.BYTES_PER_ELEMENT;
      this._cellBindBuffer = this._register(GPULifecycle.createBuffer(this._device, {
        label: "Monaco full file cell buffer",
        size: bufferSize,
        usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST
      })).object;
      this._cellValueBuffers = [
        new ArrayBuffer(bufferSize),
        new ArrayBuffer(bufferSize)
      ];
      this._cellBindBufferLineCapacity = lineCountWithIncrement;
      this._onDidChangeBindGroupEntries.fire();
    }
    // #region Event handlers
    // The primary job of these handlers is to:
    // 1. Invalidate the up to date line cache, which will cause the line to be re-rendered when
    //    it's _within the viewport_.
    // 2. Pass relevant events on to the render function so it can force certain line ranges to be
    //    re-rendered even if they're not in the viewport. For example when a view zone is added,
    //    there are lines that used to be visible but are no longer, so those ranges must be
    //    cleared and uploaded to the GPU.
    onConfigurationChanged(e) {
      return true;
    }
    onDecorationsChanged(e) {
      return true;
    }
    onTokensChanged(e) {
      return true;
    }
    onLinesDeleted(e) {
      return true;
    }
    onLinesInserted(e) {
      return true;
    }
    onLinesChanged(e) {
      return true;
    }
    onScrollChanged(e) {
      const dpr = getActiveWindow().devicePixelRatio;
      this._scrollOffsetValueBuffer[0] = (e?.scrollLeft ?? this._context.viewLayout.getCurrentScrollLeft()) * dpr;
      this._scrollOffsetValueBuffer[1] = (e?.scrollTop ?? this._context.viewLayout.getCurrentScrollTop()) * dpr;
      this._device.queue.writeBuffer(this._scrollOffsetBindBuffer, 0, this._scrollOffsetValueBuffer);
      return true;
    }
    onThemeChanged(e) {
      return true;
    }
    onLineMappingChanged(e) {
      return true;
    }
    onZonesChanged(e) {
      return true;
    }
    // #endregion
    reset() {
      for (const bufferIndex of [0, 1]) {
        const buffer = new Float32Array(this._cellValueBuffers[bufferIndex]);
        buffer.fill(0, 0, buffer.length);
        this._device.queue.writeBuffer(this._cellBindBuffer, 0, buffer.buffer, 0, buffer.byteLength);
      }
    }
    update(viewportData, viewLineOptions) {
      let chars = "";
      let segment;
      let charWidth = 0;
      let y = 0;
      let x = 0;
      let absoluteOffsetX = 0;
      let absoluteOffsetY = 0;
      let tabXOffset = 0;
      let glyph;
      let cellIndex = 0;
      let tokenStartIndex = 0;
      let tokenEndIndex = 0;
      let tokenMetadata = 0;
      let decorationStyleSetBold;
      let decorationStyleSetColor;
      let decorationStyleSetOpacity;
      let lineData;
      let decoration2;
      let fillStartIndex = 0;
      let fillEndIndex = 0;
      let tokens;
      const dpr = getActiveWindow().devicePixelRatio;
      let contentSegmenter;
      if (!this._scrollInitialized) {
        this.onScrollChanged();
        this._scrollInitialized = true;
      }
      if (this._cellBindBufferLineCapacity < viewportData.endLineNumber - viewportData.startLineNumber + 1) {
        this._rebuildCellBuffer(viewportData.endLineNumber - viewportData.startLineNumber + 1);
      }
      const cellBuffer = new Float32Array(this._cellValueBuffers[this._activeDoubleBufferIndex]);
      cellBuffer.fill(0);
      const lineIndexCount = _ViewportRenderStrategy.maxSupportedColumns * 6;
      for (y = viewportData.startLineNumber; y <= viewportData.endLineNumber; y++) {
        if (!this._viewGpuContext.canRender(viewLineOptions, viewportData, y)) {
          continue;
        }
        lineData = viewportData.getViewLineRenderingData(y);
        tabXOffset = 0;
        contentSegmenter = createContentSegmenter(lineData, viewLineOptions);
        charWidth = viewLineOptions.spaceWidth * dpr;
        absoluteOffsetX = 0;
        tokens = lineData.tokens;
        tokenStartIndex = lineData.minColumn - 1;
        tokenEndIndex = 0;
        for (let tokenIndex = 0, tokensLen = tokens.getCount(); tokenIndex < tokensLen; tokenIndex++) {
          tokenEndIndex = tokens.getEndOffset(tokenIndex);
          if (tokenEndIndex <= tokenStartIndex) {
            continue;
          }
          tokenMetadata = tokens.getMetadata(tokenIndex);
          for (x = tokenStartIndex; x < tokenEndIndex; x++) {
            if (x > _ViewportRenderStrategy.maxSupportedColumns) {
              break;
            }
            segment = contentSegmenter.getSegmentAtIndex(x);
            if (segment === void 0) {
              continue;
            }
            chars = segment;
            if (!(lineData.isBasicASCII && viewLineOptions.useMonospaceOptimizations)) {
              charWidth = this.glyphRasterizer.getTextMetrics(chars).width;
            }
            decorationStyleSetColor = void 0;
            decorationStyleSetBold = void 0;
            decorationStyleSetOpacity = void 0;
            for (decoration2 of lineData.inlineDecorations) {
              if (y < decoration2.range.startLineNumber || y > decoration2.range.endLineNumber || y === decoration2.range.startLineNumber && x < decoration2.range.startColumn - 1 || y === decoration2.range.endLineNumber && x >= decoration2.range.endColumn - 1) {
                continue;
              }
              const rules = ViewGpuContext.decorationCssRuleExtractor.getStyleRules(this._viewGpuContext.canvas.domNode, decoration2.inlineClassName);
              for (const rule of rules) {
                for (const r of rule.style) {
                  const value = rule.styleMap.get(r)?.toString() ?? "";
                  switch (r) {
                    case "color": {
                      const parsedColor = Color.Format.CSS.parse(value);
                      if (!parsedColor) {
                        throw new BugIndicatingError("Invalid color format " + value);
                      }
                      decorationStyleSetColor = parsedColor.toNumber32Bit();
                      break;
                    }
                    case "font-weight": {
                      const parsedValue = parseCssFontWeight$1(value);
                      if (parsedValue >= 400) {
                        decorationStyleSetBold = true;
                      } else {
                        decorationStyleSetBold = false;
                      }
                      break;
                    }
                    case "opacity": {
                      const parsedValue = parseCssOpacity$1(value);
                      decorationStyleSetOpacity = parsedValue;
                      break;
                    }
                    default:
                      throw new BugIndicatingError("Unexpected inline decoration style");
                  }
                }
              }
            }
            if (chars === " " || chars === "	") {
              cellIndex = ((y - 1) * _ViewportRenderStrategy.maxSupportedColumns + x) * 6;
              cellBuffer.fill(
                0,
                cellIndex,
                cellIndex + 6
                /* CellBufferInfo.FloatsPerEntry */
              );
              if (chars === "	") {
                const offsetBefore = x + tabXOffset;
                tabXOffset = CursorColumns.nextRenderTabStop(x + tabXOffset, lineData.tabSize);
                absoluteOffsetX += charWidth * (tabXOffset - offsetBefore);
                tabXOffset -= x + 1;
              } else {
                absoluteOffsetX += charWidth;
              }
              continue;
            }
            const decorationStyleSetId = ViewGpuContext.decorationStyleCache.getOrCreateEntry(decorationStyleSetColor, decorationStyleSetBold, decorationStyleSetOpacity);
            glyph = this._viewGpuContext.atlas.getGlyph(this.glyphRasterizer, chars, tokenMetadata, decorationStyleSetId, absoluteOffsetX);
            absoluteOffsetY = Math.round(
              // Top of layout box (includes line height)
              viewportData.relativeVerticalOffset[y - viewportData.startLineNumber] * dpr + // Delta from top of layout box (includes line height) to top of the inline box (no line height)
              Math.floor((viewportData.lineHeight * dpr - (glyph.fontBoundingBoxAscent + glyph.fontBoundingBoxDescent)) / 2) + // Delta from top of inline box (no line height) to top of glyph origin. If the glyph was drawn
              // with a top baseline for example, this ends up drawing the glyph correctly using the alphabetical
              // baseline.
              glyph.fontBoundingBoxAscent
            );
            cellIndex = ((y - viewportData.startLineNumber) * _ViewportRenderStrategy.maxSupportedColumns + x) * 6;
            cellBuffer[
              cellIndex + 0
              /* CellBufferInfo.Offset_X */
            ] = Math.floor(absoluteOffsetX);
            cellBuffer[
              cellIndex + 1
              /* CellBufferInfo.Offset_Y */
            ] = absoluteOffsetY;
            cellBuffer[
              cellIndex + 4
              /* CellBufferInfo.GlyphIndex */
            ] = glyph.glyphIndex;
            cellBuffer[
              cellIndex + 5
              /* CellBufferInfo.TextureIndex */
            ] = glyph.pageIndex;
            absoluteOffsetX += charWidth;
          }
          tokenStartIndex = tokenEndIndex;
        }
        fillStartIndex = ((y - viewportData.startLineNumber) * _ViewportRenderStrategy.maxSupportedColumns + tokenEndIndex) * 6;
        fillEndIndex = (y - viewportData.startLineNumber) * _ViewportRenderStrategy.maxSupportedColumns * 6;
        cellBuffer.fill(0, fillStartIndex, fillEndIndex);
      }
      const visibleObjectCount = (viewportData.endLineNumber - viewportData.startLineNumber + 1) * lineIndexCount;
      this._device.queue.writeBuffer(this._cellBindBuffer, 0, cellBuffer.buffer, 0, (viewportData.endLineNumber - viewportData.startLineNumber) * lineIndexCount * Float32Array.BYTES_PER_ELEMENT);
      this._activeDoubleBufferIndex = this._activeDoubleBufferIndex ? 0 : 1;
      this._visibleObjectCount = visibleObjectCount;
      return visibleObjectCount;
    }
    draw(pass, viewportData) {
      if (this._visibleObjectCount <= 0) {
        throw new BugIndicatingError("Attempt to draw 0 objects");
      }
      pass.draw(quadVertices.length / 2, this._visibleObjectCount);
    }
  };
  _ViewportRenderStrategy.maxSupportedColumns = 2e3;
  let ViewportRenderStrategy = _ViewportRenderStrategy;
  function parseCssFontWeight$1(value) {
    switch (value) {
      case "lighter":
      case "normal":
        return 400;
      case "bolder":
      case "bold":
        return 700;
    }
    return parseInt(value);
  }
  function parseCssOpacity$1(value) {
    if (value.endsWith("%")) {
      return parseFloat(value.substring(0, value.length - 1)) / 100;
    }
    if (value.match(/^\d+(?:\.\d*)/)) {
      return parseFloat(value);
    }
    return 1;
  }
  const _FullFileRenderStrategy = class _FullFileRenderStrategy extends BaseRenderStrategy {
    get bindGroupEntries() {
      return [
        { binding: 1, resource: { buffer: this._cellBindBuffer } },
        { binding: 6, resource: { buffer: this._scrollOffsetBindBuffer } }
      ];
    }
    constructor(context, viewGpuContext, device, glyphRasterizer) {
      super(context, viewGpuContext, device, glyphRasterizer);
      this.type = "fullfile";
      this.wgsl = fullFileRenderStrategyWgsl;
      this._activeDoubleBufferIndex = 0;
      this._upToDateLines = [/* @__PURE__ */ new Set(), /* @__PURE__ */ new Set()];
      this._visibleObjectCount = 0;
      this._finalRenderedLine = 0;
      this._scrollInitialized = false;
      this._queuedBufferUpdates = [[], []];
      const bufferSize = _FullFileRenderStrategy.maxSupportedLines * _FullFileRenderStrategy.maxSupportedColumns * 6 * Float32Array.BYTES_PER_ELEMENT;
      this._cellBindBuffer = this._register(GPULifecycle.createBuffer(this._device, {
        label: "Monaco full file cell buffer",
        size: bufferSize,
        usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST
      })).object;
      this._cellValueBuffers = [
        new ArrayBuffer(bufferSize),
        new ArrayBuffer(bufferSize)
      ];
      const scrollOffsetBufferSize = 2;
      this._scrollOffsetBindBuffer = this._register(GPULifecycle.createBuffer(this._device, {
        label: "Monaco scroll offset buffer",
        size: scrollOffsetBufferSize * Float32Array.BYTES_PER_ELEMENT,
        usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
      })).object;
      this._scrollOffsetValueBuffer = new Float32Array(scrollOffsetBufferSize);
    }
    // #region Event handlers
    // The primary job of these handlers is to:
    // 1. Invalidate the up to date line cache, which will cause the line to be re-rendered when
    //    it's _within the viewport_.
    // 2. Pass relevant events on to the render function so it can force certain line ranges to be
    //    re-rendered even if they're not in the viewport. For example when a view zone is added,
    //    there are lines that used to be visible but are no longer, so those ranges must be
    //    cleared and uploaded to the GPU.
    onConfigurationChanged(e) {
      this._invalidateAllLines();
      this._queueBufferUpdate(e);
      return true;
    }
    onDecorationsChanged(e) {
      this._invalidateAllLines();
      return true;
    }
    onTokensChanged(e) {
      for (const range2 of e.ranges) {
        this._invalidateLineRange(range2.fromLineNumber, range2.toLineNumber);
      }
      return true;
    }
    onLinesDeleted(e) {
      this._invalidateLinesFrom(e.fromLineNumber);
      this._queueBufferUpdate(e);
      return true;
    }
    onLinesInserted(e) {
      this._invalidateLinesFrom(e.fromLineNumber);
      return true;
    }
    onLinesChanged(e) {
      this._invalidateLineRange(e.fromLineNumber, e.fromLineNumber + e.count);
      return true;
    }
    onScrollChanged(e) {
      const dpr = getActiveWindow().devicePixelRatio;
      this._scrollOffsetValueBuffer[0] = (e?.scrollLeft ?? this._context.viewLayout.getCurrentScrollLeft()) * dpr;
      this._scrollOffsetValueBuffer[1] = (e?.scrollTop ?? this._context.viewLayout.getCurrentScrollTop()) * dpr;
      this._device.queue.writeBuffer(this._scrollOffsetBindBuffer, 0, this._scrollOffsetValueBuffer);
      return true;
    }
    onThemeChanged(e) {
      this._invalidateAllLines();
      return true;
    }
    onLineMappingChanged(e) {
      this._invalidateAllLines();
      this._queueBufferUpdate(e);
      return true;
    }
    onZonesChanged(e) {
      this._invalidateAllLines();
      this._queueBufferUpdate(e);
      return true;
    }
    // #endregion
    _invalidateAllLines() {
      this._upToDateLines[0].clear();
      this._upToDateLines[1].clear();
    }
    _invalidateLinesFrom(lineNumber) {
      for (const i2 of [0, 1]) {
        const upToDateLines = this._upToDateLines[i2];
        for (const upToDateLine of upToDateLines) {
          if (upToDateLine >= lineNumber) {
            upToDateLines.delete(upToDateLine);
          }
        }
      }
    }
    _invalidateLineRange(fromLineNumber, toLineNumber) {
      for (let i2 = fromLineNumber; i2 <= toLineNumber; i2++) {
        this._upToDateLines[0].delete(i2);
        this._upToDateLines[1].delete(i2);
      }
    }
    reset() {
      this._invalidateAllLines();
      for (const bufferIndex of [0, 1]) {
        const buffer = new Float32Array(this._cellValueBuffers[bufferIndex]);
        buffer.fill(0, 0, buffer.length);
        this._device.queue.writeBuffer(this._cellBindBuffer, 0, buffer.buffer, 0, buffer.byteLength);
      }
      this._finalRenderedLine = 0;
    }
    update(viewportData, viewLineOptions) {
      let chars = "";
      let segment;
      let charWidth = 0;
      let y = 0;
      let x = 0;
      let absoluteOffsetX = 0;
      let absoluteOffsetY = 0;
      let tabXOffset = 0;
      let glyph;
      let cellIndex = 0;
      let tokenStartIndex = 0;
      let tokenEndIndex = 0;
      let tokenMetadata = 0;
      let decorationStyleSetBold;
      let decorationStyleSetColor;
      let decorationStyleSetOpacity;
      let lineData;
      let decoration2;
      let fillStartIndex = 0;
      let fillEndIndex = 0;
      let tokens;
      const dpr = getActiveWindow().devicePixelRatio;
      let contentSegmenter;
      if (!this._scrollInitialized) {
        this.onScrollChanged();
        this._scrollInitialized = true;
      }
      const cellBuffer = new Float32Array(this._cellValueBuffers[this._activeDoubleBufferIndex]);
      const lineIndexCount = _FullFileRenderStrategy.maxSupportedColumns * 6;
      const upToDateLines = this._upToDateLines[this._activeDoubleBufferIndex];
      let dirtyLineStart = 3e3;
      let dirtyLineEnd = 0;
      const queuedBufferUpdates = this._queuedBufferUpdates[this._activeDoubleBufferIndex];
      while (queuedBufferUpdates.length) {
        const e = queuedBufferUpdates.shift();
        switch (e.type) {
          // TODO: Refine these cases so we're not throwing away everything
          case 2:
          case 8:
          case 17: {
            cellBuffer.fill(0);
            dirtyLineStart = 1;
            dirtyLineEnd = Math.max(dirtyLineEnd, this._finalRenderedLine);
            this._finalRenderedLine = 0;
            break;
          }
          case 10: {
            const deletedLineContentStartIndex = (e.fromLineNumber - 1) * _FullFileRenderStrategy.maxSupportedColumns * 6;
            const deletedLineContentEndIndex = e.toLineNumber * _FullFileRenderStrategy.maxSupportedColumns * 6;
            const nullContentStartIndex = (this._finalRenderedLine - (e.toLineNumber - e.fromLineNumber + 1)) * _FullFileRenderStrategy.maxSupportedColumns * 6;
            cellBuffer.set(cellBuffer.subarray(deletedLineContentEndIndex), deletedLineContentStartIndex);
            cellBuffer.fill(0, nullContentStartIndex);
            dirtyLineStart = Math.min(dirtyLineStart, e.fromLineNumber);
            dirtyLineEnd = Math.max(dirtyLineEnd, this._finalRenderedLine);
            this._finalRenderedLine -= e.toLineNumber - e.fromLineNumber + 1;
            break;
          }
        }
      }
      for (y = viewportData.startLineNumber; y <= viewportData.endLineNumber; y++) {
        if (!this._viewGpuContext.canRender(viewLineOptions, viewportData, y)) {
          fillStartIndex = (y - 1) * _FullFileRenderStrategy.maxSupportedColumns * 6;
          fillEndIndex = y * _FullFileRenderStrategy.maxSupportedColumns * 6;
          cellBuffer.fill(0, fillStartIndex, fillEndIndex);
          dirtyLineStart = Math.min(dirtyLineStart, y);
          dirtyLineEnd = Math.max(dirtyLineEnd, y);
          continue;
        }
        if (upToDateLines.has(y)) {
          continue;
        }
        dirtyLineStart = Math.min(dirtyLineStart, y);
        dirtyLineEnd = Math.max(dirtyLineEnd, y);
        lineData = viewportData.getViewLineRenderingData(y);
        tabXOffset = 0;
        contentSegmenter = createContentSegmenter(lineData, viewLineOptions);
        charWidth = viewLineOptions.spaceWidth * dpr;
        absoluteOffsetX = 0;
        tokens = lineData.tokens;
        tokenStartIndex = lineData.minColumn - 1;
        tokenEndIndex = 0;
        for (let tokenIndex = 0, tokensLen = tokens.getCount(); tokenIndex < tokensLen; tokenIndex++) {
          tokenEndIndex = tokens.getEndOffset(tokenIndex);
          if (tokenEndIndex <= tokenStartIndex) {
            continue;
          }
          tokenMetadata = tokens.getMetadata(tokenIndex);
          for (x = tokenStartIndex; x < tokenEndIndex; x++) {
            if (x > _FullFileRenderStrategy.maxSupportedColumns) {
              break;
            }
            segment = contentSegmenter.getSegmentAtIndex(x);
            if (segment === void 0) {
              continue;
            }
            chars = segment;
            if (!(lineData.isBasicASCII && viewLineOptions.useMonospaceOptimizations)) {
              charWidth = this.glyphRasterizer.getTextMetrics(chars).width;
            }
            decorationStyleSetColor = void 0;
            decorationStyleSetBold = void 0;
            decorationStyleSetOpacity = void 0;
            for (decoration2 of lineData.inlineDecorations) {
              if (y < decoration2.range.startLineNumber || y > decoration2.range.endLineNumber || y === decoration2.range.startLineNumber && x < decoration2.range.startColumn - 1 || y === decoration2.range.endLineNumber && x >= decoration2.range.endColumn - 1) {
                continue;
              }
              const rules = ViewGpuContext.decorationCssRuleExtractor.getStyleRules(this._viewGpuContext.canvas.domNode, decoration2.inlineClassName);
              for (const rule of rules) {
                for (const r of rule.style) {
                  const value = rule.styleMap.get(r)?.toString() ?? "";
                  switch (r) {
                    case "color": {
                      const parsedColor = Color.Format.CSS.parse(value);
                      if (!parsedColor) {
                        throw new BugIndicatingError("Invalid color format " + value);
                      }
                      decorationStyleSetColor = parsedColor.toNumber32Bit();
                      break;
                    }
                    case "font-weight": {
                      const parsedValue = parseCssFontWeight(value);
                      if (parsedValue >= 400) {
                        decorationStyleSetBold = true;
                      } else {
                        decorationStyleSetBold = false;
                      }
                      break;
                    }
                    case "opacity": {
                      const parsedValue = parseCssOpacity(value);
                      decorationStyleSetOpacity = parsedValue;
                      break;
                    }
                    default:
                      throw new BugIndicatingError("Unexpected inline decoration style");
                  }
                }
              }
            }
            if (chars === " " || chars === "	") {
              cellIndex = ((y - 1) * _FullFileRenderStrategy.maxSupportedColumns + x) * 6;
              cellBuffer.fill(
                0,
                cellIndex,
                cellIndex + 6
                /* CellBufferInfo.FloatsPerEntry */
              );
              if (chars === "	") {
                const offsetBefore = x + tabXOffset;
                tabXOffset = CursorColumns.nextRenderTabStop(x + tabXOffset, lineData.tabSize);
                absoluteOffsetX += charWidth * (tabXOffset - offsetBefore);
                tabXOffset -= x + 1;
              } else {
                absoluteOffsetX += charWidth;
              }
              continue;
            }
            const decorationStyleSetId = ViewGpuContext.decorationStyleCache.getOrCreateEntry(decorationStyleSetColor, decorationStyleSetBold, decorationStyleSetOpacity);
            glyph = this._viewGpuContext.atlas.getGlyph(this.glyphRasterizer, chars, tokenMetadata, decorationStyleSetId, absoluteOffsetX);
            absoluteOffsetY = Math.round(
              // Top of layout box (includes line height)
              viewportData.relativeVerticalOffset[y - viewportData.startLineNumber] * dpr + // Delta from top of layout box (includes line height) to top of the inline box (no line height)
              Math.floor((viewportData.lineHeight * dpr - (glyph.fontBoundingBoxAscent + glyph.fontBoundingBoxDescent)) / 2) + // Delta from top of inline box (no line height) to top of glyph origin. If the glyph was drawn
              // with a top baseline for example, this ends up drawing the glyph correctly using the alphabetical
              // baseline.
              glyph.fontBoundingBoxAscent
            );
            cellIndex = ((y - 1) * _FullFileRenderStrategy.maxSupportedColumns + x) * 6;
            cellBuffer[
              cellIndex + 0
              /* CellBufferInfo.Offset_X */
            ] = Math.floor(absoluteOffsetX);
            cellBuffer[
              cellIndex + 1
              /* CellBufferInfo.Offset_Y */
            ] = absoluteOffsetY;
            cellBuffer[
              cellIndex + 4
              /* CellBufferInfo.GlyphIndex */
            ] = glyph.glyphIndex;
            cellBuffer[
              cellIndex + 5
              /* CellBufferInfo.TextureIndex */
            ] = glyph.pageIndex;
            absoluteOffsetX += charWidth;
          }
          tokenStartIndex = tokenEndIndex;
        }
        fillStartIndex = ((y - 1) * _FullFileRenderStrategy.maxSupportedColumns + tokenEndIndex) * 6;
        fillEndIndex = y * _FullFileRenderStrategy.maxSupportedColumns * 6;
        cellBuffer.fill(0, fillStartIndex, fillEndIndex);
        upToDateLines.add(y);
      }
      const visibleObjectCount = (viewportData.endLineNumber - viewportData.startLineNumber + 1) * lineIndexCount;
      dirtyLineStart = Math.min(dirtyLineStart, _FullFileRenderStrategy.maxSupportedLines);
      dirtyLineEnd = Math.min(dirtyLineEnd, _FullFileRenderStrategy.maxSupportedLines);
      if (dirtyLineStart <= dirtyLineEnd) {
        this._device.queue.writeBuffer(this._cellBindBuffer, (dirtyLineStart - 1) * lineIndexCount * Float32Array.BYTES_PER_ELEMENT, cellBuffer.buffer, (dirtyLineStart - 1) * lineIndexCount * Float32Array.BYTES_PER_ELEMENT, (dirtyLineEnd - dirtyLineStart + 1) * lineIndexCount * Float32Array.BYTES_PER_ELEMENT);
      }
      this._finalRenderedLine = Math.max(this._finalRenderedLine, dirtyLineEnd);
      this._activeDoubleBufferIndex = this._activeDoubleBufferIndex ? 0 : 1;
      this._visibleObjectCount = visibleObjectCount;
      return visibleObjectCount;
    }
    draw(pass, viewportData) {
      if (this._visibleObjectCount <= 0) {
        throw new BugIndicatingError("Attempt to draw 0 objects");
      }
      pass.draw(quadVertices.length / 2, this._visibleObjectCount, void 0, (viewportData.startLineNumber - 1) * _FullFileRenderStrategy.maxSupportedColumns);
    }
    /**
     * Queue updates that need to happen on the active buffer, not just the cache. This will be
     * deferred to when the actual cell buffer is changed since the active buffer could be locked by
     * the GPU which would block the main thread.
     */
    _queueBufferUpdate(e) {
      this._queuedBufferUpdates[0].push(e);
      this._queuedBufferUpdates[1].push(e);
    }
  };
  _FullFileRenderStrategy.maxSupportedLines = 3e3;
  _FullFileRenderStrategy.maxSupportedColumns = 200;
  let FullFileRenderStrategy = _FullFileRenderStrategy;
  function parseCssFontWeight(value) {
    switch (value) {
      case "lighter":
      case "normal":
        return 400;
      case "bolder":
      case "bold":
        return 700;
    }
    return parseInt(value);
  }
  function parseCssOpacity(value) {
    if (value.endsWith("%")) {
      return parseFloat(value.substring(0, value.length - 1)) / 100;
    }
    if (value.match(/^\d+(?:\.\d*)/)) {
      return parseFloat(value);
    }
    return 1;
  }
  var __decorate$2X = 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$2S = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  let ViewLinesGpu = class ViewLinesGpu extends ViewPart {
    constructor(context, _viewGpuContext, _instantiationService, _logService) {
      super(context);
      this._viewGpuContext = _viewGpuContext;
      this._instantiationService = _instantiationService;
      this._logService = _logService;
      this._atlasGpuTextureVersions = [];
      this._initialized = false;
      this._glyphRasterizer = this._register(new MutableDisposable());
      this._renderStrategy = this._register(new MutableDisposable());
      this.canvas = this._viewGpuContext.canvas.domNode;
      this._register(autorun((reader) => {
        this._viewGpuContext.canvasDevicePixelDimensions.read(reader);
        const lastViewportData = this._lastViewportData;
        if (lastViewportData) {
          setTimeout(() => {
            if (lastViewportData === this._lastViewportData) {
              this.renderText(lastViewportData);
            }
          });
        }
      }));
      this.initWebgpu();
    }
    async initWebgpu() {
      this._device = ViewGpuContext.deviceSync || await ViewGpuContext.device;
      if (this._store.isDisposed) {
        return;
      }
      const atlas = ViewGpuContext.atlas;
      this._register(atlas.onDidDeleteGlyphs(() => {
        this._atlasGpuTextureVersions.length = 0;
        this._atlasGpuTextureVersions[0] = 0;
        this._atlasGpuTextureVersions[1] = 0;
        this._renderStrategy.value.reset();
      }));
      const presentationFormat = navigator.gpu.getPreferredCanvasFormat();
      this._viewGpuContext.ctx.configure({
        device: this._device,
        format: presentationFormat,
        alphaMode: "premultiplied"
      });
      this._renderPassColorAttachment = {
        view: null,
        // Will be filled at render time
        loadOp: "load",
        storeOp: "store"
      };
      this._renderPassDescriptor = {
        label: "Monaco render pass",
        colorAttachments: [this._renderPassColorAttachment]
      };
      let layoutInfoUniformBuffer;
      {
        const bufferValues = new Float32Array(
          6
          /* Info.FloatsPerEntry */
        );
        const updateBufferValues = (canvasDevicePixelWidth = this.canvas.width, canvasDevicePixelHeight = this.canvas.height) => {
          bufferValues[
            0
            /* Info.Offset_CanvasWidth____ */
          ] = canvasDevicePixelWidth;
          bufferValues[
            1
            /* Info.Offset_CanvasHeight___ */
          ] = canvasDevicePixelHeight;
          bufferValues[
            2
            /* Info.Offset_ViewportOffsetX */
          ] = Math.ceil(this._context.configuration.options.get(
            165
            /* EditorOption.layoutInfo */
          ).contentLeft * getActiveWindow().devicePixelRatio);
          bufferValues[
            3
            /* Info.Offset_ViewportOffsetY */
          ] = 0;
          bufferValues[
            4
            /* Info.Offset_ViewportWidth__ */
          ] = bufferValues[
            0
            /* Info.Offset_CanvasWidth____ */
          ] - bufferValues[
            2
            /* Info.Offset_ViewportOffsetX */
          ];
          bufferValues[
            5
            /* Info.Offset_ViewportHeight_ */
          ] = bufferValues[
            1
            /* Info.Offset_CanvasHeight___ */
          ] - bufferValues[
            3
            /* Info.Offset_ViewportOffsetY */
          ];
          return bufferValues;
        };
        layoutInfoUniformBuffer = this._register(GPULifecycle.createBuffer(this._device, {
          label: "Monaco uniform buffer",
          size: 24,
          usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
        }, () => updateBufferValues())).object;
        this._register(runOnChange(this._viewGpuContext.canvasDevicePixelDimensions, ({ width: width2, height }) => {
          this._device.queue.writeBuffer(layoutInfoUniformBuffer, 0, updateBufferValues(width2, height));
        }));
        this._register(runOnChange(this._viewGpuContext.contentLeft, () => {
          this._device.queue.writeBuffer(layoutInfoUniformBuffer, 0, updateBufferValues());
        }));
      }
      let atlasInfoUniformBuffer;
      {
        atlasInfoUniformBuffer = this._register(GPULifecycle.createBuffer(this._device, {
          label: "Monaco atlas info uniform buffer",
          size: 8,
          usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
        }, () => {
          const values = new Float32Array(
            2
            /* Info.FloatsPerEntry */
          );
          values[
            0
            /* Info.Offset_Width_ */
          ] = atlas.pageSize;
          values[
            1
            /* Info.Offset_Height */
          ] = atlas.pageSize;
          return values;
        })).object;
      }
      const fontFamily = this._context.configuration.options.get(
        58
        /* EditorOption.fontFamily */
      );
      const fontSize = this._context.configuration.options.get(
        61
        /* EditorOption.fontSize */
      );
      this._glyphRasterizer.value = this._register(new GlyphRasterizer(fontSize, fontFamily, this._viewGpuContext.devicePixelRatio.get(), ViewGpuContext.decorationStyleCache));
      this._register(runOnChange(this._viewGpuContext.devicePixelRatio, () => {
        this._refreshGlyphRasterizer();
      }));
      this._renderStrategy.value = this._instantiationService.createInstance(FullFileRenderStrategy, this._context, this._viewGpuContext, this._device, this._glyphRasterizer);
      this._glyphStorageBuffer = this._register(GPULifecycle.createBuffer(this._device, {
        label: "Monaco glyph storage buffer",
        size: TextureAtlas.maximumPageCount * (TextureAtlasPage.maximumGlyphCount * 24),
        usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST
      })).object;
      this._atlasGpuTextureVersions[0] = 0;
      this._atlasGpuTextureVersions[1] = 0;
      this._atlasGpuTexture = this._register(GPULifecycle.createTexture(this._device, {
        label: "Monaco atlas texture",
        format: "rgba8unorm",
        size: { width: atlas.pageSize, height: atlas.pageSize, depthOrArrayLayers: TextureAtlas.maximumPageCount },
        dimension: "2d",
        usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.RENDER_ATTACHMENT
      })).object;
      this._updateAtlasStorageBufferAndTexture();
      this._vertexBuffer = this._register(GPULifecycle.createBuffer(this._device, {
        label: "Monaco vertex buffer",
        size: quadVertices.byteLength,
        usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST
      }, quadVertices)).object;
      const module = this._device.createShaderModule({
        label: "Monaco shader module",
        code: this._renderStrategy.value.wgsl
      });
      this._pipeline = this._device.createRenderPipeline({
        label: "Monaco render pipeline",
        layout: "auto",
        vertex: {
          module,
          buffers: [
            {
              arrayStride: 2 * Float32Array.BYTES_PER_ELEMENT,
              // 2 floats, 4 bytes each
              attributes: [
                { shaderLocation: 0, offset: 0, format: "float32x2" }
                // position
              ]
            }
          ]
        },
        fragment: {
          module,
          targets: [
            {
              format: presentationFormat,
              blend: {
                color: {
                  srcFactor: "src-alpha",
                  dstFactor: "one-minus-src-alpha"
                },
                alpha: {
                  srcFactor: "src-alpha",
                  dstFactor: "one-minus-src-alpha"
                }
              }
            }
          ]
        }
      });
      this._rebuildBindGroup = () => {
        this._bindGroup = this._device.createBindGroup({
          label: "Monaco bind group",
          layout: this._pipeline.getBindGroupLayout(0),
          entries: [
            // TODO: Pass in generically as array?
            { binding: 0, resource: { buffer: this._glyphStorageBuffer } },
            {
              binding: 2,
              resource: this._device.createSampler({
                label: "Monaco atlas sampler",
                magFilter: "nearest",
                minFilter: "nearest"
              })
            },
            { binding: 3, resource: this._atlasGpuTexture.createView() },
            { binding: 4, resource: { buffer: layoutInfoUniformBuffer } },
            { binding: 5, resource: { buffer: atlasInfoUniformBuffer } },
            ...this._renderStrategy.value.bindGroupEntries
          ]
        });
      };
      this._rebuildBindGroup();
      this._initialized = true;
      if (this._initViewportData) {
        for (const viewportData of this._initViewportData) {
          this.renderText(viewportData);
        }
        this._initViewportData = void 0;
      }
    }
    _refreshRenderStrategy(viewportData) {
      if (this._renderStrategy.value?.type === "viewport") {
        return;
      }
      if (viewportData.endLineNumber < FullFileRenderStrategy.maxSupportedLines && this._viewportMaxColumn(viewportData) < FullFileRenderStrategy.maxSupportedColumns) {
        return;
      }
      this._logService.trace(`File is larger than ${FullFileRenderStrategy.maxSupportedLines} lines or ${FullFileRenderStrategy.maxSupportedColumns} columns, switching to viewport render strategy`);
      const viewportRenderStrategy = this._instantiationService.createInstance(ViewportRenderStrategy, this._context, this._viewGpuContext, this._device, this._glyphRasterizer);
      this._renderStrategy.value = viewportRenderStrategy;
      this._register(viewportRenderStrategy.onDidChangeBindGroupEntries(() => this._rebuildBindGroup?.()));
      this._rebuildBindGroup?.();
    }
    _viewportMaxColumn(viewportData) {
      let maxColumn = 0;
      let lineData;
      for (let i2 = viewportData.startLineNumber; i2 <= viewportData.endLineNumber; i2++) {
        lineData = viewportData.getViewLineRenderingData(i2);
        maxColumn = Math.max(maxColumn, lineData.maxColumn);
      }
      return maxColumn;
    }
    _updateAtlasStorageBufferAndTexture() {
      for (const [layerIndex, page] of ViewGpuContext.atlas.pages.entries()) {
        if (layerIndex >= TextureAtlas.maximumPageCount) {
          console.log(`Attempt to upload atlas page [${layerIndex}], only ${TextureAtlas.maximumPageCount} are supported currently`);
          continue;
        }
        if (page.version === this._atlasGpuTextureVersions[layerIndex]) {
          continue;
        }
        this._logService.trace("Updating atlas page[", layerIndex, "] from version ", this._atlasGpuTextureVersions[layerIndex], " to version ", page.version);
        const entryCount = 6 * TextureAtlasPage.maximumGlyphCount;
        const values = new Float32Array(entryCount);
        let entryOffset = 0;
        for (const glyph of page.glyphs) {
          values[
            entryOffset + 0
            /* GlyphStorageBufferInfo.Offset_TexturePosition */
          ] = glyph.x;
          values[entryOffset + 0 + 1] = glyph.y;
          values[
            entryOffset + 2
            /* GlyphStorageBufferInfo.Offset_TextureSize */
          ] = glyph.w;
          values[entryOffset + 2 + 1] = glyph.h;
          values[
            entryOffset + 4
            /* GlyphStorageBufferInfo.Offset_OriginPosition */
          ] = glyph.originOffsetX;
          values[entryOffset + 4 + 1] = glyph.originOffsetY;
          entryOffset += 6;
        }
        if (entryOffset / 6 > TextureAtlasPage.maximumGlyphCount) {
          throw new Error(`Attempting to write more glyphs (${entryOffset / 6}) than the GPUBuffer can hold (${TextureAtlasPage.maximumGlyphCount})`);
        }
        this._device.queue.writeBuffer(this._glyphStorageBuffer, layerIndex * 6 * TextureAtlasPage.maximumGlyphCount * Float32Array.BYTES_PER_ELEMENT, values, 0, 6 * TextureAtlasPage.maximumGlyphCount);
        if (page.usedArea.right - page.usedArea.left > 0 && page.usedArea.bottom - page.usedArea.top > 0) {
          this._device.queue.copyExternalImageToTexture({ source: page.source }, {
            texture: this._atlasGpuTexture,
            origin: {
              x: page.usedArea.left,
              y: page.usedArea.top,
              z: layerIndex
            }
          }, {
            width: page.usedArea.right - page.usedArea.left + 1,
            height: page.usedArea.bottom - page.usedArea.top + 1
          });
        }
        this._atlasGpuTextureVersions[layerIndex] = page.version;
      }
    }
    prepareRender(ctx) {
      throw new BugIndicatingError("Should not be called");
    }
    render(ctx) {
      throw new BugIndicatingError("Should not be called");
    }
    // #region Event handlers
    // Since ViewLinesGpu currently coordinates rendering to the canvas, it must listen to all
    // changed events that any GPU part listens to. This is because any drawing to the canvas will
    // clear it for that frame, so all parts must be rendered every time.
    //
    // Additionally, since this is intrinsically linked to ViewLines, it must also listen to events
    // from that side. Luckily rendering is cheap, it's only when uploaded data changes does it
    // start to cost.
    onConfigurationChanged(e) {
      this._refreshGlyphRasterizer();
      return true;
    }
    onCursorStateChanged(e) {
      return true;
    }
    onDecorationsChanged(e) {
      return true;
    }
    onFlushed(e) {
      return true;
    }
    onLinesChanged(e) {
      return true;
    }
    onLinesDeleted(e) {
      return true;
    }
    onLinesInserted(e) {
      return true;
    }
    onLineMappingChanged(e) {
      return true;
    }
    onRevealRangeRequest(e) {
      return true;
    }
    onScrollChanged(e) {
      return true;
    }
    onThemeChanged(e) {
      return true;
    }
    onZonesChanged(e) {
      return true;
    }
    // #endregion
    _refreshGlyphRasterizer() {
      const glyphRasterizer = this._glyphRasterizer.value;
      if (!glyphRasterizer) {
        return;
      }
      const fontFamily = this._context.configuration.options.get(
        58
        /* EditorOption.fontFamily */
      );
      const fontSize = this._context.configuration.options.get(
        61
        /* EditorOption.fontSize */
      );
      const devicePixelRatio = this._viewGpuContext.devicePixelRatio.get();
      if (glyphRasterizer.fontFamily !== fontFamily || glyphRasterizer.fontSize !== fontSize || glyphRasterizer.devicePixelRatio !== devicePixelRatio) {
        this._glyphRasterizer.value = new GlyphRasterizer(fontSize, fontFamily, devicePixelRatio, ViewGpuContext.decorationStyleCache);
      }
    }
    renderText(viewportData) {
      if (this._initialized) {
        this._refreshRenderStrategy(viewportData);
        return this._renderText(viewportData);
      } else {
        this._initViewportData = this._initViewportData ?? [];
        this._initViewportData.push(viewportData);
      }
    }
    _renderText(viewportData) {
      this._viewGpuContext.rectangleRenderer.draw(viewportData);
      const options = new ViewLineOptions(this._context.configuration, this._context.theme.type);
      this._renderStrategy.value.update(viewportData, options);
      this._updateAtlasStorageBufferAndTexture();
      const encoder = this._device.createCommandEncoder({ label: "Monaco command encoder" });
      this._renderPassColorAttachment.view = this._viewGpuContext.ctx.getCurrentTexture().createView({ label: "Monaco canvas texture view" });
      const pass = encoder.beginRenderPass(this._renderPassDescriptor);
      pass.setPipeline(this._pipeline);
      pass.setVertexBuffer(0, this._vertexBuffer);
      const contentLeft = Math.ceil(this._viewGpuContext.contentLeft.get() * this._viewGpuContext.devicePixelRatio.get());
      pass.setScissorRect(contentLeft, 0, this.canvas.width - contentLeft, this.canvas.height);
      pass.setBindGroup(0, this._bindGroup);
      this._renderStrategy.value.draw(pass, viewportData);
      pass.end();
      const commandBuffer = encoder.finish();
      this._device.queue.submit([commandBuffer]);
      this._lastViewportData = viewportData;
      this._lastViewLineOptions = options;
    }
    linesVisibleRangesForRange(_range, includeNewLines) {
      if (!this._lastViewportData) {
        return null;
      }
      const originalEndLineNumber = _range.endLineNumber;
      const range2 = Range$2.intersectRanges(_range, this._lastViewportData.visibleRange);
      if (!range2) {
        return null;
      }
      const rendStartLineNumber = this._lastViewportData.startLineNumber;
      const rendEndLineNumber = this._lastViewportData.endLineNumber;
      const viewportData = this._lastViewportData;
      const viewLineOptions = this._lastViewLineOptions;
      if (!viewportData || !viewLineOptions) {
        return null;
      }
      const visibleRanges = [];
      let nextLineModelLineNumber = 0;
      if (includeNewLines) {
        nextLineModelLineNumber = this._context.viewModel.coordinatesConverter.convertViewPositionToModelPosition(new Position$1(range2.startLineNumber, 1)).lineNumber;
      }
      for (let lineNumber = range2.startLineNumber; lineNumber <= range2.endLineNumber; lineNumber++) {
        if (lineNumber < rendStartLineNumber || lineNumber > rendEndLineNumber) {
          continue;
        }
        const startColumn = lineNumber === range2.startLineNumber ? range2.startColumn : 1;
        const continuesInNextLine = lineNumber !== originalEndLineNumber;
        const endColumn = continuesInNextLine ? this._context.viewModel.getLineMaxColumn(lineNumber) : range2.endColumn;
        const visibleRangesForLine = this._visibleRangesForLineRange(lineNumber, startColumn, endColumn);
        if (!visibleRangesForLine) {
          continue;
        }
        if (includeNewLines && lineNumber < originalEndLineNumber) {
          const currentLineModelLineNumber = nextLineModelLineNumber;
          nextLineModelLineNumber = this._context.viewModel.coordinatesConverter.convertViewPositionToModelPosition(new Position$1(lineNumber + 1, 1)).lineNumber;
          if (currentLineModelLineNumber !== nextLineModelLineNumber) {
            visibleRangesForLine.ranges[visibleRangesForLine.ranges.length - 1].width += viewLineOptions.spaceWidth;
          }
        }
        visibleRanges.push(new LineVisibleRanges(visibleRangesForLine.outsideRenderedLine, lineNumber, HorizontalRange.from(visibleRangesForLine.ranges), continuesInNextLine));
      }
      if (visibleRanges.length === 0) {
        return null;
      }
      return visibleRanges;
    }
    _visibleRangesForLineRange(lineNumber, startColumn, endColumn) {
      if (this.shouldRender()) {
        return null;
      }
      const viewportData = this._lastViewportData;
      const viewLineOptions = this._lastViewLineOptions;
      if (!viewportData || !viewLineOptions || lineNumber < viewportData.startLineNumber || lineNumber > viewportData.endLineNumber) {
        return null;
      }
      const lineData = viewportData.getViewLineRenderingData(lineNumber);
      const content = lineData.content;
      let contentSegmenter;
      if (!(lineData.isBasicASCII && viewLineOptions.useMonospaceOptimizations)) {
        contentSegmenter = createContentSegmenter(lineData, viewLineOptions);
      }
      let chars = "";
      let resolvedStartColumn = 0;
      let resolvedStartCssPixelOffset = 0;
      for (let x = 0; x < startColumn - 1; x++) {
        if (lineData.isBasicASCII && viewLineOptions.useMonospaceOptimizations) {
          chars = content.charAt(x);
        } else {
          chars = contentSegmenter.getSegmentAtIndex(x);
          if (chars === void 0) {
            continue;
          }
          resolvedStartCssPixelOffset += this._renderStrategy.value.glyphRasterizer.getTextMetrics(chars).width / getActiveWindow().devicePixelRatio - viewLineOptions.spaceWidth;
        }
        if (chars === "	") {
          resolvedStartColumn = CursorColumns.nextRenderTabStop(resolvedStartColumn, lineData.tabSize);
        } else {
          resolvedStartColumn++;
        }
      }
      let resolvedEndColumn = resolvedStartColumn;
      let resolvedEndCssPixelOffset = 0;
      for (let x = startColumn - 1; x < endColumn - 1; x++) {
        if (lineData.isBasicASCII && viewLineOptions.useMonospaceOptimizations) {
          chars = content.charAt(x);
        } else {
          chars = contentSegmenter.getSegmentAtIndex(x);
          if (chars === void 0) {
            continue;
          }
          resolvedEndCssPixelOffset += this._renderStrategy.value.glyphRasterizer.getTextMetrics(chars).width / getActiveWindow().devicePixelRatio - viewLineOptions.spaceWidth;
        }
        if (chars === "	") {
          resolvedEndColumn = CursorColumns.nextRenderTabStop(resolvedEndColumn, lineData.tabSize);
        } else {
          resolvedEndColumn++;
        }
      }
      const result = new VisibleRanges(false, [
        new FloatHorizontalRange(resolvedStartColumn * viewLineOptions.spaceWidth + resolvedStartCssPixelOffset, (resolvedEndColumn - resolvedStartColumn) * viewLineOptions.spaceWidth + resolvedEndCssPixelOffset)
      ]);
      return result;
    }
    visibleRangeForPosition(position) {
      const visibleRanges = this._visibleRangesForLineRange(position.lineNumber, position.column, position.column);
      if (!visibleRanges) {
        return null;
      }
      return new HorizontalPosition(visibleRanges.outsideRenderedLine, visibleRanges.ranges[0].left);
    }
    getLineWidth(lineNumber) {
      if (!this._lastViewportData || !this._lastViewLineOptions) {
        return void 0;
      }
      if (!this._viewGpuContext.canRender(this._lastViewLineOptions, this._lastViewportData, lineNumber)) {
        return void 0;
      }
      const lineData = this._lastViewportData.getViewLineRenderingData(lineNumber);
      const lineRange = this._visibleRangesForLineRange(lineNumber, 1, lineData.maxColumn);
      const lastRange = lineRange?.ranges.at(-1);
      if (lastRange) {
        return lastRange.width;
      }
      return void 0;
    }
    getPositionAtCoordinate(lineNumber, mouseContentHorizontalOffset) {
      if (!this._lastViewportData || !this._lastViewLineOptions) {
        return void 0;
      }
      if (!this._viewGpuContext.canRender(this._lastViewLineOptions, this._lastViewportData, lineNumber)) {
        return void 0;
      }
      const lineData = this._lastViewportData.getViewLineRenderingData(lineNumber);
      const content = lineData.content;
      const dpr = getActiveWindow().devicePixelRatio;
      const mouseContentHorizontalOffsetDevicePixels = mouseContentHorizontalOffset * dpr;
      const spaceWidthDevicePixels = this._lastViewLineOptions.spaceWidth * dpr;
      const contentSegmenter = createContentSegmenter(lineData, this._lastViewLineOptions);
      let widthSoFar = 0;
      let charWidth = 0;
      let tabXOffset = 0;
      let column = 0;
      for (let x = 0; x < content.length; x++) {
        const chars = contentSegmenter.getSegmentAtIndex(x);
        if (chars === void 0) {
          column++;
          continue;
        }
        if (chars === "	") {
          const offsetBefore = x + tabXOffset;
          tabXOffset = CursorColumns.nextRenderTabStop(x + tabXOffset, lineData.tabSize);
          charWidth = spaceWidthDevicePixels * (tabXOffset - offsetBefore);
          tabXOffset -= x + 1;
        } else if (lineData.isBasicASCII && this._lastViewLineOptions.useMonospaceOptimizations) {
          charWidth = spaceWidthDevicePixels;
        } else {
          charWidth = this._renderStrategy.value.glyphRasterizer.getTextMetrics(chars).width;
        }
        if (mouseContentHorizontalOffsetDevicePixels < widthSoFar + charWidth / 2) {
          break;
        }
        widthSoFar += charWidth;
        column++;
      }
      return new Position$1(lineNumber, column + 1);
    }
  };
  ViewLinesGpu = __decorate$2X([
    __param$2S(2, IInstantiationService),
    __param$2S(3, ILogService)
  ], ViewLinesGpu);
  class IMEImpl {
    constructor() {
      this._onDidChange = new Emitter$1();
      this.onDidChange = this._onDidChange.event;
      this._enabled = true;
    }
    get enabled() {
      return this._enabled;
    }
    /**
     * Enable IME
     */
    enable() {
      this._enabled = true;
      this._onDidChange.fire();
    }
    /**
     * Disable IME
     */
    disable() {
      this._enabled = false;
      this._onDidChange.fire();
    }
  }
  const IME = new IMEImpl();
  const IKeybindingService = createDecorator("keybindingService");
  class AbstractEditContext extends ViewPart {
  }
  class SimplePagedScreenReaderStrategy {
    _getPageOfLine(lineNumber, linesPerPage) {
      return Math.floor((lineNumber - 1) / linesPerPage);
    }
    _getRangeForPage(page, linesPerPage) {
      const offset = page * linesPerPage;
      const startLineNumber = offset + 1;
      const endLineNumber = offset + linesPerPage;
      return new Range$2(startLineNumber, 1, endLineNumber + 1, 1);
    }
    fromEditorSelection(model, selection, linesPerPage, trimLongText) {
      const LIMIT_CHARS = 500;
      const selectionStartPage = this._getPageOfLine(selection.startLineNumber, linesPerPage);
      const selectionStartPageRange = this._getRangeForPage(selectionStartPage, linesPerPage);
      const selectionEndPage = this._getPageOfLine(selection.endLineNumber, linesPerPage);
      const selectionEndPageRange = this._getRangeForPage(selectionEndPage, linesPerPage);
      let pretextRange = selectionStartPageRange.intersectRanges(new Range$2(1, 1, selection.startLineNumber, selection.startColumn));
      if (trimLongText && model.getValueLengthInRange(
        pretextRange,
        1
        /* EndOfLinePreference.LF */
      ) > LIMIT_CHARS) {
        const pretextStart = model.modifyPosition(pretextRange.getEndPosition(), -LIMIT_CHARS);
        pretextRange = Range$2.fromPositions(pretextStart, pretextRange.getEndPosition());
      }
      const pretext = model.getValueInRange(
        pretextRange,
        1
        /* EndOfLinePreference.LF */
      );
      const lastLine = model.getLineCount();
      const lastLineMaxColumn = model.getLineMaxColumn(lastLine);
      let posttextRange = selectionEndPageRange.intersectRanges(new Range$2(selection.endLineNumber, selection.endColumn, lastLine, lastLineMaxColumn));
      if (trimLongText && model.getValueLengthInRange(
        posttextRange,
        1
        /* EndOfLinePreference.LF */
      ) > LIMIT_CHARS) {
        const posttextEnd = model.modifyPosition(posttextRange.getStartPosition(), LIMIT_CHARS);
        posttextRange = Range$2.fromPositions(posttextRange.getStartPosition(), posttextEnd);
      }
      const posttext = model.getValueInRange(
        posttextRange,
        1
        /* EndOfLinePreference.LF */
      );
      let text2;
      if (selectionStartPage === selectionEndPage || selectionStartPage + 1 === selectionEndPage) {
        text2 = model.getValueInRange(
          selection,
          1
          /* EndOfLinePreference.LF */
        );
      } else {
        const selectionRange1 = selectionStartPageRange.intersectRanges(selection);
        const selectionRange2 = selectionEndPageRange.intersectRanges(selection);
        text2 = model.getValueInRange(
          selectionRange1,
          1
          /* EndOfLinePreference.LF */
        ) + String.fromCharCode(8230) + model.getValueInRange(
          selectionRange2,
          1
          /* EndOfLinePreference.LF */
        );
      }
      if (trimLongText && text2.length > 2 * LIMIT_CHARS) {
        text2 = text2.substring(0, LIMIT_CHARS) + String.fromCharCode(8230) + text2.substring(text2.length - LIMIT_CHARS, text2.length);
      }
      let selectionStart;
      let selectionEnd;
      if (selection.getDirection() === 0) {
        selectionStart = pretext.length;
        selectionEnd = pretext.length + text2.length;
      } else {
        selectionEnd = pretext.length;
        selectionStart = pretext.length + text2.length;
      }
      return {
        value: pretext + text2 + posttext,
        selection,
        selectionStart,
        selectionEnd,
        startPositionWithinEditor: pretextRange.getStartPosition(),
        newlineCountBeforeSelection: pretextRange.endLineNumber - pretextRange.startLineNumber
      };
    }
  }
  function ariaLabelForScreenReaderContent(options, keybindingService) {
    const accessibilitySupport = options.get(
      2
      /* EditorOption.accessibilitySupport */
    );
    if (accessibilitySupport === 1) {
      const toggleKeybindingLabel = keybindingService.lookupKeybinding("editor.action.toggleScreenReaderAccessibilityMode")?.getAriaLabel();
      const runCommandKeybindingLabel = keybindingService.lookupKeybinding("workbench.action.showCommands")?.getAriaLabel();
      const keybindingEditorKeybindingLabel = keybindingService.lookupKeybinding("workbench.action.openGlobalKeybindings")?.getAriaLabel();
      const editorNotAccessibleMessage = localize(61, "The editor is not accessible at this time.");
      if (toggleKeybindingLabel) {
        return localize(62, "{0} To enable screen reader optimized mode, use {1}", editorNotAccessibleMessage, toggleKeybindingLabel);
      } else if (runCommandKeybindingLabel) {
        return localize(63, "{0} To enable screen reader optimized mode, open the quick pick with {1} and run the command Toggle Screen Reader Accessibility Mode, which is currently not triggerable via keyboard.", editorNotAccessibleMessage, runCommandKeybindingLabel);
      } else if (keybindingEditorKeybindingLabel) {
        return localize(64, "{0} Please assign a keybinding for the command Toggle Screen Reader Accessibility Mode by accessing the keybindings editor with {1} and run it.", editorNotAccessibleMessage, keybindingEditorKeybindingLabel);
      } else {
        return editorNotAccessibleMessage;
      }
    }
    return options.get(
      8
      /* EditorOption.ariaLabel */
    );
  }
  function newlinecount(text2) {
    let result = 0;
    let startIndex = -1;
    do {
      startIndex = text2.indexOf("\n", startIndex + 1);
      if (startIndex === -1) {
        break;
      }
      result++;
    } while (true);
    return result;
  }
  var __decorate$2W = 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$2R = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  class VisibleTextAreaData {
    constructor(_context, modelLineNumber, distanceToModelLineStart, widthOfHiddenLineTextBefore, distanceToModelLineEnd) {
      this._context = _context;
      this.modelLineNumber = modelLineNumber;
      this.distanceToModelLineStart = distanceToModelLineStart;
      this.widthOfHiddenLineTextBefore = widthOfHiddenLineTextBefore;
      this.distanceToModelLineEnd = distanceToModelLineEnd;
      this._visibleTextAreaBrand = void 0;
      this.startPosition = null;
      this.endPosition = null;
      this.visibleTextareaStart = null;
      this.visibleTextareaEnd = null;
      this._previousPresentation = null;
    }
    prepareRender(visibleRangeProvider) {
      const startModelPosition = new Position$1(this.modelLineNumber, this.distanceToModelLineStart + 1);
      const endModelPosition = new Position$1(this.modelLineNumber, this._context.viewModel.model.getLineMaxColumn(this.modelLineNumber) - this.distanceToModelLineEnd);
      this.startPosition = this._context.viewModel.coordinatesConverter.convertModelPositionToViewPosition(startModelPosition);
      this.endPosition = this._context.viewModel.coordinatesConverter.convertModelPositionToViewPosition(endModelPosition);
      if (this.startPosition.lineNumber === this.endPosition.lineNumber) {
        this.visibleTextareaStart = visibleRangeProvider.visibleRangeForPosition(this.startPosition);
        this.visibleTextareaEnd = visibleRangeProvider.visibleRangeForPosition(this.endPosition);
      } else {
        this.visibleTextareaStart = null;
        this.visibleTextareaEnd = null;
      }
    }
    definePresentation(tokenPresentation) {
      if (!this._previousPresentation) {
        if (tokenPresentation) {
          this._previousPresentation = tokenPresentation;
        } else {
          this._previousPresentation = {
            foreground: 1,
            italic: false,
            bold: false,
            underline: false,
            strikethrough: false
          };
        }
      }
      return this._previousPresentation;
    }
  }
  const canUseZeroSizeTextarea = isFirefox$1;
  let TextAreaEditContext = class TextAreaEditContext extends AbstractEditContext {
    constructor(context, overflowGuardContainer, viewController, visibleRangeProvider, _keybindingService, _instantiationService) {
      super(context);
      this._keybindingService = _keybindingService;
      this._instantiationService = _instantiationService;
      this._primaryCursorPosition = new Position$1(1, 1);
      this._primaryCursorVisibleRange = null;
      this._viewController = viewController;
      this._visibleRangeProvider = visibleRangeProvider;
      this._scrollLeft = 0;
      this._scrollTop = 0;
      const options = this._context.configuration.options;
      const layoutInfo = options.get(
        165
        /* EditorOption.layoutInfo */
      );
      this._setAccessibilityOptions(options);
      this._contentLeft = layoutInfo.contentLeft;
      this._contentWidth = layoutInfo.contentWidth;
      this._contentHeight = layoutInfo.height;
      this._fontInfo = options.get(
        59
        /* EditorOption.fontInfo */
      );
      this._emptySelectionClipboard = options.get(
        45
        /* EditorOption.emptySelectionClipboard */
      );
      this._copyWithSyntaxHighlighting = options.get(
        31
        /* EditorOption.copyWithSyntaxHighlighting */
      );
      this._visibleTextArea = null;
      this._selections = [new Selection$1(1, 1, 1, 1)];
      this._modelSelections = [new Selection$1(1, 1, 1, 1)];
      this._lastRenderPosition = null;
      this.textArea = createFastDomNode(document.createElement("textarea"));
      PartFingerprints.write(
        this.textArea,
        7
        /* PartFingerprint.TextArea */
      );
      this.textArea.setClassName(`inputarea ${MOUSE_CURSOR_TEXT_CSS_CLASS_NAME}`);
      this.textArea.setAttribute("wrap", this._textAreaWrapping && !this._visibleTextArea ? "on" : "off");
      const { tabSize } = this._context.viewModel.model.getOptions();
      this.textArea.domNode.style.tabSize = `${tabSize * this._fontInfo.spaceWidth}px`;
      this.textArea.setAttribute("autocorrect", "off");
      this.textArea.setAttribute("autocapitalize", "off");
      this.textArea.setAttribute("autocomplete", "off");
      this.textArea.setAttribute("spellcheck", "false");
      this.textArea.setAttribute("aria-label", ariaLabelForScreenReaderContent(options, this._keybindingService));
      this.textArea.setAttribute("aria-required", options.get(
        9
        /* EditorOption.ariaRequired */
      ) ? "true" : "false");
      this.textArea.setAttribute("tabindex", String(options.get(
        140
        /* EditorOption.tabIndex */
      )));
      this.textArea.setAttribute("role", "textbox");
      this.textArea.setAttribute("aria-roledescription", localize(65, "editor"));
      this.textArea.setAttribute("aria-multiline", "true");
      this.textArea.setAttribute("aria-autocomplete", options.get(
        104
        /* EditorOption.readOnly */
      ) ? "none" : "both");
      this._ensureReadOnlyAttribute();
      this.textAreaCover = createFastDomNode(document.createElement("div"));
      this.textAreaCover.setPosition("absolute");
      overflowGuardContainer.appendChild(this.textArea);
      overflowGuardContainer.appendChild(this.textAreaCover);
      const simplePagedScreenReaderStrategy = new SimplePagedScreenReaderStrategy();
      const textAreaInputHost = {
        getDataToCopy: () => {
          return getDataToCopy(this._context.viewModel, this._modelSelections, this._emptySelectionClipboard, this._copyWithSyntaxHighlighting);
        },
        getScreenReaderContent: () => {
          if (this._accessibilitySupport === 1) {
            const selection = this._selections[0];
            if (isMacintosh && selection.isEmpty()) {
              const position = selection.getStartPosition();
              let textBefore = this._getWordBeforePosition(position);
              if (textBefore.length === 0) {
                textBefore = this._getCharacterBeforePosition(position);
              }
              if (textBefore.length > 0) {
                return new TextAreaState(textBefore, textBefore.length, textBefore.length, Range$2.fromPositions(position), 0);
              }
            }
            const LIMIT_CHARS = 500;
            if (isMacintosh && !selection.isEmpty() && this._context.viewModel.getValueLengthInRange(
              selection,
              0
              /* EndOfLinePreference.TextDefined */
            ) < LIMIT_CHARS) {
              const text2 = this._context.viewModel.getValueInRange(
                selection,
                0
                /* EndOfLinePreference.TextDefined */
              );
              return new TextAreaState(text2, 0, text2.length, selection, 0);
            }
            if (isSafari$1 && !selection.isEmpty()) {
              const placeholderText = "vscode-placeholder";
              return new TextAreaState(placeholderText, 0, placeholderText.length, null, void 0);
            }
            return TextAreaState.EMPTY;
          }
          if (isAndroid$1) {
            const selection = this._selections[0];
            if (selection.isEmpty()) {
              const position = selection.getStartPosition();
              const [wordAtPosition, positionOffsetInWord] = this._getAndroidWordAtPosition(position);
              if (wordAtPosition.length > 0) {
                return new TextAreaState(wordAtPosition, positionOffsetInWord, positionOffsetInWord, Range$2.fromPositions(position), 0);
              }
            }
            return TextAreaState.EMPTY;
          }
          const screenReaderContentState = simplePagedScreenReaderStrategy.fromEditorSelection(
            this._context.viewModel,
            this._selections[0],
            this._accessibilityPageSize,
            this._accessibilitySupport === 0
            /* AccessibilitySupport.Unknown */
          );
          return TextAreaState.fromScreenReaderContentState(screenReaderContentState);
        },
        deduceModelPosition: (viewAnchorPosition, deltaOffset, lineFeedCnt) => {
          return this._context.viewModel.deduceModelPositionRelativeToViewPosition(viewAnchorPosition, deltaOffset, lineFeedCnt);
        }
      };
      const textAreaWrapper = this._register(new TextAreaWrapper(this.textArea.domNode));
      this._textAreaInput = this._register(this._instantiationService.createInstance(TextAreaInput, textAreaInputHost, textAreaWrapper, OS, {
        isAndroid: isAndroid$1,
        isChrome: isChrome$1,
        isFirefox: isFirefox$1,
        isSafari: isSafari$1
      }));
      this._register(this._textAreaInput.onKeyDown((e) => {
        this._viewController.emitKeyDown(e);
      }));
      this._register(this._textAreaInput.onKeyUp((e) => {
        this._viewController.emitKeyUp(e);
      }));
      this._register(this._textAreaInput.onPaste((e) => {
        let pasteOnNewLine = false;
        let multicursorText = null;
        let mode = null;
        if (e.metadata) {
          pasteOnNewLine = this._emptySelectionClipboard && !!e.metadata.isFromEmptySelection;
          multicursorText = typeof e.metadata.multicursorText !== "undefined" ? e.metadata.multicursorText : null;
          mode = e.metadata.mode;
        }
        this._viewController.paste(e.text, pasteOnNewLine, multicursorText, mode);
      }));
      this._register(this._textAreaInput.onCut(() => {
        this._viewController.cut();
      }));
      this._register(this._textAreaInput.onType((e) => {
        if (e.replacePrevCharCnt || e.replaceNextCharCnt || e.positionDelta) {
          this._viewController.compositionType(e.text, e.replacePrevCharCnt, e.replaceNextCharCnt, e.positionDelta);
        } else {
          this._viewController.type(e.text);
        }
      }));
      this._register(this._textAreaInput.onSelectionChangeRequest((modelSelection) => {
        this._viewController.setSelection(modelSelection);
      }));
      this._register(this._textAreaInput.onCompositionStart((e) => {
        const ta = this.textArea.domNode;
        const modelSelection = this._modelSelections[0];
        const { distanceToModelLineStart, widthOfHiddenTextBefore } = (() => {
          const textBeforeSelection = ta.value.substring(0, Math.min(ta.selectionStart, ta.selectionEnd));
          const lineFeedOffset1 = textBeforeSelection.lastIndexOf("\n");
          const lineTextBeforeSelection = textBeforeSelection.substring(lineFeedOffset1 + 1);
          const tabOffset1 = lineTextBeforeSelection.lastIndexOf("	");
          const desiredVisibleBeforeCharCount = lineTextBeforeSelection.length - tabOffset1 - 1;
          const startModelPosition = modelSelection.getStartPosition();
          const visibleBeforeCharCount = Math.min(startModelPosition.column - 1, desiredVisibleBeforeCharCount);
          const distanceToModelLineStart2 = startModelPosition.column - 1 - visibleBeforeCharCount;
          const hiddenLineTextBefore = lineTextBeforeSelection.substring(0, lineTextBeforeSelection.length - visibleBeforeCharCount);
          const { tabSize: tabSize2 } = this._context.viewModel.model.getOptions();
          const widthOfHiddenTextBefore2 = measureText(this.textArea.domNode.ownerDocument, hiddenLineTextBefore, this._fontInfo, tabSize2);
          return { distanceToModelLineStart: distanceToModelLineStart2, widthOfHiddenTextBefore: widthOfHiddenTextBefore2 };
        })();
        const { distanceToModelLineEnd } = (() => {
          const textAfterSelection = ta.value.substring(Math.max(ta.selectionStart, ta.selectionEnd));
          const lineFeedOffset2 = textAfterSelection.indexOf("\n");
          const lineTextAfterSelection = lineFeedOffset2 === -1 ? textAfterSelection : textAfterSelection.substring(0, lineFeedOffset2);
          const tabOffset2 = lineTextAfterSelection.indexOf("	");
          const desiredVisibleAfterCharCount = tabOffset2 === -1 ? lineTextAfterSelection.length : lineTextAfterSelection.length - tabOffset2 - 1;
          const endModelPosition = modelSelection.getEndPosition();
          const visibleAfterCharCount = Math.min(this._context.viewModel.model.getLineMaxColumn(endModelPosition.lineNumber) - endModelPosition.column, desiredVisibleAfterCharCount);
          const distanceToModelLineEnd2 = this._context.viewModel.model.getLineMaxColumn(endModelPosition.lineNumber) - endModelPosition.column - visibleAfterCharCount;
          return { distanceToModelLineEnd: distanceToModelLineEnd2 };
        })();
        this._context.viewModel.revealRange(
          "keyboard",
          true,
          Range$2.fromPositions(this._selections[0].getStartPosition()),
          0,
          1
          /* ScrollType.Immediate */
        );
        this._visibleTextArea = new VisibleTextAreaData(this._context, modelSelection.startLineNumber, distanceToModelLineStart, widthOfHiddenTextBefore, distanceToModelLineEnd);
        this.textArea.setAttribute("wrap", this._textAreaWrapping && !this._visibleTextArea ? "on" : "off");
        this._visibleTextArea.prepareRender(this._visibleRangeProvider);
        this._render();
        this.textArea.setClassName(`inputarea ${MOUSE_CURSOR_TEXT_CSS_CLASS_NAME} ime-input`);
        this._viewController.compositionStart();
        this._context.viewModel.onCompositionStart();
      }));
      this._register(this._textAreaInput.onCompositionUpdate((e) => {
        if (!this._visibleTextArea) {
          return;
        }
        this._visibleTextArea.prepareRender(this._visibleRangeProvider);
        this._render();
      }));
      this._register(this._textAreaInput.onCompositionEnd(() => {
        this._visibleTextArea = null;
        this.textArea.setAttribute("wrap", this._textAreaWrapping && !this._visibleTextArea ? "on" : "off");
        this._render();
        this.textArea.setClassName(`inputarea ${MOUSE_CURSOR_TEXT_CSS_CLASS_NAME}`);
        this._viewController.compositionEnd();
        this._context.viewModel.onCompositionEnd();
      }));
      this._register(this._textAreaInput.onFocus(() => {
        this._context.viewModel.setHasFocus(true);
      }));
      this._register(this._textAreaInput.onBlur(() => {
        this._context.viewModel.setHasFocus(false);
      }));
      this._register(IME.onDidChange(() => {
        this._ensureReadOnlyAttribute();
      }));
    }
    get domNode() {
      return this.textArea;
    }
    writeScreenReaderContent(reason) {
      this._textAreaInput.writeNativeTextAreaContent(reason);
    }
    dispose() {
      super.dispose();
      this.textArea.domNode.remove();
      this.textAreaCover.domNode.remove();
    }
    _getAndroidWordAtPosition(position) {
      const ANDROID_WORD_SEPARATORS = '`~!@#$%^&*()-=+[{]}\\|;:",.<>/?';
      const lineContent = this._context.viewModel.getLineContent(position.lineNumber);
      const wordSeparators2 = getMapForWordSeparators(ANDROID_WORD_SEPARATORS, []);
      let goingLeft = true;
      let startColumn = position.column;
      let goingRight = true;
      let endColumn = position.column;
      let distance = 0;
      while (distance < 50 && (goingLeft || goingRight)) {
        if (goingLeft && startColumn <= 1) {
          goingLeft = false;
        }
        if (goingLeft) {
          const charCode = lineContent.charCodeAt(startColumn - 2);
          const charClass = wordSeparators2.get(charCode);
          if (charClass !== 0) {
            goingLeft = false;
          } else {
            startColumn--;
          }
        }
        if (goingRight && endColumn > lineContent.length) {
          goingRight = false;
        }
        if (goingRight) {
          const charCode = lineContent.charCodeAt(endColumn - 1);
          const charClass = wordSeparators2.get(charCode);
          if (charClass !== 0) {
            goingRight = false;
          } else {
            endColumn++;
          }
        }
        distance++;
      }
      return [lineContent.substring(startColumn - 1, endColumn - 1), position.column - startColumn];
    }
    _getWordBeforePosition(position) {
      const lineContent = this._context.viewModel.getLineContent(position.lineNumber);
      const wordSeparators2 = getMapForWordSeparators(this._context.configuration.options.get(
        148
        /* EditorOption.wordSeparators */
      ), []);
      let column = position.column;
      let distance = 0;
      while (column > 1) {
        const charCode = lineContent.charCodeAt(column - 2);
        const charClass = wordSeparators2.get(charCode);
        if (charClass !== 0 || distance > 50) {
          return lineContent.substring(column - 1, position.column - 1);
        }
        distance++;
        column--;
      }
      return lineContent.substring(0, position.column - 1);
    }
    _getCharacterBeforePosition(position) {
      if (position.column > 1) {
        const lineContent = this._context.viewModel.getLineContent(position.lineNumber);
        const charBefore = lineContent.charAt(position.column - 2);
        if (!isHighSurrogate(charBefore.charCodeAt(0))) {
          return charBefore;
        }
      }
      return "";
    }
    _setAccessibilityOptions(options) {
      this._accessibilitySupport = options.get(
        2
        /* EditorOption.accessibilitySupport */
      );
      const accessibilityPageSize = options.get(
        3
        /* EditorOption.accessibilityPageSize */
      );
      if (this._accessibilitySupport === 2 && accessibilityPageSize === EditorOptions.accessibilityPageSize.defaultValue) {
        this._accessibilityPageSize = 500;
      } else {
        this._accessibilityPageSize = accessibilityPageSize;
      }
      const layoutInfo = options.get(
        165
        /* EditorOption.layoutInfo */
      );
      const wrappingColumn = layoutInfo.wrappingColumn;
      if (wrappingColumn !== -1 && this._accessibilitySupport !== 1) {
        const fontInfo = options.get(
          59
          /* EditorOption.fontInfo */
        );
        this._textAreaWrapping = true;
        this._textAreaWidth = Math.round(wrappingColumn * fontInfo.typicalHalfwidthCharacterWidth);
      } else {
        this._textAreaWrapping = false;
        this._textAreaWidth = canUseZeroSizeTextarea ? 0 : 1;
      }
    }
    // --- begin event handlers
    onConfigurationChanged(e) {
      const options = this._context.configuration.options;
      const layoutInfo = options.get(
        165
        /* EditorOption.layoutInfo */
      );
      this._setAccessibilityOptions(options);
      this._contentLeft = layoutInfo.contentLeft;
      this._contentWidth = layoutInfo.contentWidth;
      this._contentHeight = layoutInfo.height;
      this._fontInfo = options.get(
        59
        /* EditorOption.fontInfo */
      );
      this._emptySelectionClipboard = options.get(
        45
        /* EditorOption.emptySelectionClipboard */
      );
      this._copyWithSyntaxHighlighting = options.get(
        31
        /* EditorOption.copyWithSyntaxHighlighting */
      );
      this.textArea.setAttribute("wrap", this._textAreaWrapping && !this._visibleTextArea ? "on" : "off");
      const { tabSize } = this._context.viewModel.model.getOptions();
      this.textArea.domNode.style.tabSize = `${tabSize * this._fontInfo.spaceWidth}px`;
      this.textArea.setAttribute("aria-label", ariaLabelForScreenReaderContent(options, this._keybindingService));
      this.textArea.setAttribute("aria-required", options.get(
        9
        /* EditorOption.ariaRequired */
      ) ? "true" : "false");
      this.textArea.setAttribute("tabindex", String(options.get(
        140
        /* EditorOption.tabIndex */
      )));
      if (e.hasChanged(
        41
        /* EditorOption.domReadOnly */
      ) || e.hasChanged(
        104
        /* EditorOption.readOnly */
      )) {
        this._ensureReadOnlyAttribute();
      }
      if (e.hasChanged(
        2
        /* EditorOption.accessibilitySupport */
      )) {
        this._textAreaInput.writeNativeTextAreaContent("strategy changed");
      }
      return true;
    }
    onCursorStateChanged(e) {
      this._selections = e.selections.slice(0);
      this._modelSelections = e.modelSelections.slice(0);
      this._textAreaInput.writeNativeTextAreaContent("selection changed");
      return true;
    }
    onDecorationsChanged(e) {
      return true;
    }
    onFlushed(e) {
      return true;
    }
    onLinesChanged(e) {
      return true;
    }
    onLinesDeleted(e) {
      return true;
    }
    onLinesInserted(e) {
      return true;
    }
    onScrollChanged(e) {
      this._scrollLeft = e.scrollLeft;
      this._scrollTop = e.scrollTop;
      return true;
    }
    onZonesChanged(e) {
      return true;
    }
    // --- end event handlers
    // --- begin view API
    isFocused() {
      return this._textAreaInput.isFocused();
    }
    focus() {
      this._textAreaInput.focusTextArea();
    }
    refreshFocusState() {
      this._textAreaInput.refreshFocusState();
    }
    getLastRenderData() {
      return this._lastRenderPosition;
    }
    setAriaOptions(options) {
      if (options.activeDescendant) {
        this.textArea.setAttribute("aria-haspopup", "true");
        this.textArea.setAttribute("aria-autocomplete", "list");
        this.textArea.setAttribute("aria-activedescendant", options.activeDescendant);
      } else {
        this.textArea.setAttribute("aria-haspopup", "false");
        this.textArea.setAttribute("aria-autocomplete", "both");
        this.textArea.removeAttribute("aria-activedescendant");
      }
      if (options.role) {
        this.textArea.setAttribute("role", options.role);
      }
    }
    // --- end view API
    _ensureReadOnlyAttribute() {
      const options = this._context.configuration.options;
      const useReadOnly = !IME.enabled || options.get(
        41
        /* EditorOption.domReadOnly */
      ) && options.get(
        104
        /* EditorOption.readOnly */
      );
      if (useReadOnly) {
        this.textArea.setAttribute("readonly", "true");
      } else {
        this.textArea.removeAttribute("readonly");
      }
    }
    prepareRender(ctx) {
      this._primaryCursorPosition = new Position$1(this._selections[0].positionLineNumber, this._selections[0].positionColumn);
      this._primaryCursorVisibleRange = ctx.visibleRangeForPosition(this._primaryCursorPosition);
      this._visibleTextArea?.prepareRender(ctx);
    }
    render(ctx) {
      this._textAreaInput.writeNativeTextAreaContent("render");
      this._render();
    }
    _render() {
      if (this._visibleTextArea) {
        const visibleStart = this._visibleTextArea.visibleTextareaStart;
        const visibleEnd = this._visibleTextArea.visibleTextareaEnd;
        const startPosition = this._visibleTextArea.startPosition;
        const endPosition = this._visibleTextArea.endPosition;
        if (startPosition && endPosition && visibleStart && visibleEnd && visibleEnd.left >= this._scrollLeft && visibleStart.left <= this._scrollLeft + this._contentWidth) {
          const top2 = this._context.viewLayout.getVerticalOffsetForLineNumber(this._primaryCursorPosition.lineNumber) - this._scrollTop;
          const lineCount = newlinecount(this.textArea.domNode.value.substr(0, this.textArea.domNode.selectionStart));
          let scrollLeft = this._visibleTextArea.widthOfHiddenLineTextBefore;
          let left2 = this._contentLeft + visibleStart.left - this._scrollLeft;
          let width2 = visibleEnd.left - visibleStart.left + 1;
          if (left2 < this._contentLeft) {
            const delta = this._contentLeft - left2;
            left2 += delta;
            scrollLeft += delta;
            width2 -= delta;
          }
          if (width2 > this._contentWidth) {
            width2 = this._contentWidth;
          }
          const lineHeight = this._context.viewLayout.getLineHeightForLineNumber(startPosition.lineNumber);
          const fontSize = this._context.viewModel.getFontSizeAtPosition(this._primaryCursorPosition);
          const viewLineData = this._context.viewModel.getViewLineData(startPosition.lineNumber);
          const startTokenIndex = viewLineData.tokens.findTokenIndexAtOffset(startPosition.column - 1);
          const endTokenIndex = viewLineData.tokens.findTokenIndexAtOffset(endPosition.column - 1);
          const textareaSpansSingleToken = startTokenIndex === endTokenIndex;
          const presentation = this._visibleTextArea.definePresentation(textareaSpansSingleToken ? viewLineData.tokens.getPresentation(startTokenIndex) : null);
          this.textArea.domNode.scrollTop = lineCount * lineHeight;
          this.textArea.domNode.scrollLeft = scrollLeft;
          this._doRender({
            lastRenderPosition: null,
            top: top2,
            left: left2,
            width: width2,
            height: lineHeight,
            useCover: false,
            color: (TokenizationRegistry.getColorMap() || [])[presentation.foreground],
            italic: presentation.italic,
            bold: presentation.bold,
            underline: presentation.underline,
            strikethrough: presentation.strikethrough,
            fontSize
          });
        }
        return;
      }
      if (!this._primaryCursorVisibleRange) {
        this._renderAtTopLeft();
        return;
      }
      const left = this._contentLeft + this._primaryCursorVisibleRange.left - this._scrollLeft;
      if (left < this._contentLeft || left > this._contentLeft + this._contentWidth) {
        this._renderAtTopLeft();
        return;
      }
      const top = this._context.viewLayout.getVerticalOffsetForLineNumber(this._selections[0].positionLineNumber) - this._scrollTop;
      if (top < 0 || top > this._contentHeight) {
        this._renderAtTopLeft();
        return;
      }
      if (isMacintosh || this._accessibilitySupport === 2) {
        const lineNumber = this._primaryCursorPosition.lineNumber;
        const lineHeight = this._context.viewLayout.getLineHeightForLineNumber(lineNumber);
        this._doRender({
          lastRenderPosition: this._primaryCursorPosition,
          top,
          left: this._textAreaWrapping ? this._contentLeft : left,
          width: this._textAreaWidth,
          height: lineHeight,
          useCover: false
        });
        this.textArea.domNode.scrollLeft = this._primaryCursorVisibleRange.left;
        const lineCount = this._textAreaInput.textAreaState.newlineCountBeforeSelection ?? newlinecount(this.textArea.domNode.value.substring(0, this.textArea.domNode.selectionStart));
        this.textArea.domNode.scrollTop = lineCount * lineHeight;
        return;
      }
      this._doRender({
        lastRenderPosition: this._primaryCursorPosition,
        top,
        left: this._textAreaWrapping ? this._contentLeft : left,
        width: this._textAreaWidth,
        height: canUseZeroSizeTextarea ? 0 : 1,
        useCover: false
      });
    }
    _renderAtTopLeft() {
      this._doRender({
        lastRenderPosition: null,
        top: 0,
        left: 0,
        width: this._textAreaWidth,
        height: canUseZeroSizeTextarea ? 0 : 1,
        useCover: true
      });
    }
    _doRender(renderData) {
      this._lastRenderPosition = renderData.lastRenderPosition;
      const ta = this.textArea;
      const tac = this.textAreaCover;
      applyFontInfo(ta, this._fontInfo);
      ta.setTop(renderData.top);
      ta.setLeft(renderData.left);
      ta.setWidth(renderData.width);
      ta.setHeight(renderData.height);
      ta.setLineHeight(renderData.height);
      ta.setFontSize(renderData.fontSize ?? this._fontInfo.fontSize);
      ta.setColor(renderData.color ? Color.Format.CSS.formatHex(renderData.color) : "");
      ta.setFontStyle(renderData.italic ? "italic" : "");
      if (renderData.bold) {
        ta.setFontWeight("bold");
      }
      ta.setTextDecoration(`${renderData.underline ? " underline" : ""}${renderData.strikethrough ? " line-through" : ""}`);
      tac.setTop(renderData.useCover ? renderData.top : 0);
      tac.setLeft(renderData.useCover ? renderData.left : 0);
      tac.setWidth(renderData.useCover ? renderData.width : 0);
      tac.setHeight(renderData.useCover ? renderData.height : 0);
      const options = this._context.configuration.options;
      if (options.get(
        66
        /* EditorOption.glyphMargin */
      )) {
        tac.setClassName("monaco-editor-background textAreaCover " + Margin.OUTER_CLASS_NAME);
      } else {
        if (options.get(
          76
          /* EditorOption.lineNumbers */
        ).renderType !== 0) {
          tac.setClassName("monaco-editor-background textAreaCover " + LineNumbersOverlay.CLASS_NAME);
        } else {
          tac.setClassName("monaco-editor-background textAreaCover");
        }
      }
    }
  };
  TextAreaEditContext = __decorate$2W([
    __param$2R(4, IKeybindingService),
    __param$2R(5, IInstantiationService)
  ], TextAreaEditContext);
  function measureText(targetDocument, text2, fontInfo, tabSize) {
    if (text2.length === 0) {
      return 0;
    }
    const container = targetDocument.createElement("div");
    container.style.position = "absolute";
    container.style.top = "-50000px";
    container.style.width = "50000px";
    const regularDomNode = targetDocument.createElement("span");
    applyFontInfo(regularDomNode, fontInfo);
    regularDomNode.style.whiteSpace = "pre";
    regularDomNode.style.tabSize = `${tabSize * fontInfo.spaceWidth}px`;
    regularDomNode.append(text2);
    container.appendChild(regularDomNode);
    targetDocument.body.appendChild(container);
    const res = regularDomNode.offsetWidth;
    container.remove();
    return res;
  }
  var __decorate$2V = 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$2Q = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  let FocusTracker = class FocusTracker extends Disposable {
    constructor(_logService, _domNode, _onFocusChange) {
      super();
      this._domNode = _domNode;
      this._onFocusChange = _onFocusChange;
      this._isFocused = false;
      this._isPaused = false;
      this._register(addDisposableListener(this._domNode, "focus", () => {
        _logService.trace("NativeEditContext.focus");
        if (this._isPaused) {
          return;
        }
        this.refreshFocusState();
      }));
      this._register(addDisposableListener(this._domNode, "blur", () => {
        _logService.trace("NativeEditContext.blur");
        if (this._isPaused) {
          return;
        }
        this._handleFocusedChanged(false);
      }));
    }
    pause() {
      this._isPaused = true;
    }
    resume() {
      this._isPaused = false;
      this.refreshFocusState();
    }
    _handleFocusedChanged(focused) {
      if (this._isFocused === focused) {
        return;
      }
      this._isFocused = focused;
      this._onFocusChange(this._isFocused);
    }
    focus() {
      this._domNode.focus();
      this.refreshFocusState();
    }
    refreshFocusState() {
      const shadowRoot = getShadowRoot(this._domNode);
      const activeElement = shadowRoot ? shadowRoot.activeElement : getActiveElement();
      const focused = this._domNode === activeElement;
      this._handleFocusedChanged(focused);
    }
    get isFocused() {
      return this._isFocused;
    }
  };
  FocusTracker = __decorate$2V([
    __param$2Q(0, ILogService)
  ], FocusTracker);
  function editContextAddDisposableListener(target, type, listener, options) {
    target.addEventListener(type, listener, options);
    return {
      dispose() {
        target.removeEventListener(type, listener);
      }
    };
  }
  var __decorate$2U = 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$2P = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  const ttPolicy$5 = createTrustedTypesPolicy("richScreenReaderContent", { createHTML: (value) => value });
  const LINE_NUMBER_ATTRIBUTE = "data-line-number";
  let RichScreenReaderContent = class RichScreenReaderContent extends Disposable {
    constructor(_domNode, _context, _viewController, _accessibilityService) {
      super();
      this._domNode = _domNode;
      this._context = _context;
      this._viewController = _viewController;
      this._accessibilityService = _accessibilityService;
      this._selectionChangeListener = this._register(new MutableDisposable());
      this._accessibilityPageSize = 1;
      this._ignoreSelectionChangeTime = 0;
      this._state = RichScreenReaderState.NULL;
      this._strategy = new RichPagedScreenReaderStrategy();
      this._renderedLines = /* @__PURE__ */ new Map();
      this._renderedSelection = new Selection$1(1, 1, 1, 1);
      this.onConfigurationChanged(this._context.configuration.options);
    }
    updateScreenReaderContent(primarySelection) {
      const focusedElement = getActiveWindow().document.activeElement;
      if (!focusedElement || focusedElement !== this._domNode.domNode) {
        return;
      }
      const isScreenReaderOptimized = this._accessibilityService.isScreenReaderOptimized();
      if (isScreenReaderOptimized) {
        const state = this._getScreenReaderContentLineIntervals(primarySelection);
        if (!this._state.equals(state)) {
          this._state = state;
          this._renderedLines = this._renderScreenReaderContent(state);
        }
        if (!this._renderedSelection.equalsSelection(primarySelection)) {
          this._renderedSelection = primarySelection;
          this._setSelectionOnScreenReaderContent(this._context, this._renderedLines, primarySelection);
        }
      } else {
        this._state = RichScreenReaderState.NULL;
        this._setIgnoreSelectionChangeTime("setValue");
        this._domNode.domNode.textContent = "";
      }
    }
    updateScrollTop(primarySelection) {
      const intervals = this._state.intervals;
      if (!intervals.length) {
        return;
      }
      const viewLayout = this._context.viewModel.viewLayout;
      const stateStartLineNumber = intervals[0].startLine;
      const verticalOffsetOfStateStartLineNumber = viewLayout.getVerticalOffsetForLineNumber(stateStartLineNumber);
      const verticalOffsetOfPositionLineNumber = viewLayout.getVerticalOffsetForLineNumber(primarySelection.positionLineNumber);
      this._domNode.domNode.scrollTop = verticalOffsetOfPositionLineNumber - verticalOffsetOfStateStartLineNumber;
    }
    onFocusChange(newFocusValue) {
      if (newFocusValue) {
        this._selectionChangeListener.value = this._setSelectionChangeListener();
      } else {
        this._selectionChangeListener.value = void 0;
      }
    }
    onConfigurationChanged(options) {
      this._accessibilityPageSize = options.get(
        3
        /* EditorOption.accessibilityPageSize */
      );
    }
    onWillCut() {
      this._setIgnoreSelectionChangeTime("onCut");
    }
    onWillPaste() {
      this._setIgnoreSelectionChangeTime("onWillPaste");
    }
    // --- private methods
    _setIgnoreSelectionChangeTime(reason) {
      this._ignoreSelectionChangeTime = Date.now();
    }
    _setSelectionChangeListener() {
      let previousSelectionChangeEventTime = 0;
      return addDisposableListener(this._domNode.domNode.ownerDocument, "selectionchange", () => {
        const activeElement = getActiveWindow().document.activeElement;
        const isFocused = activeElement === this._domNode.domNode;
        if (!isFocused) {
          return;
        }
        const isScreenReaderOptimized = this._accessibilityService.isScreenReaderOptimized();
        if (!isScreenReaderOptimized || !IME.enabled) {
          return;
        }
        const now = Date.now();
        const delta1 = now - previousSelectionChangeEventTime;
        previousSelectionChangeEventTime = now;
        if (delta1 < 5) {
          return;
        }
        const delta2 = now - this._ignoreSelectionChangeTime;
        this._ignoreSelectionChangeTime = 0;
        if (delta2 < 100) {
          return;
        }
        const selection = this._getEditorSelectionFromDomRange();
        if (!selection) {
          return;
        }
        this._viewController.setSelection(selection);
      });
    }
    _renderScreenReaderContent(state) {
      const nodes = [];
      const renderedLines = /* @__PURE__ */ new Map();
      for (const interval of state.intervals) {
        for (let lineNumber = interval.startLine; lineNumber <= interval.endLine; lineNumber++) {
          const renderedLine = this._renderLine(lineNumber);
          renderedLines.set(lineNumber, renderedLine);
          nodes.push(renderedLine.domNode);
        }
      }
      this._setIgnoreSelectionChangeTime("setValue");
      this._domNode.domNode.replaceChildren(...nodes);
      return renderedLines;
    }
    _renderLine(viewLineNumber) {
      const viewModel = this._context.viewModel;
      const positionLineData = viewModel.getViewLineRenderingData(viewLineNumber);
      const options = this._context.configuration.options;
      const fontInfo = options.get(
        59
        /* EditorOption.fontInfo */
      );
      const stopRenderingLineAfter = options.get(
        133
        /* EditorOption.stopRenderingLineAfter */
      );
      const renderControlCharacters = options.get(
        108
        /* EditorOption.renderControlCharacters */
      );
      const fontLigatures = options.get(
        60
        /* EditorOption.fontLigatures */
      );
      const disableMonospaceOptimizations = options.get(
        40
        /* EditorOption.disableMonospaceOptimizations */
      );
      const lineDecorations = LineDecoration.filter(positionLineData.inlineDecorations, viewLineNumber, positionLineData.minColumn, positionLineData.maxColumn);
      const useMonospaceOptimizations = fontInfo.isMonospace && !disableMonospaceOptimizations;
      const useFontLigatures = fontLigatures !== EditorFontLigatures.OFF;
      let renderWhitespace;
      const experimentalWhitespaceRendering = options.get(
        47
        /* EditorOption.experimentalWhitespaceRendering */
      );
      if (experimentalWhitespaceRendering === "off") {
        renderWhitespace = options.get(
          113
          /* EditorOption.renderWhitespace */
        );
      } else {
        renderWhitespace = "none";
      }
      const renderLineInput = new RenderLineInput(useMonospaceOptimizations, fontInfo.canUseHalfwidthRightwardsArrow, positionLineData.content, positionLineData.continuesWithWrappedLine, positionLineData.isBasicASCII, positionLineData.containsRTL, positionLineData.minColumn - 1, positionLineData.tokens, lineDecorations, positionLineData.tabSize, positionLineData.startVisibleColumn, fontInfo.spaceWidth, fontInfo.middotWidth, fontInfo.wsmiddotWidth, stopRenderingLineAfter, renderWhitespace, renderControlCharacters, useFontLigatures, null, null, 0, true);
      const htmlBuilder = new StringBuilder(1e4);
      const renderOutput = renderViewLine(renderLineInput, htmlBuilder);
      const html2 = htmlBuilder.build();
      const trustedhtml = ttPolicy$5?.createHTML(html2) ?? html2;
      const lineHeight = viewModel.viewLayout.getLineHeightForLineNumber(viewLineNumber) + "px";
      const domNode = document.createElement("div");
      domNode.innerHTML = trustedhtml;
      domNode.style.lineHeight = lineHeight;
      domNode.style.height = lineHeight;
      domNode.setAttribute(LINE_NUMBER_ATTRIBUTE, viewLineNumber.toString());
      return new RichRenderedScreenReaderLine(domNode, renderOutput.characterMapping);
    }
    _setSelectionOnScreenReaderContent(context, renderedLines, viewSelection) {
      const activeDocument = getActiveWindow().document;
      const activeDocumentSelection = activeDocument.getSelection();
      if (!activeDocumentSelection) {
        return;
      }
      const startLineNumber = viewSelection.startLineNumber;
      const endLineNumber = viewSelection.endLineNumber;
      const startRenderedLine = renderedLines.get(startLineNumber);
      const endRenderedLine = renderedLines.get(endLineNumber);
      if (!startRenderedLine || !endRenderedLine) {
        return;
      }
      const viewModel = context.viewModel;
      const model = viewModel.model;
      const coordinatesConverter = viewModel.coordinatesConverter;
      const startRange = new Range$2(startLineNumber, 1, startLineNumber, viewSelection.selectionStartColumn);
      const modelStartRange = coordinatesConverter.convertViewRangeToModelRange(startRange);
      const characterCountForStart = model.getCharacterCountInRange(modelStartRange);
      const endRange = new Range$2(endLineNumber, 1, endLineNumber, viewSelection.positionColumn);
      const modelEndRange = coordinatesConverter.convertViewRangeToModelRange(endRange);
      const characterCountForEnd = model.getCharacterCountInRange(modelEndRange);
      const startDomPosition = startRenderedLine.characterMapping.getDomPosition(characterCountForStart);
      const endDomPosition = endRenderedLine.characterMapping.getDomPosition(characterCountForEnd);
      const startDomNode = startRenderedLine.domNode.firstChild;
      const endDomNode = endRenderedLine.domNode.firstChild;
      const startChildren = startDomNode.childNodes;
      const endChildren = endDomNode.childNodes;
      const startNode = startChildren.item(startDomPosition.partIndex);
      const endNode = endChildren.item(endDomPosition.partIndex);
      if (!startNode.firstChild || !endNode.firstChild) {
        return;
      }
      this._setIgnoreSelectionChangeTime("setRange");
      activeDocumentSelection.setBaseAndExtent(startNode.firstChild, viewSelection.startColumn === 1 ? 0 : startDomPosition.charIndex + 1, endNode.firstChild, viewSelection.endColumn === 1 ? 0 : endDomPosition.charIndex + 1);
    }
    _getScreenReaderContentLineIntervals(primarySelection) {
      return this._strategy.fromEditorSelection(this._context.viewModel, primarySelection, this._accessibilityPageSize);
    }
    _getEditorSelectionFromDomRange() {
      if (!this._renderedLines) {
        return;
      }
      const selection = getActiveWindow().document.getSelection();
      if (!selection) {
        return;
      }
      const rangeCount = selection.rangeCount;
      if (rangeCount === 0) {
        return;
      }
      const range2 = selection.getRangeAt(0);
      const startContainer = range2.startContainer;
      const endContainer = range2.endContainer;
      const startSpanElement = startContainer.parentElement;
      const endSpanElement = endContainer.parentElement;
      if (!startSpanElement || !isHTMLElement(startSpanElement) || !endSpanElement || !isHTMLElement(endSpanElement)) {
        return;
      }
      const startLineDomNode = startSpanElement.parentElement?.parentElement;
      const endLineDomNode = endSpanElement.parentElement?.parentElement;
      if (!startLineDomNode || !endLineDomNode) {
        return;
      }
      const startLineNumberAttribute = startLineDomNode.getAttribute(LINE_NUMBER_ATTRIBUTE);
      const endLineNumberAttribute = endLineDomNode.getAttribute(LINE_NUMBER_ATTRIBUTE);
      if (!startLineNumberAttribute || !endLineNumberAttribute) {
        return;
      }
      const startLineNumber = parseInt(startLineNumberAttribute);
      const endLineNumber = parseInt(endLineNumberAttribute);
      const startMapping = this._renderedLines.get(startLineNumber)?.characterMapping;
      const endMapping = this._renderedLines.get(endLineNumber)?.characterMapping;
      if (!startMapping || !endMapping) {
        return;
      }
      const startColumn = getColumnOfNodeOffset(startMapping, startSpanElement, range2.startOffset);
      const endColumn = getColumnOfNodeOffset(endMapping, endSpanElement, range2.endOffset);
      if (selection.direction === "forward") {
        return new Selection$1(startLineNumber, startColumn, endLineNumber, endColumn);
      } else {
        return new Selection$1(endLineNumber, endColumn, startLineNumber, startColumn);
      }
    }
  };
  RichScreenReaderContent = __decorate$2U([
    __param$2P(3, IAccessibilityService)
  ], RichScreenReaderContent);
  class RichRenderedScreenReaderLine {
    constructor(domNode, characterMapping) {
      this.domNode = domNode;
      this.characterMapping = characterMapping;
    }
  }
  class LineInterval {
    constructor(startLine, endLine) {
      this.startLine = startLine;
      this.endLine = endLine;
    }
  }
  class RichScreenReaderState {
    constructor(model, intervals) {
      this.intervals = intervals;
      let value = "";
      for (const interval of intervals) {
        for (let lineNumber = interval.startLine; lineNumber <= interval.endLine; lineNumber++) {
          value += model.getLineContent(lineNumber) + "\n";
        }
      }
      this.value = value;
    }
    equals(other) {
      return this.value === other.value;
    }
    static get NULL() {
      const nullModel = {
        getLineContent: () => "",
        getLineCount: () => 1,
        getLineMaxColumn: () => 1,
        getValueInRange: () => "",
        getValueLengthInRange: () => 0,
        modifyPosition: (position, offset) => position
      };
      return new RichScreenReaderState(nullModel, []);
    }
  }
  class RichPagedScreenReaderStrategy {
    constructor() {
    }
    _getPageOfLine(lineNumber, linesPerPage) {
      return Math.floor((lineNumber - 1) / linesPerPage);
    }
    _getRangeForPage(context, page, linesPerPage) {
      const offset = page * linesPerPage;
      const startLineNumber = offset + 1;
      const endLineNumber = Math.min(offset + linesPerPage, context.getLineCount());
      return new LineInterval(startLineNumber, endLineNumber);
    }
    fromEditorSelection(context, viewSelection, linesPerPage) {
      const selectionStartPage = this._getPageOfLine(viewSelection.startLineNumber, linesPerPage);
      const selectionStartPageRange = this._getRangeForPage(context, selectionStartPage, linesPerPage);
      const selectionEndPage = this._getPageOfLine(viewSelection.endLineNumber, linesPerPage);
      const selectionEndPageRange = this._getRangeForPage(context, selectionEndPage, linesPerPage);
      const lineIntervals = [{ startLine: selectionStartPageRange.startLine, endLine: selectionStartPageRange.endLine }];
      if (selectionStartPage + 1 < selectionEndPage) {
        lineIntervals.push({ startLine: selectionEndPageRange.startLine, endLine: selectionEndPageRange.endLine });
      }
      return new RichScreenReaderState(context, lineIntervals);
    }
  }
  class BaseEdit {
    constructor(replacements) {
      this.replacements = replacements;
      let lastEndEx = -1;
      for (const replacement of replacements) {
        if (!(replacement.replaceRange.start >= lastEndEx)) {
          throw new BugIndicatingError(`Edits must be disjoint and sorted. Found ${replacement} after ${lastEndEx}`);
        }
        lastEndEx = replacement.replaceRange.endExclusive;
      }
    }
    toString() {
      const edits = this.replacements.map((e) => e.toString()).join(", ");
      return `[${edits}]`;
    }
    /**
     * Normalizes the edit by removing empty replacements and joining touching replacements (if the replacements allow joining).
     * Two edits have an equal normalized edit if and only if they have the same effect on any input.
     *
     * ![](https://raw.githubusercontent.com/microsoft/vscode/refs/heads/main/src/vs/editor/common/core/edits/docs/BaseEdit_normalize.drawio.png)
     *
     * Invariant:
     * ```
     * (forall base: TEdit.apply(base).equals(other.apply(base))) <-> this.normalize().equals(other.normalize())
     * ```
     * and
     * ```
     * forall base: TEdit.apply(base).equals(this.normalize().apply(base))
     * ```
     *
     */
    normalize() {
      const newReplacements = [];
      let lastReplacement;
      for (const r of this.replacements) {
        if (r.getNewLength() === 0 && r.replaceRange.length === 0) {
          continue;
        }
        if (lastReplacement && lastReplacement.replaceRange.endExclusive === r.replaceRange.start) {
          const joined = lastReplacement.tryJoinTouching(r);
          if (joined) {
            lastReplacement = joined;
            continue;
          }
        }
        if (lastReplacement) {
          newReplacements.push(lastReplacement);
        }
        lastReplacement = r;
      }
      if (lastReplacement) {
        newReplacements.push(lastReplacement);
      }
      return this._createNew(newReplacements);
    }
    /**
     * Combines two edits into one with the same effect.
     *
     * ![](https://raw.githubusercontent.com/microsoft/vscode/refs/heads/main/src/vs/editor/common/core/edits/docs/BaseEdit_compose.drawio.png)
     *
     * Invariant:
     * ```
     * other.apply(this.apply(s0)) = this.compose(other).apply(s0)
     * ```
     */
    compose(other) {
      const edits1 = this.normalize();
      const edits2 = other.normalize();
      if (edits1.isEmpty()) {
        return edits2;
      }
      if (edits2.isEmpty()) {
        return edits1;
      }
      const edit1Queue = [...edits1.replacements];
      const result = [];
      let edit1ToEdit2 = 0;
      for (const r2 of edits2.replacements) {
        while (true) {
          const r1 = edit1Queue[0];
          if (!r1 || r1.replaceRange.start + edit1ToEdit2 + r1.getNewLength() >= r2.replaceRange.start) {
            break;
          }
          edit1Queue.shift();
          result.push(r1);
          edit1ToEdit2 += r1.getNewLength() - r1.replaceRange.length;
        }
        const firstEdit1ToEdit2 = edit1ToEdit2;
        let firstIntersecting;
        let lastIntersecting;
        while (true) {
          const r1 = edit1Queue[0];
          if (!r1 || r1.replaceRange.start + edit1ToEdit2 > r2.replaceRange.endExclusive) {
            break;
          }
          if (!firstIntersecting) {
            firstIntersecting = r1;
          }
          lastIntersecting = r1;
          edit1Queue.shift();
          edit1ToEdit2 += r1.getNewLength() - r1.replaceRange.length;
        }
        if (!firstIntersecting) {
          result.push(r2.delta(-edit1ToEdit2));
        } else {
          const newReplaceRangeStart = Math.min(firstIntersecting.replaceRange.start, r2.replaceRange.start - firstEdit1ToEdit2);
          const prefixLength = r2.replaceRange.start - (firstIntersecting.replaceRange.start + firstEdit1ToEdit2);
          if (prefixLength > 0) {
            const prefix = firstIntersecting.slice(OffsetRange.emptyAt(newReplaceRangeStart), new OffsetRange(0, prefixLength));
            result.push(prefix);
          }
          if (!lastIntersecting) {
            throw new BugIndicatingError(`Invariant violation: lastIntersecting is undefined`);
          }
          const suffixLength = lastIntersecting.replaceRange.endExclusive + edit1ToEdit2 - r2.replaceRange.endExclusive;
          if (suffixLength > 0) {
            const e = lastIntersecting.slice(OffsetRange.ofStartAndLength(lastIntersecting.replaceRange.endExclusive, 0), new OffsetRange(lastIntersecting.getNewLength() - suffixLength, lastIntersecting.getNewLength()));
            edit1Queue.unshift(e);
            edit1ToEdit2 -= e.getNewLength() - e.replaceRange.length;
          }
          const newReplaceRange = new OffsetRange(newReplaceRangeStart, r2.replaceRange.endExclusive - edit1ToEdit2);
          const middle = r2.slice(newReplaceRange, new OffsetRange(0, r2.getNewLength()));
          result.push(middle);
        }
      }
      while (true) {
        const item = edit1Queue.shift();
        if (!item) {
          break;
        }
        result.push(item);
      }
      return this._createNew(result).normalize();
    }
    /**
     * Returns the range of each replacement in the applied value.
    */
    getNewRanges() {
      const ranges = [];
      let offset = 0;
      for (const e of this.replacements) {
        ranges.push(OffsetRange.ofStartAndLength(e.replaceRange.start + offset, e.getNewLength()));
        offset += e.getLengthDelta();
      }
      return ranges;
    }
    isEmpty() {
      return this.replacements.length === 0;
    }
  }
  class BaseReplacement {
    constructor(replaceRange) {
      this.replaceRange = replaceRange;
    }
    delta(offset) {
      return this.slice(this.replaceRange.delta(offset), new OffsetRange(0, this.getNewLength()));
    }
    getLengthDelta() {
      return this.getNewLength() - this.replaceRange.length;
    }
    toString() {
      return `{ ${this.replaceRange.toString()} -> ${this.getNewLength()} }`;
    }
    get isEmpty() {
      return this.getNewLength() === 0 && this.replaceRange.length === 0;
    }
    getRangeAfterReplace() {
      return new OffsetRange(this.replaceRange.start, this.replaceRange.start + this.getNewLength());
    }
  }
  class BaseStringEdit extends BaseEdit {
    apply(base) {
      const resultText = [];
      let pos = 0;
      for (const edit2 of this.replacements) {
        resultText.push(base.substring(pos, edit2.replaceRange.start));
        resultText.push(edit2.newText);
        pos = edit2.replaceRange.endExclusive;
      }
      resultText.push(base.substring(pos));
      return resultText.join("");
    }
  }
  class BaseStringReplacement extends BaseReplacement {
    constructor(range2, newText) {
      super(range2);
      this.newText = newText;
    }
    getNewLength() {
      return this.newText.length;
    }
    toString() {
      return `${this.replaceRange} -> ${JSON.stringify(this.newText)}`;
    }
    replace(str) {
      return str.substring(0, this.replaceRange.start) + this.newText + str.substring(this.replaceRange.endExclusive);
    }
    removeCommonSuffixPrefix(originalText) {
      const oldText = originalText.substring(this.replaceRange.start, this.replaceRange.endExclusive);
      const prefixLen = commonPrefixLength(oldText, this.newText);
      const suffixLen = Math.min(oldText.length - prefixLen, this.newText.length - prefixLen, commonSuffixLength(oldText, this.newText));
      const replaceRange = new OffsetRange(this.replaceRange.start + prefixLen, this.replaceRange.endExclusive - suffixLen);
      const newText = this.newText.substring(prefixLen, this.newText.length - suffixLen);
      return new StringReplacement(replaceRange, newText);
    }
    removeCommonSuffixAndPrefix(source) {
      return this.removeCommonSuffix(source).removeCommonPrefix(source);
    }
    removeCommonPrefix(source) {
      const oldText = this.replaceRange.substring(source);
      const prefixLen = commonPrefixLength(oldText, this.newText);
      if (prefixLen === 0) {
        return this;
      }
      return this.slice(this.replaceRange.deltaStart(prefixLen), new OffsetRange(prefixLen, this.newText.length));
    }
    removeCommonSuffix(source) {
      const oldText = this.replaceRange.substring(source);
      const suffixLen = commonSuffixLength(oldText, this.newText);
      if (suffixLen === 0) {
        return this;
      }
      return this.slice(this.replaceRange.deltaEnd(-suffixLen), new OffsetRange(0, this.newText.length - suffixLen));
    }
    toJson() {
      return {
        txt: this.newText,
        pos: this.replaceRange.start,
        len: this.replaceRange.length
      };
    }
  }
  const _StringEdit = class _StringEdit extends BaseStringEdit {
    static compose(edits) {
      if (edits.length === 0) {
        return _StringEdit.empty;
      }
      let result = edits[0];
      for (let i2 = 1; i2 < edits.length; i2++) {
        result = result.compose(edits[i2]);
      }
      return result;
    }
    constructor(replacements) {
      super(replacements);
    }
    _createNew(replacements) {
      return new _StringEdit(replacements);
    }
  };
  _StringEdit.empty = new _StringEdit([]);
  let StringEdit = _StringEdit;
  class StringReplacement extends BaseStringReplacement {
    static insert(offset, text2) {
      return new StringReplacement(OffsetRange.emptyAt(offset), text2);
    }
    static replace(range2, text2) {
      return new StringReplacement(range2, text2);
    }
    equals(other) {
      return this.replaceRange.equals(other.replaceRange) && this.newText === other.newText;
    }
    tryJoinTouching(other) {
      return new StringReplacement(this.replaceRange.joinRightTouching(other.replaceRange), this.newText + other.newText);
    }
    slice(range2, rangeInReplacement) {
      return new StringReplacement(range2, rangeInReplacement ? rangeInReplacement.substring(this.newText) : this.newText);
    }
  }
  function applyEditsToRanges(sortedRanges, edit2) {
    sortedRanges = sortedRanges.slice();
    const result = [];
    let offset = 0;
    for (const e of edit2.replacements) {
      while (true) {
        const r = sortedRanges[0];
        if (!r || r.endExclusive >= e.replaceRange.start) {
          break;
        }
        sortedRanges.shift();
        result.push(r.delta(offset));
      }
      const intersecting = [];
      while (true) {
        const r = sortedRanges[0];
        if (!r || !r.intersectsOrTouches(e.replaceRange)) {
          break;
        }
        sortedRanges.shift();
        intersecting.push(r);
      }
      for (let i2 = intersecting.length - 1; i2 >= 0; i2--) {
        let r = intersecting[i2];
        const overlap = r.intersect(e.replaceRange).length;
        r = r.deltaEnd(-overlap + (i2 === 0 ? e.newText.length : 0));
        const rangeAheadOfReplaceRange = r.start - e.replaceRange.start;
        if (rangeAheadOfReplaceRange > 0) {
          r = r.delta(-rangeAheadOfReplaceRange);
        }
        if (i2 !== 0) {
          r = r.delta(e.newText.length);
        }
        r = r.delta(-(e.newText.length - e.replaceRange.length));
        sortedRanges.unshift(r);
      }
      offset += e.newText.length - e.replaceRange.length;
    }
    while (true) {
      const r = sortedRanges[0];
      if (!r) {
        break;
      }
      sortedRanges.shift();
      result.push(r.delta(offset));
    }
    return result;
  }
  const _LineRange = class _LineRange {
    static ofLength(startLineNumber, length) {
      return new _LineRange(startLineNumber, startLineNumber + length);
    }
    static fromRange(range2) {
      return new _LineRange(range2.startLineNumber, range2.endLineNumber);
    }
    static fromRangeInclusive(range2) {
      return new _LineRange(range2.startLineNumber, range2.endLineNumber + 1);
    }
    /**
     * @param lineRanges An array of arrays of of sorted line ranges.
     */
    static joinMany(lineRanges) {
      if (lineRanges.length === 0) {
        return [];
      }
      let result = new LineRangeSet(lineRanges[0].slice());
      for (let i2 = 1; i2 < lineRanges.length; i2++) {
        result = result.getUnion(new LineRangeSet(lineRanges[i2].slice()));
      }
      return result.ranges;
    }
    static join(lineRanges) {
      if (lineRanges.length === 0) {
        throw new BugIndicatingError("lineRanges cannot be empty");
      }
      let startLineNumber = lineRanges[0].startLineNumber;
      let endLineNumberExclusive = lineRanges[0].endLineNumberExclusive;
      for (let i2 = 1; i2 < lineRanges.length; i2++) {
        startLineNumber = Math.min(startLineNumber, lineRanges[i2].startLineNumber);
        endLineNumberExclusive = Math.max(endLineNumberExclusive, lineRanges[i2].endLineNumberExclusive);
      }
      return new _LineRange(startLineNumber, endLineNumberExclusive);
    }
    /**
     * @internal
     */
    static deserialize(lineRange) {
      return new _LineRange(lineRange[0], lineRange[1]);
    }
    constructor(startLineNumber, endLineNumberExclusive) {
      if (startLineNumber > endLineNumberExclusive) {
        throw new BugIndicatingError(`startLineNumber ${startLineNumber} cannot be after endLineNumberExclusive ${endLineNumberExclusive}`);
      }
      this.startLineNumber = startLineNumber;
      this.endLineNumberExclusive = endLineNumberExclusive;
    }
    /**
     * Indicates if this line range contains the given line number.
     */
    contains(lineNumber) {
      return this.startLineNumber <= lineNumber && lineNumber < this.endLineNumberExclusive;
    }
    /**
     * Indicates if this line range is empty.
     */
    get isEmpty() {
      return this.startLineNumber === this.endLineNumberExclusive;
    }
    /**
     * Moves this line range by the given offset of line numbers.
     */
    delta(offset) {
      return new _LineRange(this.startLineNumber + offset, this.endLineNumberExclusive + offset);
    }
    deltaLength(offset) {
      return new _LineRange(this.startLineNumber, this.endLineNumberExclusive + offset);
    }
    /**
     * The number of lines this line range spans.
     */
    get length() {
      return this.endLineNumberExclusive - this.startLineNumber;
    }
    /**
     * Creates a line range that combines this and the given line range.
     */
    join(other) {
      return new _LineRange(Math.min(this.startLineNumber, other.startLineNumber), Math.max(this.endLineNumberExclusive, other.endLineNumberExclusive));
    }
    toString() {
      return `[${this.startLineNumber},${this.endLineNumberExclusive})`;
    }
    /**
     * 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 startLineNumber = Math.max(this.startLineNumber, other.startLineNumber);
      const endLineNumberExclusive = Math.min(this.endLineNumberExclusive, other.endLineNumberExclusive);
      if (startLineNumber <= endLineNumberExclusive) {
        return new _LineRange(startLineNumber, endLineNumberExclusive);
      }
      return void 0;
    }
    intersectsStrict(other) {
      return this.startLineNumber < other.endLineNumberExclusive && other.startLineNumber < this.endLineNumberExclusive;
    }
    intersectsOrTouches(other) {
      return this.startLineNumber <= other.endLineNumberExclusive && other.startLineNumber <= this.endLineNumberExclusive;
    }
    equals(b) {
      return this.startLineNumber === b.startLineNumber && this.endLineNumberExclusive === b.endLineNumberExclusive;
    }
    toInclusiveRange() {
      if (this.isEmpty) {
        return null;
      }
      return new Range$2(this.startLineNumber, 1, this.endLineNumberExclusive - 1, Number.MAX_SAFE_INTEGER);
    }
    /**
     * @deprecated Using this function is discouraged because it might lead to bugs: The end position is not guaranteed to be a valid position!
    */
    toExclusiveRange() {
      return new Range$2(this.startLineNumber, 1, this.endLineNumberExclusive, 1);
    }
    mapToLineArray(f) {
      const result = [];
      for (let lineNumber = this.startLineNumber; lineNumber < this.endLineNumberExclusive; lineNumber++) {
        result.push(f(lineNumber));
      }
      return result;
    }
    forEach(f) {
      for (let lineNumber = this.startLineNumber; lineNumber < this.endLineNumberExclusive; lineNumber++) {
        f(lineNumber);
      }
    }
    /**
     * @internal
     */
    serialize() {
      return [this.startLineNumber, this.endLineNumberExclusive];
    }
    /**
     * Converts this 1-based line range to a 0-based offset range (subtracts 1!).
     * @internal
     */
    toOffsetRange() {
      return new OffsetRange(this.startLineNumber - 1, this.endLineNumberExclusive - 1);
    }
    addMargin(marginTop, marginBottom) {
      return new _LineRange(this.startLineNumber - marginTop, this.endLineNumberExclusive + marginBottom);
    }
  };
  _LineRange.compareByStart = compareBy((l) => l.startLineNumber, numberComparator);
  let LineRange = _LineRange;
  class LineRangeSet {
    constructor(_normalizedRanges = []) {
      this._normalizedRanges = _normalizedRanges;
    }
    get ranges() {
      return this._normalizedRanges;
    }
    addRange(range2) {
      if (range2.length === 0) {
        return;
      }
      const joinRangeStartIdx = findFirstIdxMonotonousOrArrLen(this._normalizedRanges, (r) => r.endLineNumberExclusive >= range2.startLineNumber);
      const joinRangeEndIdxExclusive = findLastIdxMonotonous(this._normalizedRanges, (r) => r.startLineNumber <= range2.endLineNumberExclusive) + 1;
      if (joinRangeStartIdx === joinRangeEndIdxExclusive) {
        this._normalizedRanges.splice(joinRangeStartIdx, 0, range2);
      } else if (joinRangeStartIdx === joinRangeEndIdxExclusive - 1) {
        const joinRange = this._normalizedRanges[joinRangeStartIdx];
        this._normalizedRanges[joinRangeStartIdx] = joinRange.join(range2);
      } else {
        const joinRange = this._normalizedRanges[joinRangeStartIdx].join(this._normalizedRanges[joinRangeEndIdxExclusive - 1]).join(range2);
        this._normalizedRanges.splice(joinRangeStartIdx, joinRangeEndIdxExclusive - joinRangeStartIdx, joinRange);
      }
    }
    contains(lineNumber) {
      const rangeThatStartsBeforeEnd = findLastMonotonous(this._normalizedRanges, (r) => r.startLineNumber <= lineNumber);
      return !!rangeThatStartsBeforeEnd && rangeThatStartsBeforeEnd.endLineNumberExclusive > lineNumber;
    }
    intersects(range2) {
      const rangeThatStartsBeforeEnd = findLastMonotonous(this._normalizedRanges, (r) => r.startLineNumber < range2.endLineNumberExclusive);
      return !!rangeThatStartsBeforeEnd && rangeThatStartsBeforeEnd.endLineNumberExclusive > range2.startLineNumber;
    }
    getUnion(other) {
      if (this._normalizedRanges.length === 0) {
        return other;
      }
      if (other._normalizedRanges.length === 0) {
        return this;
      }
      const result = [];
      let i1 = 0;
      let i2 = 0;
      let current = null;
      while (i1 < this._normalizedRanges.length || i2 < other._normalizedRanges.length) {
        let next = null;
        if (i1 < this._normalizedRanges.length && i2 < other._normalizedRanges.length) {
          const lineRange1 = this._normalizedRanges[i1];
          const lineRange2 = other._normalizedRanges[i2];
          if (lineRange1.startLineNumber < lineRange2.startLineNumber) {
            next = lineRange1;
            i1++;
          } else {
            next = lineRange2;
            i2++;
          }
        } else if (i1 < this._normalizedRanges.length) {
          next = this._normalizedRanges[i1];
          i1++;
        } else {
          next = other._normalizedRanges[i2];
          i2++;
        }
        if (current === null) {
          current = next;
        } else {
          if (current.endLineNumberExclusive >= next.startLineNumber) {
            current = new LineRange(current.startLineNumber, Math.max(current.endLineNumberExclusive, next.endLineNumberExclusive));
          } else {
            result.push(current);
            current = next;
          }
        }
      }
      if (current !== null) {
        result.push(current);
      }
      return new LineRangeSet(result);
    }
    /**
     * Subtracts all ranges in this set from `range` and returns the result.
     */
    subtractFrom(range2) {
      const joinRangeStartIdx = findFirstIdxMonotonousOrArrLen(this._normalizedRanges, (r) => r.endLineNumberExclusive >= range2.startLineNumber);
      const joinRangeEndIdxExclusive = findLastIdxMonotonous(this._normalizedRanges, (r) => r.startLineNumber <= range2.endLineNumberExclusive) + 1;
      if (joinRangeStartIdx === joinRangeEndIdxExclusive) {
        return new LineRangeSet([range2]);
      }
      const result = [];
      let startLineNumber = range2.startLineNumber;
      for (let i2 = joinRangeStartIdx; i2 < joinRangeEndIdxExclusive; i2++) {
        const r = this._normalizedRanges[i2];
        if (r.startLineNumber > startLineNumber) {
          result.push(new LineRange(startLineNumber, r.startLineNumber));
        }
        startLineNumber = r.endLineNumberExclusive;
      }
      if (startLineNumber < range2.endLineNumberExclusive) {
        result.push(new LineRange(startLineNumber, range2.endLineNumberExclusive));
      }
      return new LineRangeSet(result);
    }
    toString() {
      return this._normalizedRanges.map((r) => r.toString()).join(", ");
    }
    getIntersection(other) {
      const result = [];
      let i1 = 0;
      let i2 = 0;
      while (i1 < this._normalizedRanges.length && i2 < other._normalizedRanges.length) {
        const r1 = this._normalizedRanges[i1];
        const r2 = other._normalizedRanges[i2];
        const i3 = r1.intersect(r2);
        if (i3 && !i3.isEmpty) {
          result.push(i3);
        }
        if (r1.endLineNumberExclusive < r2.endLineNumberExclusive) {
          i1++;
        } else {
          i2++;
        }
      }
      return new LineRangeSet(result);
    }
    getWithDelta(value) {
      return new LineRangeSet(this._normalizedRanges.map((r) => r.delta(value)));
    }
  }
  const _TextLength = class _TextLength {
    static betweenPositions(position1, position2) {
      if (position1.lineNumber === position2.lineNumber) {
        return new _TextLength(0, position2.column - position1.column);
      } else {
        return new _TextLength(position2.lineNumber - position1.lineNumber, position2.column - 1);
      }
    }
    static fromPosition(pos) {
      return new _TextLength(pos.lineNumber - 1, pos.column - 1);
    }
    static ofRange(range2) {
      return _TextLength.betweenPositions(range2.getStartPosition(), range2.getEndPosition());
    }
    static ofText(text2) {
      let line = 0;
      let column = 0;
      for (const c of text2) {
        if (c === "\n") {
          line++;
          column = 0;
        } else {
          column++;
        }
      }
      return new _TextLength(line, column);
    }
    constructor(lineCount, columnCount) {
      this.lineCount = lineCount;
      this.columnCount = columnCount;
    }
    isGreaterThanOrEqualTo(other) {
      if (this.lineCount !== other.lineCount) {
        return this.lineCount > other.lineCount;
      }
      return this.columnCount >= other.columnCount;
    }
    add(other) {
      if (other.lineCount === 0) {
        return new _TextLength(this.lineCount, this.columnCount + other.columnCount);
      } else {
        return new _TextLength(this.lineCount + other.lineCount, other.columnCount);
      }
    }
    createRange(startPosition) {
      if (this.lineCount === 0) {
        return new Range$2(startPosition.lineNumber, startPosition.column, startPosition.lineNumber, startPosition.column + this.columnCount);
      } else {
        return new Range$2(startPosition.lineNumber, startPosition.column, startPosition.lineNumber + this.lineCount, this.columnCount + 1);
      }
    }
    toRange() {
      return new Range$2(1, 1, this.lineCount + 1, this.columnCount + 1);
    }
    toLineRange() {
      return LineRange.ofLength(1, this.lineCount + 1);
    }
    addToPosition(position) {
      if (this.lineCount === 0) {
        return new Position$1(position.lineNumber, position.column + this.columnCount);
      } else {
        return new Position$1(position.lineNumber + this.lineCount, this.columnCount + 1);
      }
    }
    toString() {
      return `${this.lineCount},${this.columnCount}`;
    }
  };
  _TextLength.zero = new _TextLength(0, 0);
  let TextLength = _TextLength;
  class PositionOffsetTransformerBase {
    getOffsetRange(range2) {
      return new OffsetRange(this.getOffset(range2.getStartPosition()), this.getOffset(range2.getEndPosition()));
    }
    getRange(offsetRange) {
      return Range$2.fromPositions(this.getPosition(offsetRange.start), this.getPosition(offsetRange.endExclusive));
    }
    getStringReplacement(edit2) {
      return new Deps.deps.StringReplacement(this.getOffsetRange(edit2.range), edit2.text);
    }
    getTextReplacement(edit2) {
      return new Deps.deps.TextReplacement(this.getRange(edit2.replaceRange), edit2.newText);
    }
    getTextEdit(edit2) {
      const edits = edit2.replacements.map((e) => this.getTextReplacement(e));
      return new Deps.deps.TextEdit(edits);
    }
  }
  const _Deps = class _Deps {
    static get deps() {
      if (!this._deps) {
        throw new Error("Dependencies not set. Call _setDependencies first.");
      }
      return this._deps;
    }
  };
  _Deps._deps = void 0;
  let Deps = _Deps;
  function _setPositionOffsetTransformerDependencies(deps) {
    Deps._deps = deps;
  }
  class PositionOffsetTransformer extends PositionOffsetTransformerBase {
    constructor(text2) {
      super();
      this.text = text2;
      this.lineStartOffsetByLineIdx = [];
      this.lineEndOffsetByLineIdx = [];
      this.lineStartOffsetByLineIdx.push(0);
      for (let i2 = 0; i2 < text2.length; i2++) {
        if (text2.charAt(i2) === "\n") {
          this.lineStartOffsetByLineIdx.push(i2 + 1);
          if (i2 > 0 && text2.charAt(i2 - 1) === "\r") {
            this.lineEndOffsetByLineIdx.push(i2 - 1);
          } else {
            this.lineEndOffsetByLineIdx.push(i2);
          }
        }
      }
      this.lineEndOffsetByLineIdx.push(text2.length);
    }
    getOffset(position) {
      const valPos = this._validatePosition(position);
      return this.lineStartOffsetByLineIdx[valPos.lineNumber - 1] + valPos.column - 1;
    }
    _validatePosition(position) {
      if (position.lineNumber < 1) {
        return new Position$1(1, 1);
      }
      const lineCount = this.textLength.lineCount + 1;
      if (position.lineNumber > lineCount) {
        const lineLength2 = this.getLineLength(lineCount);
        return new Position$1(lineCount, lineLength2 + 1);
      }
      if (position.column < 1) {
        return new Position$1(position.lineNumber, 1);
      }
      const lineLength = this.getLineLength(position.lineNumber);
      if (position.column - 1 > lineLength) {
        return new Position$1(position.lineNumber, lineLength + 1);
      }
      return position;
    }
    getPosition(offset) {
      const idx = findLastIdxMonotonous(this.lineStartOffsetByLineIdx, (i2) => i2 <= offset);
      const lineNumber = idx + 1;
      const column = offset - this.lineStartOffsetByLineIdx[idx] + 1;
      return new Position$1(lineNumber, column);
    }
    get textLength() {
      const lineIdx = this.lineStartOffsetByLineIdx.length - 1;
      return new Deps.deps.TextLength(lineIdx, this.text.length - this.lineStartOffsetByLineIdx[lineIdx]);
    }
    getLineLength(lineNumber) {
      return this.lineEndOffsetByLineIdx[lineNumber - 1] - this.lineStartOffsetByLineIdx[lineNumber - 1];
    }
  }
  class AbstractText {
    constructor() {
      this._transformer = void 0;
    }
    get endPositionExclusive() {
      return this.length.addToPosition(new Position$1(1, 1));
    }
    get lineRange() {
      return this.length.toLineRange();
    }
    getValue() {
      return this.getValueOfRange(this.length.toRange());
    }
    getValueOfOffsetRange(range2) {
      return this.getValueOfRange(this.getTransformer().getRange(range2));
    }
    getLineLength(lineNumber) {
      return this.getValueOfRange(new Range$2(lineNumber, 1, lineNumber, Number.MAX_SAFE_INTEGER)).length;
    }
    getTransformer() {
      if (!this._transformer) {
        this._transformer = new PositionOffsetTransformer(this.getValue());
      }
      return this._transformer;
    }
    getLineAt(lineNumber) {
      return this.getValueOfRange(new Range$2(lineNumber, 1, lineNumber, Number.MAX_SAFE_INTEGER));
    }
  }
  class LineBasedText extends AbstractText {
    constructor(_getLineContent, _lineCount) {
      assert(_lineCount >= 1);
      super();
      this._getLineContent = _getLineContent;
      this._lineCount = _lineCount;
    }
    getValueOfRange(range2) {
      if (range2.startLineNumber === range2.endLineNumber) {
        return this._getLineContent(range2.startLineNumber).substring(range2.startColumn - 1, range2.endColumn - 1);
      }
      let result = this._getLineContent(range2.startLineNumber).substring(range2.startColumn - 1);
      for (let i2 = range2.startLineNumber + 1; i2 < range2.endLineNumber; i2++) {
        result += "\n" + this._getLineContent(i2);
      }
      result += "\n" + this._getLineContent(range2.endLineNumber).substring(0, range2.endColumn - 1);
      return result;
    }
    getLineLength(lineNumber) {
      return this._getLineContent(lineNumber).length;
    }
    get length() {
      const lastLine = this._getLineContent(this._lineCount);
      return new TextLength(this._lineCount - 1, lastLine.length);
    }
  }
  class ArrayText extends LineBasedText {
    constructor(lines) {
      super((lineNumber) => lines[lineNumber - 1], lines.length);
    }
  }
  class StringText extends AbstractText {
    constructor(value) {
      super();
      this.value = value;
      this._t = new PositionOffsetTransformer(this.value);
    }
    getValueOfRange(range2) {
      return this._t.getOffsetRange(range2).substring(this.value);
    }
    get length() {
      return this._t.textLength;
    }
    // Override the getTransformer method to return the cached transformer
    getTransformer() {
      return this._t;
    }
  }
  class TextEdit {
    static fromStringEdit(edit2, initialState) {
      const edits = edit2.replacements.map((e) => TextReplacement.fromStringReplacement(e, initialState));
      return new TextEdit(edits);
    }
    static fromParallelReplacementsUnsorted(replacements) {
      const r = replacements.slice().sort(compareBy((i2) => i2.range, Range$2.compareRangesUsingStarts));
      return new TextEdit(r);
    }
    constructor(replacements) {
      this.replacements = replacements;
      assertFn(() => checkAdjacentItems(replacements, (a, b) => a.range.getEndPosition().isBeforeOrEqual(b.range.getStartPosition())));
    }
    mapPosition(position) {
      let lineDelta = 0;
      let curLine = 0;
      let columnDeltaInCurLine = 0;
      for (const replacement of this.replacements) {
        const start = replacement.range.getStartPosition();
        if (position.isBeforeOrEqual(start)) {
          break;
        }
        const end = replacement.range.getEndPosition();
        const len = TextLength.ofText(replacement.text);
        if (position.isBefore(end)) {
          const startPos = new Position$1(start.lineNumber + lineDelta, start.column + (start.lineNumber + lineDelta === curLine ? columnDeltaInCurLine : 0));
          const endPos = len.addToPosition(startPos);
          return rangeFromPositions(startPos, endPos);
        }
        if (start.lineNumber + lineDelta !== curLine) {
          columnDeltaInCurLine = 0;
        }
        lineDelta += len.lineCount - (replacement.range.endLineNumber - replacement.range.startLineNumber);
        if (len.lineCount === 0) {
          if (end.lineNumber !== start.lineNumber) {
            columnDeltaInCurLine += len.columnCount - (end.column - 1);
          } else {
            columnDeltaInCurLine += len.columnCount - (end.column - start.column);
          }
        } else {
          columnDeltaInCurLine = len.columnCount;
        }
        curLine = end.lineNumber + lineDelta;
      }
      return new Position$1(position.lineNumber + lineDelta, position.column + (position.lineNumber + lineDelta === curLine ? columnDeltaInCurLine : 0));
    }
    mapRange(range2) {
      function getStart(p) {
        return p instanceof Position$1 ? p : p.getStartPosition();
      }
      function getEnd(p) {
        return p instanceof Position$1 ? p : p.getEndPosition();
      }
      const start = getStart(this.mapPosition(range2.getStartPosition()));
      const end = getEnd(this.mapPosition(range2.getEndPosition()));
      return rangeFromPositions(start, end);
    }
    apply(text2) {
      let result = "";
      let lastEditEnd = new Position$1(1, 1);
      for (const replacement of this.replacements) {
        const editRange = replacement.range;
        const editStart = editRange.getStartPosition();
        const editEnd = editRange.getEndPosition();
        const r2 = rangeFromPositions(lastEditEnd, editStart);
        if (!r2.isEmpty()) {
          result += text2.getValueOfRange(r2);
        }
        result += replacement.text;
        lastEditEnd = editEnd;
      }
      const r = rangeFromPositions(lastEditEnd, text2.endPositionExclusive);
      if (!r.isEmpty()) {
        result += text2.getValueOfRange(r);
      }
      return result;
    }
    applyToString(str) {
      const strText = new StringText(str);
      return this.apply(strText);
    }
    getNewRanges() {
      const newRanges = [];
      let previousEditEndLineNumber = 0;
      let lineOffset = 0;
      let columnOffset = 0;
      for (const replacement of this.replacements) {
        const textLength = TextLength.ofText(replacement.text);
        const newRangeStart = Position$1.lift({
          lineNumber: replacement.range.startLineNumber + lineOffset,
          column: replacement.range.startColumn + (replacement.range.startLineNumber === previousEditEndLineNumber ? columnOffset : 0)
        });
        const newRange = textLength.createRange(newRangeStart);
        newRanges.push(newRange);
        lineOffset = newRange.endLineNumber - replacement.range.endLineNumber;
        columnOffset = newRange.endColumn - replacement.range.endColumn;
        previousEditEndLineNumber = replacement.range.endLineNumber;
      }
      return newRanges;
    }
    toReplacement(text2) {
      if (this.replacements.length === 0) {
        throw new BugIndicatingError();
      }
      if (this.replacements.length === 1) {
        return this.replacements[0];
      }
      const startPos = this.replacements[0].range.getStartPosition();
      const endPos = this.replacements[this.replacements.length - 1].range.getEndPosition();
      let newText = "";
      for (let i2 = 0; i2 < this.replacements.length; i2++) {
        const curEdit = this.replacements[i2];
        newText += curEdit.text;
        if (i2 < this.replacements.length - 1) {
          const nextEdit = this.replacements[i2 + 1];
          const gapRange = Range$2.fromPositions(curEdit.range.getEndPosition(), nextEdit.range.getStartPosition());
          const gapText = text2.getValueOfRange(gapRange);
          newText += gapText;
        }
      }
      return new TextReplacement(Range$2.fromPositions(startPos, endPos), newText);
    }
    toString(text2) {
      if (text2 === void 0) {
        return this.replacements.map((edit2) => edit2.toString()).join("\n");
      }
      if (typeof text2 === "string") {
        return this.toString(new StringText(text2));
      }
      if (this.replacements.length === 0) {
        return "";
      }
      return this.replacements.map((r) => {
        const maxLength = 10;
        const originalText = text2.getValueOfRange(r.range);
        const beforeRange = Range$2.fromPositions(new Position$1(Math.max(1, r.range.startLineNumber - 1), 1), r.range.getStartPosition());
        let beforeText = text2.getValueOfRange(beforeRange);
        if (beforeText.length > maxLength) {
          beforeText = "..." + beforeText.substring(beforeText.length - maxLength);
        }
        const afterRange = Range$2.fromPositions(r.range.getEndPosition(), new Position$1(r.range.endLineNumber + 1, 1));
        let afterText = text2.getValueOfRange(afterRange);
        if (afterText.length > maxLength) {
          afterText = afterText.substring(0, maxLength) + "...";
        }
        let replacedText = originalText;
        if (replacedText.length > maxLength) {
          const halfMax = Math.floor(maxLength / 2);
          replacedText = replacedText.substring(0, halfMax) + "..." + replacedText.substring(replacedText.length - halfMax);
        }
        let newText = r.text;
        if (newText.length > maxLength) {
          const halfMax = Math.floor(maxLength / 2);
          newText = newText.substring(0, halfMax) + "..." + newText.substring(newText.length - halfMax);
        }
        if (replacedText.length === 0) {
          return `${beforeText}❰${newText}❱${afterText}`;
        }
        return `${beforeText}❰${replacedText}↦${newText}❱${afterText}`;
      }).join("\n");
    }
  }
  class TextReplacement {
    static joinReplacements(replacements, initialValue) {
      if (replacements.length === 0) {
        throw new BugIndicatingError();
      }
      if (replacements.length === 1) {
        return replacements[0];
      }
      const startPos = replacements[0].range.getStartPosition();
      const endPos = replacements[replacements.length - 1].range.getEndPosition();
      let newText = "";
      for (let i2 = 0; i2 < replacements.length; i2++) {
        const curEdit = replacements[i2];
        newText += curEdit.text;
        if (i2 < replacements.length - 1) {
          const nextEdit = replacements[i2 + 1];
          const gapRange = Range$2.fromPositions(curEdit.range.getEndPosition(), nextEdit.range.getStartPosition());
          const gapText = initialValue.getValueOfRange(gapRange);
          newText += gapText;
        }
      }
      return new TextReplacement(Range$2.fromPositions(startPos, endPos), newText);
    }
    static fromStringReplacement(replacement, initialState) {
      return new TextReplacement(initialState.getTransformer().getRange(replacement.replaceRange), replacement.newText);
    }
    static delete(range2) {
      return new TextReplacement(range2, "");
    }
    constructor(range2, text2) {
      this.range = range2;
      this.text = text2;
    }
    get isEmpty() {
      return this.range.isEmpty() && this.text.length === 0;
    }
    static equals(first2, second) {
      return first2.range.equalsRange(second.range) && first2.text === second.text;
    }
    equals(other) {
      return TextReplacement.equals(this, other);
    }
    removeCommonPrefixAndSuffix(text2) {
      const prefix = this.removeCommonPrefix(text2);
      const suffix = prefix.removeCommonSuffix(text2);
      return suffix;
    }
    removeCommonPrefix(text2) {
      const normalizedOriginalText = text2.getValueOfRange(this.range).replaceAll("\r\n", "\n");
      const normalizedModifiedText = this.text.replaceAll("\r\n", "\n");
      const commonPrefixLen = commonPrefixLength(normalizedOriginalText, normalizedModifiedText);
      const start = TextLength.ofText(normalizedOriginalText.substring(0, commonPrefixLen)).addToPosition(this.range.getStartPosition());
      const newText = normalizedModifiedText.substring(commonPrefixLen);
      const range2 = Range$2.fromPositions(start, this.range.getEndPosition());
      return new TextReplacement(range2, newText);
    }
    removeCommonSuffix(text2) {
      const normalizedOriginalText = text2.getValueOfRange(this.range).replaceAll("\r\n", "\n");
      const normalizedModifiedText = this.text.replaceAll("\r\n", "\n");
      const commonSuffixLen = commonSuffixLength(normalizedOriginalText, normalizedModifiedText);
      const end = TextLength.ofText(normalizedOriginalText.substring(0, normalizedOriginalText.length - commonSuffixLen)).addToPosition(this.range.getStartPosition());
      const newText = normalizedModifiedText.substring(0, normalizedModifiedText.length - commonSuffixLen);
      const range2 = Range$2.fromPositions(this.range.getStartPosition(), end);
      return new TextReplacement(range2, newText);
    }
    toString() {
      const start = this.range.getStartPosition();
      const end = this.range.getEndPosition();
      return `(${start.lineNumber},${start.column} -> ${end.lineNumber},${end.column}): "${this.text}"`;
    }
  }
  function rangeFromPositions(start, end) {
    if (start.lineNumber === end.lineNumber && start.column === Number.MAX_SAFE_INTEGER) {
      return Range$2.fromPositions(end, end);
    } else if (!start.isBeforeOrEqual(end)) {
      throw new BugIndicatingError("start must be before end");
    }
    return new Range$2(start.lineNumber, start.column, end.lineNumber, end.column);
  }
  _setPositionOffsetTransformerDependencies({
    StringEdit,
    StringReplacement,
    TextReplacement,
    TextEdit,
    TextLength
  });
  var __decorate$2T = 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$2O = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  let SimpleScreenReaderContent = class SimpleScreenReaderContent extends Disposable {
    constructor(_domNode, _context, _viewController, _accessibilityService) {
      super();
      this._domNode = _domNode;
      this._context = _context;
      this._viewController = _viewController;
      this._accessibilityService = _accessibilityService;
      this._selectionChangeListener = this._register(new MutableDisposable());
      this._accessibilityPageSize = 1;
      this._ignoreSelectionChangeTime = 0;
      this._strategy = new SimplePagedScreenReaderStrategy();
      this.onConfigurationChanged(this._context.configuration.options);
    }
    updateScreenReaderContent(primarySelection) {
      const domNode = this._domNode.domNode;
      const focusedElement = getActiveWindow().document.activeElement;
      if (!focusedElement || focusedElement !== domNode) {
        return;
      }
      const isScreenReaderOptimized = this._accessibilityService.isScreenReaderOptimized();
      if (isScreenReaderOptimized) {
        this._state = this._getScreenReaderContentState(primarySelection);
        if (domNode.textContent !== this._state.value) {
          this._setIgnoreSelectionChangeTime("setValue");
          domNode.textContent = this._state.value;
        }
        const selection = getActiveWindow().document.getSelection();
        if (!selection) {
          return;
        }
        const data = this._getScreenReaderRange(this._state.selectionStart, this._state.selectionEnd);
        if (!data) {
          return;
        }
        this._setIgnoreSelectionChangeTime("setRange");
        selection.setBaseAndExtent(data.anchorNode, data.anchorOffset, data.focusNode, data.focusOffset);
      } else {
        this._state = void 0;
        this._setIgnoreSelectionChangeTime("setValue");
        this._domNode.domNode.textContent = "";
      }
    }
    updateScrollTop(primarySelection) {
      if (!this._state) {
        return;
      }
      const viewLayout = this._context.viewModel.viewLayout;
      const stateStartLineNumber = this._state.startPositionWithinEditor.lineNumber;
      const verticalOffsetOfStateStartLineNumber = viewLayout.getVerticalOffsetForLineNumber(stateStartLineNumber);
      const verticalOffsetOfPositionLineNumber = viewLayout.getVerticalOffsetForLineNumber(primarySelection.positionLineNumber);
      this._domNode.domNode.scrollTop = verticalOffsetOfPositionLineNumber - verticalOffsetOfStateStartLineNumber;
    }
    onFocusChange(newFocusValue) {
      if (newFocusValue) {
        this._selectionChangeListener.value = this._setSelectionChangeListener();
      } else {
        this._selectionChangeListener.value = void 0;
      }
    }
    onConfigurationChanged(options) {
      this._accessibilityPageSize = options.get(
        3
        /* EditorOption.accessibilityPageSize */
      );
    }
    onWillCut() {
      this._setIgnoreSelectionChangeTime("onCut");
    }
    onWillPaste() {
      this._setIgnoreSelectionChangeTime("onWillPaste");
    }
    // --- private methods
    _setIgnoreSelectionChangeTime(reason) {
      this._ignoreSelectionChangeTime = Date.now();
    }
    _setSelectionChangeListener() {
      let previousSelectionChangeEventTime = 0;
      return addDisposableListener(this._domNode.domNode.ownerDocument, "selectionchange", () => {
        const isScreenReaderOptimized = this._accessibilityService.isScreenReaderOptimized();
        if (!this._state || !isScreenReaderOptimized || !IME.enabled) {
          return;
        }
        const activeElement = getActiveWindow().document.activeElement;
        const isFocused = activeElement === this._domNode.domNode;
        if (!isFocused) {
          return;
        }
        const selection = getActiveWindow().document.getSelection();
        if (!selection) {
          return;
        }
        const rangeCount = selection.rangeCount;
        if (rangeCount === 0) {
          return;
        }
        const range2 = selection.getRangeAt(0);
        const now = Date.now();
        const delta1 = now - previousSelectionChangeEventTime;
        previousSelectionChangeEventTime = now;
        if (delta1 < 5) {
          return;
        }
        const delta2 = now - this._ignoreSelectionChangeTime;
        this._ignoreSelectionChangeTime = 0;
        if (delta2 < 100) {
          return;
        }
        this._viewController.setSelection(this._getEditorSelectionFromDomRange(this._context, this._state, selection.direction, range2));
      });
    }
    _getScreenReaderContentState(primarySelection) {
      const state = this._strategy.fromEditorSelection(
        this._context.viewModel,
        primarySelection,
        this._accessibilityPageSize,
        this._accessibilityService.getAccessibilitySupport() === 0
        /* AccessibilitySupport.Unknown */
      );
      const endPosition = this._context.viewModel.model.getPositionAt(Infinity);
      let value = state.value;
      if (endPosition.column === 1 && primarySelection.getEndPosition().equals(endPosition)) {
        value += "\n";
      }
      state.value = value;
      return state;
    }
    _getScreenReaderRange(selectionOffsetStart, selectionOffsetEnd) {
      const textContent = this._domNode.domNode.firstChild;
      if (!textContent) {
        return;
      }
      const range2 = new globalThis.Range();
      range2.setStart(textContent, selectionOffsetStart);
      range2.setEnd(textContent, selectionOffsetEnd);
      return {
        anchorNode: textContent,
        anchorOffset: selectionOffsetStart,
        focusNode: textContent,
        focusOffset: selectionOffsetEnd
      };
    }
    _getEditorSelectionFromDomRange(context, state, direction, range2) {
      const viewModel = context.viewModel;
      const model = viewModel.model;
      const coordinatesConverter = viewModel.coordinatesConverter;
      const modelScreenReaderContentStartPositionWithinEditor = coordinatesConverter.convertViewPositionToModelPosition(state.startPositionWithinEditor);
      const offsetOfStartOfScreenReaderContent = model.getOffsetAt(modelScreenReaderContentStartPositionWithinEditor);
      let offsetOfSelectionStart = range2.startOffset + offsetOfStartOfScreenReaderContent;
      let offsetOfSelectionEnd = range2.endOffset + offsetOfStartOfScreenReaderContent;
      const modelUsesCRLF = model.getEndOfLineSequence() === 1;
      if (modelUsesCRLF) {
        const screenReaderContentText = state.value;
        const offsetTransformer = new PositionOffsetTransformer(screenReaderContentText);
        const positionOfStartWithinText = offsetTransformer.getPosition(range2.startOffset);
        const positionOfEndWithinText = offsetTransformer.getPosition(range2.endOffset);
        offsetOfSelectionStart += positionOfStartWithinText.lineNumber - 1;
        offsetOfSelectionEnd += positionOfEndWithinText.lineNumber - 1;
      }
      const positionOfSelectionStart = model.getPositionAt(offsetOfSelectionStart);
      const positionOfSelectionEnd = model.getPositionAt(offsetOfSelectionEnd);
      const selectionStart = direction === "forward" ? positionOfSelectionStart : positionOfSelectionEnd;
      const selectionEnd = direction === "forward" ? positionOfSelectionEnd : positionOfSelectionStart;
      return Selection$1.fromPositions(selectionStart, selectionEnd);
    }
  };
  SimpleScreenReaderContent = __decorate$2T([
    __param$2O(3, IAccessibilityService)
  ], SimpleScreenReaderContent);
  var __decorate$2S = 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$2N = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  let ScreenReaderSupport = class ScreenReaderSupport extends Disposable {
    constructor(_domNode, _context, _viewController, _keybindingService, _accessibilityService) {
      super();
      this._domNode = _domNode;
      this._context = _context;
      this._viewController = _viewController;
      this._keybindingService = _keybindingService;
      this._accessibilityService = _accessibilityService;
      this._contentLeft = 1;
      this._contentWidth = 1;
      this._contentHeight = 1;
      this._divWidth = 1;
      this._primarySelection = new Selection$1(1, 1, 1, 1);
      this._primaryCursorVisibleRange = null;
      this._state = this._register(new MutableDisposable());
      this._instantiateScreenReaderContent();
      this._updateConfigurationSettings();
      this._updateDomAttributes();
    }
    onWillPaste() {
      this._state.value?.onWillPaste();
    }
    onWillCut() {
      this._state.value?.onWillCut();
    }
    handleFocusChange(newFocusValue) {
      this._state.value?.onFocusChange(newFocusValue);
      this.writeScreenReaderContent();
    }
    onConfigurationChanged(e) {
      this._instantiateScreenReaderContent();
      this._updateConfigurationSettings();
      this._updateDomAttributes();
      if (e.hasChanged(
        2
        /* EditorOption.accessibilitySupport */
      )) {
        this.writeScreenReaderContent();
      }
    }
    _instantiateScreenReaderContent() {
      const renderRichContent = this._context.configuration.options.get(
        107
        /* EditorOption.renderRichScreenReaderContent */
      );
      if (this._renderRichContent !== renderRichContent) {
        this._renderRichContent = renderRichContent;
        this._state.value = this._createScreenReaderContent(renderRichContent);
      }
    }
    _createScreenReaderContent(renderRichContent) {
      if (renderRichContent) {
        return new RichScreenReaderContent(this._domNode, this._context, this._viewController, this._accessibilityService);
      } else {
        return new SimpleScreenReaderContent(this._domNode, this._context, this._viewController, this._accessibilityService);
      }
    }
    _updateConfigurationSettings() {
      const options = this._context.configuration.options;
      const layoutInfo = options.get(
        165
        /* EditorOption.layoutInfo */
      );
      const wrappingColumn = layoutInfo.wrappingColumn;
      this._contentLeft = layoutInfo.contentLeft;
      this._contentWidth = layoutInfo.contentWidth;
      this._contentHeight = layoutInfo.height;
      this._fontInfo = options.get(
        59
        /* EditorOption.fontInfo */
      );
      this._divWidth = Math.round(wrappingColumn * this._fontInfo.typicalHalfwidthCharacterWidth);
      this._state.value?.onConfigurationChanged(options);
    }
    _updateDomAttributes() {
      const options = this._context.configuration.options;
      this._domNode.domNode.setAttribute("role", "textbox");
      this._domNode.domNode.setAttribute("aria-required", options.get(
        9
        /* EditorOption.ariaRequired */
      ) ? "true" : "false");
      this._domNode.domNode.setAttribute("aria-multiline", "true");
      this._domNode.domNode.setAttribute("aria-autocomplete", options.get(
        104
        /* EditorOption.readOnly */
      ) ? "none" : "both");
      this._domNode.domNode.setAttribute("aria-roledescription", localize(60, "editor"));
      this._domNode.domNode.setAttribute("aria-label", ariaLabelForScreenReaderContent(options, this._keybindingService));
      const tabSize = this._context.viewModel.model.getOptions().tabSize;
      const spaceWidth = options.get(
        59
        /* EditorOption.fontInfo */
      ).spaceWidth;
      this._domNode.domNode.style.tabSize = `${tabSize * spaceWidth}px`;
      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;
      this._domNode.domNode.style.textWrap = wordWrap === "off" ? "nowrap" : "wrap";
    }
    onCursorStateChanged(e) {
      this._primarySelection = e.selections[0] ?? new Selection$1(1, 1, 1, 1);
    }
    prepareRender(ctx) {
      this.writeScreenReaderContent();
      this._primaryCursorVisibleRange = ctx.visibleRangeForPosition(this._primarySelection.getPosition());
    }
    render(ctx) {
      if (!this._primaryCursorVisibleRange) {
        this._renderAtTopLeft();
        return;
      }
      const editorScrollLeft = this._context.viewLayout.getCurrentScrollLeft();
      const left = this._contentLeft + this._primaryCursorVisibleRange.left - editorScrollLeft;
      if (left < this._contentLeft || left > this._contentLeft + this._contentWidth) {
        this._renderAtTopLeft();
        return;
      }
      const editorScrollTop = this._context.viewLayout.getCurrentScrollTop();
      const positionLineNumber = this._primarySelection.positionLineNumber;
      const top = this._context.viewLayout.getVerticalOffsetForLineNumber(positionLineNumber) - editorScrollTop;
      if (top < 0 || top > this._contentHeight) {
        this._renderAtTopLeft();
        return;
      }
      const lineHeight = this._context.viewLayout.getLineHeightForLineNumber(positionLineNumber);
      this._doRender(top, this._contentLeft, this._divWidth, lineHeight);
      this._state.value?.updateScrollTop(this._primarySelection);
    }
    _renderAtTopLeft() {
      this._doRender(0, 0, this._contentWidth, 1);
    }
    _doRender(top, left, width2, height) {
      applyFontInfo(this._domNode, this._fontInfo);
      this._domNode.setTop(top);
      this._domNode.setLeft(left);
      this._domNode.setWidth(width2);
      this._domNode.setHeight(height);
      this._domNode.setLineHeight(height);
    }
    setAriaOptions(options) {
      if (options.activeDescendant) {
        this._domNode.setAttribute("aria-haspopup", "true");
        this._domNode.setAttribute("aria-autocomplete", "list");
        this._domNode.setAttribute("aria-activedescendant", options.activeDescendant);
      } else {
        this._domNode.setAttribute("aria-haspopup", "false");
        this._domNode.setAttribute("aria-autocomplete", "both");
        this._domNode.removeAttribute("aria-activedescendant");
      }
      if (options.role) {
        this._domNode.setAttribute("role", options.role);
      }
    }
    writeScreenReaderContent() {
      this._state.value?.updateScreenReaderContent(this._primarySelection);
    }
  };
  ScreenReaderSupport = __decorate$2S([
    __param$2N(3, IKeybindingService),
    __param$2N(4, IAccessibilityService)
  ], ScreenReaderSupport);
  var EditContext;
  (function(EditContext2) {
    function create2(window2, options) {
      return new window2.EditContext(options);
    }
    EditContext2.create = create2;
  })(EditContext || (EditContext = {}));
  class NativeEditContextRegistryImpl {
    constructor() {
      this._nativeEditContextMapping = /* @__PURE__ */ new Map();
    }
    register(ownerID, nativeEditContext) {
      this._nativeEditContextMapping.set(ownerID, nativeEditContext);
      return {
        dispose: () => {
          this._nativeEditContextMapping.delete(ownerID);
        }
      };
    }
    get(ownerID) {
      return this._nativeEditContextMapping.get(ownerID);
    }
  }
  const NativeEditContextRegistry = new NativeEditContextRegistryImpl();
  var __decorate$2R = 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$2M = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  var CompositionClassName;
  (function(CompositionClassName2) {
    CompositionClassName2["NONE"] = "edit-context-composition-none";
    CompositionClassName2["SECONDARY"] = "edit-context-composition-secondary";
    CompositionClassName2["PRIMARY"] = "edit-context-composition-primary";
  })(CompositionClassName || (CompositionClassName = {}));
  let NativeEditContext = class NativeEditContext extends AbstractEditContext {
    constructor(ownerID, context, overflowGuardContainer, _viewController, _visibleRangeProvider, instantiationService, logService) {
      super(context);
      this._viewController = _viewController;
      this._visibleRangeProvider = _visibleRangeProvider;
      this.logService = logService;
      this._previousEditContextSelection = new OffsetRange(0, 0);
      this._editContextPrimarySelection = new Selection$1(1, 1, 1, 1);
      this._decorations = [];
      this._primarySelection = new Selection$1(1, 1, 1, 1);
      this._targetWindowId = -1;
      this._scrollTop = 0;
      this._scrollLeft = 0;
      this._linesVisibleRanges = null;
      this.domNode = new FastDomNode(document.createElement("div"));
      this.domNode.setClassName(`native-edit-context`);
      this._imeTextArea = new FastDomNode(document.createElement("textarea"));
      this._imeTextArea.setClassName(`ime-text-area`);
      this._imeTextArea.setAttribute("readonly", "true");
      this._imeTextArea.setAttribute("tabindex", "-1");
      this._imeTextArea.setAttribute("aria-hidden", "true");
      this.domNode.setAttribute("autocorrect", "off");
      this.domNode.setAttribute("autocapitalize", "off");
      this.domNode.setAttribute("autocomplete", "off");
      this.domNode.setAttribute("spellcheck", "false");
      this._updateDomAttributes();
      overflowGuardContainer.appendChild(this.domNode);
      overflowGuardContainer.appendChild(this._imeTextArea);
      this._parent = overflowGuardContainer.domNode;
      this._focusTracker = this._register(new FocusTracker(logService, this.domNode.domNode, (newFocusValue) => {
        logService.trace("NativeEditContext#handleFocusChange : ", newFocusValue);
        this._screenReaderSupport.handleFocusChange(newFocusValue);
        this._context.viewModel.setHasFocus(newFocusValue);
      }));
      const window2 = getWindow(this.domNode.domNode);
      this._editContext = EditContext.create(window2);
      this.setEditContextOnDomNode();
      this._screenReaderSupport = this._register(instantiationService.createInstance(ScreenReaderSupport, this.domNode, context, this._viewController));
      this._register(addDisposableListener(this.domNode.domNode, "copy", (e) => {
        this.logService.trace("NativeEditContext#copy");
        this._ensureClipboardGetsEditorSelection(e);
      }));
      this._register(addDisposableListener(this.domNode.domNode, "cut", (e) => {
        this.logService.trace("NativeEditContext#cut");
        this._screenReaderSupport.onWillCut();
        this._ensureClipboardGetsEditorSelection(e);
        this.logService.trace("NativeEditContext#cut (before viewController.cut)");
        this._viewController.cut();
      }));
      this._register(addDisposableListener(this.domNode.domNode, "keyup", (e) => this._onKeyUp(e)));
      this._register(addDisposableListener(this.domNode.domNode, "keydown", async (e) => this._onKeyDown(e)));
      this._register(addDisposableListener(this._imeTextArea.domNode, "keyup", (e) => this._onKeyUp(e)));
      this._register(addDisposableListener(this._imeTextArea.domNode, "keydown", async (e) => this._onKeyDown(e)));
      this._register(addDisposableListener(this.domNode.domNode, "beforeinput", async (e) => {
        if (e.inputType === "insertParagraph" || e.inputType === "insertLineBreak") {
          this._onType(this._viewController, { text: "\n", replacePrevCharCnt: 0, replaceNextCharCnt: 0, positionDelta: 0 });
        }
      }));
      this._register(addDisposableListener(this.domNode.domNode, "paste", (e) => {
        this.logService.trace("NativeEditContext#paste");
        e.preventDefault();
        if (!e.clipboardData) {
          return;
        }
        let [text2, metadata] = ClipboardEventUtils.getTextData(e.clipboardData);
        this.logService.trace("NativeEditContext#paste with id : ", metadata?.id, " with text.length: ", text2.length);
        if (!text2) {
          return;
        }
        metadata = metadata || InMemoryClipboardMetadataManager.INSTANCE.get(text2);
        let pasteOnNewLine = false;
        let multicursorText = null;
        let mode = null;
        if (metadata) {
          const options = this._context.configuration.options;
          const emptySelectionClipboard = options.get(
            45
            /* EditorOption.emptySelectionClipboard */
          );
          pasteOnNewLine = emptySelectionClipboard && !!metadata.isFromEmptySelection;
          multicursorText = typeof metadata.multicursorText !== "undefined" ? metadata.multicursorText : null;
          mode = metadata.mode;
        }
        this.logService.trace("NativeEditContext#paste (before viewController.paste)");
        this._viewController.paste(text2, pasteOnNewLine, multicursorText, mode);
      }));
      this._register(editContextAddDisposableListener(this._editContext, "textformatupdate", (e) => this._handleTextFormatUpdate(e)));
      this._register(editContextAddDisposableListener(this._editContext, "characterboundsupdate", (e) => this._updateCharacterBounds(e)));
      let highSurrogateCharacter;
      this._register(editContextAddDisposableListener(this._editContext, "textupdate", (e) => {
        const text2 = e.text;
        if (text2.length === 1) {
          const charCode = text2.charCodeAt(0);
          if (isHighSurrogate(charCode)) {
            highSurrogateCharacter = text2;
            return;
          }
          if (isLowSurrogate(charCode) && highSurrogateCharacter) {
            const textUpdateEvent = {
              text: highSurrogateCharacter + text2,
              selectionEnd: e.selectionEnd,
              selectionStart: e.selectionStart,
              updateRangeStart: e.updateRangeStart - 1,
              updateRangeEnd: e.updateRangeEnd - 1
            };
            highSurrogateCharacter = void 0;
            this._emitTypeEvent(this._viewController, textUpdateEvent);
            return;
          }
        }
        this._emitTypeEvent(this._viewController, e);
      }));
      this._register(editContextAddDisposableListener(this._editContext, "compositionstart", (e) => {
        this._updateEditContext();
        this._viewController.compositionStart();
        this._context.viewModel.onCompositionStart();
      }));
      this._register(editContextAddDisposableListener(this._editContext, "compositionend", (e) => {
        this._updateEditContext();
        this._viewController.compositionEnd();
        this._context.viewModel.onCompositionEnd();
      }));
      let reenableTracking = false;
      this._register(IME.onDidChange(() => {
        if (IME.enabled && reenableTracking) {
          this._focusTracker.resume();
          this.domNode.focus();
          reenableTracking = false;
        }
        if (!IME.enabled && this.isFocused()) {
          this._focusTracker.pause();
          this._imeTextArea.focus();
          reenableTracking = true;
        }
      }));
      this._register(NativeEditContextRegistry.register(ownerID, this));
    }
    // --- Public methods ---
    dispose() {
      this.domNode.domNode.editContext = void 0;
      this.domNode.domNode.blur();
      this.domNode.domNode.remove();
      this._imeTextArea.domNode.remove();
      super.dispose();
    }
    setAriaOptions(options) {
      this._screenReaderSupport.setAriaOptions(options);
    }
    /* Last rendered data needed for correct hit-testing and determining the mouse position.
     * Without this, the selection will blink as incorrect mouse position is calculated */
    getLastRenderData() {
      return this._primarySelection.getPosition();
    }
    prepareRender(ctx) {
      this._screenReaderSupport.prepareRender(ctx);
      this._updateSelectionAndControlBoundsData(ctx);
    }
    onDidRender() {
      this._updateSelectionAndControlBoundsAfterRender();
    }
    render(ctx) {
      this._screenReaderSupport.render(ctx);
    }
    onCursorStateChanged(e) {
      this._primarySelection = e.modelSelections[0] ?? new Selection$1(1, 1, 1, 1);
      this._screenReaderSupport.onCursorStateChanged(e);
      this._updateEditContext();
      return true;
    }
    onConfigurationChanged(e) {
      this._screenReaderSupport.onConfigurationChanged(e);
      this._updateDomAttributes();
      return true;
    }
    onDecorationsChanged(e) {
      return true;
    }
    onFlushed(e) {
      return true;
    }
    onLinesChanged(e) {
      this._updateEditContextOnLineChange(e.fromLineNumber, e.fromLineNumber + e.count - 1);
      return true;
    }
    onLinesDeleted(e) {
      this._updateEditContextOnLineChange(e.fromLineNumber, e.toLineNumber);
      return true;
    }
    onLinesInserted(e) {
      this._updateEditContextOnLineChange(e.fromLineNumber, e.toLineNumber);
      return true;
    }
    _updateEditContextOnLineChange(fromLineNumber, toLineNumber) {
      if (this._editContextPrimarySelection.endLineNumber < fromLineNumber || this._editContextPrimarySelection.startLineNumber > toLineNumber) {
        return;
      }
      this._updateEditContext();
    }
    onScrollChanged(e) {
      this._scrollLeft = e.scrollLeft;
      this._scrollTop = e.scrollTop;
      return true;
    }
    onZonesChanged(e) {
      return true;
    }
    onWillPaste() {
      this.logService.trace("NativeEditContext#onWillPaste");
      this._onWillPaste();
    }
    _onWillPaste() {
      this._screenReaderSupport.onWillPaste();
    }
    onWillCopy() {
      this.logService.trace("NativeEditContext#onWillCopy");
      this.logService.trace("NativeEditContext#isFocused : ", this.domNode.domNode === getActiveElement());
    }
    writeScreenReaderContent() {
      this._screenReaderSupport.writeScreenReaderContent();
    }
    isFocused() {
      return this._focusTracker.isFocused;
    }
    focus() {
      this._focusTracker.focus();
      this.refreshFocusState();
    }
    refreshFocusState() {
      this._focusTracker.refreshFocusState();
    }
    // TODO: added as a workaround fix for https://github.com/microsoft/vscode/issues/229825
    // When this issue will be fixed the following should be removed.
    setEditContextOnDomNode() {
      const targetWindow = getWindow(this.domNode.domNode);
      const targetWindowId = getWindowId(targetWindow);
      if (this._targetWindowId !== targetWindowId) {
        this.domNode.domNode.editContext = this._editContext;
        this._targetWindowId = targetWindowId;
      }
    }
    // --- Private methods ---
    _onKeyUp(e) {
      this._viewController.emitKeyUp(new StandardKeyboardEvent(e));
    }
    _onKeyDown(e) {
      const standardKeyboardEvent = new StandardKeyboardEvent(e);
      if (standardKeyboardEvent.keyCode === 114) {
        standardKeyboardEvent.stopPropagation();
      }
      this._viewController.emitKeyDown(standardKeyboardEvent);
    }
    _updateDomAttributes() {
      const options = this._context.configuration.options;
      this.domNode.domNode.setAttribute("tabindex", String(options.get(
        140
        /* EditorOption.tabIndex */
      )));
    }
    _updateEditContext() {
      const editContextState = this._getNewEditContextState();
      if (!editContextState) {
        return;
      }
      this._editContext.updateText(0, Number.MAX_SAFE_INTEGER, editContextState.text ?? " ");
      this._editContext.updateSelection(editContextState.selectionStartOffset, editContextState.selectionEndOffset);
      this._editContextPrimarySelection = editContextState.editContextPrimarySelection;
      this._previousEditContextSelection = new OffsetRange(editContextState.selectionStartOffset, editContextState.selectionEndOffset);
    }
    _emitTypeEvent(viewController, e) {
      if (!this._editContext) {
        return;
      }
      const selectionEndOffset = this._previousEditContextSelection.endExclusive;
      const selectionStartOffset = this._previousEditContextSelection.start;
      this._previousEditContextSelection = new OffsetRange(e.selectionStart, e.selectionEnd);
      let replaceNextCharCnt = 0;
      let replacePrevCharCnt = 0;
      if (e.updateRangeEnd > selectionEndOffset) {
        replaceNextCharCnt = e.updateRangeEnd - selectionEndOffset;
      }
      if (e.updateRangeStart < selectionStartOffset) {
        replacePrevCharCnt = selectionStartOffset - e.updateRangeStart;
      }
      let text2 = "";
      if (selectionStartOffset < e.updateRangeStart) {
        text2 += this._editContext.text.substring(selectionStartOffset, e.updateRangeStart);
      }
      text2 += e.text;
      if (selectionEndOffset > e.updateRangeEnd) {
        text2 += this._editContext.text.substring(e.updateRangeEnd, selectionEndOffset);
      }
      let positionDelta = 0;
      if (e.selectionStart === e.selectionEnd && selectionStartOffset === selectionEndOffset) {
        positionDelta = e.selectionStart - (e.updateRangeStart + e.text.length);
      }
      const typeInput = {
        text: text2,
        replacePrevCharCnt,
        replaceNextCharCnt,
        positionDelta
      };
      this._onType(viewController, typeInput);
    }
    _onType(viewController, typeInput) {
      if (typeInput.replacePrevCharCnt || typeInput.replaceNextCharCnt || typeInput.positionDelta) {
        viewController.compositionType(typeInput.text, typeInput.replacePrevCharCnt, typeInput.replaceNextCharCnt, typeInput.positionDelta);
      } else {
        viewController.type(typeInput.text);
      }
    }
    _getNewEditContextState() {
      const editContextPrimarySelection = this._primarySelection;
      const model = this._context.viewModel.model;
      if (!model.isValidRange(editContextPrimarySelection)) {
        return;
      }
      const primarySelectionStartLine = editContextPrimarySelection.startLineNumber;
      const primarySelectionEndLine = editContextPrimarySelection.endLineNumber;
      const endColumnOfEndLineNumber = model.getLineMaxColumn(primarySelectionEndLine);
      const rangeOfText = new Range$2(primarySelectionStartLine, 1, primarySelectionEndLine, endColumnOfEndLineNumber);
      const text2 = model.getValueInRange(
        rangeOfText,
        0
        /* EndOfLinePreference.TextDefined */
      );
      const selectionStartOffset = editContextPrimarySelection.startColumn - 1;
      const selectionEndOffset = text2.length + editContextPrimarySelection.endColumn - endColumnOfEndLineNumber;
      return {
        text: text2,
        selectionStartOffset,
        selectionEndOffset,
        editContextPrimarySelection
      };
    }
    _editContextStartPosition() {
      return new Position$1(this._editContextPrimarySelection.startLineNumber, 1);
    }
    _handleTextFormatUpdate(e) {
      if (!this._editContext) {
        return;
      }
      const formats = e.getTextFormats();
      const editContextStartPosition = this._editContextStartPosition();
      const decorations = [];
      formats.forEach((f) => {
        const textModel = this._context.viewModel.model;
        const offsetOfEditContextText = textModel.getOffsetAt(editContextStartPosition);
        const startPositionOfDecoration = textModel.getPositionAt(offsetOfEditContextText + f.rangeStart);
        const endPositionOfDecoration = textModel.getPositionAt(offsetOfEditContextText + f.rangeEnd);
        const decorationRange = Range$2.fromPositions(startPositionOfDecoration, endPositionOfDecoration);
        const thickness = f.underlineThickness.toLowerCase();
        let decorationClassName = CompositionClassName.NONE;
        switch (thickness) {
          case "thin":
            decorationClassName = CompositionClassName.SECONDARY;
            break;
          case "thick":
            decorationClassName = CompositionClassName.PRIMARY;
            break;
        }
        decorations.push({
          range: decorationRange,
          options: {
            description: "textFormatDecoration",
            inlineClassName: decorationClassName
          }
        });
      });
      this._decorations = this._context.viewModel.model.deltaDecorations(this._decorations, decorations);
    }
    _updateSelectionAndControlBoundsData(ctx) {
      const viewSelection = this._context.viewModel.coordinatesConverter.convertModelRangeToViewRange(this._primarySelection);
      if (this._primarySelection.isEmpty()) {
        const linesVisibleRanges = ctx.visibleRangeForPosition(viewSelection.getStartPosition());
        this._linesVisibleRanges = linesVisibleRanges;
      } else {
        this._linesVisibleRanges = null;
      }
    }
    _updateSelectionAndControlBoundsAfterRender() {
      const options = this._context.configuration.options;
      const contentLeft = options.get(
        165
        /* EditorOption.layoutInfo */
      ).contentLeft;
      const viewSelection = this._context.viewModel.coordinatesConverter.convertModelRangeToViewRange(this._primarySelection);
      const verticalOffsetStart = this._context.viewLayout.getVerticalOffsetForLineNumber(viewSelection.startLineNumber);
      const verticalOffsetEnd = this._context.viewLayout.getVerticalOffsetAfterLineNumber(viewSelection.endLineNumber);
      const parentBounds = this._parent.getBoundingClientRect();
      const top = parentBounds.top + verticalOffsetStart - this._scrollTop;
      const height = verticalOffsetEnd - verticalOffsetStart;
      let left = parentBounds.left + contentLeft - this._scrollLeft;
      let width2;
      if (this._primarySelection.isEmpty()) {
        if (this._linesVisibleRanges) {
          left += this._linesVisibleRanges.left;
        }
        width2 = 0;
      } else {
        width2 = parentBounds.width - contentLeft;
      }
      const selectionBounds = new DOMRect(left, top, width2, height);
      this._editContext.updateSelectionBounds(selectionBounds);
      this._editContext.updateControlBounds(selectionBounds);
    }
    _updateCharacterBounds(e) {
      const options = this._context.configuration.options;
      const typicalHalfWidthCharacterWidth = options.get(
        59
        /* EditorOption.fontInfo */
      ).typicalHalfwidthCharacterWidth;
      const contentLeft = options.get(
        165
        /* EditorOption.layoutInfo */
      ).contentLeft;
      const parentBounds = this._parent.getBoundingClientRect();
      const characterBounds = [];
      const offsetTransformer = new PositionOffsetTransformer(this._editContext.text);
      for (let offset = e.rangeStart; offset < e.rangeEnd; offset++) {
        const editContextStartPosition = offsetTransformer.getPosition(offset);
        const textStartLineOffsetWithinEditor = this._editContextPrimarySelection.startLineNumber - 1;
        const characterStartPosition = new Position$1(textStartLineOffsetWithinEditor + editContextStartPosition.lineNumber, editContextStartPosition.column);
        const characterEndPosition = characterStartPosition.delta(0, 1);
        const characterModelRange = Range$2.fromPositions(characterStartPosition, characterEndPosition);
        const characterViewRange = this._context.viewModel.coordinatesConverter.convertModelRangeToViewRange(characterModelRange);
        const characterLinesVisibleRanges = this._visibleRangeProvider.linesVisibleRangesForRange(characterViewRange, true) ?? [];
        const lineNumber = characterViewRange.startLineNumber;
        const characterVerticalOffset = this._context.viewLayout.getVerticalOffsetForLineNumber(lineNumber);
        const top = parentBounds.top + characterVerticalOffset - this._scrollTop;
        let left = 0;
        let width2 = typicalHalfWidthCharacterWidth;
        if (characterLinesVisibleRanges.length > 0) {
          for (const visibleRange of characterLinesVisibleRanges[0].ranges) {
            left = visibleRange.left;
            width2 = visibleRange.width;
            break;
          }
        }
        const lineHeight = this._context.viewLayout.getLineHeightForLineNumber(lineNumber);
        characterBounds.push(new DOMRect(parentBounds.left + contentLeft + left - this._scrollLeft, top, width2, lineHeight));
      }
      this._editContext.updateCharacterBounds(e.rangeStart, characterBounds);
    }
    _ensureClipboardGetsEditorSelection(e) {
      const options = this._context.configuration.options;
      const emptySelectionClipboard = options.get(
        45
        /* EditorOption.emptySelectionClipboard */
      );
      const copyWithSyntaxHighlighting = options.get(
        31
        /* EditorOption.copyWithSyntaxHighlighting */
      );
      const selections = this._context.viewModel.getCursorStates().map((cursorState) => cursorState.modelState.selection);
      const dataToCopy = getDataToCopy(this._context.viewModel, selections, emptySelectionClipboard, copyWithSyntaxHighlighting);
      let id = void 0;
      if (this.logService.getLevel() === LogLevel.Trace) {
        id = generateUuid();
      }
      const storedMetadata = {
        version: 1,
        id,
        isFromEmptySelection: dataToCopy.isFromEmptySelection,
        multicursorText: dataToCopy.multicursorText,
        mode: dataToCopy.mode
      };
      InMemoryClipboardMetadataManager.INSTANCE.set(
        // When writing "LINE\r\n" to the clipboard and then pasting,
        // Firefox pastes "LINE\n", so let's work around this quirk
        isFirefox$1 ? dataToCopy.text.replace(/\r\n/g, "\n") : dataToCopy.text,
        storedMetadata
      );
      e.preventDefault();
      if (e.clipboardData) {
        ClipboardEventUtils.setTextData(e.clipboardData, dataToCopy.text, dataToCopy.html, storedMetadata);
      }
      this.logService.trace("NativeEditContext#_ensureClipboardGetsEditorSelectios with id : ", id, " with text.length: ", dataToCopy.text.length);
    }
  };
  NativeEditContext = __decorate$2R([
    __param$2M(5, IInstantiationService),
    __param$2M(6, ILogService)
  ], NativeEditContext);
  class RulersGpu extends ViewPart {
    constructor(context, _viewGpuContext) {
      super(context);
      this._viewGpuContext = _viewGpuContext;
      this._gpuShapes = [];
      this._register(autorun((reader) => this._updateEntries(reader)));
    }
    // --- begin event handlers
    onConfigurationChanged(e) {
      this._updateEntries(void 0);
      return true;
    }
    // --- end event handlers
    prepareRender(ctx) {
    }
    render(ctx) {
    }
    _updateEntries(reader) {
      const options = this._context.configuration.options;
      const rulers = options.get(
        116
        /* EditorOption.rulers */
      );
      const typicalHalfwidthCharacterWidth = options.get(
        59
        /* EditorOption.fontInfo */
      ).typicalHalfwidthCharacterWidth;
      const devicePixelRatio = this._viewGpuContext.devicePixelRatio.read(reader);
      for (let i2 = 0, len = rulers.length; i2 < len; i2++) {
        const ruler = rulers[i2];
        const shape = this._gpuShapes[i2];
        const color = ruler.color ? Color.fromHex(ruler.color) : this._context.theme.getColor(editorRuler) ?? Color.white;
        const rulerData = [
          ruler.column * typicalHalfwidthCharacterWidth * devicePixelRatio,
          0,
          Math.max(1, Math.ceil(devicePixelRatio)),
          Number.MAX_SAFE_INTEGER,
          color.rgba.r / 255,
          color.rgba.g / 255,
          color.rgba.b / 255,
          color.rgba.a
        ];
        if (!shape) {
          this._gpuShapes[i2] = this._viewGpuContext.rectangleRenderer.register(...rulerData);
        } else {
          shape.setRaw(rulerData);
        }
      }
      while (this._gpuShapes.length > rulers.length) {
        this._gpuShapes.splice(-1, 1)[0].dispose();
      }
    }
  }
  const _GpuMarkOverlay = class _GpuMarkOverlay extends DynamicViewOverlay {
    constructor(context, _viewGpuContext) {
      super();
      this._viewGpuContext = _viewGpuContext;
      this._context = context;
      this._renderResult = null;
      this._context.addEventHandler(this);
    }
    dispose() {
      this._context.removeEventHandler(this);
      this._renderResult = null;
      super.dispose();
    }
    // --- begin event handlers
    onConfigurationChanged(e) {
      return true;
    }
    onCursorStateChanged(e) {
      return true;
    }
    onFlushed(e) {
      return true;
    }
    onLinesChanged(e) {
      return true;
    }
    onLinesDeleted(e) {
      return true;
    }
    onLinesInserted(e) {
      return true;
    }
    onScrollChanged(e) {
      return e.scrollTopChanged;
    }
    onZonesChanged(e) {
      return true;
    }
    onDecorationsChanged(e) {
      return true;
    }
    // --- end event handlers
    prepareRender(ctx) {
      const visibleStartLineNumber = ctx.visibleRange.startLineNumber;
      const visibleEndLineNumber = ctx.visibleRange.endLineNumber;
      const viewportData = ctx.viewportData;
      const options = new ViewLineOptions(this._context.configuration, this._context.theme.type);
      const output = [];
      for (let lineNumber = visibleStartLineNumber; lineNumber <= visibleEndLineNumber; lineNumber++) {
        const lineIndex = lineNumber - visibleStartLineNumber;
        const cannotRenderReasons = this._viewGpuContext.canRenderDetailed(options, viewportData, lineNumber);
        output[lineIndex] = cannotRenderReasons.length ? `<div class="${_GpuMarkOverlay.CLASS_NAME}" title="Cannot render on GPU: ${cannotRenderReasons.join(", ")}"></div>` : "";
      }
      this._renderResult = output;
    }
    render(startLineNumber, lineNumber) {
      if (!this._renderResult) {
        return "";
      }
      const lineIndex = lineNumber - startLineNumber;
      if (lineIndex < 0 || lineIndex >= this._renderResult.length) {
        return "";
      }
      return this._renderResult[lineIndex];
    }
  };
  _GpuMarkOverlay.CLASS_NAME = "gpu-mark";
  let GpuMarkOverlay = _GpuMarkOverlay;
  var __decorate$2Q = 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$2L = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  let View$1 = class View extends ViewEventHandler {
    constructor(editorContainer, ownerID, commandDelegate, configuration, colorTheme, model, userInputEvents, overflowWidgetsDomNode, _instantiationService) {
      super();
      this._instantiationService = _instantiationService;
      this._shouldRecomputeGlyphMarginLanes = false;
      this._ownerID = ownerID;
      this._widgetFocusTracker = this._register(new CodeEditorWidgetFocusTracker(editorContainer, overflowWidgetsDomNode));
      this._register(this._widgetFocusTracker.onChange(() => {
        this._context.viewModel.setHasWidgetFocus(this._widgetFocusTracker.hasFocus());
      }));
      this._selections = [new Selection$1(1, 1, 1, 1)];
      this._renderAnimationFrame = null;
      this._overflowGuardContainer = createFastDomNode(document.createElement("div"));
      PartFingerprints.write(
        this._overflowGuardContainer,
        3
        /* PartFingerprint.OverflowGuard */
      );
      this._overflowGuardContainer.setClassName("overflow-guard");
      this._viewController = new ViewController(configuration, model, userInputEvents, commandDelegate);
      this._context = new ViewContext(configuration, colorTheme, model);
      this._context.addEventHandler(this);
      this._viewParts = [];
      this._editContextEnabled = this._context.configuration.options.get(
        170
        /* EditorOption.effectiveEditContext */
      );
      this._accessibilitySupport = this._context.configuration.options.get(
        2
        /* EditorOption.accessibilitySupport */
      );
      this._editContext = this._instantiateEditContext();
      this._viewParts.push(this._editContext);
      this._linesContent = createFastDomNode(document.createElement("div"));
      this._linesContent.setClassName("lines-content monaco-editor-background");
      this._linesContent.setPosition("absolute");
      this.domNode = createFastDomNode(document.createElement("div"));
      this.domNode.setClassName(this._getEditorClassName());
      this.domNode.setAttribute("role", "code");
      if (this._context.configuration.options.get(
        46
        /* EditorOption.experimentalGpuAcceleration */
      ) === "on") {
        this._viewGpuContext = this._instantiationService.createInstance(ViewGpuContext, this._context);
      }
      this._scrollbar = new EditorScrollbar(this._context, this._linesContent, this.domNode, this._overflowGuardContainer);
      this._viewParts.push(this._scrollbar);
      this._viewLines = new ViewLines(this._context, this._viewGpuContext, this._linesContent);
      if (this._viewGpuContext) {
        this._viewLinesGpu = this._instantiationService.createInstance(ViewLinesGpu, this._context, this._viewGpuContext);
      }
      this._viewZones = new ViewZones(this._context);
      this._viewParts.push(this._viewZones);
      const decorationsOverviewRuler = new DecorationsOverviewRuler(this._context);
      this._viewParts.push(decorationsOverviewRuler);
      const scrollDecoration = new ScrollDecorationViewPart(this._context);
      this._viewParts.push(scrollDecoration);
      const contentViewOverlays = new ContentViewOverlays(this._context);
      this._viewParts.push(contentViewOverlays);
      contentViewOverlays.addDynamicOverlay(new CurrentLineHighlightOverlay(this._context));
      contentViewOverlays.addDynamicOverlay(new SelectionsOverlay(this._context));
      contentViewOverlays.addDynamicOverlay(new IndentGuidesOverlay(this._context));
      contentViewOverlays.addDynamicOverlay(new DecorationsOverlay(this._context));
      contentViewOverlays.addDynamicOverlay(new WhitespaceOverlay(this._context));
      const marginViewOverlays = new MarginViewOverlays(this._context);
      this._viewParts.push(marginViewOverlays);
      marginViewOverlays.addDynamicOverlay(new CurrentLineMarginHighlightOverlay(this._context));
      marginViewOverlays.addDynamicOverlay(new MarginViewLineDecorationsOverlay(this._context));
      marginViewOverlays.addDynamicOverlay(new LinesDecorationsOverlay(this._context));
      marginViewOverlays.addDynamicOverlay(new LineNumbersOverlay(this._context));
      if (this._viewGpuContext) {
        marginViewOverlays.addDynamicOverlay(new GpuMarkOverlay(this._context, this._viewGpuContext));
      }
      this._glyphMarginWidgets = new GlyphMarginWidgets(this._context);
      this._viewParts.push(this._glyphMarginWidgets);
      const margin = new Margin(this._context);
      margin.getDomNode().appendChild(this._viewZones.marginDomNode);
      margin.getDomNode().appendChild(marginViewOverlays.getDomNode());
      margin.getDomNode().appendChild(this._glyphMarginWidgets.domNode);
      this._viewParts.push(margin);
      this._contentWidgets = new ViewContentWidgets(this._context, this.domNode);
      this._viewParts.push(this._contentWidgets);
      this._viewCursors = new ViewCursors(this._context);
      this._viewParts.push(this._viewCursors);
      this._overlayWidgets = new ViewOverlayWidgets(this._context, this.domNode);
      this._viewParts.push(this._overlayWidgets);
      const rulers = this._viewGpuContext ? new RulersGpu(this._context, this._viewGpuContext) : new Rulers(this._context);
      this._viewParts.push(rulers);
      const blockOutline = new BlockDecorations(this._context);
      this._viewParts.push(blockOutline);
      const minimap = new Minimap(this._context);
      this._viewParts.push(minimap);
      if (decorationsOverviewRuler) {
        const overviewRulerData = this._scrollbar.getOverviewRulerLayoutInfo();
        overviewRulerData.parent.insertBefore(decorationsOverviewRuler.getDomNode(), overviewRulerData.insertBefore);
      }
      this._linesContent.appendChild(contentViewOverlays.getDomNode());
      if ("domNode" in rulers) {
        this._linesContent.appendChild(rulers.domNode);
      }
      this._linesContent.appendChild(this._viewZones.domNode);
      this._linesContent.appendChild(this._viewLines.getDomNode());
      this._linesContent.appendChild(this._contentWidgets.domNode);
      this._linesContent.appendChild(this._viewCursors.getDomNode());
      this._overflowGuardContainer.appendChild(margin.getDomNode());
      this._overflowGuardContainer.appendChild(this._scrollbar.getDomNode());
      if (this._viewGpuContext) {
        this._overflowGuardContainer.appendChild(this._viewGpuContext.canvas);
      }
      this._overflowGuardContainer.appendChild(scrollDecoration.getDomNode());
      this._overflowGuardContainer.appendChild(this._overlayWidgets.getDomNode());
      this._overflowGuardContainer.appendChild(minimap.getDomNode());
      this._overflowGuardContainer.appendChild(blockOutline.domNode);
      this.domNode.appendChild(this._overflowGuardContainer);
      if (overflowWidgetsDomNode) {
        overflowWidgetsDomNode.appendChild(this._contentWidgets.overflowingContentWidgetsDomNode.domNode);
        overflowWidgetsDomNode.appendChild(this._overlayWidgets.overflowingOverlayWidgetsDomNode.domNode);
      } else {
        this.domNode.appendChild(this._contentWidgets.overflowingContentWidgetsDomNode);
        this.domNode.appendChild(this._overlayWidgets.overflowingOverlayWidgetsDomNode);
      }
      this._applyLayout();
      this._pointerHandler = this._register(new PointerHandler(this._context, this._viewController, this._createPointerHandlerHelper()));
    }
    _instantiateEditContext() {
      const usingExperimentalEditContext = this._context.configuration.options.get(
        170
        /* EditorOption.effectiveEditContext */
      );
      if (usingExperimentalEditContext) {
        return this._instantiationService.createInstance(NativeEditContext, this._ownerID, this._context, this._overflowGuardContainer, this._viewController, this._createTextAreaHandlerHelper());
      } else {
        return this._instantiationService.createInstance(TextAreaEditContext, this._context, this._overflowGuardContainer, this._viewController, this._createTextAreaHandlerHelper());
      }
    }
    _updateEditContext() {
      const editContextEnabled = this._context.configuration.options.get(
        170
        /* EditorOption.effectiveEditContext */
      );
      const accessibilitySupport = this._context.configuration.options.get(
        2
        /* EditorOption.accessibilitySupport */
      );
      if (this._editContextEnabled === editContextEnabled && this._accessibilitySupport === accessibilitySupport) {
        return;
      }
      this._editContextEnabled = editContextEnabled;
      this._accessibilitySupport = accessibilitySupport;
      const isEditContextFocused = this._editContext.isFocused();
      const indexOfEditContext = this._viewParts.indexOf(this._editContext);
      this._editContext.dispose();
      this._editContext = this._instantiateEditContext();
      if (isEditContextFocused) {
        this._editContext.focus();
      }
      if (indexOfEditContext !== -1) {
        this._viewParts.splice(indexOfEditContext, 1, this._editContext);
      }
    }
    _computeGlyphMarginLanes() {
      const model = this._context.viewModel.model;
      const laneModel = this._context.viewModel.glyphLanes;
      let glyphs = [];
      let maxLineNumber = 0;
      glyphs = glyphs.concat(model.getAllMarginDecorations().map((decoration2) => {
        const lane = decoration2.options.glyphMargin?.position ?? GlyphMarginLane$1.Center;
        maxLineNumber = Math.max(maxLineNumber, decoration2.range.endLineNumber);
        return { range: decoration2.range, lane, persist: decoration2.options.glyphMargin?.persistLane };
      }));
      glyphs = glyphs.concat(this._glyphMarginWidgets.getWidgets().map((widget) => {
        const range2 = model.validateRange(widget.preference.range);
        maxLineNumber = Math.max(maxLineNumber, range2.endLineNumber);
        return { range: range2, lane: widget.preference.lane };
      }));
      glyphs.sort((a, b) => Range$2.compareRangesUsingStarts(a.range, b.range));
      laneModel.reset(maxLineNumber);
      for (const glyph of glyphs) {
        laneModel.push(glyph.lane, glyph.range, glyph.persist);
      }
      return laneModel;
    }
    _createPointerHandlerHelper() {
      return {
        viewDomNode: this.domNode.domNode,
        linesContentDomNode: this._linesContent.domNode,
        viewLinesDomNode: this._viewLines.getDomNode().domNode,
        viewLinesGpu: this._viewLinesGpu,
        focusTextArea: () => {
          this.focus();
        },
        dispatchTextAreaEvent: (event) => {
          this._editContext.domNode.domNode.dispatchEvent(event);
        },
        getLastRenderData: () => {
          const lastViewCursorsRenderData = this._viewCursors.getLastRenderData() || [];
          const lastTextareaPosition = this._editContext.getLastRenderData();
          return new PointerHandlerLastRenderData(lastViewCursorsRenderData, lastTextareaPosition);
        },
        renderNow: () => {
          this.render(true, false);
        },
        shouldSuppressMouseDownOnViewZone: (viewZoneId) => {
          return this._viewZones.shouldSuppressMouseDownOnViewZone(viewZoneId);
        },
        shouldSuppressMouseDownOnWidget: (widgetId) => {
          return this._contentWidgets.shouldSuppressMouseDownOnWidget(widgetId);
        },
        getPositionFromDOMInfo: (spanNode, offset) => {
          this._flushAccumulatedAndRenderNow();
          return this._viewLines.getPositionFromDOMInfo(spanNode, offset);
        },
        visibleRangeForPosition: (lineNumber, column) => {
          this._flushAccumulatedAndRenderNow();
          const position = new Position$1(lineNumber, column);
          return this._viewLines.visibleRangeForPosition(position) ?? this._viewLinesGpu?.visibleRangeForPosition(position) ?? null;
        },
        getLineWidth: (lineNumber) => {
          this._flushAccumulatedAndRenderNow();
          if (this._viewLinesGpu) {
            const result = this._viewLinesGpu.getLineWidth(lineNumber);
            if (result !== void 0) {
              return result;
            }
          }
          return this._viewLines.getLineWidth(lineNumber);
        }
      };
    }
    _createTextAreaHandlerHelper() {
      return {
        visibleRangeForPosition: (position) => {
          this._flushAccumulatedAndRenderNow();
          return this._viewLines.visibleRangeForPosition(position);
        },
        linesVisibleRangesForRange: (range2, includeNewLines) => {
          this._flushAccumulatedAndRenderNow();
          return this._viewLines.linesVisibleRangesForRange(range2, includeNewLines);
        }
      };
    }
    _applyLayout() {
      const options = this._context.configuration.options;
      const layoutInfo = options.get(
        165
        /* EditorOption.layoutInfo */
      );
      this.domNode.setWidth(layoutInfo.width);
      this.domNode.setHeight(layoutInfo.height);
      this._overflowGuardContainer.setWidth(layoutInfo.width);
      this._overflowGuardContainer.setHeight(layoutInfo.height);
      this._linesContent.setWidth(16777216);
      this._linesContent.setHeight(16777216);
    }
    _getEditorClassName() {
      const focused = this._editContext.isFocused() ? " focused" : "";
      return this._context.configuration.options.get(
        162
        /* EditorOption.editorClassName */
      ) + " " + getThemeTypeSelector(this._context.theme.type) + focused;
    }
    // --- begin event handlers
    handleEvents(events) {
      super.handleEvents(events);
      this._scheduleRender();
    }
    onConfigurationChanged(e) {
      this.domNode.setClassName(this._getEditorClassName());
      this._updateEditContext();
      this._applyLayout();
      return false;
    }
    onCursorStateChanged(e) {
      this._selections = e.selections;
      return false;
    }
    onDecorationsChanged(e) {
      if (e.affectsGlyphMargin) {
        this._shouldRecomputeGlyphMarginLanes = true;
      }
      return false;
    }
    onFocusChanged(e) {
      this.domNode.setClassName(this._getEditorClassName());
      return false;
    }
    onThemeChanged(e) {
      this._context.theme.update(e.theme);
      this.domNode.setClassName(this._getEditorClassName());
      return false;
    }
    // --- end event handlers
    dispose() {
      if (this._renderAnimationFrame !== null) {
        this._renderAnimationFrame.dispose();
        this._renderAnimationFrame = null;
      }
      this._contentWidgets.overflowingContentWidgetsDomNode.domNode.remove();
      this._overlayWidgets.overflowingOverlayWidgetsDomNode.domNode.remove();
      this._context.removeEventHandler(this);
      this._viewGpuContext?.dispose();
      this._viewLines.dispose();
      this._viewLinesGpu?.dispose();
      for (const viewPart of this._viewParts) {
        viewPart.dispose();
      }
      super.dispose();
    }
    _scheduleRender() {
      if (this._store.isDisposed) {
        throw new BugIndicatingError();
      }
      if (this._renderAnimationFrame === null) {
        if (this._editContext instanceof NativeEditContext) {
          this._editContext.setEditContextOnDomNode();
        }
        const rendering = this._createCoordinatedRendering();
        this._renderAnimationFrame = EditorRenderingCoordinator.INSTANCE.scheduleCoordinatedRendering({
          window: getWindow(this.domNode?.domNode),
          prepareRenderText: () => {
            if (this._store.isDisposed) {
              throw new BugIndicatingError();
            }
            try {
              return rendering.prepareRenderText();
            } finally {
              this._renderAnimationFrame = null;
            }
          },
          renderText: () => {
            if (this._store.isDisposed) {
              throw new BugIndicatingError();
            }
            return rendering.renderText();
          },
          prepareRender: (viewParts, ctx) => {
            if (this._store.isDisposed) {
              throw new BugIndicatingError();
            }
            return rendering.prepareRender(viewParts, ctx);
          },
          render: (viewParts, ctx) => {
            if (this._store.isDisposed) {
              throw new BugIndicatingError();
            }
            return rendering.render(viewParts, ctx);
          }
        });
      }
    }
    _flushAccumulatedAndRenderNow() {
      const rendering = this._createCoordinatedRendering();
      safeInvokeNoArg(() => rendering.prepareRenderText());
      const data = safeInvokeNoArg(() => rendering.renderText());
      if (data) {
        const [viewParts, ctx] = data;
        safeInvokeNoArg(() => rendering.prepareRender(viewParts, ctx));
        safeInvokeNoArg(() => rendering.render(viewParts, ctx));
      }
    }
    _getViewPartsToRender() {
      const result = [];
      let resultLen = 0;
      for (const viewPart of this._viewParts) {
        if (viewPart.shouldRender()) {
          result[resultLen++] = viewPart;
        }
      }
      return result;
    }
    _createCoordinatedRendering() {
      return {
        prepareRenderText: () => {
          if (this._shouldRecomputeGlyphMarginLanes) {
            this._shouldRecomputeGlyphMarginLanes = false;
            const model = this._computeGlyphMarginLanes();
            this._context.configuration.setGlyphMarginDecorationLaneCount(model.requiredLanes);
          }
          inputLatency.onRenderStart();
        },
        renderText: () => {
          if (!this.domNode.domNode.isConnected) {
            return null;
          }
          let viewPartsToRender = this._getViewPartsToRender();
          if (!this._viewLines.shouldRender() && viewPartsToRender.length === 0) {
            return null;
          }
          const partialViewportData = this._context.viewLayout.getLinesViewportData();
          this._context.viewModel.setViewport(partialViewportData.startLineNumber, partialViewportData.endLineNumber, partialViewportData.centeredLineNumber);
          const viewportData = new ViewportData(this._selections, partialViewportData, this._context.viewLayout.getWhitespaceViewportData(), this._context.viewModel);
          if (this._contentWidgets.shouldRender()) {
            this._contentWidgets.onBeforeRender(viewportData);
          }
          if (this._viewLines.shouldRender()) {
            this._viewLines.renderText(viewportData);
            this._viewLines.onDidRender();
            viewPartsToRender = this._getViewPartsToRender();
          }
          if (this._viewLinesGpu?.shouldRender()) {
            this._viewLinesGpu.renderText(viewportData);
            this._viewLinesGpu.onDidRender();
          }
          return [viewPartsToRender, new RenderingContext(this._context.viewLayout, viewportData, this._viewLines, this._viewLinesGpu)];
        },
        prepareRender: (viewPartsToRender, ctx) => {
          for (const viewPart of viewPartsToRender) {
            viewPart.prepareRender(ctx);
          }
        },
        render: (viewPartsToRender, ctx) => {
          for (const viewPart of viewPartsToRender) {
            viewPart.render(ctx);
            viewPart.onDidRender();
          }
        }
      };
    }
    // --- BEGIN CodeEditor helpers
    delegateVerticalScrollbarPointerDown(browserEvent) {
      this._scrollbar.delegateVerticalScrollbarPointerDown(browserEvent);
    }
    delegateScrollFromMouseWheelEvent(browserEvent) {
      this._scrollbar.delegateScrollFromMouseWheelEvent(browserEvent);
    }
    restoreState(scrollPosition) {
      this._context.viewModel.viewLayout.setScrollPosition(
        {
          scrollTop: scrollPosition.scrollTop,
          scrollLeft: scrollPosition.scrollLeft
        },
        1
        /* ScrollType.Immediate */
      );
      this._context.viewModel.visibleLinesStabilized();
    }
    getOffsetForColumn(modelLineNumber, modelColumn) {
      const modelPosition = this._context.viewModel.model.validatePosition({
        lineNumber: modelLineNumber,
        column: modelColumn
      });
      const viewPosition = this._context.viewModel.coordinatesConverter.convertModelPositionToViewPosition(modelPosition);
      this._flushAccumulatedAndRenderNow();
      const visibleRange = this._viewLines.visibleRangeForPosition(new Position$1(viewPosition.lineNumber, viewPosition.column));
      if (!visibleRange) {
        return -1;
      }
      return visibleRange.left;
    }
    getTargetAtClientPoint(clientX, clientY) {
      const mouseTarget = this._pointerHandler.getTargetAtClientPoint(clientX, clientY);
      if (!mouseTarget) {
        return null;
      }
      return ViewUserInputEvents.convertViewToModelMouseTarget(mouseTarget, this._context.viewModel.coordinatesConverter);
    }
    createOverviewRuler(cssClassName) {
      return new OverviewRuler(this._context, cssClassName);
    }
    change(callback) {
      this._viewZones.changeViewZones(callback);
      this._scheduleRender();
    }
    render(now, everything) {
      if (everything) {
        this._viewLines.forceShouldRender();
        for (const viewPart of this._viewParts) {
          viewPart.forceShouldRender();
        }
      }
      if (now) {
        this._flushAccumulatedAndRenderNow();
      } else {
        this._scheduleRender();
      }
    }
    writeScreenReaderContent(reason) {
      this._editContext.writeScreenReaderContent(reason);
    }
    focus() {
      this._editContext.focus();
    }
    isFocused() {
      return this._editContext.isFocused();
    }
    isWidgetFocused() {
      return this._widgetFocusTracker.hasFocus();
    }
    setAriaOptions(options) {
      this._editContext.setAriaOptions(options);
    }
    addContentWidget(widgetData) {
      this._contentWidgets.addWidget(widgetData.widget);
      this.layoutContentWidget(widgetData);
      this._scheduleRender();
    }
    layoutContentWidget(widgetData) {
      this._contentWidgets.setWidgetPosition(widgetData.widget, widgetData.position?.position ?? null, widgetData.position?.secondaryPosition ?? null, widgetData.position?.preference ?? null, widgetData.position?.positionAffinity ?? null);
      this._scheduleRender();
    }
    removeContentWidget(widgetData) {
      this._contentWidgets.removeWidget(widgetData.widget);
      this._scheduleRender();
    }
    addOverlayWidget(widgetData) {
      this._overlayWidgets.addWidget(widgetData.widget);
      this.layoutOverlayWidget(widgetData);
      this._scheduleRender();
    }
    layoutOverlayWidget(widgetData) {
      const shouldRender = this._overlayWidgets.setWidgetPosition(widgetData.widget, widgetData.position);
      if (shouldRender) {
        this._scheduleRender();
      }
    }
    removeOverlayWidget(widgetData) {
      this._overlayWidgets.removeWidget(widgetData.widget);
      this._scheduleRender();
    }
    addGlyphMarginWidget(widgetData) {
      this._glyphMarginWidgets.addWidget(widgetData.widget);
      this._shouldRecomputeGlyphMarginLanes = true;
      this._scheduleRender();
    }
    layoutGlyphMarginWidget(widgetData) {
      const newPreference = widgetData.position;
      const shouldRender = this._glyphMarginWidgets.setWidgetPosition(widgetData.widget, newPreference);
      if (shouldRender) {
        this._shouldRecomputeGlyphMarginLanes = true;
        this._scheduleRender();
      }
    }
    removeGlyphMarginWidget(widgetData) {
      this._glyphMarginWidgets.removeWidget(widgetData.widget);
      this._shouldRecomputeGlyphMarginLanes = true;
      this._scheduleRender();
    }
  };
  View$1 = __decorate$2Q([
    __param$2L(8, IInstantiationService)
  ], View$1);
  function safeInvokeNoArg(func) {
    try {
      return func();
    } catch (e) {
      onUnexpectedError(e);
      return null;
    }
  }
  const _EditorRenderingCoordinator = class _EditorRenderingCoordinator {
    constructor() {
      this._coordinatedRenderings = [];
      this._animationFrameRunners = /* @__PURE__ */ new Map();
    }
    scheduleCoordinatedRendering(rendering) {
      this._coordinatedRenderings.push(rendering);
      this._scheduleRender(rendering.window);
      return {
        dispose: () => {
          const renderingIndex = this._coordinatedRenderings.indexOf(rendering);
          if (renderingIndex === -1) {
            return;
          }
          this._coordinatedRenderings.splice(renderingIndex, 1);
          if (this._coordinatedRenderings.length === 0) {
            for (const [_, disposable] of this._animationFrameRunners) {
              disposable.dispose();
            }
            this._animationFrameRunners.clear();
          }
        }
      };
    }
    _scheduleRender(window2) {
      if (!this._animationFrameRunners.has(window2)) {
        const runner = () => {
          this._animationFrameRunners.delete(window2);
          this._onRenderScheduled();
        };
        this._animationFrameRunners.set(window2, runAtThisOrScheduleAtNextAnimationFrame(window2, runner, 100));
      }
    }
    _onRenderScheduled() {
      const coordinatedRenderings = this._coordinatedRenderings.slice(0);
      this._coordinatedRenderings = [];
      for (const rendering of coordinatedRenderings) {
        safeInvokeNoArg(() => rendering.prepareRenderText());
      }
      const datas = [];
      for (let i2 = 0, len = coordinatedRenderings.length; i2 < len; i2++) {
        const rendering = coordinatedRenderings[i2];
        datas[i2] = safeInvokeNoArg(() => rendering.renderText());
      }
      for (let i2 = 0, len = coordinatedRenderings.length; i2 < len; i2++) {
        const rendering = coordinatedRenderings[i2];
        const data = datas[i2];
        if (!data) {
          continue;
        }
        const [viewParts, ctx] = data;
        safeInvokeNoArg(() => rendering.prepareRender(viewParts, ctx));
      }
      for (let i2 = 0, len = coordinatedRenderings.length; i2 < len; i2++) {
        const rendering = coordinatedRenderings[i2];
        const data = datas[i2];
        if (!data) {
          continue;
        }
        const [viewParts, ctx] = data;
        safeInvokeNoArg(() => rendering.render(viewParts, ctx));
      }
    }
  };
  _EditorRenderingCoordinator.INSTANCE = new _EditorRenderingCoordinator();
  let EditorRenderingCoordinator = _EditorRenderingCoordinator;
  class CodeEditorWidgetFocusTracker extends Disposable {
    constructor(domElement, overflowWidgetsDomNode) {
      super();
      this._onChange = this._register(new Emitter$1());
      this.onChange = this._onChange.event;
      this._hadFocus = void 0;
      this._hasDomElementFocus = false;
      this._domFocusTracker = this._register(trackFocus(domElement));
      this._overflowWidgetsDomNodeHasFocus = false;
      this._register(this._domFocusTracker.onDidFocus(() => {
        this._hasDomElementFocus = true;
        this._update();
      }));
      this._register(this._domFocusTracker.onDidBlur(() => {
        this._hasDomElementFocus = false;
        this._update();
      }));
      if (overflowWidgetsDomNode) {
        this._overflowWidgetsDomNode = this._register(trackFocus(overflowWidgetsDomNode));
        this._register(this._overflowWidgetsDomNode.onDidFocus(() => {
          this._overflowWidgetsDomNodeHasFocus = true;
          this._update();
        }));
        this._register(this._overflowWidgetsDomNode.onDidBlur(() => {
          this._overflowWidgetsDomNodeHasFocus = false;
          this._update();
        }));
      }
    }
    _update() {
      const focused = this._hasDomElementFocus || this._overflowWidgetsDomNodeHasFocus;
      if (this._hadFocus !== focused) {
        this._hadFocus = focused;
        this._onChange.fire(void 0);
      }
    }
    hasFocus() {
      return this._hadFocus ?? false;
    }
  }
  class ModelLineProjectionData {
    constructor(injectionOffsets, injectionOptions, breakOffsets, breakOffsetsVisibleColumn, wrappedTextIndentLength) {
      this.injectionOffsets = injectionOffsets;
      this.injectionOptions = injectionOptions;
      this.breakOffsets = breakOffsets;
      this.breakOffsetsVisibleColumn = breakOffsetsVisibleColumn;
      this.wrappedTextIndentLength = wrappedTextIndentLength;
    }
    getOutputLineCount() {
      return this.breakOffsets.length;
    }
    getMinOutputOffset(outputLineIndex) {
      if (outputLineIndex > 0) {
        return this.wrappedTextIndentLength;
      }
      return 0;
    }
    getLineLength(outputLineIndex) {
      const startOffset = outputLineIndex > 0 ? this.breakOffsets[outputLineIndex - 1] : 0;
      const endOffset = this.breakOffsets[outputLineIndex];
      let lineLength = endOffset - startOffset;
      if (outputLineIndex > 0) {
        lineLength += this.wrappedTextIndentLength;
      }
      return lineLength;
    }
    getMaxOutputOffset(outputLineIndex) {
      return this.getLineLength(outputLineIndex);
    }
    translateToInputOffset(outputLineIndex, outputOffset) {
      if (outputLineIndex > 0) {
        outputOffset = Math.max(0, outputOffset - this.wrappedTextIndentLength);
      }
      const offsetInInputWithInjection = outputLineIndex === 0 ? outputOffset : this.breakOffsets[outputLineIndex - 1] + outputOffset;
      let offsetInInput = offsetInInputWithInjection;
      if (this.injectionOffsets !== null) {
        for (let i2 = 0; i2 < this.injectionOffsets.length; i2++) {
          if (offsetInInput > this.injectionOffsets[i2]) {
            if (offsetInInput < this.injectionOffsets[i2] + this.injectionOptions[i2].content.length) {
              offsetInInput = this.injectionOffsets[i2];
            } else {
              offsetInInput -= this.injectionOptions[i2].content.length;
            }
          } else {
            break;
          }
        }
      }
      return offsetInInput;
    }
    translateToOutputPosition(inputOffset, affinity = 2) {
      let inputOffsetInInputWithInjection = inputOffset;
      if (this.injectionOffsets !== null) {
        for (let i2 = 0; i2 < this.injectionOffsets.length; i2++) {
          if (inputOffset < this.injectionOffsets[i2]) {
            break;
          }
          if (affinity !== 1 && inputOffset === this.injectionOffsets[i2]) {
            break;
          }
          inputOffsetInInputWithInjection += this.injectionOptions[i2].content.length;
        }
      }
      return this.offsetInInputWithInjectionsToOutputPosition(inputOffsetInInputWithInjection, affinity);
    }
    offsetInInputWithInjectionsToOutputPosition(offsetInInputWithInjections, affinity = 2) {
      let low = 0;
      let high = this.breakOffsets.length - 1;
      let mid = 0;
      let midStart = 0;
      while (low <= high) {
        mid = low + (high - low) / 2 | 0;
        const midStop = this.breakOffsets[mid];
        midStart = mid > 0 ? this.breakOffsets[mid - 1] : 0;
        if (affinity === 0) {
          if (offsetInInputWithInjections <= midStart) {
            high = mid - 1;
          } else if (offsetInInputWithInjections > midStop) {
            low = mid + 1;
          } else {
            break;
          }
        } else {
          if (offsetInInputWithInjections < midStart) {
            high = mid - 1;
          } else if (offsetInInputWithInjections >= midStop) {
            low = mid + 1;
          } else {
            break;
          }
        }
      }
      let outputOffset = offsetInInputWithInjections - midStart;
      if (mid > 0) {
        outputOffset += this.wrappedTextIndentLength;
      }
      return new OutputPosition(mid, outputOffset);
    }
    normalizeOutputPosition(outputLineIndex, outputOffset, affinity) {
      if (this.injectionOffsets !== null) {
        const offsetInInputWithInjections = this.outputPositionToOffsetInInputWithInjections(outputLineIndex, outputOffset);
        const normalizedOffsetInUnwrappedLine = this.normalizeOffsetInInputWithInjectionsAroundInjections(offsetInInputWithInjections, affinity);
        if (normalizedOffsetInUnwrappedLine !== offsetInInputWithInjections) {
          return this.offsetInInputWithInjectionsToOutputPosition(normalizedOffsetInUnwrappedLine, affinity);
        }
      }
      if (affinity === 0) {
        if (outputLineIndex > 0 && outputOffset === this.getMinOutputOffset(outputLineIndex)) {
          return new OutputPosition(outputLineIndex - 1, this.getMaxOutputOffset(outputLineIndex - 1));
        }
      } else if (affinity === 1) {
        const maxOutputLineIndex = this.getOutputLineCount() - 1;
        if (outputLineIndex < maxOutputLineIndex && outputOffset === this.getMaxOutputOffset(outputLineIndex)) {
          return new OutputPosition(outputLineIndex + 1, this.getMinOutputOffset(outputLineIndex + 1));
        }
      }
      return new OutputPosition(outputLineIndex, outputOffset);
    }
    outputPositionToOffsetInInputWithInjections(outputLineIndex, outputOffset) {
      if (outputLineIndex > 0) {
        outputOffset = Math.max(0, outputOffset - this.wrappedTextIndentLength);
      }
      const result = (outputLineIndex > 0 ? this.breakOffsets[outputLineIndex - 1] : 0) + outputOffset;
      return result;
    }
    normalizeOffsetInInputWithInjectionsAroundInjections(offsetInInputWithInjections, affinity) {
      const injectedText = this.getInjectedTextAtOffset(offsetInInputWithInjections);
      if (!injectedText) {
        return offsetInInputWithInjections;
      }
      if (affinity === 2) {
        if (offsetInInputWithInjections === injectedText.offsetInInputWithInjections + injectedText.length && hasRightCursorStop(this.injectionOptions[injectedText.injectedTextIndex].cursorStops)) {
          return injectedText.offsetInInputWithInjections + injectedText.length;
        } else {
          let result = injectedText.offsetInInputWithInjections;
          if (hasLeftCursorStop(this.injectionOptions[injectedText.injectedTextIndex].cursorStops)) {
            return result;
          }
          let index = injectedText.injectedTextIndex - 1;
          while (index >= 0 && this.injectionOffsets[index] === this.injectionOffsets[injectedText.injectedTextIndex]) {
            if (hasRightCursorStop(this.injectionOptions[index].cursorStops)) {
              break;
            }
            result -= this.injectionOptions[index].content.length;
            if (hasLeftCursorStop(this.injectionOptions[index].cursorStops)) {
              break;
            }
            index--;
          }
          return result;
        }
      } else if (affinity === 1 || affinity === 4) {
        let result = injectedText.offsetInInputWithInjections + injectedText.length;
        let index = injectedText.injectedTextIndex;
        while (index + 1 < this.injectionOffsets.length && this.injectionOffsets[index + 1] === this.injectionOffsets[index]) {
          result += this.injectionOptions[index + 1].content.length;
          index++;
        }
        return result;
      } else if (affinity === 0 || affinity === 3) {
        let result = injectedText.offsetInInputWithInjections;
        let index = injectedText.injectedTextIndex;
        while (index - 1 >= 0 && this.injectionOffsets[index - 1] === this.injectionOffsets[index]) {
          result -= this.injectionOptions[index - 1].content.length;
          index--;
        }
        return result;
      }
      assertNever();
    }
    getInjectedText(outputLineIndex, outputOffset) {
      const offset = this.outputPositionToOffsetInInputWithInjections(outputLineIndex, outputOffset);
      const injectedText = this.getInjectedTextAtOffset(offset);
      if (!injectedText) {
        return null;
      }
      return {
        options: this.injectionOptions[injectedText.injectedTextIndex]
      };
    }
    getInjectedTextAtOffset(offsetInInputWithInjections) {
      const injectionOffsets = this.injectionOffsets;
      const injectionOptions = this.injectionOptions;
      if (injectionOffsets !== null) {
        let totalInjectedTextLengthBefore = 0;
        for (let i2 = 0; i2 < injectionOffsets.length; i2++) {
          const length = injectionOptions[i2].content.length;
          const injectedTextStartOffsetInInputWithInjections = injectionOffsets[i2] + totalInjectedTextLengthBefore;
          const injectedTextEndOffsetInInputWithInjections = injectionOffsets[i2] + totalInjectedTextLengthBefore + length;
          if (injectedTextStartOffsetInInputWithInjections > offsetInInputWithInjections) {
            break;
          }
          if (offsetInInputWithInjections <= injectedTextEndOffsetInInputWithInjections) {
            return {
              injectedTextIndex: i2,
              offsetInInputWithInjections: injectedTextStartOffsetInInputWithInjections,
              length
            };
          }
          totalInjectedTextLengthBefore += length;
        }
      }
      return void 0;
    }
  }
  function hasRightCursorStop(cursorStop) {
    if (cursorStop === null || cursorStop === void 0) {
      return true;
    }
    return cursorStop === InjectedTextCursorStops$1.Right || cursorStop === InjectedTextCursorStops$1.Both;
  }
  function hasLeftCursorStop(cursorStop) {
    if (cursorStop === null || cursorStop === void 0) {
      return true;
    }
    return cursorStop === InjectedTextCursorStops$1.Left || cursorStop === InjectedTextCursorStops$1.Both;
  }
  class OutputPosition {
    constructor(outputLineIndex, outputOffset) {
      this.outputLineIndex = outputLineIndex;
      this.outputOffset = outputOffset;
    }
    toString() {
      return `${this.outputLineIndex}:${this.outputOffset}`;
    }
    toPosition(baseLineNumber) {
      return new Position$1(baseLineNumber + this.outputLineIndex, this.outputOffset + 1);
    }
  }
  class ModelRawFlush {
    constructor() {
      this.changeType = 1;
    }
  }
  class LineInjectedText {
    static applyInjectedText(lineText, injectedTexts) {
      if (!injectedTexts || injectedTexts.length === 0) {
        return lineText;
      }
      let result = "";
      let lastOriginalOffset = 0;
      for (const injectedText of injectedTexts) {
        result += lineText.substring(lastOriginalOffset, injectedText.column - 1);
        lastOriginalOffset = injectedText.column - 1;
        result += injectedText.options.content;
      }
      result += lineText.substring(lastOriginalOffset);
      return result;
    }
    static fromDecorations(decorations) {
      const result = [];
      for (const decoration2 of decorations) {
        if (decoration2.options.before && decoration2.options.before.content.length > 0) {
          result.push(new LineInjectedText(decoration2.ownerId, decoration2.range.startLineNumber, decoration2.range.startColumn, decoration2.options.before, 0));
        }
        if (decoration2.options.after && decoration2.options.after.content.length > 0) {
          result.push(new LineInjectedText(decoration2.ownerId, decoration2.range.endLineNumber, decoration2.range.endColumn, decoration2.options.after, 1));
        }
      }
      result.sort((a, b) => {
        if (a.lineNumber === b.lineNumber) {
          if (a.column === b.column) {
            return a.order - b.order;
          }
          return a.column - b.column;
        }
        return a.lineNumber - b.lineNumber;
      });
      return result;
    }
    constructor(ownerId2, lineNumber, column, options, order) {
      this.ownerId = ownerId2;
      this.lineNumber = lineNumber;
      this.column = column;
      this.options = options;
      this.order = order;
    }
  }
  class ModelRawLineChanged {
    constructor(lineNumber, detail, injectedText) {
      this.changeType = 2;
      this.lineNumber = lineNumber;
      this.detail = detail;
      this.injectedText = injectedText;
    }
  }
  class ModelLineHeightChanged {
    constructor(ownerId2, decorationId, lineNumber, lineHeight) {
      this.ownerId = ownerId2;
      this.decorationId = decorationId;
      this.lineNumber = lineNumber;
      this.lineHeight = lineHeight;
    }
  }
  class ModelFontChanged {
    constructor(ownerId2, lineNumber) {
      this.ownerId = ownerId2;
      this.lineNumber = lineNumber;
    }
  }
  class ModelRawLinesDeleted {
    constructor(fromLineNumber, toLineNumber) {
      this.changeType = 3;
      this.fromLineNumber = fromLineNumber;
      this.toLineNumber = toLineNumber;
    }
  }
  class ModelRawLinesInserted {
    constructor(fromLineNumber, toLineNumber, detail, injectedTexts) {
      this.changeType = 4;
      this.injectedTexts = injectedTexts;
      this.fromLineNumber = fromLineNumber;
      this.toLineNumber = toLineNumber;
      this.detail = detail;
    }
  }
  class ModelRawEOLChanged {
    constructor() {
      this.changeType = 5;
    }
  }
  class ModelRawContentChangedEvent {
    constructor(changes, versionId, isUndoing, isRedoing) {
      this.changes = changes;
      this.versionId = versionId;
      this.isUndoing = isUndoing;
      this.isRedoing = isRedoing;
      this.resultingSelection = null;
    }
    containsEvent(type) {
      for (let i2 = 0, len = this.changes.length; i2 < len; i2++) {
        const change = this.changes[i2];
        if (change.changeType === type) {
          return true;
        }
      }
      return false;
    }
    static merge(a, b) {
      const changes = [].concat(a.changes).concat(b.changes);
      const versionId = b.versionId;
      const isUndoing = a.isUndoing || b.isUndoing;
      const isRedoing = a.isRedoing || b.isRedoing;
      return new ModelRawContentChangedEvent(changes, versionId, isUndoing, isRedoing);
    }
  }
  class ModelInjectedTextChangedEvent {
    constructor(changes) {
      this.changes = changes;
    }
  }
  let ModelLineHeightChangedEvent$1 = class ModelLineHeightChangedEvent {
    constructor(changes) {
      this.changes = changes;
    }
  };
  let ModelFontChangedEvent$1 = class ModelFontChangedEvent {
    constructor(changes) {
      this.changes = changes;
    }
  };
  class InternalModelContentChangeEvent {
    constructor(rawContentChangedEvent, contentChangedEvent) {
      this.rawContentChangedEvent = rawContentChangedEvent;
      this.contentChangedEvent = contentChangedEvent;
    }
    merge(other) {
      const rawContentChangedEvent = ModelRawContentChangedEvent.merge(this.rawContentChangedEvent, other.rawContentChangedEvent);
      const contentChangedEvent = InternalModelContentChangeEvent._mergeChangeEvents(this.contentChangedEvent, other.contentChangedEvent);
      return new InternalModelContentChangeEvent(rawContentChangedEvent, contentChangedEvent);
    }
    static _mergeChangeEvents(a, b) {
      const changes = [].concat(a.changes).concat(b.changes);
      const eol = b.eol;
      const versionId = b.versionId;
      const isUndoing = a.isUndoing || b.isUndoing;
      const isRedoing = a.isRedoing || b.isRedoing;
      const isFlush = a.isFlush || b.isFlush;
      const isEolChange = a.isEolChange && b.isEolChange;
      return {
        changes,
        eol,
        isEolChange,
        versionId,
        isUndoing,
        isRedoing,
        isFlush,
        detailedReasons: a.detailedReasons.concat(b.detailedReasons),
        detailedReasonsChangeLengths: a.detailedReasonsChangeLengths.concat(b.detailedReasonsChangeLengths)
      };
    }
  }
  const ttPolicy$4 = createTrustedTypesPolicy("domLineBreaksComputer", { createHTML: (value) => value });
  class DOMLineBreaksComputerFactory {
    static create(targetWindow) {
      return new DOMLineBreaksComputerFactory(new WeakRef(targetWindow));
    }
    constructor(targetWindow) {
      this.targetWindow = targetWindow;
    }
    createLineBreaksComputer(fontInfo, tabSize, wrappingColumn, wrappingIndent, wordBreak, wrapOnEscapedLineFeeds) {
      const requests = [];
      const injectedTexts = [];
      return {
        addRequest: (lineText, injectedText, previousLineBreakData) => {
          requests.push(lineText);
          injectedTexts.push(injectedText);
        },
        finalize: () => {
          return createLineBreaks$1(assertReturnsDefined(this.targetWindow.deref()), requests, fontInfo, tabSize, wrappingColumn, wrappingIndent, wordBreak, injectedTexts);
        }
      };
    }
  }
  function createLineBreaks$1(targetWindow, requests, fontInfo, tabSize, firstLineBreakColumn, wrappingIndent, wordBreak, injectedTextsPerLine) {
    function createEmptyLineBreakWithPossiblyInjectedText(requestIdx) {
      const injectedTexts = injectedTextsPerLine[requestIdx];
      if (injectedTexts) {
        const lineText = LineInjectedText.applyInjectedText(requests[requestIdx], injectedTexts);
        const injectionOptions = injectedTexts.map((t) => t.options);
        const injectionOffsets = injectedTexts.map((text2) => text2.column - 1);
        return new ModelLineProjectionData(injectionOffsets, injectionOptions, [lineText.length], [], 0);
      } else {
        return null;
      }
    }
    if (firstLineBreakColumn === -1) {
      const result2 = [];
      for (let i2 = 0, len = requests.length; i2 < len; i2++) {
        result2[i2] = createEmptyLineBreakWithPossiblyInjectedText(i2);
      }
      return result2;
    }
    const overallWidth = Math.round(firstLineBreakColumn * fontInfo.typicalHalfwidthCharacterWidth);
    const additionalIndent = wrappingIndent === 3 ? 2 : wrappingIndent === 2 ? 1 : 0;
    const additionalIndentSize = Math.round(tabSize * additionalIndent);
    const additionalIndentLength = Math.ceil(fontInfo.spaceWidth * additionalIndentSize);
    const containerDomNode = document.createElement("div");
    applyFontInfo(containerDomNode, fontInfo);
    const sb = new StringBuilder(1e4);
    const firstNonWhitespaceIndices = [];
    const wrappedTextIndentLengths = [];
    const renderLineContents = [];
    const allCharOffsets = [];
    const allVisibleColumns = [];
    for (let i2 = 0; i2 < requests.length; i2++) {
      const lineContent = LineInjectedText.applyInjectedText(requests[i2], injectedTextsPerLine[i2]);
      let firstNonWhitespaceIndex$1 = 0;
      let wrappedTextIndentLength = 0;
      let width2 = overallWidth;
      if (wrappingIndent !== 0) {
        firstNonWhitespaceIndex$1 = firstNonWhitespaceIndex(lineContent);
        if (firstNonWhitespaceIndex$1 === -1) {
          firstNonWhitespaceIndex$1 = 0;
        } else {
          for (let i3 = 0; i3 < firstNonWhitespaceIndex$1; i3++) {
            const charWidth = lineContent.charCodeAt(i3) === 9 ? tabSize - wrappedTextIndentLength % tabSize : 1;
            wrappedTextIndentLength += charWidth;
          }
          const indentWidth = Math.ceil(fontInfo.spaceWidth * wrappedTextIndentLength);
          if (indentWidth + fontInfo.typicalFullwidthCharacterWidth > overallWidth) {
            firstNonWhitespaceIndex$1 = 0;
            wrappedTextIndentLength = 0;
          } else {
            width2 = overallWidth - indentWidth;
          }
        }
      }
      const renderLineContent = lineContent.substr(firstNonWhitespaceIndex$1);
      const tmp = renderLine(renderLineContent, wrappedTextIndentLength, tabSize, width2, sb, additionalIndentLength);
      firstNonWhitespaceIndices[i2] = firstNonWhitespaceIndex$1;
      wrappedTextIndentLengths[i2] = wrappedTextIndentLength;
      renderLineContents[i2] = renderLineContent;
      allCharOffsets[i2] = tmp[0];
      allVisibleColumns[i2] = tmp[1];
    }
    const html2 = sb.build();
    const trustedhtml = ttPolicy$4?.createHTML(html2) ?? html2;
    containerDomNode.innerHTML = trustedhtml;
    containerDomNode.style.position = "absolute";
    containerDomNode.style.top = "10000";
    if (wordBreak === "keepAll") {
      containerDomNode.style.wordBreak = "keep-all";
      containerDomNode.style.overflowWrap = "anywhere";
    } else {
      containerDomNode.style.wordBreak = "inherit";
      containerDomNode.style.overflowWrap = "break-word";
    }
    targetWindow.document.body.appendChild(containerDomNode);
    const range2 = document.createRange();
    const lineDomNodes = Array.prototype.slice.call(containerDomNode.children, 0);
    const result = [];
    for (let i2 = 0; i2 < requests.length; i2++) {
      const lineDomNode = lineDomNodes[i2];
      const breakOffsets = readLineBreaks(range2, lineDomNode, renderLineContents[i2], allCharOffsets[i2]);
      if (breakOffsets === null) {
        result[i2] = createEmptyLineBreakWithPossiblyInjectedText(i2);
        continue;
      }
      const firstNonWhitespaceIndex2 = firstNonWhitespaceIndices[i2];
      const wrappedTextIndentLength = wrappedTextIndentLengths[i2] + additionalIndentSize;
      const visibleColumns = allVisibleColumns[i2];
      const breakOffsetsVisibleColumn = [];
      for (let j = 0, len = breakOffsets.length; j < len; j++) {
        breakOffsetsVisibleColumn[j] = visibleColumns[breakOffsets[j]];
      }
      if (firstNonWhitespaceIndex2 !== 0) {
        for (let j = 0, len = breakOffsets.length; j < len; j++) {
          breakOffsets[j] += firstNonWhitespaceIndex2;
        }
      }
      let injectionOptions;
      let injectionOffsets;
      const curInjectedTexts = injectedTextsPerLine[i2];
      if (curInjectedTexts) {
        injectionOptions = curInjectedTexts.map((t) => t.options);
        injectionOffsets = curInjectedTexts.map((text2) => text2.column - 1);
      } else {
        injectionOptions = null;
        injectionOffsets = null;
      }
      result[i2] = new ModelLineProjectionData(injectionOffsets, injectionOptions, breakOffsets, breakOffsetsVisibleColumn, wrappedTextIndentLength);
    }
    containerDomNode.remove();
    return result;
  }
  function renderLine(lineContent, initialVisibleColumn, tabSize, width2, sb, wrappingIndentLength) {
    if (wrappingIndentLength !== 0) {
      const hangingOffset = String(wrappingIndentLength);
      sb.appendString('<div style="text-indent: -');
      sb.appendString(hangingOffset);
      sb.appendString("px; padding-left: ");
      sb.appendString(hangingOffset);
      sb.appendString("px; box-sizing: border-box; width:");
    } else {
      sb.appendString('<div style="width:');
    }
    sb.appendString(String(width2));
    sb.appendString('px;">');
    const len = lineContent.length;
    let visibleColumn = initialVisibleColumn;
    let charOffset = 0;
    const charOffsets = [];
    const visibleColumns = [];
    let nextCharCode = 0 < len ? lineContent.charCodeAt(0) : 0;
    sb.appendString("<span>");
    for (let charIndex = 0; charIndex < len; charIndex++) {
      if (charIndex !== 0 && charIndex % 16384 === 0) {
        sb.appendString("</span><span>");
      }
      charOffsets[charIndex] = charOffset;
      visibleColumns[charIndex] = visibleColumn;
      const charCode = nextCharCode;
      nextCharCode = charIndex + 1 < len ? lineContent.charCodeAt(charIndex + 1) : 0;
      let producedCharacters = 1;
      let charWidth = 1;
      switch (charCode) {
        case 9:
          producedCharacters = tabSize - visibleColumn % tabSize;
          charWidth = producedCharacters;
          for (let space = 1; space <= producedCharacters; space++) {
            if (space < producedCharacters) {
              sb.appendCharCode(160);
            } else {
              sb.appendASCIICharCode(
                32
                /* CharCode.Space */
              );
            }
          }
          break;
        case 32:
          if (nextCharCode === 32) {
            sb.appendCharCode(160);
          } else {
            sb.appendASCIICharCode(
              32
              /* CharCode.Space */
            );
          }
          break;
        case 60:
          sb.appendString("&lt;");
          break;
        case 62:
          sb.appendString("&gt;");
          break;
        case 38:
          sb.appendString("&amp;");
          break;
        case 0:
          sb.appendString("&#00;");
          break;
        case 65279:
        case 8232:
        case 8233:
        case 133:
          sb.appendCharCode(65533);
          break;
        default:
          if (isFullWidthCharacter(charCode)) {
            charWidth++;
          }
          if (charCode < 32) {
            sb.appendCharCode(9216 + charCode);
          } else {
            sb.appendCharCode(charCode);
          }
      }
      charOffset += producedCharacters;
      visibleColumn += charWidth;
    }
    sb.appendString("</span>");
    charOffsets[lineContent.length] = charOffset;
    visibleColumns[lineContent.length] = visibleColumn;
    sb.appendString("</div>");
    return [charOffsets, visibleColumns];
  }
  function readLineBreaks(range2, lineDomNode, lineContent, charOffsets) {
    if (lineContent.length <= 1) {
      return null;
    }
    const spans = Array.prototype.slice.call(lineDomNode.children, 0);
    const breakOffsets = [];
    try {
      discoverBreaks(range2, spans, charOffsets, 0, null, lineContent.length - 1, null, breakOffsets);
    } catch (err) {
      console.log(err);
      return null;
    }
    if (breakOffsets.length === 0) {
      return null;
    }
    breakOffsets.push(lineContent.length);
    return breakOffsets;
  }
  function discoverBreaks(range2, spans, charOffsets, low, lowRects, high, highRects, result) {
    if (low === high) {
      return;
    }
    lowRects = lowRects || readClientRect(range2, spans, charOffsets[low], charOffsets[low + 1]);
    highRects = highRects || readClientRect(range2, spans, charOffsets[high], charOffsets[high + 1]);
    if (Math.abs(lowRects[0].top - highRects[0].top) <= 0.1) {
      return;
    }
    if (low + 1 === high) {
      result.push(high);
      return;
    }
    const mid = low + (high - low) / 2 | 0;
    const midRects = readClientRect(range2, spans, charOffsets[mid], charOffsets[mid + 1]);
    discoverBreaks(range2, spans, charOffsets, low, lowRects, mid, midRects, result);
    discoverBreaks(range2, spans, charOffsets, mid, midRects, high, highRects, result);
  }
  function readClientRect(range2, spans, startOffset, endOffset) {
    range2.setStart(
      spans[startOffset / 16384 | 0].firstChild,
      startOffset % 16384
      /* Constants.SPAN_MODULO_LIMIT */
    );
    range2.setEnd(
      spans[endOffset / 16384 | 0].firstChild,
      endOffset % 16384
      /* Constants.SPAN_MODULO_LIMIT */
    );
    return range2.getClientRects();
  }
  class CodeEditorContributions extends Disposable {
    constructor() {
      super();
      this._editor = null;
      this._instantiationService = null;
      this._instances = this._register(new DisposableMap());
      this._pending = /* @__PURE__ */ new Map();
      this._finishedInstantiation = [];
      this._finishedInstantiation[
        0
        /* EditorContributionInstantiation.Eager */
      ] = false;
      this._finishedInstantiation[
        1
        /* EditorContributionInstantiation.AfterFirstRender */
      ] = false;
      this._finishedInstantiation[
        2
        /* EditorContributionInstantiation.BeforeFirstInteraction */
      ] = false;
      this._finishedInstantiation[
        3
        /* EditorContributionInstantiation.Eventually */
      ] = false;
    }
    initialize(editor2, contributions, instantiationService) {
      this._editor = editor2;
      this._instantiationService = instantiationService;
      for (const desc of contributions) {
        if (this._pending.has(desc.id)) {
          onUnexpectedError(new Error(`Cannot have two contributions with the same id ${desc.id}`));
          continue;
        }
        this._pending.set(desc.id, desc);
      }
      this._instantiateSome(
        0
        /* EditorContributionInstantiation.Eager */
      );
      this._register(runWhenWindowIdle(getWindow(this._editor.getDomNode()), () => {
        this._instantiateSome(
          1
          /* EditorContributionInstantiation.AfterFirstRender */
        );
      }));
      this._register(runWhenWindowIdle(getWindow(this._editor.getDomNode()), () => {
        this._instantiateSome(
          2
          /* EditorContributionInstantiation.BeforeFirstInteraction */
        );
      }));
      this._register(runWhenWindowIdle(getWindow(this._editor.getDomNode()), () => {
        this._instantiateSome(
          3
          /* EditorContributionInstantiation.Eventually */
        );
      }, 5e3));
    }
    saveViewState() {
      const contributionsState = {};
      for (const [id, contribution] of this._instances) {
        if (typeof contribution.saveViewState === "function") {
          contributionsState[id] = contribution.saveViewState();
        }
      }
      return contributionsState;
    }
    restoreViewState(contributionsState) {
      for (const [id, contribution] of this._instances) {
        if (typeof contribution.restoreViewState === "function") {
          contribution.restoreViewState(contributionsState[id]);
        }
      }
    }
    get(id) {
      this._instantiateById(id);
      return this._instances.get(id) || null;
    }
    onBeforeInteractionEvent() {
      this._instantiateSome(
        2
        /* EditorContributionInstantiation.BeforeFirstInteraction */
      );
    }
    onAfterModelAttached() {
      return runWhenWindowIdle(getWindow(this._editor?.getDomNode()), () => {
        this._instantiateSome(
          1
          /* EditorContributionInstantiation.AfterFirstRender */
        );
      }, 50);
    }
    _instantiateSome(instantiation) {
      if (this._finishedInstantiation[instantiation]) {
        return;
      }
      this._finishedInstantiation[instantiation] = true;
      const contribs = this._findPendingContributionsByInstantiation(instantiation);
      for (const contrib of contribs) {
        this._instantiateById(contrib.id);
      }
    }
    _findPendingContributionsByInstantiation(instantiation) {
      const result = [];
      for (const [, desc] of this._pending) {
        if (desc.instantiation === instantiation) {
          result.push(desc);
        }
      }
      return result;
    }
    _instantiateById(id) {
      const desc = this._pending.get(id);
      if (!desc) {
        return;
      }
      this._pending.delete(id);
      if (!this._instantiationService || !this._editor) {
        throw new Error(`Cannot instantiate contributions before being initialized!`);
      }
      try {
        const instance = this._instantiationService.createInstance(desc.ctor, this._editor);
        this._instances.set(desc.id, instance);
        if (typeof instance.restoreViewState === "function" && desc.instantiation !== 0) {
          console.warn(`Editor contribution '${desc.id}' should be eager instantiated because it uses saveViewState / restoreViewState.`);
        }
      } catch (err) {
        onUnexpectedError(err);
      }
    }
  }
  class InternalEditorAction {
    constructor(id, label, alias, metadata, _precondition, _run, _contextKeyService) {
      this.id = id;
      this.label = label;
      this.alias = alias;
      this.metadata = metadata;
      this._precondition = _precondition;
      this._run = _run;
      this._contextKeyService = _contextKeyService;
    }
    isSupported() {
      return this._contextKeyService.contextMatchesRules(this._precondition);
    }
    run(args) {
      if (!this.isSupported()) {
        return Promise.resolve(void 0);
      }
      return this._run(args);
    }
  }
  const EditorType = {
    ICodeEditor: "vs.editor.ICodeEditor",
    IDiffEditor: "vs.editor.IDiffEditor"
  };
  function countEOL(text2) {
    let eolCount = 0;
    let firstLineLength = 0;
    let lastLineStart = 0;
    let eol = 0;
    for (let i2 = 0, len = text2.length; i2 < len; i2++) {
      const chr = text2.charCodeAt(i2);
      if (chr === 13) {
        if (eolCount === 0) {
          firstLineLength = i2;
        }
        eolCount++;
        if (i2 + 1 < len && text2.charCodeAt(i2 + 1) === 10) {
          eol |= 2;
          i2++;
        } else {
          eol |= 3;
        }
        lastLineStart = i2 + 1;
      } else if (chr === 10) {
        eol |= 1;
        if (eolCount === 0) {
          firstLineLength = i2;
        }
        eolCount++;
        lastLineStart = i2 + 1;
      }
    }
    if (eolCount === 0) {
      firstLineLength = text2.length;
    }
    return [eolCount, firstLineLength, text2.length - lastLineStart, eol];
  }
  class BracketInfo {
    constructor(range2, nestingLevel, nestingLevelOfEqualBracketType, isInvalid) {
      this.range = range2;
      this.nestingLevel = nestingLevel;
      this.nestingLevelOfEqualBracketType = nestingLevelOfEqualBracketType;
      this.isInvalid = isInvalid;
    }
  }
  class BracketPairInfo {
    constructor(range2, openingBracketRange, closingBracketRange, nestingLevel, nestingLevelOfEqualBracketType, bracketPairNode) {
      this.range = range2;
      this.openingBracketRange = openingBracketRange;
      this.closingBracketRange = closingBracketRange;
      this.nestingLevel = nestingLevel;
      this.nestingLevelOfEqualBracketType = nestingLevelOfEqualBracketType;
      this.bracketPairNode = bracketPairNode;
    }
    get openingBracketInfo() {
      return this.bracketPairNode.openingBracket.bracketInfo;
    }
  }
  class BracketPairWithMinIndentationInfo extends BracketPairInfo {
    constructor(range2, openingBracketRange, closingBracketRange, nestingLevel, nestingLevelOfEqualBracketType, bracketPairNode, minVisibleColumnIndentation) {
      super(range2, openingBracketRange, closingBracketRange, nestingLevel, nestingLevelOfEqualBracketType, bracketPairNode);
      this.minVisibleColumnIndentation = minVisibleColumnIndentation;
    }
  }
  function lengthDiff(startLineCount, startColumnCount, endLineCount, endColumnCount) {
    return startLineCount !== endLineCount ? toLength(endLineCount - startLineCount, endColumnCount) : toLength(0, endColumnCount - startColumnCount);
  }
  const lengthZero = 0;
  function lengthIsZero(length) {
    return length === 0;
  }
  const factor = 2 ** 26;
  function toLength(lineCount, columnCount) {
    return lineCount * factor + columnCount;
  }
  function lengthToObj(length) {
    const l = length;
    const lineCount = Math.floor(l / factor);
    const columnCount = l - lineCount * factor;
    return new TextLength(lineCount, columnCount);
  }
  function lengthGetLineCount(length) {
    return Math.floor(length / factor);
  }
  function lengthGetColumnCountIfZeroLineCount(length) {
    return length;
  }
  function lengthAdd(l1, l2) {
    let r = l1 + l2;
    if (l2 >= factor) {
      r = r - l1 % factor;
    }
    return r;
  }
  function sumLengths(items, lengthFn) {
    return items.reduce((a, b) => lengthAdd(a, lengthFn(b)), lengthZero);
  }
  function lengthEquals(length1, length2) {
    return length1 === length2;
  }
  function lengthDiffNonNegative(length1, length2) {
    const l1 = length1;
    const l2 = length2;
    const diff = l2 - l1;
    if (diff <= 0) {
      return lengthZero;
    }
    const lineCount1 = Math.floor(l1 / factor);
    const lineCount2 = Math.floor(l2 / factor);
    const colCount2 = l2 - lineCount2 * factor;
    if (lineCount1 === lineCount2) {
      const colCount1 = l1 - lineCount1 * factor;
      return toLength(0, colCount2 - colCount1);
    } else {
      return toLength(lineCount2 - lineCount1, colCount2);
    }
  }
  function lengthLessThan(length1, length2) {
    return length1 < length2;
  }
  function lengthLessThanEqual(length1, length2) {
    return length1 <= length2;
  }
  function lengthGreaterThanEqual(length1, length2) {
    return length1 >= length2;
  }
  function positionToLength(position) {
    return toLength(position.lineNumber - 1, position.column - 1);
  }
  function lengthsToRange(lengthStart, lengthEnd) {
    const l = lengthStart;
    const lineCount = Math.floor(l / factor);
    const colCount = l - lineCount * factor;
    const l2 = lengthEnd;
    const lineCount2 = Math.floor(l2 / factor);
    const colCount2 = l2 - lineCount2 * factor;
    return new Range$2(lineCount + 1, colCount + 1, lineCount2 + 1, colCount2 + 1);
  }
  function lengthOfString(str) {
    const lines = splitLines(str);
    return toLength(lines.length - 1, lines[lines.length - 1].length);
  }
  class TextEditInfo {
    static fromModelContentChanges(changes) {
      const edits = changes.map((c) => {
        const range2 = Range$2.lift(c.range);
        return new TextEditInfo(positionToLength(range2.getStartPosition()), positionToLength(range2.getEndPosition()), lengthOfString(c.text));
      }).reverse();
      return edits;
    }
    constructor(startOffset, endOffset, newLength) {
      this.startOffset = startOffset;
      this.endOffset = endOffset;
      this.newLength = newLength;
    }
    toString() {
      return `[${lengthToObj(this.startOffset)}...${lengthToObj(this.endOffset)}) -> ${lengthToObj(this.newLength)}`;
    }
  }
  class BeforeEditPositionMapper {
    /**
     * @param edits Must be sorted by offset in ascending order.
    */
    constructor(edits) {
      this.nextEditIdx = 0;
      this.deltaOldToNewLineCount = 0;
      this.deltaOldToNewColumnCount = 0;
      this.deltaLineIdxInOld = -1;
      this.edits = edits.map((edit2) => TextEditInfoCache.from(edit2));
    }
    /**
     * @param offset Must be equal to or greater than the last offset this method has been called with.
    */
    getOffsetBeforeChange(offset) {
      this.adjustNextEdit(offset);
      return this.translateCurToOld(offset);
    }
    /**
     * @param offset Must be equal to or greater than the last offset this method has been called with.
     * Returns null if there is no edit anymore.
    */
    getDistanceToNextChange(offset) {
      this.adjustNextEdit(offset);
      const nextEdit = this.edits[this.nextEditIdx];
      const nextChangeOffset = nextEdit ? this.translateOldToCur(nextEdit.offsetObj) : null;
      if (nextChangeOffset === null) {
        return null;
      }
      return lengthDiffNonNegative(offset, nextChangeOffset);
    }
    translateOldToCur(oldOffsetObj) {
      if (oldOffsetObj.lineCount === this.deltaLineIdxInOld) {
        return toLength(oldOffsetObj.lineCount + this.deltaOldToNewLineCount, oldOffsetObj.columnCount + this.deltaOldToNewColumnCount);
      } else {
        return toLength(oldOffsetObj.lineCount + this.deltaOldToNewLineCount, oldOffsetObj.columnCount);
      }
    }
    translateCurToOld(newOffset) {
      const offsetObj = lengthToObj(newOffset);
      if (offsetObj.lineCount - this.deltaOldToNewLineCount === this.deltaLineIdxInOld) {
        return toLength(offsetObj.lineCount - this.deltaOldToNewLineCount, offsetObj.columnCount - this.deltaOldToNewColumnCount);
      } else {
        return toLength(offsetObj.lineCount - this.deltaOldToNewLineCount, offsetObj.columnCount);
      }
    }
    adjustNextEdit(offset) {
      while (this.nextEditIdx < this.edits.length) {
        const nextEdit = this.edits[this.nextEditIdx];
        const nextEditEndOffsetInCur = this.translateOldToCur(nextEdit.endOffsetAfterObj);
        if (lengthLessThanEqual(nextEditEndOffsetInCur, offset)) {
          this.nextEditIdx++;
          const nextEditEndOffsetInCurObj = lengthToObj(nextEditEndOffsetInCur);
          const nextEditEndOffsetBeforeInCurObj = lengthToObj(this.translateOldToCur(nextEdit.endOffsetBeforeObj));
          const lineDelta = nextEditEndOffsetInCurObj.lineCount - nextEditEndOffsetBeforeInCurObj.lineCount;
          this.deltaOldToNewLineCount += lineDelta;
          const previousColumnDelta = this.deltaLineIdxInOld === nextEdit.endOffsetBeforeObj.lineCount ? this.deltaOldToNewColumnCount : 0;
          const columnDelta = nextEditEndOffsetInCurObj.columnCount - nextEditEndOffsetBeforeInCurObj.columnCount;
          this.deltaOldToNewColumnCount = previousColumnDelta + columnDelta;
          this.deltaLineIdxInOld = nextEdit.endOffsetBeforeObj.lineCount;
        } else {
          break;
        }
      }
    }
  }
  class TextEditInfoCache {
    static from(edit2) {
      return new TextEditInfoCache(edit2.startOffset, edit2.endOffset, edit2.newLength);
    }
    constructor(startOffset, endOffset, textLength) {
      this.endOffsetBeforeObj = lengthToObj(endOffset);
      this.endOffsetAfterObj = lengthToObj(lengthAdd(startOffset, textLength));
      this.offsetObj = lengthToObj(startOffset);
    }
  }
  const emptyArr$2 = [];
  const _SmallImmutableSet = class _SmallImmutableSet {
    static create(items, additionalItems) {
      if (items <= 128 && additionalItems.length === 0) {
        let cached = _SmallImmutableSet.cache[items];
        if (!cached) {
          cached = new _SmallImmutableSet(items, additionalItems);
          _SmallImmutableSet.cache[items] = cached;
        }
        return cached;
      }
      return new _SmallImmutableSet(items, additionalItems);
    }
    static getEmpty() {
      return this.empty;
    }
    constructor(items, additionalItems) {
      this.items = items;
      this.additionalItems = additionalItems;
    }
    add(value, keyProvider) {
      const key = keyProvider.getKey(value);
      let idx = key >> 5;
      if (idx === 0) {
        const newItem = 1 << key | this.items;
        if (newItem === this.items) {
          return this;
        }
        return _SmallImmutableSet.create(newItem, this.additionalItems);
      }
      idx--;
      const newItems = this.additionalItems.slice(0);
      while (newItems.length < idx) {
        newItems.push(0);
      }
      newItems[idx] |= 1 << (key & 31);
      return _SmallImmutableSet.create(this.items, newItems);
    }
    merge(other) {
      const merged = this.items | other.items;
      if (this.additionalItems === emptyArr$2 && other.additionalItems === emptyArr$2) {
        if (merged === this.items) {
          return this;
        }
        if (merged === other.items) {
          return other;
        }
        return _SmallImmutableSet.create(merged, emptyArr$2);
      }
      const newItems = [];
      for (let i2 = 0; i2 < Math.max(this.additionalItems.length, other.additionalItems.length); i2++) {
        const item1 = this.additionalItems[i2] || 0;
        const item2 = other.additionalItems[i2] || 0;
        newItems.push(item1 | item2);
      }
      return _SmallImmutableSet.create(merged, newItems);
    }
    intersects(other) {
      if ((this.items & other.items) !== 0) {
        return true;
      }
      for (let i2 = 0; i2 < Math.min(this.additionalItems.length, other.additionalItems.length); i2++) {
        if ((this.additionalItems[i2] & other.additionalItems[i2]) !== 0) {
          return true;
        }
      }
      return false;
    }
  };
  _SmallImmutableSet.cache = new Array(129);
  _SmallImmutableSet.empty = _SmallImmutableSet.create(0, emptyArr$2);
  let SmallImmutableSet = _SmallImmutableSet;
  const identityKeyProvider = {
    getKey(value) {
      return value;
    }
  };
  class DenseKeyProvider {
    constructor() {
      this.items = /* @__PURE__ */ new Map();
    }
    getKey(value) {
      let existing = this.items.get(value);
      if (existing === void 0) {
        existing = this.items.size;
        this.items.set(value, existing);
      }
      return existing;
    }
  }
  class BaseAstNode {
    /**
     * The length of the entire node, which should equal the sum of lengths of all children.
    */
    get length() {
      return this._length;
    }
    constructor(length) {
      this._length = length;
    }
  }
  class PairAstNode extends BaseAstNode {
    static create(openingBracket, child, closingBracket) {
      let length = openingBracket.length;
      if (child) {
        length = lengthAdd(length, child.length);
      }
      if (closingBracket) {
        length = lengthAdd(length, closingBracket.length);
      }
      return new PairAstNode(length, openingBracket, child, closingBracket, child ? child.missingOpeningBracketIds : SmallImmutableSet.getEmpty());
    }
    get kind() {
      return 2;
    }
    get listHeight() {
      return 0;
    }
    get childrenLength() {
      return 3;
    }
    getChild(idx) {
      switch (idx) {
        case 0:
          return this.openingBracket;
        case 1:
          return this.child;
        case 2:
          return this.closingBracket;
      }
      throw new Error("Invalid child index");
    }
    /**
     * Avoid using this property, it allocates an array!
    */
    get children() {
      const result = [];
      result.push(this.openingBracket);
      if (this.child) {
        result.push(this.child);
      }
      if (this.closingBracket) {
        result.push(this.closingBracket);
      }
      return result;
    }
    constructor(length, openingBracket, child, closingBracket, missingOpeningBracketIds) {
      super(length);
      this.openingBracket = openingBracket;
      this.child = child;
      this.closingBracket = closingBracket;
      this.missingOpeningBracketIds = missingOpeningBracketIds;
    }
    canBeReused(openBracketIds) {
      if (this.closingBracket === null) {
        return false;
      }
      if (openBracketIds.intersects(this.missingOpeningBracketIds)) {
        return false;
      }
      return true;
    }
    deepClone() {
      return new PairAstNode(this.length, this.openingBracket.deepClone(), this.child && this.child.deepClone(), this.closingBracket && this.closingBracket.deepClone(), this.missingOpeningBracketIds);
    }
    computeMinIndentation(offset, textModel) {
      return this.child ? this.child.computeMinIndentation(lengthAdd(offset, this.openingBracket.length), textModel) : Number.MAX_SAFE_INTEGER;
    }
  }
  class ListAstNode extends BaseAstNode {
    /**
     * This method uses more memory-efficient list nodes that can only store 2 or 3 children.
    */
    static create23(item1, item2, item3, immutable = false) {
      let length = item1.length;
      let missingBracketIds = item1.missingOpeningBracketIds;
      if (item1.listHeight !== item2.listHeight) {
        throw new Error("Invalid list heights");
      }
      length = lengthAdd(length, item2.length);
      missingBracketIds = missingBracketIds.merge(item2.missingOpeningBracketIds);
      if (item3) {
        if (item1.listHeight !== item3.listHeight) {
          throw new Error("Invalid list heights");
        }
        length = lengthAdd(length, item3.length);
        missingBracketIds = missingBracketIds.merge(item3.missingOpeningBracketIds);
      }
      return immutable ? new Immutable23ListAstNode(length, item1.listHeight + 1, item1, item2, item3, missingBracketIds) : new TwoThreeListAstNode(length, item1.listHeight + 1, item1, item2, item3, missingBracketIds);
    }
    static getEmpty() {
      return new ImmutableArrayListAstNode(lengthZero, 0, [], SmallImmutableSet.getEmpty());
    }
    get kind() {
      return 4;
    }
    get missingOpeningBracketIds() {
      return this._missingOpeningBracketIds;
    }
    /**
     * Use ListAstNode.create.
    */
    constructor(length, listHeight, _missingOpeningBracketIds) {
      super(length);
      this.listHeight = listHeight;
      this._missingOpeningBracketIds = _missingOpeningBracketIds;
      this.cachedMinIndentation = -1;
    }
    throwIfImmutable() {
    }
    makeLastElementMutable() {
      this.throwIfImmutable();
      const childCount = this.childrenLength;
      if (childCount === 0) {
        return void 0;
      }
      const lastChild = this.getChild(childCount - 1);
      const mutable = lastChild.kind === 4 ? lastChild.toMutable() : lastChild;
      if (lastChild !== mutable) {
        this.setChild(childCount - 1, mutable);
      }
      return mutable;
    }
    makeFirstElementMutable() {
      this.throwIfImmutable();
      const childCount = this.childrenLength;
      if (childCount === 0) {
        return void 0;
      }
      const firstChild = this.getChild(0);
      const mutable = firstChild.kind === 4 ? firstChild.toMutable() : firstChild;
      if (firstChild !== mutable) {
        this.setChild(0, mutable);
      }
      return mutable;
    }
    canBeReused(openBracketIds) {
      if (openBracketIds.intersects(this.missingOpeningBracketIds)) {
        return false;
      }
      if (this.childrenLength === 0) {
        return false;
      }
      let lastChild = this;
      while (lastChild.kind === 4) {
        const lastLength = lastChild.childrenLength;
        if (lastLength === 0) {
          throw new BugIndicatingError();
        }
        lastChild = lastChild.getChild(lastLength - 1);
      }
      return lastChild.canBeReused(openBracketIds);
    }
    handleChildrenChanged() {
      this.throwIfImmutable();
      const count = this.childrenLength;
      let length = this.getChild(0).length;
      let unopenedBrackets = this.getChild(0).missingOpeningBracketIds;
      for (let i2 = 1; i2 < count; i2++) {
        const child = this.getChild(i2);
        length = lengthAdd(length, child.length);
        unopenedBrackets = unopenedBrackets.merge(child.missingOpeningBracketIds);
      }
      this._length = length;
      this._missingOpeningBracketIds = unopenedBrackets;
      this.cachedMinIndentation = -1;
    }
    computeMinIndentation(offset, textModel) {
      if (this.cachedMinIndentation !== -1) {
        return this.cachedMinIndentation;
      }
      let minIndentation = Number.MAX_SAFE_INTEGER;
      let childOffset = offset;
      for (let i2 = 0; i2 < this.childrenLength; i2++) {
        const child = this.getChild(i2);
        if (child) {
          minIndentation = Math.min(minIndentation, child.computeMinIndentation(childOffset, textModel));
          childOffset = lengthAdd(childOffset, child.length);
        }
      }
      this.cachedMinIndentation = minIndentation;
      return minIndentation;
    }
  }
  class TwoThreeListAstNode extends ListAstNode {
    get childrenLength() {
      return this._item3 !== null ? 3 : 2;
    }
    getChild(idx) {
      switch (idx) {
        case 0:
          return this._item1;
        case 1:
          return this._item2;
        case 2:
          return this._item3;
      }
      throw new Error("Invalid child index");
    }
    setChild(idx, node) {
      switch (idx) {
        case 0:
          this._item1 = node;
          return;
        case 1:
          this._item2 = node;
          return;
        case 2:
          this._item3 = node;
          return;
      }
      throw new Error("Invalid child index");
    }
    get children() {
      return this._item3 ? [this._item1, this._item2, this._item3] : [this._item1, this._item2];
    }
    get item1() {
      return this._item1;
    }
    get item2() {
      return this._item2;
    }
    get item3() {
      return this._item3;
    }
    constructor(length, listHeight, _item1, _item2, _item3, missingOpeningBracketIds) {
      super(length, listHeight, missingOpeningBracketIds);
      this._item1 = _item1;
      this._item2 = _item2;
      this._item3 = _item3;
    }
    deepClone() {
      return new TwoThreeListAstNode(this.length, this.listHeight, this._item1.deepClone(), this._item2.deepClone(), this._item3 ? this._item3.deepClone() : null, this.missingOpeningBracketIds);
    }
    appendChildOfSameHeight(node) {
      if (this._item3) {
        throw new Error("Cannot append to a full (2,3) tree node");
      }
      this.throwIfImmutable();
      this._item3 = node;
      this.handleChildrenChanged();
    }
    unappendChild() {
      if (!this._item3) {
        throw new Error("Cannot remove from a non-full (2,3) tree node");
      }
      this.throwIfImmutable();
      const result = this._item3;
      this._item3 = null;
      this.handleChildrenChanged();
      return result;
    }
    prependChildOfSameHeight(node) {
      if (this._item3) {
        throw new Error("Cannot prepend to a full (2,3) tree node");
      }
      this.throwIfImmutable();
      this._item3 = this._item2;
      this._item2 = this._item1;
      this._item1 = node;
      this.handleChildrenChanged();
    }
    unprependChild() {
      if (!this._item3) {
        throw new Error("Cannot remove from a non-full (2,3) tree node");
      }
      this.throwIfImmutable();
      const result = this._item1;
      this._item1 = this._item2;
      this._item2 = this._item3;
      this._item3 = null;
      this.handleChildrenChanged();
      return result;
    }
    toMutable() {
      return this;
    }
  }
  class Immutable23ListAstNode extends TwoThreeListAstNode {
    toMutable() {
      return new TwoThreeListAstNode(this.length, this.listHeight, this.item1, this.item2, this.item3, this.missingOpeningBracketIds);
    }
    throwIfImmutable() {
      throw new Error("this instance is immutable");
    }
  }
  class ArrayListAstNode extends ListAstNode {
    get childrenLength() {
      return this._children.length;
    }
    getChild(idx) {
      return this._children[idx];
    }
    setChild(idx, child) {
      this._children[idx] = child;
    }
    get children() {
      return this._children;
    }
    constructor(length, listHeight, _children, missingOpeningBracketIds) {
      super(length, listHeight, missingOpeningBracketIds);
      this._children = _children;
    }
    deepClone() {
      const children = new Array(this._children.length);
      for (let i2 = 0; i2 < this._children.length; i2++) {
        children[i2] = this._children[i2].deepClone();
      }
      return new ArrayListAstNode(this.length, this.listHeight, children, this.missingOpeningBracketIds);
    }
    appendChildOfSameHeight(node) {
      this.throwIfImmutable();
      this._children.push(node);
      this.handleChildrenChanged();
    }
    unappendChild() {
      this.throwIfImmutable();
      const item = this._children.pop();
      this.handleChildrenChanged();
      return item;
    }
    prependChildOfSameHeight(node) {
      this.throwIfImmutable();
      this._children.unshift(node);
      this.handleChildrenChanged();
    }
    unprependChild() {
      this.throwIfImmutable();
      const item = this._children.shift();
      this.handleChildrenChanged();
      return item;
    }
    toMutable() {
      return this;
    }
  }
  class ImmutableArrayListAstNode extends ArrayListAstNode {
    toMutable() {
      return new ArrayListAstNode(this.length, this.listHeight, [...this.children], this.missingOpeningBracketIds);
    }
    throwIfImmutable() {
      throw new Error("this instance is immutable");
    }
  }
  const emptyArray = [];
  class ImmutableLeafAstNode extends BaseAstNode {
    get listHeight() {
      return 0;
    }
    get childrenLength() {
      return 0;
    }
    getChild(idx) {
      return null;
    }
    get children() {
      return emptyArray;
    }
    deepClone() {
      return this;
    }
  }
  class TextAstNode extends ImmutableLeafAstNode {
    get kind() {
      return 0;
    }
    get missingOpeningBracketIds() {
      return SmallImmutableSet.getEmpty();
    }
    canBeReused(_openedBracketIds) {
      return true;
    }
    computeMinIndentation(offset, textModel) {
      const start = lengthToObj(offset);
      const startLineNumber = (start.columnCount === 0 ? start.lineCount : start.lineCount + 1) + 1;
      const endLineNumber = lengthGetLineCount(lengthAdd(offset, this.length)) + 1;
      let result = Number.MAX_SAFE_INTEGER;
      for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
        const firstNonWsColumn = textModel.getLineFirstNonWhitespaceColumn(lineNumber);
        const lineContent = textModel.getLineContent(lineNumber);
        if (firstNonWsColumn === 0) {
          continue;
        }
        const visibleColumn = CursorColumns.visibleColumnFromColumn(lineContent, firstNonWsColumn, textModel.getOptions().tabSize);
        result = Math.min(result, visibleColumn);
      }
      return result;
    }
  }
  class BracketAstNode extends ImmutableLeafAstNode {
    static create(length, bracketInfo, bracketIds) {
      const node = new BracketAstNode(length, bracketInfo, bracketIds);
      return node;
    }
    get kind() {
      return 1;
    }
    get missingOpeningBracketIds() {
      return SmallImmutableSet.getEmpty();
    }
    constructor(length, bracketInfo, bracketIds) {
      super(length);
      this.bracketInfo = bracketInfo;
      this.bracketIds = bracketIds;
    }
    get text() {
      return this.bracketInfo.bracketText;
    }
    get languageId() {
      return this.bracketInfo.languageId;
    }
    canBeReused(_openedBracketIds) {
      return false;
    }
    computeMinIndentation(offset, textModel) {
      return Number.MAX_SAFE_INTEGER;
    }
  }
  class InvalidBracketAstNode extends ImmutableLeafAstNode {
    get kind() {
      return 3;
    }
    constructor(closingBrackets, length) {
      super(length);
      this.missingOpeningBracketIds = closingBrackets;
    }
    canBeReused(openedBracketIds) {
      return !openedBracketIds.intersects(this.missingOpeningBracketIds);
    }
    computeMinIndentation(offset, textModel) {
      return Number.MAX_SAFE_INTEGER;
    }
  }
  let Token$1 = class Token {
    constructor(length, kind, bracketId, bracketIds, astNode) {
      this.length = length;
      this.kind = kind;
      this.bracketId = bracketId;
      this.bracketIds = bracketIds;
      this.astNode = astNode;
    }
  };
  class TextBufferTokenizer {
    constructor(textModel, bracketTokens) {
      this.textModel = textModel;
      this.bracketTokens = bracketTokens;
      this.reader = new NonPeekableTextBufferTokenizer(this.textModel, this.bracketTokens);
      this._offset = lengthZero;
      this.didPeek = false;
      this.peeked = null;
      this.textBufferLineCount = textModel.getLineCount();
      this.textBufferLastLineLength = textModel.getLineLength(this.textBufferLineCount);
    }
    get offset() {
      return this._offset;
    }
    get length() {
      return toLength(this.textBufferLineCount - 1, this.textBufferLastLineLength);
    }
    skip(length) {
      this.didPeek = false;
      this._offset = lengthAdd(this._offset, length);
      const obj = lengthToObj(this._offset);
      this.reader.setPosition(obj.lineCount, obj.columnCount);
    }
    read() {
      let token;
      if (this.peeked) {
        this.didPeek = false;
        token = this.peeked;
      } else {
        token = this.reader.read();
      }
      if (token) {
        this._offset = lengthAdd(this._offset, token.length);
      }
      return token;
    }
    peek() {
      if (!this.didPeek) {
        this.peeked = this.reader.read();
        this.didPeek = true;
      }
      return this.peeked;
    }
  }
  class NonPeekableTextBufferTokenizer {
    constructor(textModel, bracketTokens) {
      this.textModel = textModel;
      this.bracketTokens = bracketTokens;
      this.lineIdx = 0;
      this.line = null;
      this.lineCharOffset = 0;
      this.lineTokens = null;
      this.lineTokenOffset = 0;
      this.peekedToken = null;
      this.textBufferLineCount = textModel.getLineCount();
      this.textBufferLastLineLength = textModel.getLineLength(this.textBufferLineCount);
    }
    setPosition(lineIdx, column) {
      if (lineIdx === this.lineIdx) {
        this.lineCharOffset = column;
        if (this.line !== null) {
          this.lineTokenOffset = this.lineCharOffset === 0 ? 0 : this.lineTokens.findTokenIndexAtOffset(this.lineCharOffset);
        }
      } else {
        this.lineIdx = lineIdx;
        this.lineCharOffset = column;
        this.line = null;
      }
      this.peekedToken = null;
    }
    read() {
      if (this.peekedToken) {
        const token = this.peekedToken;
        this.peekedToken = null;
        this.lineCharOffset += lengthGetColumnCountIfZeroLineCount(token.length);
        return token;
      }
      if (this.lineIdx > this.textBufferLineCount - 1 || this.lineIdx === this.textBufferLineCount - 1 && this.lineCharOffset >= this.textBufferLastLineLength) {
        return null;
      }
      if (this.line === null) {
        this.lineTokens = this.textModel.tokenization.getLineTokens(this.lineIdx + 1);
        this.line = this.lineTokens.getLineContent();
        this.lineTokenOffset = this.lineCharOffset === 0 ? 0 : this.lineTokens.findTokenIndexAtOffset(this.lineCharOffset);
      }
      const startLineIdx = this.lineIdx;
      const startLineCharOffset = this.lineCharOffset;
      let lengthHeuristic = 0;
      while (true) {
        const lineTokens = this.lineTokens;
        const tokenCount = lineTokens.getCount();
        let peekedBracketToken = null;
        if (this.lineTokenOffset < tokenCount) {
          const tokenMetadata = lineTokens.getMetadata(this.lineTokenOffset);
          while (this.lineTokenOffset + 1 < tokenCount && tokenMetadata === lineTokens.getMetadata(this.lineTokenOffset + 1)) {
            this.lineTokenOffset++;
          }
          const isOther = TokenMetadata.getTokenType(tokenMetadata) === 0;
          const containsBracketType = TokenMetadata.containsBalancedBrackets(tokenMetadata);
          const endOffset = lineTokens.getEndOffset(this.lineTokenOffset);
          if (containsBracketType && isOther && this.lineCharOffset < endOffset) {
            const languageId = lineTokens.getLanguageId(this.lineTokenOffset);
            const text2 = this.line.substring(this.lineCharOffset, endOffset);
            const brackets = this.bracketTokens.getSingleLanguageBracketTokens(languageId);
            const regexp = brackets.regExpGlobal;
            if (regexp) {
              regexp.lastIndex = 0;
              const match2 = regexp.exec(text2);
              if (match2) {
                peekedBracketToken = brackets.getToken(match2[0]);
                if (peekedBracketToken) {
                  this.lineCharOffset += match2.index;
                }
              }
            }
          }
          lengthHeuristic += endOffset - this.lineCharOffset;
          if (peekedBracketToken) {
            if (startLineIdx !== this.lineIdx || startLineCharOffset !== this.lineCharOffset) {
              this.peekedToken = peekedBracketToken;
              break;
            } else {
              this.lineCharOffset += lengthGetColumnCountIfZeroLineCount(peekedBracketToken.length);
              return peekedBracketToken;
            }
          } else {
            this.lineTokenOffset++;
            this.lineCharOffset = endOffset;
          }
        } else {
          if (this.lineIdx === this.textBufferLineCount - 1) {
            break;
          }
          this.lineIdx++;
          this.lineTokens = this.textModel.tokenization.getLineTokens(this.lineIdx + 1);
          this.lineTokenOffset = 0;
          this.line = this.lineTokens.getLineContent();
          this.lineCharOffset = 0;
          lengthHeuristic += 33;
          if (lengthHeuristic > 1e3) {
            break;
          }
        }
        if (lengthHeuristic > 1500) {
          break;
        }
      }
      const length = lengthDiff(startLineIdx, startLineCharOffset, this.lineIdx, this.lineCharOffset);
      return new Token$1(length, 0, -1, SmallImmutableSet.getEmpty(), new TextAstNode(length));
    }
  }
  class FastTokenizer {
    constructor(text2, brackets) {
      this.text = text2;
      this._offset = lengthZero;
      this.idx = 0;
      const regExpStr = brackets.getRegExpStr();
      const regexp = regExpStr ? new RegExp(regExpStr + "|\n", "gi") : null;
      const tokens = [];
      let match2;
      let curLineCount = 0;
      let lastLineBreakOffset = 0;
      let lastTokenEndOffset = 0;
      let lastTokenEndLine = 0;
      const smallTextTokens0Line = [];
      for (let i2 = 0; i2 < 60; i2++) {
        smallTextTokens0Line.push(new Token$1(toLength(0, i2), 0, -1, SmallImmutableSet.getEmpty(), new TextAstNode(toLength(0, i2))));
      }
      const smallTextTokens1Line = [];
      for (let i2 = 0; i2 < 60; i2++) {
        smallTextTokens1Line.push(new Token$1(toLength(1, i2), 0, -1, SmallImmutableSet.getEmpty(), new TextAstNode(toLength(1, i2))));
      }
      if (regexp) {
        regexp.lastIndex = 0;
        while ((match2 = regexp.exec(text2)) !== null) {
          const curOffset = match2.index;
          const value = match2[0];
          if (value === "\n") {
            curLineCount++;
            lastLineBreakOffset = curOffset + 1;
          } else {
            if (lastTokenEndOffset !== curOffset) {
              let token;
              if (lastTokenEndLine === curLineCount) {
                const colCount = curOffset - lastTokenEndOffset;
                if (colCount < smallTextTokens0Line.length) {
                  token = smallTextTokens0Line[colCount];
                } else {
                  const length = toLength(0, colCount);
                  token = new Token$1(length, 0, -1, SmallImmutableSet.getEmpty(), new TextAstNode(length));
                }
              } else {
                const lineCount = curLineCount - lastTokenEndLine;
                const colCount = curOffset - lastLineBreakOffset;
                if (lineCount === 1 && colCount < smallTextTokens1Line.length) {
                  token = smallTextTokens1Line[colCount];
                } else {
                  const length = toLength(lineCount, colCount);
                  token = new Token$1(length, 0, -1, SmallImmutableSet.getEmpty(), new TextAstNode(length));
                }
              }
              tokens.push(token);
            }
            tokens.push(brackets.getToken(value));
            lastTokenEndOffset = curOffset + value.length;
            lastTokenEndLine = curLineCount;
          }
        }
      }
      const offset = text2.length;
      if (lastTokenEndOffset !== offset) {
        const length = lastTokenEndLine === curLineCount ? toLength(0, offset - lastTokenEndOffset) : toLength(curLineCount - lastTokenEndLine, offset - lastLineBreakOffset);
        tokens.push(new Token$1(length, 0, -1, SmallImmutableSet.getEmpty(), new TextAstNode(length)));
      }
      this.length = toLength(curLineCount, offset - lastLineBreakOffset);
      this.tokens = tokens;
    }
    get offset() {
      return this._offset;
    }
    read() {
      return this.tokens[this.idx++] || null;
    }
    peek() {
      return this.tokens[this.idx] || null;
    }
    skip(length) {
      throw new NotSupportedError();
    }
  }
  class BracketTokens {
    static createFromLanguage(configuration, denseKeyProvider) {
      function getId(bracketInfo) {
        return denseKeyProvider.getKey(`${bracketInfo.languageId}:::${bracketInfo.bracketText}`);
      }
      const map = /* @__PURE__ */ new Map();
      for (const openingBracket of configuration.bracketsNew.openingBrackets) {
        const length = toLength(0, openingBracket.bracketText.length);
        const openingTextId = getId(openingBracket);
        const bracketIds = SmallImmutableSet.getEmpty().add(openingTextId, identityKeyProvider);
        map.set(openingBracket.bracketText, new Token$1(length, 1, openingTextId, bracketIds, BracketAstNode.create(length, openingBracket, bracketIds)));
      }
      for (const closingBracket of configuration.bracketsNew.closingBrackets) {
        const length = toLength(0, closingBracket.bracketText.length);
        let bracketIds = SmallImmutableSet.getEmpty();
        const closingBrackets = closingBracket.getOpeningBrackets();
        for (const bracket of closingBrackets) {
          bracketIds = bracketIds.add(getId(bracket), identityKeyProvider);
        }
        map.set(closingBracket.bracketText, new Token$1(length, 2, getId(closingBrackets[0]), bracketIds, BracketAstNode.create(length, closingBracket, bracketIds)));
      }
      return new BracketTokens(map);
    }
    constructor(map) {
      this.map = map;
      this.hasRegExp = false;
      this._regExpGlobal = null;
    }
    getRegExpStr() {
      if (this.isEmpty) {
        return null;
      } else {
        const keys = [...this.map.keys()];
        keys.sort();
        keys.reverse();
        return keys.map((k) => prepareBracketForRegExp(k)).join("|");
      }
    }
    /**
     * Returns null if there is no such regexp (because there are no brackets).
    */
    get regExpGlobal() {
      if (!this.hasRegExp) {
        const regExpStr = this.getRegExpStr();
        this._regExpGlobal = regExpStr ? new RegExp(regExpStr, "gi") : null;
        this.hasRegExp = true;
      }
      return this._regExpGlobal;
    }
    getToken(value) {
      return this.map.get(value.toLowerCase());
    }
    findClosingTokenText(openingBracketIds) {
      for (const [closingText, info] of this.map) {
        if (info.kind === 2 && info.bracketIds.intersects(openingBracketIds)) {
          return closingText;
        }
      }
      return void 0;
    }
    get isEmpty() {
      return this.map.size === 0;
    }
  }
  function prepareBracketForRegExp(str) {
    let escaped = escapeRegExpCharacters(str);
    if (/^[\w ]+/.test(str)) {
      escaped = `\\b${escaped}`;
    }
    if (/[\w ]+$/.test(str)) {
      escaped = `${escaped}\\b`;
    }
    return escaped;
  }
  class LanguageAgnosticBracketTokens {
    constructor(denseKeyProvider, getLanguageConfiguration) {
      this.denseKeyProvider = denseKeyProvider;
      this.getLanguageConfiguration = getLanguageConfiguration;
      this.languageIdToBracketTokens = /* @__PURE__ */ new Map();
    }
    didLanguageChange(languageId) {
      return this.languageIdToBracketTokens.has(languageId);
    }
    getSingleLanguageBracketTokens(languageId) {
      let singleLanguageBracketTokens = this.languageIdToBracketTokens.get(languageId);
      if (!singleLanguageBracketTokens) {
        singleLanguageBracketTokens = BracketTokens.createFromLanguage(this.getLanguageConfiguration(languageId), this.denseKeyProvider);
        this.languageIdToBracketTokens.set(languageId, singleLanguageBracketTokens);
      }
      return singleLanguageBracketTokens;
    }
  }
  function concat23Trees(items) {
    if (items.length === 0) {
      return null;
    }
    if (items.length === 1) {
      return items[0];
    }
    let i2 = 0;
    function readNode() {
      if (i2 >= items.length) {
        return null;
      }
      const start = i2;
      const height = items[start].listHeight;
      i2++;
      while (i2 < items.length && items[i2].listHeight === height) {
        i2++;
      }
      if (i2 - start >= 2) {
        return concat23TreesOfSameHeight(start === 0 && i2 === items.length ? items : items.slice(start, i2), false);
      } else {
        return items[start];
      }
    }
    let first2 = readNode();
    let second = readNode();
    if (!second) {
      return first2;
    }
    for (let item = readNode(); item; item = readNode()) {
      if (heightDiff(first2, second) <= heightDiff(second, item)) {
        first2 = concat$2(first2, second);
        second = item;
      } else {
        second = concat$2(second, item);
      }
    }
    const result = concat$2(first2, second);
    return result;
  }
  function concat23TreesOfSameHeight(items, createImmutableLists = false) {
    if (items.length === 0) {
      return null;
    }
    if (items.length === 1) {
      return items[0];
    }
    let length = items.length;
    while (length > 3) {
      const newLength = length >> 1;
      for (let i2 = 0; i2 < newLength; i2++) {
        const j = i2 << 1;
        items[i2] = ListAstNode.create23(items[j], items[j + 1], j + 3 === length ? items[j + 2] : null, createImmutableLists);
      }
      length = newLength;
    }
    return ListAstNode.create23(items[0], items[1], length >= 3 ? items[2] : null, createImmutableLists);
  }
  function heightDiff(node1, node2) {
    return Math.abs(node1.listHeight - node2.listHeight);
  }
  function concat$2(node1, node2) {
    if (node1.listHeight === node2.listHeight) {
      return ListAstNode.create23(node1, node2, null, false);
    } else if (node1.listHeight > node2.listHeight) {
      return append$1(node1, node2);
    } else {
      return prepend$1(node2, node1);
    }
  }
  function append$1(list2, nodeToAppend) {
    list2 = list2.toMutable();
    let curNode = list2;
    const parents = [];
    let nodeToAppendOfCorrectHeight;
    while (true) {
      if (nodeToAppend.listHeight === curNode.listHeight) {
        nodeToAppendOfCorrectHeight = nodeToAppend;
        break;
      }
      if (curNode.kind !== 4) {
        throw new Error("unexpected");
      }
      parents.push(curNode);
      curNode = curNode.makeLastElementMutable();
    }
    for (let i2 = parents.length - 1; i2 >= 0; i2--) {
      const parent = parents[i2];
      if (nodeToAppendOfCorrectHeight) {
        if (parent.childrenLength >= 3) {
          nodeToAppendOfCorrectHeight = ListAstNode.create23(parent.unappendChild(), nodeToAppendOfCorrectHeight, null, false);
        } else {
          parent.appendChildOfSameHeight(nodeToAppendOfCorrectHeight);
          nodeToAppendOfCorrectHeight = void 0;
        }
      } else {
        parent.handleChildrenChanged();
      }
    }
    if (nodeToAppendOfCorrectHeight) {
      return ListAstNode.create23(list2, nodeToAppendOfCorrectHeight, null, false);
    } else {
      return list2;
    }
  }
  function prepend$1(list2, nodeToAppend) {
    list2 = list2.toMutable();
    let curNode = list2;
    const parents = [];
    while (nodeToAppend.listHeight !== curNode.listHeight) {
      if (curNode.kind !== 4) {
        throw new Error("unexpected");
      }
      parents.push(curNode);
      curNode = curNode.makeFirstElementMutable();
    }
    let nodeToPrependOfCorrectHeight = nodeToAppend;
    for (let i2 = parents.length - 1; i2 >= 0; i2--) {
      const parent = parents[i2];
      if (nodeToPrependOfCorrectHeight) {
        if (parent.childrenLength >= 3) {
          nodeToPrependOfCorrectHeight = ListAstNode.create23(nodeToPrependOfCorrectHeight, parent.unprependChild(), null, false);
        } else {
          parent.prependChildOfSameHeight(nodeToPrependOfCorrectHeight);
          nodeToPrependOfCorrectHeight = void 0;
        }
      } else {
        parent.handleChildrenChanged();
      }
    }
    if (nodeToPrependOfCorrectHeight) {
      return ListAstNode.create23(nodeToPrependOfCorrectHeight, list2, null, false);
    } else {
      return list2;
    }
  }
  class NodeReader {
    constructor(node) {
      this.lastOffset = lengthZero;
      this.nextNodes = [node];
      this.offsets = [lengthZero];
      this.idxs = [];
    }
    /**
     * Returns the longest node at `offset` that satisfies the predicate.
     * @param offset must be greater than or equal to the last offset this method has been called with!
    */
    readLongestNodeAt(offset, predicate) {
      if (lengthLessThan(offset, this.lastOffset)) {
        throw new Error("Invalid offset");
      }
      this.lastOffset = offset;
      while (true) {
        const curNode = lastOrUndefined(this.nextNodes);
        if (!curNode) {
          return void 0;
        }
        const curNodeOffset = lastOrUndefined(this.offsets);
        if (lengthLessThan(offset, curNodeOffset)) {
          return void 0;
        }
        if (lengthLessThan(curNodeOffset, offset)) {
          if (lengthAdd(curNodeOffset, curNode.length) <= offset) {
            this.nextNodeAfterCurrent();
          } else {
            const nextChildIdx = getNextChildIdx(curNode);
            if (nextChildIdx !== -1) {
              this.nextNodes.push(curNode.getChild(nextChildIdx));
              this.offsets.push(curNodeOffset);
              this.idxs.push(nextChildIdx);
            } else {
              this.nextNodeAfterCurrent();
            }
          }
        } else {
          if (predicate(curNode)) {
            this.nextNodeAfterCurrent();
            return curNode;
          } else {
            const nextChildIdx = getNextChildIdx(curNode);
            if (nextChildIdx === -1) {
              this.nextNodeAfterCurrent();
              return void 0;
            } else {
              this.nextNodes.push(curNode.getChild(nextChildIdx));
              this.offsets.push(curNodeOffset);
              this.idxs.push(nextChildIdx);
            }
          }
        }
      }
    }
    // Navigates to the longest node that continues after the current node.
    nextNodeAfterCurrent() {
      while (true) {
        const currentOffset = lastOrUndefined(this.offsets);
        const currentNode = lastOrUndefined(this.nextNodes);
        this.nextNodes.pop();
        this.offsets.pop();
        if (this.idxs.length === 0) {
          break;
        }
        const parent = lastOrUndefined(this.nextNodes);
        const nextChildIdx = getNextChildIdx(parent, this.idxs[this.idxs.length - 1]);
        if (nextChildIdx !== -1) {
          this.nextNodes.push(parent.getChild(nextChildIdx));
          this.offsets.push(lengthAdd(currentOffset, currentNode.length));
          this.idxs[this.idxs.length - 1] = nextChildIdx;
          break;
        } else {
          this.idxs.pop();
        }
      }
    }
  }
  function getNextChildIdx(node, curIdx = -1) {
    while (true) {
      curIdx++;
      if (curIdx >= node.childrenLength) {
        return -1;
      }
      if (node.getChild(curIdx)) {
        return curIdx;
      }
    }
  }
  function lastOrUndefined(arr) {
    return arr.length > 0 ? arr[arr.length - 1] : void 0;
  }
  function parseDocument(tokenizer, edits, oldNode, createImmutableLists) {
    const parser = new Parser(tokenizer, edits, oldNode, createImmutableLists);
    return parser.parseDocument();
  }
  class Parser {
    constructor(tokenizer, edits, oldNode, createImmutableLists) {
      this.tokenizer = tokenizer;
      this.createImmutableLists = createImmutableLists;
      this._itemsConstructed = 0;
      this._itemsFromCache = 0;
      if (oldNode && createImmutableLists) {
        throw new Error("Not supported");
      }
      this.oldNodeReader = oldNode ? new NodeReader(oldNode) : void 0;
      this.positionMapper = new BeforeEditPositionMapper(edits);
    }
    parseDocument() {
      this._itemsConstructed = 0;
      this._itemsFromCache = 0;
      let result = this.parseList(SmallImmutableSet.getEmpty(), 0);
      if (!result) {
        result = ListAstNode.getEmpty();
      }
      return result;
    }
    parseList(openedBracketIds, level) {
      const items = [];
      while (true) {
        let child = this.tryReadChildFromCache(openedBracketIds);
        if (!child) {
          const token = this.tokenizer.peek();
          if (!token || token.kind === 2 && token.bracketIds.intersects(openedBracketIds)) {
            break;
          }
          child = this.parseChild(openedBracketIds, level + 1);
        }
        if (child.kind === 4 && child.childrenLength === 0) {
          continue;
        }
        items.push(child);
      }
      const result = this.oldNodeReader ? concat23Trees(items) : concat23TreesOfSameHeight(items, this.createImmutableLists);
      return result;
    }
    tryReadChildFromCache(openedBracketIds) {
      if (this.oldNodeReader) {
        const maxCacheableLength = this.positionMapper.getDistanceToNextChange(this.tokenizer.offset);
        if (maxCacheableLength === null || !lengthIsZero(maxCacheableLength)) {
          const cachedNode = this.oldNodeReader.readLongestNodeAt(this.positionMapper.getOffsetBeforeChange(this.tokenizer.offset), (curNode) => {
            if (maxCacheableLength !== null && !lengthLessThan(curNode.length, maxCacheableLength)) {
              return false;
            }
            const canBeReused = curNode.canBeReused(openedBracketIds);
            return canBeReused;
          });
          if (cachedNode) {
            this._itemsFromCache++;
            this.tokenizer.skip(cachedNode.length);
            return cachedNode;
          }
        }
      }
      return void 0;
    }
    parseChild(openedBracketIds, level) {
      this._itemsConstructed++;
      const token = this.tokenizer.read();
      switch (token.kind) {
        case 2:
          return new InvalidBracketAstNode(token.bracketIds, token.length);
        case 0:
          return token.astNode;
        case 1: {
          if (level > 300) {
            return new TextAstNode(token.length);
          }
          const set = openedBracketIds.merge(token.bracketIds);
          const child = this.parseList(set, level + 1);
          const nextToken = this.tokenizer.peek();
          if (nextToken && nextToken.kind === 2 && (nextToken.bracketId === token.bracketId || nextToken.bracketIds.intersects(token.bracketIds))) {
            this.tokenizer.read();
            return PairAstNode.create(token.astNode, child, nextToken.astNode);
          } else {
            return PairAstNode.create(token.astNode, child, null);
          }
        }
        default:
          throw new Error("unexpected");
      }
    }
  }
  function combineTextEditInfos(textEditInfoFirst, textEditInfoSecond) {
    if (textEditInfoFirst.length === 0) {
      return textEditInfoSecond;
    }
    if (textEditInfoSecond.length === 0) {
      return textEditInfoFirst;
    }
    const s0ToS1Map = new ArrayQueue(toLengthMapping(textEditInfoFirst));
    const s1ToS2Map = toLengthMapping(textEditInfoSecond);
    s1ToS2Map.push({ modified: false, lengthBefore: void 0, lengthAfter: void 0 });
    let curItem = s0ToS1Map.dequeue();
    function nextS0ToS1MapWithS1LengthOf(s1Length) {
      if (s1Length === void 0) {
        const arr = s0ToS1Map.takeWhile((v) => true) || [];
        if (curItem) {
          arr.unshift(curItem);
        }
        return arr;
      }
      const result2 = [];
      while (curItem && !lengthIsZero(s1Length)) {
        const [item, remainingItem] = curItem.splitAt(s1Length);
        result2.push(item);
        s1Length = lengthDiffNonNegative(item.lengthAfter, s1Length);
        curItem = remainingItem ?? s0ToS1Map.dequeue();
      }
      if (!lengthIsZero(s1Length)) {
        result2.push(new LengthMapping(false, s1Length, s1Length));
      }
      return result2;
    }
    const result = [];
    function pushEdit(startOffset, endOffset, newLength) {
      if (result.length > 0 && lengthEquals(result[result.length - 1].endOffset, startOffset)) {
        const lastResult = result[result.length - 1];
        result[result.length - 1] = new TextEditInfo(lastResult.startOffset, endOffset, lengthAdd(lastResult.newLength, newLength));
      } else {
        result.push({ startOffset, endOffset, newLength });
      }
    }
    let s0offset = lengthZero;
    for (const s1ToS2 of s1ToS2Map) {
      const s0ToS1Map2 = nextS0ToS1MapWithS1LengthOf(s1ToS2.lengthBefore);
      if (s1ToS2.modified) {
        const s0Length = sumLengths(s0ToS1Map2, (s) => s.lengthBefore);
        const s0EndOffset = lengthAdd(s0offset, s0Length);
        pushEdit(s0offset, s0EndOffset, s1ToS2.lengthAfter);
        s0offset = s0EndOffset;
      } else {
        for (const s1 of s0ToS1Map2) {
          const s0startOffset = s0offset;
          s0offset = lengthAdd(s0offset, s1.lengthBefore);
          if (s1.modified) {
            pushEdit(s0startOffset, s0offset, s1.lengthAfter);
          }
        }
      }
    }
    return result;
  }
  class LengthMapping {
    constructor(modified, lengthBefore, lengthAfter) {
      this.modified = modified;
      this.lengthBefore = lengthBefore;
      this.lengthAfter = lengthAfter;
    }
    splitAt(lengthAfter) {
      const remainingLengthAfter = lengthDiffNonNegative(lengthAfter, this.lengthAfter);
      if (lengthEquals(remainingLengthAfter, lengthZero)) {
        return [this, void 0];
      } else if (this.modified) {
        return [
          new LengthMapping(this.modified, this.lengthBefore, lengthAfter),
          new LengthMapping(this.modified, lengthZero, remainingLengthAfter)
        ];
      } else {
        return [
          new LengthMapping(this.modified, lengthAfter, lengthAfter),
          new LengthMapping(this.modified, remainingLengthAfter, remainingLengthAfter)
        ];
      }
    }
    toString() {
      return `${this.modified ? "M" : "U"}:${lengthToObj(this.lengthBefore)} -> ${lengthToObj(this.lengthAfter)}`;
    }
  }
  function toLengthMapping(textEditInfos) {
    const result = [];
    let lastOffset = lengthZero;
    for (const textEditInfo of textEditInfos) {
      const spaceLength = lengthDiffNonNegative(lastOffset, textEditInfo.startOffset);
      if (!lengthIsZero(spaceLength)) {
        result.push(new LengthMapping(false, spaceLength, spaceLength));
      }
      const lengthBefore = lengthDiffNonNegative(textEditInfo.startOffset, textEditInfo.endOffset);
      result.push(new LengthMapping(true, lengthBefore, textEditInfo.newLength));
      lastOffset = textEditInfo.endOffset;
    }
    return result;
  }
  class BracketPairsTree extends Disposable {
    didLanguageChange(languageId) {
      return this.brackets.didLanguageChange(languageId);
    }
    constructor(textModel, getLanguageConfiguration) {
      super();
      this.textModel = textModel;
      this.getLanguageConfiguration = getLanguageConfiguration;
      this.didChangeEmitter = new Emitter$1();
      this.denseKeyProvider = new DenseKeyProvider();
      this.brackets = new LanguageAgnosticBracketTokens(this.denseKeyProvider, this.getLanguageConfiguration);
      this.onDidChange = this.didChangeEmitter.event;
      this.queuedTextEditsForInitialAstWithoutTokens = [];
      this.queuedTextEdits = [];
      if (!textModel.tokenization.hasTokens) {
        const brackets = this.brackets.getSingleLanguageBracketTokens(this.textModel.getLanguageId());
        const tokenizer = new FastTokenizer(this.textModel.getValue(), brackets);
        this.initialAstWithoutTokens = parseDocument(tokenizer, [], void 0, true);
        this.astWithTokens = this.initialAstWithoutTokens;
      } else if (textModel.tokenization.backgroundTokenizationState === 2) {
        this.initialAstWithoutTokens = void 0;
        this.astWithTokens = this.parseDocumentFromTextBuffer([], void 0, false);
      } else {
        this.initialAstWithoutTokens = this.parseDocumentFromTextBuffer([], void 0, true);
        this.astWithTokens = this.initialAstWithoutTokens;
      }
    }
    //#region TextModel events
    handleDidChangeBackgroundTokenizationState() {
      if (this.textModel.tokenization.backgroundTokenizationState === 2) {
        const wasUndefined = this.initialAstWithoutTokens === void 0;
        this.initialAstWithoutTokens = void 0;
        if (!wasUndefined) {
          this.didChangeEmitter.fire();
        }
      }
    }
    handleDidChangeTokens({ ranges }) {
      const edits = ranges.map((r) => new TextEditInfo(toLength(r.fromLineNumber - 1, 0), toLength(r.toLineNumber, 0), toLength(r.toLineNumber - r.fromLineNumber + 1, 0)));
      this.handleEdits(edits, true);
      if (!this.initialAstWithoutTokens) {
        this.didChangeEmitter.fire();
      }
    }
    handleContentChanged(change) {
      const edits = TextEditInfo.fromModelContentChanges(change.changes);
      this.handleEdits(edits, false);
    }
    handleEdits(edits, tokenChange) {
      const result = combineTextEditInfos(this.queuedTextEdits, edits);
      this.queuedTextEdits = result;
      if (this.initialAstWithoutTokens && !tokenChange) {
        this.queuedTextEditsForInitialAstWithoutTokens = combineTextEditInfos(this.queuedTextEditsForInitialAstWithoutTokens, edits);
      }
    }
    //#endregion
    flushQueue() {
      if (this.queuedTextEdits.length > 0) {
        this.astWithTokens = this.parseDocumentFromTextBuffer(this.queuedTextEdits, this.astWithTokens, false);
        this.queuedTextEdits = [];
      }
      if (this.queuedTextEditsForInitialAstWithoutTokens.length > 0) {
        if (this.initialAstWithoutTokens) {
          this.initialAstWithoutTokens = this.parseDocumentFromTextBuffer(this.queuedTextEditsForInitialAstWithoutTokens, this.initialAstWithoutTokens, false);
        }
        this.queuedTextEditsForInitialAstWithoutTokens = [];
      }
    }
    /**
     * @pure (only if isPure = true)
    */
    parseDocumentFromTextBuffer(edits, previousAst, immutable) {
      const previousAstClone = previousAst;
      const tokenizer = new TextBufferTokenizer(this.textModel, this.brackets);
      const result = parseDocument(tokenizer, edits, previousAstClone, immutable);
      return result;
    }
    getBracketsInRange(range2, onlyColorizedBrackets) {
      this.flushQueue();
      const startOffset = toLength(range2.startLineNumber - 1, range2.startColumn - 1);
      const endOffset = toLength(range2.endLineNumber - 1, range2.endColumn - 1);
      return new CallbackIterable((cb) => {
        const node = this.initialAstWithoutTokens || this.astWithTokens;
        collectBrackets(node, lengthZero, node.length, startOffset, endOffset, cb, 0, 0, /* @__PURE__ */ new Map(), onlyColorizedBrackets);
      });
    }
    getBracketPairsInRange(range2, includeMinIndentation) {
      this.flushQueue();
      const startLength = positionToLength(range2.getStartPosition());
      const endLength = positionToLength(range2.getEndPosition());
      return new CallbackIterable((cb) => {
        const node = this.initialAstWithoutTokens || this.astWithTokens;
        const context = new CollectBracketPairsContext(cb, includeMinIndentation, this.textModel);
        collectBracketPairs(node, lengthZero, node.length, startLength, endLength, context, 0, /* @__PURE__ */ new Map());
      });
    }
    getFirstBracketAfter(position) {
      this.flushQueue();
      const node = this.initialAstWithoutTokens || this.astWithTokens;
      return getFirstBracketAfter(node, lengthZero, node.length, positionToLength(position));
    }
    getFirstBracketBefore(position) {
      this.flushQueue();
      const node = this.initialAstWithoutTokens || this.astWithTokens;
      return getFirstBracketBefore(node, lengthZero, node.length, positionToLength(position));
    }
  }
  function getFirstBracketBefore(node, nodeOffsetStart, nodeOffsetEnd, position) {
    if (node.kind === 4 || node.kind === 2) {
      const lengths = [];
      for (const child of node.children) {
        nodeOffsetEnd = lengthAdd(nodeOffsetStart, child.length);
        lengths.push({ nodeOffsetStart, nodeOffsetEnd });
        nodeOffsetStart = nodeOffsetEnd;
      }
      for (let i2 = lengths.length - 1; i2 >= 0; i2--) {
        const { nodeOffsetStart: nodeOffsetStart2, nodeOffsetEnd: nodeOffsetEnd2 } = lengths[i2];
        if (lengthLessThan(nodeOffsetStart2, position)) {
          const result = getFirstBracketBefore(node.children[i2], nodeOffsetStart2, nodeOffsetEnd2, position);
          if (result) {
            return result;
          }
        }
      }
      return null;
    } else if (node.kind === 3) {
      return null;
    } else if (node.kind === 1) {
      const range2 = lengthsToRange(nodeOffsetStart, nodeOffsetEnd);
      return {
        bracketInfo: node.bracketInfo,
        range: range2
      };
    }
    return null;
  }
  function getFirstBracketAfter(node, nodeOffsetStart, nodeOffsetEnd, position) {
    if (node.kind === 4 || node.kind === 2) {
      for (const child of node.children) {
        nodeOffsetEnd = lengthAdd(nodeOffsetStart, child.length);
        if (lengthLessThan(position, nodeOffsetEnd)) {
          const result = getFirstBracketAfter(child, nodeOffsetStart, nodeOffsetEnd, position);
          if (result) {
            return result;
          }
        }
        nodeOffsetStart = nodeOffsetEnd;
      }
      return null;
    } else if (node.kind === 3) {
      return null;
    } else if (node.kind === 1) {
      const range2 = lengthsToRange(nodeOffsetStart, nodeOffsetEnd);
      return {
        bracketInfo: node.bracketInfo,
        range: range2
      };
    }
    return null;
  }
  function collectBrackets(node, nodeOffsetStart, nodeOffsetEnd, startOffset, endOffset, push, level, nestingLevelOfEqualBracketType, levelPerBracketType, onlyColorizedBrackets, parentPairIsIncomplete = false) {
    if (level > 200) {
      return true;
    }
    whileLoop: while (true) {
      switch (node.kind) {
        case 4: {
          const childCount = node.childrenLength;
          for (let i2 = 0; i2 < childCount; i2++) {
            const child = node.getChild(i2);
            if (!child) {
              continue;
            }
            nodeOffsetEnd = lengthAdd(nodeOffsetStart, child.length);
            if (lengthLessThanEqual(nodeOffsetStart, endOffset) && lengthGreaterThanEqual(nodeOffsetEnd, startOffset)) {
              const childEndsAfterEnd = lengthGreaterThanEqual(nodeOffsetEnd, endOffset);
              if (childEndsAfterEnd) {
                node = child;
                continue whileLoop;
              }
              const shouldContinue = collectBrackets(child, nodeOffsetStart, nodeOffsetEnd, startOffset, endOffset, push, level, 0, levelPerBracketType, onlyColorizedBrackets);
              if (!shouldContinue) {
                return false;
              }
            }
            nodeOffsetStart = nodeOffsetEnd;
          }
          return true;
        }
        case 2: {
          const colorize2 = !onlyColorizedBrackets || !node.closingBracket || node.closingBracket.bracketInfo.closesColorized(node.openingBracket.bracketInfo);
          let levelPerBracket = 0;
          if (levelPerBracketType) {
            let existing = levelPerBracketType.get(node.openingBracket.text);
            if (existing === void 0) {
              existing = 0;
            }
            levelPerBracket = existing;
            if (colorize2) {
              existing++;
              levelPerBracketType.set(node.openingBracket.text, existing);
            }
          }
          const childCount = node.childrenLength;
          for (let i2 = 0; i2 < childCount; i2++) {
            const child = node.getChild(i2);
            if (!child) {
              continue;
            }
            nodeOffsetEnd = lengthAdd(nodeOffsetStart, child.length);
            if (lengthLessThanEqual(nodeOffsetStart, endOffset) && lengthGreaterThanEqual(nodeOffsetEnd, startOffset)) {
              const childEndsAfterEnd = lengthGreaterThanEqual(nodeOffsetEnd, endOffset);
              if (childEndsAfterEnd && child.kind !== 1) {
                node = child;
                if (colorize2) {
                  level++;
                  nestingLevelOfEqualBracketType = levelPerBracket + 1;
                } else {
                  nestingLevelOfEqualBracketType = levelPerBracket;
                }
                continue whileLoop;
              }
              if (colorize2 || child.kind !== 1 || !node.closingBracket) {
                const shouldContinue = collectBrackets(child, nodeOffsetStart, nodeOffsetEnd, startOffset, endOffset, push, colorize2 ? level + 1 : level, colorize2 ? levelPerBracket + 1 : levelPerBracket, levelPerBracketType, onlyColorizedBrackets, !node.closingBracket);
                if (!shouldContinue) {
                  return false;
                }
              }
            }
            nodeOffsetStart = nodeOffsetEnd;
          }
          levelPerBracketType?.set(node.openingBracket.text, levelPerBracket);
          return true;
        }
        case 3: {
          const range2 = lengthsToRange(nodeOffsetStart, nodeOffsetEnd);
          return push(new BracketInfo(range2, level - 1, 0, true));
        }
        case 1: {
          const range2 = lengthsToRange(nodeOffsetStart, nodeOffsetEnd);
          return push(new BracketInfo(range2, level - 1, nestingLevelOfEqualBracketType - 1, parentPairIsIncomplete));
        }
        case 0:
          return true;
      }
    }
  }
  class CollectBracketPairsContext {
    constructor(push, includeMinIndentation, textModel) {
      this.push = push;
      this.includeMinIndentation = includeMinIndentation;
      this.textModel = textModel;
    }
  }
  function collectBracketPairs(node, nodeOffsetStart, nodeOffsetEnd, startOffset, endOffset, context, level, levelPerBracketType) {
    if (level > 200) {
      return true;
    }
    let shouldContinue = true;
    if (node.kind === 2) {
      let levelPerBracket = 0;
      if (levelPerBracketType) {
        let existing = levelPerBracketType.get(node.openingBracket.text);
        if (existing === void 0) {
          existing = 0;
        }
        levelPerBracket = existing;
        existing++;
        levelPerBracketType.set(node.openingBracket.text, existing);
      }
      const openingBracketEnd = lengthAdd(nodeOffsetStart, node.openingBracket.length);
      let minIndentation = -1;
      if (context.includeMinIndentation) {
        minIndentation = node.computeMinIndentation(nodeOffsetStart, context.textModel);
      }
      shouldContinue = context.push(new BracketPairWithMinIndentationInfo(lengthsToRange(nodeOffsetStart, nodeOffsetEnd), lengthsToRange(nodeOffsetStart, openingBracketEnd), node.closingBracket ? lengthsToRange(lengthAdd(openingBracketEnd, node.child?.length || lengthZero), nodeOffsetEnd) : void 0, level, levelPerBracket, node, minIndentation));
      nodeOffsetStart = openingBracketEnd;
      if (shouldContinue && node.child) {
        const child = node.child;
        nodeOffsetEnd = lengthAdd(nodeOffsetStart, child.length);
        if (lengthLessThanEqual(nodeOffsetStart, endOffset) && lengthGreaterThanEqual(nodeOffsetEnd, startOffset)) {
          shouldContinue = collectBracketPairs(child, nodeOffsetStart, nodeOffsetEnd, startOffset, endOffset, context, level + 1, levelPerBracketType);
          if (!shouldContinue) {
            return false;
          }
        }
      }
      levelPerBracketType?.set(node.openingBracket.text, levelPerBracket);
    } else {
      let curOffset = nodeOffsetStart;
      for (const child of node.children) {
        const childOffset = curOffset;
        curOffset = lengthAdd(curOffset, child.length);
        if (lengthLessThanEqual(childOffset, endOffset) && lengthLessThanEqual(startOffset, curOffset)) {
          shouldContinue = collectBracketPairs(child, childOffset, curOffset, startOffset, endOffset, context, level, levelPerBracketType);
          if (!shouldContinue) {
            return false;
          }
        }
      }
    }
    return shouldContinue;
  }
  class BracketPairsTextModelPart extends Disposable {
    get canBuildAST() {
      const maxSupportedDocumentLength = (
        /* max lines */
        5e4 * /* average column count */
        100
      );
      return this.textModel.getValueLength() <= maxSupportedDocumentLength;
    }
    constructor(textModel, languageConfigurationService) {
      super();
      this.textModel = textModel;
      this.languageConfigurationService = languageConfigurationService;
      this.bracketPairsTree = this._register(new MutableDisposable());
      this.onDidChangeEmitter = new Emitter$1();
      this.onDidChange = this.onDidChangeEmitter.event;
      this.bracketsRequested = false;
    }
    //#region TextModel events
    handleLanguageConfigurationServiceChange(e) {
      if (!e.languageId || this.bracketPairsTree.value?.object.didLanguageChange(e.languageId)) {
        this.bracketPairsTree.clear();
        this.updateBracketPairsTree();
      }
    }
    handleDidChangeOptions(e) {
      this.bracketPairsTree.clear();
      this.updateBracketPairsTree();
    }
    handleDidChangeLanguage(e) {
      this.bracketPairsTree.clear();
      this.updateBracketPairsTree();
    }
    handleDidChangeContent(change) {
      this.bracketPairsTree.value?.object.handleContentChanged(change);
    }
    handleDidChangeBackgroundTokenizationState() {
      this.bracketPairsTree.value?.object.handleDidChangeBackgroundTokenizationState();
    }
    handleDidChangeTokens(e) {
      this.bracketPairsTree.value?.object.handleDidChangeTokens(e);
    }
    //#endregion
    updateBracketPairsTree() {
      if (this.bracketsRequested && this.canBuildAST) {
        if (!this.bracketPairsTree.value) {
          const store = new DisposableStore();
          this.bracketPairsTree.value = createDisposableRef(store.add(new BracketPairsTree(this.textModel, (languageId) => {
            return this.languageConfigurationService.getLanguageConfiguration(languageId);
          })), store);
          store.add(this.bracketPairsTree.value.object.onDidChange((e) => this.onDidChangeEmitter.fire(e)));
          this.onDidChangeEmitter.fire();
        }
      } else {
        if (this.bracketPairsTree.value) {
          this.bracketPairsTree.clear();
          this.onDidChangeEmitter.fire();
        }
      }
    }
    /**
     * Returns all bracket pairs that intersect the given range.
     * The result is sorted by the start position.
    */
    getBracketPairsInRange(range2) {
      this.bracketsRequested = true;
      this.updateBracketPairsTree();
      return this.bracketPairsTree.value?.object.getBracketPairsInRange(range2, false) || CallbackIterable.empty;
    }
    getBracketPairsInRangeWithMinIndentation(range2) {
      this.bracketsRequested = true;
      this.updateBracketPairsTree();
      return this.bracketPairsTree.value?.object.getBracketPairsInRange(range2, true) || CallbackIterable.empty;
    }
    getBracketsInRange(range2, onlyColorizedBrackets = false) {
      this.bracketsRequested = true;
      this.updateBracketPairsTree();
      return this.bracketPairsTree.value?.object.getBracketsInRange(range2, onlyColorizedBrackets) || CallbackIterable.empty;
    }
    findMatchingBracketUp(_bracket, _position, maxDuration) {
      const position = this.textModel.validatePosition(_position);
      const languageId = this.textModel.getLanguageIdAtPosition(position.lineNumber, position.column);
      if (this.canBuildAST) {
        const closingBracketInfo = this.languageConfigurationService.getLanguageConfiguration(languageId).bracketsNew.getClosingBracketInfo(_bracket);
        if (!closingBracketInfo) {
          return null;
        }
        const bracketPair = this.getBracketPairsInRange(Range$2.fromPositions(_position, _position)).findLast((b) => closingBracketInfo.closes(b.openingBracketInfo));
        if (bracketPair) {
          return bracketPair.openingBracketRange;
        }
        return null;
      } else {
        const bracket = _bracket.toLowerCase();
        const bracketsSupport = this.languageConfigurationService.getLanguageConfiguration(languageId).brackets;
        if (!bracketsSupport) {
          return null;
        }
        const data = bracketsSupport.textIsBracket[bracket];
        if (!data) {
          return null;
        }
        return stripBracketSearchCanceled(this._findMatchingBracketUp(data, position, createTimeBasedContinueBracketSearchPredicate(maxDuration)));
      }
    }
    matchBracket(position, maxDuration) {
      if (this.canBuildAST) {
        const bracketPair = this.getBracketPairsInRange(Range$2.fromPositions(position, position)).filter((item) => item.closingBracketRange !== void 0 && (item.openingBracketRange.containsPosition(position) || item.closingBracketRange.containsPosition(position))).findLastMaxBy(compareBy((item) => item.openingBracketRange.containsPosition(position) ? item.openingBracketRange : item.closingBracketRange, Range$2.compareRangesUsingStarts));
        if (bracketPair) {
          return [bracketPair.openingBracketRange, bracketPair.closingBracketRange];
        }
        return null;
      } else {
        const continueSearchPredicate = createTimeBasedContinueBracketSearchPredicate(maxDuration);
        return this._matchBracket(this.textModel.validatePosition(position), continueSearchPredicate);
      }
    }
    _establishBracketSearchOffsets(position, lineTokens, modeBrackets, tokenIndex) {
      const tokenCount = lineTokens.getCount();
      const currentLanguageId = lineTokens.getLanguageId(tokenIndex);
      let searchStartOffset = Math.max(0, position.column - 1 - modeBrackets.maxBracketLength);
      for (let i2 = tokenIndex - 1; i2 >= 0; i2--) {
        const tokenEndOffset = lineTokens.getEndOffset(i2);
        if (tokenEndOffset <= searchStartOffset) {
          break;
        }
        if (ignoreBracketsInToken(lineTokens.getStandardTokenType(i2)) || lineTokens.getLanguageId(i2) !== currentLanguageId) {
          searchStartOffset = tokenEndOffset;
          break;
        }
      }
      let searchEndOffset = Math.min(lineTokens.getLineContent().length, position.column - 1 + modeBrackets.maxBracketLength);
      for (let i2 = tokenIndex + 1; i2 < tokenCount; i2++) {
        const tokenStartOffset = lineTokens.getStartOffset(i2);
        if (tokenStartOffset >= searchEndOffset) {
          break;
        }
        if (ignoreBracketsInToken(lineTokens.getStandardTokenType(i2)) || lineTokens.getLanguageId(i2) !== currentLanguageId) {
          searchEndOffset = tokenStartOffset;
          break;
        }
      }
      return { searchStartOffset, searchEndOffset };
    }
    _matchBracket(position, continueSearchPredicate) {
      const lineNumber = position.lineNumber;
      const lineTokens = this.textModel.tokenization.getLineTokens(lineNumber);
      const lineText = this.textModel.getLineContent(lineNumber);
      const tokenIndex = lineTokens.findTokenIndexAtOffset(position.column - 1);
      if (tokenIndex < 0) {
        return null;
      }
      const currentModeBrackets = this.languageConfigurationService.getLanguageConfiguration(lineTokens.getLanguageId(tokenIndex)).brackets;
      if (currentModeBrackets && !ignoreBracketsInToken(lineTokens.getStandardTokenType(tokenIndex))) {
        let { searchStartOffset, searchEndOffset } = this._establishBracketSearchOffsets(position, lineTokens, currentModeBrackets, tokenIndex);
        let bestResult = null;
        while (true) {
          const foundBracket = BracketsUtils.findNextBracketInRange(currentModeBrackets.forwardRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
          if (!foundBracket) {
            break;
          }
          if (foundBracket.startColumn <= position.column && position.column <= foundBracket.endColumn) {
            const foundBracketText = lineText.substring(foundBracket.startColumn - 1, foundBracket.endColumn - 1).toLowerCase();
            const r = this._matchFoundBracket(foundBracket, currentModeBrackets.textIsBracket[foundBracketText], currentModeBrackets.textIsOpenBracket[foundBracketText], continueSearchPredicate);
            if (r) {
              if (r instanceof BracketSearchCanceled) {
                return null;
              }
              bestResult = r;
            }
          }
          searchStartOffset = foundBracket.endColumn - 1;
        }
        if (bestResult) {
          return bestResult;
        }
      }
      if (tokenIndex > 0 && lineTokens.getStartOffset(tokenIndex) === position.column - 1) {
        const prevTokenIndex = tokenIndex - 1;
        const prevModeBrackets = this.languageConfigurationService.getLanguageConfiguration(lineTokens.getLanguageId(prevTokenIndex)).brackets;
        if (prevModeBrackets && !ignoreBracketsInToken(lineTokens.getStandardTokenType(prevTokenIndex))) {
          const { searchStartOffset, searchEndOffset } = this._establishBracketSearchOffsets(position, lineTokens, prevModeBrackets, prevTokenIndex);
          const foundBracket = BracketsUtils.findPrevBracketInRange(prevModeBrackets.reversedRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
          if (foundBracket && foundBracket.startColumn <= position.column && position.column <= foundBracket.endColumn) {
            const foundBracketText = lineText.substring(foundBracket.startColumn - 1, foundBracket.endColumn - 1).toLowerCase();
            const r = this._matchFoundBracket(foundBracket, prevModeBrackets.textIsBracket[foundBracketText], prevModeBrackets.textIsOpenBracket[foundBracketText], continueSearchPredicate);
            if (r) {
              if (r instanceof BracketSearchCanceled) {
                return null;
              }
              return r;
            }
          }
        }
      }
      return null;
    }
    _matchFoundBracket(foundBracket, data, isOpen, continueSearchPredicate) {
      if (!data) {
        return null;
      }
      const matched = isOpen ? this._findMatchingBracketDown(data, foundBracket.getEndPosition(), continueSearchPredicate) : this._findMatchingBracketUp(data, foundBracket.getStartPosition(), continueSearchPredicate);
      if (!matched) {
        return null;
      }
      if (matched instanceof BracketSearchCanceled) {
        return matched;
      }
      return [foundBracket, matched];
    }
    _findMatchingBracketUp(bracket, position, continueSearchPredicate) {
      const languageId = bracket.languageId;
      const reversedBracketRegex = bracket.reversedRegex;
      let count = -1;
      let totalCallCount = 0;
      const searchPrevMatchingBracketInRange = (lineNumber, lineText, searchStartOffset, searchEndOffset) => {
        while (true) {
          if (continueSearchPredicate && ++totalCallCount % 100 === 0 && !continueSearchPredicate()) {
            return BracketSearchCanceled.INSTANCE;
          }
          const r = BracketsUtils.findPrevBracketInRange(reversedBracketRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
          if (!r) {
            break;
          }
          const hitText = lineText.substring(r.startColumn - 1, r.endColumn - 1).toLowerCase();
          if (bracket.isOpen(hitText)) {
            count++;
          } else if (bracket.isClose(hitText)) {
            count--;
          }
          if (count === 0) {
            return r;
          }
          searchEndOffset = r.startColumn - 1;
        }
        return null;
      };
      for (let lineNumber = position.lineNumber; lineNumber >= 1; lineNumber--) {
        const lineTokens = this.textModel.tokenization.getLineTokens(lineNumber);
        const tokenCount = lineTokens.getCount();
        const lineText = this.textModel.getLineContent(lineNumber);
        let tokenIndex = tokenCount - 1;
        let searchStartOffset = lineText.length;
        let searchEndOffset = lineText.length;
        if (lineNumber === position.lineNumber) {
          tokenIndex = lineTokens.findTokenIndexAtOffset(position.column - 1);
          searchStartOffset = position.column - 1;
          searchEndOffset = position.column - 1;
        }
        let prevSearchInToken = true;
        for (; tokenIndex >= 0; tokenIndex--) {
          const searchInToken = lineTokens.getLanguageId(tokenIndex) === languageId && !ignoreBracketsInToken(lineTokens.getStandardTokenType(tokenIndex));
          if (searchInToken) {
            if (prevSearchInToken) {
              searchStartOffset = lineTokens.getStartOffset(tokenIndex);
            } else {
              searchStartOffset = lineTokens.getStartOffset(tokenIndex);
              searchEndOffset = lineTokens.getEndOffset(tokenIndex);
            }
          } else {
            if (prevSearchInToken && searchStartOffset !== searchEndOffset) {
              const r = searchPrevMatchingBracketInRange(lineNumber, lineText, searchStartOffset, searchEndOffset);
              if (r) {
                return r;
              }
            }
          }
          prevSearchInToken = searchInToken;
        }
        if (prevSearchInToken && searchStartOffset !== searchEndOffset) {
          const r = searchPrevMatchingBracketInRange(lineNumber, lineText, searchStartOffset, searchEndOffset);
          if (r) {
            return r;
          }
        }
      }
      return null;
    }
    _findMatchingBracketDown(bracket, position, continueSearchPredicate) {
      const languageId = bracket.languageId;
      const bracketRegex = bracket.forwardRegex;
      let count = 1;
      let totalCallCount = 0;
      const searchNextMatchingBracketInRange = (lineNumber, lineText, searchStartOffset, searchEndOffset) => {
        while (true) {
          if (continueSearchPredicate && ++totalCallCount % 100 === 0 && !continueSearchPredicate()) {
            return BracketSearchCanceled.INSTANCE;
          }
          const r = BracketsUtils.findNextBracketInRange(bracketRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
          if (!r) {
            break;
          }
          const hitText = lineText.substring(r.startColumn - 1, r.endColumn - 1).toLowerCase();
          if (bracket.isOpen(hitText)) {
            count++;
          } else if (bracket.isClose(hitText)) {
            count--;
          }
          if (count === 0) {
            return r;
          }
          searchStartOffset = r.endColumn - 1;
        }
        return null;
      };
      const lineCount = this.textModel.getLineCount();
      for (let lineNumber = position.lineNumber; lineNumber <= lineCount; lineNumber++) {
        const lineTokens = this.textModel.tokenization.getLineTokens(lineNumber);
        const tokenCount = lineTokens.getCount();
        const lineText = this.textModel.getLineContent(lineNumber);
        let tokenIndex = 0;
        let searchStartOffset = 0;
        let searchEndOffset = 0;
        if (lineNumber === position.lineNumber) {
          tokenIndex = lineTokens.findTokenIndexAtOffset(position.column - 1);
          searchStartOffset = position.column - 1;
          searchEndOffset = position.column - 1;
        }
        let prevSearchInToken = true;
        for (; tokenIndex < tokenCount; tokenIndex++) {
          const searchInToken = lineTokens.getLanguageId(tokenIndex) === languageId && !ignoreBracketsInToken(lineTokens.getStandardTokenType(tokenIndex));
          if (searchInToken) {
            if (prevSearchInToken) {
              searchEndOffset = lineTokens.getEndOffset(tokenIndex);
            } else {
              searchStartOffset = lineTokens.getStartOffset(tokenIndex);
              searchEndOffset = lineTokens.getEndOffset(tokenIndex);
            }
          } else {
            if (prevSearchInToken && searchStartOffset !== searchEndOffset) {
              const r = searchNextMatchingBracketInRange(lineNumber, lineText, searchStartOffset, searchEndOffset);
              if (r) {
                return r;
              }
            }
          }
          prevSearchInToken = searchInToken;
        }
        if (prevSearchInToken && searchStartOffset !== searchEndOffset) {
          const r = searchNextMatchingBracketInRange(lineNumber, lineText, searchStartOffset, searchEndOffset);
          if (r) {
            return r;
          }
        }
      }
      return null;
    }
    findPrevBracket(_position) {
      const position = this.textModel.validatePosition(_position);
      if (this.canBuildAST) {
        this.bracketsRequested = true;
        this.updateBracketPairsTree();
        return this.bracketPairsTree.value?.object.getFirstBracketBefore(position) || null;
      }
      let languageId = null;
      let modeBrackets = null;
      let bracketConfig = null;
      for (let lineNumber = position.lineNumber; lineNumber >= 1; lineNumber--) {
        const lineTokens = this.textModel.tokenization.getLineTokens(lineNumber);
        const tokenCount = lineTokens.getCount();
        const lineText = this.textModel.getLineContent(lineNumber);
        let tokenIndex = tokenCount - 1;
        let searchStartOffset = lineText.length;
        let searchEndOffset = lineText.length;
        if (lineNumber === position.lineNumber) {
          tokenIndex = lineTokens.findTokenIndexAtOffset(position.column - 1);
          searchStartOffset = position.column - 1;
          searchEndOffset = position.column - 1;
          const tokenLanguageId = lineTokens.getLanguageId(tokenIndex);
          if (languageId !== tokenLanguageId) {
            languageId = tokenLanguageId;
            modeBrackets = this.languageConfigurationService.getLanguageConfiguration(languageId).brackets;
            bracketConfig = this.languageConfigurationService.getLanguageConfiguration(languageId).bracketsNew;
          }
        }
        let prevSearchInToken = true;
        for (; tokenIndex >= 0; tokenIndex--) {
          const tokenLanguageId = lineTokens.getLanguageId(tokenIndex);
          if (languageId !== tokenLanguageId) {
            if (modeBrackets && bracketConfig && prevSearchInToken && searchStartOffset !== searchEndOffset) {
              const r = BracketsUtils.findPrevBracketInRange(modeBrackets.reversedRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
              if (r) {
                return this._toFoundBracket(bracketConfig, r);
              }
              prevSearchInToken = false;
            }
            languageId = tokenLanguageId;
            modeBrackets = this.languageConfigurationService.getLanguageConfiguration(languageId).brackets;
            bracketConfig = this.languageConfigurationService.getLanguageConfiguration(languageId).bracketsNew;
          }
          const searchInToken = !!modeBrackets && !ignoreBracketsInToken(lineTokens.getStandardTokenType(tokenIndex));
          if (searchInToken) {
            if (prevSearchInToken) {
              searchStartOffset = lineTokens.getStartOffset(tokenIndex);
            } else {
              searchStartOffset = lineTokens.getStartOffset(tokenIndex);
              searchEndOffset = lineTokens.getEndOffset(tokenIndex);
            }
          } else {
            if (bracketConfig && modeBrackets && prevSearchInToken && searchStartOffset !== searchEndOffset) {
              const r = BracketsUtils.findPrevBracketInRange(modeBrackets.reversedRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
              if (r) {
                return this._toFoundBracket(bracketConfig, r);
              }
            }
          }
          prevSearchInToken = searchInToken;
        }
        if (bracketConfig && modeBrackets && prevSearchInToken && searchStartOffset !== searchEndOffset) {
          const r = BracketsUtils.findPrevBracketInRange(modeBrackets.reversedRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
          if (r) {
            return this._toFoundBracket(bracketConfig, r);
          }
        }
      }
      return null;
    }
    findNextBracket(_position) {
      const position = this.textModel.validatePosition(_position);
      if (this.canBuildAST) {
        this.bracketsRequested = true;
        this.updateBracketPairsTree();
        return this.bracketPairsTree.value?.object.getFirstBracketAfter(position) || null;
      }
      const lineCount = this.textModel.getLineCount();
      let languageId = null;
      let modeBrackets = null;
      let bracketConfig = null;
      for (let lineNumber = position.lineNumber; lineNumber <= lineCount; lineNumber++) {
        const lineTokens = this.textModel.tokenization.getLineTokens(lineNumber);
        const tokenCount = lineTokens.getCount();
        const lineText = this.textModel.getLineContent(lineNumber);
        let tokenIndex = 0;
        let searchStartOffset = 0;
        let searchEndOffset = 0;
        if (lineNumber === position.lineNumber) {
          tokenIndex = lineTokens.findTokenIndexAtOffset(position.column - 1);
          searchStartOffset = position.column - 1;
          searchEndOffset = position.column - 1;
          const tokenLanguageId = lineTokens.getLanguageId(tokenIndex);
          if (languageId !== tokenLanguageId) {
            languageId = tokenLanguageId;
            modeBrackets = this.languageConfigurationService.getLanguageConfiguration(languageId).brackets;
            bracketConfig = this.languageConfigurationService.getLanguageConfiguration(languageId).bracketsNew;
          }
        }
        let prevSearchInToken = true;
        for (; tokenIndex < tokenCount; tokenIndex++) {
          const tokenLanguageId = lineTokens.getLanguageId(tokenIndex);
          if (languageId !== tokenLanguageId) {
            if (bracketConfig && modeBrackets && prevSearchInToken && searchStartOffset !== searchEndOffset) {
              const r = BracketsUtils.findNextBracketInRange(modeBrackets.forwardRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
              if (r) {
                return this._toFoundBracket(bracketConfig, r);
              }
              prevSearchInToken = false;
            }
            languageId = tokenLanguageId;
            modeBrackets = this.languageConfigurationService.getLanguageConfiguration(languageId).brackets;
            bracketConfig = this.languageConfigurationService.getLanguageConfiguration(languageId).bracketsNew;
          }
          const searchInToken = !!modeBrackets && !ignoreBracketsInToken(lineTokens.getStandardTokenType(tokenIndex));
          if (searchInToken) {
            if (prevSearchInToken) {
              searchEndOffset = lineTokens.getEndOffset(tokenIndex);
            } else {
              searchStartOffset = lineTokens.getStartOffset(tokenIndex);
              searchEndOffset = lineTokens.getEndOffset(tokenIndex);
            }
          } else {
            if (bracketConfig && modeBrackets && prevSearchInToken && searchStartOffset !== searchEndOffset) {
              const r = BracketsUtils.findNextBracketInRange(modeBrackets.forwardRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
              if (r) {
                return this._toFoundBracket(bracketConfig, r);
              }
            }
          }
          prevSearchInToken = searchInToken;
        }
        if (bracketConfig && modeBrackets && prevSearchInToken && searchStartOffset !== searchEndOffset) {
          const r = BracketsUtils.findNextBracketInRange(modeBrackets.forwardRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
          if (r) {
            return this._toFoundBracket(bracketConfig, r);
          }
        }
      }
      return null;
    }
    findEnclosingBrackets(_position, maxDuration) {
      const position = this.textModel.validatePosition(_position);
      if (this.canBuildAST) {
        const range2 = Range$2.fromPositions(position);
        const bracketPair = this.getBracketPairsInRange(Range$2.fromPositions(position, position)).findLast((item) => item.closingBracketRange !== void 0 && item.range.strictContainsRange(range2));
        if (bracketPair) {
          return [bracketPair.openingBracketRange, bracketPair.closingBracketRange];
        }
        return null;
      }
      const continueSearchPredicate = createTimeBasedContinueBracketSearchPredicate(maxDuration);
      const lineCount = this.textModel.getLineCount();
      const savedCounts = /* @__PURE__ */ new Map();
      let counts = [];
      const resetCounts = (languageId2, modeBrackets2) => {
        if (!savedCounts.has(languageId2)) {
          const tmp = [];
          for (let i2 = 0, len = modeBrackets2 ? modeBrackets2.brackets.length : 0; i2 < len; i2++) {
            tmp[i2] = 0;
          }
          savedCounts.set(languageId2, tmp);
        }
        counts = savedCounts.get(languageId2);
      };
      let totalCallCount = 0;
      const searchInRange = (modeBrackets2, lineNumber, lineText, searchStartOffset, searchEndOffset) => {
        while (true) {
          if (continueSearchPredicate && ++totalCallCount % 100 === 0 && !continueSearchPredicate()) {
            return BracketSearchCanceled.INSTANCE;
          }
          const r = BracketsUtils.findNextBracketInRange(modeBrackets2.forwardRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
          if (!r) {
            break;
          }
          const hitText = lineText.substring(r.startColumn - 1, r.endColumn - 1).toLowerCase();
          const bracket = modeBrackets2.textIsBracket[hitText];
          if (bracket) {
            if (bracket.isOpen(hitText)) {
              counts[bracket.index]++;
            } else if (bracket.isClose(hitText)) {
              counts[bracket.index]--;
            }
            if (counts[bracket.index] === -1) {
              return this._matchFoundBracket(r, bracket, false, continueSearchPredicate);
            }
          }
          searchStartOffset = r.endColumn - 1;
        }
        return null;
      };
      let languageId = null;
      let modeBrackets = null;
      for (let lineNumber = position.lineNumber; lineNumber <= lineCount; lineNumber++) {
        const lineTokens = this.textModel.tokenization.getLineTokens(lineNumber);
        const tokenCount = lineTokens.getCount();
        const lineText = this.textModel.getLineContent(lineNumber);
        let tokenIndex = 0;
        let searchStartOffset = 0;
        let searchEndOffset = 0;
        if (lineNumber === position.lineNumber) {
          tokenIndex = lineTokens.findTokenIndexAtOffset(position.column - 1);
          searchStartOffset = position.column - 1;
          searchEndOffset = position.column - 1;
          const tokenLanguageId = lineTokens.getLanguageId(tokenIndex);
          if (languageId !== tokenLanguageId) {
            languageId = tokenLanguageId;
            modeBrackets = this.languageConfigurationService.getLanguageConfiguration(languageId).brackets;
            resetCounts(languageId, modeBrackets);
          }
        }
        let prevSearchInToken = true;
        for (; tokenIndex < tokenCount; tokenIndex++) {
          const tokenLanguageId = lineTokens.getLanguageId(tokenIndex);
          if (languageId !== tokenLanguageId) {
            if (modeBrackets && prevSearchInToken && searchStartOffset !== searchEndOffset) {
              const r = searchInRange(modeBrackets, lineNumber, lineText, searchStartOffset, searchEndOffset);
              if (r) {
                return stripBracketSearchCanceled(r);
              }
              prevSearchInToken = false;
            }
            languageId = tokenLanguageId;
            modeBrackets = this.languageConfigurationService.getLanguageConfiguration(languageId).brackets;
            resetCounts(languageId, modeBrackets);
          }
          const searchInToken = !!modeBrackets && !ignoreBracketsInToken(lineTokens.getStandardTokenType(tokenIndex));
          if (searchInToken) {
            if (prevSearchInToken) {
              searchEndOffset = lineTokens.getEndOffset(tokenIndex);
            } else {
              searchStartOffset = lineTokens.getStartOffset(tokenIndex);
              searchEndOffset = lineTokens.getEndOffset(tokenIndex);
            }
          } else {
            if (modeBrackets && prevSearchInToken && searchStartOffset !== searchEndOffset) {
              const r = searchInRange(modeBrackets, lineNumber, lineText, searchStartOffset, searchEndOffset);
              if (r) {
                return stripBracketSearchCanceled(r);
              }
            }
          }
          prevSearchInToken = searchInToken;
        }
        if (modeBrackets && prevSearchInToken && searchStartOffset !== searchEndOffset) {
          const r = searchInRange(modeBrackets, lineNumber, lineText, searchStartOffset, searchEndOffset);
          if (r) {
            return stripBracketSearchCanceled(r);
          }
        }
      }
      return null;
    }
    _toFoundBracket(bracketConfig, r) {
      if (!r) {
        return null;
      }
      let text2 = this.textModel.getValueInRange(r);
      text2 = text2.toLowerCase();
      const bracketInfo = bracketConfig.getBracketInfo(text2);
      if (!bracketInfo) {
        return null;
      }
      return {
        range: r,
        bracketInfo
      };
    }
  }
  function createDisposableRef(object, disposable) {
    return {
      object,
      dispose: () => disposable?.dispose()
    };
  }
  function createTimeBasedContinueBracketSearchPredicate(maxDuration) {
    if (typeof maxDuration === "undefined") {
      return () => true;
    } else {
      const startTime = Date.now();
      return () => {
        return Date.now() - startTime <= maxDuration;
      };
    }
  }
  const _BracketSearchCanceled = class _BracketSearchCanceled {
    constructor() {
      this._searchCanceledBrand = void 0;
    }
  };
  _BracketSearchCanceled.INSTANCE = new _BracketSearchCanceled();
  let BracketSearchCanceled = _BracketSearchCanceled;
  function stripBracketSearchCanceled(result) {
    if (result instanceof BracketSearchCanceled) {
      return null;
    }
    return result;
  }
  class ColorizedBracketPairsDecorationProvider extends Disposable {
    constructor(textModel) {
      super();
      this.textModel = textModel;
      this.colorProvider = new ColorProvider();
      this.onDidChangeEmitter = new Emitter$1();
      this.onDidChange = this.onDidChangeEmitter.event;
      this.colorizationOptions = textModel.getOptions().bracketPairColorizationOptions;
      this._register(textModel.bracketPairs.onDidChange((e) => {
        this.onDidChangeEmitter.fire();
      }));
    }
    //#region TextModel events
    handleDidChangeOptions(e) {
      this.colorizationOptions = this.textModel.getOptions().bracketPairColorizationOptions;
    }
    //#endregion
    getDecorationsInRange(range2, ownerId2, filterOutValidation, onlyMinimapDecorations) {
      if (onlyMinimapDecorations) {
        return [];
      }
      if (ownerId2 === void 0) {
        return [];
      }
      if (!this.colorizationOptions.enabled) {
        return [];
      }
      const result = this.textModel.bracketPairs.getBracketsInRange(range2, true).map((bracket) => ({
        id: `bracket${bracket.range.toString()}-${bracket.nestingLevel}`,
        options: {
          description: "BracketPairColorization",
          inlineClassName: this.colorProvider.getInlineClassName(bracket, this.colorizationOptions.independentColorPoolPerBracketType)
        },
        ownerId: 0,
        range: bracket.range
      })).toArray();
      return result;
    }
    getAllDecorations(ownerId2, filterOutValidation) {
      if (ownerId2 === void 0) {
        return [];
      }
      if (!this.colorizationOptions.enabled) {
        return [];
      }
      return this.getDecorationsInRange(new Range$2(1, 1, this.textModel.getLineCount(), 1), ownerId2, filterOutValidation);
    }
  }
  class ColorProvider {
    constructor() {
      this.unexpectedClosingBracketClassName = "unexpected-closing-bracket";
    }
    getInlineClassName(bracket, independentColorPoolPerBracketType) {
      if (bracket.isInvalid) {
        return this.unexpectedClosingBracketClassName;
      }
      return this.getInlineClassNameOfLevel(independentColorPoolPerBracketType ? bracket.nestingLevelOfEqualBracketType : bracket.nestingLevel);
    }
    getInlineClassNameOfLevel(level) {
      return `bracket-highlighting-${level % 30}`;
    }
  }
  registerThemingParticipant((theme, collector) => {
    const colors = [
      editorBracketHighlightingForeground1,
      editorBracketHighlightingForeground2,
      editorBracketHighlightingForeground3,
      editorBracketHighlightingForeground4,
      editorBracketHighlightingForeground5,
      editorBracketHighlightingForeground6
    ];
    const colorProvider = new ColorProvider();
    collector.addRule(`.monaco-editor .${colorProvider.unexpectedClosingBracketClassName} { color: ${theme.getColor(editorBracketHighlightingUnexpectedBracketForeground)}; }`);
    const colorValues = colors.map((c) => theme.getColor(c)).filter((c) => !!c).filter((c) => !c.isTransparent());
    for (let level = 0; level < 30; level++) {
      const color = colorValues[level % colorValues.length];
      collector.addRule(`.monaco-editor .${colorProvider.getInlineClassNameOfLevel(level)} { color: ${color}; }`);
    }
  });
  function escapeNewLine(str) {
    return str.replace(/\n/g, "\\n").replace(/\r/g, "\\r");
  }
  class TextChange {
    get oldLength() {
      return this.oldText.length;
    }
    get oldEnd() {
      return this.oldPosition + this.oldText.length;
    }
    get newLength() {
      return this.newText.length;
    }
    get newEnd() {
      return this.newPosition + this.newText.length;
    }
    constructor(oldPosition, oldText, newPosition, newText) {
      this.oldPosition = oldPosition;
      this.oldText = oldText;
      this.newPosition = newPosition;
      this.newText = newText;
    }
    toString() {
      if (this.oldText.length === 0) {
        return `(insert@${this.oldPosition} "${escapeNewLine(this.newText)}")`;
      }
      if (this.newText.length === 0) {
        return `(delete@${this.oldPosition} "${escapeNewLine(this.oldText)}")`;
      }
      return `(replace@${this.oldPosition} "${escapeNewLine(this.oldText)}" with "${escapeNewLine(this.newText)}")`;
    }
    static _writeStringSize(str) {
      return 4 + 2 * str.length;
    }
    static _writeString(b, str, offset) {
      const len = str.length;
      writeUInt32BE(b, len, offset);
      offset += 4;
      for (let i2 = 0; i2 < len; i2++) {
        writeUInt16LE(b, str.charCodeAt(i2), offset);
        offset += 2;
      }
      return offset;
    }
    static _readString(b, offset) {
      const len = readUInt32BE(b, offset);
      offset += 4;
      return decodeUTF16LE(b, offset, len);
    }
    writeSize() {
      return 4 + 4 + TextChange._writeStringSize(this.oldText) + TextChange._writeStringSize(this.newText);
    }
    write(b, offset) {
      writeUInt32BE(b, this.oldPosition, offset);
      offset += 4;
      writeUInt32BE(b, this.newPosition, offset);
      offset += 4;
      offset = TextChange._writeString(b, this.oldText, offset);
      offset = TextChange._writeString(b, this.newText, offset);
      return offset;
    }
    static read(b, offset, dest) {
      const oldPosition = readUInt32BE(b, offset);
      offset += 4;
      const newPosition = readUInt32BE(b, offset);
      offset += 4;
      const oldText = TextChange._readString(b, offset);
      offset += TextChange._writeStringSize(oldText);
      const newText = TextChange._readString(b, offset);
      offset += TextChange._writeStringSize(newText);
      dest.push(new TextChange(oldPosition, oldText, newPosition, newText));
      return offset;
    }
  }
  function compressConsecutiveTextChanges(prevEdits, currEdits) {
    if (prevEdits === null || prevEdits.length === 0) {
      return currEdits;
    }
    const compressor = new TextChangeCompressor(prevEdits, currEdits);
    return compressor.compress();
  }
  class TextChangeCompressor {
    constructor(prevEdits, currEdits) {
      this._prevEdits = prevEdits;
      this._currEdits = currEdits;
      this._result = [];
      this._resultLen = 0;
      this._prevLen = this._prevEdits.length;
      this._prevDeltaOffset = 0;
      this._currLen = this._currEdits.length;
      this._currDeltaOffset = 0;
    }
    compress() {
      let prevIndex = 0;
      let currIndex = 0;
      let prevEdit = this._getPrev(prevIndex);
      let currEdit = this._getCurr(currIndex);
      while (prevIndex < this._prevLen || currIndex < this._currLen) {
        if (prevEdit === null) {
          this._acceptCurr(currEdit);
          currEdit = this._getCurr(++currIndex);
          continue;
        }
        if (currEdit === null) {
          this._acceptPrev(prevEdit);
          prevEdit = this._getPrev(++prevIndex);
          continue;
        }
        if (currEdit.oldEnd <= prevEdit.newPosition) {
          this._acceptCurr(currEdit);
          currEdit = this._getCurr(++currIndex);
          continue;
        }
        if (prevEdit.newEnd <= currEdit.oldPosition) {
          this._acceptPrev(prevEdit);
          prevEdit = this._getPrev(++prevIndex);
          continue;
        }
        if (currEdit.oldPosition < prevEdit.newPosition) {
          const [e1, e2] = TextChangeCompressor._splitCurr(currEdit, prevEdit.newPosition - currEdit.oldPosition);
          this._acceptCurr(e1);
          currEdit = e2;
          continue;
        }
        if (prevEdit.newPosition < currEdit.oldPosition) {
          const [e1, e2] = TextChangeCompressor._splitPrev(prevEdit, currEdit.oldPosition - prevEdit.newPosition);
          this._acceptPrev(e1);
          prevEdit = e2;
          continue;
        }
        let mergePrev;
        let mergeCurr;
        if (currEdit.oldEnd === prevEdit.newEnd) {
          mergePrev = prevEdit;
          mergeCurr = currEdit;
          prevEdit = this._getPrev(++prevIndex);
          currEdit = this._getCurr(++currIndex);
        } else if (currEdit.oldEnd < prevEdit.newEnd) {
          const [e1, e2] = TextChangeCompressor._splitPrev(prevEdit, currEdit.oldLength);
          mergePrev = e1;
          mergeCurr = currEdit;
          prevEdit = e2;
          currEdit = this._getCurr(++currIndex);
        } else {
          const [e1, e2] = TextChangeCompressor._splitCurr(currEdit, prevEdit.newLength);
          mergePrev = prevEdit;
          mergeCurr = e1;
          prevEdit = this._getPrev(++prevIndex);
          currEdit = e2;
        }
        this._result[this._resultLen++] = new TextChange(mergePrev.oldPosition, mergePrev.oldText, mergeCurr.newPosition, mergeCurr.newText);
        this._prevDeltaOffset += mergePrev.newLength - mergePrev.oldLength;
        this._currDeltaOffset += mergeCurr.newLength - mergeCurr.oldLength;
      }
      const merged = TextChangeCompressor._merge(this._result);
      const cleaned = TextChangeCompressor._removeNoOps(merged);
      return cleaned;
    }
    _acceptCurr(currEdit) {
      this._result[this._resultLen++] = TextChangeCompressor._rebaseCurr(this._prevDeltaOffset, currEdit);
      this._currDeltaOffset += currEdit.newLength - currEdit.oldLength;
    }
    _getCurr(currIndex) {
      return currIndex < this._currLen ? this._currEdits[currIndex] : null;
    }
    _acceptPrev(prevEdit) {
      this._result[this._resultLen++] = TextChangeCompressor._rebasePrev(this._currDeltaOffset, prevEdit);
      this._prevDeltaOffset += prevEdit.newLength - prevEdit.oldLength;
    }
    _getPrev(prevIndex) {
      return prevIndex < this._prevLen ? this._prevEdits[prevIndex] : null;
    }
    static _rebaseCurr(prevDeltaOffset, currEdit) {
      return new TextChange(currEdit.oldPosition - prevDeltaOffset, currEdit.oldText, currEdit.newPosition, currEdit.newText);
    }
    static _rebasePrev(currDeltaOffset, prevEdit) {
      return new TextChange(prevEdit.oldPosition, prevEdit.oldText, prevEdit.newPosition + currDeltaOffset, prevEdit.newText);
    }
    static _splitPrev(edit2, offset) {
      const preText = edit2.newText.substr(0, offset);
      const postText = edit2.newText.substr(offset);
      return [
        new TextChange(edit2.oldPosition, edit2.oldText, edit2.newPosition, preText),
        new TextChange(edit2.oldEnd, "", edit2.newPosition + offset, postText)
      ];
    }
    static _splitCurr(edit2, offset) {
      const preText = edit2.oldText.substr(0, offset);
      const postText = edit2.oldText.substr(offset);
      return [
        new TextChange(edit2.oldPosition, preText, edit2.newPosition, edit2.newText),
        new TextChange(edit2.oldPosition + offset, postText, edit2.newEnd, "")
      ];
    }
    static _merge(edits) {
      if (edits.length === 0) {
        return edits;
      }
      const result = [];
      let resultLen = 0;
      let prev = edits[0];
      for (let i2 = 1; i2 < edits.length; i2++) {
        const curr = edits[i2];
        if (prev.oldEnd === curr.oldPosition) {
          prev = new TextChange(prev.oldPosition, prev.oldText + curr.oldText, prev.newPosition, prev.newText + curr.newText);
        } else {
          result[resultLen++] = prev;
          prev = curr;
        }
      }
      result[resultLen++] = prev;
      return result;
    }
    static _removeNoOps(edits) {
      if (edits.length === 0) {
        return edits;
      }
      const result = [];
      let resultLen = 0;
      for (let i2 = 0; i2 < edits.length; i2++) {
        const edit2 = edits[i2];
        if (edit2.oldText === edit2.newText) {
          continue;
        }
        result[resultLen++] = edit2;
      }
      return result;
    }
  }
  const privateSymbol = Symbol("TextModelEditSource");
  class TextModelEditSource {
    constructor(metadata, _privateCtorGuard) {
      this.metadata = metadata;
    }
    toString() {
      return `${this.metadata.source}`;
    }
    getType() {
      const metadata = this.metadata;
      switch (metadata.source) {
        case "cursor":
          return metadata.kind;
        case "inlineCompletionAccept":
          return metadata.source + (metadata.$nes ? ":nes" : "");
        case "unknown":
          return metadata.name || "unknown";
        default:
          return metadata.source;
      }
    }
    /**
     * Converts the metadata to a key string.
     * Only includes properties/values that have `level` many `$` prefixes or less.
    */
    toKey(level, filter = {}) {
      const metadata = this.metadata;
      const keys = Object.entries(metadata).filter(([key, value]) => {
        const filterVal = filter[key];
        if (filterVal !== void 0) {
          return filterVal;
        }
        const prefixCount = (key.match(/\$/g) || []).length;
        return prefixCount <= level && value !== void 0 && value !== null && value !== "";
      }).map(([key, value]) => `${key}:${value}`);
      return keys.join("-");
    }
  }
  function createEditSource(metadata) {
    return new TextModelEditSource(metadata, privateSymbol);
  }
  const EditSources = {
    unknown(data) {
      return createEditSource({
        source: "unknown",
        name: data.name
      });
    },
    rename: () => createEditSource({ source: "rename" }),
    chatApplyEdits(data) {
      return createEditSource({
        source: "Chat.applyEdits",
        $modelId: avoidPathRedaction(data.modelId),
        $extensionId: data.extensionId?.extensionId,
        $extensionVersion: data.extensionId?.version,
        $$languageId: data.languageId,
        $$sessionId: data.sessionId,
        $$requestId: data.requestId,
        $$mode: data.mode,
        $$codeBlockSuggestionId: data.codeBlockSuggestionId
      });
    },
    chatUndoEdits: () => createEditSource({ source: "Chat.undoEdits" }),
    chatReset: () => createEditSource({ source: "Chat.reset" }),
    inlineCompletionAccept(data) {
      return createEditSource({
        source: "inlineCompletionAccept",
        $nes: data.nes,
        ...toProperties(data.providerId),
        $$requestUuid: data.requestUuid,
        $$languageId: data.languageId
      });
    },
    inlineCompletionPartialAccept(data) {
      return createEditSource({
        source: "inlineCompletionPartialAccept",
        type: data.type,
        $nes: data.nes,
        ...toProperties(data.providerId),
        $$requestUuid: data.requestUuid,
        $$languageId: data.languageId
      });
    },
    inlineChatApplyEdit(data) {
      return createEditSource({
        source: "inlineChat.applyEdits",
        $modelId: avoidPathRedaction(data.modelId),
        $extensionId: data.extensionId?.extensionId,
        $extensionVersion: data.extensionId?.version,
        $$sessionId: data.sessionId,
        $$requestId: data.requestId,
        $$languageId: data.languageId
      });
    },
    reloadFromDisk: () => createEditSource({ source: "reloadFromDisk" }),
    cursor(data) {
      return createEditSource({
        source: "cursor",
        kind: data.kind,
        detailedSource: data.detailedSource
      });
    },
    setValue: () => createEditSource({ source: "setValue" }),
    eolChange: () => createEditSource({ source: "eolChange" }),
    applyEdits: () => createEditSource({ source: "applyEdits" }),
    snippet: () => createEditSource({ source: "snippet" }),
    suggest: (data) => createEditSource({ source: "suggest", ...toProperties(data.providerId) }),
    codeAction: (data) => createEditSource({ source: "codeAction", $kind: data.kind, ...toProperties(data.providerId) })
  };
  function toProperties(version) {
    if (!version) {
      return {};
    }
    return {
      $extensionId: version.extensionId,
      $extensionVersion: version.extensionVersion,
      $providerId: version.providerId
    };
  }
  function avoidPathRedaction(str) {
    if (str === void 0) {
      return void 0;
    }
    return str.replaceAll("/", "|");
  }
  class EditDeltaInfo {
    static fromText(text2) {
      const linesAdded = TextLength.ofText(text2).lineCount;
      const charsAdded = text2.length;
      return new EditDeltaInfo(linesAdded, 0, charsAdded, 0);
    }
    static tryCreate(linesAdded, linesRemoved, charsAdded, charsRemoved) {
      if (linesAdded === void 0 || linesRemoved === void 0 || charsAdded === void 0 || charsRemoved === void 0) {
        return void 0;
      }
      return new EditDeltaInfo(linesAdded, linesRemoved, charsAdded, charsRemoved);
    }
    constructor(linesAdded, linesRemoved, charsAdded, charsRemoved) {
      this.linesAdded = linesAdded;
      this.linesRemoved = linesRemoved;
      this.charsAdded = charsAdded;
      this.charsRemoved = charsRemoved;
    }
  }
  var EditSuggestionId;
  (function(EditSuggestionId2) {
    function newId(genPrefixedUuid) {
      const id = genPrefixedUuid ? genPrefixedUuid("sgt") : prefixedUuid("sgt");
      return toEditIdentity(id);
    }
    EditSuggestionId2.newId = newId;
  })(EditSuggestionId || (EditSuggestionId = {}));
  function toEditIdentity(id) {
    return id;
  }
  function uriGetComparisonKey(resource) {
    return resource.toString();
  }
  class SingleModelEditStackData {
    static create(model, beforeCursorState) {
      const alternativeVersionId = model.getAlternativeVersionId();
      const eol = getModelEOL(model);
      return new SingleModelEditStackData(alternativeVersionId, alternativeVersionId, eol, eol, beforeCursorState, beforeCursorState, []);
    }
    constructor(beforeVersionId, afterVersionId, beforeEOL, afterEOL, beforeCursorState, afterCursorState, changes) {
      this.beforeVersionId = beforeVersionId;
      this.afterVersionId = afterVersionId;
      this.beforeEOL = beforeEOL;
      this.afterEOL = afterEOL;
      this.beforeCursorState = beforeCursorState;
      this.afterCursorState = afterCursorState;
      this.changes = changes;
    }
    append(model, textChanges, afterEOL, afterVersionId, afterCursorState) {
      if (textChanges.length > 0) {
        this.changes = compressConsecutiveTextChanges(this.changes, textChanges);
      }
      this.afterEOL = afterEOL;
      this.afterVersionId = afterVersionId;
      this.afterCursorState = afterCursorState;
    }
    static _writeSelectionsSize(selections) {
      return 4 + 4 * 4 * (selections ? selections.length : 0);
    }
    static _writeSelections(b, selections, offset) {
      writeUInt32BE(b, selections ? selections.length : 0, offset);
      offset += 4;
      if (selections) {
        for (const selection of selections) {
          writeUInt32BE(b, selection.selectionStartLineNumber, offset);
          offset += 4;
          writeUInt32BE(b, selection.selectionStartColumn, offset);
          offset += 4;
          writeUInt32BE(b, selection.positionLineNumber, offset);
          offset += 4;
          writeUInt32BE(b, selection.positionColumn, offset);
          offset += 4;
        }
      }
      return offset;
    }
    static _readSelections(b, offset, dest) {
      const count = readUInt32BE(b, offset);
      offset += 4;
      for (let i2 = 0; i2 < count; i2++) {
        const selectionStartLineNumber = readUInt32BE(b, offset);
        offset += 4;
        const selectionStartColumn = readUInt32BE(b, offset);
        offset += 4;
        const positionLineNumber = readUInt32BE(b, offset);
        offset += 4;
        const positionColumn = readUInt32BE(b, offset);
        offset += 4;
        dest.push(new Selection$1(selectionStartLineNumber, selectionStartColumn, positionLineNumber, positionColumn));
      }
      return offset;
    }
    serialize() {
      let necessarySize = 4 + 4 + 1 + 1 + SingleModelEditStackData._writeSelectionsSize(this.beforeCursorState) + SingleModelEditStackData._writeSelectionsSize(this.afterCursorState) + 4;
      for (const change of this.changes) {
        necessarySize += change.writeSize();
      }
      const b = new Uint8Array(necessarySize);
      let offset = 0;
      writeUInt32BE(b, this.beforeVersionId, offset);
      offset += 4;
      writeUInt32BE(b, this.afterVersionId, offset);
      offset += 4;
      writeUInt8(b, this.beforeEOL, offset);
      offset += 1;
      writeUInt8(b, this.afterEOL, offset);
      offset += 1;
      offset = SingleModelEditStackData._writeSelections(b, this.beforeCursorState, offset);
      offset = SingleModelEditStackData._writeSelections(b, this.afterCursorState, offset);
      writeUInt32BE(b, this.changes.length, offset);
      offset += 4;
      for (const change of this.changes) {
        offset = change.write(b, offset);
      }
      return b.buffer;
    }
    static deserialize(source) {
      const b = new Uint8Array(source);
      let offset = 0;
      const beforeVersionId = readUInt32BE(b, offset);
      offset += 4;
      const afterVersionId = readUInt32BE(b, offset);
      offset += 4;
      const beforeEOL = readUInt8(b, offset);
      offset += 1;
      const afterEOL = readUInt8(b, offset);
      offset += 1;
      const beforeCursorState = [];
      offset = SingleModelEditStackData._readSelections(b, offset, beforeCursorState);
      const afterCursorState = [];
      offset = SingleModelEditStackData._readSelections(b, offset, afterCursorState);
      const changeCount = readUInt32BE(b, offset);
      offset += 4;
      const changes = [];
      for (let i2 = 0; i2 < changeCount; i2++) {
        offset = TextChange.read(b, offset, changes);
      }
      return new SingleModelEditStackData(beforeVersionId, afterVersionId, beforeEOL, afterEOL, beforeCursorState, afterCursorState, changes);
    }
  }
  class SingleModelEditStackElement {
    get type() {
      return 0;
    }
    get resource() {
      if (URI.isUri(this.model)) {
        return this.model;
      }
      return this.model.uri;
    }
    constructor(label, code, model, beforeCursorState) {
      this.label = label;
      this.code = code;
      this.model = model;
      this._data = SingleModelEditStackData.create(model, beforeCursorState);
    }
    toString() {
      const data = this._data instanceof SingleModelEditStackData ? this._data : SingleModelEditStackData.deserialize(this._data);
      return data.changes.map((change) => change.toString()).join(", ");
    }
    matchesResource(resource) {
      const uri = URI.isUri(this.model) ? this.model : this.model.uri;
      return uri.toString() === resource.toString();
    }
    setModel(model) {
      this.model = model;
    }
    canAppend(model) {
      return this.model === model && this._data instanceof SingleModelEditStackData;
    }
    append(model, textChanges, afterEOL, afterVersionId, afterCursorState) {
      if (this._data instanceof SingleModelEditStackData) {
        this._data.append(model, textChanges, afterEOL, afterVersionId, afterCursorState);
      }
    }
    close() {
      if (this._data instanceof SingleModelEditStackData) {
        this._data = this._data.serialize();
      }
    }
    open() {
      if (!(this._data instanceof SingleModelEditStackData)) {
        this._data = SingleModelEditStackData.deserialize(this._data);
      }
    }
    undo() {
      if (URI.isUri(this.model)) {
        throw new Error(`Invalid SingleModelEditStackElement`);
      }
      if (this._data instanceof SingleModelEditStackData) {
        this._data = this._data.serialize();
      }
      const data = SingleModelEditStackData.deserialize(this._data);
      this.model._applyUndo(data.changes, data.beforeEOL, data.beforeVersionId, data.beforeCursorState);
    }
    redo() {
      if (URI.isUri(this.model)) {
        throw new Error(`Invalid SingleModelEditStackElement`);
      }
      if (this._data instanceof SingleModelEditStackData) {
        this._data = this._data.serialize();
      }
      const data = SingleModelEditStackData.deserialize(this._data);
      this.model._applyRedo(data.changes, data.afterEOL, data.afterVersionId, data.afterCursorState);
    }
    heapSize() {
      if (this._data instanceof SingleModelEditStackData) {
        this._data = this._data.serialize();
      }
      return this._data.byteLength + 168;
    }
  }
  class MultiModelEditStackElement {
    get resources() {
      return this._editStackElementsArr.map((editStackElement) => editStackElement.resource);
    }
    constructor(label, code, editStackElements) {
      this.label = label;
      this.code = code;
      this.type = 1;
      this._isOpen = true;
      this._editStackElementsArr = editStackElements.slice(0);
      this._editStackElementsMap = /* @__PURE__ */ new Map();
      for (const editStackElement of this._editStackElementsArr) {
        const key = uriGetComparisonKey(editStackElement.resource);
        this._editStackElementsMap.set(key, editStackElement);
      }
      this._delegate = null;
    }
    prepareUndoRedo() {
      if (this._delegate) {
        return this._delegate.prepareUndoRedo(this);
      }
    }
    matchesResource(resource) {
      const key = uriGetComparisonKey(resource);
      return this._editStackElementsMap.has(key);
    }
    setModel(model) {
      const key = uriGetComparisonKey(URI.isUri(model) ? model : model.uri);
      if (this._editStackElementsMap.has(key)) {
        this._editStackElementsMap.get(key).setModel(model);
      }
    }
    canAppend(model) {
      if (!this._isOpen) {
        return false;
      }
      const key = uriGetComparisonKey(model.uri);
      if (this._editStackElementsMap.has(key)) {
        const editStackElement = this._editStackElementsMap.get(key);
        return editStackElement.canAppend(model);
      }
      return false;
    }
    append(model, textChanges, afterEOL, afterVersionId, afterCursorState) {
      const key = uriGetComparisonKey(model.uri);
      const editStackElement = this._editStackElementsMap.get(key);
      editStackElement.append(model, textChanges, afterEOL, afterVersionId, afterCursorState);
    }
    close() {
      this._isOpen = false;
    }
    open() {
    }
    undo() {
      this._isOpen = false;
      for (const editStackElement of this._editStackElementsArr) {
        editStackElement.undo();
      }
    }
    redo() {
      for (const editStackElement of this._editStackElementsArr) {
        editStackElement.redo();
      }
    }
    heapSize(resource) {
      const key = uriGetComparisonKey(resource);
      if (this._editStackElementsMap.has(key)) {
        const editStackElement = this._editStackElementsMap.get(key);
        return editStackElement.heapSize();
      }
      return 0;
    }
    split() {
      return this._editStackElementsArr;
    }
    toString() {
      const result = [];
      for (const editStackElement of this._editStackElementsArr) {
        result.push(`${basename(editStackElement.resource)}: ${editStackElement}`);
      }
      return `{${result.join(", ")}}`;
    }
  }
  function getModelEOL(model) {
    const eol = model.getEOL();
    if (eol === "\n") {
      return 0;
    } else {
      return 1;
    }
  }
  function isEditStackElement(element) {
    if (!element) {
      return false;
    }
    return element instanceof SingleModelEditStackElement || element instanceof MultiModelEditStackElement;
  }
  class EditStack {
    constructor(model, undoRedoService) {
      this._model = model;
      this._undoRedoService = undoRedoService;
    }
    pushStackElement() {
      const lastElement = this._undoRedoService.getLastElement(this._model.uri);
      if (isEditStackElement(lastElement)) {
        lastElement.close();
      }
    }
    popStackElement() {
      const lastElement = this._undoRedoService.getLastElement(this._model.uri);
      if (isEditStackElement(lastElement)) {
        lastElement.open();
      }
    }
    clear() {
      this._undoRedoService.removeElements(this._model.uri);
    }
    _getOrCreateEditStackElement(beforeCursorState, group) {
      const lastElement = this._undoRedoService.getLastElement(this._model.uri);
      if (isEditStackElement(lastElement) && lastElement.canAppend(this._model)) {
        return lastElement;
      }
      const newElement = new SingleModelEditStackElement(localize(785, "Typing"), "undoredo.textBufferEdit", this._model, beforeCursorState);
      this._undoRedoService.pushElement(newElement, group);
      return newElement;
    }
    pushEOL(eol) {
      const editStackElement = this._getOrCreateEditStackElement(null, void 0);
      this._model.setEOL(eol);
      editStackElement.append(this._model, [], getModelEOL(this._model), this._model.getAlternativeVersionId(), null);
    }
    pushEditOperation(beforeCursorState, editOperations, cursorStateComputer, group, reason = EditSources.unknown({ name: "pushEditOperation" })) {
      const editStackElement = this._getOrCreateEditStackElement(beforeCursorState, group);
      const inverseEditOperations = this._model.applyEdits(editOperations, true, reason);
      const afterCursorState = EditStack._computeCursorState(cursorStateComputer, inverseEditOperations);
      const textChanges = inverseEditOperations.map((op, index) => ({ index, textChange: op.textChange }));
      textChanges.sort((a, b) => {
        if (a.textChange.oldPosition === b.textChange.oldPosition) {
          return a.index - b.index;
        }
        return a.textChange.oldPosition - b.textChange.oldPosition;
      });
      editStackElement.append(this._model, textChanges.map((op) => op.textChange), getModelEOL(this._model), this._model.getAlternativeVersionId(), afterCursorState);
      return afterCursorState;
    }
    static _computeCursorState(cursorStateComputer, inverseEditOperations) {
      try {
        return cursorStateComputer ? cursorStateComputer(inverseEditOperations) : null;
      } catch (e) {
        onUnexpectedError(e);
        return null;
      }
    }
  }
  class SpacesDiffResult {
    constructor() {
      this.spacesDiff = 0;
      this.looksLikeAlignment = false;
    }
  }
  function spacesDiff(a, aLength, b, bLength, result) {
    result.spacesDiff = 0;
    result.looksLikeAlignment = false;
    let i2;
    for (i2 = 0; i2 < aLength && i2 < bLength; i2++) {
      const aCharCode = a.charCodeAt(i2);
      const bCharCode = b.charCodeAt(i2);
      if (aCharCode !== bCharCode) {
        break;
      }
    }
    let aSpacesCnt = 0, aTabsCount = 0;
    for (let j = i2; j < aLength; j++) {
      const aCharCode = a.charCodeAt(j);
      if (aCharCode === 32) {
        aSpacesCnt++;
      } else {
        aTabsCount++;
      }
    }
    let bSpacesCnt = 0, bTabsCount = 0;
    for (let j = i2; j < bLength; j++) {
      const bCharCode = b.charCodeAt(j);
      if (bCharCode === 32) {
        bSpacesCnt++;
      } else {
        bTabsCount++;
      }
    }
    if (aSpacesCnt > 0 && aTabsCount > 0) {
      return;
    }
    if (bSpacesCnt > 0 && bTabsCount > 0) {
      return;
    }
    const tabsDiff = Math.abs(aTabsCount - bTabsCount);
    const spacesDiff2 = Math.abs(aSpacesCnt - bSpacesCnt);
    if (tabsDiff === 0) {
      result.spacesDiff = spacesDiff2;
      if (spacesDiff2 > 0 && 0 <= bSpacesCnt - 1 && bSpacesCnt - 1 < a.length && bSpacesCnt < b.length) {
        if (b.charCodeAt(bSpacesCnt) !== 32 && a.charCodeAt(bSpacesCnt - 1) === 32) {
          if (a.charCodeAt(a.length - 1) === 44) {
            result.looksLikeAlignment = true;
          }
        }
      }
      return;
    }
    if (spacesDiff2 % tabsDiff === 0) {
      result.spacesDiff = spacesDiff2 / tabsDiff;
      return;
    }
  }
  function guessIndentation(source, defaultTabSize, defaultInsertSpaces) {
    const linesCount = Math.min(source.getLineCount(), 1e4);
    let linesIndentedWithTabsCount = 0;
    let linesIndentedWithSpacesCount = 0;
    let previousLineText = "";
    let previousLineIndentation = 0;
    const ALLOWED_TAB_SIZE_GUESSES = [2, 4, 6, 8, 3, 5, 7];
    const MAX_ALLOWED_TAB_SIZE_GUESS = 8;
    const spacesDiffCount = [0, 0, 0, 0, 0, 0, 0, 0, 0];
    const tmp = new SpacesDiffResult();
    for (let lineNumber = 1; lineNumber <= linesCount; lineNumber++) {
      const currentLineLength = source.getLineLength(lineNumber);
      const currentLineText = source.getLineContent(lineNumber);
      const useCurrentLineText = currentLineLength <= 65536;
      let currentLineHasContent = false;
      let currentLineIndentation = 0;
      let currentLineSpacesCount = 0;
      let currentLineTabsCount = 0;
      for (let j = 0, lenJ = currentLineLength; j < lenJ; j++) {
        const charCode = useCurrentLineText ? currentLineText.charCodeAt(j) : source.getLineCharCode(lineNumber, j);
        if (charCode === 9) {
          currentLineTabsCount++;
        } else if (charCode === 32) {
          currentLineSpacesCount++;
        } else {
          currentLineHasContent = true;
          currentLineIndentation = j;
          break;
        }
      }
      if (!currentLineHasContent) {
        continue;
      }
      if (currentLineTabsCount > 0) {
        linesIndentedWithTabsCount++;
      } else if (currentLineSpacesCount > 1) {
        linesIndentedWithSpacesCount++;
      }
      spacesDiff(previousLineText, previousLineIndentation, currentLineText, currentLineIndentation, tmp);
      if (tmp.looksLikeAlignment) {
        if (!(defaultInsertSpaces && defaultTabSize === tmp.spacesDiff)) {
          continue;
        }
      }
      const currentSpacesDiff = tmp.spacesDiff;
      if (currentSpacesDiff <= MAX_ALLOWED_TAB_SIZE_GUESS) {
        spacesDiffCount[currentSpacesDiff]++;
      }
      previousLineText = currentLineText;
      previousLineIndentation = currentLineIndentation;
    }
    let insertSpaces = defaultInsertSpaces;
    if (linesIndentedWithTabsCount !== linesIndentedWithSpacesCount) {
      insertSpaces = linesIndentedWithTabsCount < linesIndentedWithSpacesCount;
    }
    let tabSize = defaultTabSize;
    if (insertSpaces) {
      let tabSizeScore = insertSpaces ? 0 : 0.1 * linesCount;
      ALLOWED_TAB_SIZE_GUESSES.forEach((possibleTabSize) => {
        const possibleTabSizeScore = spacesDiffCount[possibleTabSize];
        if (possibleTabSizeScore > tabSizeScore) {
          tabSizeScore = possibleTabSizeScore;
          tabSize = possibleTabSize;
        }
      });
      if (tabSize === 4 && spacesDiffCount[4] > 0 && spacesDiffCount[2] > 0 && spacesDiffCount[2] >= spacesDiffCount[4] / 2) {
        tabSize = 2;
      }
    }
    return {
      insertSpaces,
      tabSize
    };
  }
  function getNodeColor(node) {
    return (node.metadata & 1) >>> 0;
  }
  function setNodeColor(node, color) {
    node.metadata = node.metadata & 254 | color << 0;
  }
  function getNodeIsVisited(node) {
    return (node.metadata & 2) >>> 1 === 1;
  }
  function setNodeIsVisited(node, value) {
    node.metadata = node.metadata & 253 | (value ? 1 : 0) << 1;
  }
  function getNodeIsForValidation(node) {
    return (node.metadata & 4) >>> 2 === 1;
  }
  function setNodeIsForValidation(node, value) {
    node.metadata = node.metadata & 251 | (value ? 1 : 0) << 2;
  }
  function getNodeIsInGlyphMargin(node) {
    return (node.metadata & 64) >>> 6 === 1;
  }
  function setNodeIsInGlyphMargin(node, value) {
    node.metadata = node.metadata & 191 | (value ? 1 : 0) << 6;
  }
  function getNodeAffectsFont(node) {
    return (node.metadata & 128) >>> 7 === 1;
  }
  function setNodeAffectsFont(node, value) {
    node.metadata = node.metadata & 127 | (value ? 1 : 0) << 7;
  }
  function getNodeStickiness(node) {
    return (node.metadata & 24) >>> 3;
  }
  function _setNodeStickiness(node, stickiness) {
    node.metadata = node.metadata & 231 | stickiness << 3;
  }
  function getCollapseOnReplaceEdit(node) {
    return (node.metadata & 32) >>> 5 === 1;
  }
  function setCollapseOnReplaceEdit(node, value) {
    node.metadata = node.metadata & 223 | (value ? 1 : 0) << 5;
  }
  class IntervalNode {
    constructor(id, start, end) {
      this.metadata = 0;
      this.parent = this;
      this.left = this;
      this.right = this;
      setNodeColor(
        this,
        1
        /* NodeColor.Red */
      );
      this.start = start;
      this.end = end;
      this.delta = 0;
      this.maxEnd = end;
      this.id = id;
      this.ownerId = 0;
      this.options = null;
      setNodeIsForValidation(this, false);
      setNodeIsInGlyphMargin(this, false);
      _setNodeStickiness(
        this,
        1
        /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */
      );
      setCollapseOnReplaceEdit(this, false);
      setNodeAffectsFont(this, false);
      this.cachedVersionId = 0;
      this.cachedAbsoluteStart = start;
      this.cachedAbsoluteEnd = end;
      this.range = null;
      setNodeIsVisited(this, false);
    }
    reset(versionId, start, end, range2) {
      this.start = start;
      this.end = end;
      this.maxEnd = end;
      this.cachedVersionId = versionId;
      this.cachedAbsoluteStart = start;
      this.cachedAbsoluteEnd = end;
      this.range = range2;
    }
    setOptions(options) {
      this.options = options;
      const className2 = this.options.className;
      setNodeIsForValidation(this, className2 === "squiggly-error" || className2 === "squiggly-warning" || className2 === "squiggly-info");
      setNodeIsInGlyphMargin(this, this.options.glyphMarginClassName !== null);
      _setNodeStickiness(this, this.options.stickiness);
      setCollapseOnReplaceEdit(this, this.options.collapseOnReplaceEdit);
      setNodeAffectsFont(this, this.options.affectsFont ?? false);
    }
    setCachedOffsets(absoluteStart, absoluteEnd, cachedVersionId) {
      if (this.cachedVersionId !== cachedVersionId) {
        this.range = null;
      }
      this.cachedVersionId = cachedVersionId;
      this.cachedAbsoluteStart = absoluteStart;
      this.cachedAbsoluteEnd = absoluteEnd;
    }
    detach() {
      this.parent = null;
      this.left = null;
      this.right = null;
    }
  }
  const SENTINEL$1 = new IntervalNode(null, 0, 0);
  SENTINEL$1.parent = SENTINEL$1;
  SENTINEL$1.left = SENTINEL$1;
  SENTINEL$1.right = SENTINEL$1;
  setNodeColor(
    SENTINEL$1,
    0
    /* NodeColor.Black */
  );
  class IntervalTree {
    constructor() {
      this.root = SENTINEL$1;
      this.requestNormalizeDelta = false;
    }
    intervalSearch(start, end, filterOwnerId, filterOutValidation, filterFontDecorations2, cachedVersionId, onlyMarginDecorations) {
      if (this.root === SENTINEL$1) {
        return [];
      }
      return intervalSearch(this, start, end, filterOwnerId, filterOutValidation, filterFontDecorations2, cachedVersionId, onlyMarginDecorations);
    }
    search(filterOwnerId, filterOutValidation, filterFontDecorations2, cachedVersionId, onlyMarginDecorations) {
      if (this.root === SENTINEL$1) {
        return [];
      }
      return search(this, filterOwnerId, filterOutValidation, filterFontDecorations2, cachedVersionId, onlyMarginDecorations);
    }
    /**
     * Will not set `cachedAbsoluteStart` nor `cachedAbsoluteEnd` on the returned nodes!
     */
    collectNodesFromOwner(ownerId2) {
      return collectNodesFromOwner(this, ownerId2);
    }
    /**
     * Will not set `cachedAbsoluteStart` nor `cachedAbsoluteEnd` on the returned nodes!
     */
    collectNodesPostOrder() {
      return collectNodesPostOrder(this);
    }
    insert(node) {
      rbTreeInsert(this, node);
      this._normalizeDeltaIfNecessary();
    }
    delete(node) {
      rbTreeDelete(this, node);
      this._normalizeDeltaIfNecessary();
    }
    resolveNode(node, cachedVersionId) {
      const initialNode = node;
      let delta = 0;
      while (node !== this.root) {
        if (node === node.parent.right) {
          delta += node.parent.delta;
        }
        node = node.parent;
      }
      const nodeStart = initialNode.start + delta;
      const nodeEnd = initialNode.end + delta;
      initialNode.setCachedOffsets(nodeStart, nodeEnd, cachedVersionId);
    }
    acceptReplace(offset, length, textLength, forceMoveMarkers) {
      const nodesOfInterest = searchForEditing(this, offset, offset + length);
      for (let i2 = 0, len = nodesOfInterest.length; i2 < len; i2++) {
        const node = nodesOfInterest[i2];
        rbTreeDelete(this, node);
      }
      this._normalizeDeltaIfNecessary();
      noOverlapReplace(this, offset, offset + length, textLength);
      this._normalizeDeltaIfNecessary();
      for (let i2 = 0, len = nodesOfInterest.length; i2 < len; i2++) {
        const node = nodesOfInterest[i2];
        node.start = node.cachedAbsoluteStart;
        node.end = node.cachedAbsoluteEnd;
        nodeAcceptEdit(node, offset, offset + length, textLength, forceMoveMarkers);
        node.maxEnd = node.end;
        rbTreeInsert(this, node);
      }
      this._normalizeDeltaIfNecessary();
    }
    _normalizeDeltaIfNecessary() {
      if (!this.requestNormalizeDelta) {
        return;
      }
      this.requestNormalizeDelta = false;
      normalizeDelta(this);
    }
  }
  function normalizeDelta(T) {
    let node = T.root;
    let delta = 0;
    while (node !== SENTINEL$1) {
      if (node.left !== SENTINEL$1 && !getNodeIsVisited(node.left)) {
        node = node.left;
        continue;
      }
      if (node.right !== SENTINEL$1 && !getNodeIsVisited(node.right)) {
        delta += node.delta;
        node = node.right;
        continue;
      }
      node.start = delta + node.start;
      node.end = delta + node.end;
      node.delta = 0;
      recomputeMaxEnd(node);
      setNodeIsVisited(node, true);
      setNodeIsVisited(node.left, false);
      setNodeIsVisited(node.right, false);
      if (node === node.parent.right) {
        delta -= node.parent.delta;
      }
      node = node.parent;
    }
    setNodeIsVisited(T.root, false);
  }
  function adjustMarkerBeforeColumn(markerOffset, markerStickToPreviousCharacter, checkOffset, moveSemantics) {
    if (markerOffset < checkOffset) {
      return true;
    }
    if (markerOffset > checkOffset) {
      return false;
    }
    if (moveSemantics === 1) {
      return false;
    }
    if (moveSemantics === 2) {
      return true;
    }
    return markerStickToPreviousCharacter;
  }
  function nodeAcceptEdit(node, start, end, textLength, forceMoveMarkers) {
    const nodeStickiness = getNodeStickiness(node);
    const startStickToPreviousCharacter = nodeStickiness === 0 || nodeStickiness === 2;
    const endStickToPreviousCharacter = nodeStickiness === 1 || nodeStickiness === 2;
    const deletingCnt = end - start;
    const insertingCnt = textLength;
    const commonLength = Math.min(deletingCnt, insertingCnt);
    const nodeStart = node.start;
    let startDone = false;
    const nodeEnd = node.end;
    let endDone = false;
    if (start <= nodeStart && nodeEnd <= end && getCollapseOnReplaceEdit(node)) {
      node.start = start;
      startDone = true;
      node.end = start;
      endDone = true;
    }
    {
      const moveSemantics = forceMoveMarkers ? 1 : deletingCnt > 0 ? 2 : 0;
      if (!startDone && adjustMarkerBeforeColumn(nodeStart, startStickToPreviousCharacter, start, moveSemantics)) {
        startDone = true;
      }
      if (!endDone && adjustMarkerBeforeColumn(nodeEnd, endStickToPreviousCharacter, start, moveSemantics)) {
        endDone = true;
      }
    }
    if (commonLength > 0 && !forceMoveMarkers) {
      const moveSemantics = deletingCnt > insertingCnt ? 2 : 0;
      if (!startDone && adjustMarkerBeforeColumn(nodeStart, startStickToPreviousCharacter, start + commonLength, moveSemantics)) {
        startDone = true;
      }
      if (!endDone && adjustMarkerBeforeColumn(nodeEnd, endStickToPreviousCharacter, start + commonLength, moveSemantics)) {
        endDone = true;
      }
    }
    {
      const moveSemantics = forceMoveMarkers ? 1 : 0;
      if (!startDone && adjustMarkerBeforeColumn(nodeStart, startStickToPreviousCharacter, end, moveSemantics)) {
        node.start = start + insertingCnt;
        startDone = true;
      }
      if (!endDone && adjustMarkerBeforeColumn(nodeEnd, endStickToPreviousCharacter, end, moveSemantics)) {
        node.end = start + insertingCnt;
        endDone = true;
      }
    }
    const deltaColumn = insertingCnt - deletingCnt;
    if (!startDone) {
      node.start = Math.max(0, nodeStart + deltaColumn);
    }
    if (!endDone) {
      node.end = Math.max(0, nodeEnd + deltaColumn);
    }
    if (node.start > node.end) {
      node.end = node.start;
    }
  }
  function searchForEditing(T, start, end) {
    let node = T.root;
    let delta = 0;
    let nodeMaxEnd = 0;
    let nodeStart = 0;
    let nodeEnd = 0;
    const result = [];
    let resultLen = 0;
    while (node !== SENTINEL$1) {
      if (getNodeIsVisited(node)) {
        setNodeIsVisited(node.left, false);
        setNodeIsVisited(node.right, false);
        if (node === node.parent.right) {
          delta -= node.parent.delta;
        }
        node = node.parent;
        continue;
      }
      if (!getNodeIsVisited(node.left)) {
        nodeMaxEnd = delta + node.maxEnd;
        if (nodeMaxEnd < start) {
          setNodeIsVisited(node, true);
          continue;
        }
        if (node.left !== SENTINEL$1) {
          node = node.left;
          continue;
        }
      }
      nodeStart = delta + node.start;
      if (nodeStart > end) {
        setNodeIsVisited(node, true);
        continue;
      }
      nodeEnd = delta + node.end;
      if (nodeEnd >= start) {
        node.setCachedOffsets(nodeStart, nodeEnd, 0);
        result[resultLen++] = node;
      }
      setNodeIsVisited(node, true);
      if (node.right !== SENTINEL$1 && !getNodeIsVisited(node.right)) {
        delta += node.delta;
        node = node.right;
        continue;
      }
    }
    setNodeIsVisited(T.root, false);
    return result;
  }
  function noOverlapReplace(T, start, end, textLength) {
    let node = T.root;
    let delta = 0;
    let nodeMaxEnd = 0;
    let nodeStart = 0;
    const editDelta = textLength - (end - start);
    while (node !== SENTINEL$1) {
      if (getNodeIsVisited(node)) {
        setNodeIsVisited(node.left, false);
        setNodeIsVisited(node.right, false);
        if (node === node.parent.right) {
          delta -= node.parent.delta;
        }
        recomputeMaxEnd(node);
        node = node.parent;
        continue;
      }
      if (!getNodeIsVisited(node.left)) {
        nodeMaxEnd = delta + node.maxEnd;
        if (nodeMaxEnd < start) {
          setNodeIsVisited(node, true);
          continue;
        }
        if (node.left !== SENTINEL$1) {
          node = node.left;
          continue;
        }
      }
      nodeStart = delta + node.start;
      if (nodeStart > end) {
        node.start += editDelta;
        node.end += editDelta;
        node.delta += editDelta;
        if (node.delta < -1073741824 || node.delta > 1073741824) {
          T.requestNormalizeDelta = true;
        }
        setNodeIsVisited(node, true);
        continue;
      }
      setNodeIsVisited(node, true);
      if (node.right !== SENTINEL$1 && !getNodeIsVisited(node.right)) {
        delta += node.delta;
        node = node.right;
        continue;
      }
    }
    setNodeIsVisited(T.root, false);
  }
  function collectNodesFromOwner(T, ownerId2) {
    let node = T.root;
    const result = [];
    let resultLen = 0;
    while (node !== SENTINEL$1) {
      if (getNodeIsVisited(node)) {
        setNodeIsVisited(node.left, false);
        setNodeIsVisited(node.right, false);
        node = node.parent;
        continue;
      }
      if (node.left !== SENTINEL$1 && !getNodeIsVisited(node.left)) {
        node = node.left;
        continue;
      }
      if (node.ownerId === ownerId2) {
        result[resultLen++] = node;
      }
      setNodeIsVisited(node, true);
      if (node.right !== SENTINEL$1 && !getNodeIsVisited(node.right)) {
        node = node.right;
        continue;
      }
    }
    setNodeIsVisited(T.root, false);
    return result;
  }
  function collectNodesPostOrder(T) {
    let node = T.root;
    const result = [];
    let resultLen = 0;
    while (node !== SENTINEL$1) {
      if (getNodeIsVisited(node)) {
        setNodeIsVisited(node.left, false);
        setNodeIsVisited(node.right, false);
        node = node.parent;
        continue;
      }
      if (node.left !== SENTINEL$1 && !getNodeIsVisited(node.left)) {
        node = node.left;
        continue;
      }
      if (node.right !== SENTINEL$1 && !getNodeIsVisited(node.right)) {
        node = node.right;
        continue;
      }
      result[resultLen++] = node;
      setNodeIsVisited(node, true);
    }
    setNodeIsVisited(T.root, false);
    return result;
  }
  function search(T, filterOwnerId, filterOutValidation, filterFontDecorations2, cachedVersionId, onlyMarginDecorations) {
    let node = T.root;
    let delta = 0;
    let nodeStart = 0;
    let nodeEnd = 0;
    const result = [];
    let resultLen = 0;
    while (node !== SENTINEL$1) {
      if (getNodeIsVisited(node)) {
        setNodeIsVisited(node.left, false);
        setNodeIsVisited(node.right, false);
        if (node === node.parent.right) {
          delta -= node.parent.delta;
        }
        node = node.parent;
        continue;
      }
      if (node.left !== SENTINEL$1 && !getNodeIsVisited(node.left)) {
        node = node.left;
        continue;
      }
      nodeStart = delta + node.start;
      nodeEnd = delta + node.end;
      node.setCachedOffsets(nodeStart, nodeEnd, cachedVersionId);
      let include = true;
      if (filterOwnerId && node.ownerId && node.ownerId !== filterOwnerId) {
        include = false;
      }
      if (filterOutValidation && getNodeIsForValidation(node)) {
        include = false;
      }
      if (filterFontDecorations2 && getNodeAffectsFont(node)) {
        include = false;
      }
      if (onlyMarginDecorations && !getNodeIsInGlyphMargin(node)) {
        include = false;
      }
      if (include) {
        result[resultLen++] = node;
      }
      setNodeIsVisited(node, true);
      if (node.right !== SENTINEL$1 && !getNodeIsVisited(node.right)) {
        delta += node.delta;
        node = node.right;
        continue;
      }
    }
    setNodeIsVisited(T.root, false);
    return result;
  }
  function intervalSearch(T, intervalStart, intervalEnd, filterOwnerId, filterOutValidation, filterFontDecorations2, cachedVersionId, onlyMarginDecorations) {
    let node = T.root;
    let delta = 0;
    let nodeMaxEnd = 0;
    let nodeStart = 0;
    let nodeEnd = 0;
    const result = [];
    let resultLen = 0;
    while (node !== SENTINEL$1) {
      if (getNodeIsVisited(node)) {
        setNodeIsVisited(node.left, false);
        setNodeIsVisited(node.right, false);
        if (node === node.parent.right) {
          delta -= node.parent.delta;
        }
        node = node.parent;
        continue;
      }
      if (!getNodeIsVisited(node.left)) {
        nodeMaxEnd = delta + node.maxEnd;
        if (nodeMaxEnd < intervalStart) {
          setNodeIsVisited(node, true);
          continue;
        }
        if (node.left !== SENTINEL$1) {
          node = node.left;
          continue;
        }
      }
      nodeStart = delta + node.start;
      if (nodeStart > intervalEnd) {
        setNodeIsVisited(node, true);
        continue;
      }
      nodeEnd = delta + node.end;
      if (nodeEnd >= intervalStart) {
        node.setCachedOffsets(nodeStart, nodeEnd, cachedVersionId);
        let include = true;
        if (filterOwnerId && node.ownerId && node.ownerId !== filterOwnerId) {
          include = false;
        }
        if (filterOutValidation && getNodeIsForValidation(node)) {
          include = false;
        }
        if (filterFontDecorations2 && getNodeAffectsFont(node)) {
          include = false;
        }
        if (onlyMarginDecorations && !getNodeIsInGlyphMargin(node)) {
          include = false;
        }
        if (include) {
          result[resultLen++] = node;
        }
      }
      setNodeIsVisited(node, true);
      if (node.right !== SENTINEL$1 && !getNodeIsVisited(node.right)) {
        delta += node.delta;
        node = node.right;
        continue;
      }
    }
    setNodeIsVisited(T.root, false);
    return result;
  }
  function rbTreeInsert(T, newNode) {
    if (T.root === SENTINEL$1) {
      newNode.parent = SENTINEL$1;
      newNode.left = SENTINEL$1;
      newNode.right = SENTINEL$1;
      setNodeColor(
        newNode,
        0
        /* NodeColor.Black */
      );
      T.root = newNode;
      return T.root;
    }
    treeInsert(T, newNode);
    recomputeMaxEndWalkToRoot(newNode.parent);
    let x = newNode;
    while (x !== T.root && getNodeColor(x.parent) === 1) {
      if (x.parent === x.parent.parent.left) {
        const y = x.parent.parent.right;
        if (getNodeColor(y) === 1) {
          setNodeColor(
            x.parent,
            0
            /* NodeColor.Black */
          );
          setNodeColor(
            y,
            0
            /* NodeColor.Black */
          );
          setNodeColor(
            x.parent.parent,
            1
            /* NodeColor.Red */
          );
          x = x.parent.parent;
        } else {
          if (x === x.parent.right) {
            x = x.parent;
            leftRotate$1(T, x);
          }
          setNodeColor(
            x.parent,
            0
            /* NodeColor.Black */
          );
          setNodeColor(
            x.parent.parent,
            1
            /* NodeColor.Red */
          );
          rightRotate$1(T, x.parent.parent);
        }
      } else {
        const y = x.parent.parent.left;
        if (getNodeColor(y) === 1) {
          setNodeColor(
            x.parent,
            0
            /* NodeColor.Black */
          );
          setNodeColor(
            y,
            0
            /* NodeColor.Black */
          );
          setNodeColor(
            x.parent.parent,
            1
            /* NodeColor.Red */
          );
          x = x.parent.parent;
        } else {
          if (x === x.parent.left) {
            x = x.parent;
            rightRotate$1(T, x);
          }
          setNodeColor(
            x.parent,
            0
            /* NodeColor.Black */
          );
          setNodeColor(
            x.parent.parent,
            1
            /* NodeColor.Red */
          );
          leftRotate$1(T, x.parent.parent);
        }
      }
    }
    setNodeColor(
      T.root,
      0
      /* NodeColor.Black */
    );
    return newNode;
  }
  function treeInsert(T, z) {
    let delta = 0;
    let x = T.root;
    const zAbsoluteStart = z.start;
    const zAbsoluteEnd = z.end;
    while (true) {
      const cmp3 = intervalCompare(zAbsoluteStart, zAbsoluteEnd, x.start + delta, x.end + delta);
      if (cmp3 < 0) {
        if (x.left === SENTINEL$1) {
          z.start -= delta;
          z.end -= delta;
          z.maxEnd -= delta;
          x.left = z;
          break;
        } else {
          x = x.left;
        }
      } else {
        if (x.right === SENTINEL$1) {
          z.start -= delta + x.delta;
          z.end -= delta + x.delta;
          z.maxEnd -= delta + x.delta;
          x.right = z;
          break;
        } else {
          delta += x.delta;
          x = x.right;
        }
      }
    }
    z.parent = x;
    z.left = SENTINEL$1;
    z.right = SENTINEL$1;
    setNodeColor(
      z,
      1
      /* NodeColor.Red */
    );
  }
  function rbTreeDelete(T, z) {
    let x;
    let y;
    if (z.left === SENTINEL$1) {
      x = z.right;
      y = z;
      x.delta += z.delta;
      if (x.delta < -1073741824 || x.delta > 1073741824) {
        T.requestNormalizeDelta = true;
      }
      x.start += z.delta;
      x.end += z.delta;
    } else if (z.right === SENTINEL$1) {
      x = z.left;
      y = z;
    } else {
      y = leftest$1(z.right);
      x = y.right;
      x.start += y.delta;
      x.end += y.delta;
      x.delta += y.delta;
      if (x.delta < -1073741824 || x.delta > 1073741824) {
        T.requestNormalizeDelta = true;
      }
      y.start += z.delta;
      y.end += z.delta;
      y.delta = z.delta;
      if (y.delta < -1073741824 || y.delta > 1073741824) {
        T.requestNormalizeDelta = true;
      }
    }
    if (y === T.root) {
      T.root = x;
      setNodeColor(
        x,
        0
        /* NodeColor.Black */
      );
      z.detach();
      resetSentinel$1();
      recomputeMaxEnd(x);
      T.root.parent = SENTINEL$1;
      return;
    }
    const yWasRed = getNodeColor(y) === 1;
    if (y === y.parent.left) {
      y.parent.left = x;
    } else {
      y.parent.right = x;
    }
    if (y === z) {
      x.parent = y.parent;
    } else {
      if (y.parent === z) {
        x.parent = y;
      } else {
        x.parent = y.parent;
      }
      y.left = z.left;
      y.right = z.right;
      y.parent = z.parent;
      setNodeColor(y, getNodeColor(z));
      if (z === T.root) {
        T.root = y;
      } else {
        if (z === z.parent.left) {
          z.parent.left = y;
        } else {
          z.parent.right = y;
        }
      }
      if (y.left !== SENTINEL$1) {
        y.left.parent = y;
      }
      if (y.right !== SENTINEL$1) {
        y.right.parent = y;
      }
    }
    z.detach();
    if (yWasRed) {
      recomputeMaxEndWalkToRoot(x.parent);
      if (y !== z) {
        recomputeMaxEndWalkToRoot(y);
        recomputeMaxEndWalkToRoot(y.parent);
      }
      resetSentinel$1();
      return;
    }
    recomputeMaxEndWalkToRoot(x);
    recomputeMaxEndWalkToRoot(x.parent);
    if (y !== z) {
      recomputeMaxEndWalkToRoot(y);
      recomputeMaxEndWalkToRoot(y.parent);
    }
    let w;
    while (x !== T.root && getNodeColor(x) === 0) {
      if (x === x.parent.left) {
        w = x.parent.right;
        if (getNodeColor(w) === 1) {
          setNodeColor(
            w,
            0
            /* NodeColor.Black */
          );
          setNodeColor(
            x.parent,
            1
            /* NodeColor.Red */
          );
          leftRotate$1(T, x.parent);
          w = x.parent.right;
        }
        if (getNodeColor(w.left) === 0 && getNodeColor(w.right) === 0) {
          setNodeColor(
            w,
            1
            /* NodeColor.Red */
          );
          x = x.parent;
        } else {
          if (getNodeColor(w.right) === 0) {
            setNodeColor(
              w.left,
              0
              /* NodeColor.Black */
            );
            setNodeColor(
              w,
              1
              /* NodeColor.Red */
            );
            rightRotate$1(T, w);
            w = x.parent.right;
          }
          setNodeColor(w, getNodeColor(x.parent));
          setNodeColor(
            x.parent,
            0
            /* NodeColor.Black */
          );
          setNodeColor(
            w.right,
            0
            /* NodeColor.Black */
          );
          leftRotate$1(T, x.parent);
          x = T.root;
        }
      } else {
        w = x.parent.left;
        if (getNodeColor(w) === 1) {
          setNodeColor(
            w,
            0
            /* NodeColor.Black */
          );
          setNodeColor(
            x.parent,
            1
            /* NodeColor.Red */
          );
          rightRotate$1(T, x.parent);
          w = x.parent.left;
        }
        if (getNodeColor(w.left) === 0 && getNodeColor(w.right) === 0) {
          setNodeColor(
            w,
            1
            /* NodeColor.Red */
          );
          x = x.parent;
        } else {
          if (getNodeColor(w.left) === 0) {
            setNodeColor(
              w.right,
              0
              /* NodeColor.Black */
            );
            setNodeColor(
              w,
              1
              /* NodeColor.Red */
            );
            leftRotate$1(T, w);
            w = x.parent.left;
          }
          setNodeColor(w, getNodeColor(x.parent));
          setNodeColor(
            x.parent,
            0
            /* NodeColor.Black */
          );
          setNodeColor(
            w.left,
            0
            /* NodeColor.Black */
          );
          rightRotate$1(T, x.parent);
          x = T.root;
        }
      }
    }
    setNodeColor(
      x,
      0
      /* NodeColor.Black */
    );
    resetSentinel$1();
  }
  function leftest$1(node) {
    while (node.left !== SENTINEL$1) {
      node = node.left;
    }
    return node;
  }
  function resetSentinel$1() {
    SENTINEL$1.parent = SENTINEL$1;
    SENTINEL$1.delta = 0;
    SENTINEL$1.start = 0;
    SENTINEL$1.end = 0;
  }
  function leftRotate$1(T, x) {
    const y = x.right;
    y.delta += x.delta;
    if (y.delta < -1073741824 || y.delta > 1073741824) {
      T.requestNormalizeDelta = true;
    }
    y.start += x.delta;
    y.end += x.delta;
    x.right = y.left;
    if (y.left !== SENTINEL$1) {
      y.left.parent = x;
    }
    y.parent = x.parent;
    if (x.parent === SENTINEL$1) {
      T.root = y;
    } else if (x === x.parent.left) {
      x.parent.left = y;
    } else {
      x.parent.right = y;
    }
    y.left = x;
    x.parent = y;
    recomputeMaxEnd(x);
    recomputeMaxEnd(y);
  }
  function rightRotate$1(T, y) {
    const x = y.left;
    y.delta -= x.delta;
    if (y.delta < -1073741824 || y.delta > 1073741824) {
      T.requestNormalizeDelta = true;
    }
    y.start -= x.delta;
    y.end -= x.delta;
    y.left = x.right;
    if (x.right !== SENTINEL$1) {
      x.right.parent = y;
    }
    x.parent = y.parent;
    if (y.parent === SENTINEL$1) {
      T.root = x;
    } else if (y === y.parent.right) {
      y.parent.right = x;
    } else {
      y.parent.left = x;
    }
    x.right = y;
    y.parent = x;
    recomputeMaxEnd(y);
    recomputeMaxEnd(x);
  }
  function computeMaxEnd(node) {
    let maxEnd = node.end;
    if (node.left !== SENTINEL$1) {
      const leftMaxEnd = node.left.maxEnd;
      if (leftMaxEnd > maxEnd) {
        maxEnd = leftMaxEnd;
      }
    }
    if (node.right !== SENTINEL$1) {
      const rightMaxEnd = node.right.maxEnd + node.delta;
      if (rightMaxEnd > maxEnd) {
        maxEnd = rightMaxEnd;
      }
    }
    return maxEnd;
  }
  function recomputeMaxEnd(node) {
    node.maxEnd = computeMaxEnd(node);
  }
  function recomputeMaxEndWalkToRoot(node) {
    while (node !== SENTINEL$1) {
      const maxEnd = computeMaxEnd(node);
      if (node.maxEnd === maxEnd) {
        return;
      }
      node.maxEnd = maxEnd;
      node = node.parent;
    }
  }
  function intervalCompare(aStart, aEnd, bStart, bEnd) {
    if (aStart === bStart) {
      return aEnd - bEnd;
    }
    return aStart - bStart;
  }
  class TreeNode {
    constructor(piece, color) {
      this.piece = piece;
      this.color = color;
      this.size_left = 0;
      this.lf_left = 0;
      this.parent = this;
      this.left = this;
      this.right = this;
    }
    next() {
      if (this.right !== SENTINEL) {
        return leftest(this.right);
      }
      let node = this;
      while (node.parent !== SENTINEL) {
        if (node.parent.left === node) {
          break;
        }
        node = node.parent;
      }
      if (node.parent === SENTINEL) {
        return SENTINEL;
      } else {
        return node.parent;
      }
    }
    prev() {
      if (this.left !== SENTINEL) {
        return righttest(this.left);
      }
      let node = this;
      while (node.parent !== SENTINEL) {
        if (node.parent.right === node) {
          break;
        }
        node = node.parent;
      }
      if (node.parent === SENTINEL) {
        return SENTINEL;
      } else {
        return node.parent;
      }
    }
    detach() {
      this.parent = null;
      this.left = null;
      this.right = null;
    }
  }
  const SENTINEL = new TreeNode(
    null,
    0
    /* NodeColor.Black */
  );
  SENTINEL.parent = SENTINEL;
  SENTINEL.left = SENTINEL;
  SENTINEL.right = SENTINEL;
  SENTINEL.color = 0;
  function leftest(node) {
    while (node.left !== SENTINEL) {
      node = node.left;
    }
    return node;
  }
  function righttest(node) {
    while (node.right !== SENTINEL) {
      node = node.right;
    }
    return node;
  }
  function calculateSize(node) {
    if (node === SENTINEL) {
      return 0;
    }
    return node.size_left + node.piece.length + calculateSize(node.right);
  }
  function calculateLF(node) {
    if (node === SENTINEL) {
      return 0;
    }
    return node.lf_left + node.piece.lineFeedCnt + calculateLF(node.right);
  }
  function resetSentinel() {
    SENTINEL.parent = SENTINEL;
  }
  function leftRotate(tree, x) {
    const y = x.right;
    y.size_left += x.size_left + (x.piece ? x.piece.length : 0);
    y.lf_left += x.lf_left + (x.piece ? x.piece.lineFeedCnt : 0);
    x.right = y.left;
    if (y.left !== SENTINEL) {
      y.left.parent = x;
    }
    y.parent = x.parent;
    if (x.parent === SENTINEL) {
      tree.root = y;
    } else if (x.parent.left === x) {
      x.parent.left = y;
    } else {
      x.parent.right = y;
    }
    y.left = x;
    x.parent = y;
  }
  function rightRotate(tree, y) {
    const x = y.left;
    y.left = x.right;
    if (x.right !== SENTINEL) {
      x.right.parent = y;
    }
    x.parent = y.parent;
    y.size_left -= x.size_left + (x.piece ? x.piece.length : 0);
    y.lf_left -= x.lf_left + (x.piece ? x.piece.lineFeedCnt : 0);
    if (y.parent === SENTINEL) {
      tree.root = x;
    } else if (y === y.parent.right) {
      y.parent.right = x;
    } else {
      y.parent.left = x;
    }
    x.right = y;
    y.parent = x;
  }
  function rbDelete(tree, z) {
    let x;
    let y;
    if (z.left === SENTINEL) {
      y = z;
      x = y.right;
    } else if (z.right === SENTINEL) {
      y = z;
      x = y.left;
    } else {
      y = leftest(z.right);
      x = y.right;
    }
    if (y === tree.root) {
      tree.root = x;
      x.color = 0;
      z.detach();
      resetSentinel();
      tree.root.parent = SENTINEL;
      return;
    }
    const yWasRed = y.color === 1;
    if (y === y.parent.left) {
      y.parent.left = x;
    } else {
      y.parent.right = x;
    }
    if (y === z) {
      x.parent = y.parent;
      recomputeTreeMetadata(tree, x);
    } else {
      if (y.parent === z) {
        x.parent = y;
      } else {
        x.parent = y.parent;
      }
      recomputeTreeMetadata(tree, x);
      y.left = z.left;
      y.right = z.right;
      y.parent = z.parent;
      y.color = z.color;
      if (z === tree.root) {
        tree.root = y;
      } else {
        if (z === z.parent.left) {
          z.parent.left = y;
        } else {
          z.parent.right = y;
        }
      }
      if (y.left !== SENTINEL) {
        y.left.parent = y;
      }
      if (y.right !== SENTINEL) {
        y.right.parent = y;
      }
      y.size_left = z.size_left;
      y.lf_left = z.lf_left;
      recomputeTreeMetadata(tree, y);
    }
    z.detach();
    if (x.parent.left === x) {
      const newSizeLeft = calculateSize(x);
      const newLFLeft = calculateLF(x);
      if (newSizeLeft !== x.parent.size_left || newLFLeft !== x.parent.lf_left) {
        const delta = newSizeLeft - x.parent.size_left;
        const lf_delta = newLFLeft - x.parent.lf_left;
        x.parent.size_left = newSizeLeft;
        x.parent.lf_left = newLFLeft;
        updateTreeMetadata(tree, x.parent, delta, lf_delta);
      }
    }
    recomputeTreeMetadata(tree, x.parent);
    if (yWasRed) {
      resetSentinel();
      return;
    }
    let w;
    while (x !== tree.root && x.color === 0) {
      if (x === x.parent.left) {
        w = x.parent.right;
        if (w.color === 1) {
          w.color = 0;
          x.parent.color = 1;
          leftRotate(tree, x.parent);
          w = x.parent.right;
        }
        if (w.left.color === 0 && w.right.color === 0) {
          w.color = 1;
          x = x.parent;
        } else {
          if (w.right.color === 0) {
            w.left.color = 0;
            w.color = 1;
            rightRotate(tree, w);
            w = x.parent.right;
          }
          w.color = x.parent.color;
          x.parent.color = 0;
          w.right.color = 0;
          leftRotate(tree, x.parent);
          x = tree.root;
        }
      } else {
        w = x.parent.left;
        if (w.color === 1) {
          w.color = 0;
          x.parent.color = 1;
          rightRotate(tree, x.parent);
          w = x.parent.left;
        }
        if (w.left.color === 0 && w.right.color === 0) {
          w.color = 1;
          x = x.parent;
        } else {
          if (w.left.color === 0) {
            w.right.color = 0;
            w.color = 1;
            leftRotate(tree, w);
            w = x.parent.left;
          }
          w.color = x.parent.color;
          x.parent.color = 0;
          w.left.color = 0;
          rightRotate(tree, x.parent);
          x = tree.root;
        }
      }
    }
    x.color = 0;
    resetSentinel();
  }
  function fixInsert(tree, x) {
    recomputeTreeMetadata(tree, x);
    while (x !== tree.root && x.parent.color === 1) {
      if (x.parent === x.parent.parent.left) {
        const y = x.parent.parent.right;
        if (y.color === 1) {
          x.parent.color = 0;
          y.color = 0;
          x.parent.parent.color = 1;
          x = x.parent.parent;
        } else {
          if (x === x.parent.right) {
            x = x.parent;
            leftRotate(tree, x);
          }
          x.parent.color = 0;
          x.parent.parent.color = 1;
          rightRotate(tree, x.parent.parent);
        }
      } else {
        const y = x.parent.parent.left;
        if (y.color === 1) {
          x.parent.color = 0;
          y.color = 0;
          x.parent.parent.color = 1;
          x = x.parent.parent;
        } else {
          if (x === x.parent.left) {
            x = x.parent;
            rightRotate(tree, x);
          }
          x.parent.color = 0;
          x.parent.parent.color = 1;
          leftRotate(tree, x.parent.parent);
        }
      }
    }
    tree.root.color = 0;
  }
  function updateTreeMetadata(tree, x, delta, lineFeedCntDelta) {
    while (x !== tree.root && x !== SENTINEL) {
      if (x.parent.left === x) {
        x.parent.size_left += delta;
        x.parent.lf_left += lineFeedCntDelta;
      }
      x = x.parent;
    }
  }
  function recomputeTreeMetadata(tree, x) {
    let delta = 0;
    let lf_delta = 0;
    if (x === tree.root) {
      return;
    }
    while (x !== tree.root && x === x.parent.right) {
      x = x.parent;
    }
    if (x === tree.root) {
      return;
    }
    x = x.parent;
    delta = calculateSize(x.left) - x.size_left;
    lf_delta = calculateLF(x.left) - x.lf_left;
    x.size_left += delta;
    x.lf_left += lf_delta;
    while (x !== tree.root && (delta !== 0 || lf_delta !== 0)) {
      if (x.parent.left === x) {
        x.parent.size_left += delta;
        x.parent.lf_left += lf_delta;
      }
      x = x.parent;
    }
  }
  const LIMIT_FIND_COUNT$1 = 999;
  class SearchParams {
    constructor(searchString, isRegex, matchCase, wordSeparators2) {
      this.searchString = searchString;
      this.isRegex = isRegex;
      this.matchCase = matchCase;
      this.wordSeparators = wordSeparators2;
    }
    parseSearchRequest() {
      if (this.searchString === "") {
        return null;
      }
      let multiline;
      if (this.isRegex) {
        multiline = isMultilineRegexSource(this.searchString);
      } else {
        multiline = this.searchString.indexOf("\n") >= 0;
      }
      let regex = null;
      try {
        regex = createRegExp(this.searchString, this.isRegex, {
          matchCase: this.matchCase,
          wholeWord: false,
          multiline,
          global: true,
          unicode: true
        });
      } catch (err) {
        return null;
      }
      if (!regex) {
        return null;
      }
      let canUseSimpleSearch = !this.isRegex && !multiline;
      if (canUseSimpleSearch && this.searchString.toLowerCase() !== this.searchString.toUpperCase()) {
        canUseSimpleSearch = this.matchCase;
      }
      return new SearchData(regex, this.wordSeparators ? getMapForWordSeparators(this.wordSeparators, []) : null, canUseSimpleSearch ? this.searchString : null);
    }
  }
  function isMultilineRegexSource(searchString) {
    if (!searchString || searchString.length === 0) {
      return false;
    }
    for (let i2 = 0, len = searchString.length; i2 < len; i2++) {
      const chCode = searchString.charCodeAt(i2);
      if (chCode === 10) {
        return true;
      }
      if (chCode === 92) {
        i2++;
        if (i2 >= len) {
          break;
        }
        const nextChCode = searchString.charCodeAt(i2);
        if (nextChCode === 110 || nextChCode === 114 || nextChCode === 87) {
          return true;
        }
      }
    }
    return false;
  }
  function createFindMatch(range2, rawMatches, captureMatches) {
    if (!captureMatches) {
      return new FindMatch(range2, null);
    }
    const matches = [];
    for (let i2 = 0, len = rawMatches.length; i2 < len; i2++) {
      matches[i2] = rawMatches[i2];
    }
    return new FindMatch(range2, matches);
  }
  class LineFeedCounter {
    constructor(text2) {
      const lineFeedsOffsets = [];
      let lineFeedsOffsetsLen = 0;
      for (let i2 = 0, textLen = text2.length; i2 < textLen; i2++) {
        if (text2.charCodeAt(i2) === 10) {
          lineFeedsOffsets[lineFeedsOffsetsLen++] = i2;
        }
      }
      this._lineFeedsOffsets = lineFeedsOffsets;
    }
    findLineFeedCountBeforeOffset(offset) {
      const lineFeedsOffsets = this._lineFeedsOffsets;
      let min = 0;
      let max = lineFeedsOffsets.length - 1;
      if (max === -1) {
        return 0;
      }
      if (offset <= lineFeedsOffsets[0]) {
        return 0;
      }
      while (min < max) {
        const mid = min + ((max - min) / 2 >> 0);
        if (lineFeedsOffsets[mid] >= offset) {
          max = mid - 1;
        } else {
          if (lineFeedsOffsets[mid + 1] >= offset) {
            min = mid;
            max = mid;
          } else {
            min = mid + 1;
          }
        }
      }
      return min + 1;
    }
  }
  class TextModelSearch {
    static findMatches(model, searchParams, searchRange, captureMatches, limitResultCount) {
      const searchData = searchParams.parseSearchRequest();
      if (!searchData) {
        return [];
      }
      if (searchData.regex.multiline) {
        return this._doFindMatchesMultiline(model, searchRange, new Searcher(searchData.wordSeparators, searchData.regex), captureMatches, limitResultCount);
      }
      return this._doFindMatchesLineByLine(model, searchRange, searchData, captureMatches, limitResultCount);
    }
    /**
     * Multiline search always executes on the lines concatenated with \n.
     * We must therefore compensate for the count of \n in case the model is CRLF
     */
    static _getMultilineMatchRange(model, deltaOffset, text2, lfCounter, matchIndex, match0) {
      let startOffset;
      let lineFeedCountBeforeMatch = 0;
      if (lfCounter) {
        lineFeedCountBeforeMatch = lfCounter.findLineFeedCountBeforeOffset(matchIndex);
        startOffset = deltaOffset + matchIndex + lineFeedCountBeforeMatch;
      } else {
        startOffset = deltaOffset + matchIndex;
      }
      let endOffset;
      if (lfCounter) {
        const lineFeedCountBeforeEndOfMatch = lfCounter.findLineFeedCountBeforeOffset(matchIndex + match0.length);
        const lineFeedCountInMatch = lineFeedCountBeforeEndOfMatch - lineFeedCountBeforeMatch;
        endOffset = startOffset + match0.length + lineFeedCountInMatch;
      } else {
        endOffset = startOffset + match0.length;
      }
      const startPosition = model.getPositionAt(startOffset);
      const endPosition = model.getPositionAt(endOffset);
      return new Range$2(startPosition.lineNumber, startPosition.column, endPosition.lineNumber, endPosition.column);
    }
    static _doFindMatchesMultiline(model, searchRange, searcher, captureMatches, limitResultCount) {
      const deltaOffset = model.getOffsetAt(searchRange.getStartPosition());
      const text2 = model.getValueInRange(
        searchRange,
        1
        /* EndOfLinePreference.LF */
      );
      const lfCounter = model.getEOL() === "\r\n" ? new LineFeedCounter(text2) : null;
      const result = [];
      let counter = 0;
      let m;
      searcher.reset(0);
      while (m = searcher.next(text2)) {
        result[counter++] = createFindMatch(this._getMultilineMatchRange(model, deltaOffset, text2, lfCounter, m.index, m[0]), m, captureMatches);
        if (counter >= limitResultCount) {
          return result;
        }
      }
      return result;
    }
    static _doFindMatchesLineByLine(model, searchRange, searchData, captureMatches, limitResultCount) {
      const result = [];
      let resultLen = 0;
      if (searchRange.startLineNumber === searchRange.endLineNumber) {
        const text3 = model.getLineContent(searchRange.startLineNumber).substring(searchRange.startColumn - 1, searchRange.endColumn - 1);
        resultLen = this._findMatchesInLine(searchData, text3, searchRange.startLineNumber, searchRange.startColumn - 1, resultLen, result, captureMatches, limitResultCount);
        return result;
      }
      const text2 = model.getLineContent(searchRange.startLineNumber).substring(searchRange.startColumn - 1);
      resultLen = this._findMatchesInLine(searchData, text2, searchRange.startLineNumber, searchRange.startColumn - 1, resultLen, result, captureMatches, limitResultCount);
      for (let lineNumber = searchRange.startLineNumber + 1; lineNumber < searchRange.endLineNumber && resultLen < limitResultCount; lineNumber++) {
        resultLen = this._findMatchesInLine(searchData, model.getLineContent(lineNumber), lineNumber, 0, resultLen, result, captureMatches, limitResultCount);
      }
      if (resultLen < limitResultCount) {
        const text3 = model.getLineContent(searchRange.endLineNumber).substring(0, searchRange.endColumn - 1);
        resultLen = this._findMatchesInLine(searchData, text3, searchRange.endLineNumber, 0, resultLen, result, captureMatches, limitResultCount);
      }
      return result;
    }
    static _findMatchesInLine(searchData, text2, lineNumber, deltaOffset, resultLen, result, captureMatches, limitResultCount) {
      const wordSeparators2 = searchData.wordSeparators;
      if (!captureMatches && searchData.simpleSearch) {
        const searchString = searchData.simpleSearch;
        const searchStringLen = searchString.length;
        const textLength = text2.length;
        let lastMatchIndex = -searchStringLen;
        while ((lastMatchIndex = text2.indexOf(searchString, lastMatchIndex + searchStringLen)) !== -1) {
          if (!wordSeparators2 || isValidMatch(wordSeparators2, text2, textLength, lastMatchIndex, searchStringLen)) {
            result[resultLen++] = new FindMatch(new Range$2(lineNumber, lastMatchIndex + 1 + deltaOffset, lineNumber, lastMatchIndex + 1 + searchStringLen + deltaOffset), null);
            if (resultLen >= limitResultCount) {
              return resultLen;
            }
          }
        }
        return resultLen;
      }
      const searcher = new Searcher(searchData.wordSeparators, searchData.regex);
      let m;
      searcher.reset(0);
      do {
        m = searcher.next(text2);
        if (m) {
          result[resultLen++] = createFindMatch(new Range$2(lineNumber, m.index + 1 + deltaOffset, lineNumber, m.index + 1 + m[0].length + deltaOffset), m, captureMatches);
          if (resultLen >= limitResultCount) {
            return resultLen;
          }
        }
      } while (m);
      return resultLen;
    }
    static findNextMatch(model, searchParams, searchStart, captureMatches) {
      const searchData = searchParams.parseSearchRequest();
      if (!searchData) {
        return null;
      }
      const searcher = new Searcher(searchData.wordSeparators, searchData.regex);
      if (searchData.regex.multiline) {
        return this._doFindNextMatchMultiline(model, searchStart, searcher, captureMatches);
      }
      return this._doFindNextMatchLineByLine(model, searchStart, searcher, captureMatches);
    }
    static _doFindNextMatchMultiline(model, searchStart, searcher, captureMatches) {
      const searchTextStart = new Position$1(searchStart.lineNumber, 1);
      const deltaOffset = model.getOffsetAt(searchTextStart);
      const lineCount = model.getLineCount();
      const text2 = model.getValueInRange(
        new Range$2(searchTextStart.lineNumber, searchTextStart.column, lineCount, model.getLineMaxColumn(lineCount)),
        1
        /* EndOfLinePreference.LF */
      );
      const lfCounter = model.getEOL() === "\r\n" ? new LineFeedCounter(text2) : null;
      searcher.reset(searchStart.column - 1);
      const m = searcher.next(text2);
      if (m) {
        return createFindMatch(this._getMultilineMatchRange(model, deltaOffset, text2, lfCounter, m.index, m[0]), m, captureMatches);
      }
      if (searchStart.lineNumber !== 1 || searchStart.column !== 1) {
        return this._doFindNextMatchMultiline(model, new Position$1(1, 1), searcher, captureMatches);
      }
      return null;
    }
    static _doFindNextMatchLineByLine(model, searchStart, searcher, captureMatches) {
      const lineCount = model.getLineCount();
      const startLineNumber = searchStart.lineNumber;
      const text2 = model.getLineContent(startLineNumber);
      const r = this._findFirstMatchInLine(searcher, text2, startLineNumber, searchStart.column, captureMatches);
      if (r) {
        return r;
      }
      for (let i2 = 1; i2 <= lineCount; i2++) {
        const lineIndex = (startLineNumber + i2 - 1) % lineCount;
        const text3 = model.getLineContent(lineIndex + 1);
        const r2 = this._findFirstMatchInLine(searcher, text3, lineIndex + 1, 1, captureMatches);
        if (r2) {
          return r2;
        }
      }
      return null;
    }
    static _findFirstMatchInLine(searcher, text2, lineNumber, fromColumn, captureMatches) {
      searcher.reset(fromColumn - 1);
      const m = searcher.next(text2);
      if (m) {
        return createFindMatch(new Range$2(lineNumber, m.index + 1, lineNumber, m.index + 1 + m[0].length), m, captureMatches);
      }
      return null;
    }
    static findPreviousMatch(model, searchParams, searchStart, captureMatches) {
      const searchData = searchParams.parseSearchRequest();
      if (!searchData) {
        return null;
      }
      const searcher = new Searcher(searchData.wordSeparators, searchData.regex);
      if (searchData.regex.multiline) {
        return this._doFindPreviousMatchMultiline(model, searchStart, searcher, captureMatches);
      }
      return this._doFindPreviousMatchLineByLine(model, searchStart, searcher, captureMatches);
    }
    static _doFindPreviousMatchMultiline(model, searchStart, searcher, captureMatches) {
      const matches = this._doFindMatchesMultiline(model, new Range$2(1, 1, searchStart.lineNumber, searchStart.column), searcher, captureMatches, 10 * LIMIT_FIND_COUNT$1);
      if (matches.length > 0) {
        return matches[matches.length - 1];
      }
      const lineCount = model.getLineCount();
      if (searchStart.lineNumber !== lineCount || searchStart.column !== model.getLineMaxColumn(lineCount)) {
        return this._doFindPreviousMatchMultiline(model, new Position$1(lineCount, model.getLineMaxColumn(lineCount)), searcher, captureMatches);
      }
      return null;
    }
    static _doFindPreviousMatchLineByLine(model, searchStart, searcher, captureMatches) {
      const lineCount = model.getLineCount();
      const startLineNumber = searchStart.lineNumber;
      const text2 = model.getLineContent(startLineNumber).substring(0, searchStart.column - 1);
      const r = this._findLastMatchInLine(searcher, text2, startLineNumber, captureMatches);
      if (r) {
        return r;
      }
      for (let i2 = 1; i2 <= lineCount; i2++) {
        const lineIndex = (lineCount + startLineNumber - i2 - 1) % lineCount;
        const text3 = model.getLineContent(lineIndex + 1);
        const r2 = this._findLastMatchInLine(searcher, text3, lineIndex + 1, captureMatches);
        if (r2) {
          return r2;
        }
      }
      return null;
    }
    static _findLastMatchInLine(searcher, text2, lineNumber, captureMatches) {
      let bestResult = null;
      let m;
      searcher.reset(0);
      while (m = searcher.next(text2)) {
        bestResult = createFindMatch(new Range$2(lineNumber, m.index + 1, lineNumber, m.index + 1 + m[0].length), m, captureMatches);
      }
      return bestResult;
    }
  }
  function leftIsWordBounday(wordSeparators2, text2, textLength, matchStartIndex, matchLength) {
    if (matchStartIndex === 0) {
      return true;
    }
    const charBefore = text2.charCodeAt(matchStartIndex - 1);
    if (wordSeparators2.get(charBefore) !== 0) {
      return true;
    }
    if (charBefore === 13 || charBefore === 10) {
      return true;
    }
    if (matchLength > 0) {
      const firstCharInMatch = text2.charCodeAt(matchStartIndex);
      if (wordSeparators2.get(firstCharInMatch) !== 0) {
        return true;
      }
    }
    return false;
  }
  function rightIsWordBounday(wordSeparators2, text2, textLength, matchStartIndex, matchLength) {
    if (matchStartIndex + matchLength === textLength) {
      return true;
    }
    const charAfter = text2.charCodeAt(matchStartIndex + matchLength);
    if (wordSeparators2.get(charAfter) !== 0) {
      return true;
    }
    if (charAfter === 13 || charAfter === 10) {
      return true;
    }
    if (matchLength > 0) {
      const lastCharInMatch = text2.charCodeAt(matchStartIndex + matchLength - 1);
      if (wordSeparators2.get(lastCharInMatch) !== 0) {
        return true;
      }
    }
    return false;
  }
  function isValidMatch(wordSeparators2, text2, textLength, matchStartIndex, matchLength) {
    return leftIsWordBounday(wordSeparators2, text2, textLength, matchStartIndex, matchLength) && rightIsWordBounday(wordSeparators2, text2, textLength, matchStartIndex, matchLength);
  }
  class Searcher {
    constructor(wordSeparators2, searchRegex) {
      this._wordSeparators = wordSeparators2;
      this._searchRegex = searchRegex;
      this._prevMatchStartIndex = -1;
      this._prevMatchLength = 0;
    }
    reset(lastIndex) {
      this._searchRegex.lastIndex = lastIndex;
      this._prevMatchStartIndex = -1;
      this._prevMatchLength = 0;
    }
    next(text2) {
      const textLength = text2.length;
      let m;
      do {
        if (this._prevMatchStartIndex + this._prevMatchLength === textLength) {
          return null;
        }
        m = this._searchRegex.exec(text2);
        if (!m) {
          return null;
        }
        const matchStartIndex = m.index;
        const matchLength = m[0].length;
        if (matchStartIndex === this._prevMatchStartIndex && matchLength === this._prevMatchLength) {
          if (matchLength === 0) {
            if (getNextCodePoint(text2, textLength, this._searchRegex.lastIndex) > 65535) {
              this._searchRegex.lastIndex += 2;
            } else {
              this._searchRegex.lastIndex += 1;
            }
            continue;
          }
          return null;
        }
        this._prevMatchStartIndex = matchStartIndex;
        this._prevMatchLength = matchLength;
        if (!this._wordSeparators || isValidMatch(this._wordSeparators, text2, textLength, matchStartIndex, matchLength)) {
          return m;
        }
      } while (m);
      return null;
    }
  }
  const AverageBufferSize = 65535;
  function createUintArray(arr) {
    let r;
    if (arr[arr.length - 1] < 65536) {
      r = new Uint16Array(arr.length);
    } else {
      r = new Uint32Array(arr.length);
    }
    r.set(arr, 0);
    return r;
  }
  class LineStarts {
    constructor(lineStarts, cr, lf, crlf, isBasicASCII2) {
      this.lineStarts = lineStarts;
      this.cr = cr;
      this.lf = lf;
      this.crlf = crlf;
      this.isBasicASCII = isBasicASCII2;
    }
  }
  function createLineStartsFast(str, readonly = true) {
    const r = [0];
    let rLength = 1;
    for (let i2 = 0, len = str.length; i2 < len; i2++) {
      const chr = str.charCodeAt(i2);
      if (chr === 13) {
        if (i2 + 1 < len && str.charCodeAt(i2 + 1) === 10) {
          r[rLength++] = i2 + 2;
          i2++;
        } else {
          r[rLength++] = i2 + 1;
        }
      } else if (chr === 10) {
        r[rLength++] = i2 + 1;
      }
    }
    if (readonly) {
      return createUintArray(r);
    } else {
      return r;
    }
  }
  function createLineStarts(r, str) {
    r.length = 0;
    r[0] = 0;
    let rLength = 1;
    let cr = 0, lf = 0, crlf = 0;
    let isBasicASCII2 = true;
    for (let i2 = 0, len = str.length; i2 < len; i2++) {
      const chr = str.charCodeAt(i2);
      if (chr === 13) {
        if (i2 + 1 < len && str.charCodeAt(i2 + 1) === 10) {
          crlf++;
          r[rLength++] = i2 + 2;
          i2++;
        } else {
          cr++;
          r[rLength++] = i2 + 1;
        }
      } else if (chr === 10) {
        lf++;
        r[rLength++] = i2 + 1;
      } else {
        if (isBasicASCII2) {
          if (chr !== 9 && (chr < 32 || chr > 126)) {
            isBasicASCII2 = false;
          }
        }
      }
    }
    const result = new LineStarts(createUintArray(r), cr, lf, crlf, isBasicASCII2);
    r.length = 0;
    return result;
  }
  class Piece {
    constructor(bufferIndex, start, end, lineFeedCnt, length) {
      this.bufferIndex = bufferIndex;
      this.start = start;
      this.end = end;
      this.lineFeedCnt = lineFeedCnt;
      this.length = length;
    }
  }
  class StringBuffer {
    constructor(buffer, lineStarts) {
      this.buffer = buffer;
      this.lineStarts = lineStarts;
    }
  }
  class PieceTreeSnapshot {
    constructor(tree, BOM) {
      this._pieces = [];
      this._tree = tree;
      this._BOM = BOM;
      this._index = 0;
      if (tree.root !== SENTINEL) {
        tree.iterate(tree.root, (node) => {
          if (node !== SENTINEL) {
            this._pieces.push(node.piece);
          }
          return true;
        });
      }
    }
    read() {
      if (this._pieces.length === 0) {
        if (this._index === 0) {
          this._index++;
          return this._BOM;
        } else {
          return null;
        }
      }
      if (this._index > this._pieces.length - 1) {
        return null;
      }
      if (this._index === 0) {
        return this._BOM + this._tree.getPieceContent(this._pieces[this._index++]);
      }
      return this._tree.getPieceContent(this._pieces[this._index++]);
    }
  }
  class PieceTreeSearchCache {
    constructor(limit) {
      this._limit = limit;
      this._cache = [];
    }
    get(offset) {
      for (let i2 = this._cache.length - 1; i2 >= 0; i2--) {
        const nodePos = this._cache[i2];
        if (nodePos.nodeStartOffset <= offset && nodePos.nodeStartOffset + nodePos.node.piece.length >= offset) {
          return nodePos;
        }
      }
      return null;
    }
    get2(lineNumber) {
      for (let i2 = this._cache.length - 1; i2 >= 0; i2--) {
        const nodePos = this._cache[i2];
        if (nodePos.nodeStartLineNumber && nodePos.nodeStartLineNumber < lineNumber && nodePos.nodeStartLineNumber + nodePos.node.piece.lineFeedCnt >= lineNumber) {
          return nodePos;
        }
      }
      return null;
    }
    set(nodePosition) {
      if (this._cache.length >= this._limit) {
        this._cache.shift();
      }
      this._cache.push(nodePosition);
    }
    validate(offset) {
      let hasInvalidVal = false;
      const tmp = this._cache;
      for (let i2 = 0; i2 < tmp.length; i2++) {
        const nodePos = tmp[i2];
        if (nodePos.node.parent === null || nodePos.nodeStartOffset >= offset) {
          tmp[i2] = null;
          hasInvalidVal = true;
          continue;
        }
      }
      if (hasInvalidVal) {
        const newArr = [];
        for (const entry of tmp) {
          if (entry !== null) {
            newArr.push(entry);
          }
        }
        this._cache = newArr;
      }
    }
  }
  class PieceTreeBase {
    constructor(chunks, eol, eolNormalized) {
      this.create(chunks, eol, eolNormalized);
    }
    create(chunks, eol, eolNormalized) {
      this._buffers = [
        new StringBuffer("", [0])
      ];
      this._lastChangeBufferPos = { line: 0, column: 0 };
      this.root = SENTINEL;
      this._lineCnt = 1;
      this._length = 0;
      this._EOL = eol;
      this._EOLLength = eol.length;
      this._EOLNormalized = eolNormalized;
      let lastNode = null;
      for (let i2 = 0, len = chunks.length; i2 < len; i2++) {
        if (chunks[i2].buffer.length > 0) {
          if (!chunks[i2].lineStarts) {
            chunks[i2].lineStarts = createLineStartsFast(chunks[i2].buffer);
          }
          const piece = new Piece(i2 + 1, { line: 0, column: 0 }, { line: chunks[i2].lineStarts.length - 1, column: chunks[i2].buffer.length - chunks[i2].lineStarts[chunks[i2].lineStarts.length - 1] }, chunks[i2].lineStarts.length - 1, chunks[i2].buffer.length);
          this._buffers.push(chunks[i2]);
          lastNode = this.rbInsertRight(lastNode, piece);
        }
      }
      this._searchCache = new PieceTreeSearchCache(1);
      this._lastVisitedLine = { lineNumber: 0, value: "" };
      this.computeBufferMetadata();
    }
    normalizeEOL(eol) {
      const averageBufferSize = AverageBufferSize;
      const min = averageBufferSize - Math.floor(averageBufferSize / 3);
      const max = min * 2;
      let tempChunk = "";
      let tempChunkLen = 0;
      const chunks = [];
      this.iterate(this.root, (node) => {
        const str = this.getNodeContent(node);
        const len = str.length;
        if (tempChunkLen <= min || tempChunkLen + len < max) {
          tempChunk += str;
          tempChunkLen += len;
          return true;
        }
        const text2 = tempChunk.replace(/\r\n|\r|\n/g, eol);
        chunks.push(new StringBuffer(text2, createLineStartsFast(text2)));
        tempChunk = str;
        tempChunkLen = len;
        return true;
      });
      if (tempChunkLen > 0) {
        const text2 = tempChunk.replace(/\r\n|\r|\n/g, eol);
        chunks.push(new StringBuffer(text2, createLineStartsFast(text2)));
      }
      this.create(chunks, eol, true);
    }
    // #region Buffer API
    getEOL() {
      return this._EOL;
    }
    setEOL(newEOL) {
      this._EOL = newEOL;
      this._EOLLength = this._EOL.length;
      this.normalizeEOL(newEOL);
    }
    createSnapshot(BOM) {
      return new PieceTreeSnapshot(this, BOM);
    }
    getOffsetAt(lineNumber, column) {
      let leftLen = 0;
      let x = this.root;
      while (x !== SENTINEL) {
        if (x.left !== SENTINEL && x.lf_left + 1 >= lineNumber) {
          x = x.left;
        } else if (x.lf_left + x.piece.lineFeedCnt + 1 >= lineNumber) {
          leftLen += x.size_left;
          const accumualtedValInCurrentIndex = this.getAccumulatedValue(x, lineNumber - x.lf_left - 2);
          return leftLen += accumualtedValInCurrentIndex + column - 1;
        } else {
          lineNumber -= x.lf_left + x.piece.lineFeedCnt;
          leftLen += x.size_left + x.piece.length;
          x = x.right;
        }
      }
      return leftLen;
    }
    getPositionAt(offset) {
      offset = Math.floor(offset);
      offset = Math.max(0, offset);
      let x = this.root;
      let lfCnt = 0;
      const originalOffset = offset;
      while (x !== SENTINEL) {
        if (x.size_left !== 0 && x.size_left >= offset) {
          x = x.left;
        } else if (x.size_left + x.piece.length >= offset) {
          const out = this.getIndexOf(x, offset - x.size_left);
          lfCnt += x.lf_left + out.index;
          if (out.index === 0) {
            const lineStartOffset = this.getOffsetAt(lfCnt + 1, 1);
            const column = originalOffset - lineStartOffset;
            return new Position$1(lfCnt + 1, column + 1);
          }
          return new Position$1(lfCnt + 1, out.remainder + 1);
        } else {
          offset -= x.size_left + x.piece.length;
          lfCnt += x.lf_left + x.piece.lineFeedCnt;
          if (x.right === SENTINEL) {
            const lineStartOffset = this.getOffsetAt(lfCnt + 1, 1);
            const column = originalOffset - offset - lineStartOffset;
            return new Position$1(lfCnt + 1, column + 1);
          } else {
            x = x.right;
          }
        }
      }
      return new Position$1(1, 1);
    }
    getValueInRange(range2, eol) {
      if (range2.startLineNumber === range2.endLineNumber && range2.startColumn === range2.endColumn) {
        return "";
      }
      const startPosition = this.nodeAt2(range2.startLineNumber, range2.startColumn);
      const endPosition = this.nodeAt2(range2.endLineNumber, range2.endColumn);
      const value = this.getValueInRange2(startPosition, endPosition);
      if (eol) {
        if (eol !== this._EOL || !this._EOLNormalized) {
          return value.replace(/\r\n|\r|\n/g, eol);
        }
        if (eol === this.getEOL() && this._EOLNormalized) {
          return value;
        }
        return value.replace(/\r\n|\r|\n/g, eol);
      }
      return value;
    }
    getValueInRange2(startPosition, endPosition) {
      if (startPosition.node === endPosition.node) {
        const node = startPosition.node;
        const buffer2 = this._buffers[node.piece.bufferIndex].buffer;
        const startOffset2 = this.offsetInBuffer(node.piece.bufferIndex, node.piece.start);
        return buffer2.substring(startOffset2 + startPosition.remainder, startOffset2 + endPosition.remainder);
      }
      let x = startPosition.node;
      const buffer = this._buffers[x.piece.bufferIndex].buffer;
      const startOffset = this.offsetInBuffer(x.piece.bufferIndex, x.piece.start);
      let ret = buffer.substring(startOffset + startPosition.remainder, startOffset + x.piece.length);
      x = x.next();
      while (x !== SENTINEL) {
        const buffer2 = this._buffers[x.piece.bufferIndex].buffer;
        const startOffset2 = this.offsetInBuffer(x.piece.bufferIndex, x.piece.start);
        if (x === endPosition.node) {
          ret += buffer2.substring(startOffset2, startOffset2 + endPosition.remainder);
          break;
        } else {
          ret += buffer2.substr(startOffset2, x.piece.length);
        }
        x = x.next();
      }
      return ret;
    }
    getLinesContent() {
      const lines = [];
      let linesLength = 0;
      let currentLine = "";
      let danglingCR = false;
      this.iterate(this.root, (node) => {
        if (node === SENTINEL) {
          return true;
        }
        const piece = node.piece;
        let pieceLength = piece.length;
        if (pieceLength === 0) {
          return true;
        }
        const buffer = this._buffers[piece.bufferIndex].buffer;
        const lineStarts = this._buffers[piece.bufferIndex].lineStarts;
        const pieceStartLine = piece.start.line;
        const pieceEndLine = piece.end.line;
        let pieceStartOffset = lineStarts[pieceStartLine] + piece.start.column;
        if (danglingCR) {
          if (buffer.charCodeAt(pieceStartOffset) === 10) {
            pieceStartOffset++;
            pieceLength--;
          }
          lines[linesLength++] = currentLine;
          currentLine = "";
          danglingCR = false;
          if (pieceLength === 0) {
            return true;
          }
        }
        if (pieceStartLine === pieceEndLine) {
          if (!this._EOLNormalized && buffer.charCodeAt(pieceStartOffset + pieceLength - 1) === 13) {
            danglingCR = true;
            currentLine += buffer.substr(pieceStartOffset, pieceLength - 1);
          } else {
            currentLine += buffer.substr(pieceStartOffset, pieceLength);
          }
          return true;
        }
        currentLine += this._EOLNormalized ? buffer.substring(pieceStartOffset, Math.max(pieceStartOffset, lineStarts[pieceStartLine + 1] - this._EOLLength)) : buffer.substring(pieceStartOffset, lineStarts[pieceStartLine + 1]).replace(/(\r\n|\r|\n)$/, "");
        lines[linesLength++] = currentLine;
        for (let line = pieceStartLine + 1; line < pieceEndLine; line++) {
          currentLine = this._EOLNormalized ? buffer.substring(lineStarts[line], lineStarts[line + 1] - this._EOLLength) : buffer.substring(lineStarts[line], lineStarts[line + 1]).replace(/(\r\n|\r|\n)$/, "");
          lines[linesLength++] = currentLine;
        }
        if (!this._EOLNormalized && buffer.charCodeAt(lineStarts[pieceEndLine] + piece.end.column - 1) === 13) {
          danglingCR = true;
          if (piece.end.column === 0) {
            linesLength--;
          } else {
            currentLine = buffer.substr(lineStarts[pieceEndLine], piece.end.column - 1);
          }
        } else {
          currentLine = buffer.substr(lineStarts[pieceEndLine], piece.end.column);
        }
        return true;
      });
      if (danglingCR) {
        lines[linesLength++] = currentLine;
        currentLine = "";
      }
      lines[linesLength++] = currentLine;
      return lines;
    }
    getLength() {
      return this._length;
    }
    getLineCount() {
      return this._lineCnt;
    }
    getLineContent(lineNumber) {
      if (this._lastVisitedLine.lineNumber === lineNumber) {
        return this._lastVisitedLine.value;
      }
      this._lastVisitedLine.lineNumber = lineNumber;
      if (lineNumber === this._lineCnt) {
        this._lastVisitedLine.value = this.getLineRawContent(lineNumber);
      } else if (this._EOLNormalized) {
        this._lastVisitedLine.value = this.getLineRawContent(lineNumber, this._EOLLength);
      } else {
        this._lastVisitedLine.value = this.getLineRawContent(lineNumber).replace(/(\r\n|\r|\n)$/, "");
      }
      return this._lastVisitedLine.value;
    }
    _getCharCode(nodePos) {
      if (nodePos.remainder === nodePos.node.piece.length) {
        const matchingNode = nodePos.node.next();
        if (!matchingNode) {
          return 0;
        }
        const buffer = this._buffers[matchingNode.piece.bufferIndex];
        const startOffset = this.offsetInBuffer(matchingNode.piece.bufferIndex, matchingNode.piece.start);
        return buffer.buffer.charCodeAt(startOffset);
      } else {
        const buffer = this._buffers[nodePos.node.piece.bufferIndex];
        const startOffset = this.offsetInBuffer(nodePos.node.piece.bufferIndex, nodePos.node.piece.start);
        const targetOffset = startOffset + nodePos.remainder;
        return buffer.buffer.charCodeAt(targetOffset);
      }
    }
    getLineCharCode(lineNumber, index) {
      const nodePos = this.nodeAt2(lineNumber, index + 1);
      return this._getCharCode(nodePos);
    }
    getLineLength(lineNumber) {
      if (lineNumber === this.getLineCount()) {
        const startOffset = this.getOffsetAt(lineNumber, 1);
        return this.getLength() - startOffset;
      }
      return this.getOffsetAt(lineNumber + 1, 1) - this.getOffsetAt(lineNumber, 1) - this._EOLLength;
    }
    getNearestChunk(offset) {
      const nodePos = this.nodeAt(offset);
      if (nodePos.remainder === nodePos.node.piece.length) {
        const matchingNode = nodePos.node.next();
        if (!matchingNode || matchingNode === SENTINEL) {
          return "";
        }
        const buffer = this._buffers[matchingNode.piece.bufferIndex];
        const startOffset = this.offsetInBuffer(matchingNode.piece.bufferIndex, matchingNode.piece.start);
        return buffer.buffer.substring(startOffset, startOffset + matchingNode.piece.length);
      } else {
        const buffer = this._buffers[nodePos.node.piece.bufferIndex];
        const startOffset = this.offsetInBuffer(nodePos.node.piece.bufferIndex, nodePos.node.piece.start);
        const targetOffset = startOffset + nodePos.remainder;
        const targetEnd = startOffset + nodePos.node.piece.length;
        return buffer.buffer.substring(targetOffset, targetEnd);
      }
    }
    findMatchesInNode(node, searcher, startLineNumber, startColumn, startCursor, endCursor, searchData, captureMatches, limitResultCount, resultLen, result) {
      const buffer = this._buffers[node.piece.bufferIndex];
      const startOffsetInBuffer = this.offsetInBuffer(node.piece.bufferIndex, node.piece.start);
      const start = this.offsetInBuffer(node.piece.bufferIndex, startCursor);
      const end = this.offsetInBuffer(node.piece.bufferIndex, endCursor);
      let m;
      const ret = { line: 0, column: 0 };
      let searchText;
      let offsetInBuffer;
      if (searcher._wordSeparators) {
        searchText = buffer.buffer.substring(start, end);
        offsetInBuffer = (offset) => offset + start;
        searcher.reset(0);
      } else {
        searchText = buffer.buffer;
        offsetInBuffer = (offset) => offset;
        searcher.reset(start);
      }
      do {
        m = searcher.next(searchText);
        if (m) {
          if (offsetInBuffer(m.index) >= end) {
            return resultLen;
          }
          this.positionInBuffer(node, offsetInBuffer(m.index) - startOffsetInBuffer, ret);
          const lineFeedCnt = this.getLineFeedCnt(node.piece.bufferIndex, startCursor, ret);
          const retStartColumn = ret.line === startCursor.line ? ret.column - startCursor.column + startColumn : ret.column + 1;
          const retEndColumn = retStartColumn + m[0].length;
          result[resultLen++] = createFindMatch(new Range$2(startLineNumber + lineFeedCnt, retStartColumn, startLineNumber + lineFeedCnt, retEndColumn), m, captureMatches);
          if (offsetInBuffer(m.index) + m[0].length >= end) {
            return resultLen;
          }
          if (resultLen >= limitResultCount) {
            return resultLen;
          }
        }
      } while (m);
      return resultLen;
    }
    findMatchesLineByLine(searchRange, searchData, captureMatches, limitResultCount) {
      const result = [];
      let resultLen = 0;
      const searcher = new Searcher(searchData.wordSeparators, searchData.regex);
      let startPosition = this.nodeAt2(searchRange.startLineNumber, searchRange.startColumn);
      if (startPosition === null) {
        return [];
      }
      const endPosition = this.nodeAt2(searchRange.endLineNumber, searchRange.endColumn);
      if (endPosition === null) {
        return [];
      }
      let start = this.positionInBuffer(startPosition.node, startPosition.remainder);
      const end = this.positionInBuffer(endPosition.node, endPosition.remainder);
      if (startPosition.node === endPosition.node) {
        this.findMatchesInNode(startPosition.node, searcher, searchRange.startLineNumber, searchRange.startColumn, start, end, searchData, captureMatches, limitResultCount, resultLen, result);
        return result;
      }
      let startLineNumber = searchRange.startLineNumber;
      let currentNode = startPosition.node;
      while (currentNode !== endPosition.node) {
        const lineBreakCnt = this.getLineFeedCnt(currentNode.piece.bufferIndex, start, currentNode.piece.end);
        if (lineBreakCnt >= 1) {
          const lineStarts = this._buffers[currentNode.piece.bufferIndex].lineStarts;
          const startOffsetInBuffer = this.offsetInBuffer(currentNode.piece.bufferIndex, currentNode.piece.start);
          const nextLineStartOffset = lineStarts[start.line + lineBreakCnt];
          const startColumn3 = startLineNumber === searchRange.startLineNumber ? searchRange.startColumn : 1;
          resultLen = this.findMatchesInNode(currentNode, searcher, startLineNumber, startColumn3, start, this.positionInBuffer(currentNode, nextLineStartOffset - startOffsetInBuffer), searchData, captureMatches, limitResultCount, resultLen, result);
          if (resultLen >= limitResultCount) {
            return result;
          }
          startLineNumber += lineBreakCnt;
        }
        const startColumn2 = startLineNumber === searchRange.startLineNumber ? searchRange.startColumn - 1 : 0;
        if (startLineNumber === searchRange.endLineNumber) {
          const text2 = this.getLineContent(startLineNumber).substring(startColumn2, searchRange.endColumn - 1);
          resultLen = this._findMatchesInLine(searchData, searcher, text2, searchRange.endLineNumber, startColumn2, resultLen, result, captureMatches, limitResultCount);
          return result;
        }
        resultLen = this._findMatchesInLine(searchData, searcher, this.getLineContent(startLineNumber).substr(startColumn2), startLineNumber, startColumn2, resultLen, result, captureMatches, limitResultCount);
        if (resultLen >= limitResultCount) {
          return result;
        }
        startLineNumber++;
        startPosition = this.nodeAt2(startLineNumber, 1);
        currentNode = startPosition.node;
        start = this.positionInBuffer(startPosition.node, startPosition.remainder);
      }
      if (startLineNumber === searchRange.endLineNumber) {
        const startColumn2 = startLineNumber === searchRange.startLineNumber ? searchRange.startColumn - 1 : 0;
        const text2 = this.getLineContent(startLineNumber).substring(startColumn2, searchRange.endColumn - 1);
        resultLen = this._findMatchesInLine(searchData, searcher, text2, searchRange.endLineNumber, startColumn2, resultLen, result, captureMatches, limitResultCount);
        return result;
      }
      const startColumn = startLineNumber === searchRange.startLineNumber ? searchRange.startColumn : 1;
      resultLen = this.findMatchesInNode(endPosition.node, searcher, startLineNumber, startColumn, start, end, searchData, captureMatches, limitResultCount, resultLen, result);
      return result;
    }
    _findMatchesInLine(searchData, searcher, text2, lineNumber, deltaOffset, resultLen, result, captureMatches, limitResultCount) {
      const wordSeparators2 = searchData.wordSeparators;
      if (!captureMatches && searchData.simpleSearch) {
        const searchString = searchData.simpleSearch;
        const searchStringLen = searchString.length;
        const textLength = text2.length;
        let lastMatchIndex = -searchStringLen;
        while ((lastMatchIndex = text2.indexOf(searchString, lastMatchIndex + searchStringLen)) !== -1) {
          if (!wordSeparators2 || isValidMatch(wordSeparators2, text2, textLength, lastMatchIndex, searchStringLen)) {
            result[resultLen++] = new FindMatch(new Range$2(lineNumber, lastMatchIndex + 1 + deltaOffset, lineNumber, lastMatchIndex + 1 + searchStringLen + deltaOffset), null);
            if (resultLen >= limitResultCount) {
              return resultLen;
            }
          }
        }
        return resultLen;
      }
      let m;
      searcher.reset(0);
      do {
        m = searcher.next(text2);
        if (m) {
          result[resultLen++] = createFindMatch(new Range$2(lineNumber, m.index + 1 + deltaOffset, lineNumber, m.index + 1 + m[0].length + deltaOffset), m, captureMatches);
          if (resultLen >= limitResultCount) {
            return resultLen;
          }
        }
      } while (m);
      return resultLen;
    }
    // #endregion
    // #region Piece Table
    insert(offset, value, eolNormalized = false) {
      this._EOLNormalized = this._EOLNormalized && eolNormalized;
      this._lastVisitedLine.lineNumber = 0;
      this._lastVisitedLine.value = "";
      if (this.root !== SENTINEL) {
        const { node, remainder, nodeStartOffset } = this.nodeAt(offset);
        const piece = node.piece;
        const bufferIndex = piece.bufferIndex;
        const insertPosInBuffer = this.positionInBuffer(node, remainder);
        if (node.piece.bufferIndex === 0 && piece.end.line === this._lastChangeBufferPos.line && piece.end.column === this._lastChangeBufferPos.column && nodeStartOffset + piece.length === offset && value.length < AverageBufferSize) {
          this.appendToNode(node, value);
          this.computeBufferMetadata();
          return;
        }
        if (nodeStartOffset === offset) {
          this.insertContentToNodeLeft(value, node);
          this._searchCache.validate(offset);
        } else if (nodeStartOffset + node.piece.length > offset) {
          const nodesToDel = [];
          let newRightPiece = new Piece(piece.bufferIndex, insertPosInBuffer, piece.end, this.getLineFeedCnt(piece.bufferIndex, insertPosInBuffer, piece.end), this.offsetInBuffer(bufferIndex, piece.end) - this.offsetInBuffer(bufferIndex, insertPosInBuffer));
          if (this.shouldCheckCRLF() && this.endWithCR(value)) {
            const headOfRight = this.nodeCharCodeAt(node, remainder);
            if (headOfRight === 10) {
              const newStart = { line: newRightPiece.start.line + 1, column: 0 };
              newRightPiece = new Piece(newRightPiece.bufferIndex, newStart, newRightPiece.end, this.getLineFeedCnt(newRightPiece.bufferIndex, newStart, newRightPiece.end), newRightPiece.length - 1);
              value += "\n";
            }
          }
          if (this.shouldCheckCRLF() && this.startWithLF(value)) {
            const tailOfLeft = this.nodeCharCodeAt(node, remainder - 1);
            if (tailOfLeft === 13) {
              const previousPos = this.positionInBuffer(node, remainder - 1);
              this.deleteNodeTail(node, previousPos);
              value = "\r" + value;
              if (node.piece.length === 0) {
                nodesToDel.push(node);
              }
            } else {
              this.deleteNodeTail(node, insertPosInBuffer);
            }
          } else {
            this.deleteNodeTail(node, insertPosInBuffer);
          }
          const newPieces = this.createNewPieces(value);
          if (newRightPiece.length > 0) {
            this.rbInsertRight(node, newRightPiece);
          }
          let tmpNode = node;
          for (let k = 0; k < newPieces.length; k++) {
            tmpNode = this.rbInsertRight(tmpNode, newPieces[k]);
          }
          this.deleteNodes(nodesToDel);
        } else {
          this.insertContentToNodeRight(value, node);
        }
      } else {
        const pieces = this.createNewPieces(value);
        let node = this.rbInsertLeft(null, pieces[0]);
        for (let k = 1; k < pieces.length; k++) {
          node = this.rbInsertRight(node, pieces[k]);
        }
      }
      this.computeBufferMetadata();
    }
    delete(offset, cnt) {
      this._lastVisitedLine.lineNumber = 0;
      this._lastVisitedLine.value = "";
      if (cnt <= 0 || this.root === SENTINEL) {
        return;
      }
      const startPosition = this.nodeAt(offset);
      const endPosition = this.nodeAt(offset + cnt);
      const startNode = startPosition.node;
      const endNode = endPosition.node;
      if (startNode === endNode) {
        const startSplitPosInBuffer2 = this.positionInBuffer(startNode, startPosition.remainder);
        const endSplitPosInBuffer2 = this.positionInBuffer(startNode, endPosition.remainder);
        if (startPosition.nodeStartOffset === offset) {
          if (cnt === startNode.piece.length) {
            const next = startNode.next();
            rbDelete(this, startNode);
            this.validateCRLFWithPrevNode(next);
            this.computeBufferMetadata();
            return;
          }
          this.deleteNodeHead(startNode, endSplitPosInBuffer2);
          this._searchCache.validate(offset);
          this.validateCRLFWithPrevNode(startNode);
          this.computeBufferMetadata();
          return;
        }
        if (startPosition.nodeStartOffset + startNode.piece.length === offset + cnt) {
          this.deleteNodeTail(startNode, startSplitPosInBuffer2);
          this.validateCRLFWithNextNode(startNode);
          this.computeBufferMetadata();
          return;
        }
        this.shrinkNode(startNode, startSplitPosInBuffer2, endSplitPosInBuffer2);
        this.computeBufferMetadata();
        return;
      }
      const nodesToDel = [];
      const startSplitPosInBuffer = this.positionInBuffer(startNode, startPosition.remainder);
      this.deleteNodeTail(startNode, startSplitPosInBuffer);
      this._searchCache.validate(offset);
      if (startNode.piece.length === 0) {
        nodesToDel.push(startNode);
      }
      const endSplitPosInBuffer = this.positionInBuffer(endNode, endPosition.remainder);
      this.deleteNodeHead(endNode, endSplitPosInBuffer);
      if (endNode.piece.length === 0) {
        nodesToDel.push(endNode);
      }
      const secondNode = startNode.next();
      for (let node = secondNode; node !== SENTINEL && node !== endNode; node = node.next()) {
        nodesToDel.push(node);
      }
      const prev = startNode.piece.length === 0 ? startNode.prev() : startNode;
      this.deleteNodes(nodesToDel);
      this.validateCRLFWithNextNode(prev);
      this.computeBufferMetadata();
    }
    insertContentToNodeLeft(value, node) {
      const nodesToDel = [];
      if (this.shouldCheckCRLF() && this.endWithCR(value) && this.startWithLF(node)) {
        const piece = node.piece;
        const newStart = { line: piece.start.line + 1, column: 0 };
        const nPiece = new Piece(piece.bufferIndex, newStart, piece.end, this.getLineFeedCnt(piece.bufferIndex, newStart, piece.end), piece.length - 1);
        node.piece = nPiece;
        value += "\n";
        updateTreeMetadata(this, node, -1, -1);
        if (node.piece.length === 0) {
          nodesToDel.push(node);
        }
      }
      const newPieces = this.createNewPieces(value);
      let newNode = this.rbInsertLeft(node, newPieces[newPieces.length - 1]);
      for (let k = newPieces.length - 2; k >= 0; k--) {
        newNode = this.rbInsertLeft(newNode, newPieces[k]);
      }
      this.validateCRLFWithPrevNode(newNode);
      this.deleteNodes(nodesToDel);
    }
    insertContentToNodeRight(value, node) {
      if (this.adjustCarriageReturnFromNext(value, node)) {
        value += "\n";
      }
      const newPieces = this.createNewPieces(value);
      const newNode = this.rbInsertRight(node, newPieces[0]);
      let tmpNode = newNode;
      for (let k = 1; k < newPieces.length; k++) {
        tmpNode = this.rbInsertRight(tmpNode, newPieces[k]);
      }
      this.validateCRLFWithPrevNode(newNode);
    }
    positionInBuffer(node, remainder, ret) {
      const piece = node.piece;
      const bufferIndex = node.piece.bufferIndex;
      const lineStarts = this._buffers[bufferIndex].lineStarts;
      const startOffset = lineStarts[piece.start.line] + piece.start.column;
      const offset = startOffset + remainder;
      let low = piece.start.line;
      let high = piece.end.line;
      let mid = 0;
      let midStop = 0;
      let midStart = 0;
      while (low <= high) {
        mid = low + (high - low) / 2 | 0;
        midStart = lineStarts[mid];
        if (mid === high) {
          break;
        }
        midStop = lineStarts[mid + 1];
        if (offset < midStart) {
          high = mid - 1;
        } else if (offset >= midStop) {
          low = mid + 1;
        } else {
          break;
        }
      }
      if (ret) {
        ret.line = mid;
        ret.column = offset - midStart;
        return null;
      }
      return {
        line: mid,
        column: offset - midStart
      };
    }
    getLineFeedCnt(bufferIndex, start, end) {
      if (end.column === 0) {
        return end.line - start.line;
      }
      const lineStarts = this._buffers[bufferIndex].lineStarts;
      if (end.line === lineStarts.length - 1) {
        return end.line - start.line;
      }
      const nextLineStartOffset = lineStarts[end.line + 1];
      const endOffset = lineStarts[end.line] + end.column;
      if (nextLineStartOffset > endOffset + 1) {
        return end.line - start.line;
      }
      const previousCharOffset = endOffset - 1;
      const buffer = this._buffers[bufferIndex].buffer;
      if (buffer.charCodeAt(previousCharOffset) === 13) {
        return end.line - start.line + 1;
      } else {
        return end.line - start.line;
      }
    }
    offsetInBuffer(bufferIndex, cursor) {
      const lineStarts = this._buffers[bufferIndex].lineStarts;
      return lineStarts[cursor.line] + cursor.column;
    }
    deleteNodes(nodes) {
      for (let i2 = 0; i2 < nodes.length; i2++) {
        rbDelete(this, nodes[i2]);
      }
    }
    createNewPieces(text2) {
      if (text2.length > AverageBufferSize) {
        const newPieces = [];
        while (text2.length > AverageBufferSize) {
          const lastChar = text2.charCodeAt(AverageBufferSize - 1);
          let splitText;
          if (lastChar === 13 || lastChar >= 55296 && lastChar <= 56319) {
            splitText = text2.substring(0, AverageBufferSize - 1);
            text2 = text2.substring(AverageBufferSize - 1);
          } else {
            splitText = text2.substring(0, AverageBufferSize);
            text2 = text2.substring(AverageBufferSize);
          }
          const lineStarts3 = createLineStartsFast(splitText);
          newPieces.push(new Piece(
            this._buffers.length,
            /* buffer index */
            { line: 0, column: 0 },
            { line: lineStarts3.length - 1, column: splitText.length - lineStarts3[lineStarts3.length - 1] },
            lineStarts3.length - 1,
            splitText.length
          ));
          this._buffers.push(new StringBuffer(splitText, lineStarts3));
        }
        const lineStarts2 = createLineStartsFast(text2);
        newPieces.push(new Piece(
          this._buffers.length,
          /* buffer index */
          { line: 0, column: 0 },
          { line: lineStarts2.length - 1, column: text2.length - lineStarts2[lineStarts2.length - 1] },
          lineStarts2.length - 1,
          text2.length
        ));
        this._buffers.push(new StringBuffer(text2, lineStarts2));
        return newPieces;
      }
      let startOffset = this._buffers[0].buffer.length;
      const lineStarts = createLineStartsFast(text2, false);
      let start = this._lastChangeBufferPos;
      if (this._buffers[0].lineStarts[this._buffers[0].lineStarts.length - 1] === startOffset && startOffset !== 0 && this.startWithLF(text2) && this.endWithCR(this._buffers[0].buffer)) {
        this._lastChangeBufferPos = { line: this._lastChangeBufferPos.line, column: this._lastChangeBufferPos.column + 1 };
        start = this._lastChangeBufferPos;
        for (let i2 = 0; i2 < lineStarts.length; i2++) {
          lineStarts[i2] += startOffset + 1;
        }
        this._buffers[0].lineStarts = this._buffers[0].lineStarts.concat(lineStarts.slice(1));
        this._buffers[0].buffer += "_" + text2;
        startOffset += 1;
      } else {
        if (startOffset !== 0) {
          for (let i2 = 0; i2 < lineStarts.length; i2++) {
            lineStarts[i2] += startOffset;
          }
        }
        this._buffers[0].lineStarts = this._buffers[0].lineStarts.concat(lineStarts.slice(1));
        this._buffers[0].buffer += text2;
      }
      const endOffset = this._buffers[0].buffer.length;
      const endIndex = this._buffers[0].lineStarts.length - 1;
      const endColumn = endOffset - this._buffers[0].lineStarts[endIndex];
      const endPos = { line: endIndex, column: endColumn };
      const newPiece = new Piece(
        0,
        /** todo@peng */
        start,
        endPos,
        this.getLineFeedCnt(0, start, endPos),
        endOffset - startOffset
      );
      this._lastChangeBufferPos = endPos;
      return [newPiece];
    }
    getLineRawContent(lineNumber, endOffset = 0) {
      let x = this.root;
      let ret = "";
      const cache = this._searchCache.get2(lineNumber);
      if (cache) {
        x = cache.node;
        const prevAccumulatedValue = this.getAccumulatedValue(x, lineNumber - cache.nodeStartLineNumber - 1);
        const buffer = this._buffers[x.piece.bufferIndex].buffer;
        const startOffset = this.offsetInBuffer(x.piece.bufferIndex, x.piece.start);
        if (cache.nodeStartLineNumber + x.piece.lineFeedCnt === lineNumber) {
          ret = buffer.substring(startOffset + prevAccumulatedValue, startOffset + x.piece.length);
        } else {
          const accumulatedValue = this.getAccumulatedValue(x, lineNumber - cache.nodeStartLineNumber);
          return buffer.substring(startOffset + prevAccumulatedValue, startOffset + accumulatedValue - endOffset);
        }
      } else {
        let nodeStartOffset = 0;
        const originalLineNumber = lineNumber;
        while (x !== SENTINEL) {
          if (x.left !== SENTINEL && x.lf_left >= lineNumber - 1) {
            x = x.left;
          } else if (x.lf_left + x.piece.lineFeedCnt > lineNumber - 1) {
            const prevAccumulatedValue = this.getAccumulatedValue(x, lineNumber - x.lf_left - 2);
            const accumulatedValue = this.getAccumulatedValue(x, lineNumber - x.lf_left - 1);
            const buffer = this._buffers[x.piece.bufferIndex].buffer;
            const startOffset = this.offsetInBuffer(x.piece.bufferIndex, x.piece.start);
            nodeStartOffset += x.size_left;
            this._searchCache.set({
              node: x,
              nodeStartOffset,
              nodeStartLineNumber: originalLineNumber - (lineNumber - 1 - x.lf_left)
            });
            return buffer.substring(startOffset + prevAccumulatedValue, startOffset + accumulatedValue - endOffset);
          } else if (x.lf_left + x.piece.lineFeedCnt === lineNumber - 1) {
            const prevAccumulatedValue = this.getAccumulatedValue(x, lineNumber - x.lf_left - 2);
            const buffer = this._buffers[x.piece.bufferIndex].buffer;
            const startOffset = this.offsetInBuffer(x.piece.bufferIndex, x.piece.start);
            ret = buffer.substring(startOffset + prevAccumulatedValue, startOffset + x.piece.length);
            break;
          } else {
            lineNumber -= x.lf_left + x.piece.lineFeedCnt;
            nodeStartOffset += x.size_left + x.piece.length;
            x = x.right;
          }
        }
      }
      x = x.next();
      while (x !== SENTINEL) {
        const buffer = this._buffers[x.piece.bufferIndex].buffer;
        if (x.piece.lineFeedCnt > 0) {
          const accumulatedValue = this.getAccumulatedValue(x, 0);
          const startOffset = this.offsetInBuffer(x.piece.bufferIndex, x.piece.start);
          ret += buffer.substring(startOffset, startOffset + accumulatedValue - endOffset);
          return ret;
        } else {
          const startOffset = this.offsetInBuffer(x.piece.bufferIndex, x.piece.start);
          ret += buffer.substr(startOffset, x.piece.length);
        }
        x = x.next();
      }
      return ret;
    }
    computeBufferMetadata() {
      let x = this.root;
      let lfCnt = 1;
      let len = 0;
      while (x !== SENTINEL) {
        lfCnt += x.lf_left + x.piece.lineFeedCnt;
        len += x.size_left + x.piece.length;
        x = x.right;
      }
      this._lineCnt = lfCnt;
      this._length = len;
      this._searchCache.validate(this._length);
    }
    // #region node operations
    getIndexOf(node, accumulatedValue) {
      const piece = node.piece;
      const pos = this.positionInBuffer(node, accumulatedValue);
      const lineCnt = pos.line - piece.start.line;
      if (this.offsetInBuffer(piece.bufferIndex, piece.end) - this.offsetInBuffer(piece.bufferIndex, piece.start) === accumulatedValue) {
        const realLineCnt = this.getLineFeedCnt(node.piece.bufferIndex, piece.start, pos);
        if (realLineCnt !== lineCnt) {
          return { index: realLineCnt, remainder: 0 };
        }
      }
      return { index: lineCnt, remainder: pos.column };
    }
    getAccumulatedValue(node, index) {
      if (index < 0) {
        return 0;
      }
      const piece = node.piece;
      const lineStarts = this._buffers[piece.bufferIndex].lineStarts;
      const expectedLineStartIndex = piece.start.line + index + 1;
      if (expectedLineStartIndex > piece.end.line) {
        return lineStarts[piece.end.line] + piece.end.column - lineStarts[piece.start.line] - piece.start.column;
      } else {
        return lineStarts[expectedLineStartIndex] - lineStarts[piece.start.line] - piece.start.column;
      }
    }
    deleteNodeTail(node, pos) {
      const piece = node.piece;
      const originalLFCnt = piece.lineFeedCnt;
      const originalEndOffset = this.offsetInBuffer(piece.bufferIndex, piece.end);
      const newEnd = pos;
      const newEndOffset = this.offsetInBuffer(piece.bufferIndex, newEnd);
      const newLineFeedCnt = this.getLineFeedCnt(piece.bufferIndex, piece.start, newEnd);
      const lf_delta = newLineFeedCnt - originalLFCnt;
      const size_delta = newEndOffset - originalEndOffset;
      const newLength = piece.length + size_delta;
      node.piece = new Piece(piece.bufferIndex, piece.start, newEnd, newLineFeedCnt, newLength);
      updateTreeMetadata(this, node, size_delta, lf_delta);
    }
    deleteNodeHead(node, pos) {
      const piece = node.piece;
      const originalLFCnt = piece.lineFeedCnt;
      const originalStartOffset = this.offsetInBuffer(piece.bufferIndex, piece.start);
      const newStart = pos;
      const newLineFeedCnt = this.getLineFeedCnt(piece.bufferIndex, newStart, piece.end);
      const newStartOffset = this.offsetInBuffer(piece.bufferIndex, newStart);
      const lf_delta = newLineFeedCnt - originalLFCnt;
      const size_delta = originalStartOffset - newStartOffset;
      const newLength = piece.length + size_delta;
      node.piece = new Piece(piece.bufferIndex, newStart, piece.end, newLineFeedCnt, newLength);
      updateTreeMetadata(this, node, size_delta, lf_delta);
    }
    shrinkNode(node, start, end) {
      const piece = node.piece;
      const originalStartPos = piece.start;
      const originalEndPos = piece.end;
      const oldLength = piece.length;
      const oldLFCnt = piece.lineFeedCnt;
      const newEnd = start;
      const newLineFeedCnt = this.getLineFeedCnt(piece.bufferIndex, piece.start, newEnd);
      const newLength = this.offsetInBuffer(piece.bufferIndex, start) - this.offsetInBuffer(piece.bufferIndex, originalStartPos);
      node.piece = new Piece(piece.bufferIndex, piece.start, newEnd, newLineFeedCnt, newLength);
      updateTreeMetadata(this, node, newLength - oldLength, newLineFeedCnt - oldLFCnt);
      const newPiece = new Piece(piece.bufferIndex, end, originalEndPos, this.getLineFeedCnt(piece.bufferIndex, end, originalEndPos), this.offsetInBuffer(piece.bufferIndex, originalEndPos) - this.offsetInBuffer(piece.bufferIndex, end));
      const newNode = this.rbInsertRight(node, newPiece);
      this.validateCRLFWithPrevNode(newNode);
    }
    appendToNode(node, value) {
      if (this.adjustCarriageReturnFromNext(value, node)) {
        value += "\n";
      }
      const hitCRLF = this.shouldCheckCRLF() && this.startWithLF(value) && this.endWithCR(node);
      const startOffset = this._buffers[0].buffer.length;
      this._buffers[0].buffer += value;
      const lineStarts = createLineStartsFast(value, false);
      for (let i2 = 0; i2 < lineStarts.length; i2++) {
        lineStarts[i2] += startOffset;
      }
      if (hitCRLF) {
        const prevStartOffset = this._buffers[0].lineStarts[this._buffers[0].lineStarts.length - 2];
        this._buffers[0].lineStarts.pop();
        this._lastChangeBufferPos = { line: this._lastChangeBufferPos.line - 1, column: startOffset - prevStartOffset };
      }
      this._buffers[0].lineStarts = this._buffers[0].lineStarts.concat(lineStarts.slice(1));
      const endIndex = this._buffers[0].lineStarts.length - 1;
      const endColumn = this._buffers[0].buffer.length - this._buffers[0].lineStarts[endIndex];
      const newEnd = { line: endIndex, column: endColumn };
      const newLength = node.piece.length + value.length;
      const oldLineFeedCnt = node.piece.lineFeedCnt;
      const newLineFeedCnt = this.getLineFeedCnt(0, node.piece.start, newEnd);
      const lf_delta = newLineFeedCnt - oldLineFeedCnt;
      node.piece = new Piece(node.piece.bufferIndex, node.piece.start, newEnd, newLineFeedCnt, newLength);
      this._lastChangeBufferPos = newEnd;
      updateTreeMetadata(this, node, value.length, lf_delta);
    }
    nodeAt(offset) {
      let x = this.root;
      const cache = this._searchCache.get(offset);
      if (cache) {
        return {
          node: cache.node,
          nodeStartOffset: cache.nodeStartOffset,
          remainder: offset - cache.nodeStartOffset
        };
      }
      let nodeStartOffset = 0;
      while (x !== SENTINEL) {
        if (x.size_left > offset) {
          x = x.left;
        } else if (x.size_left + x.piece.length >= offset) {
          nodeStartOffset += x.size_left;
          const ret = {
            node: x,
            remainder: offset - x.size_left,
            nodeStartOffset
          };
          this._searchCache.set(ret);
          return ret;
        } else {
          offset -= x.size_left + x.piece.length;
          nodeStartOffset += x.size_left + x.piece.length;
          x = x.right;
        }
      }
      return null;
    }
    nodeAt2(lineNumber, column) {
      let x = this.root;
      let nodeStartOffset = 0;
      while (x !== SENTINEL) {
        if (x.left !== SENTINEL && x.lf_left >= lineNumber - 1) {
          x = x.left;
        } else if (x.lf_left + x.piece.lineFeedCnt > lineNumber - 1) {
          const prevAccumualtedValue = this.getAccumulatedValue(x, lineNumber - x.lf_left - 2);
          const accumulatedValue = this.getAccumulatedValue(x, lineNumber - x.lf_left - 1);
          nodeStartOffset += x.size_left;
          return {
            node: x,
            remainder: Math.min(prevAccumualtedValue + column - 1, accumulatedValue),
            nodeStartOffset
          };
        } else if (x.lf_left + x.piece.lineFeedCnt === lineNumber - 1) {
          const prevAccumualtedValue = this.getAccumulatedValue(x, lineNumber - x.lf_left - 2);
          if (prevAccumualtedValue + column - 1 <= x.piece.length) {
            return {
              node: x,
              remainder: prevAccumualtedValue + column - 1,
              nodeStartOffset
            };
          } else {
            column -= x.piece.length - prevAccumualtedValue;
            break;
          }
        } else {
          lineNumber -= x.lf_left + x.piece.lineFeedCnt;
          nodeStartOffset += x.size_left + x.piece.length;
          x = x.right;
        }
      }
      x = x.next();
      while (x !== SENTINEL) {
        if (x.piece.lineFeedCnt > 0) {
          const accumulatedValue = this.getAccumulatedValue(x, 0);
          const nodeStartOffset2 = this.offsetOfNode(x);
          return {
            node: x,
            remainder: Math.min(column - 1, accumulatedValue),
            nodeStartOffset: nodeStartOffset2
          };
        } else {
          if (x.piece.length >= column - 1) {
            const nodeStartOffset2 = this.offsetOfNode(x);
            return {
              node: x,
              remainder: column - 1,
              nodeStartOffset: nodeStartOffset2
            };
          } else {
            column -= x.piece.length;
          }
        }
        x = x.next();
      }
      return null;
    }
    nodeCharCodeAt(node, offset) {
      if (node.piece.lineFeedCnt < 1) {
        return -1;
      }
      const buffer = this._buffers[node.piece.bufferIndex];
      const newOffset = this.offsetInBuffer(node.piece.bufferIndex, node.piece.start) + offset;
      return buffer.buffer.charCodeAt(newOffset);
    }
    offsetOfNode(node) {
      if (!node) {
        return 0;
      }
      let pos = node.size_left;
      while (node !== this.root) {
        if (node.parent.right === node) {
          pos += node.parent.size_left + node.parent.piece.length;
        }
        node = node.parent;
      }
      return pos;
    }
    // #endregion
    // #region CRLF
    shouldCheckCRLF() {
      return !(this._EOLNormalized && this._EOL === "\n");
    }
    startWithLF(val) {
      if (typeof val === "string") {
        return val.charCodeAt(0) === 10;
      }
      if (val === SENTINEL || val.piece.lineFeedCnt === 0) {
        return false;
      }
      const piece = val.piece;
      const lineStarts = this._buffers[piece.bufferIndex].lineStarts;
      const line = piece.start.line;
      const startOffset = lineStarts[line] + piece.start.column;
      if (line === lineStarts.length - 1) {
        return false;
      }
      const nextLineOffset = lineStarts[line + 1];
      if (nextLineOffset > startOffset + 1) {
        return false;
      }
      return this._buffers[piece.bufferIndex].buffer.charCodeAt(startOffset) === 10;
    }
    endWithCR(val) {
      if (typeof val === "string") {
        return val.charCodeAt(val.length - 1) === 13;
      }
      if (val === SENTINEL || val.piece.lineFeedCnt === 0) {
        return false;
      }
      return this.nodeCharCodeAt(val, val.piece.length - 1) === 13;
    }
    validateCRLFWithPrevNode(nextNode) {
      if (this.shouldCheckCRLF() && this.startWithLF(nextNode)) {
        const node = nextNode.prev();
        if (this.endWithCR(node)) {
          this.fixCRLF(node, nextNode);
        }
      }
    }
    validateCRLFWithNextNode(node) {
      if (this.shouldCheckCRLF() && this.endWithCR(node)) {
        const nextNode = node.next();
        if (this.startWithLF(nextNode)) {
          this.fixCRLF(node, nextNode);
        }
      }
    }
    fixCRLF(prev, next) {
      const nodesToDel = [];
      const lineStarts = this._buffers[prev.piece.bufferIndex].lineStarts;
      let newEnd;
      if (prev.piece.end.column === 0) {
        newEnd = { line: prev.piece.end.line - 1, column: lineStarts[prev.piece.end.line] - lineStarts[prev.piece.end.line - 1] - 1 };
      } else {
        newEnd = { line: prev.piece.end.line, column: prev.piece.end.column - 1 };
      }
      const prevNewLength = prev.piece.length - 1;
      const prevNewLFCnt = prev.piece.lineFeedCnt - 1;
      prev.piece = new Piece(prev.piece.bufferIndex, prev.piece.start, newEnd, prevNewLFCnt, prevNewLength);
      updateTreeMetadata(this, prev, -1, -1);
      if (prev.piece.length === 0) {
        nodesToDel.push(prev);
      }
      const newStart = { line: next.piece.start.line + 1, column: 0 };
      const newLength = next.piece.length - 1;
      const newLineFeedCnt = this.getLineFeedCnt(next.piece.bufferIndex, newStart, next.piece.end);
      next.piece = new Piece(next.piece.bufferIndex, newStart, next.piece.end, newLineFeedCnt, newLength);
      updateTreeMetadata(this, next, -1, -1);
      if (next.piece.length === 0) {
        nodesToDel.push(next);
      }
      const pieces = this.createNewPieces("\r\n");
      this.rbInsertRight(prev, pieces[0]);
      for (let i2 = 0; i2 < nodesToDel.length; i2++) {
        rbDelete(this, nodesToDel[i2]);
      }
    }
    adjustCarriageReturnFromNext(value, node) {
      if (this.shouldCheckCRLF() && this.endWithCR(value)) {
        const nextNode = node.next();
        if (this.startWithLF(nextNode)) {
          value += "\n";
          if (nextNode.piece.length === 1) {
            rbDelete(this, nextNode);
          } else {
            const piece = nextNode.piece;
            const newStart = { line: piece.start.line + 1, column: 0 };
            const newLength = piece.length - 1;
            const newLineFeedCnt = this.getLineFeedCnt(piece.bufferIndex, newStart, piece.end);
            nextNode.piece = new Piece(piece.bufferIndex, newStart, piece.end, newLineFeedCnt, newLength);
            updateTreeMetadata(this, nextNode, -1, -1);
          }
          return true;
        }
      }
      return false;
    }
    // #endregion
    // #endregion
    // #region Tree operations
    iterate(node, callback) {
      if (node === SENTINEL) {
        return callback(SENTINEL);
      }
      const leftRet = this.iterate(node.left, callback);
      if (!leftRet) {
        return leftRet;
      }
      return callback(node) && this.iterate(node.right, callback);
    }
    getNodeContent(node) {
      if (node === SENTINEL) {
        return "";
      }
      const buffer = this._buffers[node.piece.bufferIndex];
      const piece = node.piece;
      const startOffset = this.offsetInBuffer(piece.bufferIndex, piece.start);
      const endOffset = this.offsetInBuffer(piece.bufferIndex, piece.end);
      const currentContent = buffer.buffer.substring(startOffset, endOffset);
      return currentContent;
    }
    getPieceContent(piece) {
      const buffer = this._buffers[piece.bufferIndex];
      const startOffset = this.offsetInBuffer(piece.bufferIndex, piece.start);
      const endOffset = this.offsetInBuffer(piece.bufferIndex, piece.end);
      const currentContent = buffer.buffer.substring(startOffset, endOffset);
      return currentContent;
    }
    /**
     *      node              node
     *     /  \              /  \
     *    a   b    <----   a    b
     *                         /
     *                        z
     */
    rbInsertRight(node, p) {
      const z = new TreeNode(
        p,
        1
        /* NodeColor.Red */
      );
      z.left = SENTINEL;
      z.right = SENTINEL;
      z.parent = SENTINEL;
      z.size_left = 0;
      z.lf_left = 0;
      const x = this.root;
      if (x === SENTINEL) {
        this.root = z;
        z.color = 0;
      } else if (node.right === SENTINEL) {
        node.right = z;
        z.parent = node;
      } else {
        const nextNode = leftest(node.right);
        nextNode.left = z;
        z.parent = nextNode;
      }
      fixInsert(this, z);
      return z;
    }
    /**
     *      node              node
     *     /  \              /  \
     *    a   b     ---->   a    b
     *                       \
     *                        z
     */
    rbInsertLeft(node, p) {
      const z = new TreeNode(
        p,
        1
        /* NodeColor.Red */
      );
      z.left = SENTINEL;
      z.right = SENTINEL;
      z.parent = SENTINEL;
      z.size_left = 0;
      z.lf_left = 0;
      if (this.root === SENTINEL) {
        this.root = z;
        z.color = 0;
      } else if (node.left === SENTINEL) {
        node.left = z;
        z.parent = node;
      } else {
        const prevNode = righttest(node.left);
        prevNode.right = z;
        z.parent = prevNode;
      }
      fixInsert(this, z);
      return z;
    }
  }
  class PieceTreeTextBuffer extends Disposable {
    constructor(chunks, BOM, eol, containsRTL2, containsUnusualLineTerminators2, isBasicASCII2, eolNormalized) {
      super();
      this._onDidChangeContent = this._register(new Emitter$1());
      this._BOM = BOM;
      this._mightContainNonBasicASCII = !isBasicASCII2;
      this._mightContainRTL = containsRTL2;
      this._mightContainUnusualLineTerminators = containsUnusualLineTerminators2;
      this._pieceTree = new PieceTreeBase(chunks, eol, eolNormalized);
    }
    mightContainRTL() {
      return this._mightContainRTL;
    }
    mightContainUnusualLineTerminators() {
      return this._mightContainUnusualLineTerminators;
    }
    resetMightContainUnusualLineTerminators() {
      this._mightContainUnusualLineTerminators = false;
    }
    mightContainNonBasicASCII() {
      return this._mightContainNonBasicASCII;
    }
    getBOM() {
      return this._BOM;
    }
    getEOL() {
      return this._pieceTree.getEOL();
    }
    createSnapshot(preserveBOM) {
      return this._pieceTree.createSnapshot(preserveBOM ? this._BOM : "");
    }
    getOffsetAt(lineNumber, column) {
      return this._pieceTree.getOffsetAt(lineNumber, column);
    }
    getPositionAt(offset) {
      return this._pieceTree.getPositionAt(offset);
    }
    getRangeAt(start, length) {
      const end = start + length;
      const startPosition = this.getPositionAt(start);
      const endPosition = this.getPositionAt(end);
      return new Range$2(startPosition.lineNumber, startPosition.column, endPosition.lineNumber, endPosition.column);
    }
    getValueInRange(range2, eol = 0) {
      if (range2.isEmpty()) {
        return "";
      }
      const lineEnding = this._getEndOfLine(eol);
      return this._pieceTree.getValueInRange(range2, lineEnding);
    }
    getValueLengthInRange(range2, eol = 0) {
      if (range2.isEmpty()) {
        return 0;
      }
      if (range2.startLineNumber === range2.endLineNumber) {
        return range2.endColumn - range2.startColumn;
      }
      const startOffset = this.getOffsetAt(range2.startLineNumber, range2.startColumn);
      const endOffset = this.getOffsetAt(range2.endLineNumber, range2.endColumn);
      let eolOffsetCompensation = 0;
      const desiredEOL = this._getEndOfLine(eol);
      const actualEOL = this.getEOL();
      if (desiredEOL.length !== actualEOL.length) {
        const delta = desiredEOL.length - actualEOL.length;
        const eolCount = range2.endLineNumber - range2.startLineNumber;
        eolOffsetCompensation = delta * eolCount;
      }
      return endOffset - startOffset + eolOffsetCompensation;
    }
    getCharacterCountInRange(range2, eol = 0) {
      if (this._mightContainNonBasicASCII) {
        let result = 0;
        const fromLineNumber = range2.startLineNumber;
        const toLineNumber = range2.endLineNumber;
        for (let lineNumber = fromLineNumber; lineNumber <= toLineNumber; lineNumber++) {
          const lineContent = this.getLineContent(lineNumber);
          const fromOffset = lineNumber === fromLineNumber ? range2.startColumn - 1 : 0;
          const toOffset = lineNumber === toLineNumber ? range2.endColumn - 1 : lineContent.length;
          for (let offset = fromOffset; offset < toOffset; offset++) {
            if (isHighSurrogate(lineContent.charCodeAt(offset))) {
              result = result + 1;
              offset = offset + 1;
            } else {
              result = result + 1;
            }
          }
        }
        result += this._getEndOfLine(eol).length * (toLineNumber - fromLineNumber);
        return result;
      }
      return this.getValueLengthInRange(range2, eol);
    }
    getNearestChunk(offset) {
      return this._pieceTree.getNearestChunk(offset);
    }
    getLength() {
      return this._pieceTree.getLength();
    }
    getLineCount() {
      return this._pieceTree.getLineCount();
    }
    getLinesContent() {
      return this._pieceTree.getLinesContent();
    }
    getLineContent(lineNumber) {
      return this._pieceTree.getLineContent(lineNumber);
    }
    getLineCharCode(lineNumber, index) {
      return this._pieceTree.getLineCharCode(lineNumber, index);
    }
    getLineLength(lineNumber) {
      return this._pieceTree.getLineLength(lineNumber);
    }
    getLineFirstNonWhitespaceColumn(lineNumber) {
      const result = firstNonWhitespaceIndex(this.getLineContent(lineNumber));
      if (result === -1) {
        return 0;
      }
      return result + 1;
    }
    getLineLastNonWhitespaceColumn(lineNumber) {
      const result = lastNonWhitespaceIndex(this.getLineContent(lineNumber));
      if (result === -1) {
        return 0;
      }
      return result + 2;
    }
    _getEndOfLine(eol) {
      switch (eol) {
        case 1:
          return "\n";
        case 2:
          return "\r\n";
        case 0:
          return this.getEOL();
        default:
          throw new Error("Unknown EOL preference");
      }
    }
    setEOL(newEOL) {
      this._pieceTree.setEOL(newEOL);
    }
    applyEdits(rawOperations, recordTrimAutoWhitespace, computeUndoEdits) {
      let mightContainRTL = this._mightContainRTL;
      let mightContainUnusualLineTerminators = this._mightContainUnusualLineTerminators;
      let mightContainNonBasicASCII = this._mightContainNonBasicASCII;
      let canReduceOperations = true;
      let operations = [];
      for (let i2 = 0; i2 < rawOperations.length; i2++) {
        const op = rawOperations[i2];
        if (canReduceOperations && op._isTracked) {
          canReduceOperations = false;
        }
        const validatedRange = op.range;
        if (op.text) {
          let textMightContainNonBasicASCII = true;
          if (!mightContainNonBasicASCII) {
            textMightContainNonBasicASCII = !isBasicASCII(op.text);
            mightContainNonBasicASCII = textMightContainNonBasicASCII;
          }
          if (!mightContainRTL && textMightContainNonBasicASCII) {
            mightContainRTL = containsRTL(op.text);
          }
          if (!mightContainUnusualLineTerminators && textMightContainNonBasicASCII) {
            mightContainUnusualLineTerminators = containsUnusualLineTerminators(op.text);
          }
        }
        let validText = "";
        let eolCount = 0;
        let firstLineLength = 0;
        let lastLineLength = 0;
        if (op.text) {
          let strEOL;
          [eolCount, firstLineLength, lastLineLength, strEOL] = countEOL(op.text);
          const bufferEOL = this.getEOL();
          const expectedStrEOL = bufferEOL === "\r\n" ? 2 : 1;
          if (strEOL === 0 || strEOL === expectedStrEOL) {
            validText = op.text;
          } else {
            validText = op.text.replace(/\r\n|\r|\n/g, bufferEOL);
          }
        }
        operations[i2] = {
          sortIndex: i2,
          identifier: op.identifier || null,
          range: validatedRange,
          rangeOffset: this.getOffsetAt(validatedRange.startLineNumber, validatedRange.startColumn),
          rangeLength: this.getValueLengthInRange(validatedRange),
          text: validText,
          eolCount,
          firstLineLength,
          lastLineLength,
          forceMoveMarkers: Boolean(op.forceMoveMarkers),
          isAutoWhitespaceEdit: op.isAutoWhitespaceEdit || false
        };
      }
      operations.sort(PieceTreeTextBuffer._sortOpsAscending);
      let hasTouchingRanges = false;
      for (let i2 = 0, count = operations.length - 1; i2 < count; i2++) {
        const rangeEnd = operations[i2].range.getEndPosition();
        const nextRangeStart = operations[i2 + 1].range.getStartPosition();
        if (nextRangeStart.isBeforeOrEqual(rangeEnd)) {
          if (nextRangeStart.isBefore(rangeEnd)) {
            throw new Error("Overlapping ranges are not allowed!");
          }
          hasTouchingRanges = true;
        }
      }
      if (canReduceOperations) {
        operations = this._reduceOperations(operations);
      }
      const reverseRanges = computeUndoEdits || recordTrimAutoWhitespace ? PieceTreeTextBuffer._getInverseEditRanges(operations) : [];
      const newTrimAutoWhitespaceCandidates = [];
      if (recordTrimAutoWhitespace) {
        for (let i2 = 0; i2 < operations.length; i2++) {
          const op = operations[i2];
          const reverseRange = reverseRanges[i2];
          if (op.isAutoWhitespaceEdit && op.range.isEmpty()) {
            for (let lineNumber = reverseRange.startLineNumber; lineNumber <= reverseRange.endLineNumber; lineNumber++) {
              let currentLineContent = "";
              if (lineNumber === reverseRange.startLineNumber) {
                currentLineContent = this.getLineContent(op.range.startLineNumber);
                if (firstNonWhitespaceIndex(currentLineContent) !== -1) {
                  continue;
                }
              }
              newTrimAutoWhitespaceCandidates.push({ lineNumber, oldContent: currentLineContent });
            }
          }
        }
      }
      let reverseOperations = null;
      if (computeUndoEdits) {
        let reverseRangeDeltaOffset = 0;
        reverseOperations = [];
        for (let i2 = 0; i2 < operations.length; i2++) {
          const op = operations[i2];
          const reverseRange = reverseRanges[i2];
          const bufferText = this.getValueInRange(op.range);
          const reverseRangeOffset = op.rangeOffset + reverseRangeDeltaOffset;
          reverseRangeDeltaOffset += op.text.length - bufferText.length;
          reverseOperations[i2] = {
            sortIndex: op.sortIndex,
            identifier: op.identifier,
            range: reverseRange,
            text: bufferText,
            textChange: new TextChange(op.rangeOffset, bufferText, reverseRangeOffset, op.text)
          };
        }
        if (!hasTouchingRanges) {
          reverseOperations.sort((a, b) => a.sortIndex - b.sortIndex);
        }
      }
      this._mightContainRTL = mightContainRTL;
      this._mightContainUnusualLineTerminators = mightContainUnusualLineTerminators;
      this._mightContainNonBasicASCII = mightContainNonBasicASCII;
      const contentChanges = this._doApplyEdits(operations);
      let trimAutoWhitespaceLineNumbers = null;
      if (recordTrimAutoWhitespace && newTrimAutoWhitespaceCandidates.length > 0) {
        newTrimAutoWhitespaceCandidates.sort((a, b) => b.lineNumber - a.lineNumber);
        trimAutoWhitespaceLineNumbers = [];
        for (let i2 = 0, len = newTrimAutoWhitespaceCandidates.length; i2 < len; i2++) {
          const lineNumber = newTrimAutoWhitespaceCandidates[i2].lineNumber;
          if (i2 > 0 && newTrimAutoWhitespaceCandidates[i2 - 1].lineNumber === lineNumber) {
            continue;
          }
          const prevContent = newTrimAutoWhitespaceCandidates[i2].oldContent;
          const lineContent = this.getLineContent(lineNumber);
          if (lineContent.length === 0 || lineContent === prevContent || firstNonWhitespaceIndex(lineContent) !== -1) {
            continue;
          }
          trimAutoWhitespaceLineNumbers.push(lineNumber);
        }
      }
      this._onDidChangeContent.fire();
      return new ApplyEditsResult(reverseOperations, contentChanges, trimAutoWhitespaceLineNumbers);
    }
    /**
     * Transform operations such that they represent the same logic edit,
     * but that they also do not cause OOM crashes.
     */
    _reduceOperations(operations) {
      if (operations.length < 1e3) {
        return operations;
      }
      return [this._toSingleEditOperation(operations)];
    }
    _toSingleEditOperation(operations) {
      let forceMoveMarkers = false;
      const firstEditRange = operations[0].range;
      const lastEditRange = operations[operations.length - 1].range;
      const entireEditRange = new Range$2(firstEditRange.startLineNumber, firstEditRange.startColumn, lastEditRange.endLineNumber, lastEditRange.endColumn);
      let lastEndLineNumber = firstEditRange.startLineNumber;
      let lastEndColumn = firstEditRange.startColumn;
      const result = [];
      for (let i2 = 0, len = operations.length; i2 < len; i2++) {
        const operation = operations[i2];
        const range2 = operation.range;
        forceMoveMarkers = forceMoveMarkers || operation.forceMoveMarkers;
        result.push(this.getValueInRange(new Range$2(lastEndLineNumber, lastEndColumn, range2.startLineNumber, range2.startColumn)));
        if (operation.text.length > 0) {
          result.push(operation.text);
        }
        lastEndLineNumber = range2.endLineNumber;
        lastEndColumn = range2.endColumn;
      }
      const text2 = result.join("");
      const [eolCount, firstLineLength, lastLineLength] = countEOL(text2);
      return {
        sortIndex: 0,
        identifier: operations[0].identifier,
        range: entireEditRange,
        rangeOffset: this.getOffsetAt(entireEditRange.startLineNumber, entireEditRange.startColumn),
        rangeLength: this.getValueLengthInRange(
          entireEditRange,
          0
          /* EndOfLinePreference.TextDefined */
        ),
        text: text2,
        eolCount,
        firstLineLength,
        lastLineLength,
        forceMoveMarkers,
        isAutoWhitespaceEdit: false
      };
    }
    _doApplyEdits(operations) {
      operations.sort(PieceTreeTextBuffer._sortOpsDescending);
      const contentChanges = [];
      for (let i2 = 0; i2 < operations.length; i2++) {
        const op = operations[i2];
        const startLineNumber = op.range.startLineNumber;
        const startColumn = op.range.startColumn;
        const endLineNumber = op.range.endLineNumber;
        const endColumn = op.range.endColumn;
        if (startLineNumber === endLineNumber && startColumn === endColumn && op.text.length === 0) {
          continue;
        }
        if (op.text) {
          this._pieceTree.delete(op.rangeOffset, op.rangeLength);
          this._pieceTree.insert(op.rangeOffset, op.text, true);
        } else {
          this._pieceTree.delete(op.rangeOffset, op.rangeLength);
        }
        const contentChangeRange = new Range$2(startLineNumber, startColumn, endLineNumber, endColumn);
        contentChanges.push({
          range: contentChangeRange,
          rangeLength: op.rangeLength,
          text: op.text,
          rangeOffset: op.rangeOffset,
          forceMoveMarkers: op.forceMoveMarkers
        });
      }
      return contentChanges;
    }
    findMatchesLineByLine(searchRange, searchData, captureMatches, limitResultCount) {
      return this._pieceTree.findMatchesLineByLine(searchRange, searchData, captureMatches, limitResultCount);
    }
    /**
     * Assumes `operations` are validated and sorted ascending
     */
    static _getInverseEditRanges(operations) {
      const result = [];
      let prevOpEndLineNumber = 0;
      let prevOpEndColumn = 0;
      let prevOp = null;
      for (let i2 = 0, len = operations.length; i2 < len; i2++) {
        const op = operations[i2];
        let startLineNumber;
        let startColumn;
        if (prevOp) {
          if (prevOp.range.endLineNumber === op.range.startLineNumber) {
            startLineNumber = prevOpEndLineNumber;
            startColumn = prevOpEndColumn + (op.range.startColumn - prevOp.range.endColumn);
          } else {
            startLineNumber = prevOpEndLineNumber + (op.range.startLineNumber - prevOp.range.endLineNumber);
            startColumn = op.range.startColumn;
          }
        } else {
          startLineNumber = op.range.startLineNumber;
          startColumn = op.range.startColumn;
        }
        let resultRange;
        if (op.text.length > 0) {
          const lineCount = op.eolCount + 1;
          if (lineCount === 1) {
            resultRange = new Range$2(startLineNumber, startColumn, startLineNumber, startColumn + op.firstLineLength);
          } else {
            resultRange = new Range$2(startLineNumber, startColumn, startLineNumber + lineCount - 1, op.lastLineLength + 1);
          }
        } else {
          resultRange = new Range$2(startLineNumber, startColumn, startLineNumber, startColumn);
        }
        prevOpEndLineNumber = resultRange.endLineNumber;
        prevOpEndColumn = resultRange.endColumn;
        result.push(resultRange);
        prevOp = op;
      }
      return result;
    }
    static _sortOpsAscending(a, b) {
      const r = Range$2.compareRangesUsingEnds(a.range, b.range);
      if (r === 0) {
        return a.sortIndex - b.sortIndex;
      }
      return r;
    }
    static _sortOpsDescending(a, b) {
      const r = Range$2.compareRangesUsingEnds(a.range, b.range);
      if (r === 0) {
        return b.sortIndex - a.sortIndex;
      }
      return -r;
    }
  }
  class PieceTreeTextBufferFactory {
    constructor(_chunks, _bom, _cr, _lf, _crlf, _containsRTL, _containsUnusualLineTerminators, _isBasicASCII, _normalizeEOL) {
      this._chunks = _chunks;
      this._bom = _bom;
      this._cr = _cr;
      this._lf = _lf;
      this._crlf = _crlf;
      this._containsRTL = _containsRTL;
      this._containsUnusualLineTerminators = _containsUnusualLineTerminators;
      this._isBasicASCII = _isBasicASCII;
      this._normalizeEOL = _normalizeEOL;
    }
    _getEOL(defaultEOL) {
      const totalEOLCount = this._cr + this._lf + this._crlf;
      const totalCRCount = this._cr + this._crlf;
      if (totalEOLCount === 0) {
        return defaultEOL === 1 ? "\n" : "\r\n";
      }
      if (totalCRCount > totalEOLCount / 2) {
        return "\r\n";
      }
      return "\n";
    }
    create(defaultEOL) {
      const eol = this._getEOL(defaultEOL);
      const chunks = this._chunks;
      if (this._normalizeEOL && (eol === "\r\n" && (this._cr > 0 || this._lf > 0) || eol === "\n" && (this._cr > 0 || this._crlf > 0))) {
        for (let i2 = 0, len = chunks.length; i2 < len; i2++) {
          const str = chunks[i2].buffer.replace(/\r\n|\r|\n/g, eol);
          const newLineStart = createLineStartsFast(str);
          chunks[i2] = new StringBuffer(str, newLineStart);
        }
      }
      const textBuffer = new PieceTreeTextBuffer(chunks, this._bom, eol, this._containsRTL, this._containsUnusualLineTerminators, this._isBasicASCII, this._normalizeEOL);
      return { textBuffer, disposable: textBuffer };
    }
  }
  class PieceTreeTextBufferBuilder {
    constructor() {
      this.chunks = [];
      this.BOM = "";
      this._hasPreviousChar = false;
      this._previousChar = 0;
      this._tmpLineStarts = [];
      this.cr = 0;
      this.lf = 0;
      this.crlf = 0;
      this.containsRTL = false;
      this.containsUnusualLineTerminators = false;
      this.isBasicASCII = true;
    }
    acceptChunk(chunk) {
      if (chunk.length === 0) {
        return;
      }
      if (this.chunks.length === 0) {
        if (startsWithUTF8BOM(chunk)) {
          this.BOM = UTF8_BOM_CHARACTER;
          chunk = chunk.substr(1);
        }
      }
      const lastChar = chunk.charCodeAt(chunk.length - 1);
      if (lastChar === 13 || lastChar >= 55296 && lastChar <= 56319) {
        this._acceptChunk1(chunk.substr(0, chunk.length - 1), false);
        this._hasPreviousChar = true;
        this._previousChar = lastChar;
      } else {
        this._acceptChunk1(chunk, false);
        this._hasPreviousChar = false;
        this._previousChar = lastChar;
      }
    }
    _acceptChunk1(chunk, allowEmptyStrings) {
      if (!allowEmptyStrings && chunk.length === 0) {
        return;
      }
      if (this._hasPreviousChar) {
        this._acceptChunk2(String.fromCharCode(this._previousChar) + chunk);
      } else {
        this._acceptChunk2(chunk);
      }
    }
    _acceptChunk2(chunk) {
      const lineStarts = createLineStarts(this._tmpLineStarts, chunk);
      this.chunks.push(new StringBuffer(chunk, lineStarts.lineStarts));
      this.cr += lineStarts.cr;
      this.lf += lineStarts.lf;
      this.crlf += lineStarts.crlf;
      if (!lineStarts.isBasicASCII) {
        this.isBasicASCII = false;
        if (!this.containsRTL) {
          this.containsRTL = containsRTL(chunk);
        }
        if (!this.containsUnusualLineTerminators) {
          this.containsUnusualLineTerminators = containsUnusualLineTerminators(chunk);
        }
      }
    }
    finish(normalizeEOL = true) {
      this._finish();
      return new PieceTreeTextBufferFactory(this.chunks, this.BOM, this.cr, this.lf, this.crlf, this.containsRTL, this.containsUnusualLineTerminators, this.isBasicASCII, normalizeEOL);
    }
    _finish() {
      if (this.chunks.length === 0) {
        this._acceptChunk1("", true);
      }
      if (this._hasPreviousChar) {
        this._hasPreviousChar = false;
        const lastChunk = this.chunks[this.chunks.length - 1];
        lastChunk.buffer += String.fromCharCode(this._previousChar);
        const newLineStarts = createLineStartsFast(lastChunk.buffer);
        lastChunk.lineStarts = newLineStarts;
        if (this._previousChar === 13) {
          this.cr++;
        }
      }
    }
  }
  class AttachedViews {
    constructor() {
      this._onDidChangeVisibleRanges = new Emitter$1();
      this.onDidChangeVisibleRanges = this._onDidChangeVisibleRanges.event;
      this._views = /* @__PURE__ */ new Set();
      this._viewsChanged = observableSignal(this);
      this.visibleLineRanges = derivedOpts({
        owner: this,
        equalsFn: itemsEquals(itemEquals())
      }, (reader) => {
        this._viewsChanged.read(reader);
        const ranges = LineRange.joinMany([...this._views].map((view) => view.state.read(reader)?.visibleLineRanges ?? []));
        return ranges;
      });
    }
    attachView() {
      const view = new AttachedViewImpl((state) => {
        this._onDidChangeVisibleRanges.fire({ view, state });
      });
      this._views.add(view);
      this._viewsChanged.trigger(void 0);
      return view;
    }
    detachView(view) {
      this._views.delete(view);
      this._onDidChangeVisibleRanges.fire({ view, state: void 0 });
      this._viewsChanged.trigger(void 0);
    }
  }
  class AttachedViewState {
    constructor(visibleLineRanges, stabilized) {
      this.visibleLineRanges = visibleLineRanges;
      this.stabilized = stabilized;
    }
    equals(other) {
      if (this === other) {
        return true;
      }
      if (!equals$1(this.visibleLineRanges, other.visibleLineRanges, (a, b) => a.equals(b))) {
        return false;
      }
      if (this.stabilized !== other.stabilized) {
        return false;
      }
      return true;
    }
  }
  class AttachedViewImpl {
    get state() {
      return this._state;
    }
    constructor(handleStateChange) {
      this.handleStateChange = handleStateChange;
      this._state = observableValueOpts({ owner: this, equalsFn: equalsIfDefined((a, b) => a.equals(b)) }, void 0);
    }
    setVisibleLines(visibleLines, stabilized) {
      const visibleLineRanges = visibleLines.map((line) => new LineRange(line.startLineNumber, line.endLineNumber + 1));
      const state = new AttachedViewState(visibleLineRanges, stabilized);
      this._state.set(state, void 0, void 0);
      this.handleStateChange(state);
    }
  }
  class AttachedViewHandler extends Disposable {
    get lineRanges() {
      return this._lineRanges;
    }
    constructor(_refreshTokens) {
      super();
      this._refreshTokens = _refreshTokens;
      this.runner = this._register(new RunOnceScheduler(() => this.update(), 50));
      this._computedLineRanges = [];
      this._lineRanges = [];
    }
    update() {
      if (equals$1(this._computedLineRanges, this._lineRanges, (a, b) => a.equals(b))) {
        return;
      }
      this._computedLineRanges = this._lineRanges;
      this._refreshTokens();
    }
    handleStateChange(state) {
      this._lineRanges = state.visibleLineRanges;
      if (state.stabilized) {
        this.runner.cancel();
        this.update();
      } else {
        this.runner.schedule();
      }
    }
  }
  class AbstractSyntaxTokenBackend extends Disposable {
    get backgroundTokenizationState() {
      return this._backgroundTokenizationState;
    }
    constructor(_languageIdCodec, _textModel) {
      super();
      this._languageIdCodec = _languageIdCodec;
      this._textModel = _textModel;
      this._onDidChangeTokens = this._register(new Emitter$1());
      this.onDidChangeTokens = this._onDidChangeTokens.event;
    }
    tokenizeIfCheap(lineNumber) {
      if (this.isCheapToTokenize(lineNumber)) {
        this.forceTokenization(lineNumber);
      }
    }
  }
  function gotoNextSibling(newCursor, oldCursor) {
    const n2 = newCursor.gotoNextSibling();
    const o = oldCursor.gotoNextSibling();
    if (n2 !== o) {
      throw new Error("Trees are out of sync");
    }
    return n2 && o;
  }
  function gotoParent(newCursor, oldCursor) {
    const n2 = newCursor.gotoParent();
    const o = oldCursor.gotoParent();
    if (n2 !== o) {
      throw new Error("Trees are out of sync");
    }
    return n2 && o;
  }
  function gotoNthChild(newCursor, oldCursor, index) {
    const n2 = newCursor.gotoFirstChild();
    const o = oldCursor.gotoFirstChild();
    if (n2 !== o) {
      throw new Error("Trees are out of sync");
    }
    if (index === 0) {
      return n2 && o;
    }
    for (let i2 = 1; i2 <= index; i2++) {
      const nn = newCursor.gotoNextSibling();
      const oo = oldCursor.gotoNextSibling();
      if (nn !== oo) {
        throw new Error("Trees are out of sync");
      }
      if (!nn || !oo) {
        return false;
      }
    }
    return n2 && o;
  }
  function nextSiblingOrParentSibling(newCursor, oldCursor) {
    do {
      if (newCursor.currentNode.nextSibling) {
        return gotoNextSibling(newCursor, oldCursor);
      }
      if (newCursor.currentNode.parent) {
        gotoParent(newCursor, oldCursor);
      }
    } while (newCursor.currentNode.nextSibling || newCursor.currentNode.parent);
    return false;
  }
  function getClosestPreviousNodes(cursor, tree) {
    const findPrev = tree.walk();
    findPrev.resetTo(cursor);
    const startingNode = cursor.currentNode;
    do {
      if (findPrev.currentNode.previousSibling && findPrev.currentNode.endIndex - findPrev.currentNode.startIndex !== 0) {
        findPrev.gotoPreviousSibling();
      } else {
        while (!findPrev.currentNode.previousSibling && findPrev.currentNode.parent) {
          findPrev.gotoParent();
        }
        findPrev.gotoPreviousSibling();
      }
    } while (findPrev.currentNode.endIndex > startingNode.startIndex && (findPrev.currentNode.parent || findPrev.currentNode.previousSibling) && findPrev.currentNode.id !== startingNode.id);
    if (findPrev.currentNode.id !== startingNode.id && findPrev.currentNode.endIndex <= startingNode.startIndex) {
      return findPrev.currentNode;
    } else {
      return void 0;
    }
  }
  var __decorate$2P = 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$2K = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  let TreeSitterTree = class TreeSitterTree extends Disposable {
    constructor(languageId, _ranges, _parser, _parserClass, textModel, _logService, _telemetryService) {
      super();
      this.languageId = languageId;
      this._ranges = _ranges;
      this._parser = _parser;
      this._parserClass = _parserClass;
      this.textModel = textModel;
      this._logService = _logService;
      this._telemetryService = _telemetryService;
      this._tree = observableValue(this, void 0);
      this.tree = this._tree;
      this._treeLastParsedVersion = observableValue(this, -1);
      this.treeLastParsedVersion = this._treeLastParsedVersion;
      this._onDidChangeContentQueue = new TaskQueue$1();
      this._tree = observableValue(this, void 0);
      this.tree = this._tree;
      this._register(toDisposable(() => {
        this._tree.get()?.delete();
        this._lastFullyParsed?.delete();
        this._lastFullyParsedWithEdits?.delete();
        this._parser.delete();
      }));
      this.handleContentChange(void 0, this._ranges);
    }
    handleContentChange(e, ranges) {
      const version = this.textModel.getVersionId();
      let newRanges = [];
      if (ranges) {
        newRanges = this._setRanges(ranges);
      }
      if (e) {
        this._applyEdits(e.changes);
      }
      this._onDidChangeContentQueue.clearPending();
      this._onDidChangeContentQueue.schedule(async () => {
        if (this._store.isDisposed) {
          return;
        }
        const oldTree = this._lastFullyParsed;
        let changedNodes;
        if (this._lastFullyParsedWithEdits && this._lastFullyParsed) {
          changedNodes = this._findChangedNodes(this._lastFullyParsedWithEdits, this._lastFullyParsed);
        }
        const completed = await this._parseAndUpdateTree(version);
        if (completed) {
          let ranges2;
          if (!changedNodes) {
            if (this._ranges) {
              ranges2 = this._ranges.map((r) => ({ newRange: new Range$2(r.startPosition.row + 1, r.startPosition.column + 1, r.endPosition.row + 1, r.endPosition.column + 1), oldRangeLength: r.endIndex - r.startIndex, newRangeStartOffset: r.startIndex, newRangeEndOffset: r.endIndex }));
            }
          } else if (oldTree && changedNodes) {
            ranges2 = this._findTreeChanges(completed, changedNodes, newRanges);
          }
          if (!ranges2) {
            ranges2 = [{ newRange: this.textModel.getFullModelRange(), newRangeStartOffset: 0, newRangeEndOffset: this.textModel.getValueLength() }];
          }
          const previousTree = this._tree.get();
          transaction((tx) => {
            this._tree.set(completed, tx, { ranges: ranges2, versionId: version });
            this._treeLastParsedVersion.set(version, tx);
          });
          previousTree?.delete();
        }
      });
    }
    _applyEdits(changes) {
      for (const change of changes) {
        const originalTextLength = TextLength.ofRange(Range$2.lift(change.range));
        const newTextLength = TextLength.ofText(change.text);
        const summedTextLengths = change.text.length === 0 ? newTextLength : originalTextLength.add(newTextLength);
        const edit2 = {
          startIndex: change.rangeOffset,
          oldEndIndex: change.rangeOffset + change.rangeLength,
          newEndIndex: change.rangeOffset + change.text.length,
          startPosition: { row: change.range.startLineNumber - 1, column: change.range.startColumn - 1 },
          oldEndPosition: { row: change.range.endLineNumber - 1, column: change.range.endColumn - 1 },
          newEndPosition: { row: change.range.startLineNumber + summedTextLengths.lineCount - 1, column: summedTextLengths.lineCount ? summedTextLengths.columnCount : change.range.endColumn + summedTextLengths.columnCount }
        };
        this._tree.get()?.edit(edit2);
        this._lastFullyParsedWithEdits?.edit(edit2);
      }
    }
    _findChangedNodes(newTree, oldTree) {
      if (this._ranges && this._ranges.every((range2) => range2.startPosition.row !== newTree.rootNode.startPosition.row) || newTree.rootNode.startPosition.row !== 0) {
        return [];
      }
      const newCursor = newTree.walk();
      const oldCursor = oldTree.walk();
      const nodes = [];
      let next = true;
      do {
        if (newCursor.currentNode.hasChanges) {
          const newChildren = newCursor.currentNode.children;
          const indexChangedChildren = [];
          const changedChildren = newChildren.filter((c, index) => {
            if (c?.hasChanges || oldCursor.currentNode.children.length <= index) {
              indexChangedChildren.push(index);
              return true;
            }
            return false;
          });
          if (changedChildren.length === 0 || newCursor.currentNode.hasError !== oldCursor.currentNode.hasError) {
            while (newCursor.currentNode.parent && next && !newCursor.currentNode.isNamed) {
              next = gotoParent(newCursor, oldCursor);
            }
            const newNode = newCursor.currentNode;
            const closestPreviousNode = getClosestPreviousNodes(newCursor, newTree) ?? newNode;
            nodes.push({
              startIndex: closestPreviousNode.startIndex,
              endIndex: newNode.endIndex,
              startPosition: closestPreviousNode.startPosition,
              endPosition: newNode.endPosition
            });
            next = nextSiblingOrParentSibling(newCursor, oldCursor);
          } else if (changedChildren.length >= 1) {
            next = gotoNthChild(newCursor, oldCursor, indexChangedChildren[0]);
          }
        } else {
          next = nextSiblingOrParentSibling(newCursor, oldCursor);
        }
      } while (next);
      newCursor.delete();
      oldCursor.delete();
      return nodes;
    }
    _findTreeChanges(newTree, changedNodes, newRanges) {
      let newRangeIndex = 0;
      const mergedChanges = [];
      for (let nodeIndex = 0; nodeIndex < changedNodes.length; nodeIndex++) {
        const node = changedNodes[nodeIndex];
        if (mergedChanges.length > 0) {
          if (node.startIndex >= mergedChanges[mergedChanges.length - 1].newRangeStartOffset && node.endIndex <= mergedChanges[mergedChanges.length - 1].newRangeEndOffset) {
            continue;
          }
        }
        const cursor = newTree.walk();
        const cursorContainersNode = () => cursor.startIndex < node.startIndex && cursor.endIndex > node.endIndex;
        while (cursorContainersNode()) {
          let child = cursor.gotoFirstChild();
          let foundChild = false;
          while (child) {
            if (cursorContainersNode() && cursor.currentNode.isNamed) {
              foundChild = true;
              break;
            } else {
              child = cursor.gotoNextSibling();
            }
          }
          if (!foundChild) {
            cursor.gotoParent();
            break;
          }
          if (cursor.currentNode.childCount === 0) {
            break;
          }
        }
        const startPosition = cursor.currentNode.startPosition;
        const endPosition = cursor.currentNode.endPosition;
        const startIndex = cursor.currentNode.startIndex;
        const endIndex = cursor.currentNode.endIndex;
        const newChange = { newRange: new Range$2(startPosition.row + 1, startPosition.column + 1, endPosition.row + 1, endPosition.column + 1), newRangeStartOffset: startIndex, newRangeEndOffset: endIndex };
        if (newRangeIndex < newRanges.length && rangesIntersect(newRanges[newRangeIndex], { startIndex, endIndex })) {
          if (newRanges[newRangeIndex].startIndex < newChange.newRangeStartOffset) {
            newChange.newRange = newChange.newRange.setStartPosition(newRanges[newRangeIndex].startPosition.row + 1, newRanges[newRangeIndex].startPosition.column + 1);
            newChange.newRangeStartOffset = newRanges[newRangeIndex].startIndex;
          }
          if (newRanges[newRangeIndex].endIndex > newChange.newRangeEndOffset) {
            newChange.newRange = newChange.newRange.setEndPosition(newRanges[newRangeIndex].endPosition.row + 1, newRanges[newRangeIndex].endPosition.column + 1);
            newChange.newRangeEndOffset = newRanges[newRangeIndex].endIndex;
          }
          newRangeIndex++;
        } else if (newRangeIndex < newRanges.length && newRanges[newRangeIndex].endIndex < newChange.newRangeStartOffset) {
          mergedChanges.push({
            newRange: new Range$2(newRanges[newRangeIndex].startPosition.row + 1, newRanges[newRangeIndex].startPosition.column + 1, newRanges[newRangeIndex].endPosition.row + 1, newRanges[newRangeIndex].endPosition.column + 1),
            newRangeStartOffset: newRanges[newRangeIndex].startIndex,
            newRangeEndOffset: newRanges[newRangeIndex].endIndex
          });
        }
        if (mergedChanges.length > 0 && mergedChanges[mergedChanges.length - 1].newRangeEndOffset >= newChange.newRangeStartOffset) {
          mergedChanges[mergedChanges.length - 1].newRange = Range$2.fromPositions(mergedChanges[mergedChanges.length - 1].newRange.getStartPosition(), newChange.newRange.getEndPosition());
          mergedChanges[mergedChanges.length - 1].newRangeEndOffset = newChange.newRangeEndOffset;
        } else {
          mergedChanges.push(newChange);
        }
      }
      return this._constrainRanges(mergedChanges);
    }
    _constrainRanges(changes) {
      if (!this._ranges) {
        return changes;
      }
      const constrainedChanges = [];
      let changesIndex = 0;
      let rangesIndex = 0;
      while (changesIndex < changes.length && rangesIndex < this._ranges.length) {
        const change = changes[changesIndex];
        const range2 = this._ranges[rangesIndex];
        if (change.newRangeEndOffset < range2.startIndex) {
          changesIndex++;
        } else if (change.newRangeStartOffset > range2.endIndex) {
          rangesIndex++;
        } else {
          const newRangeStartOffset = Math.max(change.newRangeStartOffset, range2.startIndex);
          const newRangeEndOffset = Math.min(change.newRangeEndOffset, range2.endIndex);
          const newRange = change.newRange.intersectRanges(new Range$2(range2.startPosition.row + 1, range2.startPosition.column + 1, range2.endPosition.row + 1, range2.endPosition.column + 1));
          constrainedChanges.push({
            newRange,
            newRangeEndOffset,
            newRangeStartOffset
          });
          if (newRangeEndOffset < change.newRangeEndOffset) {
            change.newRange = Range$2.fromPositions(newRange.getEndPosition(), change.newRange.getEndPosition());
            change.newRangeStartOffset = newRangeEndOffset + 1;
          } else {
            changesIndex++;
          }
        }
      }
      return constrainedChanges;
    }
    async _parseAndUpdateTree(version) {
      const tree = await this._parse();
      if (tree) {
        this._lastFullyParsed?.delete();
        this._lastFullyParsed = tree.copy();
        this._lastFullyParsedWithEdits?.delete();
        this._lastFullyParsedWithEdits = tree.copy();
        return tree;
      } else if (!this._tree.get()) {
        this._parser.reset();
      }
      return void 0;
    }
    _parse() {
      let parseType = "fullParse";
      if (this._tree.get()) {
        parseType = "incrementalParse";
      }
      return this._parseAndYield(parseType);
    }
    async _parseAndYield(parseType) {
      let time = 0;
      let passes = 0;
      const inProgressVersion = this.textModel.getVersionId();
      let newTree;
      const progressCallback = newTimeOutProgressCallback();
      do {
        const timer = performance.now();
        newTree = this._parser.parse((index, position) => this._parseCallback(index), this._tree.get(), { progressCallback, includedRanges: this._ranges });
        time += performance.now() - timer;
        passes++;
        await new Promise((resolve2) => setTimeout0(resolve2));
      } while (!this._store.isDisposed && !newTree && inProgressVersion === this.textModel.getVersionId());
      this._sendParseTimeTelemetry(parseType, time, passes);
      return newTree && inProgressVersion === this.textModel.getVersionId() ? newTree : void 0;
    }
    _parseCallback(index) {
      try {
        return this.textModel.getTextBuffer().getNearestChunk(index);
      } catch (e) {
        this._logService.debug("Error getting chunk for tree-sitter parsing", e);
      }
      return void 0;
    }
    _setRanges(newRanges) {
      const unKnownRanges = [];
      if (this._ranges) {
        for (const newRange of newRanges) {
          let isFullyIncluded = false;
          for (let i2 = 0; i2 < this._ranges.length; i2++) {
            const existingRange = this._ranges[i2];
            if (rangesEqual(existingRange, newRange) || rangesIntersect(existingRange, newRange)) {
              isFullyIncluded = true;
              break;
            }
          }
          if (!isFullyIncluded) {
            unKnownRanges.push(newRange);
          }
        }
      } else {
        unKnownRanges.push(...newRanges);
      }
      this._ranges = newRanges;
      return unKnownRanges;
    }
    _sendParseTimeTelemetry(parseType, time, passes) {
      this._logService.debug(`Tree parsing (${parseType}) took ${time} ms and ${passes} passes.`);
      if (parseType === "fullParse") {
        this._telemetryService.publicLog2(`treeSitter.fullParse`, { languageId: this.languageId, time, passes });
      } else {
        this._telemetryService.publicLog2(`treeSitter.incrementalParse`, { languageId: this.languageId, time, passes });
      }
    }
    createParsedTreeSync(src) {
      const parser = new this._parserClass();
      parser.setLanguage(this._parser.language);
      const tree = parser.parse(src);
      parser.delete();
      return tree ?? void 0;
    }
  };
  TreeSitterTree = __decorate$2P([
    __param$2K(5, ILogService),
    __param$2K(6, ITelemetryService)
  ], TreeSitterTree);
  function newTimeOutProgressCallback() {
    let lastYieldTime = performance.now();
    return function parseProgressCallback(_state) {
      const now = performance.now();
      if (now - lastYieldTime > 50) {
        lastYieldTime = now;
        return true;
      }
      return false;
    };
  }
  function rangesEqual(a, b) {
    return a.startPosition.row === b.startPosition.row && a.startPosition.column === b.startPosition.column && a.endPosition.row === b.endPosition.row && a.endPosition.column === b.endPosition.column && a.startIndex === b.startIndex && a.endIndex === b.endIndex;
  }
  function rangesIntersect(a, b) {
    return a.startIndex <= b.startIndex && a.endIndex >= b.startIndex || b.startIndex <= a.startIndex && b.endIndex >= a.startIndex;
  }
  const NullState = new class {
    clone() {
      return this;
    }
    equals(other) {
      return this === other;
    }
  }();
  function nullTokenize(languageId, state) {
    return new TokenizationResult([new Token$2(0, "", languageId)], state);
  }
  function nullTokenizeEncoded(languageId, state) {
    const tokens = new Uint32Array(2);
    tokens[0] = 0;
    tokens[1] = (languageId << 0 | 0 << 8 | 0 << 11 | 1 << 15 | 2 << 24) >>> 0;
    return new EncodedTokenizationResult(tokens, state === null ? NullState : state);
  }
  class FixedArray {
    constructor(_default) {
      this._default = _default;
      this._store = [];
    }
    get(index) {
      if (index < this._store.length) {
        return this._store[index];
      }
      return this._default;
    }
    set(index, value) {
      while (index >= this._store.length) {
        this._store[this._store.length] = this._default;
      }
      this._store[index] = value;
    }
    replace(index, oldLength, newLength) {
      if (index >= this._store.length) {
        return;
      }
      if (oldLength === 0) {
        this.insert(index, newLength);
        return;
      } else if (newLength === 0) {
        this.delete(index, oldLength);
        return;
      }
      const before = this._store.slice(0, index);
      const after2 = this._store.slice(index + oldLength);
      const insertArr = arrayFill(newLength, this._default);
      this._store = before.concat(insertArr, after2);
    }
    delete(deleteIndex, deleteCount) {
      if (deleteCount === 0 || deleteIndex >= this._store.length) {
        return;
      }
      this._store.splice(deleteIndex, deleteCount);
    }
    insert(insertIndex, insertCount) {
      if (insertCount === 0 || insertIndex >= this._store.length) {
        return;
      }
      const arr = [];
      for (let i2 = 0; i2 < insertCount; i2++) {
        arr[i2] = this._default;
      }
      this._store = arrayInsert(this._store, insertIndex, arr);
    }
  }
  function arrayFill(length, value) {
    const arr = [];
    for (let i2 = 0; i2 < length; i2++) {
      arr[i2] = value;
    }
    return arr;
  }
  class ContiguousMultilineTokens {
    /**
     * (Inclusive) start line number for these tokens.
     */
    get startLineNumber() {
      return this._startLineNumber;
    }
    /**
     * (Inclusive) end line number for these tokens.
     */
    get endLineNumber() {
      return this._startLineNumber + this._tokens.length - 1;
    }
    constructor(startLineNumber, tokens) {
      this._startLineNumber = startLineNumber;
      this._tokens = tokens;
    }
    /**
     * @see {@link _tokens}
     */
    getLineTokens(lineNumber) {
      return this._tokens[lineNumber - this._startLineNumber];
    }
    appendLineTokens(lineTokens) {
      this._tokens.push(lineTokens);
    }
  }
  class ContiguousMultilineTokensBuilder {
    constructor() {
      this._tokens = [];
    }
    add(lineNumber, lineTokens) {
      if (this._tokens.length > 0) {
        const last = this._tokens[this._tokens.length - 1];
        if (last.endLineNumber + 1 === lineNumber) {
          last.appendLineTokens(lineTokens);
          return;
        }
      }
      this._tokens.push(new ContiguousMultilineTokens(lineNumber, [lineTokens]));
    }
    finalize() {
      return this._tokens;
    }
  }
  class TokenizerWithStateStore {
    constructor(lineCount, tokenizationSupport) {
      this.tokenizationSupport = tokenizationSupport;
      this.initialState = this.tokenizationSupport.getInitialState();
      this.store = new TrackingTokenizationStateStore(lineCount);
    }
    getStartState(lineNumber) {
      return this.store.getStartState(lineNumber, this.initialState);
    }
    getFirstInvalidLine() {
      return this.store.getFirstInvalidLine(this.initialState);
    }
  }
  class TokenizerWithStateStoreAndTextModel extends TokenizerWithStateStore {
    constructor(lineCount, tokenizationSupport, _textModel, _languageIdCodec) {
      super(lineCount, tokenizationSupport);
      this._textModel = _textModel;
      this._languageIdCodec = _languageIdCodec;
    }
    updateTokensUntilLine(builder, lineNumber) {
      const languageId = this._textModel.getLanguageId();
      while (true) {
        const lineToTokenize = this.getFirstInvalidLine();
        if (!lineToTokenize || lineToTokenize.lineNumber > lineNumber) {
          break;
        }
        const text2 = this._textModel.getLineContent(lineToTokenize.lineNumber);
        const r = safeTokenize(this._languageIdCodec, languageId, this.tokenizationSupport, text2, true, lineToTokenize.startState);
        builder.add(lineToTokenize.lineNumber, r.tokens);
        this.store.setEndState(lineToTokenize.lineNumber, r.endState);
      }
    }
    /** assumes state is up to date */
    getTokenTypeIfInsertingCharacter(position, character) {
      const lineStartState = this.getStartState(position.lineNumber);
      if (!lineStartState) {
        return 0;
      }
      const languageId = this._textModel.getLanguageId();
      const lineContent = this._textModel.getLineContent(position.lineNumber);
      const text2 = lineContent.substring(0, position.column - 1) + character + lineContent.substring(position.column - 1);
      const r = safeTokenize(this._languageIdCodec, languageId, this.tokenizationSupport, text2, true, lineStartState);
      const lineTokens = new LineTokens(r.tokens, text2, this._languageIdCodec);
      if (lineTokens.getCount() === 0) {
        return 0;
      }
      const tokenIndex = lineTokens.findTokenIndexAtOffset(position.column - 1);
      return lineTokens.getStandardTokenType(tokenIndex);
    }
    /** assumes state is up to date */
    tokenizeLinesAt(lineNumber, lines) {
      const lineStartState = this.getStartState(lineNumber);
      if (!lineStartState) {
        return null;
      }
      const languageId = this._textModel.getLanguageId();
      const result = [];
      let state = lineStartState;
      for (const line of lines) {
        const r = safeTokenize(this._languageIdCodec, languageId, this.tokenizationSupport, line, true, state);
        result.push(new LineTokens(r.tokens, line, this._languageIdCodec));
        state = r.endState;
      }
      return result;
    }
    hasAccurateTokensForLine(lineNumber) {
      const firstInvalidLineNumber = this.store.getFirstInvalidEndStateLineNumberOrMax();
      return lineNumber < firstInvalidLineNumber;
    }
    isCheapToTokenize(lineNumber) {
      const firstInvalidLineNumber = this.store.getFirstInvalidEndStateLineNumberOrMax();
      if (lineNumber < firstInvalidLineNumber) {
        return true;
      }
      if (lineNumber === firstInvalidLineNumber && this._textModel.getLineLength(lineNumber) < 2048) {
        return true;
      }
      return false;
    }
    /**
     * The result is not cached.
     */
    tokenizeHeuristically(builder, startLineNumber, endLineNumber) {
      if (endLineNumber <= this.store.getFirstInvalidEndStateLineNumberOrMax()) {
        return { heuristicTokens: false };
      }
      if (startLineNumber <= this.store.getFirstInvalidEndStateLineNumberOrMax()) {
        this.updateTokensUntilLine(builder, endLineNumber);
        return { heuristicTokens: false };
      }
      let state = this.guessStartState(startLineNumber);
      const languageId = this._textModel.getLanguageId();
      for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
        const text2 = this._textModel.getLineContent(lineNumber);
        const r = safeTokenize(this._languageIdCodec, languageId, this.tokenizationSupport, text2, true, state);
        builder.add(lineNumber, r.tokens);
        state = r.endState;
      }
      return { heuristicTokens: true };
    }
    guessStartState(lineNumber) {
      let { likelyRelevantLines, initialState } = findLikelyRelevantLines(this._textModel, lineNumber, this);
      if (!initialState) {
        initialState = this.tokenizationSupport.getInitialState();
      }
      const languageId = this._textModel.getLanguageId();
      let state = initialState;
      for (const line of likelyRelevantLines) {
        const r = safeTokenize(this._languageIdCodec, languageId, this.tokenizationSupport, line, false, state);
        state = r.endState;
      }
      return state;
    }
  }
  function findLikelyRelevantLines(model, lineNumber, store) {
    let nonWhitespaceColumn = model.getLineFirstNonWhitespaceColumn(lineNumber);
    const likelyRelevantLines = [];
    let initialState = null;
    for (let i2 = lineNumber - 1; nonWhitespaceColumn > 1 && i2 >= 1; i2--) {
      const newNonWhitespaceIndex = model.getLineFirstNonWhitespaceColumn(i2);
      if (newNonWhitespaceIndex === 0) {
        continue;
      }
      if (newNonWhitespaceIndex < nonWhitespaceColumn) {
        likelyRelevantLines.push(model.getLineContent(i2));
        nonWhitespaceColumn = newNonWhitespaceIndex;
        initialState = store?.getStartState(i2);
        if (initialState) {
          break;
        }
      }
    }
    likelyRelevantLines.reverse();
    return { likelyRelevantLines, initialState: initialState ?? void 0 };
  }
  class TrackingTokenizationStateStore {
    constructor(lineCount) {
      this.lineCount = lineCount;
      this._tokenizationStateStore = new TokenizationStateStore();
      this._invalidEndStatesLineNumbers = new RangePriorityQueueImpl();
      this._invalidEndStatesLineNumbers.addRange(new OffsetRange(1, lineCount + 1));
    }
    getEndState(lineNumber) {
      return this._tokenizationStateStore.getEndState(lineNumber);
    }
    /**
     * @returns if the end state has changed.
     */
    setEndState(lineNumber, state) {
      if (!state) {
        throw new BugIndicatingError("Cannot set null/undefined state");
      }
      this._invalidEndStatesLineNumbers.delete(lineNumber);
      const r = this._tokenizationStateStore.setEndState(lineNumber, state);
      if (r && lineNumber < this.lineCount) {
        this._invalidEndStatesLineNumbers.addRange(new OffsetRange(lineNumber + 1, lineNumber + 2));
      }
      return r;
    }
    acceptChange(range2, newLineCount) {
      this.lineCount += newLineCount - range2.length;
      this._tokenizationStateStore.acceptChange(range2, newLineCount);
      this._invalidEndStatesLineNumbers.addRangeAndResize(new OffsetRange(range2.startLineNumber, range2.endLineNumberExclusive), newLineCount);
    }
    acceptChanges(changes) {
      for (const c of changes) {
        const [eolCount] = countEOL(c.text);
        this.acceptChange(new LineRange(c.range.startLineNumber, c.range.endLineNumber + 1), eolCount + 1);
      }
    }
    invalidateEndStateRange(range2) {
      this._invalidEndStatesLineNumbers.addRange(new OffsetRange(range2.startLineNumber, range2.endLineNumberExclusive));
    }
    getFirstInvalidEndStateLineNumber() {
      return this._invalidEndStatesLineNumbers.min;
    }
    getFirstInvalidEndStateLineNumberOrMax() {
      return this.getFirstInvalidEndStateLineNumber() || Number.MAX_SAFE_INTEGER;
    }
    allStatesValid() {
      return this._invalidEndStatesLineNumbers.min === null;
    }
    getStartState(lineNumber, initialState) {
      if (lineNumber === 1) {
        return initialState;
      }
      return this.getEndState(lineNumber - 1);
    }
    getFirstInvalidLine(initialState) {
      const lineNumber = this.getFirstInvalidEndStateLineNumber();
      if (lineNumber === null) {
        return null;
      }
      const startState = this.getStartState(lineNumber, initialState);
      if (!startState) {
        throw new BugIndicatingError("Start state must be defined");
      }
      return { lineNumber, startState };
    }
  }
  class TokenizationStateStore {
    constructor() {
      this._lineEndStates = new FixedArray(null);
    }
    getEndState(lineNumber) {
      return this._lineEndStates.get(lineNumber);
    }
    setEndState(lineNumber, state) {
      const oldState = this._lineEndStates.get(lineNumber);
      if (oldState && oldState.equals(state)) {
        return false;
      }
      this._lineEndStates.set(lineNumber, state);
      return true;
    }
    acceptChange(range2, newLineCount) {
      let length = range2.length;
      if (newLineCount > 0 && length > 0) {
        length--;
        newLineCount--;
      }
      this._lineEndStates.replace(range2.startLineNumber, length, newLineCount);
    }
  }
  class RangePriorityQueueImpl {
    constructor() {
      this._ranges = [];
    }
    get min() {
      if (this._ranges.length === 0) {
        return null;
      }
      return this._ranges[0].start;
    }
    delete(value) {
      const idx = this._ranges.findIndex((r) => r.contains(value));
      if (idx !== -1) {
        const range2 = this._ranges[idx];
        if (range2.start === value) {
          if (range2.endExclusive === value + 1) {
            this._ranges.splice(idx, 1);
          } else {
            this._ranges[idx] = new OffsetRange(value + 1, range2.endExclusive);
          }
        } else {
          if (range2.endExclusive === value + 1) {
            this._ranges[idx] = new OffsetRange(range2.start, value);
          } else {
            this._ranges.splice(idx, 1, new OffsetRange(range2.start, value), new OffsetRange(value + 1, range2.endExclusive));
          }
        }
      }
    }
    addRange(range2) {
      OffsetRange.addRange(range2, this._ranges);
    }
    addRangeAndResize(range2, newLength) {
      let idxFirstMightBeIntersecting = 0;
      while (!(idxFirstMightBeIntersecting >= this._ranges.length || range2.start <= this._ranges[idxFirstMightBeIntersecting].endExclusive)) {
        idxFirstMightBeIntersecting++;
      }
      let idxFirstIsAfter = idxFirstMightBeIntersecting;
      while (!(idxFirstIsAfter >= this._ranges.length || range2.endExclusive < this._ranges[idxFirstIsAfter].start)) {
        idxFirstIsAfter++;
      }
      const delta = newLength - range2.length;
      for (let i2 = idxFirstIsAfter; i2 < this._ranges.length; i2++) {
        this._ranges[i2] = this._ranges[i2].delta(delta);
      }
      if (idxFirstMightBeIntersecting === idxFirstIsAfter) {
        const newRange = new OffsetRange(range2.start, range2.start + newLength);
        if (!newRange.isEmpty) {
          this._ranges.splice(idxFirstMightBeIntersecting, 0, newRange);
        }
      } else {
        const start = Math.min(range2.start, this._ranges[idxFirstMightBeIntersecting].start);
        const endEx = Math.max(range2.endExclusive, this._ranges[idxFirstIsAfter - 1].endExclusive);
        const newRange = new OffsetRange(start, endEx + delta);
        if (!newRange.isEmpty) {
          this._ranges.splice(idxFirstMightBeIntersecting, idxFirstIsAfter - idxFirstMightBeIntersecting, newRange);
        } else {
          this._ranges.splice(idxFirstMightBeIntersecting, idxFirstIsAfter - idxFirstMightBeIntersecting);
        }
      }
    }
    toString() {
      return this._ranges.map((r) => r.toString()).join(" + ");
    }
  }
  function safeTokenize(languageIdCodec, languageId, tokenizationSupport, text2, hasEOL, state) {
    let r = null;
    if (tokenizationSupport) {
      try {
        r = tokenizationSupport.tokenizeEncoded(text2, hasEOL, state.clone());
      } catch (e) {
        onUnexpectedError(e);
      }
    }
    if (!r) {
      r = nullTokenizeEncoded(languageIdCodec.encodeLanguageId(languageId), state);
    }
    LineTokens.convertToEndOffset(r.tokens, text2.length);
    return r;
  }
  class DefaultBackgroundTokenizer {
    constructor(_tokenizerWithStateStore, _backgroundTokenStore) {
      this._tokenizerWithStateStore = _tokenizerWithStateStore;
      this._backgroundTokenStore = _backgroundTokenStore;
      this._isDisposed = false;
      this._isScheduled = false;
    }
    dispose() {
      this._isDisposed = true;
    }
    handleChanges() {
      this._beginBackgroundTokenization();
    }
    _beginBackgroundTokenization() {
      if (this._isScheduled || !this._tokenizerWithStateStore._textModel.isAttachedToEditor() || !this._hasLinesToTokenize()) {
        return;
      }
      this._isScheduled = true;
      runWhenGlobalIdle((deadline) => {
        this._isScheduled = false;
        this._backgroundTokenizeWithDeadline(deadline);
      });
    }
    /**
     * Tokenize until the deadline occurs, but try to yield every 1-2ms.
     */
    _backgroundTokenizeWithDeadline(deadline) {
      const endTime = Date.now() + deadline.timeRemaining();
      const execute = () => {
        if (this._isDisposed || !this._tokenizerWithStateStore._textModel.isAttachedToEditor() || !this._hasLinesToTokenize()) {
          return;
        }
        this._backgroundTokenizeForAtLeast1ms();
        if (Date.now() < endTime) {
          setTimeout0(execute);
        } else {
          this._beginBackgroundTokenization();
        }
      };
      execute();
    }
    /**
     * Tokenize for at least 1ms.
     */
    _backgroundTokenizeForAtLeast1ms() {
      const lineCount = this._tokenizerWithStateStore._textModel.getLineCount();
      const builder = new ContiguousMultilineTokensBuilder();
      const sw = StopWatch.create(false);
      do {
        if (sw.elapsed() > 1) {
          break;
        }
        const tokenizedLineNumber = this._tokenizeOneInvalidLine(builder);
        if (tokenizedLineNumber >= lineCount) {
          break;
        }
      } while (this._hasLinesToTokenize());
      this._backgroundTokenStore.setTokens(builder.finalize());
      this.checkFinished();
    }
    _hasLinesToTokenize() {
      if (!this._tokenizerWithStateStore) {
        return false;
      }
      return !this._tokenizerWithStateStore.store.allStatesValid();
    }
    _tokenizeOneInvalidLine(builder) {
      const firstInvalidLine = this._tokenizerWithStateStore?.getFirstInvalidLine();
      if (!firstInvalidLine) {
        return this._tokenizerWithStateStore._textModel.getLineCount() + 1;
      }
      this._tokenizerWithStateStore.updateTokensUntilLine(builder, firstInvalidLine.lineNumber);
      return firstInvalidLine.lineNumber;
    }
    checkFinished() {
      if (this._isDisposed) {
        return;
      }
      if (this._tokenizerWithStateStore.store.allStatesValid()) {
        this._backgroundTokenStore.backgroundTokenizationFinished();
      }
    }
    requestTokens(startLineNumber, endLineNumberExclusive) {
      this._tokenizerWithStateStore.store.invalidateEndStateRange(new LineRange(startLineNumber, endLineNumberExclusive));
    }
  }
  class ListNode {
    get children() {
      return this._children;
    }
    get length() {
      return this._length;
    }
    constructor(height) {
      this.height = height;
      this._children = [];
      this._length = 0;
    }
    static create(node1, node2) {
      const list2 = new ListNode(node1.height + 1);
      list2.appendChild(node1);
      list2.appendChild(node2);
      return list2;
    }
    canAppendChild() {
      return this._children.length < 3;
    }
    appendChild(node) {
      if (!this.canAppendChild()) {
        throw new Error("Cannot insert more than 3 children in a ListNode");
      }
      this._children.push(node);
      this._length += node.length;
      this._updateParentLength(node.length);
      if (!isLeaf(node)) {
        node.parent = this;
      }
    }
    _updateParentLength(delta) {
      let updateParent = this.parent;
      while (updateParent) {
        updateParent._length += delta;
        updateParent = updateParent.parent;
      }
    }
    unappendChild() {
      const child = this._children.pop();
      this._length -= child.length;
      this._updateParentLength(-child.length);
      return child;
    }
    prependChild(node) {
      if (this._children.length >= 3) {
        throw new Error("Cannot prepend more than 3 children in a ListNode");
      }
      this._children.unshift(node);
      this._length += node.length;
      this._updateParentLength(node.length);
      if (!isLeaf(node)) {
        node.parent = this;
      }
    }
    unprependChild() {
      const child = this._children.shift();
      this._length -= child.length;
      this._updateParentLength(-child.length);
      return child;
    }
    lastChild() {
      return this._children[this._children.length - 1];
    }
    dispose() {
      this._children.splice(0, this._children.length);
    }
  }
  var TokenQuality;
  (function(TokenQuality2) {
    TokenQuality2[TokenQuality2["None"] = 0] = "None";
    TokenQuality2[TokenQuality2["ViewportGuess"] = 1] = "ViewportGuess";
    TokenQuality2[TokenQuality2["EditGuess"] = 2] = "EditGuess";
    TokenQuality2[TokenQuality2["Accurate"] = 3] = "Accurate";
  })(TokenQuality || (TokenQuality = {}));
  function isLeaf(node) {
    return node.token !== void 0;
  }
  function append(node, nodeToAppend) {
    let curNode = node;
    const parents = [];
    let nodeToAppendOfCorrectHeight;
    while (true) {
      if (nodeToAppend.height === curNode.height) {
        nodeToAppendOfCorrectHeight = nodeToAppend;
        break;
      }
      if (isLeaf(curNode)) {
        throw new Error("unexpected");
      }
      parents.push(curNode);
      curNode = curNode.lastChild();
    }
    for (let i2 = parents.length - 1; i2 >= 0; i2--) {
      const parent = parents[i2];
      if (nodeToAppendOfCorrectHeight) {
        if (parent.children.length >= 3) {
          const newList = ListNode.create(parent.unappendChild(), nodeToAppendOfCorrectHeight);
          nodeToAppendOfCorrectHeight = newList;
        } else {
          parent.appendChild(nodeToAppendOfCorrectHeight);
          nodeToAppendOfCorrectHeight = void 0;
        }
      }
    }
    if (nodeToAppendOfCorrectHeight) {
      const newList = new ListNode(nodeToAppendOfCorrectHeight.height + 1);
      newList.appendChild(node);
      newList.appendChild(nodeToAppendOfCorrectHeight);
      return newList;
    } else {
      return node;
    }
  }
  function prepend(list2, nodeToAppend) {
    let curNode = list2;
    const parents = [];
    while (nodeToAppend.height !== curNode.height) {
      if (isLeaf(curNode)) {
        throw new Error("unexpected");
      }
      parents.push(curNode);
      curNode = curNode.children[0];
    }
    let nodeToPrependOfCorrectHeight = nodeToAppend;
    for (let i2 = parents.length - 1; i2 >= 0; i2--) {
      const parent = parents[i2];
      if (nodeToPrependOfCorrectHeight) {
        if (parent.children.length >= 3) {
          nodeToPrependOfCorrectHeight = ListNode.create(nodeToPrependOfCorrectHeight, parent.unprependChild());
        } else {
          parent.prependChild(nodeToPrependOfCorrectHeight);
          nodeToPrependOfCorrectHeight = void 0;
        }
      }
    }
    if (nodeToPrependOfCorrectHeight) {
      return ListNode.create(nodeToPrependOfCorrectHeight, list2);
    } else {
      return list2;
    }
  }
  function concat$1(node1, node2) {
    if (node1.height === node2.height) {
      return ListNode.create(node1, node2);
    } else if (node1.height > node2.height) {
      return append(node1, node2);
    } else {
      return prepend(node2, node1);
    }
  }
  class TokenStore {
    constructor(_textModel) {
      this._textModel = _textModel;
      this._root = this.createEmptyRoot();
    }
    createEmptyRoot() {
      return {
        length: this._textModel.getValueLength(),
        token: 0,
        height: 0,
        tokenQuality: TokenQuality.None
      };
    }
    /**
     *
     * @param update all the tokens for the document in sequence
     */
    buildStore(tokens, tokenQuality) {
      this._root = this.createFromUpdates(tokens, tokenQuality);
    }
    createFromUpdates(tokens, tokenQuality) {
      if (tokens.length === 0) {
        return this.createEmptyRoot();
      }
      let newRoot = {
        length: tokens[0].length,
        token: tokens[0].token,
        height: 0,
        tokenQuality
      };
      for (let j = 1; j < tokens.length; j++) {
        newRoot = append(newRoot, { length: tokens[j].length, token: tokens[j].token, height: 0, tokenQuality });
      }
      return newRoot;
    }
    /**
     *
     * @param tokens tokens are in sequence in the document.
     */
    update(length, tokens, tokenQuality) {
      if (tokens.length === 0) {
        return;
      }
      this.replace(length, tokens[0].startOffsetInclusive, tokens, tokenQuality);
    }
    delete(length, startOffset) {
      this.replace(length, startOffset, [], TokenQuality.EditGuess);
    }
    /**
     *
     * @param tokens tokens are in sequence in the document.
     */
    replace(length, updateOffsetStart, tokens, tokenQuality) {
      const firstUnchangedOffsetAfterUpdate = updateOffsetStart + length;
      const precedingNodes = [];
      const postcedingNodes = [];
      const stack = [{ node: this._root, offset: 0 }];
      while (stack.length > 0) {
        const node = stack.pop();
        const currentOffset = node.offset;
        if (currentOffset < updateOffsetStart && currentOffset + node.node.length <= updateOffsetStart) {
          if (!isLeaf(node.node)) {
            node.node.parent = void 0;
          }
          precedingNodes.push(node.node);
          continue;
        } else if (isLeaf(node.node) && currentOffset < updateOffsetStart) {
          precedingNodes.push({ length: updateOffsetStart - currentOffset, token: node.node.token, height: 0, tokenQuality: node.node.tokenQuality });
        }
        if (updateOffsetStart <= currentOffset && currentOffset + node.node.length <= firstUnchangedOffsetAfterUpdate) {
          continue;
        }
        if (currentOffset >= firstUnchangedOffsetAfterUpdate) {
          if (!isLeaf(node.node)) {
            node.node.parent = void 0;
          }
          postcedingNodes.push(node.node);
          continue;
        } else if (isLeaf(node.node) && currentOffset + node.node.length > firstUnchangedOffsetAfterUpdate) {
          postcedingNodes.push({ length: currentOffset + node.node.length - firstUnchangedOffsetAfterUpdate, token: node.node.token, height: 0, tokenQuality: node.node.tokenQuality });
          continue;
        }
        if (!isLeaf(node.node)) {
          let childOffset = currentOffset + node.node.length;
          for (let i2 = node.node.children.length - 1; i2 >= 0; i2--) {
            childOffset -= node.node.children[i2].length;
            stack.push({ node: node.node.children[i2], offset: childOffset });
          }
        }
      }
      let allNodes;
      if (tokens.length > 0) {
        allNodes = precedingNodes.concat(this.createFromUpdates(tokens, tokenQuality), postcedingNodes);
      } else {
        allNodes = precedingNodes.concat(postcedingNodes);
      }
      let newRoot = allNodes[0];
      for (let i2 = 1; i2 < allNodes.length; i2++) {
        newRoot = concat$1(newRoot, allNodes[i2]);
      }
      this._root = newRoot ?? this.createEmptyRoot();
    }
    /**
     *
     * @param startOffsetInclusive
     * @param endOffsetExclusive
     * @param visitor Return true from visitor to exit early
     * @returns
     */
    traverseInOrderInRange(startOffsetInclusive, endOffsetExclusive, visitor) {
      const stack = [{ node: this._root, offset: 0 }];
      while (stack.length > 0) {
        const { node, offset } = stack.pop();
        const nodeEnd = offset + node.length;
        if (nodeEnd <= startOffsetInclusive || offset >= endOffsetExclusive) {
          continue;
        }
        if (visitor(node, offset)) {
          return;
        }
        if (!isLeaf(node)) {
          let childOffset = offset + node.length;
          for (let i2 = node.children.length - 1; i2 >= 0; i2--) {
            childOffset -= node.children[i2].length;
            stack.push({ node: node.children[i2], offset: childOffset });
          }
        }
      }
    }
    getTokenAt(offset) {
      let result;
      this.traverseInOrderInRange(offset, this._root.length, (node, offset2) => {
        if (isLeaf(node)) {
          result = { token: node.token, startOffsetInclusive: offset2, length: node.length };
          return true;
        }
        return false;
      });
      return result;
    }
    getTokensInRange(startOffsetInclusive, endOffsetExclusive) {
      const result = [];
      this.traverseInOrderInRange(startOffsetInclusive, endOffsetExclusive, (node, offset) => {
        if (isLeaf(node)) {
          let clippedLength = node.length;
          let clippedOffset = offset;
          if (offset < startOffsetInclusive && offset + node.length > endOffsetExclusive) {
            clippedOffset = startOffsetInclusive;
            clippedLength = endOffsetExclusive - startOffsetInclusive;
          } else if (offset < startOffsetInclusive) {
            clippedLength -= startOffsetInclusive - offset;
            clippedOffset = startOffsetInclusive;
          } else if (offset + node.length > endOffsetExclusive) {
            clippedLength -= offset + node.length - endOffsetExclusive;
          }
          result.push({ token: node.token, startOffsetInclusive: clippedOffset, length: clippedLength });
        }
        return false;
      });
      return result;
    }
    markForRefresh(startOffsetInclusive, endOffsetExclusive) {
      this.traverseInOrderInRange(startOffsetInclusive, endOffsetExclusive, (node) => {
        if (isLeaf(node)) {
          node.tokenQuality = TokenQuality.None;
        }
        return false;
      });
    }
    rangeHasTokens(startOffsetInclusive, endOffsetExclusive, minimumTokenQuality) {
      let hasAny = true;
      this.traverseInOrderInRange(startOffsetInclusive, endOffsetExclusive, (node) => {
        if (isLeaf(node) && node.tokenQuality < minimumTokenQuality) {
          hasAny = false;
        }
        return false;
      });
      return hasAny;
    }
    rangeNeedsRefresh(startOffsetInclusive, endOffsetExclusive) {
      let needsRefresh = false;
      this.traverseInOrderInRange(startOffsetInclusive, endOffsetExclusive, (node) => {
        if (isLeaf(node) && node.tokenQuality !== TokenQuality.Accurate) {
          needsRefresh = true;
        }
        return false;
      });
      return needsRefresh;
    }
    getNeedsRefresh() {
      const result = [];
      this.traverseInOrderInRange(0, this._textModel.getValueLength(), (node, offset) => {
        if (isLeaf(node) && node.tokenQuality !== TokenQuality.Accurate) {
          if (result.length > 0 && result[result.length - 1].endOffset === offset) {
            result[result.length - 1].endOffset += node.length;
          } else {
            result.push({ startOffset: offset, endOffset: offset + node.length });
          }
        }
        return false;
      });
      return result;
    }
    dispose() {
      const stack = [[this._root, false]];
      while (stack.length > 0) {
        const [node, visited] = stack.pop();
        if (isLeaf(node)) ;
        else if (!visited) {
          stack.push([node, true]);
          for (let i2 = node.children.length - 1; i2 >= 0; i2--) {
            stack.push([node.children[i2], false]);
          }
        } else {
          node.dispose();
          node.parent = void 0;
        }
      }
      this._root = void 0;
    }
  }
  const ITreeSitterThemeService = createDecorator("treeSitterThemeService");
  var __decorate$2O = 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$2J = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  let TreeSitterTokenizationImpl = class TreeSitterTokenizationImpl extends Disposable {
    get _textModel() {
      return this._tree.textModel;
    }
    constructor(_tree, _highlightingQueries, _languageIdCodec, _visibleLineRanges, _treeSitterThemeService) {
      super();
      this._tree = _tree;
      this._highlightingQueries = _highlightingQueries;
      this._languageIdCodec = _languageIdCodec;
      this._visibleLineRanges = _visibleLineRanges;
      this._treeSitterThemeService = _treeSitterThemeService;
      this._onDidChangeTokens = this._register(new Emitter$1());
      this.onDidChangeTokens = this._onDidChangeTokens.event;
      this._onDidCompleteBackgroundTokenization = this._register(new Emitter$1());
      this.onDidChangeBackgroundTokenization = this._onDidCompleteBackgroundTokenization.event;
      this._encodedLanguageId = this._languageIdCodec.encodeLanguageId(this._tree.languageId);
      this._register(runOnChange(this._treeSitterThemeService.onChange, () => {
        this._updateTheme();
      }));
      this._tokenStore = this._register(new TokenStore(this._textModel));
      this._accurateVersion = this._textModel.getVersionId();
      this._guessVersion = this._textModel.getVersionId();
      this._tokenStore.buildStore(this._createEmptyTokens(), TokenQuality.None);
      this._register(autorun((reader) => {
        const visibleLineRanges = this._visibleLineRanges.read(reader);
        this._parseAndTokenizeViewPort(visibleLineRanges);
      }));
      this._register(autorunHandleChanges({
        owner: this,
        changeTracker: recordChanges({ tree: this._tree.tree })
      }, (reader, ctx) => {
        const changeEvent = ctx.changes.at(0)?.change;
        if (ctx.changes.length > 1) {
          throw new BugIndicatingError("The tree changed twice in one transaction. This is currently not supported and should not happen.");
        }
        if (!changeEvent) {
          if (ctx.tree) {
            this._firstTreeUpdate(this._tree.treeLastParsedVersion.read(reader));
          }
        } else {
          if (this.hasTokens()) {
            for (const range2 of changeEvent.ranges) {
              this._markForRefresh(range2.newRange);
            }
          }
          if (!this.hasTokens()) {
            this._firstTreeUpdate(changeEvent.versionId);
          } else {
            this._handleTreeUpdate(changeEvent.ranges, changeEvent.versionId);
          }
        }
      }));
    }
    handleContentChanged(e) {
      this._guessVersion = e.versionId;
      for (const change of e.changes) {
        if (change.text.length > change.rangeLength) {
          const offset = change.rangeOffset > 0 ? change.rangeOffset - 1 : change.rangeOffset;
          const oldToken = this._tokenStore.getTokenAt(offset);
          let newToken;
          if (oldToken) {
            newToken = { startOffsetInclusive: oldToken.startOffsetInclusive, length: oldToken.length + change.text.length - change.rangeLength, token: oldToken.token };
            this._tokenStore.markForRefresh(offset, change.rangeOffset + (change.text.length > change.rangeLength ? change.text.length : change.rangeLength));
          } else {
            newToken = { startOffsetInclusive: offset, length: change.text.length, token: 0 };
          }
          this._tokenStore.update(oldToken?.length ?? 0, [newToken], TokenQuality.EditGuess);
        } else if (change.text.length < change.rangeLength) {
          const deletedCharCount = change.rangeLength - change.text.length;
          this._tokenStore.delete(deletedCharCount, change.rangeOffset);
        }
      }
    }
    getLineTokens(lineNumber) {
      const content = this._textModel.getLineContent(lineNumber);
      const rawTokens = this.getTokens(lineNumber);
      return new LineTokens(rawTokens, content, this._languageIdCodec);
    }
    _createEmptyTokens() {
      const emptyToken = this._emptyToken();
      const modelEndOffset = this._textModel.getValueLength();
      const emptyTokens = [this._emptyTokensForOffsetAndLength(0, modelEndOffset, emptyToken)];
      return emptyTokens;
    }
    _emptyToken() {
      return this._treeSitterThemeService.findMetadata([], this._encodedLanguageId, false, void 0);
    }
    _emptyTokensForOffsetAndLength(offset, length, emptyToken) {
      return { token: emptyToken, length: offset + length, startOffsetInclusive: 0 };
    }
    hasAccurateTokensForLine(lineNumber) {
      return this.hasTokens(new Range$2(lineNumber, 1, lineNumber, this._textModel.getLineMaxColumn(lineNumber)));
    }
    tokenizeLinesAt(lineNumber, lines) {
      const rawLineTokens = this._guessTokensForLinesContent(lineNumber, lines);
      const lineTokens = [];
      if (!rawLineTokens) {
        return null;
      }
      for (let i2 = 0; i2 < rawLineTokens.length; i2++) {
        lineTokens.push(new LineTokens(rawLineTokens[i2], lines[i2], this._languageIdCodec));
      }
      return lineTokens;
    }
    _rangeHasTokens(range2, minimumTokenQuality) {
      return this._tokenStore.rangeHasTokens(this._textModel.getOffsetAt(range2.getStartPosition()), this._textModel.getOffsetAt(range2.getEndPosition()), minimumTokenQuality);
    }
    hasTokens(accurateForRange) {
      if (!accurateForRange || this._guessVersion === this._accurateVersion) {
        return true;
      }
      return !this._tokenStore.rangeNeedsRefresh(this._textModel.getOffsetAt(accurateForRange.getStartPosition()), this._textModel.getOffsetAt(accurateForRange.getEndPosition()));
    }
    getTokens(line) {
      const lineStartOffset = this._textModel.getOffsetAt({ lineNumber: line, column: 1 });
      const lineEndOffset = this._textModel.getOffsetAt({ lineNumber: line, column: this._textModel.getLineLength(line) + 1 });
      const lineTokens = this._tokenStore.getTokensInRange(lineStartOffset, lineEndOffset);
      const result = new Uint32Array(lineTokens.length * 2);
      for (let i2 = 0; i2 < lineTokens.length; i2++) {
        result[i2 * 2] = lineTokens[i2].startOffsetInclusive - lineStartOffset + lineTokens[i2].length;
        result[i2 * 2 + 1] = lineTokens[i2].token;
      }
      return result;
    }
    getTokensInRange(range2, rangeStartOffset, rangeEndOffset, captures) {
      const tokens = captures ? this._tokenizeCapturesWithMetadata(captures, rangeStartOffset, rangeEndOffset) : this._tokenize(range2, rangeStartOffset, rangeEndOffset);
      if (tokens?.endOffsetsAndMetadata) {
        return this._rangeTokensAsUpdates(rangeStartOffset, tokens.endOffsetsAndMetadata);
      }
      return void 0;
    }
    _updateTokensInStore(version, updates, tokenQuality) {
      this._accurateVersion = version;
      for (const update of updates) {
        const lastToken = update.newTokens.length > 0 ? update.newTokens[update.newTokens.length - 1] : void 0;
        let oldRangeLength;
        if (lastToken && this._guessVersion >= version) {
          oldRangeLength = lastToken.startOffsetInclusive + lastToken.length - update.newTokens[0].startOffsetInclusive;
        } else if (update.oldRangeLength) {
          oldRangeLength = update.oldRangeLength;
        } else {
          oldRangeLength = 0;
        }
        this._tokenStore.update(oldRangeLength, update.newTokens, tokenQuality);
      }
    }
    _markForRefresh(range2) {
      this._tokenStore.markForRefresh(this._textModel.getOffsetAt(range2.getStartPosition()), this._textModel.getOffsetAt(range2.getEndPosition()));
    }
    _getNeedsRefresh() {
      const needsRefreshOffsetRanges = this._tokenStore.getNeedsRefresh();
      if (!needsRefreshOffsetRanges) {
        return [];
      }
      return needsRefreshOffsetRanges.map((range2) => ({
        range: Range$2.fromPositions(this._textModel.getPositionAt(range2.startOffset), this._textModel.getPositionAt(range2.endOffset)),
        startOffset: range2.startOffset,
        endOffset: range2.endOffset
      }));
    }
    _parseAndTokenizeViewPort(lineRanges) {
      const viewportRanges = lineRanges.map((r) => r.toInclusiveRange()).filter(isDefined);
      for (const range2 of viewportRanges) {
        const startOffsetOfRangeInDocument = this._textModel.getOffsetAt(range2.getStartPosition());
        const endOffsetOfRangeInDocument = this._textModel.getOffsetAt(range2.getEndPosition());
        const version = this._textModel.getVersionId();
        if (this._rangeHasTokens(range2, TokenQuality.ViewportGuess)) {
          continue;
        }
        const content = this._textModel.getValueInRange(range2);
        const tokenUpdates = this._forceParseAndTokenizeContent(range2, startOffsetOfRangeInDocument, endOffsetOfRangeInDocument, content, true);
        if (!tokenUpdates || this._rangeHasTokens(range2, TokenQuality.ViewportGuess)) {
          continue;
        }
        if (tokenUpdates.length === 0) {
          continue;
        }
        const lastToken = tokenUpdates[tokenUpdates.length - 1];
        const oldRangeLength = lastToken.startOffsetInclusive + lastToken.length - tokenUpdates[0].startOffsetInclusive;
        this._updateTokensInStore(version, [{ newTokens: tokenUpdates, oldRangeLength }], TokenQuality.ViewportGuess);
        this._onDidChangeTokens.fire({ changes: { semanticTokensApplied: false, ranges: [{ fromLineNumber: range2.startLineNumber, toLineNumber: range2.endLineNumber }] } });
      }
    }
    _guessTokensForLinesContent(lineNumber, lines) {
      if (lines.length === 0) {
        return void 0;
      }
      const lineContent = lines.join(this._textModel.getEOL());
      const range2 = new Range$2(1, 1, lineNumber + lines.length, lines[lines.length - 1].length + 1);
      const startOffset = this._textModel.getOffsetAt({ lineNumber, column: 1 });
      const tokens = this._forceParseAndTokenizeContent(range2, startOffset, startOffset + lineContent.length, lineContent, false);
      if (!tokens) {
        return void 0;
      }
      const tokensByLine = new Array(lines.length);
      let tokensIndex = 0;
      let tokenStartOffset = 0;
      let lineStartOffset = 0;
      for (let i2 = 0; i2 < lines.length; i2++) {
        const tokensForLine = [];
        let moveToNextLine = false;
        for (let j = tokensIndex; !moveToNextLine && j < tokens.length; j++) {
          const token = tokens[j];
          const lineAdjustedEndOffset = token.endOffset - lineStartOffset;
          const lineAdjustedStartOffset = tokenStartOffset - lineStartOffset;
          if (lineAdjustedEndOffset <= lines[i2].length) {
            tokensForLine.push({ endOffset: lineAdjustedEndOffset, metadata: token.metadata });
            tokensIndex++;
          } else if (lineAdjustedStartOffset < lines[i2].length) {
            const partialToken = { endOffset: lines[i2].length, metadata: token.metadata };
            tokensForLine.push(partialToken);
            moveToNextLine = true;
          } else {
            moveToNextLine = true;
          }
          tokenStartOffset = token.endOffset;
        }
        tokensByLine[i2] = this._endOffsetTokensToUint32Array(tokensForLine);
        lineStartOffset += lines[i2].length + this._textModel.getEOL().length;
      }
      return tokensByLine;
    }
    _forceParseAndTokenizeContent(range2, startOffsetOfRangeInDocument, endOffsetOfRangeInDocument, content, asUpdate) {
      const likelyRelevantLines = findLikelyRelevantLines(this._textModel, range2.startLineNumber).likelyRelevantLines;
      const likelyRelevantPrefix = likelyRelevantLines.join(this._textModel.getEOL());
      const tree = this._tree.createParsedTreeSync(`${likelyRelevantPrefix}${content}`);
      if (!tree) {
        return;
      }
      const treeRange = new Range$2(1, 1, range2.endLineNumber - range2.startLineNumber + 1 + likelyRelevantLines.length, range2.endColumn);
      const captures = this.captureAtRange(treeRange);
      const tokens = this._tokenizeCapturesWithMetadata(captures, likelyRelevantPrefix.length, endOffsetOfRangeInDocument - startOffsetOfRangeInDocument + likelyRelevantPrefix.length);
      tree.delete();
      if (!tokens) {
        return;
      }
      if (asUpdate) {
        return this._rangeTokensAsUpdates(startOffsetOfRangeInDocument, tokens.endOffsetsAndMetadata, likelyRelevantPrefix.length);
      } else {
        return tokens.endOffsetsAndMetadata;
      }
    }
    _firstTreeUpdate(versionId) {
      return this._setViewPortTokens(versionId);
    }
    _setViewPortTokens(versionId) {
      const rangeChanges = this._visibleLineRanges.get().map((lineRange) => {
        const range2 = lineRange.toInclusiveRange();
        if (!range2) {
          return void 0;
        }
        const newRangeStartOffset = this._textModel.getOffsetAt(range2.getStartPosition());
        const newRangeEndOffset = this._textModel.getOffsetAt(range2.getEndPosition());
        return {
          newRange: range2,
          newRangeEndOffset,
          newRangeStartOffset
        };
      }).filter(isDefined);
      return this._handleTreeUpdate(rangeChanges, versionId);
    }
    /**
     * Do not await in this method, it will cause a race
     */
    _handleTreeUpdate(ranges, versionId) {
      const rangeChanges = [];
      const chunkSize = 1e3;
      for (let i2 = 0; i2 < ranges.length; i2++) {
        const rangeLinesLength = ranges[i2].newRange.endLineNumber - ranges[i2].newRange.startLineNumber;
        if (rangeLinesLength > chunkSize) {
          const fullRangeEndLineNumber = ranges[i2].newRange.endLineNumber;
          let chunkLineStart = ranges[i2].newRange.startLineNumber;
          let chunkColumnStart = ranges[i2].newRange.startColumn;
          let chunkLineEnd = chunkLineStart + chunkSize;
          do {
            const chunkStartingPosition = new Position$1(chunkLineStart, chunkColumnStart);
            const chunkEndColumn = chunkLineEnd === ranges[i2].newRange.endLineNumber ? ranges[i2].newRange.endColumn : this._textModel.getLineMaxColumn(chunkLineEnd);
            const chunkEndPosition = new Position$1(chunkLineEnd, chunkEndColumn);
            const chunkRange = Range$2.fromPositions(chunkStartingPosition, chunkEndPosition);
            rangeChanges.push({
              range: chunkRange,
              startOffset: this._textModel.getOffsetAt(chunkRange.getStartPosition()),
              endOffset: this._textModel.getOffsetAt(chunkRange.getEndPosition())
            });
            chunkLineStart = chunkLineEnd + 1;
            chunkColumnStart = 1;
            if (chunkLineEnd < fullRangeEndLineNumber && chunkLineEnd + chunkSize > fullRangeEndLineNumber) {
              chunkLineEnd = fullRangeEndLineNumber;
            } else {
              chunkLineEnd = chunkLineEnd + chunkSize;
            }
          } while (chunkLineEnd <= fullRangeEndLineNumber);
        } else {
          if (i2 === 0 || rangeChanges[i2 - 1].endOffset < ranges[i2].newRangeStartOffset) {
            rangeChanges.push({
              range: ranges[i2].newRange,
              startOffset: ranges[i2].newRangeStartOffset,
              endOffset: ranges[i2].newRangeEndOffset
            });
          } else if (rangeChanges[i2 - 1].endOffset < ranges[i2].newRangeEndOffset) {
            const startPosition = this._textModel.getPositionAt(rangeChanges[i2 - 1].endOffset + 1);
            const range2 = new Range$2(startPosition.lineNumber, startPosition.column, ranges[i2].newRange.endLineNumber, ranges[i2].newRange.endColumn);
            rangeChanges.push({
              range: range2,
              startOffset: rangeChanges[i2 - 1].endOffset + 1,
              endOffset: ranges[i2].newRangeEndOffset
            });
          }
        }
      }
      const captures = rangeChanges.map((range2) => this._getCaptures(range2.range));
      return this._updateTreeForRanges(rangeChanges, versionId, captures).then(() => {
        if (!this._textModel.isDisposed() && this._tree.treeLastParsedVersion.get() === this._textModel.getVersionId()) {
          this._refreshNeedsRefresh(versionId);
        }
      });
    }
    async _updateTreeForRanges(rangeChanges, versionId, captures) {
      let tokenUpdate;
      for (let i2 = 0; i2 < rangeChanges.length; i2++) {
        if (!this._textModel.isDisposed() && versionId !== this._textModel.getVersionId()) {
          break;
        }
        const capture = captures[i2];
        const range2 = rangeChanges[i2];
        const updates = this.getTokensInRange(range2.range, range2.startOffset, range2.endOffset, capture);
        if (updates) {
          tokenUpdate = { newTokens: updates };
        } else {
          tokenUpdate = { newTokens: [] };
        }
        this._updateTokensInStore(versionId, [tokenUpdate], TokenQuality.Accurate);
        this._onDidChangeTokens.fire({
          changes: {
            semanticTokensApplied: false,
            ranges: [{ fromLineNumber: range2.range.getStartPosition().lineNumber, toLineNumber: range2.range.getEndPosition().lineNumber }]
          }
        });
        await new Promise((resolve2) => setTimeout0(resolve2));
      }
      this._onDidCompleteBackgroundTokenization.fire();
    }
    _refreshNeedsRefresh(versionId) {
      const rangesToRefresh = this._getNeedsRefresh();
      if (rangesToRefresh.length === 0) {
        return;
      }
      const rangeChanges = new Array(rangesToRefresh.length);
      for (let i2 = 0; i2 < rangesToRefresh.length; i2++) {
        const range2 = rangesToRefresh[i2];
        rangeChanges[i2] = {
          newRange: range2.range,
          newRangeStartOffset: range2.startOffset,
          newRangeEndOffset: range2.endOffset
        };
      }
      this._handleTreeUpdate(rangeChanges, versionId);
    }
    _rangeTokensAsUpdates(rangeOffset, endOffsetToken, startingOffsetInArray) {
      const updates = [];
      let lastEnd = 0;
      for (const token of endOffsetToken) {
        if (token.endOffset <= lastEnd || startingOffsetInArray && token.endOffset < startingOffsetInArray) {
          continue;
        }
        let tokenUpdate;
        if (startingOffsetInArray && lastEnd < startingOffsetInArray) {
          tokenUpdate = { startOffsetInclusive: rangeOffset + startingOffsetInArray, length: token.endOffset - startingOffsetInArray, token: token.metadata };
        } else {
          tokenUpdate = { startOffsetInclusive: rangeOffset + lastEnd, length: token.endOffset - lastEnd, token: token.metadata };
        }
        updates.push(tokenUpdate);
        lastEnd = token.endOffset;
      }
      return updates;
    }
    _updateTheme() {
      const modelRange = this._textModel.getFullModelRange();
      this._markForRefresh(modelRange);
      this._parseAndTokenizeViewPort(this._visibleLineRanges.get());
    }
    captureAtRange(range2) {
      const tree = this._tree.tree.get();
      if (!tree) {
        return [];
      }
      return this._highlightingQueries.captures(tree.rootNode, { startPosition: { row: range2.startLineNumber - 1, column: range2.startColumn - 1 }, endPosition: { row: range2.endLineNumber - 1, column: range2.endColumn - 1 } }).map((capture) => ({
        name: capture.name,
        text: capture.node.text,
        node: {
          startIndex: capture.node.startIndex,
          endIndex: capture.node.endIndex,
          startPosition: {
            lineNumber: capture.node.startPosition.row + 1,
            column: capture.node.startPosition.column + 1
          },
          endPosition: {
            lineNumber: capture.node.endPosition.row + 1,
            column: capture.node.endPosition.column + 1
          }
        },
        encodedLanguageId: this._encodedLanguageId
      }));
    }
    captureAtRangeWithInjections(range2) {
      const captures = this.captureAtRange(range2);
      for (let i2 = 0; i2 < captures.length; i2++) {
        const capture = captures[i2];
        const capStartLine = capture.node.startPosition.lineNumber;
        const capEndLine = capture.node.endPosition.lineNumber;
        const capStartColumn = capture.node.startPosition.column;
        const capEndColumn = capture.node.endPosition.column;
        const startLine = capStartLine > range2.startLineNumber && capStartLine < range2.endLineNumber ? capStartLine : range2.startLineNumber;
        const endLine = capEndLine > range2.startLineNumber && capEndLine < range2.endLineNumber ? capEndLine : range2.endLineNumber;
        const startColumn = capStartLine === range2.startLineNumber ? capStartColumn < range2.startColumn ? range2.startColumn : capStartColumn : capStartLine < range2.startLineNumber ? range2.startColumn : capStartColumn;
        const endColumn = capEndLine === range2.endLineNumber ? capEndColumn > range2.endColumn ? range2.endColumn : capEndColumn : capEndLine > range2.endLineNumber ? range2.endColumn : capEndColumn;
        const injectionRange = new Range$2(startLine, startColumn, endLine, endColumn);
        const injection = this._getInjectionCaptures(capture, injectionRange);
        if (injection && injection.length > 0) {
          captures.splice(i2 + 1, 0, ...injection);
          i2 += injection.length;
        }
      }
      return captures;
    }
    /**
     * Gets the tokens for a given line.
     * Each token takes 2 elements in the array. The first element is the offset of the end of the token *in the line, not in the document*, and the second element is the metadata.
     *
     * @param lineNumber
     * @returns
     */
    tokenizeEncoded(lineNumber) {
      const tokens = this._tokenizeEncoded(lineNumber);
      if (!tokens) {
        return void 0;
      }
      const updates = this._rangeTokensAsUpdates(this._textModel.getOffsetAt({ lineNumber, column: 1 }), tokens.result);
      if (tokens.versionId === this._textModel.getVersionId()) {
        this._updateTokensInStore(tokens.versionId, [{ newTokens: updates, oldRangeLength: this._textModel.getLineLength(lineNumber) }], TokenQuality.Accurate);
      }
    }
    _getCaptures(range2) {
      const captures = this.captureAtRangeWithInjections(range2);
      return captures;
    }
    _tokenize(range2, rangeStartOffset, rangeEndOffset) {
      const captures = this._getCaptures(range2);
      const result = this._tokenizeCapturesWithMetadata(captures, rangeStartOffset, rangeEndOffset);
      if (!result) {
        return void 0;
      }
      return { ...result, versionId: this._tree.treeLastParsedVersion.get() };
    }
    _createTokensFromCaptures(captures, rangeStartOffset, rangeEndOffset) {
      const tree = this._tree.tree.get();
      const stopwatch = StopWatch.create();
      const rangeLength = rangeEndOffset - rangeStartOffset;
      const encodedLanguageId = this._languageIdCodec.encodeLanguageId(this._tree.languageId);
      const baseScope = TREESITTER_BASE_SCOPES[this._tree.languageId] || "source";
      if (captures.length === 0) {
        if (tree) {
          stopwatch.stop();
          const endOffsetsAndMetadata = [{ endOffset: rangeLength, scopes: [], encodedLanguageId }];
          return { endOffsets: endOffsetsAndMetadata, captureTime: stopwatch.elapsed() };
        }
        return void 0;
      }
      const endOffsetsAndScopes = Array(captures.length);
      endOffsetsAndScopes.fill({ endOffset: 0, scopes: [baseScope], encodedLanguageId });
      let tokenIndex = 0;
      const increaseSizeOfTokensByOneToken = () => {
        endOffsetsAndScopes.push({ endOffset: 0, scopes: [baseScope], encodedLanguageId });
      };
      const brackets = (capture, startOffset) => {
        return capture.name.includes("punctuation") && capture.text ? Array.from(capture.text.matchAll(BRACKETS)).map((match2) => startOffset + match2.index) : void 0;
      };
      const addCurrentTokenToArray = (capture, startOffset, endOffset, position) => {
        if (position !== void 0) {
          const oldScopes = endOffsetsAndScopes[position].scopes;
          let oldBracket = endOffsetsAndScopes[position].bracket;
          const prevEndOffset = position > 0 ? endOffsetsAndScopes[position - 1].endOffset : 0;
          if (prevEndOffset !== startOffset) {
            let preInsertBracket = void 0;
            if (oldBracket && oldBracket.length > 0) {
              preInsertBracket = [];
              const postInsertBracket = [];
              for (let i2 = 0; i2 < oldBracket.length; i2++) {
                const bracket = oldBracket[i2];
                if (bracket < startOffset) {
                  preInsertBracket.push(bracket);
                } else if (bracket > endOffset) {
                  postInsertBracket.push(bracket);
                }
              }
              if (preInsertBracket.length === 0) {
                preInsertBracket = void 0;
              }
              if (postInsertBracket.length === 0) {
                oldBracket = void 0;
              } else {
                oldBracket = postInsertBracket;
              }
            }
            endOffsetsAndScopes.splice(position, 0, { endOffset: startOffset, scopes: [...oldScopes], bracket: preInsertBracket, encodedLanguageId: capture.encodedLanguageId });
            position++;
            increaseSizeOfTokensByOneToken();
            tokenIndex++;
          }
          endOffsetsAndScopes.splice(position, 0, { endOffset, scopes: [...oldScopes, capture.name], bracket: brackets(capture, startOffset), encodedLanguageId: capture.encodedLanguageId });
          endOffsetsAndScopes[tokenIndex].bracket = oldBracket;
        } else {
          endOffsetsAndScopes[tokenIndex] = { endOffset, scopes: [baseScope, capture.name], bracket: brackets(capture, startOffset), encodedLanguageId: capture.encodedLanguageId };
        }
        tokenIndex++;
      };
      for (let captureIndex = 0; captureIndex < captures.length; captureIndex++) {
        const capture = captures[captureIndex];
        const tokenEndIndex = capture.node.endIndex < rangeEndOffset ? capture.node.endIndex < rangeStartOffset ? rangeStartOffset : capture.node.endIndex : rangeEndOffset;
        const tokenStartIndex = capture.node.startIndex < rangeStartOffset ? rangeStartOffset : capture.node.startIndex;
        const endOffset = tokenEndIndex - rangeStartOffset;
        let previousEndOffset;
        const currentTokenLength = tokenEndIndex - tokenStartIndex;
        if (captureIndex > 0) {
          previousEndOffset = endOffsetsAndScopes[tokenIndex - 1].endOffset;
        } else {
          previousEndOffset = tokenStartIndex - rangeStartOffset - 1;
        }
        const startOffset = endOffset - currentTokenLength;
        if (previousEndOffset >= 0 && previousEndOffset < startOffset) {
          endOffsetsAndScopes[tokenIndex] = { endOffset: startOffset, scopes: [baseScope], encodedLanguageId: this._encodedLanguageId };
          tokenIndex++;
          increaseSizeOfTokensByOneToken();
        }
        if (currentTokenLength < 0) {
          continue;
        }
        if (previousEndOffset >= endOffset) {
          let withinTokenIndex = tokenIndex - 1;
          let previousTokenEndOffset = endOffsetsAndScopes[withinTokenIndex].endOffset;
          let previousTokenStartOffset = withinTokenIndex >= 2 ? endOffsetsAndScopes[withinTokenIndex - 1].endOffset : 0;
          do {
            if (previousTokenStartOffset + currentTokenLength === previousTokenEndOffset) {
              if (previousTokenStartOffset === startOffset) {
                endOffsetsAndScopes[withinTokenIndex].scopes.push(capture.name);
                const oldBracket = endOffsetsAndScopes[withinTokenIndex].bracket;
                endOffsetsAndScopes[withinTokenIndex].bracket = oldBracket && oldBracket.length > 0 ? oldBracket : brackets(capture, startOffset);
              }
            } else if (previousTokenStartOffset <= startOffset) {
              addCurrentTokenToArray(capture, startOffset, endOffset, withinTokenIndex);
              break;
            }
            withinTokenIndex--;
            previousTokenStartOffset = withinTokenIndex >= 1 ? endOffsetsAndScopes[withinTokenIndex - 1].endOffset : 0;
            previousTokenEndOffset = withinTokenIndex >= 0 ? endOffsetsAndScopes[withinTokenIndex].endOffset : 0;
          } while (previousTokenEndOffset > startOffset);
        } else {
          addCurrentTokenToArray(capture, startOffset, endOffset);
        }
      }
      if (endOffsetsAndScopes[tokenIndex - 1].endOffset < rangeLength) {
        if (rangeLength - endOffsetsAndScopes[tokenIndex - 1].endOffset > 0) {
          increaseSizeOfTokensByOneToken();
          endOffsetsAndScopes[tokenIndex] = { endOffset: rangeLength, scopes: endOffsetsAndScopes[tokenIndex].scopes, encodedLanguageId: this._encodedLanguageId };
          tokenIndex++;
        }
      }
      for (let i2 = 0; i2 < endOffsetsAndScopes.length; i2++) {
        const token = endOffsetsAndScopes[i2];
        if (token.endOffset === 0 && i2 !== 0) {
          endOffsetsAndScopes.splice(i2, endOffsetsAndScopes.length - i2);
          break;
        }
      }
      const captureTime = stopwatch.elapsed();
      return { endOffsets: endOffsetsAndScopes, captureTime };
    }
    _getInjectionCaptures(parentCapture, range2) {
      return [];
    }
    _tokenizeCapturesWithMetadata(captures, rangeStartOffset, rangeEndOffset) {
      const stopwatch = StopWatch.create();
      const emptyTokens = this._createTokensFromCaptures(captures, rangeStartOffset, rangeEndOffset);
      if (!emptyTokens) {
        return void 0;
      }
      const endOffsetsAndScopes = emptyTokens.endOffsets;
      for (let i2 = 0; i2 < endOffsetsAndScopes.length; i2++) {
        const token = endOffsetsAndScopes[i2];
        token.metadata = this._treeSitterThemeService.findMetadata(token.scopes, token.encodedLanguageId, !!token.bracket && token.bracket.length > 0, void 0);
      }
      const metadataTime = stopwatch.elapsed();
      return { endOffsetsAndMetadata: endOffsetsAndScopes, captureTime: emptyTokens.captureTime, metadataTime };
    }
    _tokenizeEncoded(lineNumber) {
      const lineOffset = this._textModel.getOffsetAt({ lineNumber, column: 1 });
      const maxLine = this._textModel.getLineCount();
      const lineEndOffset = lineNumber + 1 <= maxLine ? this._textModel.getOffsetAt({ lineNumber: lineNumber + 1, column: 1 }) : this._textModel.getValueLength();
      const lineLength = lineEndOffset - lineOffset;
      const result = this._tokenize(new Range$2(lineNumber, 1, lineNumber, lineLength + 1), lineOffset, lineEndOffset);
      if (!result) {
        return void 0;
      }
      return { result: result.endOffsetsAndMetadata, captureTime: result.captureTime, metadataTime: result.metadataTime, versionId: result.versionId };
    }
    _endOffsetTokensToUint32Array(endOffsetsAndMetadata) {
      const uint32Array = new Uint32Array(endOffsetsAndMetadata.length * 2);
      for (let i2 = 0; i2 < endOffsetsAndMetadata.length; i2++) {
        uint32Array[i2 * 2] = endOffsetsAndMetadata[i2].endOffset;
        uint32Array[i2 * 2 + 1] = endOffsetsAndMetadata[i2].metadata;
      }
      return uint32Array;
    }
  };
  TreeSitterTokenizationImpl = __decorate$2O([
    __param$2J(4, ITreeSitterThemeService)
  ], TreeSitterTokenizationImpl);
  const TREESITTER_BASE_SCOPES = {
    "css": "source.css",
    "typescript": "source.ts",
    "ini": "source.ini",
    "regex": "source.regex"
  };
  const BRACKETS = /[\{\}\[\]\<\>\(\)]/g;
  const ITreeSitterLibraryService = createDecorator("treeSitterLibraryService");
  var __decorate$2N = 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$2I = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  let TreeSitterSyntaxTokenBackend = class TreeSitterSyntaxTokenBackend extends AbstractSyntaxTokenBackend {
    constructor(_languageIdObs, languageIdCodec, textModel, visibleLineRanges, _treeSitterLibraryService, _instantiationService) {
      super(languageIdCodec, textModel);
      this._languageIdObs = _languageIdObs;
      this._treeSitterLibraryService = _treeSitterLibraryService;
      this._instantiationService = _instantiationService;
      this._backgroundTokenizationState = 1;
      this._onDidChangeBackgroundTokenizationState = this._register(new Emitter$1());
      this.onDidChangeBackgroundTokenizationState = this._onDidChangeBackgroundTokenizationState.event;
      const parserClassPromise = new ObservablePromise(this._treeSitterLibraryService.getParserClass());
      const parserClassObs = derived(this, (reader) => {
        const parser = parserClassPromise.promiseResult?.read(reader)?.getDataOrThrow();
        return parser;
      });
      this._tree = derived(this, (reader) => {
        const parserClass = parserClassObs.read(reader);
        if (!parserClass) {
          return void 0;
        }
        const currentLanguage = this._languageIdObs.read(reader);
        const treeSitterLang = this._treeSitterLibraryService.getLanguage(currentLanguage, false, reader);
        if (!treeSitterLang) {
          return void 0;
        }
        const parser = new parserClass();
        reader.store.add(toDisposable(() => {
          parser.delete();
        }));
        parser.setLanguage(treeSitterLang);
        const queries = this._treeSitterLibraryService.getInjectionQueries(currentLanguage, reader);
        if (queries === void 0) {
          return void 0;
        }
        return reader.store.add(this._instantiationService.createInstance(
          TreeSitterTree,
          currentLanguage,
          void 0,
          parser,
          parserClass,
          /*queries, */
          this._textModel
        ));
      });
      this._tokenizationImpl = derived(this, (reader) => {
        const treeModel = this._tree.read(reader);
        if (!treeModel) {
          return void 0;
        }
        const queries = this._treeSitterLibraryService.getHighlightingQueries(treeModel.languageId, reader);
        if (!queries) {
          return void 0;
        }
        return reader.store.add(this._instantiationService.createInstance(TreeSitterTokenizationImpl, treeModel, queries, this._languageIdCodec, visibleLineRanges));
      });
      this._register(autorun((reader) => {
        const tokModel = this._tokenizationImpl.read(reader);
        if (!tokModel) {
          return;
        }
        reader.store.add(tokModel.onDidChangeTokens((e) => {
          this._onDidChangeTokens.fire(e.changes);
        }));
        reader.store.add(tokModel.onDidChangeBackgroundTokenization((e) => {
          this._backgroundTokenizationState = 2;
          this._onDidChangeBackgroundTokenizationState.fire();
        }));
      }));
    }
    getLineTokens(lineNumber) {
      const model = this._tokenizationImpl.get();
      if (!model) {
        const content = this._textModel.getLineContent(lineNumber);
        return LineTokens.createEmpty(content, this._languageIdCodec);
      }
      return model.getLineTokens(lineNumber);
    }
    todo_resetTokenization(fireTokenChangeEvent = true) {
      if (fireTokenChangeEvent) {
        this._onDidChangeTokens.fire({
          semanticTokensApplied: false,
          ranges: [
            {
              fromLineNumber: 1,
              toLineNumber: this._textModel.getLineCount()
            }
          ]
        });
      }
    }
    handleDidChangeAttached() {
    }
    handleDidChangeContent(e) {
      if (e.isFlush) {
        this.todo_resetTokenization(false);
      } else {
        const model = this._tokenizationImpl.get();
        model?.handleContentChanged(e);
      }
      const treeModel = this._tree.get();
      treeModel?.handleContentChange(e);
    }
    forceTokenization(lineNumber) {
      const model = this._tokenizationImpl.get();
      if (!model) {
        return;
      }
      if (!model.hasAccurateTokensForLine(lineNumber)) {
        model.tokenizeEncoded(lineNumber);
      }
    }
    hasAccurateTokensForLine(lineNumber) {
      const model = this._tokenizationImpl.get();
      if (!model) {
        return false;
      }
      return model.hasAccurateTokensForLine(lineNumber);
    }
    isCheapToTokenize(lineNumber) {
      return true;
    }
    getTokenTypeIfInsertingCharacter(lineNumber, column, character) {
      return 0;
    }
    tokenizeLinesAt(lineNumber, lines) {
      const model = this._tokenizationImpl.get();
      if (!model) {
        return null;
      }
      return model.tokenizeLinesAt(lineNumber, lines);
    }
    get hasTokens() {
      const model = this._tokenizationImpl.get();
      if (!model) {
        return false;
      }
      return model.hasTokens();
    }
  };
  TreeSitterSyntaxTokenBackend = __decorate$2N([
    __param$2I(4, ITreeSitterLibraryService),
    __param$2I(5, IInstantiationService)
  ], TreeSitterSyntaxTokenBackend);
  class SparseTokensStore {
    constructor(languageIdCodec) {
      this._pieces = [];
      this._isComplete = false;
      this._languageIdCodec = languageIdCodec;
    }
    flush() {
      this._pieces = [];
      this._isComplete = false;
    }
    isEmpty() {
      return this._pieces.length === 0;
    }
    set(pieces, isComplete, textModel = void 0) {
      this._pieces = pieces || [];
      this._isComplete = isComplete;
      if (textModel) {
        for (const p of this._pieces) {
          p.reportIfInvalid(textModel);
        }
      }
    }
    setPartial(_range, pieces) {
      let range2 = _range;
      if (pieces.length > 0) {
        const _firstRange = pieces[0].getRange();
        const _lastRange = pieces[pieces.length - 1].getRange();
        if (!_firstRange || !_lastRange) {
          return _range;
        }
        range2 = _range.plusRange(_firstRange).plusRange(_lastRange);
      }
      let insertPosition = null;
      for (let i2 = 0, len = this._pieces.length; i2 < len; i2++) {
        const piece = this._pieces[i2];
        if (piece.endLineNumber < range2.startLineNumber) {
          continue;
        }
        if (piece.startLineNumber > range2.endLineNumber) {
          insertPosition = insertPosition || { index: i2 };
          break;
        }
        piece.removeTokens(range2);
        if (piece.isEmpty()) {
          this._pieces.splice(i2, 1);
          i2--;
          len--;
          continue;
        }
        if (piece.endLineNumber < range2.startLineNumber) {
          continue;
        }
        if (piece.startLineNumber > range2.endLineNumber) {
          insertPosition = insertPosition || { index: i2 };
          continue;
        }
        const [a, b] = piece.split(range2);
        if (a.isEmpty()) {
          insertPosition = insertPosition || { index: i2 };
          continue;
        }
        if (b.isEmpty()) {
          continue;
        }
        this._pieces.splice(i2, 1, a, b);
        i2++;
        len++;
        insertPosition = insertPosition || { index: i2 };
      }
      insertPosition = insertPosition || { index: this._pieces.length };
      if (pieces.length > 0) {
        this._pieces = arrayInsert(this._pieces, insertPosition.index, pieces);
      }
      return range2;
    }
    isComplete() {
      return this._isComplete;
    }
    addSparseTokens(lineNumber, aTokens) {
      if (aTokens.getTextLength() === 0) {
        return aTokens;
      }
      const pieces = this._pieces;
      if (pieces.length === 0) {
        return aTokens;
      }
      const pieceIndex = SparseTokensStore._findFirstPieceWithLine(pieces, lineNumber);
      const bTokens = pieces[pieceIndex].getLineTokens(lineNumber);
      if (!bTokens) {
        return aTokens;
      }
      const aLen = aTokens.getCount();
      const bLen = bTokens.getCount();
      let aIndex = 0;
      const result = [];
      let resultLen = 0;
      let lastEndOffset = 0;
      const emitToken = (endOffset, metadata) => {
        if (endOffset === lastEndOffset) {
          return;
        }
        lastEndOffset = endOffset;
        result[resultLen++] = endOffset;
        result[resultLen++] = metadata;
      };
      for (let bIndex = 0; bIndex < bLen; bIndex++) {
        const bStartCharacter = Math.min(bTokens.getStartCharacter(bIndex), aTokens.getTextLength());
        const bEndCharacter = Math.min(bTokens.getEndCharacter(bIndex), aTokens.getTextLength());
        const bMetadata = bTokens.getMetadata(bIndex);
        const bMask = ((bMetadata & 1 ? 2048 : 0) | (bMetadata & 2 ? 4096 : 0) | (bMetadata & 4 ? 8192 : 0) | (bMetadata & 8 ? 16384 : 0) | (bMetadata & 16 ? 16744448 : 0) | (bMetadata & 32 ? 4278190080 : 0)) >>> 0;
        const aMask = ~bMask >>> 0;
        while (aIndex < aLen && aTokens.getEndOffset(aIndex) <= bStartCharacter) {
          emitToken(aTokens.getEndOffset(aIndex), aTokens.getMetadata(aIndex));
          aIndex++;
        }
        if (aIndex < aLen && aTokens.getStartOffset(aIndex) < bStartCharacter) {
          emitToken(bStartCharacter, aTokens.getMetadata(aIndex));
        }
        while (aIndex < aLen && aTokens.getEndOffset(aIndex) < bEndCharacter) {
          emitToken(aTokens.getEndOffset(aIndex), aTokens.getMetadata(aIndex) & aMask | bMetadata & bMask);
          aIndex++;
        }
        if (aIndex < aLen) {
          emitToken(bEndCharacter, aTokens.getMetadata(aIndex) & aMask | bMetadata & bMask);
          if (aTokens.getEndOffset(aIndex) === bEndCharacter) {
            aIndex++;
          }
        } else {
          const aMergeIndex = Math.min(Math.max(0, aIndex - 1), aLen - 1);
          emitToken(bEndCharacter, aTokens.getMetadata(aMergeIndex) & aMask | bMetadata & bMask);
        }
      }
      while (aIndex < aLen) {
        emitToken(aTokens.getEndOffset(aIndex), aTokens.getMetadata(aIndex));
        aIndex++;
      }
      return new LineTokens(new Uint32Array(result), aTokens.getLineContent(), this._languageIdCodec);
    }
    static _findFirstPieceWithLine(pieces, lineNumber) {
      let low = 0;
      let high = pieces.length - 1;
      while (low < high) {
        let mid = low + Math.floor((high - low) / 2);
        if (pieces[mid].endLineNumber < lineNumber) {
          low = mid + 1;
        } else if (pieces[mid].startLineNumber > lineNumber) {
          high = mid - 1;
        } else {
          while (mid > low && pieces[mid - 1].startLineNumber <= lineNumber && lineNumber <= pieces[mid - 1].endLineNumber) {
            mid--;
          }
          return mid;
        }
      }
      return low;
    }
    acceptEdit(range2, eolCount, firstLineLength, lastLineLength, firstCharCode) {
      for (let i2 = 0; i2 < this._pieces.length; i2++) {
        const piece = this._pieces[i2];
        piece.acceptEdit(range2, eolCount, firstLineLength, lastLineLength, firstCharCode);
        if (piece.isEmpty()) {
          this._pieces.splice(i2, 1);
          i2--;
        }
      }
    }
  }
  const EMPTY_LINE_TOKENS = new Uint32Array(0).buffer;
  class ContiguousTokensEditing {
    static deleteBeginning(lineTokens, toChIndex) {
      if (lineTokens === null || lineTokens === EMPTY_LINE_TOKENS) {
        return lineTokens;
      }
      return ContiguousTokensEditing.delete(lineTokens, 0, toChIndex);
    }
    static deleteEnding(lineTokens, fromChIndex) {
      if (lineTokens === null || lineTokens === EMPTY_LINE_TOKENS) {
        return lineTokens;
      }
      const tokens = toUint32Array(lineTokens);
      const lineTextLength = tokens[tokens.length - 2];
      return ContiguousTokensEditing.delete(lineTokens, fromChIndex, lineTextLength);
    }
    static delete(lineTokens, fromChIndex, toChIndex) {
      if (lineTokens === null || lineTokens === EMPTY_LINE_TOKENS || fromChIndex === toChIndex) {
        return lineTokens;
      }
      const tokens = toUint32Array(lineTokens);
      const tokensCount = tokens.length >>> 1;
      if (fromChIndex === 0 && tokens[tokens.length - 2] === toChIndex) {
        return EMPTY_LINE_TOKENS;
      }
      const fromTokenIndex = LineTokens.findIndexInTokensArray(tokens, fromChIndex);
      const fromTokenStartOffset = fromTokenIndex > 0 ? tokens[fromTokenIndex - 1 << 1] : 0;
      const fromTokenEndOffset = tokens[fromTokenIndex << 1];
      if (toChIndex < fromTokenEndOffset) {
        const delta2 = toChIndex - fromChIndex;
        for (let i2 = fromTokenIndex; i2 < tokensCount; i2++) {
          tokens[i2 << 1] -= delta2;
        }
        return lineTokens;
      }
      let dest;
      let lastEnd;
      if (fromTokenStartOffset !== fromChIndex) {
        tokens[fromTokenIndex << 1] = fromChIndex;
        dest = fromTokenIndex + 1 << 1;
        lastEnd = fromChIndex;
      } else {
        dest = fromTokenIndex << 1;
        lastEnd = fromTokenStartOffset;
      }
      const delta = toChIndex - fromChIndex;
      for (let tokenIndex = fromTokenIndex + 1; tokenIndex < tokensCount; tokenIndex++) {
        const tokenEndOffset = tokens[tokenIndex << 1] - delta;
        if (tokenEndOffset > lastEnd) {
          tokens[dest++] = tokenEndOffset;
          tokens[dest++] = tokens[(tokenIndex << 1) + 1];
          lastEnd = tokenEndOffset;
        }
      }
      if (dest === tokens.length) {
        return lineTokens;
      }
      const tmp = new Uint32Array(dest);
      tmp.set(tokens.subarray(0, dest), 0);
      return tmp.buffer;
    }
    static append(lineTokens, _otherTokens) {
      if (_otherTokens === EMPTY_LINE_TOKENS) {
        return lineTokens;
      }
      if (lineTokens === EMPTY_LINE_TOKENS) {
        return _otherTokens;
      }
      if (lineTokens === null) {
        return lineTokens;
      }
      if (_otherTokens === null) {
        return null;
      }
      const myTokens = toUint32Array(lineTokens);
      const otherTokens = toUint32Array(_otherTokens);
      const otherTokensCount = otherTokens.length >>> 1;
      const result = new Uint32Array(myTokens.length + otherTokens.length);
      result.set(myTokens, 0);
      let dest = myTokens.length;
      const delta = myTokens[myTokens.length - 2];
      for (let i2 = 0; i2 < otherTokensCount; i2++) {
        result[dest++] = otherTokens[i2 << 1] + delta;
        result[dest++] = otherTokens[(i2 << 1) + 1];
      }
      return result.buffer;
    }
    static insert(lineTokens, chIndex, textLength) {
      if (lineTokens === null || lineTokens === EMPTY_LINE_TOKENS) {
        return lineTokens;
      }
      const tokens = toUint32Array(lineTokens);
      const tokensCount = tokens.length >>> 1;
      let fromTokenIndex = LineTokens.findIndexInTokensArray(tokens, chIndex);
      if (fromTokenIndex > 0) {
        const fromTokenStartOffset = tokens[fromTokenIndex - 1 << 1];
        if (fromTokenStartOffset === chIndex) {
          fromTokenIndex--;
        }
      }
      for (let tokenIndex = fromTokenIndex; tokenIndex < tokensCount; tokenIndex++) {
        tokens[tokenIndex << 1] += textLength;
      }
      return lineTokens;
    }
  }
  function toUint32Array(arr) {
    if (arr instanceof Uint32Array) {
      return arr;
    } else {
      return new Uint32Array(arr);
    }
  }
  class ContiguousTokensStore {
    constructor(languageIdCodec) {
      this._lineTokens = [];
      this._len = 0;
      this._languageIdCodec = languageIdCodec;
    }
    flush() {
      this._lineTokens = [];
      this._len = 0;
    }
    get hasTokens() {
      return this._lineTokens.length > 0;
    }
    getTokens(topLevelLanguageId, lineIndex, lineText) {
      let rawLineTokens = null;
      if (lineIndex < this._len) {
        rawLineTokens = this._lineTokens[lineIndex];
      }
      if (rawLineTokens !== null && rawLineTokens !== EMPTY_LINE_TOKENS) {
        return new LineTokens(toUint32Array(rawLineTokens), lineText, this._languageIdCodec);
      }
      const lineTokens = new Uint32Array(2);
      lineTokens[0] = lineText.length;
      lineTokens[1] = getDefaultMetadata(this._languageIdCodec.encodeLanguageId(topLevelLanguageId));
      return new LineTokens(lineTokens, lineText, this._languageIdCodec);
    }
    static _massageTokens(topLevelLanguageId, lineTextLength, _tokens) {
      const tokens = _tokens ? toUint32Array(_tokens) : null;
      if (lineTextLength === 0) {
        let hasDifferentLanguageId = false;
        if (tokens && tokens.length > 1) {
          hasDifferentLanguageId = TokenMetadata.getLanguageId(tokens[1]) !== topLevelLanguageId;
        }
        if (!hasDifferentLanguageId) {
          return EMPTY_LINE_TOKENS;
        }
      }
      if (!tokens || tokens.length === 0) {
        const tokens2 = new Uint32Array(2);
        tokens2[0] = lineTextLength;
        tokens2[1] = getDefaultMetadata(topLevelLanguageId);
        return tokens2.buffer;
      }
      tokens[tokens.length - 2] = lineTextLength;
      if (tokens.byteOffset === 0 && tokens.byteLength === tokens.buffer.byteLength) {
        return tokens.buffer;
      }
      return tokens;
    }
    _ensureLine(lineIndex) {
      while (lineIndex >= this._len) {
        this._lineTokens[this._len] = null;
        this._len++;
      }
    }
    _deleteLines(start, deleteCount) {
      if (deleteCount === 0) {
        return;
      }
      if (start + deleteCount > this._len) {
        deleteCount = this._len - start;
      }
      this._lineTokens.splice(start, deleteCount);
      this._len -= deleteCount;
    }
    _insertLines(insertIndex, insertCount) {
      if (insertCount === 0) {
        return;
      }
      const lineTokens = [];
      for (let i2 = 0; i2 < insertCount; i2++) {
        lineTokens[i2] = null;
      }
      this._lineTokens = arrayInsert(this._lineTokens, insertIndex, lineTokens);
      this._len += insertCount;
    }
    setTokens(topLevelLanguageId, lineIndex, lineTextLength, _tokens, checkEquality) {
      const tokens = ContiguousTokensStore._massageTokens(this._languageIdCodec.encodeLanguageId(topLevelLanguageId), lineTextLength, _tokens);
      this._ensureLine(lineIndex);
      const oldTokens = this._lineTokens[lineIndex];
      this._lineTokens[lineIndex] = tokens;
      if (checkEquality) {
        return !ContiguousTokensStore._equals(oldTokens, tokens);
      }
      return false;
    }
    static _equals(_a3, _b3) {
      if (!_a3 || !_b3) {
        return !_a3 && !_b3;
      }
      const a = toUint32Array(_a3);
      const b = toUint32Array(_b3);
      if (a.length !== b.length) {
        return false;
      }
      for (let i2 = 0, len = a.length; i2 < len; i2++) {
        if (a[i2] !== b[i2]) {
          return false;
        }
      }
      return true;
    }
    //#region Editing
    acceptEdit(range2, eolCount, firstLineLength) {
      this._acceptDeleteRange(range2);
      this._acceptInsertText(new Position$1(range2.startLineNumber, range2.startColumn), eolCount, firstLineLength);
    }
    _acceptDeleteRange(range2) {
      const firstLineIndex = range2.startLineNumber - 1;
      if (firstLineIndex >= this._len) {
        return;
      }
      if (range2.startLineNumber === range2.endLineNumber) {
        if (range2.startColumn === range2.endColumn) {
          return;
        }
        this._lineTokens[firstLineIndex] = ContiguousTokensEditing.delete(this._lineTokens[firstLineIndex], range2.startColumn - 1, range2.endColumn - 1);
        return;
      }
      this._lineTokens[firstLineIndex] = ContiguousTokensEditing.deleteEnding(this._lineTokens[firstLineIndex], range2.startColumn - 1);
      const lastLineIndex = range2.endLineNumber - 1;
      let lastLineTokens = null;
      if (lastLineIndex < this._len) {
        lastLineTokens = ContiguousTokensEditing.deleteBeginning(this._lineTokens[lastLineIndex], range2.endColumn - 1);
      }
      this._lineTokens[firstLineIndex] = ContiguousTokensEditing.append(this._lineTokens[firstLineIndex], lastLineTokens);
      this._deleteLines(range2.startLineNumber, range2.endLineNumber - range2.startLineNumber);
    }
    _acceptInsertText(position, eolCount, firstLineLength) {
      if (eolCount === 0 && firstLineLength === 0) {
        return;
      }
      const lineIndex = position.lineNumber - 1;
      if (lineIndex >= this._len) {
        return;
      }
      if (eolCount === 0) {
        this._lineTokens[lineIndex] = ContiguousTokensEditing.insert(this._lineTokens[lineIndex], position.column - 1, firstLineLength);
        return;
      }
      this._lineTokens[lineIndex] = ContiguousTokensEditing.deleteEnding(this._lineTokens[lineIndex], position.column - 1);
      this._lineTokens[lineIndex] = ContiguousTokensEditing.insert(this._lineTokens[lineIndex], position.column - 1, firstLineLength);
      this._insertLines(position.lineNumber, eolCount);
    }
    //#endregion
    setMultilineTokens(tokens, textModel) {
      if (tokens.length === 0) {
        return { changes: [] };
      }
      const ranges = [];
      for (let i2 = 0, len = tokens.length; i2 < len; i2++) {
        const element = tokens[i2];
        let minChangedLineNumber = 0;
        let maxChangedLineNumber = 0;
        let hasChange = false;
        for (let lineNumber = element.startLineNumber; lineNumber <= element.endLineNumber; lineNumber++) {
          if (hasChange) {
            this.setTokens(textModel.getLanguageId(), lineNumber - 1, textModel.getLineLength(lineNumber), element.getLineTokens(lineNumber), false);
            maxChangedLineNumber = lineNumber;
          } else {
            const lineHasChange = this.setTokens(textModel.getLanguageId(), lineNumber - 1, textModel.getLineLength(lineNumber), element.getLineTokens(lineNumber), true);
            if (lineHasChange) {
              hasChange = true;
              minChangedLineNumber = lineNumber;
              maxChangedLineNumber = lineNumber;
            }
          }
        }
        if (hasChange) {
          ranges.push({ fromLineNumber: minChangedLineNumber, toLineNumber: maxChangedLineNumber });
        }
      }
      return { changes: ranges };
    }
  }
  function getDefaultMetadata(topLevelLanguageId) {
    return (topLevelLanguageId << 0 | 0 << 8 | 0 << 11 | 1 << 15 | 2 << 24 | 1024) >>> 0;
  }
  class TokenizerSyntaxTokenBackend extends AbstractSyntaxTokenBackend {
    constructor(languageIdCodec, textModel, getLanguageId, attachedViews) {
      super(languageIdCodec, textModel);
      this.getLanguageId = getLanguageId;
      this._tokenizer = null;
      this._backgroundTokenizationState = 1;
      this._onDidChangeBackgroundTokenizationState = this._register(new Emitter$1());
      this.onDidChangeBackgroundTokenizationState = this._onDidChangeBackgroundTokenizationState.event;
      this._defaultBackgroundTokenizer = null;
      this._backgroundTokenizer = this._register(new MutableDisposable());
      this._tokens = new ContiguousTokensStore(this._languageIdCodec);
      this._debugBackgroundTokenizer = this._register(new MutableDisposable());
      this._attachedViewStates = this._register(new DisposableMap());
      this._register(TokenizationRegistry.onDidChange((e) => {
        const languageId = this.getLanguageId();
        if (e.changedLanguages.indexOf(languageId) === -1) {
          return;
        }
        this.todo_resetTokenization();
      }));
      this.todo_resetTokenization();
      this._register(attachedViews.onDidChangeVisibleRanges(({ view, state }) => {
        if (state) {
          let existing = this._attachedViewStates.get(view);
          if (!existing) {
            existing = new AttachedViewHandler(() => this.refreshRanges(existing.lineRanges));
            this._attachedViewStates.set(view, existing);
          }
          existing.handleStateChange(state);
        } else {
          this._attachedViewStates.deleteAndDispose(view);
        }
      }));
    }
    todo_resetTokenization(fireTokenChangeEvent = true) {
      this._tokens.flush();
      this._debugBackgroundTokens?.flush();
      if (this._debugBackgroundStates) {
        this._debugBackgroundStates = new TrackingTokenizationStateStore(this._textModel.getLineCount());
      }
      if (fireTokenChangeEvent) {
        this._onDidChangeTokens.fire({
          semanticTokensApplied: false,
          ranges: [
            {
              fromLineNumber: 1,
              toLineNumber: this._textModel.getLineCount()
            }
          ]
        });
      }
      const initializeTokenization = () => {
        if (this._textModel.isTooLargeForTokenization()) {
          return [null, null];
        }
        const tokenizationSupport2 = TokenizationRegistry.get(this.getLanguageId());
        if (!tokenizationSupport2) {
          return [null, null];
        }
        let initialState2;
        try {
          initialState2 = tokenizationSupport2.getInitialState();
        } catch (e) {
          onUnexpectedError(e);
          return [null, null];
        }
        return [tokenizationSupport2, initialState2];
      };
      const [tokenizationSupport, initialState] = initializeTokenization();
      if (tokenizationSupport && initialState) {
        this._tokenizer = new TokenizerWithStateStoreAndTextModel(this._textModel.getLineCount(), tokenizationSupport, this._textModel, this._languageIdCodec);
      } else {
        this._tokenizer = null;
      }
      this._backgroundTokenizer.clear();
      this._defaultBackgroundTokenizer = null;
      if (this._tokenizer) {
        const b = {
          setTokens: (tokens) => {
            this.setTokens(tokens);
          },
          backgroundTokenizationFinished: () => {
            if (this._backgroundTokenizationState === 2) {
              return;
            }
            const newState = 2;
            this._backgroundTokenizationState = newState;
            this._onDidChangeBackgroundTokenizationState.fire();
          },
          setEndState: (lineNumber, state) => {
            if (!this._tokenizer) {
              return;
            }
            const firstInvalidEndStateLineNumber = this._tokenizer.store.getFirstInvalidEndStateLineNumber();
            if (firstInvalidEndStateLineNumber !== null && lineNumber >= firstInvalidEndStateLineNumber) {
              this._tokenizer?.store.setEndState(lineNumber, state);
            }
          }
        };
        if (tokenizationSupport && tokenizationSupport.createBackgroundTokenizer && !tokenizationSupport.backgroundTokenizerShouldOnlyVerifyTokens) {
          this._backgroundTokenizer.value = tokenizationSupport.createBackgroundTokenizer(this._textModel, b);
        }
        if (!this._backgroundTokenizer.value && !this._textModel.isTooLargeForTokenization()) {
          this._backgroundTokenizer.value = this._defaultBackgroundTokenizer = new DefaultBackgroundTokenizer(this._tokenizer, b);
          this._defaultBackgroundTokenizer.handleChanges();
        }
        if (tokenizationSupport?.backgroundTokenizerShouldOnlyVerifyTokens && tokenizationSupport.createBackgroundTokenizer) {
          this._debugBackgroundTokens = new ContiguousTokensStore(this._languageIdCodec);
          this._debugBackgroundStates = new TrackingTokenizationStateStore(this._textModel.getLineCount());
          this._debugBackgroundTokenizer.clear();
          this._debugBackgroundTokenizer.value = tokenizationSupport.createBackgroundTokenizer(this._textModel, {
            setTokens: (tokens) => {
              this._debugBackgroundTokens?.setMultilineTokens(tokens, this._textModel);
            },
            backgroundTokenizationFinished() {
            },
            setEndState: (lineNumber, state) => {
              this._debugBackgroundStates?.setEndState(lineNumber, state);
            }
          });
        } else {
          this._debugBackgroundTokens = void 0;
          this._debugBackgroundStates = void 0;
          this._debugBackgroundTokenizer.value = void 0;
        }
      }
      this.refreshAllVisibleLineTokens();
    }
    handleDidChangeAttached() {
      this._defaultBackgroundTokenizer?.handleChanges();
    }
    handleDidChangeContent(e) {
      if (e.isFlush) {
        this.todo_resetTokenization(false);
      } else if (!e.isEolChange) {
        for (const c of e.changes) {
          const [eolCount, firstLineLength] = countEOL(c.text);
          this._tokens.acceptEdit(c.range, eolCount, firstLineLength);
          this._debugBackgroundTokens?.acceptEdit(c.range, eolCount, firstLineLength);
        }
        this._debugBackgroundStates?.acceptChanges(e.changes);
        if (this._tokenizer) {
          this._tokenizer.store.acceptChanges(e.changes);
        }
        this._defaultBackgroundTokenizer?.handleChanges();
      }
    }
    setTokens(tokens) {
      const { changes } = this._tokens.setMultilineTokens(tokens, this._textModel);
      if (changes.length > 0) {
        this._onDidChangeTokens.fire({ semanticTokensApplied: false, ranges: changes });
      }
      return { changes };
    }
    refreshAllVisibleLineTokens() {
      const ranges = LineRange.joinMany([...this._attachedViewStates].map(([_, s]) => s.lineRanges));
      this.refreshRanges(ranges);
    }
    refreshRanges(ranges) {
      for (const range2 of ranges) {
        this.refreshRange(range2.startLineNumber, range2.endLineNumberExclusive - 1);
      }
    }
    refreshRange(startLineNumber, endLineNumber) {
      if (!this._tokenizer) {
        return;
      }
      startLineNumber = Math.max(1, Math.min(this._textModel.getLineCount(), startLineNumber));
      endLineNumber = Math.min(this._textModel.getLineCount(), endLineNumber);
      const builder = new ContiguousMultilineTokensBuilder();
      const { heuristicTokens } = this._tokenizer.tokenizeHeuristically(builder, startLineNumber, endLineNumber);
      const changedTokens = this.setTokens(builder.finalize());
      if (heuristicTokens) {
        for (const c of changedTokens.changes) {
          this._backgroundTokenizer.value?.requestTokens(c.fromLineNumber, c.toLineNumber + 1);
        }
      }
      this._defaultBackgroundTokenizer?.checkFinished();
    }
    forceTokenization(lineNumber) {
      const builder = new ContiguousMultilineTokensBuilder();
      this._tokenizer?.updateTokensUntilLine(builder, lineNumber);
      this.setTokens(builder.finalize());
      this._defaultBackgroundTokenizer?.checkFinished();
    }
    hasAccurateTokensForLine(lineNumber) {
      if (!this._tokenizer) {
        return true;
      }
      return this._tokenizer.hasAccurateTokensForLine(lineNumber);
    }
    isCheapToTokenize(lineNumber) {
      if (!this._tokenizer) {
        return true;
      }
      return this._tokenizer.isCheapToTokenize(lineNumber);
    }
    getLineTokens(lineNumber) {
      const lineText = this._textModel.getLineContent(lineNumber);
      const result = this._tokens.getTokens(this._textModel.getLanguageId(), lineNumber - 1, lineText);
      if (this._debugBackgroundTokens && this._debugBackgroundStates && this._tokenizer) {
        if (this._debugBackgroundStates.getFirstInvalidEndStateLineNumberOrMax() > lineNumber && this._tokenizer.store.getFirstInvalidEndStateLineNumberOrMax() > lineNumber) {
          const backgroundResult = this._debugBackgroundTokens.getTokens(this._textModel.getLanguageId(), lineNumber - 1, lineText);
          if (!result.equals(backgroundResult) && this._debugBackgroundTokenizer.value?.reportMismatchingTokens) {
            this._debugBackgroundTokenizer.value.reportMismatchingTokens(lineNumber);
          }
        }
      }
      return result;
    }
    getTokenTypeIfInsertingCharacter(lineNumber, column, character) {
      if (!this._tokenizer) {
        return 0;
      }
      const position = this._textModel.validatePosition(new Position$1(lineNumber, column));
      this.forceTokenization(position.lineNumber);
      return this._tokenizer.getTokenTypeIfInsertingCharacter(position, character);
    }
    tokenizeLinesAt(lineNumber, lines) {
      if (!this._tokenizer) {
        return null;
      }
      this.forceTokenization(lineNumber);
      return this._tokenizer.tokenizeLinesAt(lineNumber, lines);
    }
    get hasTokens() {
      return this._tokens.hasTokens;
    }
  }
  var __decorate$2M = 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$2H = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  var TokenizationTextModelPart_1;
  let TokenizationTextModelPart = TokenizationTextModelPart_1 = class TokenizationTextModelPart extends TextModelPart {
    constructor(_textModel, _bracketPairsTextModelPart, _languageId, _attachedViews, _languageService, _languageConfigurationService, _instantiationService, _treeSitterLibraryService) {
      super();
      this._textModel = _textModel;
      this._bracketPairsTextModelPart = _bracketPairsTextModelPart;
      this._languageId = _languageId;
      this._attachedViews = _attachedViews;
      this._languageService = _languageService;
      this._languageConfigurationService = _languageConfigurationService;
      this._instantiationService = _instantiationService;
      this._treeSitterLibraryService = _treeSitterLibraryService;
      this._languageIdObs = observableValue(this, this._languageId);
      this._useTreeSitter = derived(this, (reader) => {
        const languageId = this._languageIdObs.read(reader);
        return this._treeSitterLibraryService.supportsLanguage(languageId, reader);
      });
      this.tokens = derived(this, (reader) => {
        let tokens;
        if (this._useTreeSitter.read(reader)) {
          tokens = reader.store.add(this._instantiationService.createInstance(TreeSitterSyntaxTokenBackend, this._languageIdObs, this._languageService.languageIdCodec, this._textModel, this._attachedViews.visibleLineRanges));
        } else {
          tokens = reader.store.add(new TokenizerSyntaxTokenBackend(this._languageService.languageIdCodec, this._textModel, () => this._languageId, this._attachedViews));
        }
        reader.store.add(tokens.onDidChangeTokens((e) => {
          this._emitModelTokensChangedEvent(e);
        }));
        reader.store.add(tokens.onDidChangeBackgroundTokenizationState((e) => {
          this._bracketPairsTextModelPart.handleDidChangeBackgroundTokenizationState();
        }));
        return tokens;
      });
      let hadTokens = false;
      this.tokens.recomputeInitiallyAndOnChange(this._store, (value) => {
        if (hadTokens) {
          value.todo_resetTokenization();
        }
        hadTokens = true;
      });
      this._semanticTokens = new SparseTokensStore(this._languageService.languageIdCodec);
      this._onDidChangeLanguage = this._register(new Emitter$1());
      this.onDidChangeLanguage = this._onDidChangeLanguage.event;
      this._onDidChangeLanguageConfiguration = this._register(new Emitter$1());
      this.onDidChangeLanguageConfiguration = this._onDidChangeLanguageConfiguration.event;
      this._onDidChangeTokens = this._register(new Emitter$1());
      this.onDidChangeTokens = this._onDidChangeTokens.event;
    }
    handleLanguageConfigurationServiceChange(e) {
      if (e.affects(this._languageId)) {
        this._onDidChangeLanguageConfiguration.fire({});
      }
    }
    handleDidChangeContent(e) {
      if (e.isFlush) {
        this._semanticTokens.flush();
      } else if (!e.isEolChange) {
        for (const c of e.changes) {
          const [eolCount, firstLineLength, lastLineLength] = countEOL(c.text);
          this._semanticTokens.acceptEdit(
            c.range,
            eolCount,
            firstLineLength,
            lastLineLength,
            c.text.length > 0 ? c.text.charCodeAt(0) : 0
            /* CharCode.Null */
          );
        }
      }
      this.tokens.get().handleDidChangeContent(e);
    }
    handleDidChangeAttached() {
      this.tokens.get().handleDidChangeAttached();
    }
    /**
     * Includes grammar and semantic tokens.
     */
    getLineTokens(lineNumber) {
      this.validateLineNumber(lineNumber);
      const syntacticTokens = this.tokens.get().getLineTokens(lineNumber);
      return this._semanticTokens.addSparseTokens(lineNumber, syntacticTokens);
    }
    _emitModelTokensChangedEvent(e) {
      if (!this._textModel._isDisposing()) {
        this._bracketPairsTextModelPart.handleDidChangeTokens(e);
        this._onDidChangeTokens.fire(e);
      }
    }
    // #region Grammar Tokens
    validateLineNumber(lineNumber) {
      if (lineNumber < 1 || lineNumber > this._textModel.getLineCount()) {
        throw new BugIndicatingError("Illegal value for lineNumber");
      }
    }
    get hasTokens() {
      return this.tokens.get().hasTokens;
    }
    resetTokenization() {
      this.tokens.get().todo_resetTokenization();
    }
    get backgroundTokenizationState() {
      return this.tokens.get().backgroundTokenizationState;
    }
    forceTokenization(lineNumber) {
      this.validateLineNumber(lineNumber);
      this.tokens.get().forceTokenization(lineNumber);
    }
    hasAccurateTokensForLine(lineNumber) {
      this.validateLineNumber(lineNumber);
      return this.tokens.get().hasAccurateTokensForLine(lineNumber);
    }
    isCheapToTokenize(lineNumber) {
      this.validateLineNumber(lineNumber);
      return this.tokens.get().isCheapToTokenize(lineNumber);
    }
    tokenizeIfCheap(lineNumber) {
      this.validateLineNumber(lineNumber);
      this.tokens.get().tokenizeIfCheap(lineNumber);
    }
    getTokenTypeIfInsertingCharacter(lineNumber, column, character) {
      return this.tokens.get().getTokenTypeIfInsertingCharacter(lineNumber, column, character);
    }
    tokenizeLinesAt(lineNumber, lines) {
      return this.tokens.get().tokenizeLinesAt(lineNumber, lines);
    }
    // #endregion
    // #region Semantic Tokens
    setSemanticTokens(tokens, isComplete) {
      this._semanticTokens.set(tokens, isComplete, this._textModel);
      this._emitModelTokensChangedEvent({
        semanticTokensApplied: tokens !== null,
        ranges: [{ fromLineNumber: 1, toLineNumber: this._textModel.getLineCount() }]
      });
    }
    hasCompleteSemanticTokens() {
      return this._semanticTokens.isComplete();
    }
    hasSomeSemanticTokens() {
      return !this._semanticTokens.isEmpty();
    }
    setPartialSemanticTokens(range2, tokens) {
      if (this.hasCompleteSemanticTokens()) {
        return;
      }
      const changedRange = this._textModel.validateRange(this._semanticTokens.setPartial(range2, tokens));
      this._emitModelTokensChangedEvent({
        semanticTokensApplied: true,
        ranges: [
          {
            fromLineNumber: changedRange.startLineNumber,
            toLineNumber: changedRange.endLineNumber
          }
        ]
      });
    }
    // #endregion
    // #region Utility Methods
    getWordAtPosition(_position) {
      this.assertNotDisposed();
      const position = this._textModel.validatePosition(_position);
      const lineContent = this._textModel.getLineContent(position.lineNumber);
      const lineTokens = this.getLineTokens(position.lineNumber);
      const tokenIndex = lineTokens.findTokenIndexAtOffset(position.column - 1);
      const [rbStartOffset, rbEndOffset] = TokenizationTextModelPart_1._findLanguageBoundaries(lineTokens, tokenIndex);
      const rightBiasedWord = getWordAtText(position.column, this.getLanguageConfiguration(lineTokens.getLanguageId(tokenIndex)).getWordDefinition(), lineContent.substring(rbStartOffset, rbEndOffset), rbStartOffset);
      if (rightBiasedWord && rightBiasedWord.startColumn <= _position.column && _position.column <= rightBiasedWord.endColumn) {
        return rightBiasedWord;
      }
      if (tokenIndex > 0 && rbStartOffset === position.column - 1) {
        const [lbStartOffset, lbEndOffset] = TokenizationTextModelPart_1._findLanguageBoundaries(lineTokens, tokenIndex - 1);
        const leftBiasedWord = getWordAtText(position.column, this.getLanguageConfiguration(lineTokens.getLanguageId(tokenIndex - 1)).getWordDefinition(), lineContent.substring(lbStartOffset, lbEndOffset), lbStartOffset);
        if (leftBiasedWord && leftBiasedWord.startColumn <= _position.column && _position.column <= leftBiasedWord.endColumn) {
          return leftBiasedWord;
        }
      }
      return null;
    }
    getLanguageConfiguration(languageId) {
      return this._languageConfigurationService.getLanguageConfiguration(languageId);
    }
    static _findLanguageBoundaries(lineTokens, tokenIndex) {
      const languageId = lineTokens.getLanguageId(tokenIndex);
      let startOffset = 0;
      for (let i2 = tokenIndex; i2 >= 0 && lineTokens.getLanguageId(i2) === languageId; i2--) {
        startOffset = lineTokens.getStartOffset(i2);
      }
      let endOffset = lineTokens.getLineContent().length;
      for (let i2 = tokenIndex, tokenCount = lineTokens.getCount(); i2 < tokenCount && lineTokens.getLanguageId(i2) === languageId; i2++) {
        endOffset = lineTokens.getEndOffset(i2);
      }
      return [startOffset, endOffset];
    }
    getWordUntilPosition(position) {
      const wordAtPosition = this.getWordAtPosition(position);
      if (!wordAtPosition) {
        return { word: "", startColumn: position.column, endColumn: position.column };
      }
      return {
        word: wordAtPosition.word.substr(0, position.column - wordAtPosition.startColumn),
        startColumn: wordAtPosition.startColumn,
        endColumn: position.column
      };
    }
    // #endregion
    // #region Language Id handling
    getLanguageId() {
      return this._languageId;
    }
    getLanguageIdAtPosition(lineNumber, column) {
      const position = this._textModel.validatePosition(new Position$1(lineNumber, column));
      const lineTokens = this.getLineTokens(position.lineNumber);
      return lineTokens.getLanguageId(lineTokens.findTokenIndexAtOffset(position.column - 1));
    }
    setLanguageId(languageId, source = "api") {
      if (this._languageId === languageId) {
        return;
      }
      const e = {
        oldLanguage: this._languageId,
        newLanguage: languageId,
        source
      };
      this._languageId = languageId;
      this._languageIdObs.set(languageId, void 0);
      this._bracketPairsTextModelPart.handleDidChangeLanguage(e);
      this._onDidChangeLanguage.fire(e);
      this._onDidChangeLanguageConfiguration.fire({});
    }
  };
  TokenizationTextModelPart = TokenizationTextModelPart_1 = __decorate$2M([
    __param$2H(4, ILanguageService),
    __param$2H(5, ILanguageConfigurationService),
    __param$2H(6, IInstantiationService),
    __param$2H(7, ITreeSitterLibraryService)
  ], TokenizationTextModelPart);
  const IUndoRedoService = createDecorator("undoRedoService");
  class ResourceEditStackSnapshot {
    constructor(resource, elements) {
      this.resource = resource;
      this.elements = elements;
    }
  }
  const _UndoRedoGroup = class _UndoRedoGroup {
    constructor() {
      this.id = _UndoRedoGroup._ID++;
      this.order = 1;
    }
    nextOrder() {
      if (this.id === 0) {
        return 0;
      }
      return this.order++;
    }
  };
  _UndoRedoGroup._ID = 0;
  _UndoRedoGroup.None = new _UndoRedoGroup();
  let UndoRedoGroup = _UndoRedoGroup;
  const _UndoRedoSource = class _UndoRedoSource {
    constructor() {
      this.id = _UndoRedoSource._ID++;
      this.order = 1;
    }
    nextOrder() {
      if (this.id === 0) {
        return 0;
      }
      return this.order++;
    }
  };
  _UndoRedoSource._ID = 0;
  _UndoRedoSource.None = new _UndoRedoSource();
  let UndoRedoSource = _UndoRedoSource;
  var _a;
  function groupByMap(data, groupFn) {
    const result = /* @__PURE__ */ new Map();
    for (const element of data) {
      const key = groupFn(element);
      let target = result.get(key);
      if (!target) {
        target = [];
        result.set(key, target);
      }
      target.push(element);
    }
    return result;
  }
  function diffSets(before, after2) {
    const removed = [];
    const added = [];
    for (const element of before) {
      if (!after2.has(element)) {
        removed.push(element);
      }
    }
    for (const element of after2) {
      if (!before.has(element)) {
        added.push(element);
      }
    }
    return { removed, added };
  }
  function intersection(setA, setB) {
    const result = /* @__PURE__ */ new Set();
    for (const elem of setB) {
      if (setA.has(elem)) {
        result.add(elem);
      }
    }
    return result;
  }
  class SetWithKey {
    constructor(values, toKey) {
      this.toKey = toKey;
      this._map = /* @__PURE__ */ new Map();
      this[_a] = "SetWithKey";
      for (const value of values) {
        this.add(value);
      }
    }
    get size() {
      return this._map.size;
    }
    add(value) {
      const key = this.toKey(value);
      this._map.set(key, value);
      return this;
    }
    delete(value) {
      return this._map.delete(this.toKey(value));
    }
    has(value) {
      return this._map.has(this.toKey(value));
    }
    *entries() {
      for (const entry of this._map.values()) {
        yield [entry, entry];
      }
    }
    keys() {
      return this.values();
    }
    *values() {
      for (const entry of this._map.values()) {
        yield entry;
      }
    }
    clear() {
      this._map.clear();
    }
    forEach(callbackfn, thisArg) {
      this._map.forEach((entry) => callbackfn.call(thisArg, entry, entry, this));
    }
    [Symbol.iterator]() {
      return this.values();
    }
  }
  _a = Symbol.toStringTag;
  var __decorate$2L = 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$2G = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  var TextModel_1;
  function createTextBufferFactory(text2) {
    const builder = new PieceTreeTextBufferBuilder();
    builder.acceptChunk(text2);
    return builder.finish();
  }
  function createTextBufferFactoryFromSnapshot(snapshot) {
    const builder = new PieceTreeTextBufferBuilder();
    let chunk;
    while (typeof (chunk = snapshot.read()) === "string") {
      builder.acceptChunk(chunk);
    }
    return builder.finish();
  }
  function createTextBuffer(value, defaultEOL) {
    let factory;
    if (typeof value === "string") {
      factory = createTextBufferFactory(value);
    } else if (isITextSnapshot(value)) {
      factory = createTextBufferFactoryFromSnapshot(value);
    } else {
      factory = value;
    }
    return factory.create(defaultEOL);
  }
  let MODEL_ID$1 = 0;
  const LIMIT_FIND_COUNT = 999;
  const LONG_LINE_BOUNDARY = 1e4;
  const LINE_HEIGHT_CEILING = 300;
  class TextModelSnapshot {
    constructor(source) {
      this._source = source;
      this._eos = false;
    }
    read() {
      if (this._eos) {
        return null;
      }
      const result = [];
      let resultCnt = 0;
      let resultLength = 0;
      do {
        const tmp = this._source.read();
        if (tmp === null) {
          this._eos = true;
          if (resultCnt === 0) {
            return null;
          } else {
            return result.join("");
          }
        }
        if (tmp.length > 0) {
          result[resultCnt++] = tmp;
          resultLength += tmp.length;
        }
        if (resultLength >= 64 * 1024) {
          return result.join("");
        }
      } while (true);
    }
  }
  const invalidFunc = () => {
    throw new Error(`Invalid change accessor`);
  };
  let TextModel = (_h = class extends Disposable {
    static resolveOptions(textBuffer, options) {
      if (options.detectIndentation) {
        const guessedIndentation = guessIndentation(textBuffer, options.tabSize, options.insertSpaces);
        return new TextModelResolvedOptions({
          tabSize: guessedIndentation.tabSize,
          indentSize: "tabSize",
          // TODO@Alex: guess indentSize independent of tabSize
          insertSpaces: guessedIndentation.insertSpaces,
          trimAutoWhitespace: options.trimAutoWhitespace,
          defaultEOL: options.defaultEOL,
          bracketPairColorizationOptions: options.bracketPairColorizationOptions
        });
      }
      return new TextModelResolvedOptions(options);
    }
    get onDidChangeLanguage() {
      return this._tokenizationTextModelPart.onDidChangeLanguage;
    }
    get onDidChangeLanguageConfiguration() {
      return this._tokenizationTextModelPart.onDidChangeLanguageConfiguration;
    }
    get onDidChangeTokens() {
      return this._tokenizationTextModelPart.onDidChangeTokens;
    }
    get onDidChangeOptions() {
      return this._onDidChangeOptions.event;
    }
    get onDidChangeAttached() {
      return this._onDidChangeAttached.event;
    }
    get onDidChangeLineHeight() {
      return this._onDidChangeLineHeight.event;
    }
    get onDidChangeFont() {
      return this._onDidChangeFont.event;
    }
    onDidChangeContent(listener) {
      return this._eventEmitter.slowEvent((e) => listener(e.contentChangedEvent));
    }
    onDidChangeContentOrInjectedText(listener) {
      return combinedDisposable(this._eventEmitter.fastEvent((e) => listener(e)), this._onDidChangeInjectedText.event((e) => listener(e)));
    }
    _isDisposing() {
      return this.__isDisposing;
    }
    get tokenization() {
      return this._tokenizationTextModelPart;
    }
    get bracketPairs() {
      return this._bracketPairs;
    }
    get guides() {
      return this._guidesTextModelPart;
    }
    constructor(source, languageIdOrSelection, creationOptions, associatedResource = null, _undoRedoService, _languageService, _languageConfigurationService, instantiationService) {
      super();
      this._undoRedoService = _undoRedoService;
      this._languageService = _languageService;
      this._languageConfigurationService = _languageConfigurationService;
      this.instantiationService = instantiationService;
      this._onWillDispose = this._register(new Emitter$1());
      this.onWillDispose = this._onWillDispose.event;
      this._onDidChangeDecorations = this._register(new DidChangeDecorationsEmitter((affectedInjectedTextLines, affectedLineHeights, affectedFontLines) => this.handleBeforeFireDecorationsChangedEvent(affectedInjectedTextLines, affectedLineHeights, affectedFontLines)));
      this.onDidChangeDecorations = this._onDidChangeDecorations.event;
      this._onDidChangeOptions = this._register(new Emitter$1());
      this._onDidChangeAttached = this._register(new Emitter$1());
      this._onDidChangeInjectedText = this._register(new Emitter$1());
      this._onDidChangeLineHeight = this._register(new Emitter$1());
      this._onDidChangeFont = this._register(new Emitter$1());
      this._eventEmitter = this._register(new DidChangeContentEmitter());
      this._languageSelectionListener = this._register(new MutableDisposable());
      this._deltaDecorationCallCnt = 0;
      this._attachedViews = new AttachedViews();
      MODEL_ID$1++;
      this.id = "$model" + MODEL_ID$1;
      this.isForSimpleWidget = creationOptions.isForSimpleWidget;
      if (typeof associatedResource === "undefined" || associatedResource === null) {
        this._associatedResource = URI.parse("inmemory://model/" + MODEL_ID$1);
      } else {
        this._associatedResource = associatedResource;
      }
      this._attachedEditorCount = 0;
      const { textBuffer, disposable } = createTextBuffer(source, creationOptions.defaultEOL);
      this._buffer = textBuffer;
      this._bufferDisposable = disposable;
      const bufferLineCount = this._buffer.getLineCount();
      const bufferTextLength = this._buffer.getValueLengthInRange(
        new Range$2(1, 1, bufferLineCount, this._buffer.getLineLength(bufferLineCount) + 1),
        0
        /* model.EndOfLinePreference.TextDefined */
      );
      if (creationOptions.largeFileOptimizations) {
        this._isTooLargeForTokenization = bufferTextLength > TextModel_1.LARGE_FILE_SIZE_THRESHOLD || bufferLineCount > TextModel_1.LARGE_FILE_LINE_COUNT_THRESHOLD;
        this._isTooLargeForHeapOperation = bufferTextLength > TextModel_1.LARGE_FILE_HEAP_OPERATION_THRESHOLD;
      } else {
        this._isTooLargeForTokenization = false;
        this._isTooLargeForHeapOperation = false;
      }
      this._options = TextModel_1.resolveOptions(this._buffer, creationOptions);
      const languageId = typeof languageIdOrSelection === "string" ? languageIdOrSelection : languageIdOrSelection.languageId;
      if (typeof languageIdOrSelection !== "string") {
        this._languageSelectionListener.value = languageIdOrSelection.onDidChange(() => this._setLanguage(languageIdOrSelection.languageId));
      }
      this._bracketPairs = this._register(new BracketPairsTextModelPart(this, this._languageConfigurationService));
      this._guidesTextModelPart = this._register(new GuidesTextModelPart(this, this._languageConfigurationService));
      this._decorationProvider = this._register(new ColorizedBracketPairsDecorationProvider(this));
      this._tokenizationTextModelPart = this.instantiationService.createInstance(TokenizationTextModelPart, this, this._bracketPairs, languageId, this._attachedViews);
      this._isTooLargeForSyncing = bufferTextLength > TextModel_1._MODEL_SYNC_LIMIT;
      this._versionId = 1;
      this._alternativeVersionId = 1;
      this._initialUndoRedoSnapshot = null;
      this._isDisposed = false;
      this.__isDisposing = false;
      this._instanceId = singleLetterHash(MODEL_ID$1);
      this._lastDecorationId = 0;
      this._decorations = /* @__PURE__ */ Object.create(null);
      this._decorationsTree = new DecorationsTrees();
      this._commandManager = new EditStack(this, this._undoRedoService);
      this._isUndoing = false;
      this._isRedoing = false;
      this._trimAutoWhitespaceLines = null;
      this._register(this._decorationProvider.onDidChange(() => {
        this._onDidChangeDecorations.beginDeferredEmit();
        this._onDidChangeDecorations.fire();
        this._onDidChangeDecorations.endDeferredEmit();
      }));
      this._languageService.requestRichLanguageFeatures(languageId);
      this._register(this._languageConfigurationService.onDidChange((e) => {
        this._bracketPairs.handleLanguageConfigurationServiceChange(e);
        this._tokenizationTextModelPart.handleLanguageConfigurationServiceChange(e);
      }));
    }
    dispose() {
      this.__isDisposing = true;
      this._onWillDispose.fire();
      this._tokenizationTextModelPart.dispose();
      this._isDisposed = true;
      super.dispose();
      this._bufferDisposable.dispose();
      this.__isDisposing = false;
      const emptyDisposedTextBuffer = new PieceTreeTextBuffer([], "", "\n", false, false, true, true);
      emptyDisposedTextBuffer.dispose();
      this._buffer = emptyDisposedTextBuffer;
      this._bufferDisposable = Disposable.None;
    }
    _assertNotDisposed() {
      if (this._isDisposed) {
        throw new BugIndicatingError("Model is disposed!");
      }
    }
    getTextBuffer() {
      this._assertNotDisposed();
      return this._buffer;
    }
    _emitContentChangedEvent(rawChange, change) {
      if (this.__isDisposing) {
        return;
      }
      this._tokenizationTextModelPart.handleDidChangeContent(change);
      this._bracketPairs.handleDidChangeContent(change);
      this._eventEmitter.fire(new InternalModelContentChangeEvent(rawChange, change));
    }
    setValue(value, reason = EditSources.setValue()) {
      this._assertNotDisposed();
      if (value === null || value === void 0) {
        throw illegalArgument();
      }
      const { textBuffer, disposable } = createTextBuffer(value, this._options.defaultEOL);
      this._setValueFromTextBuffer(textBuffer, disposable, reason);
    }
    _createContentChanged2(range2, rangeOffset, rangeLength, rangeEndPosition, text2, isUndoing, isRedoing, isFlush, isEolChange, reason) {
      return {
        changes: [{
          range: range2,
          rangeOffset,
          rangeLength,
          text: text2
        }],
        eol: this._buffer.getEOL(),
        isEolChange,
        versionId: this.getVersionId(),
        isUndoing,
        isRedoing,
        isFlush,
        detailedReasons: [reason],
        detailedReasonsChangeLengths: [1]
      };
    }
    _setValueFromTextBuffer(textBuffer, textBufferDisposable, reason) {
      this._assertNotDisposed();
      const oldFullModelRange = this.getFullModelRange();
      const oldModelValueLength = this.getValueLengthInRange(oldFullModelRange);
      const endLineNumber = this.getLineCount();
      const endColumn = this.getLineMaxColumn(endLineNumber);
      this._buffer = textBuffer;
      this._bufferDisposable.dispose();
      this._bufferDisposable = textBufferDisposable;
      this._increaseVersionId();
      this._decorations = /* @__PURE__ */ Object.create(null);
      this._decorationsTree = new DecorationsTrees();
      this._commandManager.clear();
      this._trimAutoWhitespaceLines = null;
      this._emitContentChangedEvent(new ModelRawContentChangedEvent([
        new ModelRawFlush()
      ], this._versionId, false, false), this._createContentChanged2(new Range$2(1, 1, endLineNumber, endColumn), 0, oldModelValueLength, new Position$1(endLineNumber, endColumn), this.getValue(), false, false, true, false, reason));
    }
    setEOL(eol) {
      this._assertNotDisposed();
      const newEOL = eol === 1 ? "\r\n" : "\n";
      if (this._buffer.getEOL() === newEOL) {
        return;
      }
      const oldFullModelRange = this.getFullModelRange();
      const oldModelValueLength = this.getValueLengthInRange(oldFullModelRange);
      const endLineNumber = this.getLineCount();
      const endColumn = this.getLineMaxColumn(endLineNumber);
      this._onBeforeEOLChange();
      this._buffer.setEOL(newEOL);
      this._increaseVersionId();
      this._onAfterEOLChange();
      this._emitContentChangedEvent(new ModelRawContentChangedEvent([
        new ModelRawEOLChanged()
      ], this._versionId, false, false), this._createContentChanged2(new Range$2(1, 1, endLineNumber, endColumn), 0, oldModelValueLength, new Position$1(endLineNumber, endColumn), this.getValue(), false, false, false, true, EditSources.eolChange()));
    }
    _onBeforeEOLChange() {
      this._decorationsTree.ensureAllNodesHaveRanges(this);
    }
    _onAfterEOLChange() {
      const versionId = this.getVersionId();
      const allDecorations = this._decorationsTree.collectNodesPostOrder();
      for (let i2 = 0, len = allDecorations.length; i2 < len; i2++) {
        const node = allDecorations[i2];
        const range2 = node.range;
        const delta = node.cachedAbsoluteStart - node.start;
        const startOffset = this._buffer.getOffsetAt(range2.startLineNumber, range2.startColumn);
        const endOffset = this._buffer.getOffsetAt(range2.endLineNumber, range2.endColumn);
        node.cachedAbsoluteStart = startOffset;
        node.cachedAbsoluteEnd = endOffset;
        node.cachedVersionId = versionId;
        node.start = startOffset - delta;
        node.end = endOffset - delta;
        recomputeMaxEnd(node);
      }
    }
    onBeforeAttached() {
      this._attachedEditorCount++;
      if (this._attachedEditorCount === 1) {
        this._tokenizationTextModelPart.handleDidChangeAttached();
        this._onDidChangeAttached.fire(void 0);
      }
      return this._attachedViews.attachView();
    }
    onBeforeDetached(view) {
      this._attachedEditorCount--;
      if (this._attachedEditorCount === 0) {
        this._tokenizationTextModelPart.handleDidChangeAttached();
        this._onDidChangeAttached.fire(void 0);
      }
      this._attachedViews.detachView(view);
    }
    isAttachedToEditor() {
      return this._attachedEditorCount > 0;
    }
    getAttachedEditorCount() {
      return this._attachedEditorCount;
    }
    isTooLargeForSyncing() {
      return this._isTooLargeForSyncing;
    }
    isTooLargeForTokenization() {
      return this._isTooLargeForTokenization;
    }
    isTooLargeForHeapOperation() {
      return this._isTooLargeForHeapOperation;
    }
    isDisposed() {
      return this._isDisposed;
    }
    isDominatedByLongLines() {
      this._assertNotDisposed();
      if (this.isTooLargeForTokenization()) {
        return false;
      }
      let smallLineCharCount = 0;
      let longLineCharCount = 0;
      const lineCount = this._buffer.getLineCount();
      for (let lineNumber = 1; lineNumber <= lineCount; lineNumber++) {
        const lineLength = this._buffer.getLineLength(lineNumber);
        if (lineLength >= LONG_LINE_BOUNDARY) {
          longLineCharCount += lineLength;
        } else {
          smallLineCharCount += lineLength;
        }
      }
      return longLineCharCount > smallLineCharCount;
    }
    get uri() {
      return this._associatedResource;
    }
    //#region Options
    getOptions() {
      this._assertNotDisposed();
      return this._options;
    }
    getFormattingOptions() {
      return {
        tabSize: this._options.indentSize,
        insertSpaces: this._options.insertSpaces
      };
    }
    updateOptions(_newOpts) {
      this._assertNotDisposed();
      const tabSize = typeof _newOpts.tabSize !== "undefined" ? _newOpts.tabSize : this._options.tabSize;
      const indentSize = typeof _newOpts.indentSize !== "undefined" ? _newOpts.indentSize : this._options.originalIndentSize;
      const insertSpaces = typeof _newOpts.insertSpaces !== "undefined" ? _newOpts.insertSpaces : this._options.insertSpaces;
      const trimAutoWhitespace = typeof _newOpts.trimAutoWhitespace !== "undefined" ? _newOpts.trimAutoWhitespace : this._options.trimAutoWhitespace;
      const bracketPairColorizationOptions = typeof _newOpts.bracketColorizationOptions !== "undefined" ? _newOpts.bracketColorizationOptions : this._options.bracketPairColorizationOptions;
      const newOpts = new TextModelResolvedOptions({
        tabSize,
        indentSize,
        insertSpaces,
        defaultEOL: this._options.defaultEOL,
        trimAutoWhitespace,
        bracketPairColorizationOptions
      });
      if (this._options.equals(newOpts)) {
        return;
      }
      const e = this._options.createChangeEvent(newOpts);
      this._options = newOpts;
      this._bracketPairs.handleDidChangeOptions(e);
      this._decorationProvider.handleDidChangeOptions(e);
      this._onDidChangeOptions.fire(e);
    }
    detectIndentation(defaultInsertSpaces, defaultTabSize) {
      this._assertNotDisposed();
      const guessedIndentation = guessIndentation(this._buffer, defaultTabSize, defaultInsertSpaces);
      this.updateOptions({
        insertSpaces: guessedIndentation.insertSpaces,
        tabSize: guessedIndentation.tabSize,
        indentSize: guessedIndentation.tabSize
        // TODO@Alex: guess indentSize independent of tabSize
      });
    }
    normalizeIndentation(str) {
      this._assertNotDisposed();
      return normalizeIndentation(str, this._options.indentSize, this._options.insertSpaces);
    }
    //#endregion
    //#region Reading
    getVersionId() {
      this._assertNotDisposed();
      return this._versionId;
    }
    mightContainRTL() {
      return this._buffer.mightContainRTL();
    }
    mightContainUnusualLineTerminators() {
      return this._buffer.mightContainUnusualLineTerminators();
    }
    removeUnusualLineTerminators(selections = null) {
      const matches = this.findMatches(
        UNUSUAL_LINE_TERMINATORS.source,
        false,
        true,
        false,
        null,
        false,
        1073741824
        /* Constants.MAX_SAFE_SMALL_INTEGER */
      );
      this._buffer.resetMightContainUnusualLineTerminators();
      this.pushEditOperations(selections, matches.map((m) => ({ range: m.range, text: null })), () => null);
    }
    mightContainNonBasicASCII() {
      return this._buffer.mightContainNonBasicASCII();
    }
    getAlternativeVersionId() {
      this._assertNotDisposed();
      return this._alternativeVersionId;
    }
    getInitialUndoRedoSnapshot() {
      this._assertNotDisposed();
      return this._initialUndoRedoSnapshot;
    }
    getOffsetAt(rawPosition) {
      this._assertNotDisposed();
      const position = this._validatePosition(
        rawPosition.lineNumber,
        rawPosition.column,
        0
        /* StringOffsetValidationType.Relaxed */
      );
      return this._buffer.getOffsetAt(position.lineNumber, position.column);
    }
    getPositionAt(rawOffset) {
      this._assertNotDisposed();
      const offset = Math.min(this._buffer.getLength(), Math.max(0, rawOffset));
      return this._buffer.getPositionAt(offset);
    }
    _increaseVersionId() {
      this._versionId = this._versionId + 1;
      this._alternativeVersionId = this._versionId;
    }
    _overwriteVersionId(versionId) {
      this._versionId = versionId;
    }
    _overwriteAlternativeVersionId(newAlternativeVersionId) {
      this._alternativeVersionId = newAlternativeVersionId;
    }
    _overwriteInitialUndoRedoSnapshot(newInitialUndoRedoSnapshot) {
      this._initialUndoRedoSnapshot = newInitialUndoRedoSnapshot;
    }
    getValue(eol, preserveBOM = false) {
      this._assertNotDisposed();
      if (this.isTooLargeForHeapOperation()) {
        throw new BugIndicatingError("Operation would exceed heap memory limits");
      }
      const fullModelRange = this.getFullModelRange();
      const fullModelValue = this.getValueInRange(fullModelRange, eol);
      if (preserveBOM) {
        return this._buffer.getBOM() + fullModelValue;
      }
      return fullModelValue;
    }
    createSnapshot(preserveBOM = false) {
      return new TextModelSnapshot(this._buffer.createSnapshot(preserveBOM));
    }
    getValueLength(eol, preserveBOM = false) {
      this._assertNotDisposed();
      const fullModelRange = this.getFullModelRange();
      const fullModelValue = this.getValueLengthInRange(fullModelRange, eol);
      if (preserveBOM) {
        return this._buffer.getBOM().length + fullModelValue;
      }
      return fullModelValue;
    }
    getValueInRange(rawRange, eol = 0) {
      this._assertNotDisposed();
      return this._buffer.getValueInRange(this.validateRange(rawRange), eol);
    }
    getValueLengthInRange(rawRange, eol = 0) {
      this._assertNotDisposed();
      return this._buffer.getValueLengthInRange(this.validateRange(rawRange), eol);
    }
    getCharacterCountInRange(rawRange, eol = 0) {
      this._assertNotDisposed();
      return this._buffer.getCharacterCountInRange(this.validateRange(rawRange), eol);
    }
    getLineCount() {
      this._assertNotDisposed();
      return this._buffer.getLineCount();
    }
    getLineContent(lineNumber) {
      this._assertNotDisposed();
      if (lineNumber < 1 || lineNumber > this.getLineCount()) {
        throw new BugIndicatingError("Illegal value for lineNumber");
      }
      return this._buffer.getLineContent(lineNumber);
    }
    getLineLength(lineNumber) {
      this._assertNotDisposed();
      if (lineNumber < 1 || lineNumber > this.getLineCount()) {
        throw new BugIndicatingError("Illegal value for lineNumber");
      }
      return this._buffer.getLineLength(lineNumber);
    }
    getLinesContent() {
      this._assertNotDisposed();
      if (this.isTooLargeForHeapOperation()) {
        throw new BugIndicatingError("Operation would exceed heap memory limits");
      }
      return this._buffer.getLinesContent();
    }
    getEOL() {
      this._assertNotDisposed();
      return this._buffer.getEOL();
    }
    getEndOfLineSequence() {
      this._assertNotDisposed();
      return this._buffer.getEOL() === "\n" ? 0 : 1;
    }
    getLineMinColumn(lineNumber) {
      this._assertNotDisposed();
      return 1;
    }
    getLineMaxColumn(lineNumber) {
      this._assertNotDisposed();
      if (lineNumber < 1 || lineNumber > this.getLineCount()) {
        throw new BugIndicatingError("Illegal value for lineNumber");
      }
      return this._buffer.getLineLength(lineNumber) + 1;
    }
    getLineFirstNonWhitespaceColumn(lineNumber) {
      this._assertNotDisposed();
      if (lineNumber < 1 || lineNumber > this.getLineCount()) {
        throw new BugIndicatingError("Illegal value for lineNumber");
      }
      return this._buffer.getLineFirstNonWhitespaceColumn(lineNumber);
    }
    getLineLastNonWhitespaceColumn(lineNumber) {
      this._assertNotDisposed();
      if (lineNumber < 1 || lineNumber > this.getLineCount()) {
        throw new BugIndicatingError("Illegal value for lineNumber");
      }
      return this._buffer.getLineLastNonWhitespaceColumn(lineNumber);
    }
    /**
     * Validates `range` is within buffer bounds, but allows it to sit in between surrogate pairs, etc.
     * Will try to not allocate if possible.
     */
    _validateRangeRelaxedNoAllocations(range2) {
      const linesCount = this._buffer.getLineCount();
      const initialStartLineNumber = range2.startLineNumber;
      const initialStartColumn = range2.startColumn;
      let startLineNumber = Math.floor(typeof initialStartLineNumber === "number" && !isNaN(initialStartLineNumber) ? initialStartLineNumber : 1);
      let startColumn = Math.floor(typeof initialStartColumn === "number" && !isNaN(initialStartColumn) ? initialStartColumn : 1);
      if (startLineNumber < 1) {
        startLineNumber = 1;
        startColumn = 1;
      } else if (startLineNumber > linesCount) {
        startLineNumber = linesCount;
        startColumn = this.getLineMaxColumn(startLineNumber);
      } else {
        if (startColumn <= 1) {
          startColumn = 1;
        } else {
          const maxColumn = this.getLineMaxColumn(startLineNumber);
          if (startColumn >= maxColumn) {
            startColumn = maxColumn;
          }
        }
      }
      const initialEndLineNumber = range2.endLineNumber;
      const initialEndColumn = range2.endColumn;
      let endLineNumber = Math.floor(typeof initialEndLineNumber === "number" && !isNaN(initialEndLineNumber) ? initialEndLineNumber : 1);
      let endColumn = Math.floor(typeof initialEndColumn === "number" && !isNaN(initialEndColumn) ? initialEndColumn : 1);
      if (endLineNumber < 1) {
        endLineNumber = 1;
        endColumn = 1;
      } else if (endLineNumber > linesCount) {
        endLineNumber = linesCount;
        endColumn = this.getLineMaxColumn(endLineNumber);
      } else {
        if (endColumn <= 1) {
          endColumn = 1;
        } else {
          const maxColumn = this.getLineMaxColumn(endLineNumber);
          if (endColumn >= maxColumn) {
            endColumn = maxColumn;
          }
        }
      }
      if (initialStartLineNumber === startLineNumber && initialStartColumn === startColumn && initialEndLineNumber === endLineNumber && initialEndColumn === endColumn && range2 instanceof Range$2 && !(range2 instanceof Selection$1)) {
        return range2;
      }
      return new Range$2(startLineNumber, startColumn, endLineNumber, endColumn);
    }
    _isValidPosition(lineNumber, column, validationType) {
      if (typeof lineNumber !== "number" || typeof column !== "number") {
        return false;
      }
      if (isNaN(lineNumber) || isNaN(column)) {
        return false;
      }
      if (lineNumber < 1 || column < 1) {
        return false;
      }
      if ((lineNumber | 0) !== lineNumber || (column | 0) !== column) {
        return false;
      }
      const lineCount = this._buffer.getLineCount();
      if (lineNumber > lineCount) {
        return false;
      }
      if (column === 1) {
        return true;
      }
      const maxColumn = this.getLineMaxColumn(lineNumber);
      if (column > maxColumn) {
        return false;
      }
      if (validationType === 1) {
        const charCodeBefore = this._buffer.getLineCharCode(lineNumber, column - 2);
        if (isHighSurrogate(charCodeBefore)) {
          return false;
        }
      }
      return true;
    }
    _validatePosition(_lineNumber, _column, validationType) {
      const lineNumber = Math.floor(typeof _lineNumber === "number" && !isNaN(_lineNumber) ? _lineNumber : 1);
      const column = Math.floor(typeof _column === "number" && !isNaN(_column) ? _column : 1);
      const lineCount = this._buffer.getLineCount();
      if (lineNumber < 1) {
        return new Position$1(1, 1);
      }
      if (lineNumber > lineCount) {
        return new Position$1(lineCount, this.getLineMaxColumn(lineCount));
      }
      if (column <= 1) {
        return new Position$1(lineNumber, 1);
      }
      const maxColumn = this.getLineMaxColumn(lineNumber);
      if (column >= maxColumn) {
        return new Position$1(lineNumber, maxColumn);
      }
      if (validationType === 1) {
        const charCodeBefore = this._buffer.getLineCharCode(lineNumber, column - 2);
        if (isHighSurrogate(charCodeBefore)) {
          return new Position$1(lineNumber, column - 1);
        }
      }
      return new Position$1(lineNumber, column);
    }
    validatePosition(position) {
      const validationType = 1;
      this._assertNotDisposed();
      if (position instanceof Position$1) {
        if (this._isValidPosition(position.lineNumber, position.column, validationType)) {
          return position;
        }
      }
      return this._validatePosition(position.lineNumber, position.column, validationType);
    }
    isValidRange(range2) {
      return this._isValidRange(
        range2,
        1
        /* StringOffsetValidationType.SurrogatePairs */
      );
    }
    _isValidRange(range2, validationType) {
      const startLineNumber = range2.startLineNumber;
      const startColumn = range2.startColumn;
      const endLineNumber = range2.endLineNumber;
      const endColumn = range2.endColumn;
      if (!this._isValidPosition(
        startLineNumber,
        startColumn,
        0
        /* StringOffsetValidationType.Relaxed */
      )) {
        return false;
      }
      if (!this._isValidPosition(
        endLineNumber,
        endColumn,
        0
        /* StringOffsetValidationType.Relaxed */
      )) {
        return false;
      }
      if (validationType === 1) {
        const charCodeBeforeStart = startColumn > 1 ? this._buffer.getLineCharCode(startLineNumber, startColumn - 2) : 0;
        const charCodeBeforeEnd = endColumn > 1 && endColumn <= this._buffer.getLineLength(endLineNumber) ? this._buffer.getLineCharCode(endLineNumber, endColumn - 2) : 0;
        const startInsideSurrogatePair = isHighSurrogate(charCodeBeforeStart);
        const endInsideSurrogatePair = isHighSurrogate(charCodeBeforeEnd);
        if (!startInsideSurrogatePair && !endInsideSurrogatePair) {
          return true;
        }
        return false;
      }
      return true;
    }
    validateRange(_range) {
      const validationType = 1;
      this._assertNotDisposed();
      if (_range instanceof Range$2 && !(_range instanceof Selection$1)) {
        if (this._isValidRange(_range, validationType)) {
          return _range;
        }
      }
      const start = this._validatePosition(
        _range.startLineNumber,
        _range.startColumn,
        0
        /* StringOffsetValidationType.Relaxed */
      );
      const end = this._validatePosition(
        _range.endLineNumber,
        _range.endColumn,
        0
        /* StringOffsetValidationType.Relaxed */
      );
      const startLineNumber = start.lineNumber;
      const startColumn = start.column;
      const endLineNumber = end.lineNumber;
      const endColumn = end.column;
      {
        const charCodeBeforeStart = startColumn > 1 ? this._buffer.getLineCharCode(startLineNumber, startColumn - 2) : 0;
        const charCodeBeforeEnd = endColumn > 1 && endColumn <= this._buffer.getLineLength(endLineNumber) ? this._buffer.getLineCharCode(endLineNumber, endColumn - 2) : 0;
        const startInsideSurrogatePair = isHighSurrogate(charCodeBeforeStart);
        const endInsideSurrogatePair = isHighSurrogate(charCodeBeforeEnd);
        if (!startInsideSurrogatePair && !endInsideSurrogatePair) {
          return new Range$2(startLineNumber, startColumn, endLineNumber, endColumn);
        }
        if (startLineNumber === endLineNumber && startColumn === endColumn) {
          return new Range$2(startLineNumber, startColumn - 1, endLineNumber, endColumn - 1);
        }
        if (startInsideSurrogatePair && endInsideSurrogatePair) {
          return new Range$2(startLineNumber, startColumn - 1, endLineNumber, endColumn + 1);
        }
        if (startInsideSurrogatePair) {
          return new Range$2(startLineNumber, startColumn - 1, endLineNumber, endColumn);
        }
        return new Range$2(startLineNumber, startColumn, endLineNumber, endColumn + 1);
      }
    }
    modifyPosition(rawPosition, offset) {
      this._assertNotDisposed();
      const candidate = this.getOffsetAt(rawPosition) + offset;
      return this.getPositionAt(Math.min(this._buffer.getLength(), Math.max(0, candidate)));
    }
    getFullModelRange() {
      this._assertNotDisposed();
      const lineCount = this.getLineCount();
      return new Range$2(1, 1, lineCount, this.getLineMaxColumn(lineCount));
    }
    findMatchesLineByLine(searchRange, searchData, captureMatches, limitResultCount) {
      return this._buffer.findMatchesLineByLine(searchRange, searchData, captureMatches, limitResultCount);
    }
    findMatches(searchString, rawSearchScope, isRegex, matchCase, wordSeparators2, captureMatches, limitResultCount = LIMIT_FIND_COUNT) {
      this._assertNotDisposed();
      let searchRanges = null;
      if (rawSearchScope !== null && typeof rawSearchScope !== "boolean") {
        if (!Array.isArray(rawSearchScope)) {
          rawSearchScope = [rawSearchScope];
        }
        if (rawSearchScope.every((searchScope) => Range$2.isIRange(searchScope))) {
          searchRanges = rawSearchScope.map((searchScope) => this.validateRange(searchScope));
        }
      }
      if (searchRanges === null) {
        searchRanges = [this.getFullModelRange()];
      }
      searchRanges = searchRanges.sort((d1, d2) => d1.startLineNumber - d2.startLineNumber || d1.startColumn - d2.startColumn);
      const uniqueSearchRanges = [];
      uniqueSearchRanges.push(searchRanges.reduce((prev, curr) => {
        if (Range$2.areIntersecting(prev, curr)) {
          return prev.plusRange(curr);
        }
        uniqueSearchRanges.push(prev);
        return curr;
      }));
      let matchMapper;
      if (!isRegex && searchString.indexOf("\n") < 0) {
        const searchParams = new SearchParams(searchString, isRegex, matchCase, wordSeparators2);
        const searchData = searchParams.parseSearchRequest();
        if (!searchData) {
          return [];
        }
        matchMapper = (searchRange) => this.findMatchesLineByLine(searchRange, searchData, captureMatches, limitResultCount);
      } else {
        matchMapper = (searchRange) => TextModelSearch.findMatches(this, new SearchParams(searchString, isRegex, matchCase, wordSeparators2), searchRange, captureMatches, limitResultCount);
      }
      return uniqueSearchRanges.map(matchMapper).reduce((arr, matches) => arr.concat(matches), []);
    }
    findNextMatch(searchString, rawSearchStart, isRegex, matchCase, wordSeparators2, captureMatches) {
      this._assertNotDisposed();
      const searchStart = this.validatePosition(rawSearchStart);
      if (!isRegex && searchString.indexOf("\n") < 0) {
        const searchParams = new SearchParams(searchString, isRegex, matchCase, wordSeparators2);
        const searchData = searchParams.parseSearchRequest();
        if (!searchData) {
          return null;
        }
        const lineCount = this.getLineCount();
        let searchRange = new Range$2(searchStart.lineNumber, searchStart.column, lineCount, this.getLineMaxColumn(lineCount));
        let ret = this.findMatchesLineByLine(searchRange, searchData, captureMatches, 1);
        TextModelSearch.findNextMatch(this, new SearchParams(searchString, isRegex, matchCase, wordSeparators2), searchStart, captureMatches);
        if (ret.length > 0) {
          return ret[0];
        }
        searchRange = new Range$2(1, 1, searchStart.lineNumber, this.getLineMaxColumn(searchStart.lineNumber));
        ret = this.findMatchesLineByLine(searchRange, searchData, captureMatches, 1);
        if (ret.length > 0) {
          return ret[0];
        }
        return null;
      }
      return TextModelSearch.findNextMatch(this, new SearchParams(searchString, isRegex, matchCase, wordSeparators2), searchStart, captureMatches);
    }
    findPreviousMatch(searchString, rawSearchStart, isRegex, matchCase, wordSeparators2, captureMatches) {
      this._assertNotDisposed();
      const searchStart = this.validatePosition(rawSearchStart);
      return TextModelSearch.findPreviousMatch(this, new SearchParams(searchString, isRegex, matchCase, wordSeparators2), searchStart, captureMatches);
    }
    //#endregion
    //#region Editing
    pushStackElement() {
      this._commandManager.pushStackElement();
    }
    popStackElement() {
      this._commandManager.popStackElement();
    }
    pushEOL(eol) {
      const currentEOL = this.getEOL() === "\n" ? 0 : 1;
      if (currentEOL === eol) {
        return;
      }
      try {
        this._onDidChangeDecorations.beginDeferredEmit();
        this._eventEmitter.beginDeferredEmit();
        if (this._initialUndoRedoSnapshot === null) {
          this._initialUndoRedoSnapshot = this._undoRedoService.createSnapshot(this.uri);
        }
        this._commandManager.pushEOL(eol);
      } finally {
        this._eventEmitter.endDeferredEmit();
        this._onDidChangeDecorations.endDeferredEmit();
      }
    }
    _validateEditOperation(rawOperation) {
      if (rawOperation instanceof ValidAnnotatedEditOperation) {
        return rawOperation;
      }
      return new ValidAnnotatedEditOperation(rawOperation.identifier || null, this.validateRange(rawOperation.range), rawOperation.text, rawOperation.forceMoveMarkers || false, rawOperation.isAutoWhitespaceEdit || false, rawOperation._isTracked || false);
    }
    _validateEditOperations(rawOperations) {
      const result = [];
      for (let i2 = 0, len = rawOperations.length; i2 < len; i2++) {
        result[i2] = this._validateEditOperation(rawOperations[i2]);
      }
      return result;
    }
    pushEditOperations(beforeCursorState, editOperations, cursorStateComputer, group, reason) {
      try {
        this._onDidChangeDecorations.beginDeferredEmit();
        this._eventEmitter.beginDeferredEmit();
        return this._pushEditOperations(beforeCursorState, this._validateEditOperations(editOperations), cursorStateComputer, group, reason);
      } finally {
        this._eventEmitter.endDeferredEmit();
        this._onDidChangeDecorations.endDeferredEmit();
      }
    }
    _pushEditOperations(beforeCursorState, editOperations, cursorStateComputer, group, reason) {
      if (this._options.trimAutoWhitespace && this._trimAutoWhitespaceLines) {
        const incomingEdits = editOperations.map((op) => {
          return {
            range: this.validateRange(op.range),
            text: op.text
          };
        });
        let editsAreNearCursors = true;
        if (beforeCursorState) {
          for (let i2 = 0, len = beforeCursorState.length; i2 < len; i2++) {
            const sel = beforeCursorState[i2];
            let foundEditNearSel = false;
            for (let j = 0, lenJ = incomingEdits.length; j < lenJ; j++) {
              const editRange = incomingEdits[j].range;
              const selIsAbove = editRange.startLineNumber > sel.endLineNumber;
              const selIsBelow = sel.startLineNumber > editRange.endLineNumber;
              if (!selIsAbove && !selIsBelow) {
                foundEditNearSel = true;
                break;
              }
            }
            if (!foundEditNearSel) {
              editsAreNearCursors = false;
              break;
            }
          }
        }
        if (editsAreNearCursors) {
          for (let i2 = 0, len = this._trimAutoWhitespaceLines.length; i2 < len; i2++) {
            const trimLineNumber = this._trimAutoWhitespaceLines[i2];
            const maxLineColumn = this.getLineMaxColumn(trimLineNumber);
            let allowTrimLine = true;
            for (let j = 0, lenJ = incomingEdits.length; j < lenJ; j++) {
              const editRange = incomingEdits[j].range;
              const editText = incomingEdits[j].text;
              if (trimLineNumber < editRange.startLineNumber || trimLineNumber > editRange.endLineNumber) {
                continue;
              }
              if (trimLineNumber === editRange.startLineNumber && editRange.startColumn === maxLineColumn && editRange.isEmpty() && editText && editText.length > 0 && editText.charAt(0) === "\n") {
                continue;
              }
              if (trimLineNumber === editRange.startLineNumber && editRange.startColumn === 1 && editRange.isEmpty() && editText && editText.length > 0 && editText.charAt(editText.length - 1) === "\n") {
                continue;
              }
              allowTrimLine = false;
              break;
            }
            if (allowTrimLine) {
              const trimRange = new Range$2(trimLineNumber, 1, trimLineNumber, maxLineColumn);
              editOperations.push(new ValidAnnotatedEditOperation(null, trimRange, null, false, false, false));
            }
          }
        }
        this._trimAutoWhitespaceLines = null;
      }
      if (this._initialUndoRedoSnapshot === null) {
        this._initialUndoRedoSnapshot = this._undoRedoService.createSnapshot(this.uri);
      }
      return this._commandManager.pushEditOperation(beforeCursorState, editOperations, cursorStateComputer, group, reason);
    }
    _applyUndo(changes, eol, resultingAlternativeVersionId, resultingSelection) {
      const edits = changes.map((change) => {
        const rangeStart = this.getPositionAt(change.newPosition);
        const rangeEnd = this.getPositionAt(change.newEnd);
        return {
          range: new Range$2(rangeStart.lineNumber, rangeStart.column, rangeEnd.lineNumber, rangeEnd.column),
          text: change.oldText
        };
      });
      this._applyUndoRedoEdits(edits, eol, true, false, resultingAlternativeVersionId, resultingSelection);
    }
    _applyRedo(changes, eol, resultingAlternativeVersionId, resultingSelection) {
      const edits = changes.map((change) => {
        const rangeStart = this.getPositionAt(change.oldPosition);
        const rangeEnd = this.getPositionAt(change.oldEnd);
        return {
          range: new Range$2(rangeStart.lineNumber, rangeStart.column, rangeEnd.lineNumber, rangeEnd.column),
          text: change.newText
        };
      });
      this._applyUndoRedoEdits(edits, eol, false, true, resultingAlternativeVersionId, resultingSelection);
    }
    _applyUndoRedoEdits(edits, eol, isUndoing, isRedoing, resultingAlternativeVersionId, resultingSelection) {
      try {
        this._onDidChangeDecorations.beginDeferredEmit();
        this._eventEmitter.beginDeferredEmit();
        this._isUndoing = isUndoing;
        this._isRedoing = isRedoing;
        this.applyEdits(edits, false);
        this.setEOL(eol);
        this._overwriteAlternativeVersionId(resultingAlternativeVersionId);
      } finally {
        this._isUndoing = false;
        this._isRedoing = false;
        this._eventEmitter.endDeferredEmit(resultingSelection);
        this._onDidChangeDecorations.endDeferredEmit();
      }
    }
    applyEdits(rawOperations, computeUndoEdits, reason) {
      try {
        this._onDidChangeDecorations.beginDeferredEmit();
        this._eventEmitter.beginDeferredEmit();
        const operations = this._validateEditOperations(rawOperations);
        return this._doApplyEdits(operations, computeUndoEdits ?? false, reason ?? EditSources.applyEdits());
      } finally {
        this._eventEmitter.endDeferredEmit();
        this._onDidChangeDecorations.endDeferredEmit();
      }
    }
    _doApplyEdits(rawOperations, computeUndoEdits, reason) {
      const oldLineCount = this._buffer.getLineCount();
      const result = this._buffer.applyEdits(rawOperations, this._options.trimAutoWhitespace, computeUndoEdits);
      const newLineCount = this._buffer.getLineCount();
      const contentChanges = result.changes;
      this._trimAutoWhitespaceLines = result.trimAutoWhitespaceLineNumbers;
      if (contentChanges.length !== 0) {
        for (let i2 = 0, len = contentChanges.length; i2 < len; i2++) {
          const change = contentChanges[i2];
          this._decorationsTree.acceptReplace(change.rangeOffset, change.rangeLength, change.text.length, change.forceMoveMarkers);
        }
        const rawContentChanges = [];
        this._increaseVersionId();
        let lineCount = oldLineCount;
        for (let i2 = 0, len = contentChanges.length; i2 < len; i2++) {
          const change = contentChanges[i2];
          const [eolCount] = countEOL(change.text);
          this._onDidChangeDecorations.fire();
          const startLineNumber = change.range.startLineNumber;
          const endLineNumber = change.range.endLineNumber;
          const deletingLinesCnt = endLineNumber - startLineNumber;
          const insertingLinesCnt = eolCount;
          const editingLinesCnt = Math.min(deletingLinesCnt, insertingLinesCnt);
          const changeLineCountDelta = insertingLinesCnt - deletingLinesCnt;
          const currentEditStartLineNumber = newLineCount - lineCount - changeLineCountDelta + startLineNumber;
          const firstEditLineNumber = currentEditStartLineNumber;
          const lastInsertedLineNumber = currentEditStartLineNumber + insertingLinesCnt;
          const decorationsWithInjectedTextInEditedRange = this._decorationsTree.getInjectedTextInInterval(this, this.getOffsetAt(new Position$1(firstEditLineNumber, 1)), this.getOffsetAt(new Position$1(lastInsertedLineNumber, this.getLineMaxColumn(lastInsertedLineNumber))), 0);
          const injectedTextInEditedRange = LineInjectedText.fromDecorations(decorationsWithInjectedTextInEditedRange);
          const injectedTextInEditedRangeQueue = new ArrayQueue(injectedTextInEditedRange);
          for (let j = editingLinesCnt; j >= 0; j--) {
            const editLineNumber = startLineNumber + j;
            const currentEditLineNumber = currentEditStartLineNumber + j;
            injectedTextInEditedRangeQueue.takeFromEndWhile((r) => r.lineNumber > currentEditLineNumber);
            const decorationsInCurrentLine = injectedTextInEditedRangeQueue.takeFromEndWhile((r) => r.lineNumber === currentEditLineNumber);
            rawContentChanges.push(new ModelRawLineChanged(editLineNumber, this.getLineContent(currentEditLineNumber), decorationsInCurrentLine));
          }
          if (editingLinesCnt < deletingLinesCnt) {
            const spliceStartLineNumber = startLineNumber + editingLinesCnt;
            rawContentChanges.push(new ModelRawLinesDeleted(spliceStartLineNumber + 1, endLineNumber));
          }
          if (editingLinesCnt < insertingLinesCnt) {
            const injectedTextInEditedRangeQueue2 = new ArrayQueue(injectedTextInEditedRange);
            const spliceLineNumber = startLineNumber + editingLinesCnt;
            const cnt = insertingLinesCnt - editingLinesCnt;
            const fromLineNumber = newLineCount - lineCount - cnt + spliceLineNumber + 1;
            const injectedTexts = [];
            const newLines = [];
            for (let i3 = 0; i3 < cnt; i3++) {
              const lineNumber = fromLineNumber + i3;
              newLines[i3] = this.getLineContent(lineNumber);
              injectedTextInEditedRangeQueue2.takeWhile((r) => r.lineNumber < lineNumber);
              injectedTexts[i3] = injectedTextInEditedRangeQueue2.takeWhile((r) => r.lineNumber === lineNumber);
            }
            rawContentChanges.push(new ModelRawLinesInserted(spliceLineNumber + 1, startLineNumber + insertingLinesCnt, newLines, injectedTexts));
          }
          lineCount += changeLineCountDelta;
        }
        this._emitContentChangedEvent(new ModelRawContentChangedEvent(rawContentChanges, this.getVersionId(), this._isUndoing, this._isRedoing), {
          changes: contentChanges,
          eol: this._buffer.getEOL(),
          isEolChange: false,
          versionId: this.getVersionId(),
          isUndoing: this._isUndoing,
          isRedoing: this._isRedoing,
          isFlush: false,
          detailedReasons: [reason],
          detailedReasonsChangeLengths: [contentChanges.length]
        });
      }
      return result.reverseEdits === null ? void 0 : result.reverseEdits;
    }
    undo() {
      return this._undoRedoService.undo(this.uri);
    }
    canUndo() {
      return this._undoRedoService.canUndo(this.uri);
    }
    redo() {
      return this._undoRedoService.redo(this.uri);
    }
    canRedo() {
      return this._undoRedoService.canRedo(this.uri);
    }
    //#endregion
    //#region Decorations
    handleBeforeFireDecorationsChangedEvent(affectedInjectedTextLines, affectedLineHeights, affectedFontLines) {
      if (affectedInjectedTextLines && affectedInjectedTextLines.size > 0) {
        const affectedLines = Array.from(affectedInjectedTextLines);
        const lineChangeEvents = affectedLines.map((lineNumber) => new ModelRawLineChanged(lineNumber, this.getLineContent(lineNumber), this._getInjectedTextInLine(lineNumber)));
        this._onDidChangeInjectedText.fire(new ModelInjectedTextChangedEvent(lineChangeEvents));
      }
      if (affectedLineHeights && affectedLineHeights.size > 0) {
        const affectedLines = Array.from(affectedLineHeights);
        const lineHeightChangeEvent = affectedLines.map((specialLineHeightChange) => new ModelLineHeightChanged(specialLineHeightChange.ownerId, specialLineHeightChange.decorationId, specialLineHeightChange.lineNumber, specialLineHeightChange.lineHeight));
        this._onDidChangeLineHeight.fire(new ModelLineHeightChangedEvent$1(lineHeightChangeEvent));
      }
      if (affectedFontLines && affectedFontLines.size > 0) {
        const affectedLines = Array.from(affectedFontLines);
        const fontChangeEvent = affectedLines.map((fontChange) => new ModelFontChanged(fontChange.ownerId, fontChange.lineNumber));
        this._onDidChangeFont.fire(new ModelFontChangedEvent$1(fontChangeEvent));
      }
    }
    changeDecorations(callback, ownerId2 = 0) {
      this._assertNotDisposed();
      try {
        this._onDidChangeDecorations.beginDeferredEmit();
        return this._changeDecorations(ownerId2, callback);
      } finally {
        this._onDidChangeDecorations.endDeferredEmit();
      }
    }
    _changeDecorations(ownerId2, callback) {
      const changeAccessor = {
        addDecoration: (range2, options) => {
          return this._deltaDecorationsImpl(ownerId2, [], [{ range: range2, options }])[0];
        },
        changeDecoration: (id, newRange) => {
          this._changeDecorationImpl(ownerId2, id, newRange);
        },
        changeDecorationOptions: (id, options) => {
          this._changeDecorationOptionsImpl(ownerId2, id, _normalizeOptions(options));
        },
        removeDecoration: (id) => {
          this._deltaDecorationsImpl(ownerId2, [id], []);
        },
        deltaDecorations: (oldDecorations, newDecorations) => {
          if (oldDecorations.length === 0 && newDecorations.length === 0) {
            return [];
          }
          return this._deltaDecorationsImpl(ownerId2, oldDecorations, newDecorations);
        }
      };
      let result = null;
      try {
        result = callback(changeAccessor);
      } catch (e) {
        onUnexpectedError(e);
      }
      changeAccessor.addDecoration = invalidFunc;
      changeAccessor.changeDecoration = invalidFunc;
      changeAccessor.changeDecorationOptions = invalidFunc;
      changeAccessor.removeDecoration = invalidFunc;
      changeAccessor.deltaDecorations = invalidFunc;
      return result;
    }
    deltaDecorations(oldDecorations, newDecorations, ownerId2 = 0) {
      this._assertNotDisposed();
      if (!oldDecorations) {
        oldDecorations = [];
      }
      if (oldDecorations.length === 0 && newDecorations.length === 0) {
        return [];
      }
      try {
        this._deltaDecorationCallCnt++;
        if (this._deltaDecorationCallCnt > 1) {
          console.warn(`Invoking deltaDecorations recursively could lead to leaking decorations.`);
          onUnexpectedError(new Error(`Invoking deltaDecorations recursively could lead to leaking decorations.`));
        }
        this._onDidChangeDecorations.beginDeferredEmit();
        return this._deltaDecorationsImpl(ownerId2, oldDecorations, newDecorations);
      } finally {
        this._onDidChangeDecorations.endDeferredEmit();
        this._deltaDecorationCallCnt--;
      }
    }
    _getTrackedRange(id) {
      return this.getDecorationRange(id);
    }
    _setTrackedRange(id, newRange, newStickiness) {
      const node = id ? this._decorations[id] : null;
      if (!node) {
        if (!newRange) {
          return null;
        }
        return this._deltaDecorationsImpl(0, [], [{ range: newRange, options: TRACKED_RANGE_OPTIONS[newStickiness] }], true)[0];
      }
      if (!newRange) {
        this._decorationsTree.delete(node);
        delete this._decorations[node.id];
        return null;
      }
      const range2 = this._validateRangeRelaxedNoAllocations(newRange);
      const startOffset = this._buffer.getOffsetAt(range2.startLineNumber, range2.startColumn);
      const endOffset = this._buffer.getOffsetAt(range2.endLineNumber, range2.endColumn);
      this._decorationsTree.delete(node);
      node.reset(this.getVersionId(), startOffset, endOffset, range2);
      node.setOptions(TRACKED_RANGE_OPTIONS[newStickiness]);
      this._decorationsTree.insert(node);
      return node.id;
    }
    removeAllDecorationsWithOwnerId(ownerId2) {
      if (this._isDisposed) {
        return;
      }
      const nodes = this._decorationsTree.collectNodesFromOwner(ownerId2);
      for (let i2 = 0, len = nodes.length; i2 < len; i2++) {
        const node = nodes[i2];
        this._decorationsTree.delete(node);
        delete this._decorations[node.id];
      }
    }
    getDecorationOptions(decorationId) {
      const node = this._decorations[decorationId];
      if (!node) {
        return null;
      }
      return node.options;
    }
    getDecorationRange(decorationId) {
      const node = this._decorations[decorationId];
      if (!node) {
        return null;
      }
      return this._decorationsTree.getNodeRange(this, node);
    }
    getLineDecorations(lineNumber, ownerId2 = 0, filterOutValidation = false, filterFontDecorations2 = false) {
      if (lineNumber < 1 || lineNumber > this.getLineCount()) {
        return [];
      }
      return this.getLinesDecorations(lineNumber, lineNumber, ownerId2, filterOutValidation, filterFontDecorations2);
    }
    getLinesDecorations(_startLineNumber, _endLineNumber, ownerId2 = 0, filterOutValidation = false, filterFontDecorations2 = false, onlyMarginDecorations = false) {
      const lineCount = this.getLineCount();
      const startLineNumber = Math.min(lineCount, Math.max(1, _startLineNumber));
      const endLineNumber = Math.min(lineCount, Math.max(1, _endLineNumber));
      const endColumn = this.getLineMaxColumn(endLineNumber);
      const range2 = new Range$2(startLineNumber, 1, endLineNumber, endColumn);
      const decorations = this._getDecorationsInRange(range2, ownerId2, filterOutValidation, filterFontDecorations2, onlyMarginDecorations);
      pushMany(decorations, this._decorationProvider.getDecorationsInRange(range2, ownerId2, filterOutValidation));
      return decorations;
    }
    getDecorationsInRange(range2, ownerId2 = 0, filterOutValidation = false, filterFontDecorations2 = false, onlyMinimapDecorations = false, onlyMarginDecorations = false) {
      const validatedRange = this.validateRange(range2);
      const decorations = this._getDecorationsInRange(validatedRange, ownerId2, filterOutValidation, filterFontDecorations2, onlyMarginDecorations);
      pushMany(decorations, this._decorationProvider.getDecorationsInRange(validatedRange, ownerId2, filterOutValidation, onlyMinimapDecorations));
      return decorations;
    }
    getOverviewRulerDecorations(ownerId2 = 0, filterOutValidation = false, filterFontDecorations2 = false) {
      return this._decorationsTree.getAll(this, ownerId2, filterOutValidation, filterFontDecorations2, true, false);
    }
    getInjectedTextDecorations(ownerId2 = 0) {
      return this._decorationsTree.getAllInjectedText(this, ownerId2);
    }
    getCustomLineHeightsDecorations(ownerId2 = 0) {
      return this._decorationsTree.getAllCustomLineHeights(this, ownerId2);
    }
    _getInjectedTextInLine(lineNumber) {
      const startOffset = this._buffer.getOffsetAt(lineNumber, 1);
      const endOffset = startOffset + this._buffer.getLineLength(lineNumber);
      const result = this._decorationsTree.getInjectedTextInInterval(this, startOffset, endOffset, 0);
      return LineInjectedText.fromDecorations(result).filter((t) => t.lineNumber === lineNumber);
    }
    getFontDecorationsInRange(range2, ownerId2 = 0) {
      const startOffset = this._buffer.getOffsetAt(range2.startLineNumber, range2.startColumn);
      const endOffset = this._buffer.getOffsetAt(range2.endLineNumber, range2.endColumn);
      return this._decorationsTree.getFontDecorationsInInterval(this, startOffset, endOffset, ownerId2);
    }
    getAllDecorations(ownerId2 = 0, filterOutValidation = false, filterFontDecorations2 = false) {
      let result = this._decorationsTree.getAll(this, ownerId2, filterOutValidation, filterFontDecorations2, false, false);
      result = result.concat(this._decorationProvider.getAllDecorations(ownerId2, filterOutValidation));
      return result;
    }
    getAllMarginDecorations(ownerId2 = 0) {
      return this._decorationsTree.getAll(this, ownerId2, false, false, false, true);
    }
    _getDecorationsInRange(filterRange, filterOwnerId, filterOutValidation, filterFontDecorations2, onlyMarginDecorations) {
      const startOffset = this._buffer.getOffsetAt(filterRange.startLineNumber, filterRange.startColumn);
      const endOffset = this._buffer.getOffsetAt(filterRange.endLineNumber, filterRange.endColumn);
      return this._decorationsTree.getAllInInterval(this, startOffset, endOffset, filterOwnerId, filterOutValidation, filterFontDecorations2, onlyMarginDecorations);
    }
    getRangeAt(start, end) {
      return this._buffer.getRangeAt(start, end - start);
    }
    _changeDecorationImpl(ownerId2, decorationId, _range) {
      const node = this._decorations[decorationId];
      if (!node) {
        return;
      }
      if (node.options.after) {
        const oldRange = this.getDecorationRange(decorationId);
        this._onDidChangeDecorations.recordLineAffectedByInjectedText(oldRange.endLineNumber);
      }
      if (node.options.before) {
        const oldRange = this.getDecorationRange(decorationId);
        this._onDidChangeDecorations.recordLineAffectedByInjectedText(oldRange.startLineNumber);
      }
      if (node.options.lineHeight !== null) {
        const oldRange = this.getDecorationRange(decorationId);
        this._onDidChangeDecorations.recordLineAffectedByLineHeightChange(ownerId2, decorationId, oldRange.startLineNumber, null);
      }
      if (node.options.affectsFont) {
        const oldRange = this.getDecorationRange(decorationId);
        this._onDidChangeDecorations.recordLineAffectedByFontChange(ownerId2, node.id, oldRange.startLineNumber);
      }
      const range2 = this._validateRangeRelaxedNoAllocations(_range);
      const startOffset = this._buffer.getOffsetAt(range2.startLineNumber, range2.startColumn);
      const endOffset = this._buffer.getOffsetAt(range2.endLineNumber, range2.endColumn);
      this._decorationsTree.delete(node);
      node.reset(this.getVersionId(), startOffset, endOffset, range2);
      this._decorationsTree.insert(node);
      this._onDidChangeDecorations.checkAffectedAndFire(node.options);
      if (node.options.after) {
        this._onDidChangeDecorations.recordLineAffectedByInjectedText(range2.endLineNumber);
      }
      if (node.options.before) {
        this._onDidChangeDecorations.recordLineAffectedByInjectedText(range2.startLineNumber);
      }
      if (node.options.lineHeight !== null) {
        this._onDidChangeDecorations.recordLineAffectedByLineHeightChange(ownerId2, decorationId, range2.startLineNumber, node.options.lineHeight);
      }
      if (node.options.affectsFont) {
        this._onDidChangeDecorations.recordLineAffectedByFontChange(ownerId2, node.id, range2.startLineNumber);
      }
    }
    _changeDecorationOptionsImpl(ownerId2, decorationId, options) {
      const node = this._decorations[decorationId];
      if (!node) {
        return;
      }
      const nodeWasInOverviewRuler = node.options.overviewRuler && node.options.overviewRuler.color ? true : false;
      const nodeIsInOverviewRuler = options.overviewRuler && options.overviewRuler.color ? true : false;
      this._onDidChangeDecorations.checkAffectedAndFire(node.options);
      this._onDidChangeDecorations.checkAffectedAndFire(options);
      if (node.options.after || options.after) {
        const nodeRange = this._decorationsTree.getNodeRange(this, node);
        this._onDidChangeDecorations.recordLineAffectedByInjectedText(nodeRange.endLineNumber);
      }
      if (node.options.before || options.before) {
        const nodeRange = this._decorationsTree.getNodeRange(this, node);
        this._onDidChangeDecorations.recordLineAffectedByInjectedText(nodeRange.startLineNumber);
      }
      if (node.options.lineHeight !== null || options.lineHeight !== null) {
        const nodeRange = this._decorationsTree.getNodeRange(this, node);
        this._onDidChangeDecorations.recordLineAffectedByLineHeightChange(ownerId2, decorationId, nodeRange.startLineNumber, options.lineHeight);
      }
      if (node.options.affectsFont || options.affectsFont) {
        const nodeRange = this._decorationsTree.getNodeRange(this, node);
        this._onDidChangeDecorations.recordLineAffectedByFontChange(ownerId2, decorationId, nodeRange.startLineNumber);
      }
      const movedInOverviewRuler = nodeWasInOverviewRuler !== nodeIsInOverviewRuler;
      const changedWhetherInjectedText = isOptionsInjectedText(options) !== isNodeInjectedText(node);
      if (movedInOverviewRuler || changedWhetherInjectedText) {
        this._decorationsTree.delete(node);
        node.setOptions(options);
        this._decorationsTree.insert(node);
      } else {
        node.setOptions(options);
      }
    }
    _deltaDecorationsImpl(ownerId2, oldDecorationsIds, newDecorations, suppressEvents = false) {
      const versionId = this.getVersionId();
      const oldDecorationsLen = oldDecorationsIds.length;
      let oldDecorationIndex = 0;
      const newDecorationsLen = newDecorations.length;
      let newDecorationIndex = 0;
      this._onDidChangeDecorations.beginDeferredEmit();
      try {
        const result = new Array(newDecorationsLen);
        while (oldDecorationIndex < oldDecorationsLen || newDecorationIndex < newDecorationsLen) {
          let node = null;
          if (oldDecorationIndex < oldDecorationsLen) {
            let decorationId;
            do {
              decorationId = oldDecorationsIds[oldDecorationIndex++];
              node = this._decorations[decorationId];
            } while (!node && oldDecorationIndex < oldDecorationsLen);
            if (node) {
              if (node.options.after) {
                const nodeRange = this._decorationsTree.getNodeRange(this, node);
                this._onDidChangeDecorations.recordLineAffectedByInjectedText(nodeRange.endLineNumber);
              }
              if (node.options.before) {
                const nodeRange = this._decorationsTree.getNodeRange(this, node);
                this._onDidChangeDecorations.recordLineAffectedByInjectedText(nodeRange.startLineNumber);
              }
              if (node.options.lineHeight !== null) {
                const nodeRange = this._decorationsTree.getNodeRange(this, node);
                this._onDidChangeDecorations.recordLineAffectedByLineHeightChange(ownerId2, decorationId, nodeRange.startLineNumber, null);
              }
              if (node.options.affectsFont) {
                const nodeRange = this._decorationsTree.getNodeRange(this, node);
                this._onDidChangeDecorations.recordLineAffectedByFontChange(ownerId2, decorationId, nodeRange.startLineNumber);
              }
              this._decorationsTree.delete(node);
              if (!suppressEvents) {
                this._onDidChangeDecorations.checkAffectedAndFire(node.options);
              }
            }
          }
          if (newDecorationIndex < newDecorationsLen) {
            if (!node) {
              const internalDecorationId = ++this._lastDecorationId;
              const decorationId = `${this._instanceId};${internalDecorationId}`;
              node = new IntervalNode(decorationId, 0, 0);
              this._decorations[decorationId] = node;
            }
            const newDecoration = newDecorations[newDecorationIndex];
            const range2 = this._validateRangeRelaxedNoAllocations(newDecoration.range);
            const options = _normalizeOptions(newDecoration.options);
            const startOffset = this._buffer.getOffsetAt(range2.startLineNumber, range2.startColumn);
            const endOffset = this._buffer.getOffsetAt(range2.endLineNumber, range2.endColumn);
            node.ownerId = ownerId2;
            node.reset(versionId, startOffset, endOffset, range2);
            node.setOptions(options);
            if (node.options.after) {
              this._onDidChangeDecorations.recordLineAffectedByInjectedText(range2.endLineNumber);
            }
            if (node.options.before) {
              this._onDidChangeDecorations.recordLineAffectedByInjectedText(range2.startLineNumber);
            }
            if (node.options.lineHeight !== null) {
              this._onDidChangeDecorations.recordLineAffectedByLineHeightChange(ownerId2, node.id, range2.startLineNumber, node.options.lineHeight);
            }
            if (node.options.affectsFont) {
              this._onDidChangeDecorations.recordLineAffectedByFontChange(ownerId2, node.id, range2.startLineNumber);
            }
            if (!suppressEvents) {
              this._onDidChangeDecorations.checkAffectedAndFire(options);
            }
            this._decorationsTree.insert(node);
            result[newDecorationIndex] = node.id;
            newDecorationIndex++;
          } else {
            if (node) {
              delete this._decorations[node.id];
            }
          }
        }
        return result;
      } finally {
        this._onDidChangeDecorations.endDeferredEmit();
      }
    }
    //#endregion
    //#region Tokenization
    // TODO move them to the tokenization part.
    getLanguageId() {
      return this.tokenization.getLanguageId();
    }
    setLanguage(languageIdOrSelection, source) {
      if (typeof languageIdOrSelection === "string") {
        this._languageSelectionListener.clear();
        this._setLanguage(languageIdOrSelection, source);
      } else {
        this._languageSelectionListener.value = languageIdOrSelection.onDidChange(() => this._setLanguage(languageIdOrSelection.languageId, source));
        this._setLanguage(languageIdOrSelection.languageId, source);
      }
    }
    _setLanguage(languageId, source) {
      this.tokenization.setLanguageId(languageId, source);
      this._languageService.requestRichLanguageFeatures(languageId);
    }
    getLanguageIdAtPosition(lineNumber, column) {
      return this.tokenization.getLanguageIdAtPosition(lineNumber, column);
    }
    getWordAtPosition(position) {
      return this._tokenizationTextModelPart.getWordAtPosition(position);
    }
    getWordUntilPosition(position) {
      return this._tokenizationTextModelPart.getWordUntilPosition(position);
    }
    //#endregion
    normalizePosition(position, affinity) {
      return position;
    }
    /**
     * Gets the column at which indentation stops at a given line.
     * @internal
    */
    getLineIndentColumn(lineNumber) {
      return indentOfLine(this.getLineContent(lineNumber)) + 1;
    }
    toString() {
      return `TextModel(${this.uri.toString()})`;
    }
  }, TextModel_1 = _h, _h._MODEL_SYNC_LIMIT = 50 * 1024 * 1024, _h.LARGE_FILE_SIZE_THRESHOLD = 20 * 1024 * 1024, _h.LARGE_FILE_LINE_COUNT_THRESHOLD = 300 * 1e3, _h.LARGE_FILE_HEAP_OPERATION_THRESHOLD = 256 * 1024 * 1024, _h.DEFAULT_CREATION_OPTIONS = {
    isForSimpleWidget: false,
    tabSize: EDITOR_MODEL_DEFAULTS.tabSize,
    indentSize: EDITOR_MODEL_DEFAULTS.indentSize,
    insertSpaces: EDITOR_MODEL_DEFAULTS.insertSpaces,
    detectIndentation: false,
    defaultEOL: 1,
    trimAutoWhitespace: EDITOR_MODEL_DEFAULTS.trimAutoWhitespace,
    largeFileOptimizations: EDITOR_MODEL_DEFAULTS.largeFileOptimizations,
    bracketPairColorizationOptions: EDITOR_MODEL_DEFAULTS.bracketPairColorizationOptions
  }, _h);
  TextModel = TextModel_1 = __decorate$2L([
    __param$2G(4, IUndoRedoService),
    __param$2G(5, ILanguageService),
    __param$2G(6, ILanguageConfigurationService),
    __param$2G(7, IInstantiationService)
  ], TextModel);
  function indentOfLine(line) {
    let indent = 0;
    for (const c of line) {
      if (c === " " || c === "	") {
        indent++;
      } else {
        break;
      }
    }
    return indent;
  }
  function isNodeInOverviewRuler(node) {
    return node.options.overviewRuler && node.options.overviewRuler.color ? true : false;
  }
  function isOptionsInjectedText(options) {
    return !!options.after || !!options.before;
  }
  function isNodeInjectedText(node) {
    return !!node.options.after || !!node.options.before;
  }
  class DecorationsTrees {
    constructor() {
      this._decorationsTree0 = new IntervalTree();
      this._decorationsTree1 = new IntervalTree();
      this._injectedTextDecorationsTree = new IntervalTree();
    }
    ensureAllNodesHaveRanges(host) {
      this.getAll(host, 0, false, false, false, false);
    }
    _ensureNodesHaveRanges(host, nodes) {
      for (const node of nodes) {
        if (node.range === null) {
          node.range = host.getRangeAt(node.cachedAbsoluteStart, node.cachedAbsoluteEnd);
        }
      }
      return nodes;
    }
    getAllInInterval(host, start, end, filterOwnerId, filterOutValidation, filterFontDecorations2, onlyMarginDecorations) {
      const versionId = host.getVersionId();
      const result = this._intervalSearch(start, end, filterOwnerId, filterOutValidation, filterFontDecorations2, versionId, onlyMarginDecorations);
      return this._ensureNodesHaveRanges(host, result);
    }
    _intervalSearch(start, end, filterOwnerId, filterOutValidation, filterFontDecorations2, cachedVersionId, onlyMarginDecorations) {
      const r0 = this._decorationsTree0.intervalSearch(start, end, filterOwnerId, filterOutValidation, filterFontDecorations2, cachedVersionId, onlyMarginDecorations);
      const r1 = this._decorationsTree1.intervalSearch(start, end, filterOwnerId, filterOutValidation, filterFontDecorations2, cachedVersionId, onlyMarginDecorations);
      const r2 = this._injectedTextDecorationsTree.intervalSearch(start, end, filterOwnerId, filterOutValidation, filterFontDecorations2, cachedVersionId, onlyMarginDecorations);
      return r0.concat(r1).concat(r2);
    }
    getInjectedTextInInterval(host, start, end, filterOwnerId) {
      const versionId = host.getVersionId();
      const result = this._injectedTextDecorationsTree.intervalSearch(start, end, filterOwnerId, false, false, versionId, false);
      return this._ensureNodesHaveRanges(host, result).filter((i2) => i2.options.showIfCollapsed || !i2.range.isEmpty());
    }
    getFontDecorationsInInterval(host, start, end, filterOwnerId) {
      const versionId = host.getVersionId();
      const decorations = this._decorationsTree0.intervalSearch(start, end, filterOwnerId, false, false, versionId, false);
      return this._ensureNodesHaveRanges(host, decorations).filter((i2) => i2.options.affectsFont);
    }
    getAllInjectedText(host, filterOwnerId) {
      const versionId = host.getVersionId();
      const result = this._injectedTextDecorationsTree.search(filterOwnerId, false, false, versionId, false);
      return this._ensureNodesHaveRanges(host, result).filter((i2) => i2.options.showIfCollapsed || !i2.range.isEmpty());
    }
    getAllCustomLineHeights(host, filterOwnerId) {
      const versionId = host.getVersionId();
      const result = this._search(filterOwnerId, false, false, false, versionId, false);
      return this._ensureNodesHaveRanges(host, result).filter((i2) => typeof i2.options.lineHeight === "number");
    }
    getAll(host, filterOwnerId, filterOutValidation, filterFontDecorations2, overviewRulerOnly, onlyMarginDecorations) {
      const versionId = host.getVersionId();
      const result = this._search(filterOwnerId, filterOutValidation, filterFontDecorations2, overviewRulerOnly, versionId, onlyMarginDecorations);
      return this._ensureNodesHaveRanges(host, result);
    }
    _search(filterOwnerId, filterOutValidation, filterFontDecorations2, overviewRulerOnly, cachedVersionId, onlyMarginDecorations) {
      if (overviewRulerOnly) {
        return this._decorationsTree1.search(filterOwnerId, filterOutValidation, filterFontDecorations2, cachedVersionId, onlyMarginDecorations);
      } else {
        const r0 = this._decorationsTree0.search(filterOwnerId, filterOutValidation, filterFontDecorations2, cachedVersionId, onlyMarginDecorations);
        const r1 = this._decorationsTree1.search(filterOwnerId, filterOutValidation, filterFontDecorations2, cachedVersionId, onlyMarginDecorations);
        const r2 = this._injectedTextDecorationsTree.search(filterOwnerId, filterOutValidation, filterFontDecorations2, cachedVersionId, onlyMarginDecorations);
        return r0.concat(r1).concat(r2);
      }
    }
    collectNodesFromOwner(ownerId2) {
      const r0 = this._decorationsTree0.collectNodesFromOwner(ownerId2);
      const r1 = this._decorationsTree1.collectNodesFromOwner(ownerId2);
      const r2 = this._injectedTextDecorationsTree.collectNodesFromOwner(ownerId2);
      return r0.concat(r1).concat(r2);
    }
    collectNodesPostOrder() {
      const r0 = this._decorationsTree0.collectNodesPostOrder();
      const r1 = this._decorationsTree1.collectNodesPostOrder();
      const r2 = this._injectedTextDecorationsTree.collectNodesPostOrder();
      return r0.concat(r1).concat(r2);
    }
    insert(node) {
      if (isNodeInjectedText(node)) {
        this._injectedTextDecorationsTree.insert(node);
      } else if (isNodeInOverviewRuler(node)) {
        this._decorationsTree1.insert(node);
      } else {
        this._decorationsTree0.insert(node);
      }
    }
    delete(node) {
      if (isNodeInjectedText(node)) {
        this._injectedTextDecorationsTree.delete(node);
      } else if (isNodeInOverviewRuler(node)) {
        this._decorationsTree1.delete(node);
      } else {
        this._decorationsTree0.delete(node);
      }
    }
    getNodeRange(host, node) {
      const versionId = host.getVersionId();
      if (node.cachedVersionId !== versionId) {
        this._resolveNode(node, versionId);
      }
      if (node.range === null) {
        node.range = host.getRangeAt(node.cachedAbsoluteStart, node.cachedAbsoluteEnd);
      }
      return node.range;
    }
    _resolveNode(node, cachedVersionId) {
      if (isNodeInjectedText(node)) {
        this._injectedTextDecorationsTree.resolveNode(node, cachedVersionId);
      } else if (isNodeInOverviewRuler(node)) {
        this._decorationsTree1.resolveNode(node, cachedVersionId);
      } else {
        this._decorationsTree0.resolveNode(node, cachedVersionId);
      }
    }
    acceptReplace(offset, length, textLength, forceMoveMarkers) {
      this._decorationsTree0.acceptReplace(offset, length, textLength, forceMoveMarkers);
      this._decorationsTree1.acceptReplace(offset, length, textLength, forceMoveMarkers);
      this._injectedTextDecorationsTree.acceptReplace(offset, length, textLength, forceMoveMarkers);
    }
  }
  function cleanClassName(className2) {
    return className2.replace(/[^a-z0-9\-_]/gi, " ");
  }
  class DecorationOptions {
    constructor(options) {
      this.color = options.color || "";
      this.darkColor = options.darkColor || "";
    }
  }
  class ModelDecorationOverviewRulerOptions extends DecorationOptions {
    constructor(options) {
      super(options);
      this._resolvedColor = null;
      this.position = typeof options.position === "number" ? options.position : OverviewRulerLane$1.Center;
    }
    getColor(theme) {
      if (!this._resolvedColor) {
        if (isDark(theme.type) && this.darkColor) {
          this._resolvedColor = this._resolveColor(this.darkColor, theme);
        } else {
          this._resolvedColor = this._resolveColor(this.color, theme);
        }
      }
      return this._resolvedColor;
    }
    invalidateCachedColor() {
      this._resolvedColor = null;
    }
    _resolveColor(color, theme) {
      if (typeof color === "string") {
        return color;
      }
      const c = color ? theme.getColor(color.id) : null;
      if (!c) {
        return "";
      }
      return c.toString();
    }
  }
  class ModelDecorationGlyphMarginOptions {
    constructor(options) {
      this.position = options?.position ?? GlyphMarginLane$1.Center;
      this.persistLane = options?.persistLane;
    }
  }
  class ModelDecorationMinimapOptions extends DecorationOptions {
    constructor(options) {
      super(options);
      this.position = options.position;
      this.sectionHeaderStyle = options.sectionHeaderStyle ?? null;
      this.sectionHeaderText = options.sectionHeaderText ?? null;
    }
    getColor(theme) {
      if (!this._resolvedColor) {
        if (isDark(theme.type) && this.darkColor) {
          this._resolvedColor = this._resolveColor(this.darkColor, theme);
        } else {
          this._resolvedColor = this._resolveColor(this.color, theme);
        }
      }
      return this._resolvedColor;
    }
    invalidateCachedColor() {
      this._resolvedColor = void 0;
    }
    _resolveColor(color, theme) {
      if (typeof color === "string") {
        return Color.fromHex(color);
      }
      return theme.getColor(color.id);
    }
  }
  class ModelDecorationInjectedTextOptions {
    static from(options) {
      if (options instanceof ModelDecorationInjectedTextOptions) {
        return options;
      }
      return new ModelDecorationInjectedTextOptions(options);
    }
    constructor(options) {
      this.content = options.content || "";
      this.tokens = options.tokens ?? null;
      this.inlineClassName = options.inlineClassName || null;
      this.inlineClassNameAffectsLetterSpacing = options.inlineClassNameAffectsLetterSpacing || false;
      this.attachedData = options.attachedData || null;
      this.cursorStops = options.cursorStops || null;
    }
  }
  class ModelDecorationOptions {
    static register(options) {
      return new ModelDecorationOptions(options);
    }
    static createDynamic(options) {
      return new ModelDecorationOptions(options);
    }
    constructor(options) {
      this.description = options.description;
      this.blockClassName = options.blockClassName ? cleanClassName(options.blockClassName) : null;
      this.blockDoesNotCollapse = options.blockDoesNotCollapse ?? null;
      this.blockIsAfterEnd = options.blockIsAfterEnd ?? null;
      this.blockPadding = options.blockPadding ?? null;
      this.stickiness = options.stickiness || 0;
      this.zIndex = options.zIndex || 0;
      this.className = options.className ? cleanClassName(options.className) : null;
      this.shouldFillLineOnLineBreak = options.shouldFillLineOnLineBreak ?? null;
      this.hoverMessage = options.hoverMessage || null;
      this.glyphMarginHoverMessage = options.glyphMarginHoverMessage || null;
      this.lineNumberHoverMessage = options.lineNumberHoverMessage || null;
      this.isWholeLine = options.isWholeLine || false;
      this.lineHeight = options.lineHeight ? Math.min(options.lineHeight, LINE_HEIGHT_CEILING) : null;
      this.fontSize = options.fontSize || null;
      this.affectsFont = !!options.fontSize || !!options.fontFamily || !!options.fontWeight || !!options.fontStyle;
      this.showIfCollapsed = options.showIfCollapsed || false;
      this.collapseOnReplaceEdit = options.collapseOnReplaceEdit || false;
      this.overviewRuler = options.overviewRuler ? new ModelDecorationOverviewRulerOptions(options.overviewRuler) : null;
      this.minimap = options.minimap ? new ModelDecorationMinimapOptions(options.minimap) : null;
      this.glyphMargin = options.glyphMarginClassName ? new ModelDecorationGlyphMarginOptions(options.glyphMargin) : null;
      this.glyphMarginClassName = options.glyphMarginClassName ? cleanClassName(options.glyphMarginClassName) : null;
      this.linesDecorationsClassName = options.linesDecorationsClassName ? cleanClassName(options.linesDecorationsClassName) : null;
      this.lineNumberClassName = options.lineNumberClassName ? cleanClassName(options.lineNumberClassName) : null;
      this.linesDecorationsTooltip = options.linesDecorationsTooltip ? htmlAttributeEncodeValue(options.linesDecorationsTooltip) : null;
      this.firstLineDecorationClassName = options.firstLineDecorationClassName ? cleanClassName(options.firstLineDecorationClassName) : null;
      this.marginClassName = options.marginClassName ? cleanClassName(options.marginClassName) : null;
      this.inlineClassName = options.inlineClassName ? cleanClassName(options.inlineClassName) : null;
      this.inlineClassNameAffectsLetterSpacing = options.inlineClassNameAffectsLetterSpacing || false;
      this.beforeContentClassName = options.beforeContentClassName ? cleanClassName(options.beforeContentClassName) : null;
      this.afterContentClassName = options.afterContentClassName ? cleanClassName(options.afterContentClassName) : null;
      this.after = options.after ? ModelDecorationInjectedTextOptions.from(options.after) : null;
      this.before = options.before ? ModelDecorationInjectedTextOptions.from(options.before) : null;
      this.hideInCommentTokens = options.hideInCommentTokens ?? false;
      this.hideInStringTokens = options.hideInStringTokens ?? false;
      this.textDirection = options.textDirection ?? null;
    }
  }
  ModelDecorationOptions.EMPTY = ModelDecorationOptions.register({ description: "empty" });
  const TRACKED_RANGE_OPTIONS = [
    ModelDecorationOptions.register({
      description: "tracked-range-always-grows-when-typing-at-edges",
      stickiness: 0
      /* model.TrackedRangeStickiness.AlwaysGrowsWhenTypingAtEdges */
    }),
    ModelDecorationOptions.register({
      description: "tracked-range-never-grows-when-typing-at-edges",
      stickiness: 1
      /* model.TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */
    }),
    ModelDecorationOptions.register({
      description: "tracked-range-grows-only-when-typing-before",
      stickiness: 2
      /* model.TrackedRangeStickiness.GrowsOnlyWhenTypingBefore */
    }),
    ModelDecorationOptions.register({
      description: "tracked-range-grows-only-when-typing-after",
      stickiness: 3
      /* model.TrackedRangeStickiness.GrowsOnlyWhenTypingAfter */
    })
  ];
  function _normalizeOptions(options) {
    if (options instanceof ModelDecorationOptions) {
      return options;
    }
    return ModelDecorationOptions.createDynamic(options);
  }
  class LineHeightChangingDecoration {
    static toKey(obj) {
      return `${obj.ownerId};${obj.decorationId};${obj.lineNumber}`;
    }
    constructor(ownerId2, decorationId, lineNumber, lineHeight) {
      this.ownerId = ownerId2;
      this.decorationId = decorationId;
      this.lineNumber = lineNumber;
      this.lineHeight = lineHeight;
    }
  }
  class LineFontChangingDecoration {
    static toKey(obj) {
      return `${obj.ownerId};${obj.decorationId};${obj.lineNumber}`;
    }
    constructor(ownerId2, decorationId, lineNumber) {
      this.ownerId = ownerId2;
      this.decorationId = decorationId;
      this.lineNumber = lineNumber;
    }
  }
  class DidChangeDecorationsEmitter extends Disposable {
    constructor(handleBeforeFire) {
      super();
      this.handleBeforeFire = handleBeforeFire;
      this._actual = this._register(new Emitter$1());
      this.event = this._actual.event;
      this._affectedInjectedTextLines = null;
      this._affectedLineHeights = null;
      this._affectedFontLines = null;
      this._deferredCnt = 0;
      this._shouldFireDeferred = false;
      this._affectsMinimap = false;
      this._affectsOverviewRuler = false;
      this._affectsGlyphMargin = false;
      this._affectsLineNumber = false;
    }
    beginDeferredEmit() {
      this._deferredCnt++;
    }
    endDeferredEmit() {
      this._deferredCnt--;
      if (this._deferredCnt === 0) {
        if (this._shouldFireDeferred) {
          this.doFire();
        }
        this._affectedInjectedTextLines?.clear();
        this._affectedInjectedTextLines = null;
        this._affectedLineHeights?.clear();
        this._affectedLineHeights = null;
        this._affectedFontLines?.clear();
        this._affectedFontLines = null;
      }
    }
    recordLineAffectedByInjectedText(lineNumber) {
      if (!this._affectedInjectedTextLines) {
        this._affectedInjectedTextLines = /* @__PURE__ */ new Set();
      }
      this._affectedInjectedTextLines.add(lineNumber);
    }
    recordLineAffectedByLineHeightChange(ownerId2, decorationId, lineNumber, lineHeight) {
      if (!this._affectedLineHeights) {
        this._affectedLineHeights = new SetWithKey([], LineHeightChangingDecoration.toKey);
      }
      this._affectedLineHeights.add(new LineHeightChangingDecoration(ownerId2, decorationId, lineNumber, lineHeight));
    }
    recordLineAffectedByFontChange(ownerId2, decorationId, lineNumber) {
      if (!this._affectedFontLines) {
        this._affectedFontLines = new SetWithKey([], LineFontChangingDecoration.toKey);
      }
      this._affectedFontLines.add(new LineFontChangingDecoration(ownerId2, decorationId, lineNumber));
    }
    checkAffectedAndFire(options) {
      this._affectsMinimap ||= !!options.minimap?.position;
      this._affectsOverviewRuler ||= !!options.overviewRuler?.color;
      this._affectsGlyphMargin ||= !!options.glyphMarginClassName;
      this._affectsLineNumber ||= !!options.lineNumberClassName;
      this.tryFire();
    }
    fire() {
      this._affectsMinimap = true;
      this._affectsOverviewRuler = true;
      this._affectsGlyphMargin = true;
      this.tryFire();
    }
    tryFire() {
      if (this._deferredCnt === 0) {
        this.doFire();
      } else {
        this._shouldFireDeferred = true;
      }
    }
    doFire() {
      this.handleBeforeFire(this._affectedInjectedTextLines, this._affectedLineHeights, this._affectedFontLines);
      const event = {
        affectsMinimap: this._affectsMinimap,
        affectsOverviewRuler: this._affectsOverviewRuler,
        affectsGlyphMargin: this._affectsGlyphMargin,
        affectsLineNumber: this._affectsLineNumber
      };
      this._shouldFireDeferred = false;
      this._affectsMinimap = false;
      this._affectsOverviewRuler = false;
      this._affectsGlyphMargin = false;
      this._actual.fire(event);
    }
  }
  class DidChangeContentEmitter extends Disposable {
    constructor() {
      super();
      this._fastEmitter = this._register(new Emitter$1());
      this.fastEvent = this._fastEmitter.event;
      this._slowEmitter = this._register(new Emitter$1());
      this.slowEvent = this._slowEmitter.event;
      this._deferredCnt = 0;
      this._deferredEvent = null;
    }
    beginDeferredEmit() {
      this._deferredCnt++;
    }
    endDeferredEmit(resultingSelection = null) {
      this._deferredCnt--;
      if (this._deferredCnt === 0) {
        if (this._deferredEvent !== null) {
          this._deferredEvent.rawContentChangedEvent.resultingSelection = resultingSelection;
          const e = this._deferredEvent;
          this._deferredEvent = null;
          this._fastEmitter.fire(e);
          this._slowEmitter.fire(e);
        }
      }
    }
    fire(e) {
      if (this._deferredCnt > 0) {
        if (this._deferredEvent) {
          this._deferredEvent = this._deferredEvent.merge(e);
        } else {
          this._deferredEvent = e;
        }
        return;
      }
      this._fastEmitter.fire(e);
      this._slowEmitter.fire(e);
    }
  }
  const ILanguageFeaturesService = createDecorator("ILanguageFeaturesService");
  class MonospaceLineBreaksComputerFactory {
    static create(options) {
      return new MonospaceLineBreaksComputerFactory(options.get(
        151
        /* EditorOption.wordWrapBreakBeforeCharacters */
      ), options.get(
        150
        /* EditorOption.wordWrapBreakAfterCharacters */
      ));
    }
    constructor(breakBeforeChars, breakAfterChars) {
      this.classifier = new WrappingCharacterClassifier(breakBeforeChars, breakAfterChars);
    }
    createLineBreaksComputer(fontInfo, tabSize, wrappingColumn, wrappingIndent, wordBreak, wrapOnEscapedLineFeeds) {
      const requests = [];
      const injectedTexts = [];
      const previousBreakingData = [];
      return {
        addRequest: (lineText, injectedText, previousLineBreakData) => {
          requests.push(lineText);
          injectedTexts.push(injectedText);
          previousBreakingData.push(previousLineBreakData);
        },
        finalize: () => {
          const columnsForFullWidthChar = fontInfo.typicalFullwidthCharacterWidth / fontInfo.typicalHalfwidthCharacterWidth;
          const result = [];
          for (let i2 = 0, len = requests.length; i2 < len; i2++) {
            const injectedText = injectedTexts[i2];
            const previousLineBreakData = previousBreakingData[i2];
            const lineText = requests[i2];
            const isLineFeedWrappingEnabled = wrapOnEscapedLineFeeds && lineText.includes('"') && lineText.includes("\\n");
            if (previousLineBreakData && !previousLineBreakData.injectionOptions && !injectedText && !isLineFeedWrappingEnabled) {
              result[i2] = createLineBreaksFromPreviousLineBreaks(this.classifier, previousLineBreakData, lineText, tabSize, wrappingColumn, columnsForFullWidthChar, wrappingIndent, wordBreak);
            } else {
              result[i2] = createLineBreaks(this.classifier, lineText, injectedText, tabSize, wrappingColumn, columnsForFullWidthChar, wrappingIndent, wordBreak, isLineFeedWrappingEnabled);
            }
          }
          arrPool1.length = 0;
          arrPool2.length = 0;
          return result;
        }
      };
    }
  }
  class WrappingCharacterClassifier extends CharacterClassifier {
    constructor(BREAK_BEFORE, BREAK_AFTER) {
      super(
        0
        /* CharacterClass.NONE */
      );
      for (let i2 = 0; i2 < BREAK_BEFORE.length; i2++) {
        this.set(
          BREAK_BEFORE.charCodeAt(i2),
          1
          /* CharacterClass.BREAK_BEFORE */
        );
      }
      for (let i2 = 0; i2 < BREAK_AFTER.length; i2++) {
        this.set(
          BREAK_AFTER.charCodeAt(i2),
          2
          /* CharacterClass.BREAK_AFTER */
        );
      }
    }
    get(charCode) {
      if (charCode >= 0 && charCode < 256) {
        return this._asciiMap[charCode];
      } else {
        if (charCode >= 12352 && charCode <= 12543 || charCode >= 13312 && charCode <= 19903 || charCode >= 19968 && charCode <= 40959) {
          return 3;
        }
        return this._map.get(charCode) || this._defaultValue;
      }
    }
  }
  let arrPool1 = [];
  let arrPool2 = [];
  function createLineBreaksFromPreviousLineBreaks(classifier, previousBreakingData, lineText, tabSize, firstLineBreakColumn, columnsForFullWidthChar, wrappingIndent, wordBreak) {
    if (firstLineBreakColumn === -1) {
      return null;
    }
    const len = lineText.length;
    if (len <= 1) {
      return null;
    }
    const isKeepAll = wordBreak === "keepAll";
    const prevBreakingOffsets = previousBreakingData.breakOffsets;
    const prevBreakingOffsetsVisibleColumn = previousBreakingData.breakOffsetsVisibleColumn;
    const wrappedTextIndentLength = computeWrappedTextIndentLength(lineText, tabSize, firstLineBreakColumn, columnsForFullWidthChar, wrappingIndent);
    const wrappedLineBreakColumn = firstLineBreakColumn - wrappedTextIndentLength;
    const breakingOffsets = arrPool1;
    const breakingOffsetsVisibleColumn = arrPool2;
    let breakingOffsetsCount = 0;
    let lastBreakingOffset = 0;
    let lastBreakingOffsetVisibleColumn = 0;
    let breakingColumn = firstLineBreakColumn;
    const prevLen = prevBreakingOffsets.length;
    let prevIndex = 0;
    if (prevIndex >= 0) {
      let bestDistance = Math.abs(prevBreakingOffsetsVisibleColumn[prevIndex] - breakingColumn);
      while (prevIndex + 1 < prevLen) {
        const distance = Math.abs(prevBreakingOffsetsVisibleColumn[prevIndex + 1] - breakingColumn);
        if (distance >= bestDistance) {
          break;
        }
        bestDistance = distance;
        prevIndex++;
      }
    }
    while (prevIndex < prevLen) {
      let prevBreakOffset = prevIndex < 0 ? 0 : prevBreakingOffsets[prevIndex];
      let prevBreakOffsetVisibleColumn = prevIndex < 0 ? 0 : prevBreakingOffsetsVisibleColumn[prevIndex];
      if (lastBreakingOffset > prevBreakOffset) {
        prevBreakOffset = lastBreakingOffset;
        prevBreakOffsetVisibleColumn = lastBreakingOffsetVisibleColumn;
      }
      let breakOffset = 0;
      let breakOffsetVisibleColumn = 0;
      let forcedBreakOffset = 0;
      let forcedBreakOffsetVisibleColumn = 0;
      if (prevBreakOffsetVisibleColumn <= breakingColumn) {
        let visibleColumn = prevBreakOffsetVisibleColumn;
        let prevCharCode = prevBreakOffset === 0 ? 0 : lineText.charCodeAt(prevBreakOffset - 1);
        let prevCharCodeClass = prevBreakOffset === 0 ? 0 : classifier.get(prevCharCode);
        let entireLineFits = true;
        for (let i2 = prevBreakOffset; i2 < len; i2++) {
          const charStartOffset = i2;
          const charCode = lineText.charCodeAt(i2);
          let charCodeClass;
          let charWidth;
          if (isHighSurrogate(charCode)) {
            i2++;
            charCodeClass = 0;
            charWidth = 2;
          } else {
            charCodeClass = classifier.get(charCode);
            charWidth = computeCharWidth(charCode, visibleColumn, tabSize, columnsForFullWidthChar);
          }
          if (charStartOffset > lastBreakingOffset && canBreak(prevCharCode, prevCharCodeClass, charCode, charCodeClass, isKeepAll)) {
            breakOffset = charStartOffset;
            breakOffsetVisibleColumn = visibleColumn;
          }
          visibleColumn += charWidth;
          if (visibleColumn > breakingColumn) {
            if (charStartOffset > lastBreakingOffset) {
              forcedBreakOffset = charStartOffset;
              forcedBreakOffsetVisibleColumn = visibleColumn - charWidth;
            } else {
              forcedBreakOffset = i2 + 1;
              forcedBreakOffsetVisibleColumn = visibleColumn;
            }
            if (visibleColumn - breakOffsetVisibleColumn > wrappedLineBreakColumn) {
              breakOffset = 0;
            }
            entireLineFits = false;
            break;
          }
          prevCharCode = charCode;
          prevCharCodeClass = charCodeClass;
        }
        if (entireLineFits) {
          if (breakingOffsetsCount > 0) {
            breakingOffsets[breakingOffsetsCount] = prevBreakingOffsets[prevBreakingOffsets.length - 1];
            breakingOffsetsVisibleColumn[breakingOffsetsCount] = prevBreakingOffsetsVisibleColumn[prevBreakingOffsets.length - 1];
            breakingOffsetsCount++;
          }
          break;
        }
      }
      if (breakOffset === 0) {
        let visibleColumn = prevBreakOffsetVisibleColumn;
        let charCode = lineText.charCodeAt(prevBreakOffset);
        let charCodeClass = classifier.get(charCode);
        let hitATabCharacter = false;
        for (let i2 = prevBreakOffset - 1; i2 >= lastBreakingOffset; i2--) {
          const charStartOffset = i2 + 1;
          const prevCharCode = lineText.charCodeAt(i2);
          if (prevCharCode === 9) {
            hitATabCharacter = true;
            break;
          }
          let prevCharCodeClass;
          let prevCharWidth;
          if (isLowSurrogate(prevCharCode)) {
            i2--;
            prevCharCodeClass = 0;
            prevCharWidth = 2;
          } else {
            prevCharCodeClass = classifier.get(prevCharCode);
            prevCharWidth = isFullWidthCharacter(prevCharCode) ? columnsForFullWidthChar : 1;
          }
          if (visibleColumn <= breakingColumn) {
            if (forcedBreakOffset === 0) {
              forcedBreakOffset = charStartOffset;
              forcedBreakOffsetVisibleColumn = visibleColumn;
            }
            if (visibleColumn <= breakingColumn - wrappedLineBreakColumn) {
              break;
            }
            if (canBreak(prevCharCode, prevCharCodeClass, charCode, charCodeClass, isKeepAll)) {
              breakOffset = charStartOffset;
              breakOffsetVisibleColumn = visibleColumn;
              break;
            }
          }
          visibleColumn -= prevCharWidth;
          charCode = prevCharCode;
          charCodeClass = prevCharCodeClass;
        }
        if (breakOffset !== 0) {
          const remainingWidthOfNextLine = wrappedLineBreakColumn - (forcedBreakOffsetVisibleColumn - breakOffsetVisibleColumn);
          if (remainingWidthOfNextLine <= tabSize) {
            const charCodeAtForcedBreakOffset = lineText.charCodeAt(forcedBreakOffset);
            let charWidth;
            if (isHighSurrogate(charCodeAtForcedBreakOffset)) {
              charWidth = 2;
            } else {
              charWidth = computeCharWidth(charCodeAtForcedBreakOffset, forcedBreakOffsetVisibleColumn, tabSize, columnsForFullWidthChar);
            }
            if (remainingWidthOfNextLine - charWidth < 0) {
              breakOffset = 0;
            }
          }
        }
        if (hitATabCharacter) {
          prevIndex--;
          continue;
        }
      }
      if (breakOffset === 0) {
        breakOffset = forcedBreakOffset;
        breakOffsetVisibleColumn = forcedBreakOffsetVisibleColumn;
      }
      if (breakOffset <= lastBreakingOffset) {
        const charCode = lineText.charCodeAt(lastBreakingOffset);
        if (isHighSurrogate(charCode)) {
          breakOffset = lastBreakingOffset + 2;
          breakOffsetVisibleColumn = lastBreakingOffsetVisibleColumn + 2;
        } else {
          breakOffset = lastBreakingOffset + 1;
          breakOffsetVisibleColumn = lastBreakingOffsetVisibleColumn + computeCharWidth(charCode, lastBreakingOffsetVisibleColumn, tabSize, columnsForFullWidthChar);
        }
      }
      lastBreakingOffset = breakOffset;
      breakingOffsets[breakingOffsetsCount] = breakOffset;
      lastBreakingOffsetVisibleColumn = breakOffsetVisibleColumn;
      breakingOffsetsVisibleColumn[breakingOffsetsCount] = breakOffsetVisibleColumn;
      breakingOffsetsCount++;
      breakingColumn = breakOffsetVisibleColumn + wrappedLineBreakColumn;
      while (prevIndex < 0 || prevIndex < prevLen && prevBreakingOffsetsVisibleColumn[prevIndex] < breakOffsetVisibleColumn) {
        prevIndex++;
      }
      let bestDistance = Math.abs(prevBreakingOffsetsVisibleColumn[prevIndex] - breakingColumn);
      while (prevIndex + 1 < prevLen) {
        const distance = Math.abs(prevBreakingOffsetsVisibleColumn[prevIndex + 1] - breakingColumn);
        if (distance >= bestDistance) {
          break;
        }
        bestDistance = distance;
        prevIndex++;
      }
    }
    if (breakingOffsetsCount === 0) {
      return null;
    }
    breakingOffsets.length = breakingOffsetsCount;
    breakingOffsetsVisibleColumn.length = breakingOffsetsCount;
    arrPool1 = previousBreakingData.breakOffsets;
    arrPool2 = previousBreakingData.breakOffsetsVisibleColumn;
    previousBreakingData.breakOffsets = breakingOffsets;
    previousBreakingData.breakOffsetsVisibleColumn = breakingOffsetsVisibleColumn;
    previousBreakingData.wrappedTextIndentLength = wrappedTextIndentLength;
    return previousBreakingData;
  }
  function createLineBreaks(classifier, _lineText, injectedTexts, tabSize, firstLineBreakColumn, columnsForFullWidthChar, wrappingIndent, wordBreak, wrapOnEscapedLineFeeds) {
    const lineText = LineInjectedText.applyInjectedText(_lineText, injectedTexts);
    let injectionOptions;
    let injectionOffsets;
    if (injectedTexts && injectedTexts.length > 0) {
      injectionOptions = injectedTexts.map((t) => t.options);
      injectionOffsets = injectedTexts.map((text2) => text2.column - 1);
    } else {
      injectionOptions = null;
      injectionOffsets = null;
    }
    if (firstLineBreakColumn === -1) {
      if (!injectionOptions) {
        return null;
      }
      return new ModelLineProjectionData(injectionOffsets, injectionOptions, [lineText.length], [], 0);
    }
    const len = lineText.length;
    if (len <= 1) {
      if (!injectionOptions) {
        return null;
      }
      return new ModelLineProjectionData(injectionOffsets, injectionOptions, [lineText.length], [], 0);
    }
    const isKeepAll = wordBreak === "keepAll";
    const wrappedTextIndentLength = computeWrappedTextIndentLength(lineText, tabSize, firstLineBreakColumn, columnsForFullWidthChar, wrappingIndent);
    const wrappedLineBreakColumn = firstLineBreakColumn - wrappedTextIndentLength;
    const breakingOffsets = [];
    const breakingOffsetsVisibleColumn = [];
    let breakingOffsetsCount = 0;
    let breakOffset = 0;
    let breakOffsetVisibleColumn = 0;
    let breakingColumn = firstLineBreakColumn;
    let prevCharCode = lineText.charCodeAt(0);
    let prevCharCodeClass = classifier.get(prevCharCode);
    let visibleColumn = computeCharWidth(prevCharCode, 0, tabSize, columnsForFullWidthChar);
    let startOffset = 1;
    if (isHighSurrogate(prevCharCode)) {
      visibleColumn += 1;
      prevCharCode = lineText.charCodeAt(1);
      prevCharCodeClass = classifier.get(prevCharCode);
      startOffset++;
    }
    for (let i2 = startOffset; i2 < len; i2++) {
      const charStartOffset = i2;
      const charCode = lineText.charCodeAt(i2);
      let charCodeClass;
      let charWidth;
      let wrapEscapedLineFeed = false;
      if (isHighSurrogate(charCode)) {
        i2++;
        charCodeClass = 0;
        charWidth = 2;
      } else {
        charCodeClass = classifier.get(charCode);
        charWidth = computeCharWidth(charCode, visibleColumn, tabSize, columnsForFullWidthChar);
      }
      if (wrapOnEscapedLineFeeds && isEscapedLineBreakAtPosition(lineText, i2)) {
        breakOffset = charStartOffset;
        breakOffsetVisibleColumn = visibleColumn;
        wrapEscapedLineFeed = true;
      } else if (canBreak(prevCharCode, prevCharCodeClass, charCode, charCodeClass, isKeepAll)) {
        breakOffset = charStartOffset;
        breakOffsetVisibleColumn = visibleColumn;
      }
      visibleColumn += charWidth;
      if (visibleColumn > breakingColumn || wrapEscapedLineFeed) {
        if (breakOffset === 0 || visibleColumn - breakOffsetVisibleColumn > wrappedLineBreakColumn) {
          breakOffset = charStartOffset;
          breakOffsetVisibleColumn = visibleColumn - charWidth;
        }
        breakingOffsets[breakingOffsetsCount] = breakOffset;
        breakingOffsetsVisibleColumn[breakingOffsetsCount] = breakOffsetVisibleColumn;
        breakingOffsetsCount++;
        breakingColumn = breakOffsetVisibleColumn + wrappedLineBreakColumn;
        breakOffset = 0;
      }
      prevCharCode = charCode;
      prevCharCodeClass = charCodeClass;
    }
    if (breakingOffsetsCount === 0 && (!injectedTexts || injectedTexts.length === 0)) {
      return null;
    }
    breakingOffsets[breakingOffsetsCount] = len;
    breakingOffsetsVisibleColumn[breakingOffsetsCount] = visibleColumn;
    return new ModelLineProjectionData(injectionOffsets, injectionOptions, breakingOffsets, breakingOffsetsVisibleColumn, wrappedTextIndentLength);
  }
  function computeCharWidth(charCode, visibleColumn, tabSize, columnsForFullWidthChar) {
    if (charCode === 9) {
      return tabSize - visibleColumn % tabSize;
    }
    if (isFullWidthCharacter(charCode)) {
      return columnsForFullWidthChar;
    }
    if (charCode < 32) {
      return columnsForFullWidthChar;
    }
    return 1;
  }
  function tabCharacterWidth(visibleColumn, tabSize) {
    return tabSize - visibleColumn % tabSize;
  }
  function isEscapedLineBreakAtPosition(lineText, i2) {
    if (i2 >= 2 && lineText.charAt(i2 - 1) === "n") {
      let escapeCount = 0;
      for (let j = i2 - 2; j >= 0; j--) {
        if (lineText.charAt(j) === "\\") {
          escapeCount++;
        } else {
          return escapeCount % 2 === 1;
        }
      }
    }
    return false;
  }
  function canBreak(prevCharCode, prevCharCodeClass, charCode, charCodeClass, isKeepAll) {
    return charCode !== 32 && (prevCharCodeClass === 2 && charCodeClass !== 2 || prevCharCodeClass !== 1 && charCodeClass === 1 || !isKeepAll && prevCharCodeClass === 3 && charCodeClass !== 2 || !isKeepAll && charCodeClass === 3 && prevCharCodeClass !== 1);
  }
  function computeWrappedTextIndentLength(lineText, tabSize, firstLineBreakColumn, columnsForFullWidthChar, wrappingIndent) {
    let wrappedTextIndentLength = 0;
    if (wrappingIndent !== 0) {
      const firstNonWhitespaceIndex$1 = firstNonWhitespaceIndex(lineText);
      if (firstNonWhitespaceIndex$1 !== -1) {
        for (let i2 = 0; i2 < firstNonWhitespaceIndex$1; i2++) {
          const charWidth = lineText.charCodeAt(i2) === 9 ? tabCharacterWidth(wrappedTextIndentLength, tabSize) : 1;
          wrappedTextIndentLength += charWidth;
        }
        const numberOfAdditionalTabs = wrappingIndent === 3 ? 2 : wrappingIndent === 2 ? 1 : 0;
        for (let i2 = 0; i2 < numberOfAdditionalTabs; i2++) {
          const charWidth = tabCharacterWidth(wrappedTextIndentLength, tabSize);
          wrappedTextIndentLength += charWidth;
        }
        if (wrappedTextIndentLength + columnsForFullWidthChar > firstLineBreakColumn) {
          wrappedTextIndentLength = 0;
        }
      }
    }
    return wrappedTextIndentLength;
  }
  class Cursor {
    constructor(context) {
      this._selTrackedRange = null;
      this._trackSelection = true;
      this._setState(context, new SingleCursorState(new Range$2(1, 1, 1, 1), 0, 0, new Position$1(1, 1), 0), new SingleCursorState(new Range$2(1, 1, 1, 1), 0, 0, new Position$1(1, 1), 0));
    }
    dispose(context) {
      this._removeTrackedRange(context);
    }
    startTrackingSelection(context) {
      this._trackSelection = true;
      this._updateTrackedRange(context);
    }
    stopTrackingSelection(context) {
      this._trackSelection = false;
      this._removeTrackedRange(context);
    }
    _updateTrackedRange(context) {
      if (!this._trackSelection) {
        return;
      }
      this._selTrackedRange = context.model._setTrackedRange(
        this._selTrackedRange,
        this.modelState.selection,
        0
        /* TrackedRangeStickiness.AlwaysGrowsWhenTypingAtEdges */
      );
    }
    _removeTrackedRange(context) {
      this._selTrackedRange = context.model._setTrackedRange(
        this._selTrackedRange,
        null,
        0
        /* TrackedRangeStickiness.AlwaysGrowsWhenTypingAtEdges */
      );
    }
    asCursorState() {
      return new CursorState$1(this.modelState, this.viewState);
    }
    readSelectionFromMarkers(context) {
      const range2 = context.model._getTrackedRange(this._selTrackedRange);
      if (this.modelState.selection.isEmpty() && !range2.isEmpty()) {
        return Selection$1.fromRange(range2.collapseToEnd(), this.modelState.selection.getDirection());
      }
      return Selection$1.fromRange(range2, this.modelState.selection.getDirection());
    }
    ensureValidState(context) {
      this._setState(context, this.modelState, this.viewState);
    }
    setState(context, modelState, viewState) {
      this._setState(context, modelState, viewState);
    }
    static _validatePositionWithCache(viewModel, position, cacheInput, cacheOutput) {
      if (position.equals(cacheInput)) {
        return cacheOutput;
      }
      return viewModel.normalizePosition(
        position,
        2
        /* PositionAffinity.None */
      );
    }
    static _validateViewState(viewModel, viewState) {
      const position = viewState.position;
      const sStartPosition = viewState.selectionStart.getStartPosition();
      const sEndPosition = viewState.selectionStart.getEndPosition();
      const validPosition = viewModel.normalizePosition(
        position,
        2
        /* PositionAffinity.None */
      );
      const validSStartPosition = this._validatePositionWithCache(viewModel, sStartPosition, position, validPosition);
      const validSEndPosition = this._validatePositionWithCache(viewModel, sEndPosition, sStartPosition, validSStartPosition);
      if (position.equals(validPosition) && sStartPosition.equals(validSStartPosition) && sEndPosition.equals(validSEndPosition)) {
        return viewState;
      }
      return new SingleCursorState(Range$2.fromPositions(validSStartPosition, validSEndPosition), viewState.selectionStartKind, viewState.selectionStartLeftoverVisibleColumns + sStartPosition.column - validSStartPosition.column, validPosition, viewState.leftoverVisibleColumns + position.column - validPosition.column);
    }
    _setState(context, modelState, viewState) {
      if (viewState) {
        viewState = Cursor._validateViewState(context.viewModel, viewState);
      }
      if (!modelState) {
        if (!viewState) {
          return;
        }
        const selectionStart = context.model.validateRange(context.coordinatesConverter.convertViewRangeToModelRange(viewState.selectionStart));
        const position = context.model.validatePosition(context.coordinatesConverter.convertViewPositionToModelPosition(viewState.position));
        modelState = new SingleCursorState(selectionStart, viewState.selectionStartKind, viewState.selectionStartLeftoverVisibleColumns, position, viewState.leftoverVisibleColumns);
      } else {
        const selectionStart = context.model.validateRange(modelState.selectionStart);
        const selectionStartLeftoverVisibleColumns = modelState.selectionStart.equalsRange(selectionStart) ? modelState.selectionStartLeftoverVisibleColumns : 0;
        const position = context.model.validatePosition(modelState.position);
        const leftoverVisibleColumns = modelState.position.equals(position) ? modelState.leftoverVisibleColumns : 0;
        modelState = new SingleCursorState(selectionStart, modelState.selectionStartKind, selectionStartLeftoverVisibleColumns, position, leftoverVisibleColumns);
      }
      if (!viewState) {
        const viewSelectionStart1 = context.coordinatesConverter.convertModelPositionToViewPosition(new Position$1(modelState.selectionStart.startLineNumber, modelState.selectionStart.startColumn));
        const viewSelectionStart2 = context.coordinatesConverter.convertModelPositionToViewPosition(new Position$1(modelState.selectionStart.endLineNumber, modelState.selectionStart.endColumn));
        const viewSelectionStart = new Range$2(viewSelectionStart1.lineNumber, viewSelectionStart1.column, viewSelectionStart2.lineNumber, viewSelectionStart2.column);
        const viewPosition = context.coordinatesConverter.convertModelPositionToViewPosition(modelState.position);
        viewState = new SingleCursorState(viewSelectionStart, modelState.selectionStartKind, modelState.selectionStartLeftoverVisibleColumns, viewPosition, modelState.leftoverVisibleColumns);
      } else {
        const viewSelectionStart = context.coordinatesConverter.validateViewRange(viewState.selectionStart, modelState.selectionStart);
        const viewPosition = context.coordinatesConverter.validateViewPosition(viewState.position, modelState.position);
        viewState = new SingleCursorState(viewSelectionStart, modelState.selectionStartKind, modelState.selectionStartLeftoverVisibleColumns, viewPosition, modelState.leftoverVisibleColumns);
      }
      this.modelState = modelState;
      this.viewState = viewState;
      this._updateTrackedRange(context);
    }
  }
  class CursorCollection {
    constructor(context) {
      this.context = context;
      this.cursors = [new Cursor(context)];
      this.lastAddedCursorIndex = 0;
    }
    dispose() {
      for (const cursor of this.cursors) {
        cursor.dispose(this.context);
      }
    }
    startTrackingSelections() {
      for (const cursor of this.cursors) {
        cursor.startTrackingSelection(this.context);
      }
    }
    stopTrackingSelections() {
      for (const cursor of this.cursors) {
        cursor.stopTrackingSelection(this.context);
      }
    }
    updateContext(context) {
      this.context = context;
    }
    ensureValidState() {
      for (const cursor of this.cursors) {
        cursor.ensureValidState(this.context);
      }
    }
    readSelectionFromMarkers() {
      return this.cursors.map((c) => c.readSelectionFromMarkers(this.context));
    }
    getAll() {
      return this.cursors.map((c) => c.asCursorState());
    }
    getViewPositions() {
      return this.cursors.map((c) => c.viewState.position);
    }
    getTopMostViewPosition() {
      return findFirstMin(this.cursors, compareBy((c) => c.viewState.position, Position$1.compare)).viewState.position;
    }
    getBottomMostViewPosition() {
      return findLastMax(this.cursors, compareBy((c) => c.viewState.position, Position$1.compare)).viewState.position;
    }
    getSelections() {
      return this.cursors.map((c) => c.modelState.selection);
    }
    getViewSelections() {
      return this.cursors.map((c) => c.viewState.selection);
    }
    setSelections(selections) {
      this.setStates(CursorState$1.fromModelSelections(selections));
    }
    getPrimaryCursor() {
      return this.cursors[0].asCursorState();
    }
    setStates(states) {
      if (states === null) {
        return;
      }
      this.cursors[0].setState(this.context, states[0].modelState, states[0].viewState);
      this._setSecondaryStates(states.slice(1));
    }
    /**
     * Creates or disposes secondary cursors as necessary to match the number of `secondarySelections`.
     */
    _setSecondaryStates(secondaryStates) {
      const secondaryCursorsLength = this.cursors.length - 1;
      const secondaryStatesLength = secondaryStates.length;
      if (secondaryCursorsLength < secondaryStatesLength) {
        const createCnt = secondaryStatesLength - secondaryCursorsLength;
        for (let i2 = 0; i2 < createCnt; i2++) {
          this._addSecondaryCursor();
        }
      } else if (secondaryCursorsLength > secondaryStatesLength) {
        const removeCnt = secondaryCursorsLength - secondaryStatesLength;
        for (let i2 = 0; i2 < removeCnt; i2++) {
          this._removeSecondaryCursor(this.cursors.length - 2);
        }
      }
      for (let i2 = 0; i2 < secondaryStatesLength; i2++) {
        this.cursors[i2 + 1].setState(this.context, secondaryStates[i2].modelState, secondaryStates[i2].viewState);
      }
    }
    killSecondaryCursors() {
      this._setSecondaryStates([]);
    }
    _addSecondaryCursor() {
      this.cursors.push(new Cursor(this.context));
      this.lastAddedCursorIndex = this.cursors.length - 1;
    }
    getLastAddedCursorIndex() {
      if (this.cursors.length === 1 || this.lastAddedCursorIndex === 0) {
        return 0;
      }
      return this.lastAddedCursorIndex;
    }
    _removeSecondaryCursor(removeIndex) {
      if (this.lastAddedCursorIndex >= removeIndex + 1) {
        this.lastAddedCursorIndex--;
      }
      this.cursors[removeIndex + 1].dispose(this.context);
      this.cursors.splice(removeIndex + 1, 1);
    }
    normalize() {
      if (this.cursors.length === 1) {
        return;
      }
      const cursors = this.cursors.slice(0);
      const sortedCursors = [];
      for (let i2 = 0, len = cursors.length; i2 < len; i2++) {
        sortedCursors.push({
          index: i2,
          selection: cursors[i2].modelState.selection
        });
      }
      sortedCursors.sort(compareBy((s) => s.selection, Range$2.compareRangesUsingStarts));
      for (let sortedCursorIndex = 0; sortedCursorIndex < sortedCursors.length - 1; sortedCursorIndex++) {
        const current = sortedCursors[sortedCursorIndex];
        const next = sortedCursors[sortedCursorIndex + 1];
        const currentSelection = current.selection;
        const nextSelection = next.selection;
        if (!this.context.cursorConfig.multiCursorMergeOverlapping) {
          continue;
        }
        let shouldMergeCursors;
        if (nextSelection.isEmpty() || currentSelection.isEmpty()) {
          shouldMergeCursors = nextSelection.getStartPosition().isBeforeOrEqual(currentSelection.getEndPosition());
        } else {
          shouldMergeCursors = nextSelection.getStartPosition().isBefore(currentSelection.getEndPosition());
        }
        if (shouldMergeCursors) {
          const winnerSortedCursorIndex = current.index < next.index ? sortedCursorIndex : sortedCursorIndex + 1;
          const looserSortedCursorIndex = current.index < next.index ? sortedCursorIndex + 1 : sortedCursorIndex;
          const looserIndex = sortedCursors[looserSortedCursorIndex].index;
          const winnerIndex = sortedCursors[winnerSortedCursorIndex].index;
          const looserSelection = sortedCursors[looserSortedCursorIndex].selection;
          const winnerSelection = sortedCursors[winnerSortedCursorIndex].selection;
          if (!looserSelection.equalsSelection(winnerSelection)) {
            const resultingRange = looserSelection.plusRange(winnerSelection);
            const looserSelectionIsLTR = looserSelection.selectionStartLineNumber === looserSelection.startLineNumber && looserSelection.selectionStartColumn === looserSelection.startColumn;
            const winnerSelectionIsLTR = winnerSelection.selectionStartLineNumber === winnerSelection.startLineNumber && winnerSelection.selectionStartColumn === winnerSelection.startColumn;
            let resultingSelectionIsLTR;
            if (looserIndex === this.lastAddedCursorIndex) {
              resultingSelectionIsLTR = looserSelectionIsLTR;
              this.lastAddedCursorIndex = winnerIndex;
            } else {
              resultingSelectionIsLTR = winnerSelectionIsLTR;
            }
            let resultingSelection;
            if (resultingSelectionIsLTR) {
              resultingSelection = new Selection$1(resultingRange.startLineNumber, resultingRange.startColumn, resultingRange.endLineNumber, resultingRange.endColumn);
            } else {
              resultingSelection = new Selection$1(resultingRange.endLineNumber, resultingRange.endColumn, resultingRange.startLineNumber, resultingRange.startColumn);
            }
            sortedCursors[winnerSortedCursorIndex].selection = resultingSelection;
            const resultingState = CursorState$1.fromModelSelection(resultingSelection);
            cursors[winnerIndex].setState(this.context, resultingState.modelState, resultingState.viewState);
          }
          for (const sortedCursor of sortedCursors) {
            if (sortedCursor.index > looserIndex) {
              sortedCursor.index--;
            }
          }
          cursors.splice(looserIndex, 1);
          sortedCursors.splice(looserSortedCursorIndex, 1);
          this._removeSecondaryCursor(looserIndex - 1);
          sortedCursorIndex--;
        }
      }
    }
  }
  class CursorContext {
    constructor(model, viewModel, coordinatesConverter, cursorConfig) {
      this._cursorContextBrand = void 0;
      this.model = model;
      this.viewModel = viewModel;
      this.coordinatesConverter = coordinatesConverter;
      this.cursorConfig = cursorConfig;
    }
  }
  class ViewCompositionStartEvent {
    constructor() {
      this.type = 0;
    }
  }
  class ViewCompositionEndEvent {
    constructor() {
      this.type = 1;
    }
  }
  class ViewConfigurationChangedEvent {
    constructor(source) {
      this.type = 2;
      this._source = source;
    }
    hasChanged(id) {
      return this._source.hasChanged(id);
    }
  }
  class ViewCursorStateChangedEvent {
    constructor(selections, modelSelections, reason) {
      this.selections = selections;
      this.modelSelections = modelSelections;
      this.reason = reason;
      this.type = 3;
    }
  }
  class ViewDecorationsChangedEvent {
    constructor(source) {
      this.type = 4;
      if (source) {
        this.affectsMinimap = source.affectsMinimap;
        this.affectsOverviewRuler = source.affectsOverviewRuler;
        this.affectsGlyphMargin = source.affectsGlyphMargin;
        this.affectsLineNumber = source.affectsLineNumber;
      } else {
        this.affectsMinimap = true;
        this.affectsOverviewRuler = true;
        this.affectsGlyphMargin = true;
        this.affectsLineNumber = true;
      }
    }
  }
  class ViewFlushedEvent {
    constructor() {
      this.type = 5;
    }
  }
  class ViewFocusChangedEvent {
    constructor(isFocused) {
      this.type = 6;
      this.isFocused = isFocused;
    }
  }
  class ViewLanguageConfigurationEvent {
    constructor() {
      this.type = 7;
    }
  }
  class ViewLineMappingChangedEvent {
    constructor() {
      this.type = 8;
    }
  }
  class ViewLinesChangedEvent {
    constructor(fromLineNumber, count) {
      this.fromLineNumber = fromLineNumber;
      this.count = count;
      this.type = 9;
    }
  }
  class ViewLinesDeletedEvent {
    constructor(fromLineNumber, toLineNumber) {
      this.type = 10;
      this.fromLineNumber = fromLineNumber;
      this.toLineNumber = toLineNumber;
    }
  }
  class ViewLinesInsertedEvent {
    constructor(fromLineNumber, toLineNumber) {
      this.type = 11;
      this.fromLineNumber = fromLineNumber;
      this.toLineNumber = toLineNumber;
    }
  }
  class ViewRevealRangeRequestEvent {
    constructor(source, minimalReveal, range2, selections, verticalType, revealHorizontal, scrollType) {
      this.source = source;
      this.minimalReveal = minimalReveal;
      this.range = range2;
      this.selections = selections;
      this.verticalType = verticalType;
      this.revealHorizontal = revealHorizontal;
      this.scrollType = scrollType;
      this.type = 12;
    }
  }
  class ViewScrollChangedEvent {
    constructor(source) {
      this.type = 13;
      this.scrollWidth = source.scrollWidth;
      this.scrollLeft = source.scrollLeft;
      this.scrollHeight = source.scrollHeight;
      this.scrollTop = source.scrollTop;
      this.scrollWidthChanged = source.scrollWidthChanged;
      this.scrollLeftChanged = source.scrollLeftChanged;
      this.scrollHeightChanged = source.scrollHeightChanged;
      this.scrollTopChanged = source.scrollTopChanged;
    }
  }
  class ViewThemeChangedEvent {
    constructor(theme) {
      this.theme = theme;
      this.type = 14;
    }
  }
  class ViewTokensChangedEvent {
    constructor(ranges) {
      this.type = 15;
      this.ranges = ranges;
    }
  }
  class ViewTokensColorsChangedEvent {
    constructor() {
      this.type = 16;
    }
  }
  let ViewZonesChangedEvent$1 = class ViewZonesChangedEvent {
    constructor() {
      this.type = 17;
    }
  };
  class ViewModelEventDispatcher extends Disposable {
    constructor() {
      super();
      this._onEvent = this._register(new Emitter$1());
      this.onEvent = this._onEvent.event;
      this._eventHandlers = [];
      this._viewEventQueue = null;
      this._isConsumingViewEventQueue = false;
      this._collector = null;
      this._collectorCnt = 0;
      this._outgoingEvents = [];
    }
    emitOutgoingEvent(e) {
      this._addOutgoingEvent(e);
      this._emitOutgoingEvents();
    }
    _addOutgoingEvent(e) {
      for (let i2 = 0, len = this._outgoingEvents.length; i2 < len; i2++) {
        const mergeResult = this._outgoingEvents[i2].kind === e.kind ? this._outgoingEvents[i2].attemptToMerge(e) : null;
        if (mergeResult) {
          this._outgoingEvents[i2] = mergeResult;
          return;
        }
      }
      this._outgoingEvents.push(e);
    }
    _emitOutgoingEvents() {
      while (this._outgoingEvents.length > 0) {
        if (this._collector || this._isConsumingViewEventQueue) {
          return;
        }
        const event = this._outgoingEvents.shift();
        if (event.isNoOp()) {
          continue;
        }
        this._onEvent.fire(event);
      }
    }
    addViewEventHandler(eventHandler) {
      for (let i2 = 0, len = this._eventHandlers.length; i2 < len; i2++) {
        if (this._eventHandlers[i2] === eventHandler) {
          console.warn("Detected duplicate listener in ViewEventDispatcher", eventHandler);
        }
      }
      this._eventHandlers.push(eventHandler);
    }
    removeViewEventHandler(eventHandler) {
      for (let i2 = 0; i2 < this._eventHandlers.length; i2++) {
        if (this._eventHandlers[i2] === eventHandler) {
          this._eventHandlers.splice(i2, 1);
          break;
        }
      }
    }
    beginEmitViewEvents() {
      this._collectorCnt++;
      if (this._collectorCnt === 1) {
        this._collector = new ViewModelEventsCollector();
      }
      return this._collector;
    }
    endEmitViewEvents() {
      this._collectorCnt--;
      if (this._collectorCnt === 0) {
        const outgoingEvents = this._collector.outgoingEvents;
        const viewEvents = this._collector.viewEvents;
        this._collector = null;
        for (const outgoingEvent of outgoingEvents) {
          this._addOutgoingEvent(outgoingEvent);
        }
        if (viewEvents.length > 0) {
          this._emitMany(viewEvents);
        }
      }
      this._emitOutgoingEvents();
    }
    emitSingleViewEvent(event) {
      try {
        const eventsCollector = this.beginEmitViewEvents();
        eventsCollector.emitViewEvent(event);
      } finally {
        this.endEmitViewEvents();
      }
    }
    _emitMany(events) {
      if (this._viewEventQueue) {
        this._viewEventQueue = this._viewEventQueue.concat(events);
      } else {
        this._viewEventQueue = events;
      }
      if (!this._isConsumingViewEventQueue) {
        this._consumeViewEventQueue();
      }
    }
    _consumeViewEventQueue() {
      try {
        this._isConsumingViewEventQueue = true;
        this._doConsumeQueue();
      } finally {
        this._isConsumingViewEventQueue = false;
      }
    }
    _doConsumeQueue() {
      while (this._viewEventQueue) {
        const events = this._viewEventQueue;
        this._viewEventQueue = null;
        const eventHandlers = this._eventHandlers.slice(0);
        for (const eventHandler of eventHandlers) {
          eventHandler.handleEvents(events);
        }
      }
    }
  }
  class ViewModelEventsCollector {
    constructor() {
      this.viewEvents = [];
      this.outgoingEvents = [];
    }
    emitViewEvent(event) {
      this.viewEvents.push(event);
    }
    emitOutgoingEvent(e) {
      this.outgoingEvents.push(e);
    }
  }
  class ContentSizeChangedEvent {
    constructor(oldContentWidth, oldContentHeight, contentWidth, contentHeight) {
      this.kind = 0;
      this._oldContentWidth = oldContentWidth;
      this._oldContentHeight = oldContentHeight;
      this.contentWidth = contentWidth;
      this.contentHeight = contentHeight;
      this.contentWidthChanged = this._oldContentWidth !== this.contentWidth;
      this.contentHeightChanged = this._oldContentHeight !== this.contentHeight;
    }
    isNoOp() {
      return !this.contentWidthChanged && !this.contentHeightChanged;
    }
    attemptToMerge(other) {
      if (other.kind !== this.kind) {
        return null;
      }
      return new ContentSizeChangedEvent(this._oldContentWidth, this._oldContentHeight, other.contentWidth, other.contentHeight);
    }
  }
  class FocusChangedEvent {
    constructor(oldHasFocus, hasFocus) {
      this.kind = 1;
      this.oldHasFocus = oldHasFocus;
      this.hasFocus = hasFocus;
    }
    isNoOp() {
      return this.oldHasFocus === this.hasFocus;
    }
    attemptToMerge(other) {
      if (other.kind !== this.kind) {
        return null;
      }
      return new FocusChangedEvent(this.oldHasFocus, other.hasFocus);
    }
  }
  class WidgetFocusChangedEvent {
    constructor(oldHasFocus, hasFocus) {
      this.kind = 2;
      this.oldHasFocus = oldHasFocus;
      this.hasFocus = hasFocus;
    }
    isNoOp() {
      return this.oldHasFocus === this.hasFocus;
    }
    attemptToMerge(other) {
      if (other.kind !== this.kind) {
        return null;
      }
      return new FocusChangedEvent(this.oldHasFocus, other.hasFocus);
    }
  }
  class ScrollChangedEvent {
    constructor(oldScrollWidth, oldScrollLeft, oldScrollHeight, oldScrollTop, scrollWidth, scrollLeft, scrollHeight, scrollTop) {
      this.kind = 3;
      this._oldScrollWidth = oldScrollWidth;
      this._oldScrollLeft = oldScrollLeft;
      this._oldScrollHeight = oldScrollHeight;
      this._oldScrollTop = oldScrollTop;
      this.scrollWidth = scrollWidth;
      this.scrollLeft = scrollLeft;
      this.scrollHeight = scrollHeight;
      this.scrollTop = scrollTop;
      this.scrollWidthChanged = this._oldScrollWidth !== this.scrollWidth;
      this.scrollLeftChanged = this._oldScrollLeft !== this.scrollLeft;
      this.scrollHeightChanged = this._oldScrollHeight !== this.scrollHeight;
      this.scrollTopChanged = this._oldScrollTop !== this.scrollTop;
    }
    isNoOp() {
      return !this.scrollWidthChanged && !this.scrollLeftChanged && !this.scrollHeightChanged && !this.scrollTopChanged;
    }
    attemptToMerge(other) {
      if (other.kind !== this.kind) {
        return null;
      }
      return new ScrollChangedEvent(this._oldScrollWidth, this._oldScrollLeft, this._oldScrollHeight, this._oldScrollTop, other.scrollWidth, other.scrollLeft, other.scrollHeight, other.scrollTop);
    }
  }
  class ViewZonesChangedEvent {
    constructor() {
      this.kind = 4;
    }
    isNoOp() {
      return false;
    }
    attemptToMerge(other) {
      if (other.kind !== this.kind) {
        return null;
      }
      return this;
    }
  }
  class HiddenAreasChangedEvent {
    constructor() {
      this.kind = 5;
    }
    isNoOp() {
      return false;
    }
    attemptToMerge(other) {
      if (other.kind !== this.kind) {
        return null;
      }
      return this;
    }
  }
  class CursorStateChangedEvent {
    constructor(oldSelections, selections, oldModelVersionId, modelVersionId, source, reason, reachedMaxCursorCount) {
      this.kind = 7;
      this.oldSelections = oldSelections;
      this.selections = selections;
      this.oldModelVersionId = oldModelVersionId;
      this.modelVersionId = modelVersionId;
      this.source = source;
      this.reason = reason;
      this.reachedMaxCursorCount = reachedMaxCursorCount;
    }
    static _selectionsAreEqual(a, b) {
      if (!a && !b) {
        return true;
      }
      if (!a || !b) {
        return false;
      }
      const aLen = a.length;
      const bLen = b.length;
      if (aLen !== bLen) {
        return false;
      }
      for (let i2 = 0; i2 < aLen; i2++) {
        if (!a[i2].equalsSelection(b[i2])) {
          return false;
        }
      }
      return true;
    }
    isNoOp() {
      return CursorStateChangedEvent._selectionsAreEqual(this.oldSelections, this.selections) && this.oldModelVersionId === this.modelVersionId;
    }
    attemptToMerge(other) {
      if (other.kind !== this.kind) {
        return null;
      }
      return new CursorStateChangedEvent(this.oldSelections, other.selections, this.oldModelVersionId, other.modelVersionId, other.source, other.reason, this.reachedMaxCursorCount || other.reachedMaxCursorCount);
    }
  }
  class ReadOnlyEditAttemptEvent {
    constructor() {
      this.kind = 6;
    }
    isNoOp() {
      return false;
    }
    attemptToMerge(other) {
      if (other.kind !== this.kind) {
        return null;
      }
      return this;
    }
  }
  class ModelDecorationsChangedEvent {
    constructor(event) {
      this.event = event;
      this.kind = 8;
    }
    isNoOp() {
      return false;
    }
    attemptToMerge(other) {
      return null;
    }
  }
  class ModelLanguageChangedEvent {
    constructor(event) {
      this.event = event;
      this.kind = 9;
    }
    isNoOp() {
      return false;
    }
    attemptToMerge(other) {
      return null;
    }
  }
  class ModelLanguageConfigurationChangedEvent {
    constructor(event) {
      this.event = event;
      this.kind = 10;
    }
    isNoOp() {
      return false;
    }
    attemptToMerge(other) {
      return null;
    }
  }
  class ModelContentChangedEvent {
    constructor(event) {
      this.event = event;
      this.kind = 11;
    }
    isNoOp() {
      return false;
    }
    attemptToMerge(other) {
      return null;
    }
  }
  class ModelOptionsChangedEvent {
    constructor(event) {
      this.event = event;
      this.kind = 12;
    }
    isNoOp() {
      return false;
    }
    attemptToMerge(other) {
      return null;
    }
  }
  class ModelTokensChangedEvent {
    constructor(event) {
      this.event = event;
      this.kind = 13;
    }
    isNoOp() {
      return false;
    }
    attemptToMerge(other) {
      return null;
    }
  }
  class ModelLineHeightChangedEvent {
    constructor(event) {
      this.event = event;
      this.kind = 14;
    }
    isNoOp() {
      return false;
    }
    attemptToMerge(other) {
      return null;
    }
  }
  class ModelFontChangedEvent {
    constructor(event) {
      this.event = event;
      this.kind = 15;
    }
    isNoOp() {
      return false;
    }
    attemptToMerge(other) {
      return null;
    }
  }
  class CursorsController extends Disposable {
    constructor(model, viewModel, coordinatesConverter, cursorConfig) {
      super();
      this._model = model;
      this._knownModelVersionId = this._model.getVersionId();
      this._viewModel = viewModel;
      this._coordinatesConverter = coordinatesConverter;
      this.context = new CursorContext(this._model, this._viewModel, this._coordinatesConverter, cursorConfig);
      this._cursors = new CursorCollection(this.context);
      this._hasFocus = false;
      this._isHandling = false;
      this._compositionState = null;
      this._columnSelectData = null;
      this._autoClosedActions = [];
      this._prevEditOperationType = 0;
    }
    dispose() {
      this._cursors.dispose();
      this._autoClosedActions = dispose(this._autoClosedActions);
      super.dispose();
    }
    updateConfiguration(cursorConfig) {
      this.context = new CursorContext(this._model, this._viewModel, this._coordinatesConverter, cursorConfig);
      this._cursors.updateContext(this.context);
    }
    onLineMappingChanged(eventsCollector) {
      if (this._knownModelVersionId !== this._model.getVersionId()) {
        return;
      }
      this.setStates(eventsCollector, "viewModel", 0, this.getCursorStates());
    }
    setHasFocus(hasFocus) {
      this._hasFocus = hasFocus;
    }
    _validateAutoClosedActions() {
      if (this._autoClosedActions.length > 0) {
        const selections = this._cursors.getSelections();
        for (let i2 = 0; i2 < this._autoClosedActions.length; i2++) {
          const autoClosedAction = this._autoClosedActions[i2];
          if (!autoClosedAction.isValid(selections)) {
            autoClosedAction.dispose();
            this._autoClosedActions.splice(i2, 1);
            i2--;
          }
        }
      }
    }
    // ------ some getters/setters
    getPrimaryCursorState() {
      return this._cursors.getPrimaryCursor();
    }
    getLastAddedCursorIndex() {
      return this._cursors.getLastAddedCursorIndex();
    }
    getCursorStates() {
      return this._cursors.getAll();
    }
    setStates(eventsCollector, source, reason, states) {
      let reachedMaxCursorCount = false;
      const multiCursorLimit = this.context.cursorConfig.multiCursorLimit;
      if (states !== null && states.length > multiCursorLimit) {
        states = states.slice(0, multiCursorLimit);
        reachedMaxCursorCount = true;
      }
      const oldState = CursorModelState.from(this._model, this);
      this._cursors.setStates(states);
      this._cursors.normalize();
      this._columnSelectData = null;
      this._validateAutoClosedActions();
      return this._emitStateChangedIfNecessary(eventsCollector, source, reason, oldState, reachedMaxCursorCount);
    }
    setCursorColumnSelectData(columnSelectData) {
      this._columnSelectData = columnSelectData;
    }
    revealAll(eventsCollector, source, minimalReveal, verticalType, revealHorizontal, scrollType) {
      const viewPositions = this._cursors.getViewPositions();
      let revealViewRange = null;
      let revealViewSelections = null;
      if (viewPositions.length > 1) {
        revealViewSelections = this._cursors.getViewSelections();
      } else {
        revealViewRange = Range$2.fromPositions(viewPositions[0], viewPositions[0]);
      }
      eventsCollector.emitViewEvent(new ViewRevealRangeRequestEvent(source, minimalReveal, revealViewRange, revealViewSelections, verticalType, revealHorizontal, scrollType));
    }
    revealPrimary(eventsCollector, source, minimalReveal, verticalType, revealHorizontal, scrollType) {
      const primaryCursor = this._cursors.getPrimaryCursor();
      const revealViewSelections = [primaryCursor.viewState.selection];
      eventsCollector.emitViewEvent(new ViewRevealRangeRequestEvent(source, minimalReveal, null, revealViewSelections, verticalType, revealHorizontal, scrollType));
    }
    saveState() {
      const result = [];
      const selections = this._cursors.getSelections();
      for (let i2 = 0, len = selections.length; i2 < len; i2++) {
        const selection = selections[i2];
        result.push({
          inSelectionMode: !selection.isEmpty(),
          selectionStart: {
            lineNumber: selection.selectionStartLineNumber,
            column: selection.selectionStartColumn
          },
          position: {
            lineNumber: selection.positionLineNumber,
            column: selection.positionColumn
          }
        });
      }
      return result;
    }
    restoreState(eventsCollector, states) {
      const desiredSelections = [];
      for (let i2 = 0, len = states.length; i2 < len; i2++) {
        const state = states[i2];
        let positionLineNumber = 1;
        let positionColumn = 1;
        if (state.position && state.position.lineNumber) {
          positionLineNumber = state.position.lineNumber;
        }
        if (state.position && state.position.column) {
          positionColumn = state.position.column;
        }
        let selectionStartLineNumber = positionLineNumber;
        let selectionStartColumn = positionColumn;
        if (state.selectionStart && state.selectionStart.lineNumber) {
          selectionStartLineNumber = state.selectionStart.lineNumber;
        }
        if (state.selectionStart && state.selectionStart.column) {
          selectionStartColumn = state.selectionStart.column;
        }
        desiredSelections.push({
          selectionStartLineNumber,
          selectionStartColumn,
          positionLineNumber,
          positionColumn
        });
      }
      this.setStates(eventsCollector, "restoreState", 0, CursorState$1.fromModelSelections(desiredSelections));
      this.revealAll(
        eventsCollector,
        "restoreState",
        false,
        0,
        true,
        1
        /* editorCommon.ScrollType.Immediate */
      );
    }
    onModelContentChanged(eventsCollector, event) {
      if (event instanceof ModelInjectedTextChangedEvent) {
        if (this._isHandling) {
          return;
        }
        this._isHandling = true;
        try {
          this.setStates(eventsCollector, "modelChange", 0, this.getCursorStates());
        } finally {
          this._isHandling = false;
        }
      } else {
        const e = event.rawContentChangedEvent;
        this._knownModelVersionId = e.versionId;
        if (this._isHandling) {
          return;
        }
        const hadFlushEvent = e.containsEvent(
          1
          /* RawContentChangedType.Flush */
        );
        this._prevEditOperationType = 0;
        if (hadFlushEvent) {
          this._cursors.dispose();
          this._cursors = new CursorCollection(this.context);
          this._validateAutoClosedActions();
          this._emitStateChangedIfNecessary(eventsCollector, "model", 1, null, false);
        } else {
          if (this._hasFocus && e.resultingSelection && e.resultingSelection.length > 0) {
            const cursorState = CursorState$1.fromModelSelections(e.resultingSelection);
            if (this.setStates(eventsCollector, "modelChange", e.isUndoing ? 5 : e.isRedoing ? 6 : 2, cursorState)) {
              this.revealAll(
                eventsCollector,
                "modelChange",
                false,
                0,
                true,
                0
                /* editorCommon.ScrollType.Smooth */
              );
            }
          } else {
            const selectionsFromMarkers = this._cursors.readSelectionFromMarkers();
            this.setStates(eventsCollector, "modelChange", 2, CursorState$1.fromModelSelections(selectionsFromMarkers));
          }
        }
      }
    }
    getSelection() {
      return this._cursors.getPrimaryCursor().modelState.selection;
    }
    getTopMostViewPosition() {
      return this._cursors.getTopMostViewPosition();
    }
    getBottomMostViewPosition() {
      return this._cursors.getBottomMostViewPosition();
    }
    getCursorColumnSelectData() {
      if (this._columnSelectData) {
        return this._columnSelectData;
      }
      const primaryCursor = this._cursors.getPrimaryCursor();
      const viewSelectionStart = primaryCursor.viewState.selectionStart.getStartPosition();
      const viewPosition = primaryCursor.viewState.position;
      return {
        isReal: false,
        fromViewLineNumber: viewSelectionStart.lineNumber,
        fromViewVisualColumn: this.context.cursorConfig.visibleColumnFromColumn(this._viewModel, viewSelectionStart),
        toViewLineNumber: viewPosition.lineNumber,
        toViewVisualColumn: this.context.cursorConfig.visibleColumnFromColumn(this._viewModel, viewPosition)
      };
    }
    getSelections() {
      return this._cursors.getSelections();
    }
    setSelections(eventsCollector, source, selections, reason) {
      this.setStates(eventsCollector, source, reason, CursorState$1.fromModelSelections(selections));
    }
    getPrevEditOperationType() {
      return this._prevEditOperationType;
    }
    setPrevEditOperationType(type) {
      this._prevEditOperationType = type;
    }
    // ------ auxiliary handling logic
    _pushAutoClosedAction(autoClosedCharactersRanges, autoClosedEnclosingRanges) {
      const autoClosedCharactersDeltaDecorations = [];
      const autoClosedEnclosingDeltaDecorations = [];
      for (let i2 = 0, len = autoClosedCharactersRanges.length; i2 < len; i2++) {
        autoClosedCharactersDeltaDecorations.push({
          range: autoClosedCharactersRanges[i2],
          options: {
            description: "auto-closed-character",
            inlineClassName: "auto-closed-character",
            stickiness: 1
            /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */
          }
        });
        autoClosedEnclosingDeltaDecorations.push({
          range: autoClosedEnclosingRanges[i2],
          options: {
            description: "auto-closed-enclosing",
            stickiness: 1
            /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */
          }
        });
      }
      const autoClosedCharactersDecorations = this._model.deltaDecorations([], autoClosedCharactersDeltaDecorations);
      const autoClosedEnclosingDecorations = this._model.deltaDecorations([], autoClosedEnclosingDeltaDecorations);
      this._autoClosedActions.push(new AutoClosedAction(this._model, autoClosedCharactersDecorations, autoClosedEnclosingDecorations));
    }
    _executeEditOperation(opResult, editReason) {
      if (!opResult) {
        return;
      }
      if (opResult.shouldPushStackElementBefore) {
        this._model.pushStackElement();
      }
      const result = CommandExecutor.executeCommands(this._model, this._cursors.getSelections(), opResult.commands, editReason);
      if (result) {
        this._interpretCommandResult(result);
        const autoClosedCharactersRanges = [];
        const autoClosedEnclosingRanges = [];
        for (let i2 = 0; i2 < opResult.commands.length; i2++) {
          const command = opResult.commands[i2];
          if (command instanceof BaseTypeWithAutoClosingCommand && command.enclosingRange && command.closeCharacterRange) {
            autoClosedCharactersRanges.push(command.closeCharacterRange);
            autoClosedEnclosingRanges.push(command.enclosingRange);
          }
        }
        if (autoClosedCharactersRanges.length > 0) {
          this._pushAutoClosedAction(autoClosedCharactersRanges, autoClosedEnclosingRanges);
        }
        this._prevEditOperationType = opResult.type;
      }
      if (opResult.shouldPushStackElementAfter) {
        this._model.pushStackElement();
      }
    }
    _interpretCommandResult(cursorState) {
      if (!cursorState || cursorState.length === 0) {
        cursorState = this._cursors.readSelectionFromMarkers();
      }
      this._columnSelectData = null;
      this._cursors.setSelections(cursorState);
      this._cursors.normalize();
    }
    // -----------------------------------------------------------------------------------------------------------
    // ----- emitting events
    _emitStateChangedIfNecessary(eventsCollector, source, reason, oldState, reachedMaxCursorCount) {
      const newState = CursorModelState.from(this._model, this);
      if (newState.equals(oldState)) {
        return false;
      }
      const selections = this._cursors.getSelections();
      const viewSelections = this._cursors.getViewSelections();
      eventsCollector.emitViewEvent(new ViewCursorStateChangedEvent(viewSelections, selections, reason));
      if (!oldState || oldState.cursorState.length !== newState.cursorState.length || newState.cursorState.some((newCursorState, i2) => !newCursorState.modelState.equals(oldState.cursorState[i2].modelState))) {
        const oldSelections = oldState ? oldState.cursorState.map((s) => s.modelState.selection) : null;
        const oldModelVersionId = oldState ? oldState.modelVersionId : 0;
        eventsCollector.emitOutgoingEvent(new CursorStateChangedEvent(oldSelections, selections, oldModelVersionId, newState.modelVersionId, source || "keyboard", reason, reachedMaxCursorCount));
      }
      return true;
    }
    // -----------------------------------------------------------------------------------------------------------
    // ----- handlers beyond this point
    _findAutoClosingPairs(edits) {
      if (!edits.length) {
        return null;
      }
      const indices = [];
      for (let i2 = 0, len = edits.length; i2 < len; i2++) {
        const edit2 = edits[i2];
        if (!edit2.text || edit2.text.indexOf("\n") >= 0) {
          return null;
        }
        const m = edit2.text.match(/([)\]}>'"`])([^)\]}>'"`]*)$/);
        if (!m) {
          return null;
        }
        const closeChar = m[1];
        const autoClosingPairsCandidates = this.context.cursorConfig.autoClosingPairs.autoClosingPairsCloseSingleChar.get(closeChar);
        if (!autoClosingPairsCandidates || autoClosingPairsCandidates.length !== 1) {
          return null;
        }
        const openChar = autoClosingPairsCandidates[0].open;
        const closeCharIndex = edit2.text.length - m[2].length - 1;
        const openCharIndex = edit2.text.lastIndexOf(openChar, closeCharIndex - 1);
        if (openCharIndex === -1) {
          return null;
        }
        indices.push([openCharIndex, closeCharIndex]);
      }
      return indices;
    }
    executeEdits(eventsCollector, source, edits, cursorStateComputer, reason) {
      let autoClosingIndices = null;
      if (source === "snippet") {
        autoClosingIndices = this._findAutoClosingPairs(edits);
      }
      if (autoClosingIndices) {
        edits[0]._isTracked = true;
      }
      const autoClosedCharactersRanges = [];
      const autoClosedEnclosingRanges = [];
      const selections = this._model.pushEditOperations(this.getSelections(), edits, (undoEdits) => {
        if (autoClosingIndices) {
          for (let i2 = 0, len = autoClosingIndices.length; i2 < len; i2++) {
            const [openCharInnerIndex, closeCharInnerIndex] = autoClosingIndices[i2];
            const undoEdit = undoEdits[i2];
            const lineNumber = undoEdit.range.startLineNumber;
            const openCharIndex = undoEdit.range.startColumn - 1 + openCharInnerIndex;
            const closeCharIndex = undoEdit.range.startColumn - 1 + closeCharInnerIndex;
            autoClosedCharactersRanges.push(new Range$2(lineNumber, closeCharIndex + 1, lineNumber, closeCharIndex + 2));
            autoClosedEnclosingRanges.push(new Range$2(lineNumber, openCharIndex + 1, lineNumber, closeCharIndex + 2));
          }
        }
        const selections2 = cursorStateComputer(undoEdits);
        if (selections2) {
          this._isHandling = true;
        }
        return selections2;
      }, void 0, reason);
      if (selections) {
        this._isHandling = false;
        this.setSelections(
          eventsCollector,
          source,
          selections,
          0
          /* CursorChangeReason.NotSet */
        );
      }
      if (autoClosedCharactersRanges.length > 0) {
        this._pushAutoClosedAction(autoClosedCharactersRanges, autoClosedEnclosingRanges);
      }
    }
    _executeEdit(callback, eventsCollector, source, cursorChangeReason = 0) {
      if (this.context.cursorConfig.readOnly) {
        return;
      }
      const oldState = CursorModelState.from(this._model, this);
      this._cursors.stopTrackingSelections();
      this._isHandling = true;
      try {
        this._cursors.ensureValidState();
        callback();
      } catch (err) {
        onUnexpectedError(err);
      }
      this._isHandling = false;
      this._cursors.startTrackingSelections();
      this._validateAutoClosedActions();
      if (this._emitStateChangedIfNecessary(eventsCollector, source, cursorChangeReason, oldState, false)) {
        this.revealAll(
          eventsCollector,
          source,
          false,
          0,
          true,
          0
          /* editorCommon.ScrollType.Smooth */
        );
      }
    }
    getAutoClosedCharacters() {
      return AutoClosedAction.getAllAutoClosedCharacters(this._autoClosedActions);
    }
    startComposition(eventsCollector) {
      this._compositionState = new CompositionState(this._model, this.getSelections());
    }
    endComposition(eventsCollector, source) {
      const reason = EditSources.cursor({ kind: "compositionEnd", detailedSource: source });
      const compositionOutcome = this._compositionState ? this._compositionState.deduceOutcome(this._model, this.getSelections()) : null;
      this._compositionState = null;
      this._executeEdit(() => {
        if (source === "keyboard") {
          this._executeEditOperation(TypeOperations.compositionEndWithInterceptors(this._prevEditOperationType, this.context.cursorConfig, this._model, compositionOutcome, this.getSelections(), this.getAutoClosedCharacters()), reason);
        }
      }, eventsCollector, source);
    }
    type(eventsCollector, text2, source) {
      const reason = EditSources.cursor({ kind: "type", detailedSource: source });
      this._executeEdit(() => {
        if (source === "keyboard") {
          const len = text2.length;
          let offset = 0;
          while (offset < len) {
            const charLength = nextCharLength(text2, offset);
            const chr = text2.substr(offset, charLength);
            this._executeEditOperation(TypeOperations.typeWithInterceptors(!!this._compositionState, this._prevEditOperationType, this.context.cursorConfig, this._model, this.getSelections(), this.getAutoClosedCharacters(), chr), reason);
            offset += charLength;
          }
        } else {
          this._executeEditOperation(TypeOperations.typeWithoutInterceptors(this._prevEditOperationType, this.context.cursorConfig, this._model, this.getSelections(), text2), reason);
        }
      }, eventsCollector, source);
    }
    compositionType(eventsCollector, text2, replacePrevCharCnt, replaceNextCharCnt, positionDelta, source) {
      const reason = EditSources.cursor({ kind: "compositionType", detailedSource: source });
      if (text2.length === 0 && replacePrevCharCnt === 0 && replaceNextCharCnt === 0) {
        if (positionDelta !== 0) {
          const newSelections = this.getSelections().map((selection) => {
            const position = selection.getPosition();
            return new Selection$1(position.lineNumber, position.column + positionDelta, position.lineNumber, position.column + positionDelta);
          });
          this.setSelections(
            eventsCollector,
            source,
            newSelections,
            0
            /* CursorChangeReason.NotSet */
          );
        }
        return;
      }
      this._executeEdit(() => {
        this._executeEditOperation(TypeOperations.compositionType(this._prevEditOperationType, this.context.cursorConfig, this._model, this.getSelections(), text2, replacePrevCharCnt, replaceNextCharCnt, positionDelta), reason);
      }, eventsCollector, source);
    }
    paste(eventsCollector, text2, pasteOnNewLine, multicursorText, source) {
      const reason = EditSources.cursor({ kind: "paste", detailedSource: source });
      this._executeEdit(
        () => {
          this._executeEditOperation(TypeOperations.paste(this.context.cursorConfig, this._model, this.getSelections(), text2, pasteOnNewLine, multicursorText || []), reason);
        },
        eventsCollector,
        source,
        4
        /* CursorChangeReason.Paste */
      );
    }
    cut(eventsCollector, source) {
      const reason = EditSources.cursor({ kind: "cut", detailedSource: source });
      this._executeEdit(() => {
        this._executeEditOperation(DeleteOperations.cut(this.context.cursorConfig, this._model, this.getSelections()), reason);
      }, eventsCollector, source);
    }
    executeCommand(eventsCollector, command, source) {
      const reason = EditSources.cursor({ kind: "executeCommand", detailedSource: source });
      this._executeEdit(() => {
        this._cursors.killSecondaryCursors();
        this._executeEditOperation(new EditOperationResult(0, [command], {
          shouldPushStackElementBefore: false,
          shouldPushStackElementAfter: false
        }), reason);
      }, eventsCollector, source);
    }
    executeCommands(eventsCollector, commands, source) {
      const reason = EditSources.cursor({ kind: "executeCommands", detailedSource: source });
      this._executeEdit(() => {
        this._executeEditOperation(new EditOperationResult(0, commands, {
          shouldPushStackElementBefore: false,
          shouldPushStackElementAfter: false
        }), reason);
      }, eventsCollector, source);
    }
  }
  class CursorModelState {
    static from(model, cursor) {
      return new CursorModelState(model.getVersionId(), cursor.getCursorStates());
    }
    constructor(modelVersionId, cursorState) {
      this.modelVersionId = modelVersionId;
      this.cursorState = cursorState;
    }
    equals(other) {
      if (!other) {
        return false;
      }
      if (this.modelVersionId !== other.modelVersionId) {
        return false;
      }
      if (this.cursorState.length !== other.cursorState.length) {
        return false;
      }
      for (let i2 = 0, len = this.cursorState.length; i2 < len; i2++) {
        if (!this.cursorState[i2].equals(other.cursorState[i2])) {
          return false;
        }
      }
      return true;
    }
  }
  class AutoClosedAction {
    static getAllAutoClosedCharacters(autoClosedActions) {
      let autoClosedCharacters = [];
      for (const autoClosedAction of autoClosedActions) {
        autoClosedCharacters = autoClosedCharacters.concat(autoClosedAction.getAutoClosedCharactersRanges());
      }
      return autoClosedCharacters;
    }
    constructor(model, autoClosedCharactersDecorations, autoClosedEnclosingDecorations) {
      this._model = model;
      this._autoClosedCharactersDecorations = autoClosedCharactersDecorations;
      this._autoClosedEnclosingDecorations = autoClosedEnclosingDecorations;
    }
    dispose() {
      this._autoClosedCharactersDecorations = this._model.deltaDecorations(this._autoClosedCharactersDecorations, []);
      this._autoClosedEnclosingDecorations = this._model.deltaDecorations(this._autoClosedEnclosingDecorations, []);
    }
    getAutoClosedCharactersRanges() {
      const result = [];
      for (let i2 = 0; i2 < this._autoClosedCharactersDecorations.length; i2++) {
        const decorationRange = this._model.getDecorationRange(this._autoClosedCharactersDecorations[i2]);
        if (decorationRange) {
          result.push(decorationRange);
        }
      }
      return result;
    }
    isValid(selections) {
      const enclosingRanges = [];
      for (let i2 = 0; i2 < this._autoClosedEnclosingDecorations.length; i2++) {
        const decorationRange = this._model.getDecorationRange(this._autoClosedEnclosingDecorations[i2]);
        if (decorationRange) {
          enclosingRanges.push(decorationRange);
          if (decorationRange.startLineNumber !== decorationRange.endLineNumber) {
            return false;
          }
        }
      }
      enclosingRanges.sort(Range$2.compareRangesUsingStarts);
      selections.sort(Range$2.compareRangesUsingStarts);
      for (let i2 = 0; i2 < selections.length; i2++) {
        if (i2 >= enclosingRanges.length) {
          return false;
        }
        if (!enclosingRanges[i2].strictContainsRange(selections[i2])) {
          return false;
        }
      }
      return true;
    }
  }
  class CommandExecutor {
    static executeCommands(model, selectionsBefore, commands, editReason = EditSources.unknown({ name: "executeCommands" })) {
      const ctx = {
        model,
        selectionsBefore,
        trackedRanges: [],
        trackedRangesDirection: []
      };
      const result = this._innerExecuteCommands(ctx, commands, editReason);
      for (let i2 = 0, len = ctx.trackedRanges.length; i2 < len; i2++) {
        ctx.model._setTrackedRange(
          ctx.trackedRanges[i2],
          null,
          0
          /* TrackedRangeStickiness.AlwaysGrowsWhenTypingAtEdges */
        );
      }
      return result;
    }
    static _innerExecuteCommands(ctx, commands, editReason) {
      if (this._arrayIsEmpty(commands)) {
        return null;
      }
      const commandsData = this._getEditOperations(ctx, commands);
      if (commandsData.operations.length === 0) {
        return null;
      }
      const rawOperations = commandsData.operations;
      const loserCursorsMap = this._getLoserCursorMap(rawOperations);
      if (loserCursorsMap.hasOwnProperty("0")) {
        console.warn("Ignoring commands");
        return null;
      }
      const filteredOperations = [];
      for (let i2 = 0, len = rawOperations.length; i2 < len; i2++) {
        if (!loserCursorsMap.hasOwnProperty(rawOperations[i2].identifier.major.toString())) {
          filteredOperations.push(rawOperations[i2]);
        }
      }
      if (commandsData.hadTrackedEditOperation && filteredOperations.length > 0) {
        filteredOperations[0]._isTracked = true;
      }
      let selectionsAfter = ctx.model.pushEditOperations(ctx.selectionsBefore, filteredOperations, (inverseEditOperations) => {
        const groupedInverseEditOperations = [];
        for (let i2 = 0; i2 < ctx.selectionsBefore.length; i2++) {
          groupedInverseEditOperations[i2] = [];
        }
        for (const op of inverseEditOperations) {
          if (!op.identifier) {
            continue;
          }
          groupedInverseEditOperations[op.identifier.major].push(op);
        }
        const minorBasedSorter = (a, b) => {
          return a.identifier.minor - b.identifier.minor;
        };
        const cursorSelections = [];
        for (let i2 = 0; i2 < ctx.selectionsBefore.length; i2++) {
          if (groupedInverseEditOperations[i2].length > 0) {
            groupedInverseEditOperations[i2].sort(minorBasedSorter);
            cursorSelections[i2] = commands[i2].computeCursorState(ctx.model, {
              getInverseEditOperations: () => {
                return groupedInverseEditOperations[i2];
              },
              getTrackedSelection: (id) => {
                const idx = parseInt(id, 10);
                const range2 = ctx.model._getTrackedRange(ctx.trackedRanges[idx]);
                if (ctx.trackedRangesDirection[idx] === 0) {
                  return new Selection$1(range2.startLineNumber, range2.startColumn, range2.endLineNumber, range2.endColumn);
                }
                return new Selection$1(range2.endLineNumber, range2.endColumn, range2.startLineNumber, range2.startColumn);
              }
            });
          } else {
            cursorSelections[i2] = ctx.selectionsBefore[i2];
          }
        }
        return cursorSelections;
      }, void 0, editReason);
      if (!selectionsAfter) {
        selectionsAfter = ctx.selectionsBefore;
      }
      const losingCursors = [];
      for (const losingCursorIndex in loserCursorsMap) {
        if (loserCursorsMap.hasOwnProperty(losingCursorIndex)) {
          losingCursors.push(parseInt(losingCursorIndex, 10));
        }
      }
      losingCursors.sort((a, b) => {
        return b - a;
      });
      for (const losingCursor of losingCursors) {
        selectionsAfter.splice(losingCursor, 1);
      }
      return selectionsAfter;
    }
    static _arrayIsEmpty(commands) {
      for (let i2 = 0, len = commands.length; i2 < len; i2++) {
        if (commands[i2]) {
          return false;
        }
      }
      return true;
    }
    static _getEditOperations(ctx, commands) {
      let operations = [];
      let hadTrackedEditOperation = false;
      for (let i2 = 0, len = commands.length; i2 < len; i2++) {
        const command = commands[i2];
        if (command) {
          const r = this._getEditOperationsFromCommand(ctx, i2, command);
          operations = operations.concat(r.operations);
          hadTrackedEditOperation = hadTrackedEditOperation || r.hadTrackedEditOperation;
        }
      }
      return {
        operations,
        hadTrackedEditOperation
      };
    }
    static _getEditOperationsFromCommand(ctx, majorIdentifier, command) {
      const operations = [];
      let operationMinor = 0;
      const addEditOperation = (range2, text2, forceMoveMarkers = false) => {
        if (Range$2.isEmpty(range2) && text2 === "") {
          return;
        }
        operations.push({
          identifier: {
            major: majorIdentifier,
            minor: operationMinor++
          },
          range: range2,
          text: text2,
          forceMoveMarkers,
          isAutoWhitespaceEdit: command.insertsAutoWhitespace
        });
      };
      let hadTrackedEditOperation = false;
      const addTrackedEditOperation = (selection, text2, forceMoveMarkers) => {
        hadTrackedEditOperation = true;
        addEditOperation(selection, text2, forceMoveMarkers);
      };
      const trackSelection = (_selection, trackPreviousOnEmpty) => {
        const selection = Selection$1.liftSelection(_selection);
        let stickiness;
        if (selection.isEmpty()) {
          if (typeof trackPreviousOnEmpty === "boolean") {
            if (trackPreviousOnEmpty) {
              stickiness = 2;
            } else {
              stickiness = 3;
            }
          } else {
            const maxLineColumn = ctx.model.getLineMaxColumn(selection.startLineNumber);
            if (selection.startColumn === maxLineColumn) {
              stickiness = 2;
            } else {
              stickiness = 3;
            }
          }
        } else {
          stickiness = 1;
        }
        const l = ctx.trackedRanges.length;
        const id = ctx.model._setTrackedRange(null, selection, stickiness);
        ctx.trackedRanges[l] = id;
        ctx.trackedRangesDirection[l] = selection.getDirection();
        return l.toString();
      };
      const editOperationBuilder = {
        addEditOperation,
        addTrackedEditOperation,
        trackSelection
      };
      try {
        command.getEditOperations(ctx.model, editOperationBuilder);
      } catch (e) {
        onUnexpectedError(e);
        return {
          operations: [],
          hadTrackedEditOperation: false
        };
      }
      return {
        operations,
        hadTrackedEditOperation
      };
    }
    static _getLoserCursorMap(operations) {
      operations = operations.slice(0);
      operations.sort((a, b) => {
        return -Range$2.compareRangesUsingEnds(a.range, b.range);
      });
      const loserCursorsMap = {};
      for (let i2 = 1; i2 < operations.length; i2++) {
        const previousOp = operations[i2 - 1];
        const currentOp = operations[i2];
        if (Range$2.getStartPosition(previousOp.range).isBefore(Range$2.getEndPosition(currentOp.range))) {
          let loserMajor;
          if (previousOp.identifier.major > currentOp.identifier.major) {
            loserMajor = previousOp.identifier.major;
          } else {
            loserMajor = currentOp.identifier.major;
          }
          loserCursorsMap[loserMajor.toString()] = true;
          for (let j = 0; j < operations.length; j++) {
            if (operations[j].identifier.major === loserMajor) {
              operations.splice(j, 1);
              if (j < i2) {
                i2--;
              }
              j--;
            }
          }
          if (i2 > 0) {
            i2--;
          }
        }
      }
      return loserCursorsMap;
    }
  }
  class CompositionLineState {
    constructor(text2, lineNumber, startSelectionOffset, endSelectionOffset) {
      this.text = text2;
      this.lineNumber = lineNumber;
      this.startSelectionOffset = startSelectionOffset;
      this.endSelectionOffset = endSelectionOffset;
    }
  }
  class CompositionState {
    static _capture(textModel, selections) {
      const result = [];
      for (const selection of selections) {
        if (selection.startLineNumber !== selection.endLineNumber) {
          return null;
        }
        const lineNumber = selection.startLineNumber;
        result.push(new CompositionLineState(textModel.getLineContent(lineNumber), lineNumber, selection.startColumn - 1, selection.endColumn - 1));
      }
      return result;
    }
    constructor(textModel, selections) {
      this._original = CompositionState._capture(textModel, selections);
    }
    /**
     * Returns the inserted text during this composition.
     * If the composition resulted in existing text being changed (i.e. not a pure insertion) it returns null.
     */
    deduceOutcome(textModel, selections) {
      if (!this._original) {
        return null;
      }
      const current = CompositionState._capture(textModel, selections);
      if (!current) {
        return null;
      }
      if (this._original.length !== current.length) {
        return null;
      }
      const result = [];
      for (let i2 = 0, len = this._original.length; i2 < len; i2++) {
        result.push(CompositionState._deduceOutcome(this._original[i2], current[i2]));
      }
      return result;
    }
    static _deduceOutcome(original, current) {
      const commonPrefix = Math.min(original.startSelectionOffset, current.startSelectionOffset, commonPrefixLength(original.text, current.text));
      const commonSuffix = Math.min(original.text.length - original.endSelectionOffset, current.text.length - current.endSelectionOffset, commonSuffixLength(original.text, current.text));
      const deletedText = original.text.substring(commonPrefix, original.text.length - commonSuffix);
      const insertedTextStartOffset = commonPrefix;
      const insertedTextEndOffset = current.text.length - commonSuffix;
      const insertedText = current.text.substring(insertedTextStartOffset, insertedTextEndOffset);
      const insertedTextRange = new Range$2(current.lineNumber, insertedTextStartOffset + 1, current.lineNumber, insertedTextEndOffset + 1);
      return new CompositionOutcome(deletedText, original.startSelectionOffset - commonPrefix, original.endSelectionOffset - commonPrefix, insertedText, current.startSelectionOffset - commonPrefix, current.endSelectionOffset - commonPrefix, insertedTextRange);
    }
  }
  const fallback = {
    getInitialState: () => NullState,
    tokenizeEncoded: (buffer, hasEOL, state) => nullTokenizeEncoded(0, state)
  };
  async function tokenizeToString(languageService, text2, languageId) {
    if (!languageId) {
      return _tokenizeToString(text2, languageService.languageIdCodec, fallback);
    }
    const tokenizationSupport = await TokenizationRegistry.getOrCreate(languageId);
    return _tokenizeToString(text2, languageService.languageIdCodec, tokenizationSupport || fallback);
  }
  function tokenizeLineToHTML(text2, viewLineTokens, colorMap, startOffset, endOffset, tabSize, useNbsp) {
    let result = `<div>`;
    let charIndex = 0;
    let width2 = 0;
    let prevIsSpace = true;
    for (let tokenIndex = 0, tokenCount = viewLineTokens.getCount(); tokenIndex < tokenCount; tokenIndex++) {
      const tokenEndIndex = viewLineTokens.getEndOffset(tokenIndex);
      let partContent = "";
      for (; charIndex < tokenEndIndex && charIndex < endOffset; charIndex++) {
        const charCode = text2.charCodeAt(charIndex);
        const isTab = charCode === 9;
        width2 += isFullWidthCharacter(charCode) ? 2 : isTab ? 0 : 1;
        if (charIndex < startOffset) {
          if (isTab) {
            const remainder = width2 % tabSize;
            width2 += remainder === 0 ? tabSize : tabSize - remainder;
          }
          continue;
        }
        switch (charCode) {
          case 9: {
            const remainder = width2 % tabSize;
            const insertSpacesCount = remainder === 0 ? tabSize : tabSize - remainder;
            width2 += insertSpacesCount;
            let spacesRemaining = insertSpacesCount;
            while (spacesRemaining > 0) {
              if (useNbsp && prevIsSpace) {
                partContent += "&#160;";
                prevIsSpace = false;
              } else {
                partContent += " ";
                prevIsSpace = true;
              }
              spacesRemaining--;
            }
            break;
          }
          case 60:
            partContent += "&lt;";
            prevIsSpace = false;
            break;
          case 62:
            partContent += "&gt;";
            prevIsSpace = false;
            break;
          case 38:
            partContent += "&amp;";
            prevIsSpace = false;
            break;
          case 0:
            partContent += "&#00;";
            prevIsSpace = false;
            break;
          case 65279:
          case 8232:
          case 8233:
          case 133:
            partContent += "�";
            prevIsSpace = false;
            break;
          case 13:
            partContent += "&#8203";
            prevIsSpace = false;
            break;
          case 32:
            if (useNbsp && prevIsSpace) {
              partContent += "&#160;";
              prevIsSpace = false;
            } else {
              partContent += " ";
              prevIsSpace = true;
            }
            break;
          default:
            partContent += String.fromCharCode(charCode);
            prevIsSpace = false;
        }
      }
      if (tokenEndIndex <= startOffset) {
        continue;
      }
      result += `<span style="${viewLineTokens.getInlineStyle(tokenIndex, colorMap)}">${partContent}</span>`;
      if (tokenEndIndex > endOffset || charIndex >= endOffset || startOffset >= endOffset) {
        break;
      }
    }
    result += `</div>`;
    return result;
  }
  function _tokenizeToString(text2, languageIdCodec, tokenizationSupport) {
    let result = `<div class="monaco-tokenized-source">`;
    const lines = splitLines(text2);
    let currentState = tokenizationSupport.getInitialState();
    for (let i2 = 0, len = lines.length; i2 < len; i2++) {
      const line = lines[i2];
      if (i2 > 0) {
        result += `<br/>`;
      }
      const tokenizationResult = tokenizationSupport.tokenizeEncoded(line, true, currentState);
      LineTokens.convertToEndOffset(tokenizationResult.tokens, line.length);
      const lineTokens = new LineTokens(tokenizationResult.tokens, line, languageIdCodec);
      const viewLineTokens = lineTokens.inflate();
      let startOffset = 0;
      for (let j = 0, lenJ = viewLineTokens.getCount(); j < lenJ; j++) {
        const type = viewLineTokens.getClassName(j);
        const endIndex = viewLineTokens.getEndOffset(j);
        result += `<span class="${type}">${escape$2(line.substring(startOffset, endIndex))}</span>`;
        startOffset = endIndex;
      }
      currentState = tokenizationResult.endState;
    }
    result += `</div>`;
    return result;
  }
  class CustomLine {
    constructor(decorationId, index, lineNumber, specialHeight, prefixSum) {
      this.decorationId = decorationId;
      this.index = index;
      this.lineNumber = lineNumber;
      this.specialHeight = specialHeight;
      this.prefixSum = prefixSum;
      this.maximumSpecialHeight = specialHeight;
      this.deleted = false;
    }
  }
  class LineHeightsManager {
    constructor(defaultLineHeight, customLineHeightData) {
      this._decorationIDToCustomLine = new ArrayMap();
      this._orderedCustomLines = [];
      this._pendingSpecialLinesToInsert = [];
      this._invalidIndex = 0;
      this._hasPending = false;
      this._defaultLineHeight = defaultLineHeight;
      if (customLineHeightData.length > 0) {
        for (const data of customLineHeightData) {
          this.insertOrChangeCustomLineHeight(data.decorationId, data.startLineNumber, data.endLineNumber, data.lineHeight);
        }
        this.commit();
      }
    }
    set defaultLineHeight(defaultLineHeight) {
      this._defaultLineHeight = defaultLineHeight;
    }
    get defaultLineHeight() {
      return this._defaultLineHeight;
    }
    removeCustomLineHeight(decorationID) {
      const customLines = this._decorationIDToCustomLine.get(decorationID);
      if (!customLines) {
        return;
      }
      this._decorationIDToCustomLine.delete(decorationID);
      for (const customLine of customLines) {
        customLine.deleted = true;
        this._invalidIndex = Math.min(this._invalidIndex, customLine.index);
      }
      this._hasPending = true;
    }
    insertOrChangeCustomLineHeight(decorationId, startLineNumber, endLineNumber, lineHeight) {
      this.removeCustomLineHeight(decorationId);
      for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
        const customLine = new CustomLine(decorationId, -1, lineNumber, lineHeight, 0);
        this._pendingSpecialLinesToInsert.push(customLine);
      }
      this._hasPending = true;
    }
    heightForLineNumber(lineNumber) {
      const searchIndex = this._binarySearchOverOrderedCustomLinesArray(lineNumber);
      if (searchIndex >= 0) {
        return this._orderedCustomLines[searchIndex].maximumSpecialHeight;
      }
      return this._defaultLineHeight;
    }
    getAccumulatedLineHeightsIncludingLineNumber(lineNumber) {
      const searchIndex = this._binarySearchOverOrderedCustomLinesArray(lineNumber);
      if (searchIndex >= 0) {
        return this._orderedCustomLines[searchIndex].prefixSum + this._orderedCustomLines[searchIndex].maximumSpecialHeight;
      }
      if (searchIndex === -1) {
        return this._defaultLineHeight * lineNumber;
      }
      const modifiedIndex = -(searchIndex + 1);
      const previousSpecialLine = this._orderedCustomLines[modifiedIndex - 1];
      return previousSpecialLine.prefixSum + previousSpecialLine.maximumSpecialHeight + this._defaultLineHeight * (lineNumber - previousSpecialLine.lineNumber);
    }
    onLinesDeleted(fromLineNumber, toLineNumber) {
      const deleteCount = toLineNumber - fromLineNumber + 1;
      const numberOfCustomLines = this._orderedCustomLines.length;
      const candidateStartIndexOfDeletion = this._binarySearchOverOrderedCustomLinesArray(fromLineNumber);
      let startIndexOfDeletion;
      if (candidateStartIndexOfDeletion >= 0) {
        startIndexOfDeletion = candidateStartIndexOfDeletion;
        for (let i2 = candidateStartIndexOfDeletion - 1; i2 >= 0; i2--) {
          if (this._orderedCustomLines[i2].lineNumber === fromLineNumber) {
            startIndexOfDeletion--;
          } else {
            break;
          }
        }
      } else {
        startIndexOfDeletion = candidateStartIndexOfDeletion === -(numberOfCustomLines + 1) && candidateStartIndexOfDeletion !== -1 ? numberOfCustomLines - 1 : -(candidateStartIndexOfDeletion + 1);
      }
      const candidateEndIndexOfDeletion = this._binarySearchOverOrderedCustomLinesArray(toLineNumber);
      let endIndexOfDeletion;
      if (candidateEndIndexOfDeletion >= 0) {
        endIndexOfDeletion = candidateEndIndexOfDeletion;
        for (let i2 = candidateEndIndexOfDeletion + 1; i2 < numberOfCustomLines; i2++) {
          if (this._orderedCustomLines[i2].lineNumber === toLineNumber) {
            endIndexOfDeletion++;
          } else {
            break;
          }
        }
      } else {
        endIndexOfDeletion = candidateEndIndexOfDeletion === -(numberOfCustomLines + 1) && candidateEndIndexOfDeletion !== -1 ? numberOfCustomLines - 1 : -(candidateEndIndexOfDeletion + 1);
      }
      const isEndIndexBiggerThanStartIndex = endIndexOfDeletion > startIndexOfDeletion;
      const isEndIndexEqualToStartIndexAndCoversCustomLine = endIndexOfDeletion === startIndexOfDeletion && this._orderedCustomLines[startIndexOfDeletion] && this._orderedCustomLines[startIndexOfDeletion].lineNumber >= fromLineNumber && this._orderedCustomLines[startIndexOfDeletion].lineNumber <= toLineNumber;
      if (isEndIndexBiggerThanStartIndex || isEndIndexEqualToStartIndexAndCoversCustomLine) {
        let maximumSpecialHeightOnDeletedInterval = 0;
        for (let i2 = startIndexOfDeletion; i2 <= endIndexOfDeletion; i2++) {
          maximumSpecialHeightOnDeletedInterval = Math.max(maximumSpecialHeightOnDeletedInterval, this._orderedCustomLines[i2].maximumSpecialHeight);
        }
        let prefixSumOnDeletedInterval = 0;
        if (startIndexOfDeletion > 0) {
          const previousSpecialLine = this._orderedCustomLines[startIndexOfDeletion - 1];
          prefixSumOnDeletedInterval = previousSpecialLine.prefixSum + previousSpecialLine.maximumSpecialHeight + this._defaultLineHeight * (fromLineNumber - previousSpecialLine.lineNumber - 1);
        } else {
          prefixSumOnDeletedInterval = fromLineNumber > 0 ? (fromLineNumber - 1) * this._defaultLineHeight : 0;
        }
        const firstSpecialLineDeleted = this._orderedCustomLines[startIndexOfDeletion];
        const lastSpecialLineDeleted = this._orderedCustomLines[endIndexOfDeletion];
        const firstSpecialLineAfterDeletion = this._orderedCustomLines[endIndexOfDeletion + 1];
        const heightOfFirstLineAfterDeletion = firstSpecialLineAfterDeletion && firstSpecialLineAfterDeletion.lineNumber === toLineNumber + 1 ? firstSpecialLineAfterDeletion.maximumSpecialHeight : this._defaultLineHeight;
        const totalHeightDeleted = lastSpecialLineDeleted.prefixSum + lastSpecialLineDeleted.maximumSpecialHeight - firstSpecialLineDeleted.prefixSum + this._defaultLineHeight * (toLineNumber - lastSpecialLineDeleted.lineNumber) + this._defaultLineHeight * (firstSpecialLineDeleted.lineNumber - fromLineNumber) + heightOfFirstLineAfterDeletion - maximumSpecialHeightOnDeletedInterval;
        const decorationIdsSeen = /* @__PURE__ */ new Set();
        const newOrderedCustomLines = [];
        const newDecorationIDToSpecialLine = new ArrayMap();
        let numberOfDeletions = 0;
        for (let i2 = 0; i2 < this._orderedCustomLines.length; i2++) {
          const customLine = this._orderedCustomLines[i2];
          if (i2 < startIndexOfDeletion) {
            newOrderedCustomLines.push(customLine);
            newDecorationIDToSpecialLine.add(customLine.decorationId, customLine);
          } else if (i2 >= startIndexOfDeletion && i2 <= endIndexOfDeletion) {
            const decorationId = customLine.decorationId;
            if (!decorationIdsSeen.has(decorationId)) {
              customLine.index -= numberOfDeletions;
              customLine.lineNumber = fromLineNumber;
              customLine.prefixSum = prefixSumOnDeletedInterval;
              customLine.maximumSpecialHeight = maximumSpecialHeightOnDeletedInterval;
              newOrderedCustomLines.push(customLine);
              newDecorationIDToSpecialLine.add(customLine.decorationId, customLine);
            } else {
              numberOfDeletions++;
            }
          } else if (i2 > endIndexOfDeletion) {
            customLine.index -= numberOfDeletions;
            customLine.lineNumber -= deleteCount;
            customLine.prefixSum -= totalHeightDeleted;
            newOrderedCustomLines.push(customLine);
            newDecorationIDToSpecialLine.add(customLine.decorationId, customLine);
          }
          decorationIdsSeen.add(customLine.decorationId);
        }
        this._orderedCustomLines = newOrderedCustomLines;
        this._decorationIDToCustomLine = newDecorationIDToSpecialLine;
      } else {
        const totalHeightDeleted = deleteCount * this._defaultLineHeight;
        for (let i2 = endIndexOfDeletion; i2 < this._orderedCustomLines.length; i2++) {
          const customLine = this._orderedCustomLines[i2];
          if (customLine.lineNumber > toLineNumber) {
            customLine.lineNumber -= deleteCount;
            customLine.prefixSum -= totalHeightDeleted;
          }
        }
      }
    }
    onLinesInserted(fromLineNumber, toLineNumber) {
      const insertCount = toLineNumber - fromLineNumber + 1;
      const candidateStartIndexOfInsertion = this._binarySearchOverOrderedCustomLinesArray(fromLineNumber);
      let startIndexOfInsertion;
      if (candidateStartIndexOfInsertion >= 0) {
        startIndexOfInsertion = candidateStartIndexOfInsertion;
        for (let i2 = candidateStartIndexOfInsertion - 1; i2 >= 0; i2--) {
          if (this._orderedCustomLines[i2].lineNumber === fromLineNumber) {
            startIndexOfInsertion--;
          } else {
            break;
          }
        }
      } else {
        startIndexOfInsertion = -(candidateStartIndexOfInsertion + 1);
      }
      const toReAdd = [];
      const decorationsImmediatelyAfter = /* @__PURE__ */ new Set();
      for (let i2 = startIndexOfInsertion; i2 < this._orderedCustomLines.length; i2++) {
        if (this._orderedCustomLines[i2].lineNumber === fromLineNumber) {
          decorationsImmediatelyAfter.add(this._orderedCustomLines[i2].decorationId);
        }
      }
      const decorationsImmediatelyBefore = /* @__PURE__ */ new Set();
      for (let i2 = startIndexOfInsertion - 1; i2 >= 0; i2--) {
        if (this._orderedCustomLines[i2].lineNumber === fromLineNumber - 1) {
          decorationsImmediatelyBefore.add(this._orderedCustomLines[i2].decorationId);
        }
      }
      const decorationsWithGaps = intersection(decorationsImmediatelyBefore, decorationsImmediatelyAfter);
      for (let i2 = startIndexOfInsertion; i2 < this._orderedCustomLines.length; i2++) {
        this._orderedCustomLines[i2].lineNumber += insertCount;
        this._orderedCustomLines[i2].prefixSum += this._defaultLineHeight * insertCount;
      }
      if (decorationsWithGaps.size > 0) {
        for (const decorationId of decorationsWithGaps) {
          const decoration2 = this._decorationIDToCustomLine.get(decorationId);
          if (decoration2) {
            const startLineNumber = decoration2.reduce((min, l) => Math.min(min, l.lineNumber), fromLineNumber);
            const endLineNumber = decoration2.reduce((max, l) => Math.max(max, l.lineNumber), fromLineNumber);
            const lineHeight = decoration2.reduce((max, l) => Math.max(max, l.specialHeight), 0);
            toReAdd.push({
              decorationId,
              startLineNumber,
              endLineNumber,
              lineHeight
            });
          }
        }
        for (const dec of toReAdd) {
          this.insertOrChangeCustomLineHeight(dec.decorationId, dec.startLineNumber, dec.endLineNumber, dec.lineHeight);
        }
        this.commit();
      }
    }
    commit() {
      if (!this._hasPending) {
        return;
      }
      for (const pendingChange of this._pendingSpecialLinesToInsert) {
        const candidateInsertionIndex = this._binarySearchOverOrderedCustomLinesArray(pendingChange.lineNumber);
        const insertionIndex = candidateInsertionIndex >= 0 ? candidateInsertionIndex : -(candidateInsertionIndex + 1);
        this._orderedCustomLines.splice(insertionIndex, 0, pendingChange);
        this._invalidIndex = Math.min(this._invalidIndex, insertionIndex);
      }
      this._pendingSpecialLinesToInsert = [];
      const newDecorationIDToSpecialLine = new ArrayMap();
      const newOrderedSpecialLines = [];
      for (let i2 = 0; i2 < this._invalidIndex; i2++) {
        const customLine = this._orderedCustomLines[i2];
        newOrderedSpecialLines.push(customLine);
        newDecorationIDToSpecialLine.add(customLine.decorationId, customLine);
      }
      let numberOfDeletions = 0;
      let previousSpecialLine = this._invalidIndex > 0 ? newOrderedSpecialLines[this._invalidIndex - 1] : void 0;
      for (let i2 = this._invalidIndex; i2 < this._orderedCustomLines.length; i2++) {
        const customLine = this._orderedCustomLines[i2];
        if (customLine.deleted) {
          numberOfDeletions++;
          continue;
        }
        customLine.index = i2 - numberOfDeletions;
        if (previousSpecialLine && previousSpecialLine.lineNumber === customLine.lineNumber) {
          customLine.maximumSpecialHeight = previousSpecialLine.maximumSpecialHeight;
          customLine.prefixSum = previousSpecialLine.prefixSum;
        } else {
          let maximumSpecialHeight = customLine.specialHeight;
          for (let j = i2; j < this._orderedCustomLines.length; j++) {
            const nextSpecialLine = this._orderedCustomLines[j];
            if (nextSpecialLine.deleted) {
              continue;
            }
            if (nextSpecialLine.lineNumber !== customLine.lineNumber) {
              break;
            }
            maximumSpecialHeight = Math.max(maximumSpecialHeight, nextSpecialLine.specialHeight);
          }
          customLine.maximumSpecialHeight = maximumSpecialHeight;
          let prefixSum;
          if (previousSpecialLine) {
            prefixSum = previousSpecialLine.prefixSum + previousSpecialLine.maximumSpecialHeight + this._defaultLineHeight * (customLine.lineNumber - previousSpecialLine.lineNumber - 1);
          } else {
            prefixSum = this._defaultLineHeight * (customLine.lineNumber - 1);
          }
          customLine.prefixSum = prefixSum;
        }
        previousSpecialLine = customLine;
        newOrderedSpecialLines.push(customLine);
        newDecorationIDToSpecialLine.add(customLine.decorationId, customLine);
      }
      this._orderedCustomLines = newOrderedSpecialLines;
      this._decorationIDToCustomLine = newDecorationIDToSpecialLine;
      this._invalidIndex = Infinity;
      this._hasPending = false;
    }
    _binarySearchOverOrderedCustomLinesArray(lineNumber) {
      return binarySearch2(this._orderedCustomLines.length, (index) => {
        const line = this._orderedCustomLines[index];
        if (line.lineNumber === lineNumber) {
          return 0;
        } else if (line.lineNumber < lineNumber) {
          return -1;
        } else {
          return 1;
        }
      });
    }
  }
  class ArrayMap {
    constructor() {
      this._map = /* @__PURE__ */ new Map();
    }
    add(key, value) {
      const array2 = this._map.get(key);
      if (!array2) {
        this._map.set(key, [value]);
      } else {
        array2.push(value);
      }
    }
    get(key) {
      return this._map.get(key);
    }
    delete(key) {
      this._map.delete(key);
    }
  }
  class PendingChanges {
    constructor() {
      this._hasPending = false;
      this._inserts = [];
      this._changes = [];
      this._removes = [];
    }
    insert(x) {
      this._hasPending = true;
      this._inserts.push(x);
    }
    change(x) {
      this._hasPending = true;
      this._changes.push(x);
    }
    remove(x) {
      this._hasPending = true;
      this._removes.push(x);
    }
    commit(linesLayout) {
      if (!this._hasPending) {
        return;
      }
      const inserts = this._inserts;
      const changes = this._changes;
      const removes = this._removes;
      this._hasPending = false;
      this._inserts = [];
      this._changes = [];
      this._removes = [];
      linesLayout._commitPendingChanges(inserts, changes, removes);
    }
  }
  class EditorWhitespace {
    constructor(id, afterLineNumber, ordinal, height, minWidth) {
      this.id = id;
      this.afterLineNumber = afterLineNumber;
      this.ordinal = ordinal;
      this.height = height;
      this.minWidth = minWidth;
      this.prefixSum = 0;
    }
  }
  let LinesLayout$1 = (_i = class {
    constructor(lineCount, defaultLineHeight, paddingTop, paddingBottom, customLineHeightData) {
      this._instanceId = singleLetterHash(++_i.INSTANCE_COUNT);
      this._pendingChanges = new PendingChanges();
      this._lastWhitespaceId = 0;
      this._arr = [];
      this._prefixSumValidIndex = -1;
      this._minWidth = -1;
      this._lineCount = lineCount;
      this._paddingTop = paddingTop;
      this._paddingBottom = paddingBottom;
      this._lineHeightsManager = new LineHeightsManager(defaultLineHeight, customLineHeightData);
    }
    /**
     * Find the insertion index for a new value inside a sorted array of values.
     * If the value is already present in the sorted array, the insertion index will be after the already existing value.
     */
    static findInsertionIndex(arr, afterLineNumber, ordinal) {
      let low = 0;
      let high = arr.length;
      while (low < high) {
        const mid = low + high >>> 1;
        if (afterLineNumber === arr[mid].afterLineNumber) {
          if (ordinal < arr[mid].ordinal) {
            high = mid;
          } else {
            low = mid + 1;
          }
        } else if (afterLineNumber < arr[mid].afterLineNumber) {
          high = mid;
        } else {
          low = mid + 1;
        }
      }
      return low;
    }
    /**
     * Change the height of a line in pixels.
     */
    setDefaultLineHeight(lineHeight) {
      this._lineHeightsManager.defaultLineHeight = lineHeight;
    }
    /**
     * Changes the padding used to calculate vertical offsets.
     */
    setPadding(paddingTop, paddingBottom) {
      this._paddingTop = paddingTop;
      this._paddingBottom = paddingBottom;
    }
    /**
     * Set the number of lines.
     *
     * @param lineCount New number of lines.
     */
    onFlushed(lineCount, customLineHeightData) {
      this._lineCount = lineCount;
      this._lineHeightsManager = new LineHeightsManager(this._lineHeightsManager.defaultLineHeight, customLineHeightData);
    }
    changeLineHeights(callback) {
      let hadAChange = false;
      try {
        const accessor = {
          insertOrChangeCustomLineHeight: (decorationId, startLineNumber, endLineNumber, lineHeight) => {
            hadAChange = true;
            this._lineHeightsManager.insertOrChangeCustomLineHeight(decorationId, startLineNumber, endLineNumber, lineHeight);
          },
          removeCustomLineHeight: (decorationId) => {
            hadAChange = true;
            this._lineHeightsManager.removeCustomLineHeight(decorationId);
          }
        };
        callback(accessor);
      } finally {
        this._lineHeightsManager.commit();
      }
      return hadAChange;
    }
    changeWhitespace(callback) {
      let hadAChange = false;
      try {
        const accessor = {
          insertWhitespace: (afterLineNumber, ordinal, heightInPx, minWidth) => {
            hadAChange = true;
            afterLineNumber = afterLineNumber | 0;
            ordinal = ordinal | 0;
            heightInPx = heightInPx | 0;
            minWidth = minWidth | 0;
            const id = this._instanceId + ++this._lastWhitespaceId;
            this._pendingChanges.insert(new EditorWhitespace(id, afterLineNumber, ordinal, heightInPx, minWidth));
            return id;
          },
          changeOneWhitespace: (id, newAfterLineNumber, newHeight) => {
            hadAChange = true;
            newAfterLineNumber = newAfterLineNumber | 0;
            newHeight = newHeight | 0;
            this._pendingChanges.change({ id, newAfterLineNumber, newHeight });
          },
          removeWhitespace: (id) => {
            hadAChange = true;
            this._pendingChanges.remove({ id });
          }
        };
        callback(accessor);
      } finally {
        this._pendingChanges.commit(this);
      }
      return hadAChange;
    }
    _commitPendingChanges(inserts, changes, removes) {
      if (inserts.length > 0 || removes.length > 0) {
        this._minWidth = -1;
      }
      if (inserts.length + changes.length + removes.length <= 1) {
        for (const insert of inserts) {
          this._insertWhitespace(insert);
        }
        for (const change of changes) {
          this._changeOneWhitespace(change.id, change.newAfterLineNumber, change.newHeight);
        }
        for (const remove of removes) {
          const index = this._findWhitespaceIndex(remove.id);
          if (index === -1) {
            continue;
          }
          this._removeWhitespace(index);
        }
        return;
      }
      const toRemove = /* @__PURE__ */ new Set();
      for (const remove of removes) {
        toRemove.add(remove.id);
      }
      const toChange = /* @__PURE__ */ new Map();
      for (const change of changes) {
        toChange.set(change.id, change);
      }
      const applyRemoveAndChange = (whitespaces) => {
        const result2 = [];
        for (const whitespace of whitespaces) {
          if (toRemove.has(whitespace.id)) {
            continue;
          }
          if (toChange.has(whitespace.id)) {
            const change = toChange.get(whitespace.id);
            whitespace.afterLineNumber = change.newAfterLineNumber;
            whitespace.height = change.newHeight;
          }
          result2.push(whitespace);
        }
        return result2;
      };
      const result = applyRemoveAndChange(this._arr).concat(applyRemoveAndChange(inserts));
      result.sort((a, b) => {
        if (a.afterLineNumber === b.afterLineNumber) {
          return a.ordinal - b.ordinal;
        }
        return a.afterLineNumber - b.afterLineNumber;
      });
      this._arr = result;
      this._prefixSumValidIndex = -1;
    }
    _insertWhitespace(whitespace) {
      const insertIndex = _i.findInsertionIndex(this._arr, whitespace.afterLineNumber, whitespace.ordinal);
      this._arr.splice(insertIndex, 0, whitespace);
      this._prefixSumValidIndex = Math.min(this._prefixSumValidIndex, insertIndex - 1);
    }
    _findWhitespaceIndex(id) {
      const arr = this._arr;
      for (let i2 = 0, len = arr.length; i2 < len; i2++) {
        if (arr[i2].id === id) {
          return i2;
        }
      }
      return -1;
    }
    _changeOneWhitespace(id, newAfterLineNumber, newHeight) {
      const index = this._findWhitespaceIndex(id);
      if (index === -1) {
        return;
      }
      if (this._arr[index].height !== newHeight) {
        this._arr[index].height = newHeight;
        this._prefixSumValidIndex = Math.min(this._prefixSumValidIndex, index - 1);
      }
      if (this._arr[index].afterLineNumber !== newAfterLineNumber) {
        const whitespace = this._arr[index];
        this._removeWhitespace(index);
        whitespace.afterLineNumber = newAfterLineNumber;
        this._insertWhitespace(whitespace);
      }
    }
    _removeWhitespace(removeIndex) {
      this._arr.splice(removeIndex, 1);
      this._prefixSumValidIndex = Math.min(this._prefixSumValidIndex, removeIndex - 1);
    }
    /**
     * Notify the layouter that lines have been deleted (a continuous zone of lines).
     *
     * @param fromLineNumber The line number at which the deletion started, inclusive
     * @param toLineNumber The line number at which the deletion ended, inclusive
     */
    onLinesDeleted(fromLineNumber, toLineNumber) {
      fromLineNumber = fromLineNumber | 0;
      toLineNumber = toLineNumber | 0;
      this._lineCount -= toLineNumber - fromLineNumber + 1;
      for (let i2 = 0, len = this._arr.length; i2 < len; i2++) {
        const afterLineNumber = this._arr[i2].afterLineNumber;
        if (fromLineNumber <= afterLineNumber && afterLineNumber <= toLineNumber) {
          this._arr[i2].afterLineNumber = fromLineNumber - 1;
        } else if (afterLineNumber > toLineNumber) {
          this._arr[i2].afterLineNumber -= toLineNumber - fromLineNumber + 1;
        }
      }
      this._lineHeightsManager.onLinesDeleted(fromLineNumber, toLineNumber);
    }
    /**
     * Notify the layouter that lines have been inserted (a continuous zone of lines).
     *
     * @param fromLineNumber The line number at which the insertion started, inclusive
     * @param toLineNumber The line number at which the insertion ended, inclusive.
     */
    onLinesInserted(fromLineNumber, toLineNumber) {
      fromLineNumber = fromLineNumber | 0;
      toLineNumber = toLineNumber | 0;
      this._lineCount += toLineNumber - fromLineNumber + 1;
      for (let i2 = 0, len = this._arr.length; i2 < len; i2++) {
        const afterLineNumber = this._arr[i2].afterLineNumber;
        if (fromLineNumber <= afterLineNumber) {
          this._arr[i2].afterLineNumber += toLineNumber - fromLineNumber + 1;
        }
      }
      this._lineHeightsManager.onLinesInserted(fromLineNumber, toLineNumber);
    }
    /**
     * Get the sum of all the whitespaces.
     */
    getWhitespacesTotalHeight() {
      if (this._arr.length === 0) {
        return 0;
      }
      return this.getWhitespacesAccumulatedHeight(this._arr.length - 1);
    }
    /**
     * Return the sum of the heights of the whitespaces at [0..index].
     * This includes the whitespace at `index`.
     *
     * @param index The index of the whitespace.
     * @return The sum of the heights of all whitespaces before the one at `index`, including the one at `index`.
     */
    getWhitespacesAccumulatedHeight(index) {
      index = index | 0;
      let startIndex = Math.max(0, this._prefixSumValidIndex + 1);
      if (startIndex === 0) {
        this._arr[0].prefixSum = this._arr[0].height;
        startIndex++;
      }
      for (let i2 = startIndex; i2 <= index; i2++) {
        this._arr[i2].prefixSum = this._arr[i2 - 1].prefixSum + this._arr[i2].height;
      }
      this._prefixSumValidIndex = Math.max(this._prefixSumValidIndex, index);
      return this._arr[index].prefixSum;
    }
    /**
     * Get the sum of heights for all objects.
     *
     * @return The sum of heights for all objects.
     */
    getLinesTotalHeight() {
      const linesHeight = this._lineHeightsManager.getAccumulatedLineHeightsIncludingLineNumber(this._lineCount);
      const whitespacesHeight = this.getWhitespacesTotalHeight();
      return linesHeight + whitespacesHeight + this._paddingTop + this._paddingBottom;
    }
    /**
     * Returns the accumulated height of whitespaces before the given line number.
     *
     * @param lineNumber The line number
     */
    getWhitespaceAccumulatedHeightBeforeLineNumber(lineNumber) {
      lineNumber = lineNumber | 0;
      const lastWhitespaceBeforeLineNumber = this._findLastWhitespaceBeforeLineNumber(lineNumber);
      if (lastWhitespaceBeforeLineNumber === -1) {
        return 0;
      }
      return this.getWhitespacesAccumulatedHeight(lastWhitespaceBeforeLineNumber);
    }
    _findLastWhitespaceBeforeLineNumber(lineNumber) {
      lineNumber = lineNumber | 0;
      const arr = this._arr;
      let low = 0;
      let high = arr.length - 1;
      while (low <= high) {
        const delta = high - low | 0;
        const halfDelta = delta / 2 | 0;
        const mid = low + halfDelta | 0;
        if (arr[mid].afterLineNumber < lineNumber) {
          if (mid + 1 >= arr.length || arr[mid + 1].afterLineNumber >= lineNumber) {
            return mid;
          } else {
            low = mid + 1 | 0;
          }
        } else {
          high = mid - 1 | 0;
        }
      }
      return -1;
    }
    _findFirstWhitespaceAfterLineNumber(lineNumber) {
      lineNumber = lineNumber | 0;
      const lastWhitespaceBeforeLineNumber = this._findLastWhitespaceBeforeLineNumber(lineNumber);
      const firstWhitespaceAfterLineNumber = lastWhitespaceBeforeLineNumber + 1;
      if (firstWhitespaceAfterLineNumber < this._arr.length) {
        return firstWhitespaceAfterLineNumber;
      }
      return -1;
    }
    /**
     * Find the index of the first whitespace which has `afterLineNumber` >= `lineNumber`.
     * @return The index of the first whitespace with `afterLineNumber` >= `lineNumber` or -1 if no whitespace is found.
     */
    getFirstWhitespaceIndexAfterLineNumber(lineNumber) {
      lineNumber = lineNumber | 0;
      return this._findFirstWhitespaceAfterLineNumber(lineNumber);
    }
    /**
     * Get the vertical offset (the sum of heights for all objects above) a certain line number.
     *
     * @param lineNumber The line number
     * @return The sum of heights for all objects above `lineNumber`.
     */
    getVerticalOffsetForLineNumber(lineNumber, includeViewZones = false) {
      lineNumber = lineNumber | 0;
      let previousLinesHeight;
      if (lineNumber > 1) {
        previousLinesHeight = this._lineHeightsManager.getAccumulatedLineHeightsIncludingLineNumber(lineNumber - 1);
      } else {
        previousLinesHeight = 0;
      }
      const previousWhitespacesHeight = this.getWhitespaceAccumulatedHeightBeforeLineNumber(lineNumber - (includeViewZones ? 1 : 0));
      return previousLinesHeight + previousWhitespacesHeight + this._paddingTop;
    }
    getLineHeightForLineNumber(lineNumber) {
      return this._lineHeightsManager.heightForLineNumber(lineNumber);
    }
    /**
     * Get the vertical offset (the sum of heights for all objects above) a certain line number and also the line height of the line.
     *
     * @param lineNumber The line number
     * @return The sum of heights for all objects above `lineNumber`.
     */
    getVerticalOffsetAfterLineNumber(lineNumber, includeViewZones = false) {
      lineNumber = lineNumber | 0;
      const previousLinesHeight = this._lineHeightsManager.getAccumulatedLineHeightsIncludingLineNumber(lineNumber);
      const previousWhitespacesHeight = this.getWhitespaceAccumulatedHeightBeforeLineNumber(lineNumber + (includeViewZones ? 1 : 0));
      return previousLinesHeight + previousWhitespacesHeight + this._paddingTop;
    }
    /**
     * The maximum min width for all whitespaces.
     */
    getWhitespaceMinWidth() {
      if (this._minWidth === -1) {
        let minWidth = 0;
        for (let i2 = 0, len = this._arr.length; i2 < len; i2++) {
          minWidth = Math.max(minWidth, this._arr[i2].minWidth);
        }
        this._minWidth = minWidth;
      }
      return this._minWidth;
    }
    /**
     * Check if `verticalOffset` is below all lines.
     */
    isAfterLines(verticalOffset) {
      const totalHeight = this.getLinesTotalHeight();
      return verticalOffset > totalHeight;
    }
    isInTopPadding(verticalOffset) {
      if (this._paddingTop === 0) {
        return false;
      }
      return verticalOffset < this._paddingTop;
    }
    isInBottomPadding(verticalOffset) {
      if (this._paddingBottom === 0) {
        return false;
      }
      const totalHeight = this.getLinesTotalHeight();
      return verticalOffset >= totalHeight - this._paddingBottom;
    }
    /**
     * Find the first line number that is at or after vertical offset `verticalOffset`.
     * i.e. if getVerticalOffsetForLine(line) is x and getVerticalOffsetForLine(line + 1) is y, then
     * getLineNumberAtOrAfterVerticalOffset(i) = line, x <= i < y.
     *
     * @param verticalOffset The vertical offset to search at.
     * @return The line number at or after vertical offset `verticalOffset`.
     */
    getLineNumberAtOrAfterVerticalOffset(verticalOffset) {
      verticalOffset = verticalOffset | 0;
      if (verticalOffset < 0) {
        return 1;
      }
      const linesCount = this._lineCount | 0;
      let minLineNumber = 1;
      let maxLineNumber = linesCount;
      while (minLineNumber < maxLineNumber) {
        const midLineNumber = (minLineNumber + maxLineNumber) / 2 | 0;
        const lineHeight = this.getLineHeightForLineNumber(midLineNumber);
        const midLineNumberVerticalOffset = this.getVerticalOffsetForLineNumber(midLineNumber) | 0;
        if (verticalOffset >= midLineNumberVerticalOffset + lineHeight) {
          minLineNumber = midLineNumber + 1;
        } else if (verticalOffset >= midLineNumberVerticalOffset) {
          return midLineNumber;
        } else {
          maxLineNumber = midLineNumber;
        }
      }
      if (minLineNumber > linesCount) {
        return linesCount;
      }
      return minLineNumber;
    }
    /**
     * Get all the lines and their relative vertical offsets that are positioned between `verticalOffset1` and `verticalOffset2`.
     *
     * @param verticalOffset1 The beginning of the viewport.
     * @param verticalOffset2 The end of the viewport.
     * @return A structure describing the lines positioned between `verticalOffset1` and `verticalOffset2`.
     */
    getLinesViewportData(verticalOffset1, verticalOffset2) {
      verticalOffset1 = verticalOffset1 | 0;
      verticalOffset2 = verticalOffset2 | 0;
      const startLineNumber = this.getLineNumberAtOrAfterVerticalOffset(verticalOffset1) | 0;
      const startLineNumberVerticalOffset = this.getVerticalOffsetForLineNumber(startLineNumber) | 0;
      let endLineNumber = this._lineCount | 0;
      let whitespaceIndex = this.getFirstWhitespaceIndexAfterLineNumber(startLineNumber) | 0;
      const whitespaceCount = this.getWhitespacesCount() | 0;
      let currentWhitespaceHeight;
      let currentWhitespaceAfterLineNumber;
      if (whitespaceIndex === -1) {
        whitespaceIndex = whitespaceCount;
        currentWhitespaceAfterLineNumber = endLineNumber + 1;
        currentWhitespaceHeight = 0;
      } else {
        currentWhitespaceAfterLineNumber = this.getAfterLineNumberForWhitespaceIndex(whitespaceIndex) | 0;
        currentWhitespaceHeight = this.getHeightForWhitespaceIndex(whitespaceIndex) | 0;
      }
      let currentVerticalOffset = startLineNumberVerticalOffset;
      let currentLineRelativeOffset = currentVerticalOffset;
      const STEP_SIZE = 5e5;
      let bigNumbersDelta = 0;
      if (startLineNumberVerticalOffset >= STEP_SIZE) {
        bigNumbersDelta = Math.floor(startLineNumberVerticalOffset / STEP_SIZE) * STEP_SIZE;
        bigNumbersDelta = Math.floor(bigNumbersDelta / this._lineHeightsManager.defaultLineHeight) * this._lineHeightsManager.defaultLineHeight;
        currentLineRelativeOffset -= bigNumbersDelta;
      }
      const linesOffsets = [];
      const verticalCenter = verticalOffset1 + (verticalOffset2 - verticalOffset1) / 2;
      let centeredLineNumber = -1;
      for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
        const lineHeight = this.getLineHeightForLineNumber(lineNumber);
        if (centeredLineNumber === -1) {
          const currentLineTop = currentVerticalOffset;
          const currentLineBottom = currentVerticalOffset + lineHeight;
          if (currentLineTop <= verticalCenter && verticalCenter < currentLineBottom || currentLineTop > verticalCenter) {
            centeredLineNumber = lineNumber;
          }
        }
        currentVerticalOffset += lineHeight;
        linesOffsets[lineNumber - startLineNumber] = currentLineRelativeOffset;
        currentLineRelativeOffset += lineHeight;
        while (currentWhitespaceAfterLineNumber === lineNumber) {
          currentLineRelativeOffset += currentWhitespaceHeight;
          currentVerticalOffset += currentWhitespaceHeight;
          whitespaceIndex++;
          if (whitespaceIndex >= whitespaceCount) {
            currentWhitespaceAfterLineNumber = endLineNumber + 1;
          } else {
            currentWhitespaceAfterLineNumber = this.getAfterLineNumberForWhitespaceIndex(whitespaceIndex) | 0;
            currentWhitespaceHeight = this.getHeightForWhitespaceIndex(whitespaceIndex) | 0;
          }
        }
        if (currentVerticalOffset >= verticalOffset2) {
          endLineNumber = lineNumber;
          break;
        }
      }
      if (centeredLineNumber === -1) {
        centeredLineNumber = endLineNumber;
      }
      const endLineNumberVerticalOffset = this.getVerticalOffsetForLineNumber(endLineNumber) | 0;
      let completelyVisibleStartLineNumber = startLineNumber;
      let completelyVisibleEndLineNumber = endLineNumber;
      if (completelyVisibleStartLineNumber < completelyVisibleEndLineNumber) {
        if (startLineNumberVerticalOffset < verticalOffset1) {
          completelyVisibleStartLineNumber++;
        }
      }
      if (completelyVisibleStartLineNumber < completelyVisibleEndLineNumber) {
        const endLineHeight = this.getLineHeightForLineNumber(endLineNumber);
        if (endLineNumberVerticalOffset + endLineHeight > verticalOffset2) {
          completelyVisibleEndLineNumber--;
        }
      }
      return {
        bigNumbersDelta,
        startLineNumber,
        endLineNumber,
        relativeVerticalOffset: linesOffsets,
        centeredLineNumber,
        completelyVisibleStartLineNumber,
        completelyVisibleEndLineNumber,
        lineHeight: this._lineHeightsManager.defaultLineHeight
      };
    }
    getVerticalOffsetForWhitespaceIndex(whitespaceIndex) {
      whitespaceIndex = whitespaceIndex | 0;
      const afterLineNumber = this.getAfterLineNumberForWhitespaceIndex(whitespaceIndex);
      let previousLinesHeight;
      if (afterLineNumber >= 1) {
        previousLinesHeight = this._lineHeightsManager.getAccumulatedLineHeightsIncludingLineNumber(afterLineNumber);
      } else {
        previousLinesHeight = 0;
      }
      let previousWhitespacesHeight;
      if (whitespaceIndex > 0) {
        previousWhitespacesHeight = this.getWhitespacesAccumulatedHeight(whitespaceIndex - 1);
      } else {
        previousWhitespacesHeight = 0;
      }
      return previousLinesHeight + previousWhitespacesHeight + this._paddingTop;
    }
    getWhitespaceIndexAtOrAfterVerticallOffset(verticalOffset) {
      verticalOffset = verticalOffset | 0;
      let minWhitespaceIndex = 0;
      let maxWhitespaceIndex = this.getWhitespacesCount() - 1;
      if (maxWhitespaceIndex < 0) {
        return -1;
      }
      const maxWhitespaceVerticalOffset = this.getVerticalOffsetForWhitespaceIndex(maxWhitespaceIndex);
      const maxWhitespaceHeight = this.getHeightForWhitespaceIndex(maxWhitespaceIndex);
      if (verticalOffset >= maxWhitespaceVerticalOffset + maxWhitespaceHeight) {
        return -1;
      }
      while (minWhitespaceIndex < maxWhitespaceIndex) {
        const midWhitespaceIndex = Math.floor((minWhitespaceIndex + maxWhitespaceIndex) / 2);
        const midWhitespaceVerticalOffset = this.getVerticalOffsetForWhitespaceIndex(midWhitespaceIndex);
        const midWhitespaceHeight = this.getHeightForWhitespaceIndex(midWhitespaceIndex);
        if (verticalOffset >= midWhitespaceVerticalOffset + midWhitespaceHeight) {
          minWhitespaceIndex = midWhitespaceIndex + 1;
        } else if (verticalOffset >= midWhitespaceVerticalOffset) {
          return midWhitespaceIndex;
        } else {
          maxWhitespaceIndex = midWhitespaceIndex;
        }
      }
      return minWhitespaceIndex;
    }
    /**
     * Get exactly the whitespace that is layouted at `verticalOffset`.
     *
     * @param verticalOffset The vertical offset.
     * @return Precisely the whitespace that is layouted at `verticaloffset` or null.
     */
    getWhitespaceAtVerticalOffset(verticalOffset) {
      verticalOffset = verticalOffset | 0;
      const candidateIndex = this.getWhitespaceIndexAtOrAfterVerticallOffset(verticalOffset);
      if (candidateIndex < 0) {
        return null;
      }
      if (candidateIndex >= this.getWhitespacesCount()) {
        return null;
      }
      const candidateTop = this.getVerticalOffsetForWhitespaceIndex(candidateIndex);
      if (candidateTop > verticalOffset) {
        return null;
      }
      const candidateHeight = this.getHeightForWhitespaceIndex(candidateIndex);
      const candidateId = this.getIdForWhitespaceIndex(candidateIndex);
      const candidateAfterLineNumber = this.getAfterLineNumberForWhitespaceIndex(candidateIndex);
      return {
        id: candidateId,
        afterLineNumber: candidateAfterLineNumber,
        verticalOffset: candidateTop,
        height: candidateHeight
      };
    }
    /**
     * Get a list of whitespaces that are positioned between `verticalOffset1` and `verticalOffset2`.
     *
     * @param verticalOffset1 The beginning of the viewport.
     * @param verticalOffset2 The end of the viewport.
     * @return An array with all the whitespaces in the viewport. If no whitespace is in viewport, the array is empty.
     */
    getWhitespaceViewportData(verticalOffset1, verticalOffset2) {
      verticalOffset1 = verticalOffset1 | 0;
      verticalOffset2 = verticalOffset2 | 0;
      const startIndex = this.getWhitespaceIndexAtOrAfterVerticallOffset(verticalOffset1);
      const endIndex = this.getWhitespacesCount() - 1;
      if (startIndex < 0) {
        return [];
      }
      const result = [];
      for (let i2 = startIndex; i2 <= endIndex; i2++) {
        const top = this.getVerticalOffsetForWhitespaceIndex(i2);
        const height = this.getHeightForWhitespaceIndex(i2);
        if (top >= verticalOffset2) {
          break;
        }
        result.push({
          id: this.getIdForWhitespaceIndex(i2),
          afterLineNumber: this.getAfterLineNumberForWhitespaceIndex(i2),
          verticalOffset: top,
          height
        });
      }
      return result;
    }
    /**
     * Get all whitespaces.
     */
    getWhitespaces() {
      return this._arr.slice(0);
    }
    /**
     * The number of whitespaces.
     */
    getWhitespacesCount() {
      return this._arr.length;
    }
    /**
     * Get the `id` for whitespace at index `index`.
     *
     * @param index The index of the whitespace.
     * @return `id` of whitespace at `index`.
     */
    getIdForWhitespaceIndex(index) {
      index = index | 0;
      return this._arr[index].id;
    }
    /**
     * Get the `afterLineNumber` for whitespace at index `index`.
     *
     * @param index The index of the whitespace.
     * @return `afterLineNumber` of whitespace at `index`.
     */
    getAfterLineNumberForWhitespaceIndex(index) {
      index = index | 0;
      return this._arr[index].afterLineNumber;
    }
    /**
     * Get the `height` for whitespace at index `index`.
     *
     * @param index The index of the whitespace.
     * @return `height` of whitespace at `index`.
     */
    getHeightForWhitespaceIndex(index) {
      index = index | 0;
      return this._arr[index].height;
    }
  }, _i.INSTANCE_COUNT = 0, _i);
  const SMOOTH_SCROLLING_TIME = 125;
  class EditorScrollDimensions {
    constructor(width2, contentWidth, height, contentHeight) {
      width2 = width2 | 0;
      contentWidth = contentWidth | 0;
      height = height | 0;
      contentHeight = contentHeight | 0;
      if (width2 < 0) {
        width2 = 0;
      }
      if (contentWidth < 0) {
        contentWidth = 0;
      }
      if (height < 0) {
        height = 0;
      }
      if (contentHeight < 0) {
        contentHeight = 0;
      }
      this.width = width2;
      this.contentWidth = contentWidth;
      this.scrollWidth = Math.max(width2, contentWidth);
      this.height = height;
      this.contentHeight = contentHeight;
      this.scrollHeight = Math.max(height, contentHeight);
    }
    equals(other) {
      return this.width === other.width && this.contentWidth === other.contentWidth && this.height === other.height && this.contentHeight === other.contentHeight;
    }
  }
  class EditorScrollable extends Disposable {
    constructor(smoothScrollDuration, scheduleAtNextAnimationFrame2) {
      super();
      this._onDidContentSizeChange = this._register(new Emitter$1());
      this.onDidContentSizeChange = this._onDidContentSizeChange.event;
      this._dimensions = new EditorScrollDimensions(0, 0, 0, 0);
      this._scrollable = this._register(new Scrollable({
        forceIntegerValues: true,
        smoothScrollDuration,
        scheduleAtNextAnimationFrame: scheduleAtNextAnimationFrame2
      }));
      this.onDidScroll = this._scrollable.onScroll;
    }
    getScrollable() {
      return this._scrollable;
    }
    setSmoothScrollDuration(smoothScrollDuration) {
      this._scrollable.setSmoothScrollDuration(smoothScrollDuration);
    }
    validateScrollPosition(scrollPosition) {
      return this._scrollable.validateScrollPosition(scrollPosition);
    }
    getScrollDimensions() {
      return this._dimensions;
    }
    setScrollDimensions(dimensions) {
      if (this._dimensions.equals(dimensions)) {
        return;
      }
      const oldDimensions = this._dimensions;
      this._dimensions = dimensions;
      this._scrollable.setScrollDimensions({
        width: dimensions.width,
        scrollWidth: dimensions.scrollWidth,
        height: dimensions.height,
        scrollHeight: dimensions.scrollHeight
      }, true);
      const contentWidthChanged = oldDimensions.contentWidth !== dimensions.contentWidth;
      const contentHeightChanged = oldDimensions.contentHeight !== dimensions.contentHeight;
      if (contentWidthChanged || contentHeightChanged) {
        this._onDidContentSizeChange.fire(new ContentSizeChangedEvent(oldDimensions.contentWidth, oldDimensions.contentHeight, dimensions.contentWidth, dimensions.contentHeight));
      }
    }
    getFutureScrollPosition() {
      return this._scrollable.getFutureScrollPosition();
    }
    getCurrentScrollPosition() {
      return this._scrollable.getCurrentScrollPosition();
    }
    setScrollPositionNow(update) {
      this._scrollable.setScrollPositionNow(update);
    }
    setScrollPositionSmooth(update) {
      this._scrollable.setScrollPositionSmooth(update);
    }
    hasPendingScrollAnimation() {
      return this._scrollable.hasPendingScrollAnimation();
    }
  }
  class ViewLayout extends Disposable {
    constructor(configuration, lineCount, customLineHeightData, scheduleAtNextAnimationFrame2) {
      super();
      this._configuration = configuration;
      const options = this._configuration.options;
      const layoutInfo = options.get(
        165
        /* EditorOption.layoutInfo */
      );
      const padding = options.get(
        96
        /* EditorOption.padding */
      );
      this._linesLayout = new LinesLayout$1(lineCount, options.get(
        75
        /* EditorOption.lineHeight */
      ), padding.top, padding.bottom, customLineHeightData);
      this._maxLineWidth = 0;
      this._overlayWidgetsMinWidth = 0;
      this._scrollable = this._register(new EditorScrollable(0, scheduleAtNextAnimationFrame2));
      this._configureSmoothScrollDuration();
      this._scrollable.setScrollDimensions(new EditorScrollDimensions(layoutInfo.contentWidth, 0, layoutInfo.height, 0));
      this.onDidScroll = this._scrollable.onDidScroll;
      this.onDidContentSizeChange = this._scrollable.onDidContentSizeChange;
      this._updateHeight();
    }
    dispose() {
      super.dispose();
    }
    getScrollable() {
      return this._scrollable.getScrollable();
    }
    onHeightMaybeChanged() {
      this._updateHeight();
    }
    _configureSmoothScrollDuration() {
      this._scrollable.setSmoothScrollDuration(this._configuration.options.get(
        130
        /* EditorOption.smoothScrolling */
      ) ? SMOOTH_SCROLLING_TIME : 0);
    }
    // ---- begin view event handlers
    onConfigurationChanged(e) {
      const options = this._configuration.options;
      if (e.hasChanged(
        75
        /* EditorOption.lineHeight */
      )) {
        this._linesLayout.setDefaultLineHeight(options.get(
          75
          /* EditorOption.lineHeight */
        ));
      }
      if (e.hasChanged(
        96
        /* EditorOption.padding */
      )) {
        const padding = options.get(
          96
          /* EditorOption.padding */
        );
        this._linesLayout.setPadding(padding.top, padding.bottom);
      }
      if (e.hasChanged(
        165
        /* EditorOption.layoutInfo */
      )) {
        const layoutInfo = options.get(
          165
          /* EditorOption.layoutInfo */
        );
        const width2 = layoutInfo.contentWidth;
        const height = layoutInfo.height;
        const scrollDimensions = this._scrollable.getScrollDimensions();
        const contentWidth = scrollDimensions.contentWidth;
        this._scrollable.setScrollDimensions(new EditorScrollDimensions(width2, scrollDimensions.contentWidth, height, this._getContentHeight(width2, height, contentWidth)));
      } else {
        this._updateHeight();
      }
      if (e.hasChanged(
        130
        /* EditorOption.smoothScrolling */
      )) {
        this._configureSmoothScrollDuration();
      }
    }
    onFlushed(lineCount, customLineHeightData) {
      this._linesLayout.onFlushed(lineCount, customLineHeightData);
    }
    onLinesDeleted(fromLineNumber, toLineNumber) {
      this._linesLayout.onLinesDeleted(fromLineNumber, toLineNumber);
    }
    onLinesInserted(fromLineNumber, toLineNumber) {
      this._linesLayout.onLinesInserted(fromLineNumber, toLineNumber);
    }
    // ---- end view event handlers
    _getHorizontalScrollbarHeight(width2, scrollWidth) {
      const options = this._configuration.options;
      const scrollbar = options.get(
        117
        /* EditorOption.scrollbar */
      );
      if (scrollbar.horizontal === 2) {
        return 0;
      }
      if (width2 >= scrollWidth) {
        return 0;
      }
      return scrollbar.horizontalScrollbarSize;
    }
    _getContentHeight(width2, height, contentWidth) {
      const options = this._configuration.options;
      let result = this._linesLayout.getLinesTotalHeight();
      if (options.get(
        119
        /* EditorOption.scrollBeyondLastLine */
      )) {
        result += Math.max(0, height - options.get(
          75
          /* EditorOption.lineHeight */
        ) - options.get(
          96
          /* EditorOption.padding */
        ).bottom);
      } else if (!options.get(
        117
        /* EditorOption.scrollbar */
      ).ignoreHorizontalScrollbarInContentHeight) {
        result += this._getHorizontalScrollbarHeight(width2, contentWidth);
      }
      return result;
    }
    _updateHeight() {
      const scrollDimensions = this._scrollable.getScrollDimensions();
      const width2 = scrollDimensions.width;
      const height = scrollDimensions.height;
      const contentWidth = scrollDimensions.contentWidth;
      this._scrollable.setScrollDimensions(new EditorScrollDimensions(width2, scrollDimensions.contentWidth, height, this._getContentHeight(width2, height, contentWidth)));
    }
    // ---- Layouting logic
    getCurrentViewport() {
      const scrollDimensions = this._scrollable.getScrollDimensions();
      const currentScrollPosition = this._scrollable.getCurrentScrollPosition();
      return new Viewport(currentScrollPosition.scrollTop, currentScrollPosition.scrollLeft, scrollDimensions.width, scrollDimensions.height);
    }
    getFutureViewport() {
      const scrollDimensions = this._scrollable.getScrollDimensions();
      const currentScrollPosition = this._scrollable.getFutureScrollPosition();
      return new Viewport(currentScrollPosition.scrollTop, currentScrollPosition.scrollLeft, scrollDimensions.width, scrollDimensions.height);
    }
    _computeContentWidth() {
      const options = this._configuration.options;
      const maxLineWidth = this._maxLineWidth;
      const wrappingInfo = options.get(
        166
        /* EditorOption.wrappingInfo */
      );
      const fontInfo = options.get(
        59
        /* EditorOption.fontInfo */
      );
      const layoutInfo = options.get(
        165
        /* EditorOption.layoutInfo */
      );
      if (wrappingInfo.isViewportWrapping) {
        const minimap = options.get(
          81
          /* EditorOption.minimap */
        );
        if (maxLineWidth > layoutInfo.contentWidth + fontInfo.typicalHalfwidthCharacterWidth) {
          if (minimap.enabled && minimap.side === "right") {
            return maxLineWidth + layoutInfo.verticalScrollbarWidth;
          }
        }
        return maxLineWidth;
      } else {
        const extraHorizontalSpace = options.get(
          118
          /* EditorOption.scrollBeyondLastColumn */
        ) * fontInfo.typicalHalfwidthCharacterWidth;
        const whitespaceMinWidth = this._linesLayout.getWhitespaceMinWidth();
        return Math.max(maxLineWidth + extraHorizontalSpace + layoutInfo.verticalScrollbarWidth, whitespaceMinWidth, this._overlayWidgetsMinWidth);
      }
    }
    setMaxLineWidth(maxLineWidth) {
      this._maxLineWidth = maxLineWidth;
      this._updateContentWidth();
    }
    setOverlayWidgetsMinWidth(maxMinWidth) {
      this._overlayWidgetsMinWidth = maxMinWidth;
      this._updateContentWidth();
    }
    _updateContentWidth() {
      const scrollDimensions = this._scrollable.getScrollDimensions();
      this._scrollable.setScrollDimensions(new EditorScrollDimensions(scrollDimensions.width, this._computeContentWidth(), scrollDimensions.height, scrollDimensions.contentHeight));
      this._updateHeight();
    }
    // ---- view state
    saveState() {
      const currentScrollPosition = this._scrollable.getFutureScrollPosition();
      const scrollTop = currentScrollPosition.scrollTop;
      const firstLineNumberInViewport = this._linesLayout.getLineNumberAtOrAfterVerticalOffset(scrollTop);
      const whitespaceAboveFirstLine = this._linesLayout.getWhitespaceAccumulatedHeightBeforeLineNumber(firstLineNumberInViewport);
      return {
        scrollTop,
        scrollTopWithoutViewZones: scrollTop - whitespaceAboveFirstLine,
        scrollLeft: currentScrollPosition.scrollLeft
      };
    }
    // ----
    changeWhitespace(callback) {
      const hadAChange = this._linesLayout.changeWhitespace(callback);
      if (hadAChange) {
        this.onHeightMaybeChanged();
      }
      return hadAChange;
    }
    changeSpecialLineHeights(callback) {
      const hadAChange = this._linesLayout.changeLineHeights(callback);
      if (hadAChange) {
        this.onHeightMaybeChanged();
      }
      return hadAChange;
    }
    getVerticalOffsetForLineNumber(lineNumber, includeViewZones = false) {
      return this._linesLayout.getVerticalOffsetForLineNumber(lineNumber, includeViewZones);
    }
    getVerticalOffsetAfterLineNumber(lineNumber, includeViewZones = false) {
      return this._linesLayout.getVerticalOffsetAfterLineNumber(lineNumber, includeViewZones);
    }
    getLineHeightForLineNumber(lineNumber) {
      return this._linesLayout.getLineHeightForLineNumber(lineNumber);
    }
    isAfterLines(verticalOffset) {
      return this._linesLayout.isAfterLines(verticalOffset);
    }
    isInTopPadding(verticalOffset) {
      return this._linesLayout.isInTopPadding(verticalOffset);
    }
    isInBottomPadding(verticalOffset) {
      return this._linesLayout.isInBottomPadding(verticalOffset);
    }
    getLineNumberAtVerticalOffset(verticalOffset) {
      return this._linesLayout.getLineNumberAtOrAfterVerticalOffset(verticalOffset);
    }
    getWhitespaceAtVerticalOffset(verticalOffset) {
      return this._linesLayout.getWhitespaceAtVerticalOffset(verticalOffset);
    }
    getLinesViewportData() {
      const visibleBox = this.getCurrentViewport();
      return this._linesLayout.getLinesViewportData(visibleBox.top, visibleBox.top + visibleBox.height);
    }
    getLinesViewportDataAtScrollTop(scrollTop) {
      const scrollDimensions = this._scrollable.getScrollDimensions();
      if (scrollTop + scrollDimensions.height > scrollDimensions.scrollHeight) {
        scrollTop = scrollDimensions.scrollHeight - scrollDimensions.height;
      }
      if (scrollTop < 0) {
        scrollTop = 0;
      }
      return this._linesLayout.getLinesViewportData(scrollTop, scrollTop + scrollDimensions.height);
    }
    getWhitespaceViewportData() {
      const visibleBox = this.getCurrentViewport();
      return this._linesLayout.getWhitespaceViewportData(visibleBox.top, visibleBox.top + visibleBox.height);
    }
    getWhitespaces() {
      return this._linesLayout.getWhitespaces();
    }
    // ----
    getContentWidth() {
      const scrollDimensions = this._scrollable.getScrollDimensions();
      return scrollDimensions.contentWidth;
    }
    getScrollWidth() {
      const scrollDimensions = this._scrollable.getScrollDimensions();
      return scrollDimensions.scrollWidth;
    }
    getContentHeight() {
      const scrollDimensions = this._scrollable.getScrollDimensions();
      return scrollDimensions.contentHeight;
    }
    getScrollHeight() {
      const scrollDimensions = this._scrollable.getScrollDimensions();
      return scrollDimensions.scrollHeight;
    }
    getCurrentScrollLeft() {
      const currentScrollPosition = this._scrollable.getCurrentScrollPosition();
      return currentScrollPosition.scrollLeft;
    }
    getCurrentScrollTop() {
      const currentScrollPosition = this._scrollable.getCurrentScrollPosition();
      return currentScrollPosition.scrollTop;
    }
    validateScrollPosition(scrollPosition) {
      return this._scrollable.validateScrollPosition(scrollPosition);
    }
    setScrollPosition(position, type) {
      if (type === 1) {
        this._scrollable.setScrollPositionNow(position);
      } else {
        this._scrollable.setScrollPositionSmooth(position);
      }
    }
    hasPendingScrollAnimation() {
      return this._scrollable.hasPendingScrollAnimation();
    }
    deltaScrollNow(deltaScrollLeft, deltaScrollTop) {
      const currentScrollPosition = this._scrollable.getCurrentScrollPosition();
      this._scrollable.setScrollPositionNow({
        scrollLeft: currentScrollPosition.scrollLeft + deltaScrollLeft,
        scrollTop: currentScrollPosition.scrollTop + deltaScrollTop
      });
    }
  }
  class InlineDecoration {
    constructor(range2, inlineClassName, type) {
      this.range = range2;
      this.inlineClassName = inlineClassName;
      this.type = type;
    }
  }
  class SingleLineInlineDecoration {
    constructor(startOffset, endOffset, inlineClassName, inlineClassNameAffectsLetterSpacing) {
      this.startOffset = startOffset;
      this.endOffset = endOffset;
      this.inlineClassName = inlineClassName;
      this.inlineClassNameAffectsLetterSpacing = inlineClassNameAffectsLetterSpacing;
    }
    toInlineDecoration(lineNumber) {
      return new InlineDecoration(
        new Range$2(lineNumber, this.startOffset + 1, lineNumber, this.endOffset + 1),
        this.inlineClassName,
        this.inlineClassNameAffectsLetterSpacing ? 3 : 0
        /* InlineDecorationType.Regular */
      );
    }
  }
  class ViewModelDecorations {
    constructor(editorId, model, configuration, linesCollection, coordinatesConverter) {
      this.editorId = editorId;
      this.model = model;
      this.configuration = configuration;
      this._linesCollection = linesCollection;
      this._coordinatesConverter = coordinatesConverter;
      this._decorationsCache = /* @__PURE__ */ Object.create(null);
      this._cachedModelDecorationsResolver = null;
      this._cachedModelDecorationsResolverViewRange = null;
    }
    _clearCachedModelDecorationsResolver() {
      this._cachedModelDecorationsResolver = null;
      this._cachedModelDecorationsResolverViewRange = null;
    }
    dispose() {
      this._decorationsCache = /* @__PURE__ */ Object.create(null);
      this._clearCachedModelDecorationsResolver();
    }
    reset() {
      this._decorationsCache = /* @__PURE__ */ Object.create(null);
      this._clearCachedModelDecorationsResolver();
    }
    onModelDecorationsChanged() {
      this._decorationsCache = /* @__PURE__ */ Object.create(null);
      this._clearCachedModelDecorationsResolver();
    }
    onLineMappingChanged() {
      this._decorationsCache = /* @__PURE__ */ Object.create(null);
      this._clearCachedModelDecorationsResolver();
    }
    _getOrCreateViewModelDecoration(modelDecoration) {
      const id = modelDecoration.id;
      let r = this._decorationsCache[id];
      if (!r) {
        const modelRange = modelDecoration.range;
        const options = modelDecoration.options;
        let viewRange;
        if (options.isWholeLine) {
          const start = this._coordinatesConverter.convertModelPositionToViewPosition(new Position$1(modelRange.startLineNumber, 1), 0, false, true);
          const end = this._coordinatesConverter.convertModelPositionToViewPosition(
            new Position$1(modelRange.endLineNumber, this.model.getLineMaxColumn(modelRange.endLineNumber)),
            1
            /* PositionAffinity.Right */
          );
          viewRange = new Range$2(start.lineNumber, start.column, end.lineNumber, end.column);
        } else {
          viewRange = this._coordinatesConverter.convertModelRangeToViewRange(
            modelRange,
            1
            /* PositionAffinity.Right */
          );
        }
        r = new ViewModelDecoration(viewRange, options);
        this._decorationsCache[id] = r;
      }
      return r;
    }
    getMinimapDecorationsInRange(range2) {
      return this._getDecorationsInRange(range2, true, false).decorations;
    }
    getDecorationsViewportData(viewRange) {
      let cacheIsValid = this._cachedModelDecorationsResolver !== null;
      cacheIsValid = cacheIsValid && viewRange.equalsRange(this._cachedModelDecorationsResolverViewRange);
      if (!cacheIsValid) {
        this._cachedModelDecorationsResolver = this._getDecorationsInRange(viewRange, false, false);
        this._cachedModelDecorationsResolverViewRange = viewRange;
      }
      return this._cachedModelDecorationsResolver;
    }
    getDecorationsOnLine(lineNumber, onlyMinimapDecorations = false, onlyMarginDecorations = false) {
      const range2 = new Range$2(lineNumber, this._linesCollection.getViewLineMinColumn(lineNumber), lineNumber, this._linesCollection.getViewLineMaxColumn(lineNumber));
      return this._getDecorationsInRange(range2, onlyMinimapDecorations, onlyMarginDecorations);
    }
    _getDecorationsInRange(viewRange, onlyMinimapDecorations, onlyMarginDecorations) {
      const modelDecorations = this._linesCollection.getDecorationsInRange(viewRange, this.editorId, filterValidationDecorations(this.configuration.options), filterFontDecorations(this.configuration.options), onlyMinimapDecorations, onlyMarginDecorations);
      const startLineNumber = viewRange.startLineNumber;
      const endLineNumber = viewRange.endLineNumber;
      const decorationsInViewport = [];
      let decorationsInViewportLen = 0;
      const inlineDecorations = [];
      for (let j = startLineNumber; j <= endLineNumber; j++) {
        inlineDecorations[j - startLineNumber] = [];
      }
      let hasVariableFonts = false;
      for (let i2 = 0, len = modelDecorations.length; i2 < len; i2++) {
        const modelDecoration = modelDecorations[i2];
        const decorationOptions = modelDecoration.options;
        if (!isModelDecorationVisible(this.model, modelDecoration)) {
          continue;
        }
        const viewModelDecoration = this._getOrCreateViewModelDecoration(modelDecoration);
        const viewRange2 = viewModelDecoration.range;
        decorationsInViewport[decorationsInViewportLen++] = viewModelDecoration;
        if (decorationOptions.inlineClassName) {
          const inlineDecoration = new InlineDecoration(
            viewRange2,
            decorationOptions.inlineClassName,
            decorationOptions.inlineClassNameAffectsLetterSpacing ? 3 : 0
            /* InlineDecorationType.Regular */
          );
          const intersectedStartLineNumber = Math.max(startLineNumber, viewRange2.startLineNumber);
          const intersectedEndLineNumber = Math.min(endLineNumber, viewRange2.endLineNumber);
          for (let j = intersectedStartLineNumber; j <= intersectedEndLineNumber; j++) {
            inlineDecorations[j - startLineNumber].push(inlineDecoration);
          }
        }
        if (decorationOptions.beforeContentClassName) {
          if (startLineNumber <= viewRange2.startLineNumber && viewRange2.startLineNumber <= endLineNumber) {
            const inlineDecoration = new InlineDecoration(
              new Range$2(viewRange2.startLineNumber, viewRange2.startColumn, viewRange2.startLineNumber, viewRange2.startColumn),
              decorationOptions.beforeContentClassName,
              1
              /* InlineDecorationType.Before */
            );
            inlineDecorations[viewRange2.startLineNumber - startLineNumber].push(inlineDecoration);
          }
        }
        if (decorationOptions.afterContentClassName) {
          if (startLineNumber <= viewRange2.endLineNumber && viewRange2.endLineNumber <= endLineNumber) {
            const inlineDecoration = new InlineDecoration(
              new Range$2(viewRange2.endLineNumber, viewRange2.endColumn, viewRange2.endLineNumber, viewRange2.endColumn),
              decorationOptions.afterContentClassName,
              2
              /* InlineDecorationType.After */
            );
            inlineDecorations[viewRange2.endLineNumber - startLineNumber].push(inlineDecoration);
          }
        }
        if (decorationOptions.affectsFont) {
          hasVariableFonts = true;
        }
      }
      return {
        decorations: decorationsInViewport,
        inlineDecorations,
        hasVariableFonts
      };
    }
  }
  function createModelLineProjection(lineBreakData, isVisible) {
    if (lineBreakData === null) {
      if (isVisible) {
        return IdentityModelLineProjection.INSTANCE;
      }
      return HiddenModelLineProjection.INSTANCE;
    } else {
      return new ModelLineProjection(lineBreakData, isVisible);
    }
  }
  class ModelLineProjection {
    constructor(lineBreakData, isVisible) {
      this._projectionData = lineBreakData;
      this._isVisible = isVisible;
    }
    isVisible() {
      return this._isVisible;
    }
    setVisible(isVisible) {
      this._isVisible = isVisible;
      return this;
    }
    getProjectionData() {
      return this._projectionData;
    }
    getViewLineCount() {
      if (!this._isVisible) {
        return 0;
      }
      return this._projectionData.getOutputLineCount();
    }
    getViewLineContent(model, modelLineNumber, outputLineIndex) {
      this._assertVisible();
      const startOffsetInInputWithInjections = outputLineIndex > 0 ? this._projectionData.breakOffsets[outputLineIndex - 1] : 0;
      const endOffsetInInputWithInjections = this._projectionData.breakOffsets[outputLineIndex];
      let r;
      if (this._projectionData.injectionOffsets !== null) {
        const injectedTexts = this._projectionData.injectionOffsets.map((offset, idx) => new LineInjectedText(0, 0, offset + 1, this._projectionData.injectionOptions[idx], 0));
        const lineWithInjections = LineInjectedText.applyInjectedText(model.getLineContent(modelLineNumber), injectedTexts);
        r = lineWithInjections.substring(startOffsetInInputWithInjections, endOffsetInInputWithInjections);
      } else {
        r = model.getValueInRange({
          startLineNumber: modelLineNumber,
          startColumn: startOffsetInInputWithInjections + 1,
          endLineNumber: modelLineNumber,
          endColumn: endOffsetInInputWithInjections + 1
        });
      }
      if (outputLineIndex > 0) {
        r = spaces(this._projectionData.wrappedTextIndentLength) + r;
      }
      return r;
    }
    getViewLineLength(model, modelLineNumber, outputLineIndex) {
      this._assertVisible();
      return this._projectionData.getLineLength(outputLineIndex);
    }
    getViewLineMinColumn(_model, _modelLineNumber, outputLineIndex) {
      this._assertVisible();
      return this._projectionData.getMinOutputOffset(outputLineIndex) + 1;
    }
    getViewLineMaxColumn(model, modelLineNumber, outputLineIndex) {
      this._assertVisible();
      return this._projectionData.getMaxOutputOffset(outputLineIndex) + 1;
    }
    /**
     * Try using {@link getViewLinesData} instead.
    */
    getViewLineData(model, modelLineNumber, outputLineIndex) {
      const arr = new Array();
      this.getViewLinesData(model, modelLineNumber, outputLineIndex, 1, 0, [true], arr);
      return arr[0];
    }
    getViewLinesData(model, modelLineNumber, outputLineIdx, lineCount, globalStartIndex, needed, result) {
      this._assertVisible();
      const lineBreakData = this._projectionData;
      const injectionOffsets = lineBreakData.injectionOffsets;
      const injectionOptions = lineBreakData.injectionOptions;
      let inlineDecorationsPerOutputLine = null;
      if (injectionOffsets) {
        inlineDecorationsPerOutputLine = [];
        let totalInjectedTextLengthBefore = 0;
        let currentInjectedOffset = 0;
        for (let outputLineIndex = 0; outputLineIndex < lineBreakData.getOutputLineCount(); outputLineIndex++) {
          const inlineDecorations = new Array();
          inlineDecorationsPerOutputLine[outputLineIndex] = inlineDecorations;
          const lineStartOffsetInInputWithInjections = outputLineIndex > 0 ? lineBreakData.breakOffsets[outputLineIndex - 1] : 0;
          const lineEndOffsetInInputWithInjections = lineBreakData.breakOffsets[outputLineIndex];
          while (currentInjectedOffset < injectionOffsets.length) {
            const length = injectionOptions[currentInjectedOffset].content.length;
            const injectedTextStartOffsetInInputWithInjections = injectionOffsets[currentInjectedOffset] + totalInjectedTextLengthBefore;
            const injectedTextEndOffsetInInputWithInjections = injectedTextStartOffsetInInputWithInjections + length;
            if (injectedTextStartOffsetInInputWithInjections > lineEndOffsetInInputWithInjections) {
              break;
            }
            if (lineStartOffsetInInputWithInjections < injectedTextEndOffsetInInputWithInjections) {
              const options = injectionOptions[currentInjectedOffset];
              if (options.inlineClassName) {
                const offset = outputLineIndex > 0 ? lineBreakData.wrappedTextIndentLength : 0;
                const start = offset + Math.max(injectedTextStartOffsetInInputWithInjections - lineStartOffsetInInputWithInjections, 0);
                const end = offset + Math.min(injectedTextEndOffsetInInputWithInjections - lineStartOffsetInInputWithInjections, lineEndOffsetInInputWithInjections - lineStartOffsetInInputWithInjections);
                if (start !== end) {
                  inlineDecorations.push(new SingleLineInlineDecoration(start, end, options.inlineClassName, options.inlineClassNameAffectsLetterSpacing));
                }
              }
            }
            if (injectedTextEndOffsetInInputWithInjections <= lineEndOffsetInInputWithInjections) {
              totalInjectedTextLengthBefore += length;
              currentInjectedOffset++;
            } else {
              break;
            }
          }
        }
      }
      let lineWithInjections;
      if (injectionOffsets) {
        const tokensToInsert = [];
        for (let idx = 0; idx < injectionOffsets.length; idx++) {
          const offset = injectionOffsets[idx];
          const tokens = injectionOptions[idx].tokens;
          if (tokens) {
            tokens.forEach((range2, info) => {
              tokensToInsert.push({
                offset,
                text: range2.substring(injectionOptions[idx].content),
                tokenMetadata: info.metadata
              });
            });
          } else {
            tokensToInsert.push({
              offset,
              text: injectionOptions[idx].content,
              tokenMetadata: LineTokens.defaultTokenMetadata
            });
          }
        }
        lineWithInjections = model.tokenization.getLineTokens(modelLineNumber).withInserted(tokensToInsert);
      } else {
        lineWithInjections = model.tokenization.getLineTokens(modelLineNumber);
      }
      for (let outputLineIndex = outputLineIdx; outputLineIndex < outputLineIdx + lineCount; outputLineIndex++) {
        const globalIndex = globalStartIndex + outputLineIndex - outputLineIdx;
        if (!needed[globalIndex]) {
          result[globalIndex] = null;
          continue;
        }
        result[globalIndex] = this._getViewLineData(lineWithInjections, inlineDecorationsPerOutputLine ? inlineDecorationsPerOutputLine[outputLineIndex] : null, outputLineIndex);
      }
    }
    _getViewLineData(lineWithInjections, inlineDecorations, outputLineIndex) {
      this._assertVisible();
      const lineBreakData = this._projectionData;
      const deltaStartIndex = outputLineIndex > 0 ? lineBreakData.wrappedTextIndentLength : 0;
      const lineStartOffsetInInputWithInjections = outputLineIndex > 0 ? lineBreakData.breakOffsets[outputLineIndex - 1] : 0;
      const lineEndOffsetInInputWithInjections = lineBreakData.breakOffsets[outputLineIndex];
      const tokens = lineWithInjections.sliceAndInflate(lineStartOffsetInInputWithInjections, lineEndOffsetInInputWithInjections, deltaStartIndex);
      let lineContent = tokens.getLineContent();
      if (outputLineIndex > 0) {
        lineContent = spaces(lineBreakData.wrappedTextIndentLength) + lineContent;
      }
      const minColumn = this._projectionData.getMinOutputOffset(outputLineIndex) + 1;
      const maxColumn = lineContent.length + 1;
      const continuesWithWrappedLine = outputLineIndex + 1 < this.getViewLineCount();
      const startVisibleColumn = outputLineIndex === 0 ? 0 : lineBreakData.breakOffsetsVisibleColumn[outputLineIndex - 1];
      return new ViewLineData(lineContent, continuesWithWrappedLine, minColumn, maxColumn, startVisibleColumn, tokens, inlineDecorations);
    }
    getModelColumnOfViewPosition(outputLineIndex, outputColumn) {
      this._assertVisible();
      return this._projectionData.translateToInputOffset(outputLineIndex, outputColumn - 1) + 1;
    }
    getViewPositionOfModelPosition(deltaLineNumber, inputColumn, affinity = 2) {
      this._assertVisible();
      const r = this._projectionData.translateToOutputPosition(inputColumn - 1, affinity);
      return r.toPosition(deltaLineNumber);
    }
    getViewLineNumberOfModelPosition(deltaLineNumber, inputColumn) {
      this._assertVisible();
      const r = this._projectionData.translateToOutputPosition(inputColumn - 1);
      return deltaLineNumber + r.outputLineIndex;
    }
    normalizePosition(outputLineIndex, outputPosition, affinity) {
      const baseViewLineNumber = outputPosition.lineNumber - outputLineIndex;
      const normalizedOutputPosition = this._projectionData.normalizeOutputPosition(outputLineIndex, outputPosition.column - 1, affinity);
      const result = normalizedOutputPosition.toPosition(baseViewLineNumber);
      return result;
    }
    getInjectedTextAt(outputLineIndex, outputColumn) {
      return this._projectionData.getInjectedText(outputLineIndex, outputColumn - 1);
    }
    _assertVisible() {
      if (!this._isVisible) {
        throw new Error("Not supported");
      }
    }
  }
  const _IdentityModelLineProjection = class _IdentityModelLineProjection {
    constructor() {
    }
    isVisible() {
      return true;
    }
    setVisible(isVisible) {
      if (isVisible) {
        return this;
      }
      return HiddenModelLineProjection.INSTANCE;
    }
    getProjectionData() {
      return null;
    }
    getViewLineCount() {
      return 1;
    }
    getViewLineContent(model, modelLineNumber, _outputLineIndex) {
      return model.getLineContent(modelLineNumber);
    }
    getViewLineLength(model, modelLineNumber, _outputLineIndex) {
      return model.getLineLength(modelLineNumber);
    }
    getViewLineMinColumn(model, modelLineNumber, _outputLineIndex) {
      return model.getLineMinColumn(modelLineNumber);
    }
    getViewLineMaxColumn(model, modelLineNumber, _outputLineIndex) {
      return model.getLineMaxColumn(modelLineNumber);
    }
    getViewLineData(model, modelLineNumber, _outputLineIndex) {
      const lineTokens = model.tokenization.getLineTokens(modelLineNumber);
      const lineContent = lineTokens.getLineContent();
      return new ViewLineData(lineContent, false, 1, lineContent.length + 1, 0, lineTokens.inflate(), null);
    }
    getViewLinesData(model, modelLineNumber, _fromOuputLineIndex, _toOutputLineIndex, globalStartIndex, needed, result) {
      if (!needed[globalStartIndex]) {
        result[globalStartIndex] = null;
        return;
      }
      result[globalStartIndex] = this.getViewLineData(model, modelLineNumber, 0);
    }
    getModelColumnOfViewPosition(_outputLineIndex, outputColumn) {
      return outputColumn;
    }
    getViewPositionOfModelPosition(deltaLineNumber, inputColumn) {
      return new Position$1(deltaLineNumber, inputColumn);
    }
    getViewLineNumberOfModelPosition(deltaLineNumber, _inputColumn) {
      return deltaLineNumber;
    }
    normalizePosition(outputLineIndex, outputPosition, affinity) {
      return outputPosition;
    }
    getInjectedTextAt(_outputLineIndex, _outputColumn) {
      return null;
    }
  };
  _IdentityModelLineProjection.INSTANCE = new _IdentityModelLineProjection();
  let IdentityModelLineProjection = _IdentityModelLineProjection;
  const _HiddenModelLineProjection = class _HiddenModelLineProjection {
    constructor() {
    }
    isVisible() {
      return false;
    }
    setVisible(isVisible) {
      if (!isVisible) {
        return this;
      }
      return IdentityModelLineProjection.INSTANCE;
    }
    getProjectionData() {
      return null;
    }
    getViewLineCount() {
      return 0;
    }
    getViewLineContent(_model, _modelLineNumber, _outputLineIndex) {
      throw new Error("Not supported");
    }
    getViewLineLength(_model, _modelLineNumber, _outputLineIndex) {
      throw new Error("Not supported");
    }
    getViewLineMinColumn(_model, _modelLineNumber, _outputLineIndex) {
      throw new Error("Not supported");
    }
    getViewLineMaxColumn(_model, _modelLineNumber, _outputLineIndex) {
      throw new Error("Not supported");
    }
    getViewLineData(_model, _modelLineNumber, _outputLineIndex) {
      throw new Error("Not supported");
    }
    getViewLinesData(_model, _modelLineNumber, _fromOuputLineIndex, _toOutputLineIndex, _globalStartIndex, _needed, _result) {
      throw new Error("Not supported");
    }
    getModelColumnOfViewPosition(_outputLineIndex, _outputColumn) {
      throw new Error("Not supported");
    }
    getViewPositionOfModelPosition(_deltaLineNumber, _inputColumn) {
      throw new Error("Not supported");
    }
    getViewLineNumberOfModelPosition(_deltaLineNumber, _inputColumn) {
      throw new Error("Not supported");
    }
    normalizePosition(outputLineIndex, outputPosition, affinity) {
      throw new Error("Not supported");
    }
    getInjectedTextAt(_outputLineIndex, _outputColumn) {
      throw new Error("Not supported");
    }
  };
  _HiddenModelLineProjection.INSTANCE = new _HiddenModelLineProjection();
  let HiddenModelLineProjection = _HiddenModelLineProjection;
  const _spaces = [""];
  function spaces(count) {
    if (count >= _spaces.length) {
      for (let i2 = 1; i2 <= count; i2++) {
        _spaces[i2] = _makeSpaces(i2);
      }
    }
    return _spaces[count];
  }
  function _makeSpaces(count) {
    return new Array(count + 1).join(" ");
  }
  class PrefixSumComputer {
    constructor(values) {
      this.values = values;
      this.prefixSum = new Uint32Array(values.length);
      this.prefixSumValidIndex = new Int32Array(1);
      this.prefixSumValidIndex[0] = -1;
    }
    insertValues(insertIndex, insertValues) {
      insertIndex = toUint32(insertIndex);
      const oldValues = this.values;
      const oldPrefixSum = this.prefixSum;
      const insertValuesLen = insertValues.length;
      if (insertValuesLen === 0) {
        return false;
      }
      this.values = new Uint32Array(oldValues.length + insertValuesLen);
      this.values.set(oldValues.subarray(0, insertIndex), 0);
      this.values.set(oldValues.subarray(insertIndex), insertIndex + insertValuesLen);
      this.values.set(insertValues, insertIndex);
      if (insertIndex - 1 < this.prefixSumValidIndex[0]) {
        this.prefixSumValidIndex[0] = insertIndex - 1;
      }
      this.prefixSum = new Uint32Array(this.values.length);
      if (this.prefixSumValidIndex[0] >= 0) {
        this.prefixSum.set(oldPrefixSum.subarray(0, this.prefixSumValidIndex[0] + 1));
      }
      return true;
    }
    setValue(index, value) {
      index = toUint32(index);
      value = toUint32(value);
      if (this.values[index] === value) {
        return false;
      }
      this.values[index] = value;
      if (index - 1 < this.prefixSumValidIndex[0]) {
        this.prefixSumValidIndex[0] = index - 1;
      }
      return true;
    }
    removeValues(startIndex, count) {
      startIndex = toUint32(startIndex);
      count = toUint32(count);
      const oldValues = this.values;
      const oldPrefixSum = this.prefixSum;
      if (startIndex >= oldValues.length) {
        return false;
      }
      const maxCount = oldValues.length - startIndex;
      if (count >= maxCount) {
        count = maxCount;
      }
      if (count === 0) {
        return false;
      }
      this.values = new Uint32Array(oldValues.length - count);
      this.values.set(oldValues.subarray(0, startIndex), 0);
      this.values.set(oldValues.subarray(startIndex + count), startIndex);
      this.prefixSum = new Uint32Array(this.values.length);
      if (startIndex - 1 < this.prefixSumValidIndex[0]) {
        this.prefixSumValidIndex[0] = startIndex - 1;
      }
      if (this.prefixSumValidIndex[0] >= 0) {
        this.prefixSum.set(oldPrefixSum.subarray(0, this.prefixSumValidIndex[0] + 1));
      }
      return true;
    }
    getTotalSum() {
      if (this.values.length === 0) {
        return 0;
      }
      return this._getPrefixSum(this.values.length - 1);
    }
    /**
     * Returns the sum of the first `index + 1` many items.
     * @returns `SUM(0 <= j <= index, values[j])`.
     */
    getPrefixSum(index) {
      if (index < 0) {
        return 0;
      }
      index = toUint32(index);
      return this._getPrefixSum(index);
    }
    _getPrefixSum(index) {
      if (index <= this.prefixSumValidIndex[0]) {
        return this.prefixSum[index];
      }
      let startIndex = this.prefixSumValidIndex[0] + 1;
      if (startIndex === 0) {
        this.prefixSum[0] = this.values[0];
        startIndex++;
      }
      if (index >= this.values.length) {
        index = this.values.length - 1;
      }
      for (let i2 = startIndex; i2 <= index; i2++) {
        this.prefixSum[i2] = this.prefixSum[i2 - 1] + this.values[i2];
      }
      this.prefixSumValidIndex[0] = Math.max(this.prefixSumValidIndex[0], index);
      return this.prefixSum[index];
    }
    getIndexOf(sum2) {
      sum2 = Math.floor(sum2);
      this.getTotalSum();
      let low = 0;
      let high = this.values.length - 1;
      let mid = 0;
      let midStop = 0;
      let midStart = 0;
      while (low <= high) {
        mid = low + (high - low) / 2 | 0;
        midStop = this.prefixSum[mid];
        midStart = midStop - this.values[mid];
        if (sum2 < midStart) {
          high = mid - 1;
        } else if (sum2 >= midStop) {
          low = mid + 1;
        } else {
          break;
        }
      }
      return new PrefixSumIndexOfResult(mid, sum2 - midStart);
    }
  }
  class ConstantTimePrefixSumComputer {
    constructor(values) {
      this._values = values;
      this._isValid = false;
      this._validEndIndex = -1;
      this._prefixSum = [];
      this._indexBySum = [];
    }
    /**
     * @returns SUM(0 <= j < values.length, values[j])
     */
    getTotalSum() {
      this._ensureValid();
      return this._indexBySum.length;
    }
    /**
     * Returns the sum of the first `count` many items.
     * @returns `SUM(0 <= j < count, values[j])`.
     */
    getPrefixSum(count) {
      this._ensureValid();
      if (count === 0) {
        return 0;
      }
      return this._prefixSum[count - 1];
    }
    /**
     * @returns `result`, such that `getPrefixSum(result.index) + result.remainder = sum`
     */
    getIndexOf(sum2) {
      this._ensureValid();
      const idx = this._indexBySum[sum2];
      const viewLinesAbove = idx > 0 ? this._prefixSum[idx - 1] : 0;
      return new PrefixSumIndexOfResult(idx, sum2 - viewLinesAbove);
    }
    removeValues(start, deleteCount) {
      this._values.splice(start, deleteCount);
      this._invalidate(start);
    }
    insertValues(insertIndex, insertArr) {
      this._values = arrayInsert(this._values, insertIndex, insertArr);
      this._invalidate(insertIndex);
    }
    _invalidate(index) {
      this._isValid = false;
      this._validEndIndex = Math.min(this._validEndIndex, index - 1);
    }
    _ensureValid() {
      if (this._isValid) {
        return;
      }
      for (let i2 = this._validEndIndex + 1, len = this._values.length; i2 < len; i2++) {
        const value = this._values[i2];
        const sumAbove = i2 > 0 ? this._prefixSum[i2 - 1] : 0;
        this._prefixSum[i2] = sumAbove + value;
        for (let j = 0; j < value; j++) {
          this._indexBySum[sumAbove + j] = i2;
        }
      }
      this._prefixSum.length = this._values.length;
      this._indexBySum.length = this._prefixSum[this._prefixSum.length - 1];
      this._isValid = true;
      this._validEndIndex = this._values.length - 1;
    }
    setValue(index, value) {
      if (this._values[index] === value) {
        return;
      }
      this._values[index] = value;
      this._invalidate(index);
    }
  }
  class PrefixSumIndexOfResult {
    constructor(index, remainder) {
      this.index = index;
      this.remainder = remainder;
      this._prefixSumIndexOfResultBrand = void 0;
      this.index = index;
      this.remainder = remainder;
    }
  }
  class IdentityCoordinatesConverter {
    constructor(model) {
      this._model = model;
    }
    _validPosition(pos) {
      return this._model.validatePosition(pos);
    }
    _validRange(range2) {
      return this._model.validateRange(range2);
    }
    // View -> Model conversion and related methods
    convertViewPositionToModelPosition(viewPosition) {
      return this._validPosition(viewPosition);
    }
    convertViewRangeToModelRange(viewRange) {
      return this._validRange(viewRange);
    }
    validateViewPosition(_viewPosition, expectedModelPosition) {
      return this._validPosition(expectedModelPosition);
    }
    validateViewRange(_viewRange, expectedModelRange) {
      return this._validRange(expectedModelRange);
    }
    // Model -> View conversion and related methods
    convertModelPositionToViewPosition(modelPosition) {
      return this._validPosition(modelPosition);
    }
    convertModelRangeToViewRange(modelRange) {
      return this._validRange(modelRange);
    }
    modelPositionIsVisible(modelPosition) {
      const lineCount = this._model.getLineCount();
      if (modelPosition.lineNumber < 1 || modelPosition.lineNumber > lineCount) {
        return false;
      }
      return true;
    }
    getModelLineViewLineCount(modelLineNumber) {
      return 1;
    }
    getViewLineNumberOfModelPosition(modelLineNumber, modelColumn) {
      return modelLineNumber;
    }
  }
  class ViewModelLinesFromProjectedModel {
    constructor(editorId, model, domLineBreaksComputerFactory, monospaceLineBreaksComputerFactory, fontInfo, tabSize, wrappingStrategy, wrappingColumn, wrappingIndent, wordBreak, wrapOnEscapedLineFeeds) {
      this._editorId = editorId;
      this.model = model;
      this._validModelVersionId = -1;
      this._domLineBreaksComputerFactory = domLineBreaksComputerFactory;
      this._monospaceLineBreaksComputerFactory = monospaceLineBreaksComputerFactory;
      this.fontInfo = fontInfo;
      this.tabSize = tabSize;
      this.wrappingStrategy = wrappingStrategy;
      this.wrappingColumn = wrappingColumn;
      this.wrappingIndent = wrappingIndent;
      this.wordBreak = wordBreak;
      this.wrapOnEscapedLineFeeds = wrapOnEscapedLineFeeds;
      this._constructLines(
        /*resetHiddenAreas*/
        true,
        null
      );
    }
    dispose() {
      this.hiddenAreasDecorationIds = this.model.deltaDecorations(this.hiddenAreasDecorationIds, []);
    }
    createCoordinatesConverter() {
      return new CoordinatesConverter(this);
    }
    _constructLines(resetHiddenAreas, previousLineBreaks) {
      this.modelLineProjections = [];
      if (resetHiddenAreas) {
        this.hiddenAreasDecorationIds = this.model.deltaDecorations(this.hiddenAreasDecorationIds, []);
      }
      const linesContent = this.model.getLinesContent();
      const injectedTextDecorations = this.model.getInjectedTextDecorations(this._editorId);
      const lineCount = linesContent.length;
      const lineBreaksComputer = this.createLineBreaksComputer();
      const injectedTextQueue = new ArrayQueue(LineInjectedText.fromDecorations(injectedTextDecorations));
      for (let i2 = 0; i2 < lineCount; i2++) {
        const lineInjectedText = injectedTextQueue.takeWhile((t) => t.lineNumber === i2 + 1);
        lineBreaksComputer.addRequest(linesContent[i2], lineInjectedText, previousLineBreaks ? previousLineBreaks[i2] : null);
      }
      const linesBreaks = lineBreaksComputer.finalize();
      const values = [];
      const hiddenAreas = this.hiddenAreasDecorationIds.map((areaId) => this.model.getDecorationRange(areaId)).sort(Range$2.compareRangesUsingStarts);
      let hiddenAreaStart = 1, hiddenAreaEnd = 0;
      let hiddenAreaIdx = -1;
      let nextLineNumberToUpdateHiddenArea = hiddenAreaIdx + 1 < hiddenAreas.length ? hiddenAreaEnd + 1 : lineCount + 2;
      for (let i2 = 0; i2 < lineCount; i2++) {
        const lineNumber = i2 + 1;
        if (lineNumber === nextLineNumberToUpdateHiddenArea) {
          hiddenAreaIdx++;
          hiddenAreaStart = hiddenAreas[hiddenAreaIdx].startLineNumber;
          hiddenAreaEnd = hiddenAreas[hiddenAreaIdx].endLineNumber;
          nextLineNumberToUpdateHiddenArea = hiddenAreaIdx + 1 < hiddenAreas.length ? hiddenAreaEnd + 1 : lineCount + 2;
        }
        const isInHiddenArea = lineNumber >= hiddenAreaStart && lineNumber <= hiddenAreaEnd;
        const line = createModelLineProjection(linesBreaks[i2], !isInHiddenArea);
        values[i2] = line.getViewLineCount();
        this.modelLineProjections[i2] = line;
      }
      this._validModelVersionId = this.model.getVersionId();
      this.projectedModelLineLineCounts = new ConstantTimePrefixSumComputer(values);
    }
    getHiddenAreas() {
      return this.hiddenAreasDecorationIds.map((decId) => this.model.getDecorationRange(decId));
    }
    setHiddenAreas(_ranges) {
      const validatedRanges = _ranges.map((r) => this.model.validateRange(r));
      const newRanges = normalizeLineRanges(validatedRanges);
      const oldRanges = this.hiddenAreasDecorationIds.map((areaId) => this.model.getDecorationRange(areaId)).sort(Range$2.compareRangesUsingStarts);
      if (newRanges.length === oldRanges.length) {
        let hasDifference = false;
        for (let i2 = 0; i2 < newRanges.length; i2++) {
          if (!newRanges[i2].equalsRange(oldRanges[i2])) {
            hasDifference = true;
            break;
          }
        }
        if (!hasDifference) {
          return false;
        }
      }
      const newDecorations = newRanges.map((r) => ({
        range: r,
        options: ModelDecorationOptions.EMPTY
      }));
      this.hiddenAreasDecorationIds = this.model.deltaDecorations(this.hiddenAreasDecorationIds, newDecorations);
      const hiddenAreas = newRanges;
      let hiddenAreaStart = 1, hiddenAreaEnd = 0;
      let hiddenAreaIdx = -1;
      let nextLineNumberToUpdateHiddenArea = hiddenAreaIdx + 1 < hiddenAreas.length ? hiddenAreaEnd + 1 : this.modelLineProjections.length + 2;
      let hasVisibleLine = false;
      for (let i2 = 0; i2 < this.modelLineProjections.length; i2++) {
        const lineNumber = i2 + 1;
        if (lineNumber === nextLineNumberToUpdateHiddenArea) {
          hiddenAreaIdx++;
          hiddenAreaStart = hiddenAreas[hiddenAreaIdx].startLineNumber;
          hiddenAreaEnd = hiddenAreas[hiddenAreaIdx].endLineNumber;
          nextLineNumberToUpdateHiddenArea = hiddenAreaIdx + 1 < hiddenAreas.length ? hiddenAreaEnd + 1 : this.modelLineProjections.length + 2;
        }
        let lineChanged = false;
        if (lineNumber >= hiddenAreaStart && lineNumber <= hiddenAreaEnd) {
          if (this.modelLineProjections[i2].isVisible()) {
            this.modelLineProjections[i2] = this.modelLineProjections[i2].setVisible(false);
            lineChanged = true;
          }
        } else {
          hasVisibleLine = true;
          if (!this.modelLineProjections[i2].isVisible()) {
            this.modelLineProjections[i2] = this.modelLineProjections[i2].setVisible(true);
            lineChanged = true;
          }
        }
        if (lineChanged) {
          const newOutputLineCount = this.modelLineProjections[i2].getViewLineCount();
          this.projectedModelLineLineCounts.setValue(i2, newOutputLineCount);
        }
      }
      if (!hasVisibleLine) {
        this.setHiddenAreas([]);
      }
      return true;
    }
    modelPositionIsVisible(modelLineNumber, _modelColumn) {
      if (modelLineNumber < 1 || modelLineNumber > this.modelLineProjections.length) {
        return false;
      }
      return this.modelLineProjections[modelLineNumber - 1].isVisible();
    }
    getModelLineViewLineCount(modelLineNumber) {
      if (modelLineNumber < 1 || modelLineNumber > this.modelLineProjections.length) {
        return 1;
      }
      return this.modelLineProjections[modelLineNumber - 1].getViewLineCount();
    }
    setTabSize(newTabSize) {
      if (this.tabSize === newTabSize) {
        return false;
      }
      this.tabSize = newTabSize;
      this._constructLines(
        /*resetHiddenAreas*/
        false,
        null
      );
      return true;
    }
    setWrappingSettings(fontInfo, wrappingStrategy, wrappingColumn, wrappingIndent, wordBreak) {
      const equalFontInfo = this.fontInfo.equals(fontInfo);
      const equalWrappingStrategy = this.wrappingStrategy === wrappingStrategy;
      const equalWrappingColumn = this.wrappingColumn === wrappingColumn;
      const equalWrappingIndent = this.wrappingIndent === wrappingIndent;
      const equalWordBreak = this.wordBreak === wordBreak;
      if (equalFontInfo && equalWrappingStrategy && equalWrappingColumn && equalWrappingIndent && equalWordBreak) {
        return false;
      }
      const onlyWrappingColumnChanged = equalFontInfo && equalWrappingStrategy && !equalWrappingColumn && equalWrappingIndent && equalWordBreak;
      this.fontInfo = fontInfo;
      this.wrappingStrategy = wrappingStrategy;
      this.wrappingColumn = wrappingColumn;
      this.wrappingIndent = wrappingIndent;
      this.wordBreak = wordBreak;
      let previousLineBreaks = null;
      if (onlyWrappingColumnChanged) {
        previousLineBreaks = [];
        for (let i2 = 0, len = this.modelLineProjections.length; i2 < len; i2++) {
          previousLineBreaks[i2] = this.modelLineProjections[i2].getProjectionData();
        }
      }
      this._constructLines(
        /*resetHiddenAreas*/
        false,
        previousLineBreaks
      );
      return true;
    }
    createLineBreaksComputer() {
      const lineBreaksComputerFactory = this.wrappingStrategy === "advanced" ? this._domLineBreaksComputerFactory : this._monospaceLineBreaksComputerFactory;
      return lineBreaksComputerFactory.createLineBreaksComputer(this.fontInfo, this.tabSize, this.wrappingColumn, this.wrappingIndent, this.wordBreak, this.wrapOnEscapedLineFeeds);
    }
    onModelFlushed() {
      this._constructLines(
        /*resetHiddenAreas*/
        true,
        null
      );
    }
    onModelLinesDeleted(versionId, fromLineNumber, toLineNumber) {
      if (!versionId || versionId <= this._validModelVersionId) {
        return null;
      }
      const outputFromLineNumber = fromLineNumber === 1 ? 1 : this.projectedModelLineLineCounts.getPrefixSum(fromLineNumber - 1) + 1;
      const outputToLineNumber = this.projectedModelLineLineCounts.getPrefixSum(toLineNumber);
      this.modelLineProjections.splice(fromLineNumber - 1, toLineNumber - fromLineNumber + 1);
      this.projectedModelLineLineCounts.removeValues(fromLineNumber - 1, toLineNumber - fromLineNumber + 1);
      return new ViewLinesDeletedEvent(outputFromLineNumber, outputToLineNumber);
    }
    onModelLinesInserted(versionId, fromLineNumber, _toLineNumber, lineBreaks) {
      if (!versionId || versionId <= this._validModelVersionId) {
        return null;
      }
      const isInHiddenArea = fromLineNumber > 2 && !this.modelLineProjections[fromLineNumber - 2].isVisible();
      const outputFromLineNumber = fromLineNumber === 1 ? 1 : this.projectedModelLineLineCounts.getPrefixSum(fromLineNumber - 1) + 1;
      let totalOutputLineCount = 0;
      const insertLines = [];
      const insertPrefixSumValues = [];
      for (let i2 = 0, len = lineBreaks.length; i2 < len; i2++) {
        const line = createModelLineProjection(lineBreaks[i2], !isInHiddenArea);
        insertLines.push(line);
        const outputLineCount = line.getViewLineCount();
        totalOutputLineCount += outputLineCount;
        insertPrefixSumValues[i2] = outputLineCount;
      }
      this.modelLineProjections = this.modelLineProjections.slice(0, fromLineNumber - 1).concat(insertLines).concat(this.modelLineProjections.slice(fromLineNumber - 1));
      this.projectedModelLineLineCounts.insertValues(fromLineNumber - 1, insertPrefixSumValues);
      return new ViewLinesInsertedEvent(outputFromLineNumber, outputFromLineNumber + totalOutputLineCount - 1);
    }
    onModelLineChanged(versionId, lineNumber, lineBreakData) {
      if (versionId !== null && versionId <= this._validModelVersionId) {
        return [false, null, null, null];
      }
      const lineIndex = lineNumber - 1;
      const oldOutputLineCount = this.modelLineProjections[lineIndex].getViewLineCount();
      const isVisible = this.modelLineProjections[lineIndex].isVisible();
      const line = createModelLineProjection(lineBreakData, isVisible);
      this.modelLineProjections[lineIndex] = line;
      const newOutputLineCount = this.modelLineProjections[lineIndex].getViewLineCount();
      let lineMappingChanged = false;
      let changeFrom = 0;
      let changeTo = -1;
      let insertFrom = 0;
      let insertTo = -1;
      let deleteFrom = 0;
      let deleteTo = -1;
      if (oldOutputLineCount > newOutputLineCount) {
        changeFrom = this.projectedModelLineLineCounts.getPrefixSum(lineNumber - 1) + 1;
        changeTo = changeFrom + newOutputLineCount - 1;
        deleteFrom = changeTo + 1;
        deleteTo = deleteFrom + (oldOutputLineCount - newOutputLineCount) - 1;
        lineMappingChanged = true;
      } else if (oldOutputLineCount < newOutputLineCount) {
        changeFrom = this.projectedModelLineLineCounts.getPrefixSum(lineNumber - 1) + 1;
        changeTo = changeFrom + oldOutputLineCount - 1;
        insertFrom = changeTo + 1;
        insertTo = insertFrom + (newOutputLineCount - oldOutputLineCount) - 1;
        lineMappingChanged = true;
      } else {
        changeFrom = this.projectedModelLineLineCounts.getPrefixSum(lineNumber - 1) + 1;
        changeTo = changeFrom + newOutputLineCount - 1;
      }
      this.projectedModelLineLineCounts.setValue(lineIndex, newOutputLineCount);
      const viewLinesChangedEvent = changeFrom <= changeTo ? new ViewLinesChangedEvent(changeFrom, changeTo - changeFrom + 1) : null;
      const viewLinesInsertedEvent = insertFrom <= insertTo ? new ViewLinesInsertedEvent(insertFrom, insertTo) : null;
      const viewLinesDeletedEvent = deleteFrom <= deleteTo ? new ViewLinesDeletedEvent(deleteFrom, deleteTo) : null;
      return [lineMappingChanged, viewLinesChangedEvent, viewLinesInsertedEvent, viewLinesDeletedEvent];
    }
    acceptVersionId(versionId) {
      this._validModelVersionId = versionId;
      if (this.modelLineProjections.length === 1 && !this.modelLineProjections[0].isVisible()) {
        this.setHiddenAreas([]);
      }
    }
    getViewLineCount() {
      return this.projectedModelLineLineCounts.getTotalSum();
    }
    _toValidViewLineNumber(viewLineNumber) {
      if (viewLineNumber < 1) {
        return 1;
      }
      const viewLineCount = this.getViewLineCount();
      if (viewLineNumber > viewLineCount) {
        return viewLineCount;
      }
      return viewLineNumber | 0;
    }
    getActiveIndentGuide(viewLineNumber, minLineNumber, maxLineNumber) {
      viewLineNumber = this._toValidViewLineNumber(viewLineNumber);
      minLineNumber = this._toValidViewLineNumber(minLineNumber);
      maxLineNumber = this._toValidViewLineNumber(maxLineNumber);
      const modelPosition = this.convertViewPositionToModelPosition(viewLineNumber, this.getViewLineMinColumn(viewLineNumber));
      const modelMinPosition = this.convertViewPositionToModelPosition(minLineNumber, this.getViewLineMinColumn(minLineNumber));
      const modelMaxPosition = this.convertViewPositionToModelPosition(maxLineNumber, this.getViewLineMinColumn(maxLineNumber));
      const result = this.model.guides.getActiveIndentGuide(modelPosition.lineNumber, modelMinPosition.lineNumber, modelMaxPosition.lineNumber);
      const viewStartPosition = this.convertModelPositionToViewPosition(result.startLineNumber, 1);
      const viewEndPosition = this.convertModelPositionToViewPosition(result.endLineNumber, this.model.getLineMaxColumn(result.endLineNumber));
      return {
        startLineNumber: viewStartPosition.lineNumber,
        endLineNumber: viewEndPosition.lineNumber,
        indent: result.indent
      };
    }
    // #region ViewLineInfo
    getViewLineInfo(viewLineNumber) {
      viewLineNumber = this._toValidViewLineNumber(viewLineNumber);
      const r = this.projectedModelLineLineCounts.getIndexOf(viewLineNumber - 1);
      const lineIndex = r.index;
      const remainder = r.remainder;
      return new ViewLineInfo(lineIndex + 1, remainder);
    }
    getMinColumnOfViewLine(viewLineInfo) {
      return this.modelLineProjections[viewLineInfo.modelLineNumber - 1].getViewLineMinColumn(this.model, viewLineInfo.modelLineNumber, viewLineInfo.modelLineWrappedLineIdx);
    }
    getMaxColumnOfViewLine(viewLineInfo) {
      return this.modelLineProjections[viewLineInfo.modelLineNumber - 1].getViewLineMaxColumn(this.model, viewLineInfo.modelLineNumber, viewLineInfo.modelLineWrappedLineIdx);
    }
    getModelStartPositionOfViewLine(viewLineInfo) {
      const line = this.modelLineProjections[viewLineInfo.modelLineNumber - 1];
      const minViewColumn = line.getViewLineMinColumn(this.model, viewLineInfo.modelLineNumber, viewLineInfo.modelLineWrappedLineIdx);
      const column = line.getModelColumnOfViewPosition(viewLineInfo.modelLineWrappedLineIdx, minViewColumn);
      return new Position$1(viewLineInfo.modelLineNumber, column);
    }
    getModelEndPositionOfViewLine(viewLineInfo) {
      const line = this.modelLineProjections[viewLineInfo.modelLineNumber - 1];
      const maxViewColumn = line.getViewLineMaxColumn(this.model, viewLineInfo.modelLineNumber, viewLineInfo.modelLineWrappedLineIdx);
      const column = line.getModelColumnOfViewPosition(viewLineInfo.modelLineWrappedLineIdx, maxViewColumn);
      return new Position$1(viewLineInfo.modelLineNumber, column);
    }
    getViewLineInfosGroupedByModelRanges(viewStartLineNumber, viewEndLineNumber) {
      const startViewLine = this.getViewLineInfo(viewStartLineNumber);
      const endViewLine = this.getViewLineInfo(viewEndLineNumber);
      const result = new Array();
      let lastVisibleModelPos = this.getModelStartPositionOfViewLine(startViewLine);
      let viewLines = new Array();
      for (let curModelLine = startViewLine.modelLineNumber; curModelLine <= endViewLine.modelLineNumber; curModelLine++) {
        const line = this.modelLineProjections[curModelLine - 1];
        if (line.isVisible()) {
          const startOffset = curModelLine === startViewLine.modelLineNumber ? startViewLine.modelLineWrappedLineIdx : 0;
          const endOffset = curModelLine === endViewLine.modelLineNumber ? endViewLine.modelLineWrappedLineIdx + 1 : line.getViewLineCount();
          for (let i2 = startOffset; i2 < endOffset; i2++) {
            viewLines.push(new ViewLineInfo(curModelLine, i2));
          }
        }
        if (!line.isVisible() && lastVisibleModelPos) {
          const lastVisibleModelPos2 = new Position$1(curModelLine - 1, this.model.getLineMaxColumn(curModelLine - 1) + 1);
          const modelRange = Range$2.fromPositions(lastVisibleModelPos, lastVisibleModelPos2);
          result.push(new ViewLineInfoGroupedByModelRange(modelRange, viewLines));
          viewLines = [];
          lastVisibleModelPos = null;
        } else if (line.isVisible() && !lastVisibleModelPos) {
          lastVisibleModelPos = new Position$1(curModelLine, 1);
        }
      }
      if (lastVisibleModelPos) {
        const modelRange = Range$2.fromPositions(lastVisibleModelPos, this.getModelEndPositionOfViewLine(endViewLine));
        result.push(new ViewLineInfoGroupedByModelRange(modelRange, viewLines));
      }
      return result;
    }
    // #endregion
    getViewLinesBracketGuides(viewStartLineNumber, viewEndLineNumber, activeViewPosition, options) {
      const modelActivePosition = activeViewPosition ? this.convertViewPositionToModelPosition(activeViewPosition.lineNumber, activeViewPosition.column) : null;
      const resultPerViewLine = [];
      for (const group of this.getViewLineInfosGroupedByModelRanges(viewStartLineNumber, viewEndLineNumber)) {
        const modelRangeStartLineNumber = group.modelRange.startLineNumber;
        const bracketGuidesPerModelLine = this.model.guides.getLinesBracketGuides(modelRangeStartLineNumber, group.modelRange.endLineNumber, modelActivePosition, options);
        for (const viewLineInfo of group.viewLines) {
          const bracketGuides = bracketGuidesPerModelLine[viewLineInfo.modelLineNumber - modelRangeStartLineNumber];
          const result = bracketGuides.map((g) => {
            if (g.forWrappedLinesAfterColumn !== -1) {
              const p2 = this.modelLineProjections[viewLineInfo.modelLineNumber - 1].getViewPositionOfModelPosition(0, g.forWrappedLinesAfterColumn);
              if (p2.lineNumber >= viewLineInfo.modelLineWrappedLineIdx) {
                return void 0;
              }
            }
            if (g.forWrappedLinesBeforeOrAtColumn !== -1) {
              const p2 = this.modelLineProjections[viewLineInfo.modelLineNumber - 1].getViewPositionOfModelPosition(0, g.forWrappedLinesBeforeOrAtColumn);
              if (p2.lineNumber < viewLineInfo.modelLineWrappedLineIdx) {
                return void 0;
              }
            }
            if (!g.horizontalLine) {
              return g;
            }
            let column = -1;
            if (g.column !== -1) {
              const p2 = this.modelLineProjections[viewLineInfo.modelLineNumber - 1].getViewPositionOfModelPosition(0, g.column);
              if (p2.lineNumber === viewLineInfo.modelLineWrappedLineIdx) {
                column = p2.column;
              } else if (p2.lineNumber < viewLineInfo.modelLineWrappedLineIdx) {
                column = this.getMinColumnOfViewLine(viewLineInfo);
              } else if (p2.lineNumber > viewLineInfo.modelLineWrappedLineIdx) {
                return void 0;
              }
            }
            const viewPosition = this.convertModelPositionToViewPosition(viewLineInfo.modelLineNumber, g.horizontalLine.endColumn);
            const p = this.modelLineProjections[viewLineInfo.modelLineNumber - 1].getViewPositionOfModelPosition(0, g.horizontalLine.endColumn);
            if (p.lineNumber === viewLineInfo.modelLineWrappedLineIdx) {
              return new IndentGuide(g.visibleColumn, column, g.className, new IndentGuideHorizontalLine(g.horizontalLine.top, viewPosition.column), -1, -1);
            } else if (p.lineNumber < viewLineInfo.modelLineWrappedLineIdx) {
              return void 0;
            } else {
              if (g.visibleColumn !== -1) {
                return void 0;
              }
              return new IndentGuide(g.visibleColumn, column, g.className, new IndentGuideHorizontalLine(g.horizontalLine.top, this.getMaxColumnOfViewLine(viewLineInfo)), -1, -1);
            }
          });
          resultPerViewLine.push(result.filter((r) => !!r));
        }
      }
      return resultPerViewLine;
    }
    getViewLinesIndentGuides(viewStartLineNumber, viewEndLineNumber) {
      viewStartLineNumber = this._toValidViewLineNumber(viewStartLineNumber);
      viewEndLineNumber = this._toValidViewLineNumber(viewEndLineNumber);
      const modelStart = this.convertViewPositionToModelPosition(viewStartLineNumber, this.getViewLineMinColumn(viewStartLineNumber));
      const modelEnd = this.convertViewPositionToModelPosition(viewEndLineNumber, this.getViewLineMaxColumn(viewEndLineNumber));
      let result = [];
      const resultRepeatCount = [];
      const resultRepeatOption = [];
      const modelStartLineIndex = modelStart.lineNumber - 1;
      const modelEndLineIndex = modelEnd.lineNumber - 1;
      let reqStart = null;
      for (let modelLineIndex = modelStartLineIndex; modelLineIndex <= modelEndLineIndex; modelLineIndex++) {
        const line = this.modelLineProjections[modelLineIndex];
        if (line.isVisible()) {
          const viewLineStartIndex = line.getViewLineNumberOfModelPosition(0, modelLineIndex === modelStartLineIndex ? modelStart.column : 1);
          const viewLineEndIndex = line.getViewLineNumberOfModelPosition(0, this.model.getLineMaxColumn(modelLineIndex + 1));
          const count = viewLineEndIndex - viewLineStartIndex + 1;
          let option2 = 0;
          if (count > 1 && line.getViewLineMinColumn(this.model, modelLineIndex + 1, viewLineEndIndex) === 1) {
            option2 = viewLineStartIndex === 0 ? 1 : 2;
          }
          resultRepeatCount.push(count);
          resultRepeatOption.push(option2);
          if (reqStart === null) {
            reqStart = new Position$1(modelLineIndex + 1, 0);
          }
        } else {
          if (reqStart !== null) {
            result = result.concat(this.model.guides.getLinesIndentGuides(reqStart.lineNumber, modelLineIndex));
            reqStart = null;
          }
        }
      }
      if (reqStart !== null) {
        result = result.concat(this.model.guides.getLinesIndentGuides(reqStart.lineNumber, modelEnd.lineNumber));
        reqStart = null;
      }
      const viewLineCount = viewEndLineNumber - viewStartLineNumber + 1;
      const viewIndents = new Array(viewLineCount);
      let currIndex = 0;
      for (let i2 = 0, len = result.length; i2 < len; i2++) {
        let value = result[i2];
        const count = Math.min(viewLineCount - currIndex, resultRepeatCount[i2]);
        const option2 = resultRepeatOption[i2];
        let blockAtIndex;
        if (option2 === 2) {
          blockAtIndex = 0;
        } else if (option2 === 1) {
          blockAtIndex = 1;
        } else {
          blockAtIndex = count;
        }
        for (let j = 0; j < count; j++) {
          if (j === blockAtIndex) {
            value = 0;
          }
          viewIndents[currIndex++] = value;
        }
      }
      return viewIndents;
    }
    getViewLineContent(viewLineNumber) {
      const info = this.getViewLineInfo(viewLineNumber);
      return this.modelLineProjections[info.modelLineNumber - 1].getViewLineContent(this.model, info.modelLineNumber, info.modelLineWrappedLineIdx);
    }
    getViewLineLength(viewLineNumber) {
      const info = this.getViewLineInfo(viewLineNumber);
      return this.modelLineProjections[info.modelLineNumber - 1].getViewLineLength(this.model, info.modelLineNumber, info.modelLineWrappedLineIdx);
    }
    getViewLineMinColumn(viewLineNumber) {
      const info = this.getViewLineInfo(viewLineNumber);
      return this.modelLineProjections[info.modelLineNumber - 1].getViewLineMinColumn(this.model, info.modelLineNumber, info.modelLineWrappedLineIdx);
    }
    getViewLineMaxColumn(viewLineNumber) {
      const info = this.getViewLineInfo(viewLineNumber);
      return this.modelLineProjections[info.modelLineNumber - 1].getViewLineMaxColumn(this.model, info.modelLineNumber, info.modelLineWrappedLineIdx);
    }
    getViewLineData(viewLineNumber) {
      const info = this.getViewLineInfo(viewLineNumber);
      return this.modelLineProjections[info.modelLineNumber - 1].getViewLineData(this.model, info.modelLineNumber, info.modelLineWrappedLineIdx);
    }
    getViewLinesData(viewStartLineNumber, viewEndLineNumber, needed) {
      viewStartLineNumber = this._toValidViewLineNumber(viewStartLineNumber);
      viewEndLineNumber = this._toValidViewLineNumber(viewEndLineNumber);
      const start = this.projectedModelLineLineCounts.getIndexOf(viewStartLineNumber - 1);
      let viewLineNumber = viewStartLineNumber;
      const startModelLineIndex = start.index;
      const startRemainder = start.remainder;
      const result = [];
      for (let modelLineIndex = startModelLineIndex, len = this.model.getLineCount(); modelLineIndex < len; modelLineIndex++) {
        const line = this.modelLineProjections[modelLineIndex];
        if (!line.isVisible()) {
          continue;
        }
        const fromViewLineIndex = modelLineIndex === startModelLineIndex ? startRemainder : 0;
        let remainingViewLineCount = line.getViewLineCount() - fromViewLineIndex;
        let lastLine = false;
        if (viewLineNumber + remainingViewLineCount > viewEndLineNumber) {
          lastLine = true;
          remainingViewLineCount = viewEndLineNumber - viewLineNumber + 1;
        }
        line.getViewLinesData(this.model, modelLineIndex + 1, fromViewLineIndex, remainingViewLineCount, viewLineNumber - viewStartLineNumber, needed, result);
        viewLineNumber += remainingViewLineCount;
        if (lastLine) {
          break;
        }
      }
      return result;
    }
    validateViewPosition(viewLineNumber, viewColumn, expectedModelPosition) {
      viewLineNumber = this._toValidViewLineNumber(viewLineNumber);
      const r = this.projectedModelLineLineCounts.getIndexOf(viewLineNumber - 1);
      const lineIndex = r.index;
      const remainder = r.remainder;
      const line = this.modelLineProjections[lineIndex];
      const minColumn = line.getViewLineMinColumn(this.model, lineIndex + 1, remainder);
      const maxColumn = line.getViewLineMaxColumn(this.model, lineIndex + 1, remainder);
      if (viewColumn < minColumn) {
        viewColumn = minColumn;
      }
      if (viewColumn > maxColumn) {
        viewColumn = maxColumn;
      }
      const computedModelColumn = line.getModelColumnOfViewPosition(remainder, viewColumn);
      const computedModelPosition = this.model.validatePosition(new Position$1(lineIndex + 1, computedModelColumn));
      if (computedModelPosition.equals(expectedModelPosition)) {
        return new Position$1(viewLineNumber, viewColumn);
      }
      return this.convertModelPositionToViewPosition(expectedModelPosition.lineNumber, expectedModelPosition.column);
    }
    validateViewRange(viewRange, expectedModelRange) {
      const validViewStart = this.validateViewPosition(viewRange.startLineNumber, viewRange.startColumn, expectedModelRange.getStartPosition());
      const validViewEnd = this.validateViewPosition(viewRange.endLineNumber, viewRange.endColumn, expectedModelRange.getEndPosition());
      return new Range$2(validViewStart.lineNumber, validViewStart.column, validViewEnd.lineNumber, validViewEnd.column);
    }
    convertViewPositionToModelPosition(viewLineNumber, viewColumn) {
      const info = this.getViewLineInfo(viewLineNumber);
      const inputColumn = this.modelLineProjections[info.modelLineNumber - 1].getModelColumnOfViewPosition(info.modelLineWrappedLineIdx, viewColumn);
      return this.model.validatePosition(new Position$1(info.modelLineNumber, inputColumn));
    }
    convertViewRangeToModelRange(viewRange) {
      const start = this.convertViewPositionToModelPosition(viewRange.startLineNumber, viewRange.startColumn);
      const end = this.convertViewPositionToModelPosition(viewRange.endLineNumber, viewRange.endColumn);
      return new Range$2(start.lineNumber, start.column, end.lineNumber, end.column);
    }
    convertModelPositionToViewPosition(_modelLineNumber, _modelColumn, affinity = 2, allowZeroLineNumber = false, belowHiddenRanges = false) {
      const validPosition = this.model.validatePosition(new Position$1(_modelLineNumber, _modelColumn));
      const inputLineNumber = validPosition.lineNumber;
      const inputColumn = validPosition.column;
      let lineIndex = inputLineNumber - 1, lineIndexChanged = false;
      if (belowHiddenRanges) {
        while (lineIndex < this.modelLineProjections.length && !this.modelLineProjections[lineIndex].isVisible()) {
          lineIndex++;
          lineIndexChanged = true;
        }
      } else {
        while (lineIndex > 0 && !this.modelLineProjections[lineIndex].isVisible()) {
          lineIndex--;
          lineIndexChanged = true;
        }
      }
      if (lineIndex === 0 && !this.modelLineProjections[lineIndex].isVisible()) {
        return new Position$1(allowZeroLineNumber ? 0 : 1, 1);
      }
      const deltaLineNumber = 1 + this.projectedModelLineLineCounts.getPrefixSum(lineIndex);
      let r;
      if (lineIndexChanged) {
        if (belowHiddenRanges) {
          r = this.modelLineProjections[lineIndex].getViewPositionOfModelPosition(deltaLineNumber, 1, affinity);
        } else {
          r = this.modelLineProjections[lineIndex].getViewPositionOfModelPosition(deltaLineNumber, this.model.getLineMaxColumn(lineIndex + 1), affinity);
        }
      } else {
        r = this.modelLineProjections[inputLineNumber - 1].getViewPositionOfModelPosition(deltaLineNumber, inputColumn, affinity);
      }
      return r;
    }
    /**
     * @param affinity The affinity in case of an empty range. Has no effect for non-empty ranges.
    */
    convertModelRangeToViewRange(modelRange, affinity = 0) {
      if (modelRange.isEmpty()) {
        const start = this.convertModelPositionToViewPosition(modelRange.startLineNumber, modelRange.startColumn, affinity);
        return Range$2.fromPositions(start);
      } else {
        const start = this.convertModelPositionToViewPosition(
          modelRange.startLineNumber,
          modelRange.startColumn,
          1
          /* PositionAffinity.Right */
        );
        const end = this.convertModelPositionToViewPosition(
          modelRange.endLineNumber,
          modelRange.endColumn,
          0
          /* PositionAffinity.Left */
        );
        return new Range$2(start.lineNumber, start.column, end.lineNumber, end.column);
      }
    }
    getViewLineNumberOfModelPosition(modelLineNumber, modelColumn) {
      let lineIndex = modelLineNumber - 1;
      if (this.modelLineProjections[lineIndex].isVisible()) {
        const deltaLineNumber2 = 1 + this.projectedModelLineLineCounts.getPrefixSum(lineIndex);
        return this.modelLineProjections[lineIndex].getViewLineNumberOfModelPosition(deltaLineNumber2, modelColumn);
      }
      while (lineIndex > 0 && !this.modelLineProjections[lineIndex].isVisible()) {
        lineIndex--;
      }
      if (lineIndex === 0 && !this.modelLineProjections[lineIndex].isVisible()) {
        return 1;
      }
      const deltaLineNumber = 1 + this.projectedModelLineLineCounts.getPrefixSum(lineIndex);
      return this.modelLineProjections[lineIndex].getViewLineNumberOfModelPosition(deltaLineNumber, this.model.getLineMaxColumn(lineIndex + 1));
    }
    getDecorationsInRange(range2, ownerId2, filterOutValidation, filterFontDecorations2, onlyMinimapDecorations, onlyMarginDecorations) {
      const modelStart = this.convertViewPositionToModelPosition(range2.startLineNumber, range2.startColumn);
      const modelEnd = this.convertViewPositionToModelPosition(range2.endLineNumber, range2.endColumn);
      if (modelEnd.lineNumber - modelStart.lineNumber <= range2.endLineNumber - range2.startLineNumber) {
        return this.model.getDecorationsInRange(new Range$2(modelStart.lineNumber, 1, modelEnd.lineNumber, modelEnd.column), ownerId2, filterOutValidation, filterFontDecorations2, onlyMinimapDecorations, onlyMarginDecorations);
      }
      let result = [];
      const modelStartLineIndex = modelStart.lineNumber - 1;
      const modelEndLineIndex = modelEnd.lineNumber - 1;
      let reqStart = null;
      for (let modelLineIndex = modelStartLineIndex; modelLineIndex <= modelEndLineIndex; modelLineIndex++) {
        const line = this.modelLineProjections[modelLineIndex];
        if (line.isVisible()) {
          if (reqStart === null) {
            reqStart = new Position$1(modelLineIndex + 1, modelLineIndex === modelStartLineIndex ? modelStart.column : 1);
          }
        } else {
          if (reqStart !== null) {
            const maxLineColumn = this.model.getLineMaxColumn(modelLineIndex);
            result = result.concat(this.model.getDecorationsInRange(new Range$2(reqStart.lineNumber, reqStart.column, modelLineIndex, maxLineColumn), ownerId2, filterOutValidation, filterFontDecorations2, onlyMinimapDecorations));
            reqStart = null;
          }
        }
      }
      if (reqStart !== null) {
        result = result.concat(this.model.getDecorationsInRange(new Range$2(reqStart.lineNumber, reqStart.column, modelEnd.lineNumber, modelEnd.column), ownerId2, filterOutValidation, filterFontDecorations2, onlyMinimapDecorations));
        reqStart = null;
      }
      result.sort((a, b) => {
        const res = Range$2.compareRangesUsingStarts(a.range, b.range);
        if (res === 0) {
          if (a.id < b.id) {
            return -1;
          }
          if (a.id > b.id) {
            return 1;
          }
          return 0;
        }
        return res;
      });
      const finalResult = [];
      let finalResultLen = 0;
      let prevDecId = null;
      for (const dec of result) {
        const decId = dec.id;
        if (prevDecId === decId) {
          continue;
        }
        prevDecId = decId;
        finalResult[finalResultLen++] = dec;
      }
      return finalResult;
    }
    getInjectedTextAt(position) {
      const info = this.getViewLineInfo(position.lineNumber);
      return this.modelLineProjections[info.modelLineNumber - 1].getInjectedTextAt(info.modelLineWrappedLineIdx, position.column);
    }
    normalizePosition(position, affinity) {
      const info = this.getViewLineInfo(position.lineNumber);
      return this.modelLineProjections[info.modelLineNumber - 1].normalizePosition(info.modelLineWrappedLineIdx, position, affinity);
    }
    getLineIndentColumn(lineNumber) {
      const info = this.getViewLineInfo(lineNumber);
      if (info.modelLineWrappedLineIdx === 0) {
        return this.model.getLineIndentColumn(info.modelLineNumber);
      }
      return 0;
    }
  }
  function normalizeLineRanges(ranges) {
    if (ranges.length === 0) {
      return [];
    }
    const sortedRanges = ranges.slice();
    sortedRanges.sort(Range$2.compareRangesUsingStarts);
    const result = [];
    let currentRangeStart = sortedRanges[0].startLineNumber;
    let currentRangeEnd = sortedRanges[0].endLineNumber;
    for (let i2 = 1, len = sortedRanges.length; i2 < len; i2++) {
      const range2 = sortedRanges[i2];
      if (range2.startLineNumber > currentRangeEnd + 1) {
        result.push(new Range$2(currentRangeStart, 1, currentRangeEnd, 1));
        currentRangeStart = range2.startLineNumber;
        currentRangeEnd = range2.endLineNumber;
      } else if (range2.endLineNumber > currentRangeEnd) {
        currentRangeEnd = range2.endLineNumber;
      }
    }
    result.push(new Range$2(currentRangeStart, 1, currentRangeEnd, 1));
    return result;
  }
  class ViewLineInfo {
    constructor(modelLineNumber, modelLineWrappedLineIdx) {
      this.modelLineNumber = modelLineNumber;
      this.modelLineWrappedLineIdx = modelLineWrappedLineIdx;
    }
  }
  class ViewLineInfoGroupedByModelRange {
    constructor(modelRange, viewLines) {
      this.modelRange = modelRange;
      this.viewLines = viewLines;
    }
  }
  class CoordinatesConverter {
    constructor(lines) {
      this._lines = lines;
    }
    // View -> Model conversion and related methods
    convertViewPositionToModelPosition(viewPosition) {
      return this._lines.convertViewPositionToModelPosition(viewPosition.lineNumber, viewPosition.column);
    }
    convertViewRangeToModelRange(viewRange) {
      return this._lines.convertViewRangeToModelRange(viewRange);
    }
    validateViewPosition(viewPosition, expectedModelPosition) {
      return this._lines.validateViewPosition(viewPosition.lineNumber, viewPosition.column, expectedModelPosition);
    }
    validateViewRange(viewRange, expectedModelRange) {
      return this._lines.validateViewRange(viewRange, expectedModelRange);
    }
    // Model -> View conversion and related methods
    convertModelPositionToViewPosition(modelPosition, affinity, allowZero, belowHiddenRanges) {
      return this._lines.convertModelPositionToViewPosition(modelPosition.lineNumber, modelPosition.column, affinity, allowZero, belowHiddenRanges);
    }
    convertModelRangeToViewRange(modelRange, affinity) {
      return this._lines.convertModelRangeToViewRange(modelRange, affinity);
    }
    modelPositionIsVisible(modelPosition) {
      return this._lines.modelPositionIsVisible(modelPosition.lineNumber, modelPosition.column);
    }
    getModelLineViewLineCount(modelLineNumber) {
      return this._lines.getModelLineViewLineCount(modelLineNumber);
    }
    getViewLineNumberOfModelPosition(modelLineNumber, modelColumn) {
      return this._lines.getViewLineNumberOfModelPosition(modelLineNumber, modelColumn);
    }
  }
  class ViewModelLinesFromModelAsIs {
    constructor(model) {
      this.model = model;
    }
    dispose() {
    }
    createCoordinatesConverter() {
      return new IdentityCoordinatesConverter(this.model);
    }
    getHiddenAreas() {
      return [];
    }
    setHiddenAreas(_ranges) {
      return false;
    }
    setTabSize(_newTabSize) {
      return false;
    }
    setWrappingSettings(_fontInfo, _wrappingStrategy, _wrappingColumn, _wrappingIndent) {
      return false;
    }
    createLineBreaksComputer() {
      const result = [];
      return {
        addRequest: (lineText, injectedText, previousLineBreakData) => {
          result.push(null);
        },
        finalize: () => {
          return result;
        }
      };
    }
    onModelFlushed() {
    }
    onModelLinesDeleted(_versionId, fromLineNumber, toLineNumber) {
      return new ViewLinesDeletedEvent(fromLineNumber, toLineNumber);
    }
    onModelLinesInserted(_versionId, fromLineNumber, toLineNumber, lineBreaks) {
      return new ViewLinesInsertedEvent(fromLineNumber, toLineNumber);
    }
    onModelLineChanged(_versionId, lineNumber, lineBreakData) {
      return [false, new ViewLinesChangedEvent(lineNumber, 1), null, null];
    }
    acceptVersionId(_versionId) {
    }
    getViewLineCount() {
      return this.model.getLineCount();
    }
    getActiveIndentGuide(viewLineNumber, _minLineNumber, _maxLineNumber) {
      return {
        startLineNumber: viewLineNumber,
        endLineNumber: viewLineNumber,
        indent: 0
      };
    }
    getViewLinesBracketGuides(startLineNumber, endLineNumber, activePosition) {
      return new Array(endLineNumber - startLineNumber + 1).fill([]);
    }
    getViewLinesIndentGuides(viewStartLineNumber, viewEndLineNumber) {
      const viewLineCount = viewEndLineNumber - viewStartLineNumber + 1;
      const result = new Array(viewLineCount);
      for (let i2 = 0; i2 < viewLineCount; i2++) {
        result[i2] = 0;
      }
      return result;
    }
    getViewLineContent(viewLineNumber) {
      return this.model.getLineContent(viewLineNumber);
    }
    getViewLineLength(viewLineNumber) {
      return this.model.getLineLength(viewLineNumber);
    }
    getViewLineMinColumn(viewLineNumber) {
      return this.model.getLineMinColumn(viewLineNumber);
    }
    getViewLineMaxColumn(viewLineNumber) {
      return this.model.getLineMaxColumn(viewLineNumber);
    }
    getViewLineData(viewLineNumber) {
      const lineTokens = this.model.tokenization.getLineTokens(viewLineNumber);
      const lineContent = lineTokens.getLineContent();
      return new ViewLineData(lineContent, false, 1, lineContent.length + 1, 0, lineTokens.inflate(), null);
    }
    getViewLinesData(viewStartLineNumber, viewEndLineNumber, needed) {
      const lineCount = this.model.getLineCount();
      viewStartLineNumber = Math.min(Math.max(1, viewStartLineNumber), lineCount);
      viewEndLineNumber = Math.min(Math.max(1, viewEndLineNumber), lineCount);
      const result = [];
      for (let lineNumber = viewStartLineNumber; lineNumber <= viewEndLineNumber; lineNumber++) {
        const idx = lineNumber - viewStartLineNumber;
        result[idx] = needed[idx] ? this.getViewLineData(lineNumber) : null;
      }
      return result;
    }
    getDecorationsInRange(range2, ownerId2, filterOutValidation, filterFontDecorations2, onlyMinimapDecorations, onlyMarginDecorations) {
      return this.model.getDecorationsInRange(range2, ownerId2, filterOutValidation, filterFontDecorations2, onlyMinimapDecorations, onlyMarginDecorations);
    }
    normalizePosition(position, affinity) {
      return this.model.normalizePosition(position, affinity);
    }
    getLineIndentColumn(lineNumber) {
      return this.model.getLineIndentColumn(lineNumber);
    }
    getInjectedTextAt(position) {
      return null;
    }
  }
  const MAX_LANE = GlyphMarginLane$1.Right;
  class GlyphMarginLanesModel {
    constructor(maxLine) {
      this.persist = 0;
      this._requiredLanes = 1;
      this.lanes = new Uint8Array(Math.ceil((maxLine + 1) * MAX_LANE / 8));
    }
    reset(maxLine) {
      const bytes = Math.ceil((maxLine + 1) * MAX_LANE / 8);
      if (this.lanes.length < bytes) {
        this.lanes = new Uint8Array(bytes);
      } else {
        this.lanes.fill(0);
      }
      this._requiredLanes = 1;
    }
    get requiredLanes() {
      return this._requiredLanes;
    }
    push(lane, range2, persist) {
      if (persist) {
        this.persist |= 1 << lane - 1;
      }
      for (let i2 = range2.startLineNumber; i2 <= range2.endLineNumber; i2++) {
        const bit = MAX_LANE * i2 + (lane - 1);
        this.lanes[bit >>> 3] |= 1 << bit % 8;
        this._requiredLanes = Math.max(this._requiredLanes, this.countAtLine(i2));
      }
    }
    getLanesAtLine(lineNumber) {
      const lanes = [];
      let bit = MAX_LANE * lineNumber;
      for (let i2 = 0; i2 < MAX_LANE; i2++) {
        if (this.persist & 1 << i2 || this.lanes[bit >>> 3] & 1 << bit % 8) {
          lanes.push(i2 + 1);
        }
        bit++;
      }
      return lanes.length ? lanes : [GlyphMarginLane$1.Center];
    }
    countAtLine(lineNumber) {
      let bit = MAX_LANE * lineNumber;
      let count = 0;
      for (let i2 = 0; i2 < MAX_LANE; i2++) {
        if (this.persist & 1 << i2 || this.lanes[bit >>> 3] & 1 << bit % 8) {
          count++;
        }
        bit++;
      }
      return count;
    }
  }
  let ViewModel$1 = class ViewModel extends Disposable {
    constructor(editorId, configuration, model, domLineBreaksComputerFactory, monospaceLineBreaksComputerFactory, scheduleAtNextAnimationFrame2, languageConfigurationService, _themeService, _attachedView, _transactionalTarget) {
      super();
      this.languageConfigurationService = languageConfigurationService;
      this._themeService = _themeService;
      this._attachedView = _attachedView;
      this._transactionalTarget = _transactionalTarget;
      this.hiddenAreasModel = new HiddenAreasModel();
      this.previousHiddenAreas = [];
      this._editorId = editorId;
      this._configuration = configuration;
      this.model = model;
      this._eventDispatcher = new ViewModelEventDispatcher();
      this.onEvent = this._eventDispatcher.onEvent;
      this.cursorConfig = new CursorConfiguration(this.model.getLanguageId(), this.model.getOptions(), this._configuration, this.languageConfigurationService);
      this._updateConfigurationViewLineCount = this._register(new RunOnceScheduler(() => this._updateConfigurationViewLineCountNow(), 0));
      this._hasFocus = false;
      this._viewportStart = ViewportStart.create(this.model);
      this.glyphLanes = new GlyphMarginLanesModel(0);
      if (this.model.isTooLargeForTokenization()) {
        this._lines = new ViewModelLinesFromModelAsIs(this.model);
      } else {
        const options = this._configuration.options;
        const fontInfo = options.get(
          59
          /* EditorOption.fontInfo */
        );
        const wrappingStrategy = options.get(
          156
          /* EditorOption.wrappingStrategy */
        );
        const wrappingInfo = options.get(
          166
          /* EditorOption.wrappingInfo */
        );
        const wrappingIndent = options.get(
          155
          /* EditorOption.wrappingIndent */
        );
        const wordBreak = options.get(
          146
          /* EditorOption.wordBreak */
        );
        const wrapOnEscapedLineFeeds = options.get(
          160
          /* EditorOption.wrapOnEscapedLineFeeds */
        );
        this._lines = new ViewModelLinesFromProjectedModel(this._editorId, this.model, domLineBreaksComputerFactory, monospaceLineBreaksComputerFactory, fontInfo, this.model.getOptions().tabSize, wrappingStrategy, wrappingInfo.wrappingColumn, wrappingIndent, wordBreak, wrapOnEscapedLineFeeds);
      }
      this.coordinatesConverter = this._lines.createCoordinatesConverter();
      this._cursor = this._register(new CursorsController(model, this, this.coordinatesConverter, this.cursorConfig));
      this.viewLayout = this._register(new ViewLayout(this._configuration, this.getLineCount(), this._getCustomLineHeights(), scheduleAtNextAnimationFrame2));
      this._register(this.viewLayout.onDidScroll((e) => {
        if (e.scrollTopChanged) {
          this._handleVisibleLinesChanged();
        }
        if (e.scrollTopChanged) {
          this._viewportStart.invalidate();
        }
        this._eventDispatcher.emitSingleViewEvent(new ViewScrollChangedEvent(e));
        this._eventDispatcher.emitOutgoingEvent(new ScrollChangedEvent(e.oldScrollWidth, e.oldScrollLeft, e.oldScrollHeight, e.oldScrollTop, e.scrollWidth, e.scrollLeft, e.scrollHeight, e.scrollTop));
      }));
      this._register(this.viewLayout.onDidContentSizeChange((e) => {
        this._eventDispatcher.emitOutgoingEvent(e);
      }));
      this._decorations = new ViewModelDecorations(this._editorId, this.model, this._configuration, this._lines, this.coordinatesConverter);
      this._registerModelEvents();
      this._register(this._configuration.onDidChangeFast((e) => {
        try {
          const eventsCollector = this._eventDispatcher.beginEmitViewEvents();
          this._onConfigurationChanged(eventsCollector, e);
        } finally {
          this._eventDispatcher.endEmitViewEvents();
        }
      }));
      this._register(MinimapTokensColorTracker.getInstance().onDidChange(() => {
        this._eventDispatcher.emitSingleViewEvent(new ViewTokensColorsChangedEvent());
      }));
      this._register(this._themeService.onDidColorThemeChange((theme) => {
        this._invalidateDecorationsColorCache();
        this._eventDispatcher.emitSingleViewEvent(new ViewThemeChangedEvent(theme));
      }));
      this._updateConfigurationViewLineCountNow();
    }
    dispose() {
      super.dispose();
      this._decorations.dispose();
      this._lines.dispose();
      this._viewportStart.dispose();
      this._eventDispatcher.dispose();
    }
    createLineBreaksComputer() {
      return this._lines.createLineBreaksComputer();
    }
    addViewEventHandler(eventHandler) {
      this._eventDispatcher.addViewEventHandler(eventHandler);
    }
    removeViewEventHandler(eventHandler) {
      this._eventDispatcher.removeViewEventHandler(eventHandler);
    }
    _getCustomLineHeights() {
      const allowVariableLineHeights = this._configuration.options.get(
        5
        /* EditorOption.allowVariableLineHeights */
      );
      if (!allowVariableLineHeights) {
        return [];
      }
      const decorations = this.model.getCustomLineHeightsDecorations(this._editorId);
      return decorations.map((d) => {
        const lineNumber = d.range.startLineNumber;
        const viewRange = this.coordinatesConverter.convertModelRangeToViewRange(new Range$2(lineNumber, 1, lineNumber, this.model.getLineMaxColumn(lineNumber)));
        return {
          decorationId: d.id,
          startLineNumber: viewRange.startLineNumber,
          endLineNumber: viewRange.endLineNumber,
          lineHeight: d.options.lineHeight || 0
        };
      });
    }
    _updateConfigurationViewLineCountNow() {
      this._configuration.setViewLineCount(this._lines.getViewLineCount());
    }
    getModelVisibleRanges() {
      const linesViewportData = this.viewLayout.getLinesViewportData();
      const viewVisibleRange = new Range$2(linesViewportData.startLineNumber, this.getLineMinColumn(linesViewportData.startLineNumber), linesViewportData.endLineNumber, this.getLineMaxColumn(linesViewportData.endLineNumber));
      const modelVisibleRanges = this._toModelVisibleRanges(viewVisibleRange);
      return modelVisibleRanges;
    }
    visibleLinesStabilized() {
      const modelVisibleRanges = this.getModelVisibleRanges();
      this._attachedView.setVisibleLines(modelVisibleRanges, true);
    }
    _handleVisibleLinesChanged() {
      const modelVisibleRanges = this.getModelVisibleRanges();
      this._attachedView.setVisibleLines(modelVisibleRanges, false);
    }
    setHasFocus(hasFocus) {
      this._hasFocus = hasFocus;
      this._cursor.setHasFocus(hasFocus);
      this._eventDispatcher.emitSingleViewEvent(new ViewFocusChangedEvent(hasFocus));
      this._eventDispatcher.emitOutgoingEvent(new FocusChangedEvent(!hasFocus, hasFocus));
    }
    setHasWidgetFocus(hasWidgetFocus) {
      this._eventDispatcher.emitOutgoingEvent(new WidgetFocusChangedEvent(!hasWidgetFocus, hasWidgetFocus));
    }
    onCompositionStart() {
      this._eventDispatcher.emitSingleViewEvent(new ViewCompositionStartEvent());
    }
    onCompositionEnd() {
      this._eventDispatcher.emitSingleViewEvent(new ViewCompositionEndEvent());
    }
    _captureStableViewport() {
      if (this._viewportStart.isValid && this.viewLayout.getCurrentScrollTop() > 0) {
        const previousViewportStartViewPosition = new Position$1(this._viewportStart.viewLineNumber, this.getLineMinColumn(this._viewportStart.viewLineNumber));
        const previousViewportStartModelPosition = this.coordinatesConverter.convertViewPositionToModelPosition(previousViewportStartViewPosition);
        return new StableViewport(previousViewportStartModelPosition, this._viewportStart.startLineDelta);
      }
      return new StableViewport(null, 0);
    }
    _onConfigurationChanged(eventsCollector, e) {
      const stableViewport = this._captureStableViewport();
      const options = this._configuration.options;
      const fontInfo = options.get(
        59
        /* EditorOption.fontInfo */
      );
      const wrappingStrategy = options.get(
        156
        /* EditorOption.wrappingStrategy */
      );
      const wrappingInfo = options.get(
        166
        /* EditorOption.wrappingInfo */
      );
      const wrappingIndent = options.get(
        155
        /* EditorOption.wrappingIndent */
      );
      const wordBreak = options.get(
        146
        /* EditorOption.wordBreak */
      );
      if (this._lines.setWrappingSettings(fontInfo, wrappingStrategy, wrappingInfo.wrappingColumn, wrappingIndent, wordBreak)) {
        eventsCollector.emitViewEvent(new ViewFlushedEvent());
        eventsCollector.emitViewEvent(new ViewLineMappingChangedEvent());
        eventsCollector.emitViewEvent(new ViewDecorationsChangedEvent(null));
        this._cursor.onLineMappingChanged(eventsCollector);
        this._decorations.onLineMappingChanged();
        this.viewLayout.onFlushed(this.getLineCount(), this._getCustomLineHeights());
        this._updateConfigurationViewLineCount.schedule();
      }
      if (e.hasChanged(
        104
        /* EditorOption.readOnly */
      )) {
        this._decorations.reset();
        eventsCollector.emitViewEvent(new ViewDecorationsChangedEvent(null));
      }
      if (e.hasChanged(
        112
        /* EditorOption.renderValidationDecorations */
      )) {
        this._decorations.reset();
        eventsCollector.emitViewEvent(new ViewDecorationsChangedEvent(null));
      }
      eventsCollector.emitViewEvent(new ViewConfigurationChangedEvent(e));
      this.viewLayout.onConfigurationChanged(e);
      stableViewport.recoverViewportStart(this.coordinatesConverter, this.viewLayout);
      if (CursorConfiguration.shouldRecreate(e)) {
        this.cursorConfig = new CursorConfiguration(this.model.getLanguageId(), this.model.getOptions(), this._configuration, this.languageConfigurationService);
        this._cursor.updateConfiguration(this.cursorConfig);
      }
    }
    _registerModelEvents() {
      this._register(this.model.onDidChangeContentOrInjectedText((e) => {
        try {
          const eventsCollector = this._eventDispatcher.beginEmitViewEvents();
          let hadOtherModelChange = false;
          let hadModelLineChangeThatChangedLineMapping = false;
          const changes = e instanceof InternalModelContentChangeEvent ? e.rawContentChangedEvent.changes : e.changes;
          const versionId = e instanceof InternalModelContentChangeEvent ? e.rawContentChangedEvent.versionId : null;
          const lineBreaksComputer = this._lines.createLineBreaksComputer();
          for (const change of changes) {
            switch (change.changeType) {
              case 4: {
                for (let lineIdx = 0; lineIdx < change.detail.length; lineIdx++) {
                  const line = change.detail[lineIdx];
                  let injectedText = change.injectedTexts[lineIdx];
                  if (injectedText) {
                    injectedText = injectedText.filter((element) => !element.ownerId || element.ownerId === this._editorId);
                  }
                  lineBreaksComputer.addRequest(line, injectedText, null);
                }
                break;
              }
              case 2: {
                let injectedText = null;
                if (change.injectedText) {
                  injectedText = change.injectedText.filter((element) => !element.ownerId || element.ownerId === this._editorId);
                }
                lineBreaksComputer.addRequest(change.detail, injectedText, null);
                break;
              }
            }
          }
          const lineBreaks = lineBreaksComputer.finalize();
          const lineBreakQueue = new ArrayQueue(lineBreaks);
          for (const change of changes) {
            switch (change.changeType) {
              case 1: {
                this._lines.onModelFlushed();
                eventsCollector.emitViewEvent(new ViewFlushedEvent());
                this._decorations.reset();
                this.viewLayout.onFlushed(this.getLineCount(), this._getCustomLineHeights());
                hadOtherModelChange = true;
                break;
              }
              case 3: {
                const linesDeletedEvent = this._lines.onModelLinesDeleted(versionId, change.fromLineNumber, change.toLineNumber);
                if (linesDeletedEvent !== null) {
                  eventsCollector.emitViewEvent(linesDeletedEvent);
                  this.viewLayout.onLinesDeleted(linesDeletedEvent.fromLineNumber, linesDeletedEvent.toLineNumber);
                }
                hadOtherModelChange = true;
                break;
              }
              case 4: {
                const insertedLineBreaks = lineBreakQueue.takeCount(change.detail.length);
                const linesInsertedEvent = this._lines.onModelLinesInserted(versionId, change.fromLineNumber, change.toLineNumber, insertedLineBreaks);
                if (linesInsertedEvent !== null) {
                  eventsCollector.emitViewEvent(linesInsertedEvent);
                  this.viewLayout.onLinesInserted(linesInsertedEvent.fromLineNumber, linesInsertedEvent.toLineNumber);
                }
                hadOtherModelChange = true;
                break;
              }
              case 2: {
                const changedLineBreakData = lineBreakQueue.dequeue();
                const [lineMappingChanged, linesChangedEvent, linesInsertedEvent, linesDeletedEvent] = this._lines.onModelLineChanged(versionId, change.lineNumber, changedLineBreakData);
                hadModelLineChangeThatChangedLineMapping = lineMappingChanged;
                if (linesChangedEvent) {
                  eventsCollector.emitViewEvent(linesChangedEvent);
                }
                if (linesInsertedEvent) {
                  eventsCollector.emitViewEvent(linesInsertedEvent);
                  this.viewLayout.onLinesInserted(linesInsertedEvent.fromLineNumber, linesInsertedEvent.toLineNumber);
                }
                if (linesDeletedEvent) {
                  eventsCollector.emitViewEvent(linesDeletedEvent);
                  this.viewLayout.onLinesDeleted(linesDeletedEvent.fromLineNumber, linesDeletedEvent.toLineNumber);
                }
                break;
              }
              case 5: {
                break;
              }
            }
          }
          if (versionId !== null) {
            this._lines.acceptVersionId(versionId);
          }
          this.viewLayout.onHeightMaybeChanged();
          if (!hadOtherModelChange && hadModelLineChangeThatChangedLineMapping) {
            eventsCollector.emitViewEvent(new ViewLineMappingChangedEvent());
            eventsCollector.emitViewEvent(new ViewDecorationsChangedEvent(null));
            this._cursor.onLineMappingChanged(eventsCollector);
            this._decorations.onLineMappingChanged();
          }
        } finally {
          this._eventDispatcher.endEmitViewEvents();
        }
        const viewportStartWasValid = this._viewportStart.isValid;
        this._viewportStart.invalidate();
        this._configuration.setModelLineCount(this.model.getLineCount());
        this._updateConfigurationViewLineCountNow();
        if (!this._hasFocus && this.model.getAttachedEditorCount() >= 2 && viewportStartWasValid) {
          const modelRange = this.model._getTrackedRange(this._viewportStart.modelTrackedRange);
          if (modelRange) {
            const viewPosition = this.coordinatesConverter.convertModelPositionToViewPosition(modelRange.getStartPosition());
            const viewPositionTop = this.viewLayout.getVerticalOffsetForLineNumber(viewPosition.lineNumber);
            this.viewLayout.setScrollPosition(
              { scrollTop: viewPositionTop + this._viewportStart.startLineDelta },
              1
              /* ScrollType.Immediate */
            );
          }
        }
        try {
          const eventsCollector = this._eventDispatcher.beginEmitViewEvents();
          if (e instanceof InternalModelContentChangeEvent) {
            eventsCollector.emitOutgoingEvent(new ModelContentChangedEvent(e.contentChangedEvent));
          }
          this._cursor.onModelContentChanged(eventsCollector, e);
        } finally {
          this._eventDispatcher.endEmitViewEvents();
        }
        this._handleVisibleLinesChanged();
      }));
      const allowVariableLineHeights = this._configuration.options.get(
        5
        /* EditorOption.allowVariableLineHeights */
      );
      if (allowVariableLineHeights) {
        this._register(this.model.onDidChangeLineHeight((e) => {
          const filteredChanges = e.changes.filter((change) => change.ownerId === this._editorId || change.ownerId === 0);
          this.viewLayout.changeSpecialLineHeights((accessor) => {
            for (const change of filteredChanges) {
              const { decorationId, lineNumber, lineHeight } = change;
              const viewRange = this.coordinatesConverter.convertModelRangeToViewRange(new Range$2(lineNumber, 1, lineNumber, this.model.getLineMaxColumn(lineNumber)));
              if (lineHeight !== null) {
                accessor.insertOrChangeCustomLineHeight(decorationId, viewRange.startLineNumber, viewRange.endLineNumber, lineHeight);
              } else {
                accessor.removeCustomLineHeight(decorationId);
              }
            }
          });
          if (filteredChanges.length > 0) {
            const filteredEvent = new ModelLineHeightChangedEvent$1(filteredChanges);
            this._eventDispatcher.emitOutgoingEvent(new ModelLineHeightChangedEvent(filteredEvent));
          }
        }));
      }
      const allowVariableFonts = this._configuration.options.get(
        172
        /* EditorOption.effectiveAllowVariableFonts */
      );
      if (allowVariableFonts) {
        this._register(this.model.onDidChangeFont((e) => {
          const filteredChanges = e.changes.filter((change) => change.ownerId === this._editorId || change.ownerId === 0);
          if (filteredChanges.length > 0) {
            const filteredEvent = new ModelFontChangedEvent$1(filteredChanges);
            this._eventDispatcher.emitOutgoingEvent(new ModelFontChangedEvent(filteredEvent));
          }
        }));
      }
      this._register(this.model.onDidChangeTokens((e) => {
        const viewRanges = [];
        for (let j = 0, lenJ = e.ranges.length; j < lenJ; j++) {
          const modelRange = e.ranges[j];
          const viewStartLineNumber = this.coordinatesConverter.convertModelPositionToViewPosition(new Position$1(modelRange.fromLineNumber, 1)).lineNumber;
          const viewEndLineNumber = this.coordinatesConverter.convertModelPositionToViewPosition(new Position$1(modelRange.toLineNumber, this.model.getLineMaxColumn(modelRange.toLineNumber))).lineNumber;
          viewRanges[j] = {
            fromLineNumber: viewStartLineNumber,
            toLineNumber: viewEndLineNumber
          };
        }
        this._eventDispatcher.emitSingleViewEvent(new ViewTokensChangedEvent(viewRanges));
        this._eventDispatcher.emitOutgoingEvent(new ModelTokensChangedEvent(e));
      }));
      this._register(this.model.onDidChangeLanguageConfiguration((e) => {
        this._eventDispatcher.emitSingleViewEvent(new ViewLanguageConfigurationEvent());
        this.cursorConfig = new CursorConfiguration(this.model.getLanguageId(), this.model.getOptions(), this._configuration, this.languageConfigurationService);
        this._cursor.updateConfiguration(this.cursorConfig);
        this._eventDispatcher.emitOutgoingEvent(new ModelLanguageConfigurationChangedEvent(e));
      }));
      this._register(this.model.onDidChangeLanguage((e) => {
        this.cursorConfig = new CursorConfiguration(this.model.getLanguageId(), this.model.getOptions(), this._configuration, this.languageConfigurationService);
        this._cursor.updateConfiguration(this.cursorConfig);
        this._eventDispatcher.emitOutgoingEvent(new ModelLanguageChangedEvent(e));
      }));
      this._register(this.model.onDidChangeOptions((e) => {
        if (this._lines.setTabSize(this.model.getOptions().tabSize)) {
          try {
            const eventsCollector = this._eventDispatcher.beginEmitViewEvents();
            eventsCollector.emitViewEvent(new ViewFlushedEvent());
            eventsCollector.emitViewEvent(new ViewLineMappingChangedEvent());
            eventsCollector.emitViewEvent(new ViewDecorationsChangedEvent(null));
            this._cursor.onLineMappingChanged(eventsCollector);
            this._decorations.onLineMappingChanged();
            this.viewLayout.onFlushed(this.getLineCount(), this._getCustomLineHeights());
          } finally {
            this._eventDispatcher.endEmitViewEvents();
          }
          this._updateConfigurationViewLineCount.schedule();
        }
        this.cursorConfig = new CursorConfiguration(this.model.getLanguageId(), this.model.getOptions(), this._configuration, this.languageConfigurationService);
        this._cursor.updateConfiguration(this.cursorConfig);
        this._eventDispatcher.emitOutgoingEvent(new ModelOptionsChangedEvent(e));
      }));
      this._register(this.model.onDidChangeDecorations((e) => {
        this._decorations.onModelDecorationsChanged();
        this._eventDispatcher.emitSingleViewEvent(new ViewDecorationsChangedEvent(e));
        this._eventDispatcher.emitOutgoingEvent(new ModelDecorationsChangedEvent(e));
      }));
    }
    getFontSizeAtPosition(position) {
      const allowVariableFonts = this._configuration.options.get(
        172
        /* EditorOption.effectiveAllowVariableFonts */
      );
      if (!allowVariableFonts) {
        return null;
      }
      const fontDecorations = this.model.getFontDecorationsInRange(Range$2.fromPositions(position), this._editorId);
      let fontSize = this._configuration.options.get(
        59
        /* EditorOption.fontInfo */
      ).fontSize + "px";
      for (const fontDecoration of fontDecorations) {
        if (fontDecoration.options.fontSize) {
          fontSize = fontDecoration.options.fontSize;
          break;
        }
      }
      return fontSize;
    }
    /**
     * @param forceUpdate If true, the hidden areas will be updated even if the new ranges are the same as the previous ranges.
     * This is because the model might have changed, which resets the hidden areas, but not the last cached value.
     * This needs a better fix in the future.
    */
    setHiddenAreas(ranges, source, forceUpdate) {
      this.hiddenAreasModel.setHiddenAreas(source, ranges);
      const mergedRanges = this.hiddenAreasModel.getMergedRanges();
      if (mergedRanges === this.previousHiddenAreas && !forceUpdate) {
        return;
      }
      this.previousHiddenAreas = mergedRanges;
      const stableViewport = this._captureStableViewport();
      let lineMappingChanged = false;
      try {
        const eventsCollector = this._eventDispatcher.beginEmitViewEvents();
        lineMappingChanged = this._lines.setHiddenAreas(mergedRanges);
        if (lineMappingChanged) {
          eventsCollector.emitViewEvent(new ViewFlushedEvent());
          eventsCollector.emitViewEvent(new ViewLineMappingChangedEvent());
          eventsCollector.emitViewEvent(new ViewDecorationsChangedEvent(null));
          this._cursor.onLineMappingChanged(eventsCollector);
          this._decorations.onLineMappingChanged();
          this.viewLayout.onFlushed(this.getLineCount(), this._getCustomLineHeights());
          this.viewLayout.onHeightMaybeChanged();
        }
        const firstModelLineInViewPort = stableViewport.viewportStartModelPosition?.lineNumber;
        const firstModelLineIsHidden = firstModelLineInViewPort && mergedRanges.some((range2) => range2.startLineNumber <= firstModelLineInViewPort && firstModelLineInViewPort <= range2.endLineNumber);
        if (!firstModelLineIsHidden) {
          stableViewport.recoverViewportStart(this.coordinatesConverter, this.viewLayout);
        }
      } finally {
        this._eventDispatcher.endEmitViewEvents();
      }
      this._updateConfigurationViewLineCount.schedule();
      if (lineMappingChanged) {
        this._eventDispatcher.emitOutgoingEvent(new HiddenAreasChangedEvent());
      }
    }
    getVisibleRangesPlusViewportAboveBelow() {
      const layoutInfo = this._configuration.options.get(
        165
        /* EditorOption.layoutInfo */
      );
      const lineHeight = this._configuration.options.get(
        75
        /* EditorOption.lineHeight */
      );
      const linesAround = Math.max(20, Math.round(layoutInfo.height / lineHeight));
      const partialData = this.viewLayout.getLinesViewportData();
      const startViewLineNumber = Math.max(1, partialData.completelyVisibleStartLineNumber - linesAround);
      const endViewLineNumber = Math.min(this.getLineCount(), partialData.completelyVisibleEndLineNumber + linesAround);
      return this._toModelVisibleRanges(new Range$2(startViewLineNumber, this.getLineMinColumn(startViewLineNumber), endViewLineNumber, this.getLineMaxColumn(endViewLineNumber)));
    }
    getVisibleRanges() {
      const visibleViewRange = this.getCompletelyVisibleViewRange();
      return this._toModelVisibleRanges(visibleViewRange);
    }
    getHiddenAreas() {
      return this._lines.getHiddenAreas();
    }
    _toModelVisibleRanges(visibleViewRange) {
      const visibleRange = this.coordinatesConverter.convertViewRangeToModelRange(visibleViewRange);
      const hiddenAreas = this._lines.getHiddenAreas();
      if (hiddenAreas.length === 0) {
        return [visibleRange];
      }
      const result = [];
      let resultLen = 0;
      let startLineNumber = visibleRange.startLineNumber;
      let startColumn = visibleRange.startColumn;
      const endLineNumber = visibleRange.endLineNumber;
      const endColumn = visibleRange.endColumn;
      for (let i2 = 0, len = hiddenAreas.length; i2 < len; i2++) {
        const hiddenStartLineNumber = hiddenAreas[i2].startLineNumber;
        const hiddenEndLineNumber = hiddenAreas[i2].endLineNumber;
        if (hiddenEndLineNumber < startLineNumber) {
          continue;
        }
        if (hiddenStartLineNumber > endLineNumber) {
          continue;
        }
        if (startLineNumber < hiddenStartLineNumber) {
          result[resultLen++] = new Range$2(startLineNumber, startColumn, hiddenStartLineNumber - 1, this.model.getLineMaxColumn(hiddenStartLineNumber - 1));
        }
        startLineNumber = hiddenEndLineNumber + 1;
        startColumn = 1;
      }
      if (startLineNumber < endLineNumber || startLineNumber === endLineNumber && startColumn < endColumn) {
        result[resultLen++] = new Range$2(startLineNumber, startColumn, endLineNumber, endColumn);
      }
      return result;
    }
    getCompletelyVisibleViewRange() {
      const partialData = this.viewLayout.getLinesViewportData();
      const startViewLineNumber = partialData.completelyVisibleStartLineNumber;
      const endViewLineNumber = partialData.completelyVisibleEndLineNumber;
      return new Range$2(startViewLineNumber, this.getLineMinColumn(startViewLineNumber), endViewLineNumber, this.getLineMaxColumn(endViewLineNumber));
    }
    getCompletelyVisibleViewRangeAtScrollTop(scrollTop) {
      const partialData = this.viewLayout.getLinesViewportDataAtScrollTop(scrollTop);
      const startViewLineNumber = partialData.completelyVisibleStartLineNumber;
      const endViewLineNumber = partialData.completelyVisibleEndLineNumber;
      return new Range$2(startViewLineNumber, this.getLineMinColumn(startViewLineNumber), endViewLineNumber, this.getLineMaxColumn(endViewLineNumber));
    }
    saveState() {
      const compatViewState = this.viewLayout.saveState();
      const scrollTop = compatViewState.scrollTop;
      const firstViewLineNumber = this.viewLayout.getLineNumberAtVerticalOffset(scrollTop);
      const firstPosition = this.coordinatesConverter.convertViewPositionToModelPosition(new Position$1(firstViewLineNumber, this.getLineMinColumn(firstViewLineNumber)));
      const firstPositionDeltaTop = this.viewLayout.getVerticalOffsetForLineNumber(firstViewLineNumber) - scrollTop;
      return {
        scrollLeft: compatViewState.scrollLeft,
        firstPosition,
        firstPositionDeltaTop
      };
    }
    reduceRestoreState(state) {
      if (typeof state.firstPosition === "undefined") {
        return this._reduceRestoreStateCompatibility(state);
      }
      const modelPosition = this.model.validatePosition(state.firstPosition);
      const viewPosition = this.coordinatesConverter.convertModelPositionToViewPosition(modelPosition);
      const scrollTop = this.viewLayout.getVerticalOffsetForLineNumber(viewPosition.lineNumber) - state.firstPositionDeltaTop;
      return {
        scrollLeft: state.scrollLeft,
        scrollTop
      };
    }
    _reduceRestoreStateCompatibility(state) {
      return {
        scrollLeft: state.scrollLeft,
        scrollTop: state.scrollTopWithoutViewZones
      };
    }
    getTabSize() {
      return this.model.getOptions().tabSize;
    }
    getLineCount() {
      return this._lines.getViewLineCount();
    }
    /**
     * Gives a hint that a lot of requests are about to come in for these line numbers.
     */
    setViewport(startLineNumber, endLineNumber, centeredLineNumber) {
      this._viewportStart.update(this, startLineNumber);
    }
    getActiveIndentGuide(lineNumber, minLineNumber, maxLineNumber) {
      return this._lines.getActiveIndentGuide(lineNumber, minLineNumber, maxLineNumber);
    }
    getLinesIndentGuides(startLineNumber, endLineNumber) {
      return this._lines.getViewLinesIndentGuides(startLineNumber, endLineNumber);
    }
    getBracketGuidesInRangeByLine(startLineNumber, endLineNumber, activePosition, options) {
      return this._lines.getViewLinesBracketGuides(startLineNumber, endLineNumber, activePosition, options);
    }
    getLineContent(lineNumber) {
      return this._lines.getViewLineContent(lineNumber);
    }
    getLineLength(lineNumber) {
      return this._lines.getViewLineLength(lineNumber);
    }
    getLineMinColumn(lineNumber) {
      return this._lines.getViewLineMinColumn(lineNumber);
    }
    getLineMaxColumn(lineNumber) {
      return this._lines.getViewLineMaxColumn(lineNumber);
    }
    getLineFirstNonWhitespaceColumn(lineNumber) {
      const result = firstNonWhitespaceIndex(this.getLineContent(lineNumber));
      if (result === -1) {
        return 0;
      }
      return result + 1;
    }
    getLineLastNonWhitespaceColumn(lineNumber) {
      const result = lastNonWhitespaceIndex(this.getLineContent(lineNumber));
      if (result === -1) {
        return 0;
      }
      return result + 2;
    }
    getMinimapDecorationsInRange(range2) {
      return this._decorations.getMinimapDecorationsInRange(range2);
    }
    getDecorationsInViewport(visibleRange) {
      return this._decorations.getDecorationsViewportData(visibleRange).decorations;
    }
    getInjectedTextAt(viewPosition) {
      return this._lines.getInjectedTextAt(viewPosition);
    }
    _getTextDirection(lineNumber, decorations) {
      let rtlCount = 0;
      for (const decoration2 of decorations) {
        const range2 = decoration2.range;
        if (range2.startLineNumber > lineNumber || range2.endLineNumber < lineNumber) {
          continue;
        }
        const textDirection = decoration2.options.textDirection;
        if (textDirection === TextDirection$1.RTL) {
          rtlCount++;
        } else if (textDirection === TextDirection$1.LTR) {
          rtlCount--;
        }
      }
      return rtlCount > 0 ? TextDirection$1.RTL : TextDirection$1.LTR;
    }
    getTextDirection(lineNumber) {
      const decorationsCollection = this._decorations.getDecorationsOnLine(lineNumber);
      return this._getTextDirection(lineNumber, decorationsCollection.decorations);
    }
    getViewportViewLineRenderingData(visibleRange, lineNumber) {
      const viewportDecorationsCollection = this._decorations.getDecorationsViewportData(visibleRange);
      const inlineDecorations = viewportDecorationsCollection.inlineDecorations[lineNumber - visibleRange.startLineNumber];
      return this._getViewLineRenderingData(lineNumber, inlineDecorations, viewportDecorationsCollection.hasVariableFonts, viewportDecorationsCollection.decorations);
    }
    getViewLineRenderingData(lineNumber) {
      const decorationsCollection = this._decorations.getDecorationsOnLine(lineNumber);
      return this._getViewLineRenderingData(lineNumber, decorationsCollection.inlineDecorations[0], decorationsCollection.hasVariableFonts, decorationsCollection.decorations);
    }
    _getViewLineRenderingData(lineNumber, inlineDecorations, hasVariableFonts, decorations) {
      const mightContainRTL = this.model.mightContainRTL();
      const mightContainNonBasicASCII = this.model.mightContainNonBasicASCII();
      const tabSize = this.getTabSize();
      const lineData = this._lines.getViewLineData(lineNumber);
      if (lineData.inlineDecorations) {
        inlineDecorations = [
          ...inlineDecorations,
          ...lineData.inlineDecorations.map((d) => d.toInlineDecoration(lineNumber))
        ];
      }
      return new ViewLineRenderingData(lineData.minColumn, lineData.maxColumn, lineData.content, lineData.continuesWithWrappedLine, mightContainRTL, mightContainNonBasicASCII, lineData.tokens, inlineDecorations, tabSize, lineData.startVisibleColumn, this._getTextDirection(lineNumber, decorations), hasVariableFonts);
    }
    getViewLineData(lineNumber) {
      return this._lines.getViewLineData(lineNumber);
    }
    getMinimapLinesRenderingData(startLineNumber, endLineNumber, needed) {
      const result = this._lines.getViewLinesData(startLineNumber, endLineNumber, needed);
      return new MinimapLinesRenderingData(this.getTabSize(), result);
    }
    getAllOverviewRulerDecorations(theme) {
      const decorations = this.model.getOverviewRulerDecorations(this._editorId, filterValidationDecorations(this._configuration.options), filterFontDecorations(this._configuration.options));
      const result = new OverviewRulerDecorations();
      for (const decoration2 of decorations) {
        const decorationOptions = decoration2.options;
        const opts = decorationOptions.overviewRuler;
        if (!opts) {
          continue;
        }
        const lane = opts.position;
        if (lane === 0) {
          continue;
        }
        const color = opts.getColor(theme.value);
        const viewStartLineNumber = this.coordinatesConverter.getViewLineNumberOfModelPosition(decoration2.range.startLineNumber, decoration2.range.startColumn);
        const viewEndLineNumber = this.coordinatesConverter.getViewLineNumberOfModelPosition(decoration2.range.endLineNumber, decoration2.range.endColumn);
        result.accept(color, decorationOptions.zIndex, viewStartLineNumber, viewEndLineNumber, lane);
      }
      return result.asArray;
    }
    _invalidateDecorationsColorCache() {
      const decorations = this.model.getOverviewRulerDecorations();
      for (const decoration2 of decorations) {
        const opts1 = decoration2.options.overviewRuler;
        opts1?.invalidateCachedColor();
        const opts2 = decoration2.options.minimap;
        opts2?.invalidateCachedColor();
      }
    }
    getValueInRange(range2, eol) {
      const modelRange = this.coordinatesConverter.convertViewRangeToModelRange(range2);
      return this.model.getValueInRange(modelRange, eol);
    }
    getValueLengthInRange(range2, eol) {
      const modelRange = this.coordinatesConverter.convertViewRangeToModelRange(range2);
      return this.model.getValueLengthInRange(modelRange, eol);
    }
    modifyPosition(position, offset) {
      const modelPosition = this.coordinatesConverter.convertViewPositionToModelPosition(position);
      const resultModelPosition = this.model.modifyPosition(modelPosition, offset);
      return this.coordinatesConverter.convertModelPositionToViewPosition(resultModelPosition);
    }
    deduceModelPositionRelativeToViewPosition(viewAnchorPosition, deltaOffset, lineFeedCnt) {
      const modelAnchor = this.coordinatesConverter.convertViewPositionToModelPosition(viewAnchorPosition);
      if (this.model.getEOL().length === 2) {
        if (deltaOffset < 0) {
          deltaOffset -= lineFeedCnt;
        } else {
          deltaOffset += lineFeedCnt;
        }
      }
      const modelAnchorOffset = this.model.getOffsetAt(modelAnchor);
      const resultOffset = modelAnchorOffset + deltaOffset;
      return this.model.getPositionAt(resultOffset);
    }
    getPlainTextToCopy(modelRanges, emptySelectionClipboard, forceCRLF) {
      const newLineCharacter = forceCRLF ? "\r\n" : this.model.getEOL();
      modelRanges = modelRanges.slice(0);
      modelRanges.sort(Range$2.compareRangesUsingStarts);
      let hasEmptyRange = false;
      let hasNonEmptyRange = false;
      for (const range2 of modelRanges) {
        if (range2.isEmpty()) {
          hasEmptyRange = true;
        } else {
          hasNonEmptyRange = true;
        }
      }
      if (!hasNonEmptyRange) {
        if (!emptySelectionClipboard) {
          return "";
        }
        const modelLineNumbers = modelRanges.map((r) => r.startLineNumber);
        let result2 = "";
        for (let i2 = 0; i2 < modelLineNumbers.length; i2++) {
          if (i2 > 0 && modelLineNumbers[i2 - 1] === modelLineNumbers[i2]) {
            continue;
          }
          result2 += this.model.getLineContent(modelLineNumbers[i2]) + newLineCharacter;
        }
        return result2;
      }
      if (hasEmptyRange && emptySelectionClipboard) {
        const result2 = [];
        let prevModelLineNumber = 0;
        for (const modelRange of modelRanges) {
          const modelLineNumber = modelRange.startLineNumber;
          if (modelRange.isEmpty()) {
            if (modelLineNumber !== prevModelLineNumber) {
              result2.push(this.model.getLineContent(modelLineNumber));
            }
          } else {
            result2.push(this.model.getValueInRange(
              modelRange,
              forceCRLF ? 2 : 0
              /* EndOfLinePreference.TextDefined */
            ));
          }
          prevModelLineNumber = modelLineNumber;
        }
        return result2.length === 1 ? result2[0] : result2;
      }
      const result = [];
      for (const modelRange of modelRanges) {
        if (!modelRange.isEmpty()) {
          result.push(this.model.getValueInRange(
            modelRange,
            forceCRLF ? 2 : 0
            /* EndOfLinePreference.TextDefined */
          ));
        }
      }
      return result.length === 1 ? result[0] : result;
    }
    getRichTextToCopy(modelRanges, emptySelectionClipboard) {
      const languageId = this.model.getLanguageId();
      if (languageId === PLAINTEXT_LANGUAGE_ID) {
        return null;
      }
      if (modelRanges.length !== 1) {
        return null;
      }
      let range2 = modelRanges[0];
      if (range2.isEmpty()) {
        if (!emptySelectionClipboard) {
          return null;
        }
        const lineNumber = range2.startLineNumber;
        range2 = new Range$2(lineNumber, this.model.getLineMinColumn(lineNumber), lineNumber, this.model.getLineMaxColumn(lineNumber));
      }
      const fontInfo = this._configuration.options.get(
        59
        /* EditorOption.fontInfo */
      );
      const colorMap = this._getColorMap();
      const hasBadChars = /[:;\\\/<>]/.test(fontInfo.fontFamily);
      const useDefaultFontFamily = hasBadChars || fontInfo.fontFamily === EDITOR_FONT_DEFAULTS.fontFamily;
      let fontFamily;
      if (useDefaultFontFamily) {
        fontFamily = EDITOR_FONT_DEFAULTS.fontFamily;
      } else {
        fontFamily = fontInfo.fontFamily;
        fontFamily = fontFamily.replace(/"/g, "'");
        const hasQuotesOrIsList = /[,']/.test(fontFamily);
        if (!hasQuotesOrIsList) {
          const needsQuotes = /[+ ]/.test(fontFamily);
          if (needsQuotes) {
            fontFamily = `'${fontFamily}'`;
          }
        }
        fontFamily = `${fontFamily}, ${EDITOR_FONT_DEFAULTS.fontFamily}`;
      }
      return {
        mode: languageId,
        html: `<div style="color: ${colorMap[
          1
          /* ColorId.DefaultForeground */
        ]};background-color: ${colorMap[
          2
          /* ColorId.DefaultBackground */
        ]};font-family: ${fontFamily};font-weight: ${fontInfo.fontWeight};font-size: ${fontInfo.fontSize}px;line-height: ${fontInfo.lineHeight}px;white-space: pre;">` + this._getHTMLToCopy(range2, colorMap) + "</div>"
      };
    }
    _getHTMLToCopy(modelRange, colorMap) {
      const startLineNumber = modelRange.startLineNumber;
      const startColumn = modelRange.startColumn;
      const endLineNumber = modelRange.endLineNumber;
      const endColumn = modelRange.endColumn;
      const tabSize = this.getTabSize();
      let result = "";
      for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
        const lineTokens = this.model.tokenization.getLineTokens(lineNumber);
        const lineContent = lineTokens.getLineContent();
        const startOffset = lineNumber === startLineNumber ? startColumn - 1 : 0;
        const endOffset = lineNumber === endLineNumber ? endColumn - 1 : lineContent.length;
        if (lineContent === "") {
          result += "<br>";
        } else {
          result += tokenizeLineToHTML(lineContent, lineTokens.inflate(), colorMap, startOffset, endOffset, tabSize, isWindows);
        }
      }
      return result;
    }
    _getColorMap() {
      const colorMap = TokenizationRegistry.getColorMap();
      const result = ["#000000"];
      if (colorMap) {
        for (let i2 = 1, len = colorMap.length; i2 < len; i2++) {
          result[i2] = Color.Format.CSS.formatHex(colorMap[i2]);
        }
      }
      return result;
    }
    //#region cursor operations
    getPrimaryCursorState() {
      return this._cursor.getPrimaryCursorState();
    }
    getLastAddedCursorIndex() {
      return this._cursor.getLastAddedCursorIndex();
    }
    getCursorStates() {
      return this._cursor.getCursorStates();
    }
    setCursorStates(source, reason, states) {
      return this._withViewEventsCollector((eventsCollector) => this._cursor.setStates(eventsCollector, source, reason, states));
    }
    getCursorColumnSelectData() {
      return this._cursor.getCursorColumnSelectData();
    }
    getCursorAutoClosedCharacters() {
      return this._cursor.getAutoClosedCharacters();
    }
    setCursorColumnSelectData(columnSelectData) {
      this._cursor.setCursorColumnSelectData(columnSelectData);
    }
    getPrevEditOperationType() {
      return this._cursor.getPrevEditOperationType();
    }
    setPrevEditOperationType(type) {
      this._cursor.setPrevEditOperationType(type);
    }
    getSelection() {
      return this._cursor.getSelection();
    }
    getSelections() {
      return this._cursor.getSelections();
    }
    getPosition() {
      return this._cursor.getPrimaryCursorState().modelState.position;
    }
    setSelections(source, selections, reason = 0) {
      this._withViewEventsCollector((eventsCollector) => this._cursor.setSelections(eventsCollector, source, selections, reason));
    }
    saveCursorState() {
      return this._cursor.saveState();
    }
    restoreCursorState(states) {
      this._withViewEventsCollector((eventsCollector) => this._cursor.restoreState(eventsCollector, states));
    }
    _executeCursorEdit(callback) {
      if (this._cursor.context.cursorConfig.readOnly) {
        this._eventDispatcher.emitOutgoingEvent(new ReadOnlyEditAttemptEvent());
        return;
      }
      this._withViewEventsCollector(callback);
    }
    executeEdits(source, edits, cursorStateComputer, reason) {
      this._executeCursorEdit((eventsCollector) => this._cursor.executeEdits(eventsCollector, source, edits, cursorStateComputer, reason));
    }
    startComposition() {
      this._executeCursorEdit((eventsCollector) => this._cursor.startComposition(eventsCollector));
    }
    endComposition(source) {
      this._executeCursorEdit((eventsCollector) => this._cursor.endComposition(eventsCollector, source));
    }
    type(text2, source) {
      this._executeCursorEdit((eventsCollector) => this._cursor.type(eventsCollector, text2, source));
    }
    compositionType(text2, replacePrevCharCnt, replaceNextCharCnt, positionDelta, source) {
      this._executeCursorEdit((eventsCollector) => this._cursor.compositionType(eventsCollector, text2, replacePrevCharCnt, replaceNextCharCnt, positionDelta, source));
    }
    paste(text2, pasteOnNewLine, multicursorText, source) {
      this._executeCursorEdit((eventsCollector) => this._cursor.paste(eventsCollector, text2, pasteOnNewLine, multicursorText, source));
    }
    cut(source) {
      this._executeCursorEdit((eventsCollector) => this._cursor.cut(eventsCollector, source));
    }
    executeCommand(command, source) {
      this._executeCursorEdit((eventsCollector) => this._cursor.executeCommand(eventsCollector, command, source));
    }
    executeCommands(commands, source) {
      this._executeCursorEdit((eventsCollector) => this._cursor.executeCommands(eventsCollector, commands, source));
    }
    revealAllCursors(source, revealHorizontal, minimalReveal = false) {
      this._withViewEventsCollector((eventsCollector) => this._cursor.revealAll(
        eventsCollector,
        source,
        minimalReveal,
        0,
        revealHorizontal,
        0
        /* ScrollType.Smooth */
      ));
    }
    revealPrimaryCursor(source, revealHorizontal, minimalReveal = false) {
      this._withViewEventsCollector((eventsCollector) => this._cursor.revealPrimary(
        eventsCollector,
        source,
        minimalReveal,
        0,
        revealHorizontal,
        0
        /* ScrollType.Smooth */
      ));
    }
    revealTopMostCursor(source) {
      const viewPosition = this._cursor.getTopMostViewPosition();
      const viewRange = new Range$2(viewPosition.lineNumber, viewPosition.column, viewPosition.lineNumber, viewPosition.column);
      this._withViewEventsCollector((eventsCollector) => eventsCollector.emitViewEvent(new ViewRevealRangeRequestEvent(
        source,
        false,
        viewRange,
        null,
        0,
        true,
        0
        /* ScrollType.Smooth */
      )));
    }
    revealBottomMostCursor(source) {
      const viewPosition = this._cursor.getBottomMostViewPosition();
      const viewRange = new Range$2(viewPosition.lineNumber, viewPosition.column, viewPosition.lineNumber, viewPosition.column);
      this._withViewEventsCollector((eventsCollector) => eventsCollector.emitViewEvent(new ViewRevealRangeRequestEvent(
        source,
        false,
        viewRange,
        null,
        0,
        true,
        0
        /* ScrollType.Smooth */
      )));
    }
    revealRange(source, revealHorizontal, viewRange, verticalType, scrollType) {
      this._withViewEventsCollector((eventsCollector) => eventsCollector.emitViewEvent(new ViewRevealRangeRequestEvent(source, false, viewRange, null, verticalType, revealHorizontal, scrollType)));
    }
    //#endregion
    //#region viewLayout
    changeWhitespace(callback) {
      const hadAChange = this.viewLayout.changeWhitespace(callback);
      if (hadAChange) {
        this._eventDispatcher.emitSingleViewEvent(new ViewZonesChangedEvent$1());
        this._eventDispatcher.emitOutgoingEvent(new ViewZonesChangedEvent());
      }
    }
    //#endregion
    _withViewEventsCollector(callback) {
      return this._transactionalTarget.batchChanges(() => {
        try {
          const eventsCollector = this._eventDispatcher.beginEmitViewEvents();
          return callback(eventsCollector);
        } finally {
          this._eventDispatcher.endEmitViewEvents();
        }
      });
    }
    batchEvents(callback) {
      this._withViewEventsCollector(() => {
        callback();
      });
    }
    normalizePosition(position, affinity) {
      return this._lines.normalizePosition(position, affinity);
    }
    /**
     * Gets the column at which indentation stops at a given line.
     * @internal
    */
    getLineIndentColumn(lineNumber) {
      return this._lines.getLineIndentColumn(lineNumber);
    }
  };
  class ViewportStart {
    static create(model) {
      const viewportStartLineTrackedRange = model._setTrackedRange(
        null,
        new Range$2(1, 1, 1, 1),
        1
        /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */
      );
      return new ViewportStart(model, 1, false, viewportStartLineTrackedRange, 0);
    }
    get viewLineNumber() {
      return this._viewLineNumber;
    }
    get isValid() {
      return this._isValid;
    }
    get modelTrackedRange() {
      return this._modelTrackedRange;
    }
    get startLineDelta() {
      return this._startLineDelta;
    }
    constructor(_model, _viewLineNumber, _isValid, _modelTrackedRange, _startLineDelta) {
      this._model = _model;
      this._viewLineNumber = _viewLineNumber;
      this._isValid = _isValid;
      this._modelTrackedRange = _modelTrackedRange;
      this._startLineDelta = _startLineDelta;
    }
    dispose() {
      this._model._setTrackedRange(
        this._modelTrackedRange,
        null,
        1
        /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */
      );
    }
    update(viewModel, startLineNumber) {
      const position = viewModel.coordinatesConverter.convertViewPositionToModelPosition(new Position$1(startLineNumber, viewModel.getLineMinColumn(startLineNumber)));
      const viewportStartLineTrackedRange = viewModel.model._setTrackedRange(
        this._modelTrackedRange,
        new Range$2(position.lineNumber, position.column, position.lineNumber, position.column),
        1
        /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */
      );
      const viewportStartLineTop = viewModel.viewLayout.getVerticalOffsetForLineNumber(startLineNumber);
      const scrollTop = viewModel.viewLayout.getCurrentScrollTop();
      this._viewLineNumber = startLineNumber;
      this._isValid = true;
      this._modelTrackedRange = viewportStartLineTrackedRange;
      this._startLineDelta = scrollTop - viewportStartLineTop;
    }
    invalidate() {
      this._isValid = false;
    }
  }
  class OverviewRulerDecorations {
    constructor() {
      this._asMap = /* @__PURE__ */ Object.create(null);
      this.asArray = [];
    }
    accept(color, zIndex, startLineNumber, endLineNumber, lane) {
      const prevGroup = this._asMap[color];
      if (prevGroup) {
        const prevData = prevGroup.data;
        const prevLane = prevData[prevData.length - 3];
        const prevEndLineNumber = prevData[prevData.length - 1];
        if (prevLane === lane && prevEndLineNumber + 1 >= startLineNumber) {
          if (endLineNumber > prevEndLineNumber) {
            prevData[prevData.length - 1] = endLineNumber;
          }
          return;
        }
        prevData.push(lane, startLineNumber, endLineNumber);
      } else {
        const group = new OverviewRulerDecorationsGroup(color, zIndex, [lane, startLineNumber, endLineNumber]);
        this._asMap[color] = group;
        this.asArray.push(group);
      }
    }
  }
  class HiddenAreasModel {
    constructor() {
      this.hiddenAreas = /* @__PURE__ */ new Map();
      this.shouldRecompute = false;
      this.ranges = [];
    }
    setHiddenAreas(source, ranges) {
      const existing = this.hiddenAreas.get(source);
      if (existing && rangeArraysEqual(existing, ranges)) {
        return;
      }
      this.hiddenAreas.set(source, ranges);
      this.shouldRecompute = true;
    }
    /**
     * The returned array is immutable.
    */
    getMergedRanges() {
      if (!this.shouldRecompute) {
        return this.ranges;
      }
      this.shouldRecompute = false;
      const newRanges = Array.from(this.hiddenAreas.values()).reduce((r, hiddenAreas) => mergeLineRangeArray(r, hiddenAreas), []);
      if (rangeArraysEqual(this.ranges, newRanges)) {
        return this.ranges;
      }
      this.ranges = newRanges;
      return this.ranges;
    }
  }
  function mergeLineRangeArray(arr1, arr2) {
    const result = [];
    let i2 = 0;
    let j = 0;
    while (i2 < arr1.length && j < arr2.length) {
      const item1 = arr1[i2];
      const item2 = arr2[j];
      if (item1.endLineNumber < item2.startLineNumber - 1) {
        result.push(arr1[i2++]);
      } else if (item2.endLineNumber < item1.startLineNumber - 1) {
        result.push(arr2[j++]);
      } else {
        const startLineNumber = Math.min(item1.startLineNumber, item2.startLineNumber);
        const endLineNumber = Math.max(item1.endLineNumber, item2.endLineNumber);
        result.push(new Range$2(startLineNumber, 1, endLineNumber, 1));
        i2++;
        j++;
      }
    }
    while (i2 < arr1.length) {
      result.push(arr1[i2++]);
    }
    while (j < arr2.length) {
      result.push(arr2[j++]);
    }
    return result;
  }
  function rangeArraysEqual(arr1, arr2) {
    if (arr1.length !== arr2.length) {
      return false;
    }
    for (let i2 = 0; i2 < arr1.length; i2++) {
      if (!arr1[i2].equalsRange(arr2[i2])) {
        return false;
      }
    }
    return true;
  }
  class StableViewport {
    constructor(viewportStartModelPosition, startLineDelta) {
      this.viewportStartModelPosition = viewportStartModelPosition;
      this.startLineDelta = startLineDelta;
    }
    recoverViewportStart(coordinatesConverter, viewLayout) {
      if (!this.viewportStartModelPosition) {
        return;
      }
      const viewPosition = coordinatesConverter.convertModelPositionToViewPosition(this.viewportStartModelPosition);
      const viewPositionTop = viewLayout.getVerticalOffsetForLineNumber(viewPosition.lineNumber);
      viewLayout.setScrollPosition(
        { scrollTop: viewPositionTop + this.startLineDelta },
        1
        /* ScrollType.Immediate */
      );
    }
  }
  class ServiceCollection {
    constructor(...entries2) {
      this._entries = /* @__PURE__ */ new Map();
      for (const [id, service] of entries2) {
        this.set(id, service);
      }
    }
    set(id, instanceOrDescriptor) {
      const result = this._entries.get(id);
      this._entries.set(id, instanceOrDescriptor);
      return result;
    }
    get(id) {
      return this._entries.get(id);
    }
  }
  var __decorate$2K = 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$2F = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  var CodeEditorWidget_1;
  let CodeEditorWidget = (_j = class extends Disposable {
    //#endregion
    get isSimpleWidget() {
      return this._configuration.isSimpleWidget;
    }
    get contextMenuId() {
      return this._configuration.contextMenuId;
    }
    get contextKeyService() {
      return this._contextKeyService;
    }
    constructor(domElement, _options, codeEditorWidgetOptions, instantiationService, codeEditorService, commandService, contextKeyService, themeService, notificationService, accessibilityService, languageConfigurationService, languageFeaturesService) {
      super();
      this.languageConfigurationService = languageConfigurationService;
      this._deliveryQueue = createEventDeliveryQueue();
      this._contributions = this._register(new CodeEditorContributions());
      this._onDidDispose = this._register(new Emitter$1());
      this.onDidDispose = this._onDidDispose.event;
      this._onDidChangeModelContent = this._register(new Emitter$1({ deliveryQueue: this._deliveryQueue }));
      this.onDidChangeModelContent = this._onDidChangeModelContent.event;
      this._onDidChangeModelLanguage = this._register(new Emitter$1({ deliveryQueue: this._deliveryQueue }));
      this.onDidChangeModelLanguage = this._onDidChangeModelLanguage.event;
      this._onDidChangeModelLanguageConfiguration = this._register(new Emitter$1({ deliveryQueue: this._deliveryQueue }));
      this.onDidChangeModelLanguageConfiguration = this._onDidChangeModelLanguageConfiguration.event;
      this._onDidChangeModelOptions = this._register(new Emitter$1({ deliveryQueue: this._deliveryQueue }));
      this.onDidChangeModelOptions = this._onDidChangeModelOptions.event;
      this._onDidChangeModelDecorations = this._register(new Emitter$1({ deliveryQueue: this._deliveryQueue }));
      this.onDidChangeModelDecorations = this._onDidChangeModelDecorations.event;
      this._onDidChangeLineHeight = this._register(new Emitter$1({ deliveryQueue: this._deliveryQueue }));
      this.onDidChangeLineHeight = this._onDidChangeLineHeight.event;
      this._onDidChangeFont = this._register(new Emitter$1({ deliveryQueue: this._deliveryQueue }));
      this.onDidChangeFont = this._onDidChangeFont.event;
      this._onDidChangeModelTokens = this._register(new Emitter$1({ deliveryQueue: this._deliveryQueue }));
      this.onDidChangeModelTokens = this._onDidChangeModelTokens.event;
      this._onDidChangeConfiguration = this._register(new Emitter$1({ deliveryQueue: this._deliveryQueue }));
      this.onDidChangeConfiguration = this._onDidChangeConfiguration.event;
      this._onWillChangeModel = this._register(new Emitter$1({ deliveryQueue: this._deliveryQueue }));
      this.onWillChangeModel = this._onWillChangeModel.event;
      this._onDidChangeModel = this._register(new Emitter$1({ deliveryQueue: this._deliveryQueue }));
      this.onDidChangeModel = this._onDidChangeModel.event;
      this._onDidChangeCursorPosition = this._register(new Emitter$1({ deliveryQueue: this._deliveryQueue }));
      this.onDidChangeCursorPosition = this._onDidChangeCursorPosition.event;
      this._onDidChangeCursorSelection = this._register(new Emitter$1({ deliveryQueue: this._deliveryQueue }));
      this.onDidChangeCursorSelection = this._onDidChangeCursorSelection.event;
      this._onDidAttemptReadOnlyEdit = this._register(new InteractionEmitter(this._contributions, this._deliveryQueue));
      this.onDidAttemptReadOnlyEdit = this._onDidAttemptReadOnlyEdit.event;
      this._onDidLayoutChange = this._register(new Emitter$1({ deliveryQueue: this._deliveryQueue }));
      this.onDidLayoutChange = this._onDidLayoutChange.event;
      this._editorTextFocus = this._register(new BooleanEventEmitter({ deliveryQueue: this._deliveryQueue }));
      this.onDidFocusEditorText = this._editorTextFocus.onDidChangeToTrue;
      this.onDidBlurEditorText = this._editorTextFocus.onDidChangeToFalse;
      this._editorWidgetFocus = this._register(new BooleanEventEmitter({ deliveryQueue: this._deliveryQueue }));
      this.onDidFocusEditorWidget = this._editorWidgetFocus.onDidChangeToTrue;
      this.onDidBlurEditorWidget = this._editorWidgetFocus.onDidChangeToFalse;
      this._onWillType = this._register(new InteractionEmitter(this._contributions, this._deliveryQueue));
      this.onWillType = this._onWillType.event;
      this._onDidType = this._register(new InteractionEmitter(this._contributions, this._deliveryQueue));
      this.onDidType = this._onDidType.event;
      this._onDidCompositionStart = this._register(new InteractionEmitter(this._contributions, this._deliveryQueue));
      this.onDidCompositionStart = this._onDidCompositionStart.event;
      this._onDidCompositionEnd = this._register(new InteractionEmitter(this._contributions, this._deliveryQueue));
      this.onDidCompositionEnd = this._onDidCompositionEnd.event;
      this._onDidPaste = this._register(new InteractionEmitter(this._contributions, this._deliveryQueue));
      this.onDidPaste = this._onDidPaste.event;
      this._onMouseUp = this._register(new InteractionEmitter(this._contributions, this._deliveryQueue));
      this.onMouseUp = this._onMouseUp.event;
      this._onMouseDown = this._register(new InteractionEmitter(this._contributions, this._deliveryQueue));
      this.onMouseDown = this._onMouseDown.event;
      this._onMouseDrag = this._register(new InteractionEmitter(this._contributions, this._deliveryQueue));
      this.onMouseDrag = this._onMouseDrag.event;
      this._onMouseDrop = this._register(new InteractionEmitter(this._contributions, this._deliveryQueue));
      this.onMouseDrop = this._onMouseDrop.event;
      this._onMouseDropCanceled = this._register(new InteractionEmitter(this._contributions, this._deliveryQueue));
      this.onMouseDropCanceled = this._onMouseDropCanceled.event;
      this._onDropIntoEditor = this._register(new InteractionEmitter(this._contributions, this._deliveryQueue));
      this.onDropIntoEditor = this._onDropIntoEditor.event;
      this._onContextMenu = this._register(new InteractionEmitter(this._contributions, this._deliveryQueue));
      this.onContextMenu = this._onContextMenu.event;
      this._onMouseMove = this._register(new InteractionEmitter(this._contributions, this._deliveryQueue));
      this.onMouseMove = this._onMouseMove.event;
      this._onMouseLeave = this._register(new InteractionEmitter(this._contributions, this._deliveryQueue));
      this.onMouseLeave = this._onMouseLeave.event;
      this._onMouseWheel = this._register(new InteractionEmitter(this._contributions, this._deliveryQueue));
      this.onMouseWheel = this._onMouseWheel.event;
      this._onKeyUp = this._register(new InteractionEmitter(this._contributions, this._deliveryQueue));
      this.onKeyUp = this._onKeyUp.event;
      this._onKeyDown = this._register(new InteractionEmitter(this._contributions, this._deliveryQueue));
      this.onKeyDown = this._onKeyDown.event;
      this._onDidContentSizeChange = this._register(new Emitter$1({ deliveryQueue: this._deliveryQueue }));
      this.onDidContentSizeChange = this._onDidContentSizeChange.event;
      this._onDidScrollChange = this._register(new Emitter$1({ deliveryQueue: this._deliveryQueue }));
      this.onDidScrollChange = this._onDidScrollChange.event;
      this._onDidChangeViewZones = this._register(new Emitter$1({ deliveryQueue: this._deliveryQueue }));
      this.onDidChangeViewZones = this._onDidChangeViewZones.event;
      this._onDidChangeHiddenAreas = this._register(new Emitter$1({ deliveryQueue: this._deliveryQueue }));
      this.onDidChangeHiddenAreas = this._onDidChangeHiddenAreas.event;
      this._updateCounter = 0;
      this._onWillTriggerEditorOperationEvent = this._register(new Emitter$1());
      this._onBeginUpdate = this._register(new Emitter$1());
      this.onBeginUpdate = this._onBeginUpdate.event;
      this._onEndUpdate = this._register(new Emitter$1());
      this.onEndUpdate = this._onEndUpdate.event;
      this._onBeforeExecuteEdit = this._register(new Emitter$1());
      this.onBeforeExecuteEdit = this._onBeforeExecuteEdit.event;
      this._actions = /* @__PURE__ */ new Map();
      this._bannerDomNode = null;
      this._dropIntoEditorDecorations = this.createDecorationsCollection();
      this.inComposition = false;
      codeEditorService.willCreateCodeEditor();
      const options = { ..._options };
      this._domElement = domElement;
      this._overflowWidgetsDomNode = options.overflowWidgetsDomNode;
      delete options.overflowWidgetsDomNode;
      this._id = ++EDITOR_ID;
      this._decorationTypeKeysToIds = {};
      this._decorationTypeSubtypes = {};
      this._telemetryData = codeEditorWidgetOptions.telemetryData;
      this._configuration = this._register(this._createConfiguration(codeEditorWidgetOptions.isSimpleWidget || false, codeEditorWidgetOptions.contextMenuId ?? (codeEditorWidgetOptions.isSimpleWidget ? MenuId.SimpleEditorContext : MenuId.EditorContext), options, accessibilityService));
      this._register(this._configuration.onDidChange((e) => {
        this._onDidChangeConfiguration.fire(e);
        const options2 = this._configuration.options;
        if (e.hasChanged(
          165
          /* EditorOption.layoutInfo */
        )) {
          const layoutInfo = options2.get(
            165
            /* EditorOption.layoutInfo */
          );
          this._onDidLayoutChange.fire(layoutInfo);
        }
      }));
      this._contextKeyService = this._register(contextKeyService.createScoped(this._domElement));
      if (codeEditorWidgetOptions.contextKeyValues) {
        for (const [key, value] of Object.entries(codeEditorWidgetOptions.contextKeyValues)) {
          this._contextKeyService.createKey(key, value);
        }
      }
      this._notificationService = notificationService;
      this._codeEditorService = codeEditorService;
      this._commandService = commandService;
      this._themeService = themeService;
      this._register(new EditorContextKeysManager(this, this._contextKeyService));
      this._register(new EditorModeContext(this, this._contextKeyService, languageFeaturesService));
      this._instantiationService = this._register(instantiationService.createChild(new ServiceCollection([IContextKeyService, this._contextKeyService])));
      this._modelData = null;
      this._contentWidgets = {};
      this._overlayWidgets = {};
      this._glyphMarginWidgets = {};
      let contributions;
      if (Array.isArray(codeEditorWidgetOptions.contributions)) {
        contributions = codeEditorWidgetOptions.contributions;
      } else {
        contributions = EditorExtensionsRegistry.getEditorContributions();
      }
      this._contributions.initialize(this, contributions, this._instantiationService);
      for (const action of EditorExtensionsRegistry.getEditorActions()) {
        if (this._actions.has(action.id)) {
          onUnexpectedError(new Error(`Cannot have two actions with the same id ${action.id}`));
          continue;
        }
        const internalAction = new InternalEditorAction(action.id, action.label, action.alias, action.metadata, action.precondition ?? void 0, (args) => {
          return this._instantiationService.invokeFunction((accessor) => {
            return Promise.resolve(action.runEditorCommand(accessor, this, args));
          });
        }, this._contextKeyService);
        this._actions.set(internalAction.id, internalAction);
      }
      const isDropIntoEnabled = () => {
        return !this._configuration.options.get(
          104
          /* EditorOption.readOnly */
        ) && this._configuration.options.get(
          43
          /* EditorOption.dropIntoEditor */
        ).enabled;
      };
      this._register(new DragAndDropObserver(this._domElement, {
        onDragOver: (e) => {
          if (!isDropIntoEnabled()) {
            return;
          }
          const target = this.getTargetAtClientPoint(e.clientX, e.clientY);
          if (target?.position) {
            this.showDropIndicatorAt(target.position);
          }
        },
        onDrop: async (e) => {
          if (!isDropIntoEnabled()) {
            return;
          }
          this.removeDropIndicator();
          if (!e.dataTransfer) {
            return;
          }
          const target = this.getTargetAtClientPoint(e.clientX, e.clientY);
          if (target?.position) {
            this._onDropIntoEditor.fire({ position: target.position, event: e });
          }
        },
        onDragLeave: () => {
          this.removeDropIndicator();
        },
        onDragEnd: () => {
          this.removeDropIndicator();
        }
      }));
      this._codeEditorService.addCodeEditor(this);
    }
    writeScreenReaderContent(reason) {
      this._modelData?.view.writeScreenReaderContent(reason);
    }
    _createConfiguration(isSimpleWidget, contextMenuId, options, accessibilityService) {
      return new EditorConfiguration(isSimpleWidget, contextMenuId, options, this._domElement, accessibilityService);
    }
    getId() {
      return this.getEditorType() + ":" + this._id;
    }
    getEditorType() {
      return EditorType.ICodeEditor;
    }
    dispose() {
      this._codeEditorService.removeCodeEditor(this);
      this._actions.clear();
      this._contentWidgets = {};
      this._overlayWidgets = {};
      this._removeDecorationTypes();
      this._postDetachModelCleanup(this._detachModel());
      this._onDidDispose.fire();
      super.dispose();
    }
    invokeWithinContext(fn) {
      return this._instantiationService.invokeFunction(fn);
    }
    updateOptions(newOptions) {
      this._configuration.updateOptions(newOptions || {});
    }
    getOptions() {
      return this._configuration.options;
    }
    getOption(id) {
      return this._configuration.options.get(id);
    }
    getRawOptions() {
      return this._configuration.getRawOptions();
    }
    getOverflowWidgetsDomNode() {
      return this._overflowWidgetsDomNode;
    }
    getConfiguredWordAtPosition(position) {
      if (!this._modelData) {
        return null;
      }
      return WordOperations.getWordAtPosition(this._modelData.model, this._configuration.options.get(
        148
        /* EditorOption.wordSeparators */
      ), this._configuration.options.get(
        147
        /* EditorOption.wordSegmenterLocales */
      ), position);
    }
    getValue(options = null) {
      if (!this._modelData) {
        return "";
      }
      const preserveBOM = options && options.preserveBOM ? true : false;
      let eolPreference = 0;
      if (options && options.lineEnding && options.lineEnding === "\n") {
        eolPreference = 1;
      } else if (options && options.lineEnding && options.lineEnding === "\r\n") {
        eolPreference = 2;
      }
      return this._modelData.model.getValue(eolPreference, preserveBOM);
    }
    setValue(newValue) {
      try {
        this._beginUpdate();
        if (!this._modelData) {
          return;
        }
        this._modelData.model.setValue(newValue);
      } finally {
        this._endUpdate();
      }
    }
    getModel() {
      if (!this._modelData) {
        return null;
      }
      return this._modelData.model;
    }
    setModel(_model = null) {
      try {
        this._beginUpdate();
        const model = _model;
        if (this._modelData === null && model === null) {
          return;
        }
        if (this._modelData && this._modelData.model === model) {
          return;
        }
        const e = {
          oldModelUrl: this._modelData?.model.uri || null,
          newModelUrl: model?.uri || null
        };
        this._onWillChangeModel.fire(e);
        const hasTextFocus = this.hasTextFocus();
        const detachedModel = this._detachModel();
        this._attachModel(model);
        if (this.hasModel()) {
          if (hasTextFocus) {
            this.focus();
          }
        } else {
          this._editorTextFocus.setValue(false);
          this._editorWidgetFocus.setValue(false);
        }
        this._removeDecorationTypes();
        this._onDidChangeModel.fire(e);
        this._postDetachModelCleanup(detachedModel);
        this._contributionsDisposable = this._contributions.onAfterModelAttached();
      } finally {
        this._endUpdate();
      }
    }
    _removeDecorationTypes() {
      this._decorationTypeKeysToIds = {};
      if (this._decorationTypeSubtypes) {
        for (const decorationType in this._decorationTypeSubtypes) {
          const subTypes = this._decorationTypeSubtypes[decorationType];
          for (const subType in subTypes) {
            this._removeDecorationType(decorationType + "-" + subType);
          }
        }
        this._decorationTypeSubtypes = {};
      }
    }
    getVisibleRanges() {
      if (!this._modelData) {
        return [];
      }
      return this._modelData.viewModel.getVisibleRanges();
    }
    getVisibleRangesPlusViewportAboveBelow() {
      if (!this._modelData) {
        return [];
      }
      return this._modelData.viewModel.getVisibleRangesPlusViewportAboveBelow();
    }
    getWhitespaces() {
      if (!this._modelData) {
        return [];
      }
      return this._modelData.viewModel.viewLayout.getWhitespaces();
    }
    static _getVerticalOffsetAfterPosition(modelData, modelLineNumber, modelColumn, includeViewZones) {
      const modelPosition = modelData.model.validatePosition({
        lineNumber: modelLineNumber,
        column: modelColumn
      });
      const viewPosition = modelData.viewModel.coordinatesConverter.convertModelPositionToViewPosition(modelPosition);
      return modelData.viewModel.viewLayout.getVerticalOffsetAfterLineNumber(viewPosition.lineNumber, includeViewZones);
    }
    getTopForLineNumber(lineNumber, includeViewZones = false) {
      if (!this._modelData) {
        return -1;
      }
      return CodeEditorWidget_1._getVerticalOffsetForPosition(this._modelData, lineNumber, 1, includeViewZones);
    }
    getTopForPosition(lineNumber, column) {
      if (!this._modelData) {
        return -1;
      }
      return CodeEditorWidget_1._getVerticalOffsetForPosition(this._modelData, lineNumber, column, false);
    }
    static _getVerticalOffsetForPosition(modelData, modelLineNumber, modelColumn, includeViewZones = false) {
      const modelPosition = modelData.model.validatePosition({
        lineNumber: modelLineNumber,
        column: modelColumn
      });
      const viewPosition = modelData.viewModel.coordinatesConverter.convertModelPositionToViewPosition(modelPosition);
      return modelData.viewModel.viewLayout.getVerticalOffsetForLineNumber(viewPosition.lineNumber, includeViewZones);
    }
    getBottomForLineNumber(lineNumber, includeViewZones = false) {
      if (!this._modelData) {
        return -1;
      }
      const maxCol = this._modelData.model.getLineMaxColumn(lineNumber);
      return CodeEditorWidget_1._getVerticalOffsetAfterPosition(this._modelData, lineNumber, maxCol, includeViewZones);
    }
    getLineHeightForPosition(position) {
      if (!this._modelData) {
        return -1;
      }
      const viewModel = this._modelData.viewModel;
      const coordinatesConverter = viewModel.coordinatesConverter;
      const pos = Position$1.lift(position);
      if (coordinatesConverter.modelPositionIsVisible(pos)) {
        const viewPosition = coordinatesConverter.convertModelPositionToViewPosition(pos);
        return viewModel.viewLayout.getLineHeightForLineNumber(viewPosition.lineNumber);
      }
      return 0;
    }
    setHiddenAreas(ranges, source, forceUpdate) {
      this._modelData?.viewModel.setHiddenAreas(ranges.map((r) => Range$2.lift(r)), source, forceUpdate);
    }
    getVisibleColumnFromPosition(rawPosition) {
      if (!this._modelData) {
        return rawPosition.column;
      }
      const position = this._modelData.model.validatePosition(rawPosition);
      const tabSize = this._modelData.model.getOptions().tabSize;
      return CursorColumns.visibleColumnFromColumn(this._modelData.model.getLineContent(position.lineNumber), position.column, tabSize) + 1;
    }
    getPosition() {
      if (!this._modelData) {
        return null;
      }
      return this._modelData.viewModel.getPosition();
    }
    setPosition(position, source = "api") {
      if (!this._modelData) {
        return;
      }
      if (!Position$1.isIPosition(position)) {
        throw new Error("Invalid arguments");
      }
      this._modelData.viewModel.setSelections(source, [{
        selectionStartLineNumber: position.lineNumber,
        selectionStartColumn: position.column,
        positionLineNumber: position.lineNumber,
        positionColumn: position.column
      }]);
    }
    _sendRevealRange(modelRange, verticalType, revealHorizontal, scrollType) {
      if (!this._modelData) {
        return;
      }
      if (!Range$2.isIRange(modelRange)) {
        throw new Error("Invalid arguments");
      }
      const validatedModelRange = this._modelData.model.validateRange(modelRange);
      const viewRange = this._modelData.viewModel.coordinatesConverter.convertModelRangeToViewRange(validatedModelRange);
      this._modelData.viewModel.revealRange("api", revealHorizontal, viewRange, verticalType, scrollType);
    }
    revealLine(lineNumber, scrollType = 0) {
      this._revealLine(lineNumber, 0, scrollType);
    }
    revealLineInCenter(lineNumber, scrollType = 0) {
      this._revealLine(lineNumber, 1, scrollType);
    }
    revealLineInCenterIfOutsideViewport(lineNumber, scrollType = 0) {
      this._revealLine(lineNumber, 2, scrollType);
    }
    revealLineNearTop(lineNumber, scrollType = 0) {
      this._revealLine(lineNumber, 5, scrollType);
    }
    _revealLine(lineNumber, revealType, scrollType) {
      if (typeof lineNumber !== "number") {
        throw new Error("Invalid arguments");
      }
      this._sendRevealRange(new Range$2(lineNumber, 1, lineNumber, 1), revealType, false, scrollType);
    }
    revealPosition(position, scrollType = 0) {
      this._revealPosition(position, 0, true, scrollType);
    }
    revealPositionInCenter(position, scrollType = 0) {
      this._revealPosition(position, 1, true, scrollType);
    }
    revealPositionInCenterIfOutsideViewport(position, scrollType = 0) {
      this._revealPosition(position, 2, true, scrollType);
    }
    revealPositionNearTop(position, scrollType = 0) {
      this._revealPosition(position, 5, true, scrollType);
    }
    _revealPosition(position, verticalType, revealHorizontal, scrollType) {
      if (!Position$1.isIPosition(position)) {
        throw new Error("Invalid arguments");
      }
      this._sendRevealRange(new Range$2(position.lineNumber, position.column, position.lineNumber, position.column), verticalType, revealHorizontal, scrollType);
    }
    getSelection() {
      if (!this._modelData) {
        return null;
      }
      return this._modelData.viewModel.getSelection();
    }
    getSelections() {
      if (!this._modelData) {
        return null;
      }
      return this._modelData.viewModel.getSelections();
    }
    setSelection(something, source = "api") {
      const isSelection = Selection$1.isISelection(something);
      const isRange = Range$2.isIRange(something);
      if (!isSelection && !isRange) {
        throw new Error("Invalid arguments");
      }
      if (isSelection) {
        this._setSelectionImpl(something, source);
      } else if (isRange) {
        const selection = {
          selectionStartLineNumber: something.startLineNumber,
          selectionStartColumn: something.startColumn,
          positionLineNumber: something.endLineNumber,
          positionColumn: something.endColumn
        };
        this._setSelectionImpl(selection, source);
      }
    }
    _setSelectionImpl(sel, source) {
      if (!this._modelData) {
        return;
      }
      const selection = new Selection$1(sel.selectionStartLineNumber, sel.selectionStartColumn, sel.positionLineNumber, sel.positionColumn);
      this._modelData.viewModel.setSelections(source, [selection]);
    }
    revealLines(startLineNumber, endLineNumber, scrollType = 0) {
      this._revealLines(startLineNumber, endLineNumber, 0, scrollType);
    }
    revealLinesInCenter(startLineNumber, endLineNumber, scrollType = 0) {
      this._revealLines(startLineNumber, endLineNumber, 1, scrollType);
    }
    revealLinesInCenterIfOutsideViewport(startLineNumber, endLineNumber, scrollType = 0) {
      this._revealLines(startLineNumber, endLineNumber, 2, scrollType);
    }
    revealLinesNearTop(startLineNumber, endLineNumber, scrollType = 0) {
      this._revealLines(startLineNumber, endLineNumber, 5, scrollType);
    }
    _revealLines(startLineNumber, endLineNumber, verticalType, scrollType) {
      if (typeof startLineNumber !== "number" || typeof endLineNumber !== "number") {
        throw new Error("Invalid arguments");
      }
      this._sendRevealRange(new Range$2(startLineNumber, 1, endLineNumber, 1), verticalType, false, scrollType);
    }
    revealRange(range2, scrollType = 0, revealVerticalInCenter = false, revealHorizontal = true) {
      this._revealRange(range2, revealVerticalInCenter ? 1 : 0, revealHorizontal, scrollType);
    }
    revealRangeInCenter(range2, scrollType = 0) {
      this._revealRange(range2, 1, true, scrollType);
    }
    revealRangeInCenterIfOutsideViewport(range2, scrollType = 0) {
      this._revealRange(range2, 2, true, scrollType);
    }
    revealRangeNearTop(range2, scrollType = 0) {
      this._revealRange(range2, 5, true, scrollType);
    }
    revealRangeNearTopIfOutsideViewport(range2, scrollType = 0) {
      this._revealRange(range2, 6, true, scrollType);
    }
    revealRangeAtTop(range2, scrollType = 0) {
      this._revealRange(range2, 3, true, scrollType);
    }
    _revealRange(range2, verticalType, revealHorizontal, scrollType) {
      if (!Range$2.isIRange(range2)) {
        throw new Error("Invalid arguments");
      }
      this._sendRevealRange(Range$2.lift(range2), verticalType, revealHorizontal, scrollType);
    }
    setSelections(ranges, source = "api", reason = 0) {
      if (!this._modelData) {
        return;
      }
      if (!ranges || ranges.length === 0) {
        throw new Error("Invalid arguments");
      }
      for (let i2 = 0, len = ranges.length; i2 < len; i2++) {
        if (!Selection$1.isISelection(ranges[i2])) {
          throw new Error("Invalid arguments");
        }
      }
      this._modelData.viewModel.setSelections(source, ranges, reason);
    }
    getContentWidth() {
      if (!this._modelData) {
        return -1;
      }
      return this._modelData.viewModel.viewLayout.getContentWidth();
    }
    getScrollWidth() {
      if (!this._modelData) {
        return -1;
      }
      return this._modelData.viewModel.viewLayout.getScrollWidth();
    }
    getScrollLeft() {
      if (!this._modelData) {
        return -1;
      }
      return this._modelData.viewModel.viewLayout.getCurrentScrollLeft();
    }
    getContentHeight() {
      if (!this._modelData) {
        return -1;
      }
      return this._modelData.viewModel.viewLayout.getContentHeight();
    }
    getScrollHeight() {
      if (!this._modelData) {
        return -1;
      }
      return this._modelData.viewModel.viewLayout.getScrollHeight();
    }
    getScrollTop() {
      if (!this._modelData) {
        return -1;
      }
      return this._modelData.viewModel.viewLayout.getCurrentScrollTop();
    }
    setScrollLeft(newScrollLeft, scrollType = 1) {
      if (!this._modelData) {
        return;
      }
      if (typeof newScrollLeft !== "number") {
        throw new Error("Invalid arguments");
      }
      this._modelData.viewModel.viewLayout.setScrollPosition({
        scrollLeft: newScrollLeft
      }, scrollType);
    }
    setScrollTop(newScrollTop, scrollType = 1) {
      if (!this._modelData) {
        return;
      }
      if (typeof newScrollTop !== "number") {
        throw new Error("Invalid arguments");
      }
      this._modelData.viewModel.viewLayout.setScrollPosition({
        scrollTop: newScrollTop
      }, scrollType);
    }
    setScrollPosition(position, scrollType = 1) {
      if (!this._modelData) {
        return;
      }
      this._modelData.viewModel.viewLayout.setScrollPosition(position, scrollType);
    }
    hasPendingScrollAnimation() {
      if (!this._modelData) {
        return false;
      }
      return this._modelData.viewModel.viewLayout.hasPendingScrollAnimation();
    }
    saveViewState() {
      if (!this._modelData) {
        return null;
      }
      const contributionsState = this._contributions.saveViewState();
      const cursorState = this._modelData.viewModel.saveCursorState();
      const viewState = this._modelData.viewModel.saveState();
      return {
        cursorState,
        viewState,
        contributionsState
      };
    }
    restoreViewState(s) {
      if (!this._modelData || !this._modelData.hasRealView) {
        return;
      }
      const codeEditorState = s;
      if (codeEditorState && codeEditorState.cursorState && codeEditorState.viewState) {
        const cursorState = codeEditorState.cursorState;
        if (Array.isArray(cursorState)) {
          if (cursorState.length > 0) {
            this._modelData.viewModel.restoreCursorState(cursorState);
          }
        } else {
          this._modelData.viewModel.restoreCursorState([cursorState]);
        }
        this._contributions.restoreViewState(codeEditorState.contributionsState || {});
        const reducedState = this._modelData.viewModel.reduceRestoreState(codeEditorState.viewState);
        this._modelData.view.restoreState(reducedState);
      }
    }
    handleInitialized() {
      this._getViewModel()?.visibleLinesStabilized();
    }
    getContribution(id) {
      return this._contributions.get(id);
    }
    getActions() {
      return Array.from(this._actions.values());
    }
    getSupportedActions() {
      let result = this.getActions();
      result = result.filter((action) => action.isSupported());
      return result;
    }
    getAction(id) {
      return this._actions.get(id) || null;
    }
    trigger(source, handlerId, payload) {
      payload = payload || {};
      try {
        this._onWillTriggerEditorOperationEvent.fire({ source, handlerId, payload });
        this._beginUpdate();
        switch (handlerId) {
          case "compositionStart":
            this._startComposition();
            return;
          case "compositionEnd":
            this._endComposition(source);
            return;
          case "type": {
            const args = payload;
            this._type(source, args.text || "");
            return;
          }
          case "replacePreviousChar": {
            const args = payload;
            this._compositionType(source, args.text || "", args.replaceCharCnt || 0, 0, 0);
            return;
          }
          case "compositionType": {
            const args = payload;
            this._compositionType(source, args.text || "", args.replacePrevCharCnt || 0, args.replaceNextCharCnt || 0, args.positionDelta || 0);
            return;
          }
          case "paste": {
            const args = payload;
            this._paste(source, args.text || "", args.pasteOnNewLine || false, args.multicursorText || null, args.mode || null, args.clipboardEvent);
            return;
          }
          case "cut":
            this._cut(source);
            return;
        }
        const action = this.getAction(handlerId);
        if (action) {
          Promise.resolve(action.run(payload)).then(void 0, onUnexpectedError);
          return;
        }
        if (!this._modelData) {
          return;
        }
        if (this._triggerEditorCommand(source, handlerId, payload)) {
          return;
        }
        this._triggerCommand(handlerId, payload);
      } finally {
        this._endUpdate();
      }
    }
    _triggerCommand(handlerId, payload) {
      this._commandService.executeCommand(handlerId, payload);
    }
    _startComposition() {
      if (!this._modelData) {
        return;
      }
      this.inComposition = true;
      this._modelData.viewModel.startComposition();
      this._onDidCompositionStart.fire();
    }
    _endComposition(source) {
      if (!this._modelData) {
        return;
      }
      this.inComposition = false;
      this._modelData.viewModel.endComposition(source);
      this._onDidCompositionEnd.fire();
    }
    _type(source, text2) {
      if (!this._modelData || text2.length === 0) {
        return;
      }
      if (source === "keyboard") {
        this._onWillType.fire(text2);
      }
      this._modelData.viewModel.type(text2, source);
      if (source === "keyboard") {
        this._onDidType.fire(text2);
      }
    }
    _compositionType(source, text2, replacePrevCharCnt, replaceNextCharCnt, positionDelta) {
      if (!this._modelData) {
        return;
      }
      this._modelData.viewModel.compositionType(text2, replacePrevCharCnt, replaceNextCharCnt, positionDelta, source);
    }
    _paste(source, text2, pasteOnNewLine, multicursorText, mode, clipboardEvent) {
      if (!this._modelData) {
        return;
      }
      const viewModel = this._modelData.viewModel;
      const startPosition = viewModel.getSelection().getStartPosition();
      viewModel.paste(text2, pasteOnNewLine, multicursorText, source);
      const endPosition = viewModel.getSelection().getStartPosition();
      if (source === "keyboard") {
        this._onDidPaste.fire({
          clipboardEvent,
          range: new Range$2(startPosition.lineNumber, startPosition.column, endPosition.lineNumber, endPosition.column),
          languageId: mode
        });
      }
    }
    _cut(source) {
      if (!this._modelData) {
        return;
      }
      this._modelData.viewModel.cut(source);
    }
    _triggerEditorCommand(source, handlerId, payload) {
      const command = EditorExtensionsRegistry.getEditorCommand(handlerId);
      if (command) {
        payload = payload || {};
        if (isObject(payload)) {
          payload.source = source;
        }
        this._instantiationService.invokeFunction((accessor) => {
          Promise.resolve(command.runEditorCommand(accessor, this, payload)).then(void 0, onUnexpectedError);
        });
        return true;
      }
      return false;
    }
    _getViewModel() {
      if (!this._modelData) {
        return null;
      }
      return this._modelData.viewModel;
    }
    pushUndoStop() {
      if (!this._modelData) {
        return false;
      }
      if (this._configuration.options.get(
        104
        /* EditorOption.readOnly */
      )) {
        return false;
      }
      this._modelData.model.pushStackElement();
      return true;
    }
    popUndoStop() {
      if (!this._modelData) {
        return false;
      }
      if (this._configuration.options.get(
        104
        /* EditorOption.readOnly */
      )) {
        return false;
      }
      this._modelData.model.popStackElement();
      return true;
    }
    edit(edit2, reason) {
      return this.executeEdits(reason, edit2.replacements.map((e) => ({ range: e.range, text: e.text })), void 0);
    }
    executeEdits(source, edits, endCursorState) {
      if (!this._modelData) {
        return false;
      }
      if (this._configuration.options.get(
        104
        /* EditorOption.readOnly */
      )) {
        return false;
      }
      let cursorStateComputer;
      if (!endCursorState) {
        cursorStateComputer = () => null;
      } else if (Array.isArray(endCursorState)) {
        cursorStateComputer = () => endCursorState;
      } else {
        cursorStateComputer = endCursorState;
      }
      let sourceStr;
      let reason;
      if (source instanceof TextModelEditSource) {
        reason = source;
        sourceStr = source.metadata.source;
      } else {
        reason = EditSources.unknown({ name: sourceStr });
        sourceStr = source;
      }
      this._onBeforeExecuteEdit.fire({ source: sourceStr ?? void 0 });
      this._modelData.viewModel.executeEdits(sourceStr, edits, cursorStateComputer, reason);
      return true;
    }
    executeCommand(source, command) {
      if (!this._modelData) {
        return;
      }
      this._modelData.viewModel.executeCommand(command, source);
    }
    executeCommands(source, commands) {
      if (!this._modelData) {
        return;
      }
      this._modelData.viewModel.executeCommands(commands, source);
    }
    createDecorationsCollection(decorations) {
      return new EditorDecorationsCollection(this, decorations);
    }
    changeDecorations(callback) {
      if (!this._modelData) {
        return null;
      }
      return this._modelData.model.changeDecorations(callback, this._id);
    }
    getLineDecorations(lineNumber) {
      if (!this._modelData) {
        return null;
      }
      const options = this._configuration.options;
      return this._modelData.model.getLineDecorations(lineNumber, this._id, filterValidationDecorations(options), filterFontDecorations(options));
    }
    getDecorationsInRange(range2) {
      if (!this._modelData) {
        return null;
      }
      const options = this._configuration.options;
      return this._modelData.model.getDecorationsInRange(range2, this._id, filterValidationDecorations(options), filterFontDecorations(options));
    }
    getFontSizeAtPosition(position) {
      if (!this._modelData) {
        return null;
      }
      return this._modelData.viewModel.getFontSizeAtPosition(position);
    }
    /**
     * @deprecated
     */
    deltaDecorations(oldDecorations, newDecorations) {
      if (!this._modelData) {
        return [];
      }
      if (oldDecorations.length === 0 && newDecorations.length === 0) {
        return oldDecorations;
      }
      return this._modelData.model.deltaDecorations(oldDecorations, newDecorations, this._id);
    }
    removeDecorations(decorationIds) {
      if (!this._modelData || decorationIds.length === 0) {
        return;
      }
      this._modelData.model.changeDecorations((changeAccessor) => {
        changeAccessor.deltaDecorations(decorationIds, []);
      });
    }
    removeDecorationsByType(decorationTypeKey) {
      const oldDecorationsIds = this._decorationTypeKeysToIds[decorationTypeKey];
      if (oldDecorationsIds) {
        this.changeDecorations((accessor) => accessor.deltaDecorations(oldDecorationsIds, []));
      }
      if (this._decorationTypeKeysToIds.hasOwnProperty(decorationTypeKey)) {
        delete this._decorationTypeKeysToIds[decorationTypeKey];
      }
      if (this._decorationTypeSubtypes.hasOwnProperty(decorationTypeKey)) {
        delete this._decorationTypeSubtypes[decorationTypeKey];
      }
    }
    getLayoutInfo() {
      const options = this._configuration.options;
      const layoutInfo = options.get(
        165
        /* EditorOption.layoutInfo */
      );
      return layoutInfo;
    }
    createOverviewRuler(cssClassName) {
      if (!this._modelData || !this._modelData.hasRealView) {
        return null;
      }
      return this._modelData.view.createOverviewRuler(cssClassName);
    }
    getContainerDomNode() {
      return this._domElement;
    }
    getDomNode() {
      if (!this._modelData || !this._modelData.hasRealView) {
        return null;
      }
      return this._modelData.view.domNode.domNode;
    }
    delegateVerticalScrollbarPointerDown(browserEvent) {
      if (!this._modelData || !this._modelData.hasRealView) {
        return;
      }
      this._modelData.view.delegateVerticalScrollbarPointerDown(browserEvent);
    }
    delegateScrollFromMouseWheelEvent(browserEvent) {
      if (!this._modelData || !this._modelData.hasRealView) {
        return;
      }
      this._modelData.view.delegateScrollFromMouseWheelEvent(browserEvent);
    }
    layout(dimension, postponeRendering = false) {
      this._configuration.observeContainer(dimension);
      if (!postponeRendering) {
        this.render();
      }
    }
    focus() {
      if (!this._modelData || !this._modelData.hasRealView) {
        return;
      }
      this._modelData.view.focus();
    }
    hasTextFocus() {
      if (!this._modelData || !this._modelData.hasRealView) {
        return false;
      }
      return this._modelData.view.isFocused();
    }
    hasWidgetFocus() {
      if (!this._modelData || !this._modelData.hasRealView) {
        return false;
      }
      return this._modelData.view.isWidgetFocused();
    }
    addContentWidget(widget) {
      const widgetData = {
        widget,
        position: widget.getPosition()
      };
      if (this._contentWidgets.hasOwnProperty(widget.getId())) {
        console.warn("Overwriting a content widget with the same id:" + widget.getId());
      }
      this._contentWidgets[widget.getId()] = widgetData;
      if (this._modelData && this._modelData.hasRealView) {
        this._modelData.view.addContentWidget(widgetData);
      }
    }
    layoutContentWidget(widget) {
      const widgetId = widget.getId();
      if (this._contentWidgets.hasOwnProperty(widgetId)) {
        const widgetData = this._contentWidgets[widgetId];
        widgetData.position = widget.getPosition();
        if (this._modelData && this._modelData.hasRealView) {
          this._modelData.view.layoutContentWidget(widgetData);
        }
      }
    }
    removeContentWidget(widget) {
      const widgetId = widget.getId();
      if (this._contentWidgets.hasOwnProperty(widgetId)) {
        const widgetData = this._contentWidgets[widgetId];
        delete this._contentWidgets[widgetId];
        if (this._modelData && this._modelData.hasRealView) {
          this._modelData.view.removeContentWidget(widgetData);
        }
      }
    }
    addOverlayWidget(widget) {
      const widgetData = {
        widget,
        position: widget.getPosition()
      };
      if (this._overlayWidgets.hasOwnProperty(widget.getId())) {
        console.warn("Overwriting an overlay widget with the same id.");
      }
      this._overlayWidgets[widget.getId()] = widgetData;
      if (this._modelData && this._modelData.hasRealView) {
        this._modelData.view.addOverlayWidget(widgetData);
      }
    }
    layoutOverlayWidget(widget) {
      const widgetId = widget.getId();
      if (this._overlayWidgets.hasOwnProperty(widgetId)) {
        const widgetData = this._overlayWidgets[widgetId];
        widgetData.position = widget.getPosition();
        if (this._modelData && this._modelData.hasRealView) {
          this._modelData.view.layoutOverlayWidget(widgetData);
        }
      }
    }
    removeOverlayWidget(widget) {
      const widgetId = widget.getId();
      if (this._overlayWidgets.hasOwnProperty(widgetId)) {
        const widgetData = this._overlayWidgets[widgetId];
        delete this._overlayWidgets[widgetId];
        if (this._modelData && this._modelData.hasRealView) {
          this._modelData.view.removeOverlayWidget(widgetData);
        }
      }
    }
    addGlyphMarginWidget(widget) {
      const widgetData = {
        widget,
        position: widget.getPosition()
      };
      if (this._glyphMarginWidgets.hasOwnProperty(widget.getId())) {
        console.warn("Overwriting a glyph margin widget with the same id.");
      }
      this._glyphMarginWidgets[widget.getId()] = widgetData;
      if (this._modelData && this._modelData.hasRealView) {
        this._modelData.view.addGlyphMarginWidget(widgetData);
      }
    }
    layoutGlyphMarginWidget(widget) {
      const widgetId = widget.getId();
      if (this._glyphMarginWidgets.hasOwnProperty(widgetId)) {
        const widgetData = this._glyphMarginWidgets[widgetId];
        widgetData.position = widget.getPosition();
        if (this._modelData && this._modelData.hasRealView) {
          this._modelData.view.layoutGlyphMarginWidget(widgetData);
        }
      }
    }
    removeGlyphMarginWidget(widget) {
      const widgetId = widget.getId();
      if (this._glyphMarginWidgets.hasOwnProperty(widgetId)) {
        const widgetData = this._glyphMarginWidgets[widgetId];
        delete this._glyphMarginWidgets[widgetId];
        if (this._modelData && this._modelData.hasRealView) {
          this._modelData.view.removeGlyphMarginWidget(widgetData);
        }
      }
    }
    changeViewZones(callback) {
      if (!this._modelData || !this._modelData.hasRealView) {
        return;
      }
      this._modelData.view.change(callback);
    }
    getTargetAtClientPoint(clientX, clientY) {
      if (!this._modelData || !this._modelData.hasRealView) {
        return null;
      }
      return this._modelData.view.getTargetAtClientPoint(clientX, clientY);
    }
    getScrolledVisiblePosition(rawPosition) {
      if (!this._modelData || !this._modelData.hasRealView) {
        return null;
      }
      const position = this._modelData.model.validatePosition(rawPosition);
      const options = this._configuration.options;
      const layoutInfo = options.get(
        165
        /* EditorOption.layoutInfo */
      );
      const top = CodeEditorWidget_1._getVerticalOffsetForPosition(this._modelData, position.lineNumber, position.column) - this.getScrollTop();
      const left = this._modelData.view.getOffsetForColumn(position.lineNumber, position.column) + layoutInfo.glyphMarginWidth + layoutInfo.lineNumbersWidth + layoutInfo.decorationsWidth - this.getScrollLeft();
      const height = this.getLineHeightForPosition(position);
      return {
        top,
        left,
        height
      };
    }
    getOffsetForColumn(lineNumber, column) {
      if (!this._modelData || !this._modelData.hasRealView) {
        return -1;
      }
      return this._modelData.view.getOffsetForColumn(lineNumber, column);
    }
    render(forceRedraw = false) {
      if (!this._modelData || !this._modelData.hasRealView) {
        return;
      }
      this._modelData.viewModel.batchEvents(() => {
        this._modelData.view.render(true, forceRedraw);
      });
    }
    setAriaOptions(options) {
      if (!this._modelData || !this._modelData.hasRealView) {
        return;
      }
      this._modelData.view.setAriaOptions(options);
    }
    applyFontInfo(target) {
      applyFontInfo(target, this._configuration.options.get(
        59
        /* EditorOption.fontInfo */
      ));
    }
    setBanner(domNode, domNodeHeight) {
      if (this._bannerDomNode && this._domElement.contains(this._bannerDomNode)) {
        this._bannerDomNode.remove();
      }
      this._bannerDomNode = domNode;
      this._configuration.setReservedHeight(domNode ? domNodeHeight : 0);
      if (this._bannerDomNode) {
        this._domElement.prepend(this._bannerDomNode);
      }
    }
    _attachModel(model) {
      if (!model) {
        this._modelData = null;
        return;
      }
      const listenersToRemove = [];
      this._domElement.setAttribute("data-mode-id", model.getLanguageId());
      this._configuration.setIsDominatedByLongLines(model.isDominatedByLongLines());
      this._configuration.setModelLineCount(model.getLineCount());
      const attachedView = model.onBeforeAttached();
      const viewModel = new ViewModel$1(this._id, this._configuration, model, DOMLineBreaksComputerFactory.create(getWindow(this._domElement)), MonospaceLineBreaksComputerFactory.create(this._configuration.options), (callback) => scheduleAtNextAnimationFrame(getWindow(this._domElement), callback), this.languageConfigurationService, this._themeService, attachedView, {
        batchChanges: (cb) => {
          try {
            this._beginUpdate();
            return cb();
          } finally {
            this._endUpdate();
          }
        }
      });
      listenersToRemove.push(model.onWillDispose(() => this.setModel(null)));
      listenersToRemove.push(viewModel.onEvent((e) => {
        switch (e.kind) {
          case 0:
            this._onDidContentSizeChange.fire(e);
            break;
          case 1:
            this._editorTextFocus.setValue(e.hasFocus);
            break;
          case 2:
            this._editorWidgetFocus.setValue(e.hasFocus);
            break;
          case 3:
            this._onDidScrollChange.fire(e);
            break;
          case 4:
            this._onDidChangeViewZones.fire();
            break;
          case 5:
            this._onDidChangeHiddenAreas.fire();
            break;
          case 6:
            this._onDidAttemptReadOnlyEdit.fire();
            break;
          case 7: {
            if (e.reachedMaxCursorCount) {
              const multiCursorLimit = this.getOption(
                89
                /* EditorOption.multiCursorLimit */
              );
              const message = localize(83, "The number of cursors has been limited to {0}. Consider using [find and replace](https://code.visualstudio.com/docs/editor/codebasics#_find-and-replace) for larger changes or increase the editor multi cursor limit setting.", multiCursorLimit);
              this._notificationService.prompt(Severity.Warning, message, [
                {
                  label: "Find and Replace",
                  run: () => {
                    this._commandService.executeCommand("editor.action.startFindReplaceAction");
                  }
                },
                {
                  label: localize(84, "Increase Multi Cursor Limit"),
                  run: () => {
                    this._commandService.executeCommand("workbench.action.openSettings2", {
                      query: "editor.multiCursorLimit"
                    });
                  }
                }
              ]);
            }
            const positions = [];
            for (let i2 = 0, len = e.selections.length; i2 < len; i2++) {
              positions[i2] = e.selections[i2].getPosition();
            }
            const e1 = {
              position: positions[0],
              secondaryPositions: positions.slice(1),
              reason: e.reason,
              source: e.source
            };
            this._onDidChangeCursorPosition.fire(e1);
            const e2 = {
              selection: e.selections[0],
              secondarySelections: e.selections.slice(1),
              modelVersionId: e.modelVersionId,
              oldSelections: e.oldSelections,
              oldModelVersionId: e.oldModelVersionId,
              source: e.source,
              reason: e.reason
            };
            this._onDidChangeCursorSelection.fire(e2);
            break;
          }
          case 8:
            this._onDidChangeModelDecorations.fire(e.event);
            break;
          case 9:
            this._domElement.setAttribute("data-mode-id", model.getLanguageId());
            this._onDidChangeModelLanguage.fire(e.event);
            break;
          case 10:
            this._onDidChangeModelLanguageConfiguration.fire(e.event);
            break;
          case 11:
            this._onDidChangeModelContent.fire(e.event);
            break;
          case 12:
            this._onDidChangeModelOptions.fire(e.event);
            break;
          case 13:
            this._onDidChangeModelTokens.fire(e.event);
            break;
          case 14:
            this._onDidChangeLineHeight.fire(e.event);
            break;
          case 15:
            this._onDidChangeFont.fire(e.event);
            break;
        }
      }));
      const [view, hasRealView] = this._createView(viewModel);
      if (hasRealView) {
        this._domElement.appendChild(view.domNode.domNode);
        let keys = Object.keys(this._contentWidgets);
        for (let i2 = 0, len = keys.length; i2 < len; i2++) {
          const widgetId = keys[i2];
          view.addContentWidget(this._contentWidgets[widgetId]);
        }
        keys = Object.keys(this._overlayWidgets);
        for (let i2 = 0, len = keys.length; i2 < len; i2++) {
          const widgetId = keys[i2];
          view.addOverlayWidget(this._overlayWidgets[widgetId]);
        }
        keys = Object.keys(this._glyphMarginWidgets);
        for (let i2 = 0, len = keys.length; i2 < len; i2++) {
          const widgetId = keys[i2];
          view.addGlyphMarginWidget(this._glyphMarginWidgets[widgetId]);
        }
        view.render(false, true);
        view.domNode.domNode.setAttribute("data-uri", model.uri.toString());
      }
      this._modelData = new ModelData$1(model, viewModel, view, hasRealView, listenersToRemove, attachedView);
    }
    _createView(viewModel) {
      let commandDelegate;
      if (this.isSimpleWidget) {
        commandDelegate = {
          paste: (text2, pasteOnNewLine, multicursorText, mode) => {
            this._paste("keyboard", text2, pasteOnNewLine, multicursorText, mode);
          },
          type: (text2) => {
            this._type("keyboard", text2);
          },
          compositionType: (text2, replacePrevCharCnt, replaceNextCharCnt, positionDelta) => {
            this._compositionType("keyboard", text2, replacePrevCharCnt, replaceNextCharCnt, positionDelta);
          },
          startComposition: () => {
            this._startComposition();
          },
          endComposition: () => {
            this._endComposition("keyboard");
          },
          cut: () => {
            this._cut("keyboard");
          }
        };
      } else {
        commandDelegate = {
          paste: (text2, pasteOnNewLine, multicursorText, mode) => {
            const payload = { text: text2, pasteOnNewLine, multicursorText, mode };
            this._commandService.executeCommand("paste", payload);
          },
          type: (text2) => {
            const payload = { text: text2 };
            this._commandService.executeCommand("type", payload);
          },
          compositionType: (text2, replacePrevCharCnt, replaceNextCharCnt, positionDelta) => {
            if (replaceNextCharCnt || positionDelta) {
              const payload = { text: text2, replacePrevCharCnt, replaceNextCharCnt, positionDelta };
              this._commandService.executeCommand("compositionType", payload);
            } else {
              const payload = { text: text2, replaceCharCnt: replacePrevCharCnt };
              this._commandService.executeCommand("replacePreviousChar", payload);
            }
          },
          startComposition: () => {
            this._commandService.executeCommand("compositionStart", {});
          },
          endComposition: () => {
            this._commandService.executeCommand("compositionEnd", {});
          },
          cut: () => {
            this._commandService.executeCommand("cut", {});
          }
        };
      }
      const viewUserInputEvents = new ViewUserInputEvents(viewModel.coordinatesConverter);
      viewUserInputEvents.onKeyDown = (e) => this._onKeyDown.fire(e);
      viewUserInputEvents.onKeyUp = (e) => this._onKeyUp.fire(e);
      viewUserInputEvents.onContextMenu = (e) => this._onContextMenu.fire(e);
      viewUserInputEvents.onMouseMove = (e) => this._onMouseMove.fire(e);
      viewUserInputEvents.onMouseLeave = (e) => this._onMouseLeave.fire(e);
      viewUserInputEvents.onMouseDown = (e) => this._onMouseDown.fire(e);
      viewUserInputEvents.onMouseUp = (e) => this._onMouseUp.fire(e);
      viewUserInputEvents.onMouseDrag = (e) => this._onMouseDrag.fire(e);
      viewUserInputEvents.onMouseDrop = (e) => this._onMouseDrop.fire(e);
      viewUserInputEvents.onMouseDropCanceled = (e) => this._onMouseDropCanceled.fire(e);
      viewUserInputEvents.onMouseWheel = (e) => this._onMouseWheel.fire(e);
      const view = new View$1(this._domElement, this.getId(), commandDelegate, this._configuration, this._themeService.getColorTheme(), viewModel, viewUserInputEvents, this._overflowWidgetsDomNode, this._instantiationService);
      return [view, true];
    }
    _postDetachModelCleanup(detachedModel) {
      detachedModel?.removeAllDecorationsWithOwnerId(this._id);
    }
    _detachModel() {
      this._contributionsDisposable?.dispose();
      this._contributionsDisposable = void 0;
      if (!this._modelData) {
        return null;
      }
      const model = this._modelData.model;
      const removeDomNode = this._modelData.hasRealView ? this._modelData.view.domNode.domNode : null;
      this._modelData.dispose();
      this._modelData = null;
      this._domElement.removeAttribute("data-mode-id");
      if (removeDomNode && this._domElement.contains(removeDomNode)) {
        removeDomNode.remove();
      }
      if (this._bannerDomNode && this._domElement.contains(this._bannerDomNode)) {
        this._bannerDomNode.remove();
      }
      return model;
    }
    _removeDecorationType(key) {
      this._codeEditorService.removeDecorationType(key);
    }
    hasModel() {
      return this._modelData !== null;
    }
    showDropIndicatorAt(position) {
      const newDecorations = [{
        range: new Range$2(position.lineNumber, position.column, position.lineNumber, position.column),
        options: CodeEditorWidget_1.dropIntoEditorDecorationOptions
      }];
      this._dropIntoEditorDecorations.set(newDecorations);
      this.revealPosition(
        position,
        1
        /* editorCommon.ScrollType.Immediate */
      );
    }
    removeDropIndicator() {
      this._dropIntoEditorDecorations.clear();
    }
    _beginUpdate() {
      this._updateCounter++;
      if (this._updateCounter === 1) {
        this._onBeginUpdate.fire();
      }
    }
    _endUpdate() {
      this._updateCounter--;
      if (this._updateCounter === 0) {
        this._onEndUpdate.fire();
      }
    }
  }, CodeEditorWidget_1 = _j, _j.dropIntoEditorDecorationOptions = ModelDecorationOptions.register({
    description: "workbench-dnd-target",
    className: "dnd-target"
  }), _j);
  CodeEditorWidget = CodeEditorWidget_1 = __decorate$2K([
    __param$2F(3, IInstantiationService),
    __param$2F(4, ICodeEditorService),
    __param$2F(5, ICommandService),
    __param$2F(6, IContextKeyService),
    __param$2F(7, IThemeService),
    __param$2F(8, INotificationService),
    __param$2F(9, IAccessibilityService),
    __param$2F(10, ILanguageConfigurationService),
    __param$2F(11, ILanguageFeaturesService)
  ], CodeEditorWidget);
  let EDITOR_ID = 0;
  let ModelData$1 = class ModelData {
    constructor(model, viewModel, view, hasRealView, listenersToRemove, attachedView) {
      this.model = model;
      this.viewModel = viewModel;
      this.view = view;
      this.hasRealView = hasRealView;
      this.listenersToRemove = listenersToRemove;
      this.attachedView = attachedView;
    }
    dispose() {
      dispose(this.listenersToRemove);
      this.model.onBeforeDetached(this.attachedView);
      if (this.hasRealView) {
        this.view.dispose();
      }
      this.viewModel.dispose();
    }
  };
  class BooleanEventEmitter extends Disposable {
    constructor(_emitterOptions) {
      super();
      this._emitterOptions = _emitterOptions;
      this._onDidChangeToTrue = this._register(new Emitter$1(this._emitterOptions));
      this.onDidChangeToTrue = this._onDidChangeToTrue.event;
      this._onDidChangeToFalse = this._register(new Emitter$1(this._emitterOptions));
      this.onDidChangeToFalse = this._onDidChangeToFalse.event;
      this._value = 0;
    }
    setValue(_value) {
      const value = _value ? 2 : 1;
      if (this._value === value) {
        return;
      }
      this._value = value;
      if (this._value === 2) {
        this._onDidChangeToTrue.fire();
      } else if (this._value === 1) {
        this._onDidChangeToFalse.fire();
      }
    }
  }
  class InteractionEmitter extends Emitter$1 {
    constructor(_contributions, deliveryQueue) {
      super({ deliveryQueue });
      this._contributions = _contributions;
    }
    fire(event) {
      this._contributions.onBeforeInteractionEvent();
      super.fire(event);
    }
  }
  class EditorContextKeysManager extends Disposable {
    constructor(editor2, contextKeyService) {
      super();
      this._editor = editor2;
      contextKeyService.createKey("editorId", editor2.getId());
      this._editorSimpleInput = EditorContextKeys.editorSimpleInput.bindTo(contextKeyService);
      this._editorFocus = EditorContextKeys.focus.bindTo(contextKeyService);
      this._textInputFocus = EditorContextKeys.textInputFocus.bindTo(contextKeyService);
      this._editorTextFocus = EditorContextKeys.editorTextFocus.bindTo(contextKeyService);
      this._tabMovesFocus = EditorContextKeys.tabMovesFocus.bindTo(contextKeyService);
      this._editorReadonly = EditorContextKeys.readOnly.bindTo(contextKeyService);
      this._inDiffEditor = EditorContextKeys.inDiffEditor.bindTo(contextKeyService);
      this._editorColumnSelection = EditorContextKeys.columnSelection.bindTo(contextKeyService);
      this._hasMultipleSelections = EditorContextKeys.hasMultipleSelections.bindTo(contextKeyService);
      this._hasNonEmptySelection = EditorContextKeys.hasNonEmptySelection.bindTo(contextKeyService);
      this._canUndo = EditorContextKeys.canUndo.bindTo(contextKeyService);
      this._canRedo = EditorContextKeys.canRedo.bindTo(contextKeyService);
      this._register(this._editor.onDidChangeConfiguration(() => this._updateFromConfig()));
      this._register(this._editor.onDidChangeCursorSelection(() => this._updateFromSelection()));
      this._register(this._editor.onDidFocusEditorWidget(() => this._updateFromFocus()));
      this._register(this._editor.onDidBlurEditorWidget(() => this._updateFromFocus()));
      this._register(this._editor.onDidFocusEditorText(() => this._updateFromFocus()));
      this._register(this._editor.onDidBlurEditorText(() => this._updateFromFocus()));
      this._register(this._editor.onDidChangeModel(() => this._updateFromModel()));
      this._register(this._editor.onDidChangeConfiguration(() => this._updateFromModel()));
      this._register(TabFocus.onDidChangeTabFocus((tabFocusMode) => this._tabMovesFocus.set(tabFocusMode)));
      this._updateFromConfig();
      this._updateFromSelection();
      this._updateFromFocus();
      this._updateFromModel();
      this._editorSimpleInput.set(this._editor.isSimpleWidget);
    }
    _updateFromConfig() {
      const options = this._editor.getOptions();
      this._tabMovesFocus.set(options.get(
        164
        /* EditorOption.tabFocusMode */
      ) || TabFocus.getTabFocusMode());
      this._editorReadonly.set(options.get(
        104
        /* EditorOption.readOnly */
      ));
      this._inDiffEditor.set(options.get(
        70
        /* EditorOption.inDiffEditor */
      ));
      this._editorColumnSelection.set(options.get(
        28
        /* EditorOption.columnSelection */
      ));
    }
    _updateFromSelection() {
      const selections = this._editor.getSelections();
      if (!selections) {
        this._hasMultipleSelections.reset();
        this._hasNonEmptySelection.reset();
      } else {
        this._hasMultipleSelections.set(selections.length > 1);
        this._hasNonEmptySelection.set(selections.some((s) => !s.isEmpty()));
      }
    }
    _updateFromFocus() {
      this._editorFocus.set(this._editor.hasWidgetFocus() && !this._editor.isSimpleWidget);
      this._editorTextFocus.set(this._editor.hasTextFocus() && !this._editor.isSimpleWidget);
      this._textInputFocus.set(this._editor.hasTextFocus());
    }
    _updateFromModel() {
      const model = this._editor.getModel();
      this._canUndo.set(Boolean(model && model.canUndo()));
      this._canRedo.set(Boolean(model && model.canRedo()));
    }
  }
  class EditorModeContext extends Disposable {
    constructor(_editor, _contextKeyService, _languageFeaturesService) {
      super();
      this._editor = _editor;
      this._contextKeyService = _contextKeyService;
      this._languageFeaturesService = _languageFeaturesService;
      this._langId = EditorContextKeys.languageId.bindTo(_contextKeyService);
      this._hasCompletionItemProvider = EditorContextKeys.hasCompletionItemProvider.bindTo(_contextKeyService);
      this._hasCodeActionsProvider = EditorContextKeys.hasCodeActionsProvider.bindTo(_contextKeyService);
      this._hasCodeLensProvider = EditorContextKeys.hasCodeLensProvider.bindTo(_contextKeyService);
      this._hasDefinitionProvider = EditorContextKeys.hasDefinitionProvider.bindTo(_contextKeyService);
      this._hasDeclarationProvider = EditorContextKeys.hasDeclarationProvider.bindTo(_contextKeyService);
      this._hasImplementationProvider = EditorContextKeys.hasImplementationProvider.bindTo(_contextKeyService);
      this._hasTypeDefinitionProvider = EditorContextKeys.hasTypeDefinitionProvider.bindTo(_contextKeyService);
      this._hasHoverProvider = EditorContextKeys.hasHoverProvider.bindTo(_contextKeyService);
      this._hasDocumentHighlightProvider = EditorContextKeys.hasDocumentHighlightProvider.bindTo(_contextKeyService);
      this._hasDocumentSymbolProvider = EditorContextKeys.hasDocumentSymbolProvider.bindTo(_contextKeyService);
      this._hasReferenceProvider = EditorContextKeys.hasReferenceProvider.bindTo(_contextKeyService);
      this._hasRenameProvider = EditorContextKeys.hasRenameProvider.bindTo(_contextKeyService);
      this._hasSignatureHelpProvider = EditorContextKeys.hasSignatureHelpProvider.bindTo(_contextKeyService);
      this._hasInlayHintsProvider = EditorContextKeys.hasInlayHintsProvider.bindTo(_contextKeyService);
      this._hasDocumentFormattingProvider = EditorContextKeys.hasDocumentFormattingProvider.bindTo(_contextKeyService);
      this._hasDocumentSelectionFormattingProvider = EditorContextKeys.hasDocumentSelectionFormattingProvider.bindTo(_contextKeyService);
      this._hasMultipleDocumentFormattingProvider = EditorContextKeys.hasMultipleDocumentFormattingProvider.bindTo(_contextKeyService);
      this._hasMultipleDocumentSelectionFormattingProvider = EditorContextKeys.hasMultipleDocumentSelectionFormattingProvider.bindTo(_contextKeyService);
      this._isInEmbeddedEditor = EditorContextKeys.isInEmbeddedEditor.bindTo(_contextKeyService);
      const update = () => this._update();
      this._register(_editor.onDidChangeModel(update));
      this._register(_editor.onDidChangeModelLanguage(update));
      this._register(_languageFeaturesService.completionProvider.onDidChange(update));
      this._register(_languageFeaturesService.codeActionProvider.onDidChange(update));
      this._register(_languageFeaturesService.codeLensProvider.onDidChange(update));
      this._register(_languageFeaturesService.definitionProvider.onDidChange(update));
      this._register(_languageFeaturesService.declarationProvider.onDidChange(update));
      this._register(_languageFeaturesService.implementationProvider.onDidChange(update));
      this._register(_languageFeaturesService.typeDefinitionProvider.onDidChange(update));
      this._register(_languageFeaturesService.hoverProvider.onDidChange(update));
      this._register(_languageFeaturesService.documentHighlightProvider.onDidChange(update));
      this._register(_languageFeaturesService.documentSymbolProvider.onDidChange(update));
      this._register(_languageFeaturesService.referenceProvider.onDidChange(update));
      this._register(_languageFeaturesService.renameProvider.onDidChange(update));
      this._register(_languageFeaturesService.documentFormattingEditProvider.onDidChange(update));
      this._register(_languageFeaturesService.documentRangeFormattingEditProvider.onDidChange(update));
      this._register(_languageFeaturesService.signatureHelpProvider.onDidChange(update));
      this._register(_languageFeaturesService.inlayHintsProvider.onDidChange(update));
      update();
    }
    dispose() {
      super.dispose();
    }
    reset() {
      this._contextKeyService.bufferChangeEvents(() => {
        this._langId.reset();
        this._hasCompletionItemProvider.reset();
        this._hasCodeActionsProvider.reset();
        this._hasCodeLensProvider.reset();
        this._hasDefinitionProvider.reset();
        this._hasDeclarationProvider.reset();
        this._hasImplementationProvider.reset();
        this._hasTypeDefinitionProvider.reset();
        this._hasHoverProvider.reset();
        this._hasDocumentHighlightProvider.reset();
        this._hasDocumentSymbolProvider.reset();
        this._hasReferenceProvider.reset();
        this._hasRenameProvider.reset();
        this._hasDocumentFormattingProvider.reset();
        this._hasDocumentSelectionFormattingProvider.reset();
        this._hasSignatureHelpProvider.reset();
        this._isInEmbeddedEditor.reset();
      });
    }
    _update() {
      const model = this._editor.getModel();
      if (!model) {
        this.reset();
        return;
      }
      this._contextKeyService.bufferChangeEvents(() => {
        this._langId.set(model.getLanguageId());
        this._hasCompletionItemProvider.set(this._languageFeaturesService.completionProvider.has(model));
        this._hasCodeActionsProvider.set(this._languageFeaturesService.codeActionProvider.has(model));
        this._hasCodeLensProvider.set(this._languageFeaturesService.codeLensProvider.has(model));
        this._hasDefinitionProvider.set(this._languageFeaturesService.definitionProvider.has(model));
        this._hasDeclarationProvider.set(this._languageFeaturesService.declarationProvider.has(model));
        this._hasImplementationProvider.set(this._languageFeaturesService.implementationProvider.has(model));
        this._hasTypeDefinitionProvider.set(this._languageFeaturesService.typeDefinitionProvider.has(model));
        this._hasHoverProvider.set(this._languageFeaturesService.hoverProvider.has(model));
        this._hasDocumentHighlightProvider.set(this._languageFeaturesService.documentHighlightProvider.has(model));
        this._hasDocumentSymbolProvider.set(this._languageFeaturesService.documentSymbolProvider.has(model));
        this._hasReferenceProvider.set(this._languageFeaturesService.referenceProvider.has(model));
        this._hasRenameProvider.set(this._languageFeaturesService.renameProvider.has(model));
        this._hasSignatureHelpProvider.set(this._languageFeaturesService.signatureHelpProvider.has(model));
        this._hasInlayHintsProvider.set(this._languageFeaturesService.inlayHintsProvider.has(model));
        this._hasDocumentFormattingProvider.set(this._languageFeaturesService.documentFormattingEditProvider.has(model) || this._languageFeaturesService.documentRangeFormattingEditProvider.has(model));
        this._hasDocumentSelectionFormattingProvider.set(this._languageFeaturesService.documentRangeFormattingEditProvider.has(model));
        this._hasMultipleDocumentFormattingProvider.set(this._languageFeaturesService.documentFormattingEditProvider.all(model).length + this._languageFeaturesService.documentRangeFormattingEditProvider.all(model).length > 1);
        this._hasMultipleDocumentSelectionFormattingProvider.set(this._languageFeaturesService.documentRangeFormattingEditProvider.all(model).length > 1);
        this._isInEmbeddedEditor.set(model.uri.scheme === Schemas.walkThroughSnippet || model.uri.scheme === Schemas.vscodeChatCodeBlock);
      });
    }
  }
  class EditorDecorationsCollection {
    get length() {
      return this._decorationIds.length;
    }
    constructor(_editor, decorations) {
      this._editor = _editor;
      this._decorationIds = [];
      this._isChangingDecorations = false;
      if (Array.isArray(decorations) && decorations.length > 0) {
        this.set(decorations);
      }
    }
    onDidChange(listener, thisArgs, disposables) {
      return this._editor.onDidChangeModelDecorations((e) => {
        if (this._isChangingDecorations) {
          return;
        }
        listener.call(thisArgs, e);
      }, disposables);
    }
    getRange(index) {
      if (!this._editor.hasModel()) {
        return null;
      }
      if (index >= this._decorationIds.length) {
        return null;
      }
      return this._editor.getModel().getDecorationRange(this._decorationIds[index]);
    }
    getRanges() {
      if (!this._editor.hasModel()) {
        return [];
      }
      const model = this._editor.getModel();
      const result = [];
      for (const decorationId of this._decorationIds) {
        const range2 = model.getDecorationRange(decorationId);
        if (range2) {
          result.push(range2);
        }
      }
      return result;
    }
    has(decoration2) {
      return this._decorationIds.includes(decoration2.id);
    }
    clear() {
      if (this._decorationIds.length === 0) {
        return;
      }
      this.set([]);
    }
    set(newDecorations) {
      try {
        this._isChangingDecorations = true;
        this._editor.changeDecorations((accessor) => {
          this._decorationIds = accessor.deltaDecorations(this._decorationIds, newDecorations);
        });
      } finally {
        this._isChangingDecorations = false;
      }
      return this._decorationIds;
    }
    append(newDecorations) {
      let newDecorationIds = [];
      try {
        this._isChangingDecorations = true;
        this._editor.changeDecorations((accessor) => {
          newDecorationIds = accessor.deltaDecorations([], newDecorations);
          this._decorationIds = this._decorationIds.concat(newDecorationIds);
        });
      } finally {
        this._isChangingDecorations = false;
      }
      return newDecorationIds;
    }
  }
  const squigglyStart = encodeURIComponent(`<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 6 3' enable-background='new 0 0 6 3' height='3' width='6'><g fill='`);
  const squigglyEnd = encodeURIComponent(`'><polygon points='5.5,0 2.5,3 1.1,3 4.1,0'/><polygon points='4,0 6,2 6,0.6 5.4,0'/><polygon points='0,2 1,3 2.4,3 0,0.6'/></g></svg>`);
  function getSquigglySVGData(color) {
    return squigglyStart + encodeURIComponent(color.toString()) + squigglyEnd;
  }
  const dotdotdotStart = encodeURIComponent(`<svg xmlns="http://www.w3.org/2000/svg" height="3" width="12"><g fill="`);
  const dotdotdotEnd = encodeURIComponent(`"><circle cx="1" cy="1" r="1"/><circle cx="5" cy="1" r="1"/><circle cx="9" cy="1" r="1"/></g></svg>`);
  function getDotDotDotSVGData(color) {
    return dotdotdotStart + encodeURIComponent(color.toString()) + dotdotdotEnd;
  }
  registerThemingParticipant((theme, collector) => {
    const errorForeground = theme.getColor(editorErrorForeground);
    if (errorForeground) {
      collector.addRule(`.monaco-editor .${"squiggly-error"} { background: url("data:image/svg+xml,${getSquigglySVGData(errorForeground)}") repeat-x bottom left; }`);
      collector.addRule(`:root { --monaco-editor-error-decoration: url("data:image/svg+xml,${getSquigglySVGData(errorForeground)}"); }`);
    }
    const warningForeground = theme.getColor(editorWarningForeground);
    if (warningForeground) {
      collector.addRule(`.monaco-editor .${"squiggly-warning"} { background: url("data:image/svg+xml,${getSquigglySVGData(warningForeground)}") repeat-x bottom left; }`);
      collector.addRule(`:root { --monaco-editor-warning-decoration: url("data:image/svg+xml,${getSquigglySVGData(warningForeground)}"); }`);
    }
    const infoForeground = theme.getColor(editorInfoForeground);
    if (infoForeground) {
      collector.addRule(`.monaco-editor .${"squiggly-info"} { background: url("data:image/svg+xml,${getSquigglySVGData(infoForeground)}") repeat-x bottom left; }`);
      collector.addRule(`:root { --monaco-editor-info-decoration: url("data:image/svg+xml,${getSquigglySVGData(infoForeground)}"); }`);
    }
    const hintForeground = theme.getColor(editorHintForeground);
    if (hintForeground) {
      collector.addRule(`.monaco-editor .${"squiggly-hint"} { background: url("data:image/svg+xml,${getDotDotDotSVGData(hintForeground)}") no-repeat bottom left; }`);
      collector.addRule(`:root { --monaco-editor-hint-decoration: url("data:image/svg+xml,${getDotDotDotSVGData(hintForeground)}"); }`);
    }
    const unnecessaryForeground = theme.getColor(editorUnnecessaryCodeOpacity);
    if (unnecessaryForeground) {
      collector.addRule(`.monaco-editor.showUnused .${"squiggly-inline-unnecessary"} { opacity: ${unnecessaryForeground.rgba.a}; }`);
      collector.addRule(`:root { --monaco-editor-unnecessary-decoration-opacity: ${unnecessaryForeground.rgba.a}; }`);
    }
  });
  function readHotReloadableExport(value, reader) {
    return value;
  }
  function createHotClass(clazz) {
    {
      return constObservable(clazz);
    }
  }
  const IAccessibilitySignalService = createDecorator("accessibilitySignalService");
  const _Sound = class _Sound {
    static register(options) {
      const sound = new _Sound(options.fileName);
      return sound;
    }
    constructor(fileName) {
      this.fileName = fileName;
    }
  };
  _Sound.error = _Sound.register({ fileName: "error.mp3" });
  _Sound.warning = _Sound.register({ fileName: "warning.mp3" });
  _Sound.success = _Sound.register({ fileName: "success.mp3" });
  _Sound.foldedArea = _Sound.register({ fileName: "foldedAreas.mp3" });
  _Sound.break = _Sound.register({ fileName: "break.mp3" });
  _Sound.quickFixes = _Sound.register({ fileName: "quickFixes.mp3" });
  _Sound.taskCompleted = _Sound.register({ fileName: "taskCompleted.mp3" });
  _Sound.taskFailed = _Sound.register({ fileName: "taskFailed.mp3" });
  _Sound.terminalBell = _Sound.register({ fileName: "terminalBell.mp3" });
  _Sound.diffLineInserted = _Sound.register({ fileName: "diffLineInserted.mp3" });
  _Sound.diffLineDeleted = _Sound.register({ fileName: "diffLineDeleted.mp3" });
  _Sound.diffLineModified = _Sound.register({ fileName: "diffLineModified.mp3" });
  _Sound.requestSent = _Sound.register({ fileName: "requestSent.mp3" });
  _Sound.responseReceived1 = _Sound.register({ fileName: "responseReceived1.mp3" });
  _Sound.responseReceived2 = _Sound.register({ fileName: "responseReceived2.mp3" });
  _Sound.responseReceived3 = _Sound.register({ fileName: "responseReceived3.mp3" });
  _Sound.responseReceived4 = _Sound.register({ fileName: "responseReceived4.mp3" });
  _Sound.clear = _Sound.register({ fileName: "clear.mp3" });
  _Sound.save = _Sound.register({ fileName: "save.mp3" });
  _Sound.format = _Sound.register({ fileName: "format.mp3" });
  _Sound.voiceRecordingStarted = _Sound.register({ fileName: "voiceRecordingStarted.mp3" });
  _Sound.voiceRecordingStopped = _Sound.register({ fileName: "voiceRecordingStopped.mp3" });
  _Sound.progress = _Sound.register({ fileName: "progress.mp3" });
  _Sound.chatEditModifiedFile = _Sound.register({ fileName: "chatEditModifiedFile.mp3" });
  _Sound.editsKept = _Sound.register({ fileName: "editsKept.mp3" });
  _Sound.editsUndone = _Sound.register({ fileName: "editsUndone.mp3" });
  _Sound.nextEditSuggestion = _Sound.register({ fileName: "nextEditSuggestion.mp3" });
  _Sound.terminalCommandSucceeded = _Sound.register({ fileName: "terminalCommandSucceeded.mp3" });
  _Sound.chatUserActionRequired = _Sound.register({ fileName: "chatUserActionRequired.mp3" });
  _Sound.codeActionTriggered = _Sound.register({ fileName: "codeActionTriggered.mp3" });
  _Sound.codeActionApplied = _Sound.register({ fileName: "codeActionApplied.mp3" });
  let Sound = _Sound;
  class SoundSource {
    constructor(randomOneOf) {
      this.randomOneOf = randomOneOf;
    }
  }
  const _AccessibilitySignal = class _AccessibilitySignal {
    constructor(sound, name, legacySoundSettingsKey, settingsKey, legacyAnnouncementSettingsKey, announcementMessage, managesOwnEnablement = false) {
      this.sound = sound;
      this.name = name;
      this.legacySoundSettingsKey = legacySoundSettingsKey;
      this.settingsKey = settingsKey;
      this.legacyAnnouncementSettingsKey = legacyAnnouncementSettingsKey;
      this.announcementMessage = announcementMessage;
      this.managesOwnEnablement = managesOwnEnablement;
    }
    static register(options) {
      const soundSource = new SoundSource("randomOneOf" in options.sound ? options.sound.randomOneOf : [options.sound]);
      const signal = new _AccessibilitySignal(soundSource, options.name, options.legacySoundSettingsKey, options.settingsKey, options.legacyAnnouncementSettingsKey, options.announcementMessage, options.managesOwnEnablement);
      _AccessibilitySignal._signals.add(signal);
      return signal;
    }
  };
  _AccessibilitySignal._signals = /* @__PURE__ */ new Set();
  _AccessibilitySignal.errorAtPosition = _AccessibilitySignal.register({
    name: localize(1576, "Error at Position"),
    sound: Sound.error,
    announcementMessage: localize(1577, "Error"),
    settingsKey: "accessibility.signals.positionHasError",
    delaySettingsKey: "accessibility.signalOptions.delays.errorAtPosition"
  });
  _AccessibilitySignal.warningAtPosition = _AccessibilitySignal.register({
    name: localize(1578, "Warning at Position"),
    sound: Sound.warning,
    announcementMessage: localize(1579, "Warning"),
    settingsKey: "accessibility.signals.positionHasWarning",
    delaySettingsKey: "accessibility.signalOptions.delays.warningAtPosition"
  });
  _AccessibilitySignal.errorOnLine = _AccessibilitySignal.register({
    name: localize(1580, "Error on Line"),
    sound: Sound.error,
    legacySoundSettingsKey: "audioCues.lineHasError",
    legacyAnnouncementSettingsKey: "accessibility.alert.error",
    announcementMessage: localize(1581, "Error on Line"),
    settingsKey: "accessibility.signals.lineHasError"
  });
  _AccessibilitySignal.warningOnLine = _AccessibilitySignal.register({
    name: localize(1582, "Warning on Line"),
    sound: Sound.warning,
    legacySoundSettingsKey: "audioCues.lineHasWarning",
    legacyAnnouncementSettingsKey: "accessibility.alert.warning",
    announcementMessage: localize(1583, "Warning on Line"),
    settingsKey: "accessibility.signals.lineHasWarning"
  });
  _AccessibilitySignal.foldedArea = _AccessibilitySignal.register({
    name: localize(1584, "Folded Area on Line"),
    sound: Sound.foldedArea,
    legacySoundSettingsKey: "audioCues.lineHasFoldedArea",
    legacyAnnouncementSettingsKey: "accessibility.alert.foldedArea",
    announcementMessage: localize(1585, "Folded"),
    settingsKey: "accessibility.signals.lineHasFoldedArea"
  });
  _AccessibilitySignal.break = _AccessibilitySignal.register({
    name: localize(1586, "Breakpoint on Line"),
    sound: Sound.break,
    legacySoundSettingsKey: "audioCues.lineHasBreakpoint",
    legacyAnnouncementSettingsKey: "accessibility.alert.breakpoint",
    announcementMessage: localize(1587, "Breakpoint"),
    settingsKey: "accessibility.signals.lineHasBreakpoint"
  });
  _AccessibilitySignal.inlineSuggestion = _AccessibilitySignal.register({
    name: localize(1588, "Inline Suggestion on Line"),
    sound: Sound.quickFixes,
    legacySoundSettingsKey: "audioCues.lineHasInlineSuggestion",
    settingsKey: "accessibility.signals.lineHasInlineSuggestion"
  });
  _AccessibilitySignal.nextEditSuggestion = _AccessibilitySignal.register({
    name: localize(1589, "Next Edit Suggestion on Line"),
    sound: Sound.nextEditSuggestion,
    legacySoundSettingsKey: "audioCues.nextEditSuggestion",
    settingsKey: "accessibility.signals.nextEditSuggestion",
    announcementMessage: localize(1590, "Next Edit Suggestion")
  });
  _AccessibilitySignal.terminalQuickFix = _AccessibilitySignal.register({
    name: localize(1591, "Terminal Quick Fix"),
    sound: Sound.quickFixes,
    legacySoundSettingsKey: "audioCues.terminalQuickFix",
    legacyAnnouncementSettingsKey: "accessibility.alert.terminalQuickFix",
    announcementMessage: localize(1592, "Quick Fix"),
    settingsKey: "accessibility.signals.terminalQuickFix"
  });
  _AccessibilitySignal.onDebugBreak = _AccessibilitySignal.register({
    name: localize(1593, "Debugger Stopped on Breakpoint"),
    sound: Sound.break,
    legacySoundSettingsKey: "audioCues.onDebugBreak",
    legacyAnnouncementSettingsKey: "accessibility.alert.onDebugBreak",
    announcementMessage: localize(1594, "Breakpoint"),
    settingsKey: "accessibility.signals.onDebugBreak"
  });
  _AccessibilitySignal.noInlayHints = _AccessibilitySignal.register({
    name: localize(1595, "No Inlay Hints on Line"),
    sound: Sound.error,
    legacySoundSettingsKey: "audioCues.noInlayHints",
    legacyAnnouncementSettingsKey: "accessibility.alert.noInlayHints",
    announcementMessage: localize(1596, "No Inlay Hints"),
    settingsKey: "accessibility.signals.noInlayHints"
  });
  _AccessibilitySignal.taskCompleted = _AccessibilitySignal.register({
    name: localize(1597, "Task Completed"),
    sound: Sound.taskCompleted,
    legacySoundSettingsKey: "audioCues.taskCompleted",
    legacyAnnouncementSettingsKey: "accessibility.alert.taskCompleted",
    announcementMessage: localize(1598, "Task Completed"),
    settingsKey: "accessibility.signals.taskCompleted"
  });
  _AccessibilitySignal.taskFailed = _AccessibilitySignal.register({
    name: localize(1599, "Task Failed"),
    sound: Sound.taskFailed,
    legacySoundSettingsKey: "audioCues.taskFailed",
    legacyAnnouncementSettingsKey: "accessibility.alert.taskFailed",
    announcementMessage: localize(1600, "Task Failed"),
    settingsKey: "accessibility.signals.taskFailed"
  });
  _AccessibilitySignal.terminalCommandFailed = _AccessibilitySignal.register({
    name: localize(1601, "Terminal Command Failed"),
    sound: Sound.error,
    legacySoundSettingsKey: "audioCues.terminalCommandFailed",
    legacyAnnouncementSettingsKey: "accessibility.alert.terminalCommandFailed",
    announcementMessage: localize(1602, "Command Failed"),
    settingsKey: "accessibility.signals.terminalCommandFailed"
  });
  _AccessibilitySignal.terminalCommandSucceeded = _AccessibilitySignal.register({
    name: localize(1603, "Terminal Command Succeeded"),
    sound: Sound.terminalCommandSucceeded,
    announcementMessage: localize(1604, "Command Succeeded"),
    settingsKey: "accessibility.signals.terminalCommandSucceeded"
  });
  _AccessibilitySignal.terminalBell = _AccessibilitySignal.register({
    name: localize(1605, "Terminal Bell"),
    sound: Sound.terminalBell,
    legacySoundSettingsKey: "audioCues.terminalBell",
    legacyAnnouncementSettingsKey: "accessibility.alert.terminalBell",
    announcementMessage: localize(1606, "Terminal Bell"),
    settingsKey: "accessibility.signals.terminalBell"
  });
  _AccessibilitySignal.notebookCellCompleted = _AccessibilitySignal.register({
    name: localize(1607, "Notebook Cell Completed"),
    sound: Sound.taskCompleted,
    legacySoundSettingsKey: "audioCues.notebookCellCompleted",
    legacyAnnouncementSettingsKey: "accessibility.alert.notebookCellCompleted",
    announcementMessage: localize(1608, "Notebook Cell Completed"),
    settingsKey: "accessibility.signals.notebookCellCompleted"
  });
  _AccessibilitySignal.notebookCellFailed = _AccessibilitySignal.register({
    name: localize(1609, "Notebook Cell Failed"),
    sound: Sound.taskFailed,
    legacySoundSettingsKey: "audioCues.notebookCellFailed",
    legacyAnnouncementSettingsKey: "accessibility.alert.notebookCellFailed",
    announcementMessage: localize(1610, "Notebook Cell Failed"),
    settingsKey: "accessibility.signals.notebookCellFailed"
  });
  _AccessibilitySignal.diffLineInserted = _AccessibilitySignal.register({
    name: localize(1611, "Diff Line Inserted"),
    sound: Sound.diffLineInserted,
    legacySoundSettingsKey: "audioCues.diffLineInserted",
    settingsKey: "accessibility.signals.diffLineInserted"
  });
  _AccessibilitySignal.diffLineDeleted = _AccessibilitySignal.register({
    name: localize(1612, "Diff Line Deleted"),
    sound: Sound.diffLineDeleted,
    legacySoundSettingsKey: "audioCues.diffLineDeleted",
    settingsKey: "accessibility.signals.diffLineDeleted"
  });
  _AccessibilitySignal.diffLineModified = _AccessibilitySignal.register({
    name: localize(1613, "Diff Line Modified"),
    sound: Sound.diffLineModified,
    legacySoundSettingsKey: "audioCues.diffLineModified",
    settingsKey: "accessibility.signals.diffLineModified"
  });
  _AccessibilitySignal.chatEditModifiedFile = _AccessibilitySignal.register({
    name: localize(1614, "Chat Edit Modified File"),
    sound: Sound.chatEditModifiedFile,
    announcementMessage: localize(1615, "File Modified from Chat Edits"),
    settingsKey: "accessibility.signals.chatEditModifiedFile"
  });
  _AccessibilitySignal.chatRequestSent = _AccessibilitySignal.register({
    name: localize(1616, "Chat Request Sent"),
    sound: Sound.requestSent,
    legacySoundSettingsKey: "audioCues.chatRequestSent",
    legacyAnnouncementSettingsKey: "accessibility.alert.chatRequestSent",
    announcementMessage: localize(1617, "Chat Request Sent"),
    settingsKey: "accessibility.signals.chatRequestSent"
  });
  _AccessibilitySignal.chatResponseReceived = _AccessibilitySignal.register({
    name: localize(1618, "Chat Response Received"),
    legacySoundSettingsKey: "audioCues.chatResponseReceived",
    sound: {
      randomOneOf: [
        Sound.responseReceived1,
        Sound.responseReceived2,
        Sound.responseReceived3,
        Sound.responseReceived4
      ]
    },
    settingsKey: "accessibility.signals.chatResponseReceived"
  });
  _AccessibilitySignal.codeActionTriggered = _AccessibilitySignal.register({
    name: localize(1619, "Code Action Request Triggered"),
    sound: Sound.codeActionTriggered,
    legacySoundSettingsKey: "audioCues.codeActionRequestTriggered",
    legacyAnnouncementSettingsKey: "accessibility.alert.codeActionRequestTriggered",
    announcementMessage: localize(1620, "Code Action Request Triggered"),
    settingsKey: "accessibility.signals.codeActionTriggered"
  });
  _AccessibilitySignal.codeActionApplied = _AccessibilitySignal.register({
    name: localize(1621, "Code Action Applied"),
    legacySoundSettingsKey: "audioCues.codeActionApplied",
    sound: Sound.codeActionApplied,
    settingsKey: "accessibility.signals.codeActionApplied"
  });
  _AccessibilitySignal.progress = _AccessibilitySignal.register({
    name: localize(1622, "Progress"),
    sound: Sound.progress,
    legacySoundSettingsKey: "audioCues.chatResponsePending",
    legacyAnnouncementSettingsKey: "accessibility.alert.progress",
    announcementMessage: localize(1623, "Progress"),
    settingsKey: "accessibility.signals.progress"
  });
  _AccessibilitySignal.clear = _AccessibilitySignal.register({
    name: localize(1624, "Clear"),
    sound: Sound.clear,
    legacySoundSettingsKey: "audioCues.clear",
    legacyAnnouncementSettingsKey: "accessibility.alert.clear",
    announcementMessage: localize(1625, "Clear"),
    settingsKey: "accessibility.signals.clear"
  });
  _AccessibilitySignal.save = _AccessibilitySignal.register({
    name: localize(1626, "Save"),
    sound: Sound.save,
    legacySoundSettingsKey: "audioCues.save",
    legacyAnnouncementSettingsKey: "accessibility.alert.save",
    announcementMessage: localize(1627, "Save"),
    settingsKey: "accessibility.signals.save"
  });
  _AccessibilitySignal.format = _AccessibilitySignal.register({
    name: localize(1628, "Format"),
    sound: Sound.format,
    legacySoundSettingsKey: "audioCues.format",
    legacyAnnouncementSettingsKey: "accessibility.alert.format",
    announcementMessage: localize(1629, "Format"),
    settingsKey: "accessibility.signals.format"
  });
  _AccessibilitySignal.voiceRecordingStarted = _AccessibilitySignal.register({
    name: localize(1630, "Voice Recording Started"),
    sound: Sound.voiceRecordingStarted,
    legacySoundSettingsKey: "audioCues.voiceRecordingStarted",
    settingsKey: "accessibility.signals.voiceRecordingStarted"
  });
  _AccessibilitySignal.voiceRecordingStopped = _AccessibilitySignal.register({
    name: localize(1631, "Voice Recording Stopped"),
    sound: Sound.voiceRecordingStopped,
    legacySoundSettingsKey: "audioCues.voiceRecordingStopped",
    settingsKey: "accessibility.signals.voiceRecordingStopped"
  });
  _AccessibilitySignal.editsKept = _AccessibilitySignal.register({
    name: localize(1632, "Edits Kept"),
    sound: Sound.editsKept,
    announcementMessage: localize(1633, "Edits Kept"),
    settingsKey: "accessibility.signals.editsKept"
  });
  _AccessibilitySignal.editsUndone = _AccessibilitySignal.register({
    name: localize(1634, "Undo Edits"),
    sound: Sound.editsUndone,
    announcementMessage: localize(1635, "Edits Undone"),
    settingsKey: "accessibility.signals.editsUndone"
  });
  _AccessibilitySignal.chatUserActionRequired = _AccessibilitySignal.register({
    name: localize(1636, "Chat User Action Required"),
    sound: Sound.chatUserActionRequired,
    announcementMessage: localize(1637, "Chat User Action Required"),
    settingsKey: "accessibility.signals.chatUserActionRequired",
    managesOwnEnablement: true
  });
  let AccessibilitySignal = _AccessibilitySignal;
  function observableConfigValue(key, defaultValue, configurationService, debugLocation = DebugLocation.ofCaller()) {
    return observableFromEventOpts({ debugName: () => `Configuration Key "${key}"` }, (handleChange) => configurationService.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration(key)) {
        handleChange(e);
      }
    }), () => configurationService.getValue(key) ?? defaultValue, debugLocation);
  }
  function bindContextKey(key, service, computeValue, debugLocation = DebugLocation.ofCaller()) {
    const boundKey = key.bindTo(service);
    const store = new DisposableStore();
    derivedOpts({ debugName: () => `Set Context Key "${key.key}"` }, (reader) => {
      const value = computeValue(reader);
      boundKey.set(value);
      return value;
    }, debugLocation).recomputeInitiallyAndOnChange(store);
    return store;
  }
  const IProgressService = createDecorator("progressService");
  const _Progress = class _Progress {
    constructor(callback) {
      this.callback = callback;
    }
    report(item) {
      this._value = item;
      this.callback(this._value);
    }
  };
  _Progress.None = Object.freeze({ report() {
  } });
  let Progress = _Progress;
  const IEditorProgressService = createDecorator("editorProgressService");
  class StableEditorScrollState {
    static capture(editor2) {
      if (editor2.getScrollTop() === 0 || editor2.hasPendingScrollAnimation()) {
        return new StableEditorScrollState(editor2.getScrollTop(), editor2.getContentHeight(), null, 0, null);
      }
      let visiblePosition = null;
      let visiblePositionScrollDelta = 0;
      const visibleRanges = editor2.getVisibleRanges();
      if (visibleRanges.length > 0) {
        visiblePosition = visibleRanges[0].getStartPosition();
        const visiblePositionScrollTop = editor2.getTopForPosition(visiblePosition.lineNumber, visiblePosition.column);
        visiblePositionScrollDelta = editor2.getScrollTop() - visiblePositionScrollTop;
      }
      return new StableEditorScrollState(editor2.getScrollTop(), editor2.getContentHeight(), visiblePosition, visiblePositionScrollDelta, editor2.getPosition());
    }
    constructor(_initialScrollTop, _initialContentHeight, _visiblePosition, _visiblePositionScrollDelta, _cursorPosition) {
      this._initialScrollTop = _initialScrollTop;
      this._initialContentHeight = _initialContentHeight;
      this._visiblePosition = _visiblePosition;
      this._visiblePositionScrollDelta = _visiblePositionScrollDelta;
      this._cursorPosition = _cursorPosition;
    }
    restore(editor2) {
      if (this._initialContentHeight === editor2.getContentHeight() && this._initialScrollTop === editor2.getScrollTop()) {
        return;
      }
      if (this._visiblePosition) {
        const visiblePositionScrollTop = editor2.getTopForPosition(this._visiblePosition.lineNumber, this._visiblePosition.column);
        editor2.setScrollTop(visiblePositionScrollTop + this._visiblePositionScrollDelta);
      }
    }
    restoreRelativeVerticalPositionOfCursor(editor2) {
      if (this._initialContentHeight === editor2.getContentHeight() && this._initialScrollTop === editor2.getScrollTop()) {
        return;
      }
      const currentCursorPosition = editor2.getPosition();
      if (!this._cursorPosition || !currentCursorPosition) {
        return;
      }
      const offset = editor2.getTopForLineNumber(currentCursorPosition.lineNumber) - editor2.getTopForLineNumber(this._cursorPosition.lineNumber);
      editor2.setScrollTop(
        editor2.getScrollTop() + offset,
        1
        /* ScrollType.Immediate */
      );
    }
  }
  const DataTransfers = {
    /**
     * Application specific resource transfer type
     */
    RESOURCES: "ResourceURLs",
    /**
     * Typically transfer type for copy/paste transfers.
     */
    TEXT: Mimes.text,
    /**
     * Internal type used to pass around text/uri-list data.
     *
     * This is needed to work around https://bugs.chromium.org/p/chromium/issues/detail?id=239745.
     */
    INTERNAL_URI_LIST: "application/vnd.code.uri-list"
  };
  const nullHoverDelegateFactory = () => ({
    get delay() {
      return -1;
    },
    dispose: () => {
    },
    showHover: () => {
      return void 0;
    }
  });
  let hoverDelegateFactory = nullHoverDelegateFactory;
  const defaultHoverDelegateMouse = new Lazy(() => hoverDelegateFactory("mouse", false));
  const defaultHoverDelegateElement = new Lazy(() => hoverDelegateFactory("element", false));
  function setHoverDelegateFactory(hoverDelegateProvider) {
    hoverDelegateFactory = hoverDelegateProvider;
  }
  function getDefaultHoverDelegate(placement) {
    if (placement === "element") {
      return defaultHoverDelegateElement.value;
    }
    return defaultHoverDelegateMouse.value;
  }
  function createInstantHoverDelegate() {
    return hoverDelegateFactory("element", true);
  }
  function asFragment(raw) {
    return raw;
  }
  function asCssValueWithDefault(cssPropertyValue, dflt) {
    if (cssPropertyValue !== void 0) {
      const variableMatch = cssPropertyValue.match(/^\s*var\((.+)\)$/);
      if (variableMatch) {
        const varArguments = variableMatch[1].split(",", 2);
        if (varArguments.length === 2) {
          dflt = asCssValueWithDefault(varArguments[1].trim(), dflt);
        }
        return `var(${varArguments[0]}, ${dflt})`;
      }
      return cssPropertyValue;
    }
    return dflt;
  }
  function identValue(value) {
    const out = value.replaceAll(/[^_\-a-z0-9]/gi, "");
    if (out !== value) {
      console.warn(`CSS ident value ${value} modified to ${out} to be safe for CSS`);
    }
    return asFragment(out);
  }
  function stringValue(value) {
    return asFragment(`'${value.replaceAll(/'/g, "\\000027")}'`);
  }
  function asCSSUrl(uri) {
    if (!uri) {
      return asFragment(`url('')`);
    }
    return inline$1`url('${asFragment(CSS.escape(FileAccess.uriToBrowserUri(uri).toString(true)))}')`;
  }
  function className(value, escapingExpected = false) {
    const out = CSS.escape(value);
    if (!escapingExpected && out !== value) {
      console.warn(`CSS class name ${value} modified to ${out} to be safe for CSS`);
    }
    return asFragment(out);
  }
  function inline$1(strings, ...values) {
    return asFragment(strings.reduce((result, str, i2) => {
      const value = values[i2] || "";
      return result + str + value;
    }, ""));
  }
  class Builder {
    constructor() {
      this._parts = [];
    }
    push(...parts) {
      this._parts.push(...parts);
    }
    join(joiner = "\n") {
      return asFragment(this._parts.join(joiner));
    }
  }
  function getKoreanAltChars(code) {
    const result = disassembleKorean(code);
    if (result && result.length > 0) {
      return new Uint32Array(result);
    }
    return void 0;
  }
  let codeBufferLength = 0;
  const codeBuffer = new Uint32Array(10);
  function disassembleKorean(code) {
    codeBufferLength = 0;
    getCodesFromArray(
      code,
      modernConsonants,
      4352
      /* HangulRangeStartCode.InitialConsonant */
    );
    if (codeBufferLength > 0) {
      return codeBuffer.subarray(0, codeBufferLength);
    }
    getCodesFromArray(
      code,
      modernVowels,
      4449
      /* HangulRangeStartCode.Vowel */
    );
    if (codeBufferLength > 0) {
      return codeBuffer.subarray(0, codeBufferLength);
    }
    getCodesFromArray(
      code,
      modernFinalConsonants,
      4520
      /* HangulRangeStartCode.FinalConsonant */
    );
    if (codeBufferLength > 0) {
      return codeBuffer.subarray(0, codeBufferLength);
    }
    getCodesFromArray(
      code,
      compatibilityJamo,
      12593
      /* HangulRangeStartCode.CompatibilityJamo */
    );
    if (codeBufferLength) {
      return codeBuffer.subarray(0, codeBufferLength);
    }
    if (code >= 44032 && code <= 55203) {
      const hangulIndex = code - 44032;
      const vowelAndFinalConsonantProduct = hangulIndex % 588;
      const initialConsonantIndex = Math.floor(hangulIndex / 588);
      const vowelIndex = Math.floor(vowelAndFinalConsonantProduct / 28);
      const finalConsonantIndex = vowelAndFinalConsonantProduct % 28 - 1;
      if (initialConsonantIndex < modernConsonants.length) {
        getCodesFromArray(initialConsonantIndex, modernConsonants, 0);
      } else if (4352 + initialConsonantIndex - 12593 < compatibilityJamo.length) {
        getCodesFromArray(
          4352 + initialConsonantIndex,
          compatibilityJamo,
          12593
          /* HangulRangeStartCode.CompatibilityJamo */
        );
      }
      if (vowelIndex < modernVowels.length) {
        getCodesFromArray(vowelIndex, modernVowels, 0);
      } else if (4449 + vowelIndex - 12593 < compatibilityJamo.length) {
        getCodesFromArray(
          4449 + vowelIndex - 12593,
          compatibilityJamo,
          12593
          /* HangulRangeStartCode.CompatibilityJamo */
        );
      }
      if (finalConsonantIndex >= 0) {
        if (finalConsonantIndex < modernFinalConsonants.length) {
          getCodesFromArray(finalConsonantIndex, modernFinalConsonants, 0);
        } else if (4520 + finalConsonantIndex - 12593 < compatibilityJamo.length) {
          getCodesFromArray(
            4520 + finalConsonantIndex - 12593,
            compatibilityJamo,
            12593
            /* HangulRangeStartCode.CompatibilityJamo */
          );
        }
      }
      if (codeBufferLength > 0) {
        return codeBuffer.subarray(0, codeBufferLength);
      }
    }
    return void 0;
  }
  function getCodesFromArray(code, array2, arrayStartIndex) {
    if (code >= arrayStartIndex && code < arrayStartIndex + array2.length) {
      addCodesToBuffer(array2[code - arrayStartIndex]);
    }
  }
  function addCodesToBuffer(codes) {
    if (codes === 0) {
      return;
    }
    codeBuffer[codeBufferLength++] = codes & 255;
    if (codes >> 8) {
      codeBuffer[codeBufferLength++] = codes >> 8 & 255;
    }
    if (codes >> 16) {
      codeBuffer[codeBufferLength++] = codes >> 16 & 255;
    }
  }
  const modernConsonants = new Uint8Array([
    114,
    // ㄱ
    82,
    // ㄲ
    115,
    // ㄴ
    101,
    // ㄷ
    69,
    // ㄸ
    102,
    // ㄹ
    97,
    // ㅁ
    113,
    // ㅂ
    81,
    // ㅃ
    116,
    // ㅅ
    84,
    // ㅆ
    100,
    // ㅇ
    119,
    // ㅈ
    87,
    // ㅉ
    99,
    // ㅊ
    122,
    // ㅋ
    120,
    // ㅌ
    118,
    // ㅍ
    103
    // ㅎ
  ]);
  const modernVowels = new Uint16Array([
    107,
    //  -> ㅏ
    111,
    //  -> ㅐ
    105,
    //  -> ㅑ
    79,
    //  -> ㅒ
    106,
    //  -> ㅓ
    112,
    //  -> ㅔ
    117,
    //  -> ㅕ
    80,
    //  -> ㅖ
    104,
    //  -> ㅗ
    27496,
    //  -> ㅘ
    28520,
    //  -> ㅙ
    27752,
    //  -> ㅚ
    121,
    //  -> ㅛ
    110,
    //  -> ㅜ
    27246,
    //  -> ㅝ
    28782,
    //  -> ㅞ
    27758,
    //  -> ㅟ
    98,
    //  -> ㅠ
    109,
    //  -> ㅡ
    27757,
    //  -> ㅢ
    108
    //  -> ㅣ
  ]);
  const modernFinalConsonants = new Uint16Array([
    114,
    // ㄱ
    82,
    // ㄲ
    29810,
    // ㄳ
    115,
    // ㄴ
    30579,
    // ㄵ
    26483,
    // ㄶ
    101,
    // ㄷ
    102,
    // ㄹ
    29286,
    // ㄺ
    24934,
    // ㄻ
    29030,
    // ㄼ
    29798,
    // ㄽ
    30822,
    // ㄾ
    30310,
    // ㄿ
    26470,
    // ㅀ
    97,
    // ㅁ
    113,
    // ㅂ
    29809,
    // ㅄ
    116,
    // ㅅ
    84,
    // ㅆ
    100,
    // ㅇ
    119,
    // ㅈ
    99,
    // ㅊ
    122,
    // ㅋ
    120,
    // ㅌ
    118,
    // ㅍ
    103
    // ㅎ
  ]);
  const compatibilityJamo = new Uint16Array([
    114,
    // ㄱ
    82,
    // ㄲ
    29810,
    // ㄳ
    115,
    // ㄴ
    30579,
    // ㄵ
    26483,
    // ㄶ
    101,
    // ㄷ
    69,
    // ㄸ
    102,
    // ㄹ
    29286,
    // ㄺ
    24934,
    // ㄻ
    29030,
    // ㄼ
    29798,
    // ㄽ
    30822,
    // ㄾ
    30310,
    // ㄿ
    26470,
    // ㅀ
    97,
    // ㅁ
    113,
    // ㅂ
    81,
    // ㅃ
    29809,
    // ㅄ
    116,
    // ㅅ
    84,
    // ㅆ
    100,
    // ㅇ
    119,
    // ㅈ
    87,
    // ㅉ
    99,
    // ㅊ
    122,
    // ㅋ
    120,
    // ㅌ
    118,
    // ㅍ
    103,
    // ㅎ
    107,
    // ㅏ
    111,
    // ㅐ
    105,
    // ㅑ
    79,
    // ㅒ
    106,
    // ㅓ
    112,
    // ㅔ
    117,
    // ㅕ
    80,
    // ㅖ
    104,
    // ㅗ
    27496,
    // ㅘ
    28520,
    // ㅙ
    27752,
    // ㅚ
    121,
    // ㅛ
    110,
    // ㅜ
    27246,
    // ㅝ
    28782,
    // ㅞ
    27758,
    // ㅟ
    98,
    // ㅠ
    109,
    // ㅡ
    27757,
    // ㅢ
    108
    // ㅣ
    // HF: Hangul Filler (everything after this is archaic)
    // ㅥ
    // ㅦ
    // ㅧ
    // ㅨ
    // ㅩ
    // ㅪ
    // ㅫ
    // ㅬ
    // ㅮ
    // ㅯ
    // ㅰ
    // ㅱ
    // ㅲ
    // ㅳ
    // ㅴ
    // ㅵ
    // ㅶ
    // ㅷ
    // ㅸ
    // ㅹ
    // ㅺ
    // ㅻ
    // ㅼ
    // ㅽ
    // ㅾ
    // ㅿ
    // ㆀ
    // ㆁ
    // ㆂ
    // ㆃ
    // ㆄ
    // ㆅ
    // ㆆ
    // ㆇ
    // ㆈ
    // ㆉ
    // ㆊ
    // ㆋ
    // ㆌ
    // ㆍ
    // ㆎ
  ]);
  function or(...filter) {
    return function(word, wordToMatchAgainst) {
      for (let i2 = 0, len = filter.length; i2 < len; i2++) {
        const match2 = filter[i2](word, wordToMatchAgainst);
        if (match2) {
          return match2;
        }
      }
      return null;
    };
  }
  _matchesPrefix.bind(void 0, false);
  const matchesPrefix = _matchesPrefix.bind(void 0, true);
  function _matchesPrefix(ignoreCase, word, wordToMatchAgainst) {
    if (!wordToMatchAgainst || wordToMatchAgainst.length < word.length) {
      return null;
    }
    let matches;
    if (ignoreCase) {
      matches = startsWithIgnoreCase(wordToMatchAgainst, word);
    } else {
      matches = wordToMatchAgainst.indexOf(word) === 0;
    }
    if (!matches) {
      return null;
    }
    return word.length > 0 ? [{ start: 0, end: word.length }] : [];
  }
  function matchesContiguousSubString(word, wordToMatchAgainst) {
    const index = wordToMatchAgainst.toLowerCase().indexOf(word.toLowerCase());
    if (index === -1) {
      return null;
    }
    return [{ start: index, end: index + word.length }];
  }
  function matchesSubString(word, wordToMatchAgainst) {
    return _matchesSubString(word.toLowerCase(), wordToMatchAgainst.toLowerCase(), 0, 0);
  }
  function _matchesSubString(word, wordToMatchAgainst, i2, j) {
    if (i2 === word.length) {
      return [];
    } else if (j === wordToMatchAgainst.length) {
      return null;
    } else {
      if (word[i2] === wordToMatchAgainst[j]) {
        let result = null;
        if (result = _matchesSubString(word, wordToMatchAgainst, i2 + 1, j + 1)) {
          return join({ start: j, end: j + 1 }, result);
        }
        return null;
      }
      return _matchesSubString(word, wordToMatchAgainst, i2, j + 1);
    }
  }
  function isLower(code) {
    return 97 <= code && code <= 122;
  }
  function isUpper(code) {
    return 65 <= code && code <= 90;
  }
  function isNumber(code) {
    return 48 <= code && code <= 57;
  }
  function isWhitespace(code) {
    return code === 32 || code === 9 || code === 10 || code === 13;
  }
  const wordSeparators = /* @__PURE__ */ new Set();
  "()[]{}<>`'\"-/;:,.?!".split("").forEach((s) => wordSeparators.add(s.charCodeAt(0)));
  function isWordSeparator(code) {
    return isWhitespace(code) || wordSeparators.has(code);
  }
  function charactersMatch(codeA, codeB) {
    return codeA === codeB || isWordSeparator(codeA) && isWordSeparator(codeB);
  }
  const alternateCharsCache = /* @__PURE__ */ new Map();
  function getAlternateCodes(code) {
    if (alternateCharsCache.has(code)) {
      return alternateCharsCache.get(code);
    }
    let result;
    const codes = getKoreanAltChars(code);
    if (codes) {
      result = codes;
    }
    alternateCharsCache.set(code, result);
    return result;
  }
  function isAlphanumeric(code) {
    return isLower(code) || isUpper(code) || isNumber(code);
  }
  function join(head, tail2) {
    if (tail2.length === 0) {
      tail2 = [head];
    } else if (head.end === tail2[0].start) {
      tail2[0].start = head.start;
    } else {
      tail2.unshift(head);
    }
    return tail2;
  }
  function nextAnchor(camelCaseWord, start) {
    for (let i2 = start; i2 < camelCaseWord.length; i2++) {
      const c = camelCaseWord.charCodeAt(i2);
      if (isUpper(c) || isNumber(c) || i2 > 0 && !isAlphanumeric(camelCaseWord.charCodeAt(i2 - 1))) {
        return i2;
      }
    }
    return camelCaseWord.length;
  }
  function _matchesCamelCase(word, camelCaseWord, i2, j) {
    if (i2 === word.length) {
      return [];
    } else if (j === camelCaseWord.length) {
      return null;
    } else if (word[i2] !== camelCaseWord[j].toLowerCase()) {
      return null;
    } else {
      let result = null;
      let nextUpperIndex = j + 1;
      result = _matchesCamelCase(word, camelCaseWord, i2 + 1, j + 1);
      while (!result && (nextUpperIndex = nextAnchor(camelCaseWord, nextUpperIndex)) < camelCaseWord.length) {
        result = _matchesCamelCase(word, camelCaseWord, i2 + 1, nextUpperIndex);
        nextUpperIndex++;
      }
      return result === null ? null : join({ start: j, end: j + 1 }, result);
    }
  }
  function analyzeCamelCaseWord(word) {
    let upper = 0, lower = 0, alpha = 0, numeric = 0, code = 0;
    for (let i2 = 0; i2 < word.length; i2++) {
      code = word.charCodeAt(i2);
      if (isUpper(code)) {
        upper++;
      }
      if (isLower(code)) {
        lower++;
      }
      if (isAlphanumeric(code)) {
        alpha++;
      }
      if (isNumber(code)) {
        numeric++;
      }
    }
    const upperPercent = upper / word.length;
    const lowerPercent = lower / word.length;
    const alphaPercent = alpha / word.length;
    const numericPercent = numeric / word.length;
    return { upperPercent, lowerPercent, alphaPercent, numericPercent };
  }
  function isUpperCaseWord(analysis) {
    const { upperPercent, lowerPercent } = analysis;
    return lowerPercent === 0 && upperPercent > 0.6;
  }
  function isCamelCaseWord(analysis) {
    const { upperPercent, lowerPercent, alphaPercent, numericPercent } = analysis;
    return lowerPercent > 0.2 && upperPercent < 0.8 && alphaPercent > 0.6 && numericPercent < 0.2;
  }
  function isCamelCasePattern(word) {
    let upper = 0, lower = 0, code = 0, whitespace = 0;
    for (let i2 = 0; i2 < word.length; i2++) {
      code = word.charCodeAt(i2);
      if (isUpper(code)) {
        upper++;
      }
      if (isLower(code)) {
        lower++;
      }
      if (isWhitespace(code)) {
        whitespace++;
      }
    }
    if ((upper === 0 || lower === 0) && whitespace === 0) {
      return word.length <= 30;
    } else {
      return upper <= 5;
    }
  }
  function matchesCamelCase(word, camelCaseWord) {
    if (!camelCaseWord) {
      return null;
    }
    camelCaseWord = camelCaseWord.trim();
    if (camelCaseWord.length === 0) {
      return null;
    }
    if (!isCamelCasePattern(word)) {
      return null;
    }
    if (camelCaseWord.length > 60) {
      camelCaseWord = camelCaseWord.substring(0, 60);
    }
    const analysis = analyzeCamelCaseWord(camelCaseWord);
    if (!isCamelCaseWord(analysis)) {
      if (!isUpperCaseWord(analysis)) {
        return null;
      }
      camelCaseWord = camelCaseWord.toLowerCase();
    }
    let result = null;
    let i2 = 0;
    word = word.toLowerCase();
    while (i2 < camelCaseWord.length && (result = _matchesCamelCase(word, camelCaseWord, 0, i2)) === null) {
      i2 = nextAnchor(camelCaseWord, i2 + 1);
    }
    return result;
  }
  function matchesWords(word, target, contiguous = false) {
    if (!target || target.length === 0) {
      return null;
    }
    let result = null;
    let targetIndex = 0;
    word = word.toLowerCase();
    target = target.toLowerCase();
    while (targetIndex < target.length) {
      result = _matchesWords(word, target, 0, targetIndex, contiguous);
      if (result !== null) {
        break;
      }
      targetIndex = nextWord(target, targetIndex + 1);
    }
    return result;
  }
  function _matchesWords(word, target, wordIndex, targetIndex, contiguous) {
    let targetIndexOffset = 0;
    if (wordIndex === word.length) {
      return [];
    } else if (targetIndex === target.length) {
      return null;
    } else if (!charactersMatch(word.charCodeAt(wordIndex), target.charCodeAt(targetIndex))) {
      const altChars = getAlternateCodes(word.charCodeAt(wordIndex));
      if (!altChars) {
        return null;
      }
      for (let k = 0; k < altChars.length; k++) {
        if (!charactersMatch(altChars[k], target.charCodeAt(targetIndex + k))) {
          return null;
        }
      }
      targetIndexOffset += altChars.length - 1;
    }
    let result = null;
    let nextWordIndex = targetIndex + targetIndexOffset + 1;
    result = _matchesWords(word, target, wordIndex + 1, nextWordIndex, contiguous);
    if (!contiguous) {
      while (!result && (nextWordIndex = nextWord(target, nextWordIndex)) < target.length) {
        result = _matchesWords(word, target, wordIndex + 1, nextWordIndex, contiguous);
        nextWordIndex++;
      }
    }
    if (!result) {
      return null;
    }
    if (word.charCodeAt(wordIndex) !== target.charCodeAt(targetIndex)) {
      const altChars = getAlternateCodes(word.charCodeAt(wordIndex));
      if (!altChars) {
        return result;
      }
      for (let k = 0; k < altChars.length; k++) {
        if (altChars[k] !== target.charCodeAt(targetIndex + k)) {
          return result;
        }
      }
    }
    return join({ start: targetIndex, end: targetIndex + targetIndexOffset + 1 }, result);
  }
  function nextWord(word, start) {
    for (let i2 = start; i2 < word.length; i2++) {
      if (isWordSeparator(word.charCodeAt(i2)) || i2 > 0 && isWordSeparator(word.charCodeAt(i2 - 1))) {
        return i2;
      }
    }
    return word.length;
  }
  const fuzzyContiguousFilter = or(matchesPrefix, matchesCamelCase, matchesContiguousSubString);
  const fuzzySeparateFilter = or(matchesPrefix, matchesCamelCase, matchesSubString);
  const fuzzyRegExpCache = new LRUCache(1e4);
  function matchesFuzzy(word, wordToMatchAgainst, enableSeparateSubstringMatching = false) {
    if (typeof word !== "string" || typeof wordToMatchAgainst !== "string") {
      return null;
    }
    let regexp = fuzzyRegExpCache.get(word);
    if (!regexp) {
      regexp = new RegExp(convertSimple2RegExpPattern(word), "i");
      fuzzyRegExpCache.set(word, regexp);
    }
    const match2 = regexp.exec(wordToMatchAgainst);
    if (match2) {
      return [{ start: match2.index, end: match2.index + match2[0].length }];
    }
    return enableSeparateSubstringMatching ? fuzzySeparateFilter(word, wordToMatchAgainst) : fuzzyContiguousFilter(word, wordToMatchAgainst);
  }
  function matchesFuzzy2(pattern, word) {
    const score2 = fuzzyScore(pattern, pattern.toLowerCase(), 0, word, word.toLowerCase(), 0, { firstMatchCanBeWeak: true, boostFullMatch: true });
    return score2 ? createMatches(score2) : null;
  }
  function anyScore(pattern, lowPattern, patternPos, word, lowWord, wordPos) {
    const max = Math.min(13, pattern.length);
    for (; patternPos < max; patternPos++) {
      const result = fuzzyScore(pattern, lowPattern, patternPos, word, lowWord, wordPos, { firstMatchCanBeWeak: true, boostFullMatch: true });
      if (result) {
        return result;
      }
    }
    return [0, wordPos];
  }
  function createMatches(score2) {
    if (typeof score2 === "undefined") {
      return [];
    }
    const res = [];
    const wordPos = score2[1];
    for (let i2 = score2.length - 1; i2 > 1; i2--) {
      const pos = score2[i2] + wordPos;
      const last = res[res.length - 1];
      if (last && last.end === pos) {
        last.end = pos + 1;
      } else {
        res.push({ start: pos, end: pos + 1 });
      }
    }
    return res;
  }
  const _maxLen = 128;
  function initTable() {
    const table = [];
    const row = [];
    for (let i2 = 0; i2 <= _maxLen; i2++) {
      row[i2] = 0;
    }
    for (let i2 = 0; i2 <= _maxLen; i2++) {
      table.push(row.slice(0));
    }
    return table;
  }
  function initArr(maxLen) {
    const row = [];
    for (let i2 = 0; i2 <= maxLen; i2++) {
      row[i2] = 0;
    }
    return row;
  }
  const _minWordMatchPos = initArr(2 * _maxLen);
  const _maxWordMatchPos = initArr(2 * _maxLen);
  const _diag = initTable();
  const _table = initTable();
  const _arrows = initTable();
  function isSeparatorAtPos(value, index) {
    if (index < 0 || index >= value.length) {
      return false;
    }
    const code = value.codePointAt(index);
    switch (code) {
      case 95:
      case 45:
      case 46:
      case 32:
      case 47:
      case 92:
      case 39:
      case 34:
      case 58:
      case 36:
      case 60:
      case 62:
      case 40:
      case 41:
      case 91:
      case 93:
      case 123:
      case 125:
        return true;
      case void 0:
        return false;
      default:
        if (isEmojiImprecise(code)) {
          return true;
        }
        return false;
    }
  }
  function isWhitespaceAtPos(value, index) {
    if (index < 0 || index >= value.length) {
      return false;
    }
    const code = value.charCodeAt(index);
    switch (code) {
      case 32:
      case 9:
        return true;
      default:
        return false;
    }
  }
  function isUpperCaseAtPos(pos, word, wordLow) {
    return word[pos] !== wordLow[pos];
  }
  function isPatternInWord(patternLow, patternPos, patternLen, wordLow, wordPos, wordLen, fillMinWordPosArr = false) {
    while (patternPos < patternLen && wordPos < wordLen) {
      if (patternLow[patternPos] === wordLow[wordPos]) {
        if (fillMinWordPosArr) {
          _minWordMatchPos[patternPos] = wordPos;
        }
        patternPos += 1;
      }
      wordPos += 1;
    }
    return patternPos === patternLen;
  }
  var FuzzyScore;
  (function(FuzzyScore2) {
    FuzzyScore2.Default = [-100, 0];
    function isDefault(score2) {
      return !score2 || score2.length === 2 && score2[0] === -100 && score2[1] === 0;
    }
    FuzzyScore2.isDefault = isDefault;
  })(FuzzyScore || (FuzzyScore = {}));
  const _FuzzyScoreOptions = class _FuzzyScoreOptions {
    constructor(firstMatchCanBeWeak, boostFullMatch) {
      this.firstMatchCanBeWeak = firstMatchCanBeWeak;
      this.boostFullMatch = boostFullMatch;
    }
  };
  _FuzzyScoreOptions.default = { boostFullMatch: true, firstMatchCanBeWeak: false };
  let FuzzyScoreOptions = _FuzzyScoreOptions;
  function fuzzyScore(pattern, patternLow, patternStart, word, wordLow, wordStart, options = FuzzyScoreOptions.default) {
    const patternLen = pattern.length > _maxLen ? _maxLen : pattern.length;
    const wordLen = word.length > _maxLen ? _maxLen : word.length;
    if (patternStart >= patternLen || wordStart >= wordLen || patternLen - patternStart > wordLen - wordStart) {
      return void 0;
    }
    if (!isPatternInWord(patternLow, patternStart, patternLen, wordLow, wordStart, wordLen, true)) {
      return void 0;
    }
    _fillInMaxWordMatchPos(patternLen, wordLen, patternStart, wordStart, patternLow, wordLow);
    let row = 1;
    let column = 1;
    let patternPos = patternStart;
    let wordPos = wordStart;
    const hasStrongFirstMatch = [false];
    for (row = 1, patternPos = patternStart; patternPos < patternLen; row++, patternPos++) {
      const minWordMatchPos = _minWordMatchPos[patternPos];
      const maxWordMatchPos = _maxWordMatchPos[patternPos];
      const nextMaxWordMatchPos = patternPos + 1 < patternLen ? _maxWordMatchPos[patternPos + 1] : wordLen;
      for (column = minWordMatchPos - wordStart + 1, wordPos = minWordMatchPos; wordPos < nextMaxWordMatchPos; column++, wordPos++) {
        let score2 = Number.MIN_SAFE_INTEGER;
        let canComeDiag = false;
        if (wordPos <= maxWordMatchPos) {
          score2 = _doScore(pattern, patternLow, patternPos, patternStart, word, wordLow, wordPos, wordLen, wordStart, _diag[row - 1][column - 1] === 0, hasStrongFirstMatch);
        }
        let diagScore = 0;
        if (score2 !== Number.MIN_SAFE_INTEGER) {
          canComeDiag = true;
          diagScore = score2 + _table[row - 1][column - 1];
        }
        const canComeLeft = wordPos > minWordMatchPos;
        const leftScore = canComeLeft ? _table[row][column - 1] + (_diag[row][column - 1] > 0 ? -5 : 0) : 0;
        const canComeLeftLeft = wordPos > minWordMatchPos + 1 && _diag[row][column - 1] > 0;
        const leftLeftScore = canComeLeftLeft ? _table[row][column - 2] + (_diag[row][column - 2] > 0 ? -5 : 0) : 0;
        if (canComeLeftLeft && (!canComeLeft || leftLeftScore >= leftScore) && (!canComeDiag || leftLeftScore >= diagScore)) {
          _table[row][column] = leftLeftScore;
          _arrows[row][column] = 3;
          _diag[row][column] = 0;
        } else if (canComeLeft && (!canComeDiag || leftScore >= diagScore)) {
          _table[row][column] = leftScore;
          _arrows[row][column] = 2;
          _diag[row][column] = 0;
        } else if (canComeDiag) {
          _table[row][column] = diagScore;
          _arrows[row][column] = 1;
          _diag[row][column] = _diag[row - 1][column - 1] + 1;
        } else {
          throw new Error(`not possible`);
        }
      }
    }
    if (!hasStrongFirstMatch[0] && !options.firstMatchCanBeWeak) {
      return void 0;
    }
    row--;
    column--;
    const result = [_table[row][column], wordStart];
    let backwardsDiagLength = 0;
    let maxMatchColumn = 0;
    while (row >= 1) {
      let diagColumn = column;
      do {
        const arrow = _arrows[row][diagColumn];
        if (arrow === 3) {
          diagColumn = diagColumn - 2;
        } else if (arrow === 2) {
          diagColumn = diagColumn - 1;
        } else {
          break;
        }
      } while (diagColumn >= 1);
      if (backwardsDiagLength > 1 && patternLow[patternStart + row - 1] === wordLow[wordStart + column - 1] && !isUpperCaseAtPos(diagColumn + wordStart - 1, word, wordLow) && backwardsDiagLength + 1 > _diag[row][diagColumn]) {
        diagColumn = column;
      }
      if (diagColumn === column) {
        backwardsDiagLength++;
      } else {
        backwardsDiagLength = 1;
      }
      if (!maxMatchColumn) {
        maxMatchColumn = diagColumn;
      }
      row--;
      column = diagColumn - 1;
      result.push(column);
    }
    if (wordLen - wordStart === patternLen && options.boostFullMatch) {
      result[0] += 2;
    }
    const skippedCharsCount = maxMatchColumn - patternLen;
    result[0] -= skippedCharsCount;
    return result;
  }
  function _fillInMaxWordMatchPos(patternLen, wordLen, patternStart, wordStart, patternLow, wordLow) {
    let patternPos = patternLen - 1;
    let wordPos = wordLen - 1;
    while (patternPos >= patternStart && wordPos >= wordStart) {
      if (patternLow[patternPos] === wordLow[wordPos]) {
        _maxWordMatchPos[patternPos] = wordPos;
        patternPos--;
      }
      wordPos--;
    }
  }
  function _doScore(pattern, patternLow, patternPos, patternStart, word, wordLow, wordPos, wordLen, wordStart, newMatchStart, outFirstMatchStrong) {
    if (patternLow[patternPos] !== wordLow[wordPos]) {
      return Number.MIN_SAFE_INTEGER;
    }
    let score2 = 1;
    let isGapLocation = false;
    if (wordPos === patternPos - patternStart) {
      score2 = pattern[patternPos] === word[wordPos] ? 7 : 5;
    } else if (isUpperCaseAtPos(wordPos, word, wordLow) && (wordPos === 0 || !isUpperCaseAtPos(wordPos - 1, word, wordLow))) {
      score2 = pattern[patternPos] === word[wordPos] ? 7 : 5;
      isGapLocation = true;
    } else if (isSeparatorAtPos(wordLow, wordPos) && (wordPos === 0 || !isSeparatorAtPos(wordLow, wordPos - 1))) {
      score2 = 5;
    } else if (isSeparatorAtPos(wordLow, wordPos - 1) || isWhitespaceAtPos(wordLow, wordPos - 1)) {
      score2 = 5;
      isGapLocation = true;
    }
    if (score2 > 1 && patternPos === patternStart) {
      outFirstMatchStrong[0] = true;
    }
    if (!isGapLocation) {
      isGapLocation = isUpperCaseAtPos(wordPos, word, wordLow) || isSeparatorAtPos(wordLow, wordPos - 1) || isWhitespaceAtPos(wordLow, wordPos - 1);
    }
    if (patternPos === patternStart) {
      if (wordPos > wordStart) {
        score2 -= isGapLocation ? 3 : 5;
      }
    } else {
      if (newMatchStart) {
        score2 += isGapLocation ? 2 : 0;
      } else {
        score2 += isGapLocation ? 0 : 1;
      }
    }
    if (wordPos + 1 === wordLen) {
      score2 -= isGapLocation ? 3 : 5;
    }
    return score2;
  }
  function fuzzyScoreGracefulAggressive(pattern, lowPattern, patternPos, word, lowWord, wordPos, options) {
    return fuzzyScoreWithPermutations(pattern, lowPattern, patternPos, word, lowWord, wordPos, true, options);
  }
  function fuzzyScoreWithPermutations(pattern, lowPattern, patternPos, word, lowWord, wordPos, aggressive, options) {
    let top = fuzzyScore(pattern, lowPattern, patternPos, word, lowWord, wordPos, options);
    if (top && false) {
      return top;
    }
    if (pattern.length >= 3) {
      const tries = Math.min(7, pattern.length - 1);
      for (let movingPatternPos = patternPos + 1; movingPatternPos < tries; movingPatternPos++) {
        const newPattern = nextTypoPermutation(pattern, movingPatternPos);
        if (newPattern) {
          const candidate = fuzzyScore(newPattern, newPattern.toLowerCase(), patternPos, word, lowWord, wordPos, options);
          if (candidate) {
            candidate[0] -= 3;
            if (!top || candidate[0] > top[0]) {
              top = candidate;
            }
          }
        }
      }
    }
    return top;
  }
  function nextTypoPermutation(pattern, patternPos) {
    if (patternPos + 1 >= pattern.length) {
      return void 0;
    }
    const swap1 = pattern[patternPos];
    const swap2 = pattern[patternPos + 1];
    if (swap1 === swap2) {
      return void 0;
    }
    return pattern.slice(0, patternPos) + swap2 + swap1 + pattern.slice(patternPos + 2);
  }
  const iconStartMarker = "$(";
  const iconsRegex = new RegExp(`\\$\\(${ThemeIcon.iconNameExpression}(?:${ThemeIcon.iconModifierExpression})?\\)`, "g");
  const escapeIconsRegex = new RegExp(`(\\\\)?${iconsRegex.source}`, "g");
  function escapeIcons(text2) {
    return text2.replace(escapeIconsRegex, (match2, escaped) => escaped ? match2 : `\\${match2}`);
  }
  const markdownEscapedIconsRegex = new RegExp(`\\\\${iconsRegex.source}`, "g");
  function markdownEscapeEscapedIcons(text2) {
    return text2.replace(markdownEscapedIconsRegex, (match2) => `\\${match2}`);
  }
  const stripIconsRegex = new RegExp(`(\\s)?(\\\\)?${iconsRegex.source}(\\s)?`, "g");
  function stripIcons(text2) {
    if (text2.indexOf(iconStartMarker) === -1) {
      return text2;
    }
    return text2.replace(stripIconsRegex, (match2, preWhitespace, escaped, postWhitespace) => escaped ? match2 : preWhitespace || postWhitespace || "");
  }
  function getCodiconAriaLabel(text2) {
    if (!text2) {
      return "";
    }
    return text2.replace(/\$\((.*?)\)/g, (_match, codiconName) => ` ${codiconName} `).trim();
  }
  const _parseIconsRegex = new RegExp(`\\$\\(${ThemeIcon.iconNameCharacter}+\\)`, "g");
  function parseLabelWithIcons(input) {
    _parseIconsRegex.lastIndex = 0;
    let text2 = "";
    const iconOffsets = [];
    let iconsOffset = 0;
    while (true) {
      const pos = _parseIconsRegex.lastIndex;
      const match2 = _parseIconsRegex.exec(input);
      const chars = input.substring(pos, match2?.index);
      if (chars.length > 0) {
        text2 += chars;
        for (let i2 = 0; i2 < chars.length; i2++) {
          iconOffsets.push(iconsOffset);
        }
      }
      if (!match2) {
        break;
      }
      iconsOffset += match2[0].length;
    }
    return { text: text2, iconOffsets };
  }
  function matchesFuzzyIconAware(query, target, enableSeparateSubstringMatching = false) {
    const { text: text2, iconOffsets } = target;
    if (!iconOffsets || iconOffsets.length === 0) {
      return matchesFuzzy(query, text2, enableSeparateSubstringMatching);
    }
    const wordToMatchAgainstWithoutIconsTrimmed = ltrim(text2, " ");
    const leadingWhitespaceOffset = text2.length - wordToMatchAgainstWithoutIconsTrimmed.length;
    const matches = matchesFuzzy(query, wordToMatchAgainstWithoutIconsTrimmed, enableSeparateSubstringMatching);
    if (matches) {
      for (const match2 of matches) {
        const iconOffset = iconOffsets[match2.start + leadingWhitespaceOffset] + leadingWhitespaceOffset;
        match2.start += iconOffset;
        match2.end += iconOffset;
      }
    }
    return matches;
  }
  class MarkdownString {
    constructor(value = "", isTrustedOrOptions = false) {
      this.value = value;
      if (typeof this.value !== "string") {
        throw illegalArgument("value");
      }
      if (typeof isTrustedOrOptions === "boolean") {
        this.isTrusted = isTrustedOrOptions;
        this.supportThemeIcons = false;
        this.supportHtml = false;
        this.supportAlertSyntax = false;
      } else {
        this.isTrusted = isTrustedOrOptions.isTrusted ?? void 0;
        this.supportThemeIcons = isTrustedOrOptions.supportThemeIcons ?? false;
        this.supportHtml = isTrustedOrOptions.supportHtml ?? false;
        this.supportAlertSyntax = isTrustedOrOptions.supportAlertSyntax ?? false;
      }
    }
    appendText(value, newlineStyle = 0) {
      this.value += escapeMarkdownSyntaxTokens(this.supportThemeIcons ? escapeIcons(value) : value).replace(/([ \t]+)/g, (_match, g1) => "&nbsp;".repeat(g1.length)).replace(/\>/gm, "\\>").replace(/\n/g, newlineStyle === 1 ? "\\\n" : "\n\n");
      return this;
    }
    appendMarkdown(value) {
      this.value += value;
      return this;
    }
    appendCodeblock(langId, code) {
      this.value += `
${appendEscapedMarkdownCodeBlockFence(code, langId)}
`;
      return this;
    }
    appendLink(target, label, title) {
      this.value += "[";
      this.value += this._escape(label, "]");
      this.value += "](";
      this.value += this._escape(String(target), ")");
      if (title) {
        this.value += ` "${this._escape(this._escape(title, '"'), ")")}"`;
      }
      this.value += ")";
      return this;
    }
    _escape(value, ch) {
      const r = new RegExp(escapeRegExpCharacters(ch), "g");
      return value.replace(r, (match2, offset) => {
        if (value.charAt(offset - 1) !== "\\") {
          return `\\${match2}`;
        } else {
          return match2;
        }
      });
    }
  }
  function isEmptyMarkdownString(oneOrMany) {
    if (isMarkdownString(oneOrMany)) {
      return !oneOrMany.value;
    } else if (Array.isArray(oneOrMany)) {
      return oneOrMany.every(isEmptyMarkdownString);
    } else {
      return true;
    }
  }
  function isMarkdownString(thing) {
    if (thing instanceof MarkdownString) {
      return true;
    } else if (thing && typeof thing === "object") {
      return typeof thing.value === "string" && (typeof thing.isTrusted === "boolean" || typeof thing.isTrusted === "object" || thing.isTrusted === void 0) && (typeof thing.supportThemeIcons === "boolean" || thing.supportThemeIcons === void 0) && (typeof thing.supportAlertSyntax === "boolean" || thing.supportAlertSyntax === void 0);
    }
    return false;
  }
  function markdownStringEqual(a, b) {
    if (a === b) {
      return true;
    } else if (!a || !b) {
      return false;
    } else {
      return a.value === b.value && a.isTrusted === b.isTrusted && a.supportThemeIcons === b.supportThemeIcons && a.supportHtml === b.supportHtml && a.supportAlertSyntax === b.supportAlertSyntax && (a.baseUri === b.baseUri || !!a.baseUri && !!b.baseUri && isEqual(URI.from(a.baseUri), URI.from(b.baseUri)));
    }
  }
  function escapeMarkdownSyntaxTokens(text2) {
    return text2.replace(/[\\`*_{}[\]()#+\-!~]/g, "\\$&");
  }
  function appendEscapedMarkdownCodeBlockFence(code, langId) {
    const longestFenceLength = code.match(/^`+/gm)?.reduce((a, b) => a.length > b.length ? a : b).length ?? 0;
    const desiredFenceLength = longestFenceLength >= 3 ? longestFenceLength + 1 : 3;
    return [
      `${"`".repeat(desiredFenceLength)}${langId}`,
      code,
      `${"`".repeat(desiredFenceLength)}`
    ].join("\n");
  }
  function escapeDoubleQuotes(input) {
    return input.replace(/"/g, "&quot;");
  }
  function removeMarkdownEscapes(text2) {
    if (!text2) {
      return text2;
    }
    return text2.replace(/\\([\\`*_{}[\]()#+\-.!~])/g, "$1");
  }
  function parseHrefAndDimensions(href) {
    const dimensions = [];
    const splitted = href.split("|").map((s) => s.trim());
    href = splitted[0];
    const parameters = splitted[1];
    if (parameters) {
      const heightFromParams = /height=(\d+)/.exec(parameters);
      const widthFromParams = /width=(\d+)/.exec(parameters);
      const height = heightFromParams ? heightFromParams[1] : "";
      const width2 = widthFromParams ? widthFromParams[1] : "";
      const widthIsFinite = isFinite(parseInt(width2));
      const heightIsFinite = isFinite(parseInt(height));
      if (widthIsFinite) {
        dimensions.push(`width="${width2}"`);
      }
      if (heightIsFinite) {
        dimensions.push(`height="${height}"`);
      }
    }
    return { href, dimensions };
  }
  function createCommandUri(commandId, ...commandArgs) {
    return URI.from({
      scheme: Schemas.command,
      path: commandId,
      query: commandArgs.length ? encodeURIComponent(JSON.stringify(commandArgs)) : void 0
    });
  }
  class IdGenerator {
    constructor(prefix) {
      this._prefix = prefix;
      this._lastId = 0;
    }
    nextId() {
      return this._prefix + ++this._lastId;
    }
  }
  const defaultGenerator = new IdGenerator("id#");
  function _getDefaults() {
    return {
      async: false,
      breaks: false,
      extensions: null,
      gfm: true,
      hooks: null,
      pedantic: false,
      renderer: null,
      silent: false,
      tokenizer: null,
      walkTokens: null
    };
  }
  let _defaults = _getDefaults();
  function changeDefaults(newDefaults) {
    _defaults = newDefaults;
  }
  const escapeTest = /[&<>"']/;
  const escapeReplace = new RegExp(escapeTest.source, "g");
  const escapeTestNoEncode = /[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/;
  const escapeReplaceNoEncode = new RegExp(escapeTestNoEncode.source, "g");
  const escapeReplacements = {
    "&": "&amp;",
    "<": "&lt;",
    ">": "&gt;",
    '"': "&quot;",
    "'": "&#39;"
  };
  const getEscapeReplacement = (ch) => escapeReplacements[ch];
  function escape$1(html2, encode) {
    if (encode) {
      if (escapeTest.test(html2)) {
        return html2.replace(escapeReplace, getEscapeReplacement);
      }
    } else {
      if (escapeTestNoEncode.test(html2)) {
        return html2.replace(escapeReplaceNoEncode, getEscapeReplacement);
      }
    }
    return html2;
  }
  const caret = /(^|[^\[])\^/g;
  function edit(regex, opt) {
    let source = typeof regex === "string" ? regex : regex.source;
    opt = opt || "";
    const obj = {
      replace: (name, val) => {
        let valSource = typeof val === "string" ? val : val.source;
        valSource = valSource.replace(caret, "$1");
        source = source.replace(name, valSource);
        return obj;
      },
      getRegex: () => {
        return new RegExp(source, opt);
      }
    };
    return obj;
  }
  function cleanUrl(href) {
    try {
      href = encodeURI(href).replace(/%25/g, "%");
    } catch {
      return null;
    }
    return href;
  }
  const noopTest = { exec: () => null };
  function splitCells(tableRow, count) {
    const row = tableRow.replace(/\|/g, (match2, offset, str) => {
      let escaped = false;
      let curr = offset;
      while (--curr >= 0 && str[curr] === "\\")
        escaped = !escaped;
      if (escaped) {
        return "|";
      } else {
        return " |";
      }
    }), cells = row.split(/ \|/);
    let i2 = 0;
    if (!cells[0].trim()) {
      cells.shift();
    }
    if (cells.length > 0 && !cells[cells.length - 1].trim()) {
      cells.pop();
    }
    if (count) {
      if (cells.length > count) {
        cells.splice(count);
      } else {
        while (cells.length < count)
          cells.push("");
      }
    }
    for (; i2 < cells.length; i2++) {
      cells[i2] = cells[i2].trim().replace(/\\\|/g, "|");
    }
    return cells;
  }
  function rtrim(str, c, invert) {
    const l = str.length;
    if (l === 0) {
      return "";
    }
    let suffLen = 0;
    while (suffLen < l) {
      const currChar = str.charAt(l - suffLen - 1);
      if (currChar === c && true) {
        suffLen++;
      } else {
        break;
      }
    }
    return str.slice(0, l - suffLen);
  }
  function findClosingBracket(str, b) {
    if (str.indexOf(b[1]) === -1) {
      return -1;
    }
    let level = 0;
    for (let i2 = 0; i2 < str.length; i2++) {
      if (str[i2] === "\\") {
        i2++;
      } else if (str[i2] === b[0]) {
        level++;
      } else if (str[i2] === b[1]) {
        level--;
        if (level < 0) {
          return i2;
        }
      }
    }
    return -1;
  }
  function outputLink(cap, link2, raw, lexer2) {
    const href = link2.href;
    const title = link2.title ? escape$1(link2.title) : null;
    const text2 = cap[1].replace(/\\([\[\]])/g, "$1");
    if (cap[0].charAt(0) !== "!") {
      lexer2.state.inLink = true;
      const token = {
        type: "link",
        raw,
        href,
        title,
        text: text2,
        tokens: lexer2.inlineTokens(text2)
      };
      lexer2.state.inLink = false;
      return token;
    }
    return {
      type: "image",
      raw,
      href,
      title,
      text: escape$1(text2)
    };
  }
  function indentCodeCompensation(raw, text2) {
    const matchIndentToCode = raw.match(/^(\s+)(?:```)/);
    if (matchIndentToCode === null) {
      return text2;
    }
    const indentToCode = matchIndentToCode[1];
    return text2.split("\n").map((node) => {
      const matchIndentInNode = node.match(/^\s+/);
      if (matchIndentInNode === null) {
        return node;
      }
      const [indentInNode] = matchIndentInNode;
      if (indentInNode.length >= indentToCode.length) {
        return node.slice(indentToCode.length);
      }
      return node;
    }).join("\n");
  }
  class _Tokenizer {
    options;
    rules;
    // set by the lexer
    lexer;
    // set by the lexer
    constructor(options) {
      this.options = options || _defaults;
    }
    space(src) {
      const cap = this.rules.block.newline.exec(src);
      if (cap && cap[0].length > 0) {
        return {
          type: "space",
          raw: cap[0]
        };
      }
    }
    code(src) {
      const cap = this.rules.block.code.exec(src);
      if (cap) {
        const text2 = cap[0].replace(/^ {1,4}/gm, "");
        return {
          type: "code",
          raw: cap[0],
          codeBlockStyle: "indented",
          text: !this.options.pedantic ? rtrim(text2, "\n") : text2
        };
      }
    }
    fences(src) {
      const cap = this.rules.block.fences.exec(src);
      if (cap) {
        const raw = cap[0];
        const text2 = indentCodeCompensation(raw, cap[3] || "");
        return {
          type: "code",
          raw,
          lang: cap[2] ? cap[2].trim().replace(this.rules.inline.anyPunctuation, "$1") : cap[2],
          text: text2
        };
      }
    }
    heading(src) {
      const cap = this.rules.block.heading.exec(src);
      if (cap) {
        let text2 = cap[2].trim();
        if (/#$/.test(text2)) {
          const trimmed = rtrim(text2, "#");
          if (this.options.pedantic) {
            text2 = trimmed.trim();
          } else if (!trimmed || / $/.test(trimmed)) {
            text2 = trimmed.trim();
          }
        }
        return {
          type: "heading",
          raw: cap[0],
          depth: cap[1].length,
          text: text2,
          tokens: this.lexer.inline(text2)
        };
      }
    }
    hr(src) {
      const cap = this.rules.block.hr.exec(src);
      if (cap) {
        return {
          type: "hr",
          raw: rtrim(cap[0], "\n")
        };
      }
    }
    blockquote(src) {
      const cap = this.rules.block.blockquote.exec(src);
      if (cap) {
        let lines = rtrim(cap[0], "\n").split("\n");
        let raw = "";
        let text2 = "";
        const tokens = [];
        while (lines.length > 0) {
          let inBlockquote = false;
          const currentLines = [];
          let i2;
          for (i2 = 0; i2 < lines.length; i2++) {
            if (/^ {0,3}>/.test(lines[i2])) {
              currentLines.push(lines[i2]);
              inBlockquote = true;
            } else if (!inBlockquote) {
              currentLines.push(lines[i2]);
            } else {
              break;
            }
          }
          lines = lines.slice(i2);
          const currentRaw = currentLines.join("\n");
          const currentText = currentRaw.replace(/\n {0,3}((?:=+|-+) *)(?=\n|$)/g, "\n    $1").replace(/^ {0,3}>[ \t]?/gm, "");
          raw = raw ? `${raw}
${currentRaw}` : currentRaw;
          text2 = text2 ? `${text2}
${currentText}` : currentText;
          const top = this.lexer.state.top;
          this.lexer.state.top = true;
          this.lexer.blockTokens(currentText, tokens, true);
          this.lexer.state.top = top;
          if (lines.length === 0) {
            break;
          }
          const lastToken = tokens[tokens.length - 1];
          if (lastToken?.type === "code") {
            break;
          } else if (lastToken?.type === "blockquote") {
            const oldToken = lastToken;
            const newText = oldToken.raw + "\n" + lines.join("\n");
            const newToken = this.blockquote(newText);
            tokens[tokens.length - 1] = newToken;
            raw = raw.substring(0, raw.length - oldToken.raw.length) + newToken.raw;
            text2 = text2.substring(0, text2.length - oldToken.text.length) + newToken.text;
            break;
          } else if (lastToken?.type === "list") {
            const oldToken = lastToken;
            const newText = oldToken.raw + "\n" + lines.join("\n");
            const newToken = this.list(newText);
            tokens[tokens.length - 1] = newToken;
            raw = raw.substring(0, raw.length - lastToken.raw.length) + newToken.raw;
            text2 = text2.substring(0, text2.length - oldToken.raw.length) + newToken.raw;
            lines = newText.substring(tokens[tokens.length - 1].raw.length).split("\n");
            continue;
          }
        }
        return {
          type: "blockquote",
          raw,
          tokens,
          text: text2
        };
      }
    }
    list(src) {
      let cap = this.rules.block.list.exec(src);
      if (cap) {
        let bull = cap[1].trim();
        const isordered = bull.length > 1;
        const list2 = {
          type: "list",
          raw: "",
          ordered: isordered,
          start: isordered ? +bull.slice(0, -1) : "",
          loose: false,
          items: []
        };
        bull = isordered ? `\\d{1,9}\\${bull.slice(-1)}` : `\\${bull}`;
        if (this.options.pedantic) {
          bull = isordered ? bull : "[*+-]";
        }
        const itemRegex = new RegExp(`^( {0,3}${bull})((?:[	 ][^\\n]*)?(?:\\n|$))`);
        let endsWithBlankLine = false;
        while (src) {
          let endEarly = false;
          let raw = "";
          let itemContents = "";
          if (!(cap = itemRegex.exec(src))) {
            break;
          }
          if (this.rules.block.hr.test(src)) {
            break;
          }
          raw = cap[0];
          src = src.substring(raw.length);
          let line = cap[2].split("\n", 1)[0].replace(/^\t+/, (t) => " ".repeat(3 * t.length));
          let nextLine = src.split("\n", 1)[0];
          let blankLine = !line.trim();
          let indent = 0;
          if (this.options.pedantic) {
            indent = 2;
            itemContents = line.trimStart();
          } else if (blankLine) {
            indent = cap[1].length + 1;
          } else {
            indent = cap[2].search(/[^ ]/);
            indent = indent > 4 ? 1 : indent;
            itemContents = line.slice(indent);
            indent += cap[1].length;
          }
          if (blankLine && /^ *$/.test(nextLine)) {
            raw += nextLine + "\n";
            src = src.substring(nextLine.length + 1);
            endEarly = true;
          }
          if (!endEarly) {
            const nextBulletRegex = new RegExp(`^ {0,${Math.min(3, indent - 1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ 	][^\\n]*)?(?:\\n|$))`);
            const hrRegex = new RegExp(`^ {0,${Math.min(3, indent - 1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`);
            const fencesBeginRegex = new RegExp(`^ {0,${Math.min(3, indent - 1)}}(?:\`\`\`|~~~)`);
            const headingBeginRegex = new RegExp(`^ {0,${Math.min(3, indent - 1)}}#`);
            while (src) {
              const rawLine = src.split("\n", 1)[0];
              nextLine = rawLine;
              if (this.options.pedantic) {
                nextLine = nextLine.replace(/^ {1,4}(?=( {4})*[^ ])/g, "  ");
              }
              if (fencesBeginRegex.test(nextLine)) {
                break;
              }
              if (headingBeginRegex.test(nextLine)) {
                break;
              }
              if (nextBulletRegex.test(nextLine)) {
                break;
              }
              if (hrRegex.test(src)) {
                break;
              }
              if (nextLine.search(/[^ ]/) >= indent || !nextLine.trim()) {
                itemContents += "\n" + nextLine.slice(indent);
              } else {
                if (blankLine) {
                  break;
                }
                if (line.search(/[^ ]/) >= 4) {
                  break;
                }
                if (fencesBeginRegex.test(line)) {
                  break;
                }
                if (headingBeginRegex.test(line)) {
                  break;
                }
                if (hrRegex.test(line)) {
                  break;
                }
                itemContents += "\n" + nextLine;
              }
              if (!blankLine && !nextLine.trim()) {
                blankLine = true;
              }
              raw += rawLine + "\n";
              src = src.substring(rawLine.length + 1);
              line = nextLine.slice(indent);
            }
          }
          if (!list2.loose) {
            if (endsWithBlankLine) {
              list2.loose = true;
            } else if (/\n *\n *$/.test(raw)) {
              endsWithBlankLine = true;
            }
          }
          let istask = null;
          let ischecked;
          if (this.options.gfm) {
            istask = /^\[[ xX]\] /.exec(itemContents);
            if (istask) {
              ischecked = istask[0] !== "[ ] ";
              itemContents = itemContents.replace(/^\[[ xX]\] +/, "");
            }
          }
          list2.items.push({
            type: "list_item",
            raw,
            task: !!istask,
            checked: ischecked,
            loose: false,
            text: itemContents,
            tokens: []
          });
          list2.raw += raw;
        }
        list2.items[list2.items.length - 1].raw = list2.items[list2.items.length - 1].raw.trimEnd();
        list2.items[list2.items.length - 1].text = list2.items[list2.items.length - 1].text.trimEnd();
        list2.raw = list2.raw.trimEnd();
        for (let i2 = 0; i2 < list2.items.length; i2++) {
          this.lexer.state.top = false;
          list2.items[i2].tokens = this.lexer.blockTokens(list2.items[i2].text, []);
          if (!list2.loose) {
            const spacers = list2.items[i2].tokens.filter((t) => t.type === "space");
            const hasMultipleLineBreaks = spacers.length > 0 && spacers.some((t) => /\n.*\n/.test(t.raw));
            list2.loose = hasMultipleLineBreaks;
          }
        }
        if (list2.loose) {
          for (let i2 = 0; i2 < list2.items.length; i2++) {
            list2.items[i2].loose = true;
          }
        }
        return list2;
      }
    }
    html(src) {
      const cap = this.rules.block.html.exec(src);
      if (cap) {
        const token = {
          type: "html",
          block: true,
          raw: cap[0],
          pre: cap[1] === "pre" || cap[1] === "script" || cap[1] === "style",
          text: cap[0]
        };
        return token;
      }
    }
    def(src) {
      const cap = this.rules.block.def.exec(src);
      if (cap) {
        const tag2 = cap[1].toLowerCase().replace(/\s+/g, " ");
        const href = cap[2] ? cap[2].replace(/^<(.*)>$/, "$1").replace(this.rules.inline.anyPunctuation, "$1") : "";
        const title = cap[3] ? cap[3].substring(1, cap[3].length - 1).replace(this.rules.inline.anyPunctuation, "$1") : cap[3];
        return {
          type: "def",
          tag: tag2,
          raw: cap[0],
          href,
          title
        };
      }
    }
    table(src) {
      const cap = this.rules.block.table.exec(src);
      if (!cap) {
        return;
      }
      if (!/[:|]/.test(cap[2])) {
        return;
      }
      const headers = splitCells(cap[1]);
      const aligns = cap[2].replace(/^\||\| *$/g, "").split("|");
      const rows = cap[3] && cap[3].trim() ? cap[3].replace(/\n[ \t]*$/, "").split("\n") : [];
      const item = {
        type: "table",
        raw: cap[0],
        header: [],
        align: [],
        rows: []
      };
      if (headers.length !== aligns.length) {
        return;
      }
      for (const align of aligns) {
        if (/^ *-+: *$/.test(align)) {
          item.align.push("right");
        } else if (/^ *:-+: *$/.test(align)) {
          item.align.push("center");
        } else if (/^ *:-+ *$/.test(align)) {
          item.align.push("left");
        } else {
          item.align.push(null);
        }
      }
      for (let i2 = 0; i2 < headers.length; i2++) {
        item.header.push({
          text: headers[i2],
          tokens: this.lexer.inline(headers[i2]),
          header: true,
          align: item.align[i2]
        });
      }
      for (const row of rows) {
        item.rows.push(splitCells(row, item.header.length).map((cell, i2) => {
          return {
            text: cell,
            tokens: this.lexer.inline(cell),
            header: false,
            align: item.align[i2]
          };
        }));
      }
      return item;
    }
    lheading(src) {
      const cap = this.rules.block.lheading.exec(src);
      if (cap) {
        return {
          type: "heading",
          raw: cap[0],
          depth: cap[2].charAt(0) === "=" ? 1 : 2,
          text: cap[1],
          tokens: this.lexer.inline(cap[1])
        };
      }
    }
    paragraph(src) {
      const cap = this.rules.block.paragraph.exec(src);
      if (cap) {
        const text2 = cap[1].charAt(cap[1].length - 1) === "\n" ? cap[1].slice(0, -1) : cap[1];
        return {
          type: "paragraph",
          raw: cap[0],
          text: text2,
          tokens: this.lexer.inline(text2)
        };
      }
    }
    text(src) {
      const cap = this.rules.block.text.exec(src);
      if (cap) {
        return {
          type: "text",
          raw: cap[0],
          text: cap[0],
          tokens: this.lexer.inline(cap[0])
        };
      }
    }
    escape(src) {
      const cap = this.rules.inline.escape.exec(src);
      if (cap) {
        return {
          type: "escape",
          raw: cap[0],
          text: escape$1(cap[1])
        };
      }
    }
    tag(src) {
      const cap = this.rules.inline.tag.exec(src);
      if (cap) {
        if (!this.lexer.state.inLink && /^<a /i.test(cap[0])) {
          this.lexer.state.inLink = true;
        } else if (this.lexer.state.inLink && /^<\/a>/i.test(cap[0])) {
          this.lexer.state.inLink = false;
        }
        if (!this.lexer.state.inRawBlock && /^<(pre|code|kbd|script)(\s|>)/i.test(cap[0])) {
          this.lexer.state.inRawBlock = true;
        } else if (this.lexer.state.inRawBlock && /^<\/(pre|code|kbd|script)(\s|>)/i.test(cap[0])) {
          this.lexer.state.inRawBlock = false;
        }
        return {
          type: "html",
          raw: cap[0],
          inLink: this.lexer.state.inLink,
          inRawBlock: this.lexer.state.inRawBlock,
          block: false,
          text: cap[0]
        };
      }
    }
    link(src) {
      const cap = this.rules.inline.link.exec(src);
      if (cap) {
        const trimmedUrl = cap[2].trim();
        if (!this.options.pedantic && /^</.test(trimmedUrl)) {
          if (!/>$/.test(trimmedUrl)) {
            return;
          }
          const rtrimSlash = rtrim(trimmedUrl.slice(0, -1), "\\");
          if ((trimmedUrl.length - rtrimSlash.length) % 2 === 0) {
            return;
          }
        } else {
          const lastParenIndex = findClosingBracket(cap[2], "()");
          if (lastParenIndex > -1) {
            const start = cap[0].indexOf("!") === 0 ? 5 : 4;
            const linkLen = start + cap[1].length + lastParenIndex;
            cap[2] = cap[2].substring(0, lastParenIndex);
            cap[0] = cap[0].substring(0, linkLen).trim();
            cap[3] = "";
          }
        }
        let href = cap[2];
        let title = "";
        if (this.options.pedantic) {
          const link2 = /^([^'"]*[^\s])\s+(['"])(.*)\2/.exec(href);
          if (link2) {
            href = link2[1];
            title = link2[3];
          }
        } else {
          title = cap[3] ? cap[3].slice(1, -1) : "";
        }
        href = href.trim();
        if (/^</.test(href)) {
          if (this.options.pedantic && !/>$/.test(trimmedUrl)) {
            href = href.slice(1);
          } else {
            href = href.slice(1, -1);
          }
        }
        return outputLink(cap, {
          href: href ? href.replace(this.rules.inline.anyPunctuation, "$1") : href,
          title: title ? title.replace(this.rules.inline.anyPunctuation, "$1") : title
        }, cap[0], this.lexer);
      }
    }
    reflink(src, links) {
      let cap;
      if ((cap = this.rules.inline.reflink.exec(src)) || (cap = this.rules.inline.nolink.exec(src))) {
        const linkString = (cap[2] || cap[1]).replace(/\s+/g, " ");
        const link2 = links[linkString.toLowerCase()];
        if (!link2) {
          const text2 = cap[0].charAt(0);
          return {
            type: "text",
            raw: text2,
            text: text2
          };
        }
        return outputLink(cap, link2, cap[0], this.lexer);
      }
    }
    emStrong(src, maskedSrc, prevChar = "") {
      let match2 = this.rules.inline.emStrongLDelim.exec(src);
      if (!match2)
        return;
      if (match2[3] && prevChar.match(/[\p{L}\p{N}]/u))
        return;
      const nextChar = match2[1] || match2[2] || "";
      if (!nextChar || !prevChar || this.rules.inline.punctuation.exec(prevChar)) {
        const lLength = [...match2[0]].length - 1;
        let rDelim, rLength, delimTotal = lLength, midDelimTotal = 0;
        const endReg = match2[0][0] === "*" ? this.rules.inline.emStrongRDelimAst : this.rules.inline.emStrongRDelimUnd;
        endReg.lastIndex = 0;
        maskedSrc = maskedSrc.slice(-1 * src.length + lLength);
        while ((match2 = endReg.exec(maskedSrc)) != null) {
          rDelim = match2[1] || match2[2] || match2[3] || match2[4] || match2[5] || match2[6];
          if (!rDelim)
            continue;
          rLength = [...rDelim].length;
          if (match2[3] || match2[4]) {
            delimTotal += rLength;
            continue;
          } else if (match2[5] || match2[6]) {
            if (lLength % 3 && !((lLength + rLength) % 3)) {
              midDelimTotal += rLength;
              continue;
            }
          }
          delimTotal -= rLength;
          if (delimTotal > 0)
            continue;
          rLength = Math.min(rLength, rLength + delimTotal + midDelimTotal);
          const lastCharLength = [...match2[0]][0].length;
          const raw = src.slice(0, lLength + match2.index + lastCharLength + rLength);
          if (Math.min(lLength, rLength) % 2) {
            const text3 = raw.slice(1, -1);
            return {
              type: "em",
              raw,
              text: text3,
              tokens: this.lexer.inlineTokens(text3)
            };
          }
          const text2 = raw.slice(2, -2);
          return {
            type: "strong",
            raw,
            text: text2,
            tokens: this.lexer.inlineTokens(text2)
          };
        }
      }
    }
    codespan(src) {
      const cap = this.rules.inline.code.exec(src);
      if (cap) {
        let text2 = cap[2].replace(/\n/g, " ");
        const hasNonSpaceChars = /[^ ]/.test(text2);
        const hasSpaceCharsOnBothEnds = /^ /.test(text2) && / $/.test(text2);
        if (hasNonSpaceChars && hasSpaceCharsOnBothEnds) {
          text2 = text2.substring(1, text2.length - 1);
        }
        text2 = escape$1(text2, true);
        return {
          type: "codespan",
          raw: cap[0],
          text: text2
        };
      }
    }
    br(src) {
      const cap = this.rules.inline.br.exec(src);
      if (cap) {
        return {
          type: "br",
          raw: cap[0]
        };
      }
    }
    del(src) {
      const cap = this.rules.inline.del.exec(src);
      if (cap) {
        return {
          type: "del",
          raw: cap[0],
          text: cap[2],
          tokens: this.lexer.inlineTokens(cap[2])
        };
      }
    }
    autolink(src) {
      const cap = this.rules.inline.autolink.exec(src);
      if (cap) {
        let text2, href;
        if (cap[2] === "@") {
          text2 = escape$1(cap[1]);
          href = "mailto:" + text2;
        } else {
          text2 = escape$1(cap[1]);
          href = text2;
        }
        return {
          type: "link",
          raw: cap[0],
          text: text2,
          href,
          tokens: [
            {
              type: "text",
              raw: text2,
              text: text2
            }
          ]
        };
      }
    }
    url(src) {
      let cap;
      if (cap = this.rules.inline.url.exec(src)) {
        let text2, href;
        if (cap[2] === "@") {
          text2 = escape$1(cap[0]);
          href = "mailto:" + text2;
        } else {
          let prevCapZero;
          do {
            prevCapZero = cap[0];
            cap[0] = this.rules.inline._backpedal.exec(cap[0])?.[0] ?? "";
          } while (prevCapZero !== cap[0]);
          text2 = escape$1(cap[0]);
          if (cap[1] === "www.") {
            href = "http://" + cap[0];
          } else {
            href = cap[0];
          }
        }
        return {
          type: "link",
          raw: cap[0],
          text: text2,
          href,
          tokens: [
            {
              type: "text",
              raw: text2,
              text: text2
            }
          ]
        };
      }
    }
    inlineText(src) {
      const cap = this.rules.inline.text.exec(src);
      if (cap) {
        let text2;
        if (this.lexer.state.inRawBlock) {
          text2 = cap[0];
        } else {
          text2 = escape$1(cap[0]);
        }
        return {
          type: "text",
          raw: cap[0],
          text: text2
        };
      }
    }
  }
  const newline = /^(?: *(?:\n|$))+/;
  const blockCode = /^( {4}[^\n]+(?:\n(?: *(?:\n|$))*)?)+/;
  const fences = /^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/;
  const hr = /^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/;
  const heading = /^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/;
  const bullet = /(?:[*+-]|\d{1,9}[.)])/;
  const lheading = edit(/^(?!bull |blockCode|fences|blockquote|heading|html)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html))+?)\n {0,3}(=+|-+) *(?:\n+|$)/).replace(/bull/g, bullet).replace(/blockCode/g, / {4}/).replace(/fences/g, / {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g, / {0,3}>/).replace(/heading/g, / {0,3}#{1,6}/).replace(/html/g, / {0,3}<[^\n>]+>\n/).getRegex();
  const _paragraph = /^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/;
  const blockText = /^[^\n]+/;
  const _blockLabel = /(?!\s*\])(?:\\.|[^\[\]\\])+/;
  const def = edit(/^ {0,3}\[(label)\]: *(?:\n *)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n *)?| *\n *)(title))? *(?:\n+|$)/).replace("label", _blockLabel).replace("title", /(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex();
  const list = edit(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g, bullet).getRegex();
  const _tag = "address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul";
  const _comment = /<!--(?:-?>|[\s\S]*?(?:-->|$))/;
  const html$2 = edit("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n *)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$))", "i").replace("comment", _comment).replace("tag", _tag).replace("attribute", / +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex();
  const paragraph = edit(_paragraph).replace("hr", hr).replace("heading", " {0,3}#{1,6}(?:\\s|$)").replace("|lheading", "").replace("|table", "").replace("blockquote", " {0,3}>").replace("fences", " {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list", " {0,3}(?:[*+-]|1[.)]) ").replace("html", "</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag", _tag).getRegex();
  const blockquote = edit(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph", paragraph).getRegex();
  const blockNormal = {
    blockquote,
    code: blockCode,
    def,
    fences,
    heading,
    hr,
    html: html$2,
    lheading,
    list,
    newline,
    paragraph,
    table: noopTest,
    text: blockText
  };
  const gfmTable = edit("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr", hr).replace("heading", " {0,3}#{1,6}(?:\\s|$)").replace("blockquote", " {0,3}>").replace("code", " {4}[^\\n]").replace("fences", " {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list", " {0,3}(?:[*+-]|1[.)]) ").replace("html", "</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag", _tag).getRegex();
  const blockGfm = {
    ...blockNormal,
    table: gfmTable,
    paragraph: edit(_paragraph).replace("hr", hr).replace("heading", " {0,3}#{1,6}(?:\\s|$)").replace("|lheading", "").replace("table", gfmTable).replace("blockquote", " {0,3}>").replace("fences", " {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list", " {0,3}(?:[*+-]|1[.)]) ").replace("html", "</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag", _tag).getRegex()
  };
  const blockPedantic = {
    ...blockNormal,
    html: edit(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment", _comment).replace(/tag/g, "(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),
    def: /^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,
    heading: /^(#{1,6})(.*)(?:\n+|$)/,
    fences: noopTest,
    // fences not supported
    lheading: /^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,
    paragraph: edit(_paragraph).replace("hr", hr).replace("heading", " *#{1,6} *[^\n]").replace("lheading", lheading).replace("|table", "").replace("blockquote", " {0,3}>").replace("|fences", "").replace("|list", "").replace("|html", "").replace("|tag", "").getRegex()
  };
  const escape = /^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/;
  const inlineCode = /^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/;
  const br = /^( {2,}|\\)\n(?!\s*$)/;
  const inlineText = /^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/;
  const _punctuation = "\\p{P}\\p{S}";
  const punctuation = edit(/^((?![*_])[\spunctuation])/, "u").replace(/punctuation/g, _punctuation).getRegex();
  const blockSkip = /\[[^[\]]*?\]\([^\(\)]*?\)|`[^`]*?`|<[^<>]*?>/g;
  const emStrongLDelim = edit(/^(?:\*+(?:((?!\*)[punct])|[^\s*]))|^_+(?:((?!_)[punct])|([^\s_]))/, "u").replace(/punct/g, _punctuation).getRegex();
  const emStrongRDelimAst = edit("^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)[punct](\\*+)(?=[\\s]|$)|[^punct\\s](\\*+)(?!\\*)(?=[punct\\s]|$)|(?!\\*)[punct\\s](\\*+)(?=[^punct\\s])|[\\s](\\*+)(?!\\*)(?=[punct])|(?!\\*)[punct](\\*+)(?!\\*)(?=[punct])|[^punct\\s](\\*+)(?=[^punct\\s])", "gu").replace(/punct/g, _punctuation).getRegex();
  const emStrongRDelimUnd = edit("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)[punct](_+)(?=[\\s]|$)|[^punct\\s](_+)(?!_)(?=[punct\\s]|$)|(?!_)[punct\\s](_+)(?=[^punct\\s])|[\\s](_+)(?!_)(?=[punct])|(?!_)[punct](_+)(?!_)(?=[punct])", "gu").replace(/punct/g, _punctuation).getRegex();
  const anyPunctuation = edit(/\\([punct])/, "gu").replace(/punct/g, _punctuation).getRegex();
  const autolink = edit(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme", /[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email", /[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex();
  const _inlineComment = edit(_comment).replace("(?:-->|$)", "-->").getRegex();
  const tag = edit("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment", _inlineComment).replace("attribute", /\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex();
  const _inlineLabel = /(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/;
  const link = edit(/^!?\[(label)\]\(\s*(href)(?:\s+(title))?\s*\)/).replace("label", _inlineLabel).replace("href", /<(?:\\.|[^\n<>\\])+>|[^\s\x00-\x1f]*/).replace("title", /"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex();
  const reflink = edit(/^!?\[(label)\]\[(ref)\]/).replace("label", _inlineLabel).replace("ref", _blockLabel).getRegex();
  const nolink = edit(/^!?\[(ref)\](?:\[\])?/).replace("ref", _blockLabel).getRegex();
  const reflinkSearch = edit("reflink|nolink(?!\\()", "g").replace("reflink", reflink).replace("nolink", nolink).getRegex();
  const inlineNormal = {
    _backpedal: noopTest,
    // only used for GFM url
    anyPunctuation,
    autolink,
    blockSkip,
    br,
    code: inlineCode,
    del: noopTest,
    emStrongLDelim,
    emStrongRDelimAst,
    emStrongRDelimUnd,
    escape,
    link,
    nolink,
    punctuation,
    reflink,
    reflinkSearch,
    tag,
    text: inlineText,
    url: noopTest
  };
  const inlinePedantic = {
    ...inlineNormal,
    link: edit(/^!?\[(label)\]\((.*?)\)/).replace("label", _inlineLabel).getRegex(),
    reflink: edit(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label", _inlineLabel).getRegex()
  };
  const inlineGfm = {
    ...inlineNormal,
    escape: edit(escape).replace("])", "~|])").getRegex(),
    url: edit(/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/, "i").replace("email", /[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),
    _backpedal: /(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,
    del: /^(~~?)(?=[^\s~])([\s\S]*?[^\s~])\1(?=[^~]|$)/,
    text: /^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|https?:\/\/|ftp:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/
  };
  const inlineBreaks = {
    ...inlineGfm,
    br: edit(br).replace("{2,}", "*").getRegex(),
    text: edit(inlineGfm.text).replace("\\b_", "\\b_| {2,}\\n").replace(/\{2,\}/g, "*").getRegex()
  };
  const block = {
    normal: blockNormal,
    gfm: blockGfm,
    pedantic: blockPedantic
  };
  const inline = {
    normal: inlineNormal,
    gfm: inlineGfm,
    breaks: inlineBreaks,
    pedantic: inlinePedantic
  };
  class _Lexer {
    tokens;
    options;
    state;
    tokenizer;
    inlineQueue;
    constructor(options) {
      this.tokens = [];
      this.tokens.links = /* @__PURE__ */ Object.create(null);
      this.options = options || _defaults;
      this.options.tokenizer = this.options.tokenizer || new _Tokenizer();
      this.tokenizer = this.options.tokenizer;
      this.tokenizer.options = this.options;
      this.tokenizer.lexer = this;
      this.inlineQueue = [];
      this.state = {
        inLink: false,
        inRawBlock: false,
        top: true
      };
      const rules = {
        block: block.normal,
        inline: inline.normal
      };
      if (this.options.pedantic) {
        rules.block = block.pedantic;
        rules.inline = inline.pedantic;
      } else if (this.options.gfm) {
        rules.block = block.gfm;
        if (this.options.breaks) {
          rules.inline = inline.breaks;
        } else {
          rules.inline = inline.gfm;
        }
      }
      this.tokenizer.rules = rules;
    }
    /**
     * Expose Rules
     */
    static get rules() {
      return {
        block,
        inline
      };
    }
    /**
     * Static Lex Method
     */
    static lex(src, options) {
      const lexer2 = new _Lexer(options);
      return lexer2.lex(src);
    }
    /**
     * Static Lex Inline Method
     */
    static lexInline(src, options) {
      const lexer2 = new _Lexer(options);
      return lexer2.inlineTokens(src);
    }
    /**
     * Preprocessing
     */
    lex(src) {
      src = src.replace(/\r\n|\r/g, "\n");
      this.blockTokens(src, this.tokens);
      for (let i2 = 0; i2 < this.inlineQueue.length; i2++) {
        const next = this.inlineQueue[i2];
        this.inlineTokens(next.src, next.tokens);
      }
      this.inlineQueue = [];
      return this.tokens;
    }
    blockTokens(src, tokens = [], lastParagraphClipped = false) {
      if (this.options.pedantic) {
        src = src.replace(/\t/g, "    ").replace(/^ +$/gm, "");
      } else {
        src = src.replace(/^( *)(\t+)/gm, (_, leading, tabs) => {
          return leading + "    ".repeat(tabs.length);
        });
      }
      let token;
      let lastToken;
      let cutSrc;
      while (src) {
        if (this.options.extensions && this.options.extensions.block && this.options.extensions.block.some((extTokenizer) => {
          if (token = extTokenizer.call({ lexer: this }, src, tokens)) {
            src = src.substring(token.raw.length);
            tokens.push(token);
            return true;
          }
          return false;
        })) {
          continue;
        }
        if (token = this.tokenizer.space(src)) {
          src = src.substring(token.raw.length);
          if (token.raw.length === 1 && tokens.length > 0) {
            tokens[tokens.length - 1].raw += "\n";
          } else {
            tokens.push(token);
          }
          continue;
        }
        if (token = this.tokenizer.code(src)) {
          src = src.substring(token.raw.length);
          lastToken = tokens[tokens.length - 1];
          if (lastToken && (lastToken.type === "paragraph" || lastToken.type === "text")) {
            lastToken.raw += "\n" + token.raw;
            lastToken.text += "\n" + token.text;
            this.inlineQueue[this.inlineQueue.length - 1].src = lastToken.text;
          } else {
            tokens.push(token);
          }
          continue;
        }
        if (token = this.tokenizer.fences(src)) {
          src = src.substring(token.raw.length);
          tokens.push(token);
          continue;
        }
        if (token = this.tokenizer.heading(src)) {
          src = src.substring(token.raw.length);
          tokens.push(token);
          continue;
        }
        if (token = this.tokenizer.hr(src)) {
          src = src.substring(token.raw.length);
          tokens.push(token);
          continue;
        }
        if (token = this.tokenizer.blockquote(src)) {
          src = src.substring(token.raw.length);
          tokens.push(token);
          continue;
        }
        if (token = this.tokenizer.list(src)) {
          src = src.substring(token.raw.length);
          tokens.push(token);
          continue;
        }
        if (token = this.tokenizer.html(src)) {
          src = src.substring(token.raw.length);
          tokens.push(token);
          continue;
        }
        if (token = this.tokenizer.def(src)) {
          src = src.substring(token.raw.length);
          lastToken = tokens[tokens.length - 1];
          if (lastToken && (lastToken.type === "paragraph" || lastToken.type === "text")) {
            lastToken.raw += "\n" + token.raw;
            lastToken.text += "\n" + token.raw;
            this.inlineQueue[this.inlineQueue.length - 1].src = lastToken.text;
          } else if (!this.tokens.links[token.tag]) {
            this.tokens.links[token.tag] = {
              href: token.href,
              title: token.title
            };
          }
          continue;
        }
        if (token = this.tokenizer.table(src)) {
          src = src.substring(token.raw.length);
          tokens.push(token);
          continue;
        }
        if (token = this.tokenizer.lheading(src)) {
          src = src.substring(token.raw.length);
          tokens.push(token);
          continue;
        }
        cutSrc = src;
        if (this.options.extensions && this.options.extensions.startBlock) {
          let startIndex = Infinity;
          const tempSrc = src.slice(1);
          let tempStart;
          this.options.extensions.startBlock.forEach((getStartIndex) => {
            tempStart = getStartIndex.call({ lexer: this }, tempSrc);
            if (typeof tempStart === "number" && tempStart >= 0) {
              startIndex = Math.min(startIndex, tempStart);
            }
          });
          if (startIndex < Infinity && startIndex >= 0) {
            cutSrc = src.substring(0, startIndex + 1);
          }
        }
        if (this.state.top && (token = this.tokenizer.paragraph(cutSrc))) {
          lastToken = tokens[tokens.length - 1];
          if (lastParagraphClipped && lastToken?.type === "paragraph") {
            lastToken.raw += "\n" + token.raw;
            lastToken.text += "\n" + token.text;
            this.inlineQueue.pop();
            this.inlineQueue[this.inlineQueue.length - 1].src = lastToken.text;
          } else {
            tokens.push(token);
          }
          lastParagraphClipped = cutSrc.length !== src.length;
          src = src.substring(token.raw.length);
          continue;
        }
        if (token = this.tokenizer.text(src)) {
          src = src.substring(token.raw.length);
          lastToken = tokens[tokens.length - 1];
          if (lastToken && lastToken.type === "text") {
            lastToken.raw += "\n" + token.raw;
            lastToken.text += "\n" + token.text;
            this.inlineQueue.pop();
            this.inlineQueue[this.inlineQueue.length - 1].src = lastToken.text;
          } else {
            tokens.push(token);
          }
          continue;
        }
        if (src) {
          const errMsg = "Infinite loop on byte: " + src.charCodeAt(0);
          if (this.options.silent) {
            console.error(errMsg);
            break;
          } else {
            throw new Error(errMsg);
          }
        }
      }
      this.state.top = true;
      return tokens;
    }
    inline(src, tokens = []) {
      this.inlineQueue.push({ src, tokens });
      return tokens;
    }
    /**
     * Lexing/Compiling
     */
    inlineTokens(src, tokens = []) {
      let token, lastToken, cutSrc;
      let maskedSrc = src;
      let match2;
      let keepPrevChar, prevChar;
      if (this.tokens.links) {
        const links = Object.keys(this.tokens.links);
        if (links.length > 0) {
          while ((match2 = this.tokenizer.rules.inline.reflinkSearch.exec(maskedSrc)) != null) {
            if (links.includes(match2[0].slice(match2[0].lastIndexOf("[") + 1, -1))) {
              maskedSrc = maskedSrc.slice(0, match2.index) + "[" + "a".repeat(match2[0].length - 2) + "]" + maskedSrc.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex);
            }
          }
        }
      }
      while ((match2 = this.tokenizer.rules.inline.blockSkip.exec(maskedSrc)) != null) {
        maskedSrc = maskedSrc.slice(0, match2.index) + "[" + "a".repeat(match2[0].length - 2) + "]" + maskedSrc.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);
      }
      while ((match2 = this.tokenizer.rules.inline.anyPunctuation.exec(maskedSrc)) != null) {
        maskedSrc = maskedSrc.slice(0, match2.index) + "++" + maskedSrc.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);
      }
      while (src) {
        if (!keepPrevChar) {
          prevChar = "";
        }
        keepPrevChar = false;
        if (this.options.extensions && this.options.extensions.inline && this.options.extensions.inline.some((extTokenizer) => {
          if (token = extTokenizer.call({ lexer: this }, src, tokens)) {
            src = src.substring(token.raw.length);
            tokens.push(token);
            return true;
          }
          return false;
        })) {
          continue;
        }
        if (token = this.tokenizer.escape(src)) {
          src = src.substring(token.raw.length);
          tokens.push(token);
          continue;
        }
        if (token = this.tokenizer.tag(src)) {
          src = src.substring(token.raw.length);
          lastToken = tokens[tokens.length - 1];
          if (lastToken && token.type === "text" && lastToken.type === "text") {
            lastToken.raw += token.raw;
            lastToken.text += token.text;
          } else {
            tokens.push(token);
          }
          continue;
        }
        if (token = this.tokenizer.link(src)) {
          src = src.substring(token.raw.length);
          tokens.push(token);
          continue;
        }
        if (token = this.tokenizer.reflink(src, this.tokens.links)) {
          src = src.substring(token.raw.length);
          lastToken = tokens[tokens.length - 1];
          if (lastToken && token.type === "text" && lastToken.type === "text") {
            lastToken.raw += token.raw;
            lastToken.text += token.text;
          } else {
            tokens.push(token);
          }
          continue;
        }
        if (token = this.tokenizer.emStrong(src, maskedSrc, prevChar)) {
          src = src.substring(token.raw.length);
          tokens.push(token);
          continue;
        }
        if (token = this.tokenizer.codespan(src)) {
          src = src.substring(token.raw.length);
          tokens.push(token);
          continue;
        }
        if (token = this.tokenizer.br(src)) {
          src = src.substring(token.raw.length);
          tokens.push(token);
          continue;
        }
        if (token = this.tokenizer.del(src)) {
          src = src.substring(token.raw.length);
          tokens.push(token);
          continue;
        }
        if (token = this.tokenizer.autolink(src)) {
          src = src.substring(token.raw.length);
          tokens.push(token);
          continue;
        }
        if (!this.state.inLink && (token = this.tokenizer.url(src))) {
          src = src.substring(token.raw.length);
          tokens.push(token);
          continue;
        }
        cutSrc = src;
        if (this.options.extensions && this.options.extensions.startInline) {
          let startIndex = Infinity;
          const tempSrc = src.slice(1);
          let tempStart;
          this.options.extensions.startInline.forEach((getStartIndex) => {
            tempStart = getStartIndex.call({ lexer: this }, tempSrc);
            if (typeof tempStart === "number" && tempStart >= 0) {
              startIndex = Math.min(startIndex, tempStart);
            }
          });
          if (startIndex < Infinity && startIndex >= 0) {
            cutSrc = src.substring(0, startIndex + 1);
          }
        }
        if (token = this.tokenizer.inlineText(cutSrc)) {
          src = src.substring(token.raw.length);
          if (token.raw.slice(-1) !== "_") {
            prevChar = token.raw.slice(-1);
          }
          keepPrevChar = true;
          lastToken = tokens[tokens.length - 1];
          if (lastToken && lastToken.type === "text") {
            lastToken.raw += token.raw;
            lastToken.text += token.text;
          } else {
            tokens.push(token);
          }
          continue;
        }
        if (src) {
          const errMsg = "Infinite loop on byte: " + src.charCodeAt(0);
          if (this.options.silent) {
            console.error(errMsg);
            break;
          } else {
            throw new Error(errMsg);
          }
        }
      }
      return tokens;
    }
  }
  class _Renderer {
    options;
    parser;
    // set by the parser
    constructor(options) {
      this.options = options || _defaults;
    }
    space(token) {
      return "";
    }
    code({ text: text2, lang, escaped }) {
      const langString = (lang || "").match(/^\S*/)?.[0];
      const code = text2.replace(/\n$/, "") + "\n";
      if (!langString) {
        return "<pre><code>" + (escaped ? code : escape$1(code, true)) + "</code></pre>\n";
      }
      return '<pre><code class="language-' + escape$1(langString) + '">' + (escaped ? code : escape$1(code, true)) + "</code></pre>\n";
    }
    blockquote({ tokens }) {
      const body = this.parser.parse(tokens);
      return `<blockquote>
${body}</blockquote>
`;
    }
    html({ text: text2 }) {
      return text2;
    }
    heading({ tokens, depth }) {
      return `<h${depth}>${this.parser.parseInline(tokens)}</h${depth}>
`;
    }
    hr(token) {
      return "<hr>\n";
    }
    list(token) {
      const ordered = token.ordered;
      const start = token.start;
      let body = "";
      for (let j = 0; j < token.items.length; j++) {
        const item = token.items[j];
        body += this.listitem(item);
      }
      const type = ordered ? "ol" : "ul";
      const startAttr = ordered && start !== 1 ? ' start="' + start + '"' : "";
      return "<" + type + startAttr + ">\n" + body + "</" + type + ">\n";
    }
    listitem(item) {
      let itemBody = "";
      if (item.task) {
        const checkbox = this.checkbox({ checked: !!item.checked });
        if (item.loose) {
          if (item.tokens.length > 0 && item.tokens[0].type === "paragraph") {
            item.tokens[0].text = checkbox + " " + item.tokens[0].text;
            if (item.tokens[0].tokens && item.tokens[0].tokens.length > 0 && item.tokens[0].tokens[0].type === "text") {
              item.tokens[0].tokens[0].text = checkbox + " " + item.tokens[0].tokens[0].text;
            }
          } else {
            item.tokens.unshift({
              type: "text",
              raw: checkbox + " ",
              text: checkbox + " "
            });
          }
        } else {
          itemBody += checkbox + " ";
        }
      }
      itemBody += this.parser.parse(item.tokens, !!item.loose);
      return `<li>${itemBody}</li>
`;
    }
    checkbox({ checked }) {
      return "<input " + (checked ? 'checked="" ' : "") + 'disabled="" type="checkbox">';
    }
    paragraph({ tokens }) {
      return `<p>${this.parser.parseInline(tokens)}</p>
`;
    }
    table(token) {
      let header2 = "";
      let cell = "";
      for (let j = 0; j < token.header.length; j++) {
        cell += this.tablecell(token.header[j]);
      }
      header2 += this.tablerow({ text: cell });
      let body = "";
      for (let j = 0; j < token.rows.length; j++) {
        const row = token.rows[j];
        cell = "";
        for (let k = 0; k < row.length; k++) {
          cell += this.tablecell(row[k]);
        }
        body += this.tablerow({ text: cell });
      }
      if (body)
        body = `<tbody>${body}</tbody>`;
      return "<table>\n<thead>\n" + header2 + "</thead>\n" + body + "</table>\n";
    }
    tablerow({ text: text2 }) {
      return `<tr>
${text2}</tr>
`;
    }
    tablecell(token) {
      const content = this.parser.parseInline(token.tokens);
      const type = token.header ? "th" : "td";
      const tag2 = token.align ? `<${type} align="${token.align}">` : `<${type}>`;
      return tag2 + content + `</${type}>
`;
    }
    /**
     * span level renderer
     */
    strong({ tokens }) {
      return `<strong>${this.parser.parseInline(tokens)}</strong>`;
    }
    em({ tokens }) {
      return `<em>${this.parser.parseInline(tokens)}</em>`;
    }
    codespan({ text: text2 }) {
      return `<code>${text2}</code>`;
    }
    br(token) {
      return "<br>";
    }
    del({ tokens }) {
      return `<del>${this.parser.parseInline(tokens)}</del>`;
    }
    link({ href, title, tokens }) {
      const text2 = this.parser.parseInline(tokens);
      const cleanHref = cleanUrl(href);
      if (cleanHref === null) {
        return text2;
      }
      href = cleanHref;
      let out = '<a href="' + href + '"';
      if (title) {
        out += ' title="' + title + '"';
      }
      out += ">" + text2 + "</a>";
      return out;
    }
    image({ href, title, text: text2 }) {
      const cleanHref = cleanUrl(href);
      if (cleanHref === null) {
        return text2;
      }
      href = cleanHref;
      let out = `<img src="${href}" alt="${text2}"`;
      if (title) {
        out += ` title="${title}"`;
      }
      out += ">";
      return out;
    }
    text(token) {
      return "tokens" in token && token.tokens ? this.parser.parseInline(token.tokens) : token.text;
    }
  }
  class _TextRenderer {
    // no need for block level renderers
    strong({ text: text2 }) {
      return text2;
    }
    em({ text: text2 }) {
      return text2;
    }
    codespan({ text: text2 }) {
      return text2;
    }
    del({ text: text2 }) {
      return text2;
    }
    html({ text: text2 }) {
      return text2;
    }
    text({ text: text2 }) {
      return text2;
    }
    link({ text: text2 }) {
      return "" + text2;
    }
    image({ text: text2 }) {
      return "" + text2;
    }
    br() {
      return "";
    }
  }
  class _Parser {
    options;
    renderer;
    textRenderer;
    constructor(options) {
      this.options = options || _defaults;
      this.options.renderer = this.options.renderer || new _Renderer();
      this.renderer = this.options.renderer;
      this.renderer.options = this.options;
      this.renderer.parser = this;
      this.textRenderer = new _TextRenderer();
    }
    /**
     * Static Parse Method
     */
    static parse(tokens, options) {
      const parser = new _Parser(options);
      return parser.parse(tokens);
    }
    /**
     * Static Parse Inline Method
     */
    static parseInline(tokens, options) {
      const parser = new _Parser(options);
      return parser.parseInline(tokens);
    }
    /**
     * Parse Loop
     */
    parse(tokens, top = true) {
      let out = "";
      for (let i2 = 0; i2 < tokens.length; i2++) {
        const anyToken = tokens[i2];
        if (this.options.extensions && this.options.extensions.renderers && this.options.extensions.renderers[anyToken.type]) {
          const genericToken = anyToken;
          const ret = this.options.extensions.renderers[genericToken.type].call({ parser: this }, genericToken);
          if (ret !== false || !["space", "hr", "heading", "code", "table", "blockquote", "list", "html", "paragraph", "text"].includes(genericToken.type)) {
            out += ret || "";
            continue;
          }
        }
        const token = anyToken;
        switch (token.type) {
          case "space": {
            out += this.renderer.space(token);
            continue;
          }
          case "hr": {
            out += this.renderer.hr(token);
            continue;
          }
          case "heading": {
            out += this.renderer.heading(token);
            continue;
          }
          case "code": {
            out += this.renderer.code(token);
            continue;
          }
          case "table": {
            out += this.renderer.table(token);
            continue;
          }
          case "blockquote": {
            out += this.renderer.blockquote(token);
            continue;
          }
          case "list": {
            out += this.renderer.list(token);
            continue;
          }
          case "html": {
            out += this.renderer.html(token);
            continue;
          }
          case "paragraph": {
            out += this.renderer.paragraph(token);
            continue;
          }
          case "text": {
            let textToken = token;
            let body = this.renderer.text(textToken);
            while (i2 + 1 < tokens.length && tokens[i2 + 1].type === "text") {
              textToken = tokens[++i2];
              body += "\n" + this.renderer.text(textToken);
            }
            if (top) {
              out += this.renderer.paragraph({
                type: "paragraph",
                raw: body,
                text: body,
                tokens: [{ type: "text", raw: body, text: body }]
              });
            } else {
              out += body;
            }
            continue;
          }
          default: {
            const errMsg = 'Token with "' + token.type + '" type was not found.';
            if (this.options.silent) {
              console.error(errMsg);
              return "";
            } else {
              throw new Error(errMsg);
            }
          }
        }
      }
      return out;
    }
    /**
     * Parse Inline Tokens
     */
    parseInline(tokens, renderer) {
      renderer = renderer || this.renderer;
      let out = "";
      for (let i2 = 0; i2 < tokens.length; i2++) {
        const anyToken = tokens[i2];
        if (this.options.extensions && this.options.extensions.renderers && this.options.extensions.renderers[anyToken.type]) {
          const ret = this.options.extensions.renderers[anyToken.type].call({ parser: this }, anyToken);
          if (ret !== false || !["escape", "html", "link", "image", "strong", "em", "codespan", "br", "del", "text"].includes(anyToken.type)) {
            out += ret || "";
            continue;
          }
        }
        const token = anyToken;
        switch (token.type) {
          case "escape": {
            out += renderer.text(token);
            break;
          }
          case "html": {
            out += renderer.html(token);
            break;
          }
          case "link": {
            out += renderer.link(token);
            break;
          }
          case "image": {
            out += renderer.image(token);
            break;
          }
          case "strong": {
            out += renderer.strong(token);
            break;
          }
          case "em": {
            out += renderer.em(token);
            break;
          }
          case "codespan": {
            out += renderer.codespan(token);
            break;
          }
          case "br": {
            out += renderer.br(token);
            break;
          }
          case "del": {
            out += renderer.del(token);
            break;
          }
          case "text": {
            out += renderer.text(token);
            break;
          }
          default: {
            const errMsg = 'Token with "' + token.type + '" type was not found.';
            if (this.options.silent) {
              console.error(errMsg);
              return "";
            } else {
              throw new Error(errMsg);
            }
          }
        }
      }
      return out;
    }
  }
  class _Hooks {
    options;
    constructor(options) {
      this.options = options || _defaults;
    }
    static passThroughHooks = /* @__PURE__ */ new Set([
      "preprocess",
      "postprocess",
      "processAllTokens"
    ]);
    /**
     * Process markdown before marked
     */
    preprocess(markdown) {
      return markdown;
    }
    /**
     * Process HTML after marked is finished
     */
    postprocess(html2) {
      return html2;
    }
    /**
     * Process all tokens before walk tokens
     */
    processAllTokens(tokens) {
      return tokens;
    }
  }
  class Marked {
    defaults = _getDefaults();
    options = this.setOptions;
    parse = this.parseMarkdown(_Lexer.lex, _Parser.parse);
    parseInline = this.parseMarkdown(_Lexer.lexInline, _Parser.parseInline);
    Parser = _Parser;
    Renderer = _Renderer;
    TextRenderer = _TextRenderer;
    Lexer = _Lexer;
    Tokenizer = _Tokenizer;
    Hooks = _Hooks;
    constructor(...args) {
      this.use(...args);
    }
    /**
     * Run callback for every token
     */
    walkTokens(tokens, callback) {
      let values = [];
      for (const token of tokens) {
        values = values.concat(callback.call(this, token));
        switch (token.type) {
          case "table": {
            const tableToken = token;
            for (const cell of tableToken.header) {
              values = values.concat(this.walkTokens(cell.tokens, callback));
            }
            for (const row of tableToken.rows) {
              for (const cell of row) {
                values = values.concat(this.walkTokens(cell.tokens, callback));
              }
            }
            break;
          }
          case "list": {
            const listToken = token;
            values = values.concat(this.walkTokens(listToken.items, callback));
            break;
          }
          default: {
            const genericToken = token;
            if (this.defaults.extensions?.childTokens?.[genericToken.type]) {
              this.defaults.extensions.childTokens[genericToken.type].forEach((childTokens) => {
                const tokens2 = genericToken[childTokens].flat(Infinity);
                values = values.concat(this.walkTokens(tokens2, callback));
              });
            } else if (genericToken.tokens) {
              values = values.concat(this.walkTokens(genericToken.tokens, callback));
            }
          }
        }
      }
      return values;
    }
    use(...args) {
      const extensions = this.defaults.extensions || { renderers: {}, childTokens: {} };
      args.forEach((pack) => {
        const opts = { ...pack };
        opts.async = this.defaults.async || opts.async || false;
        if (pack.extensions) {
          pack.extensions.forEach((ext) => {
            if (!ext.name) {
              throw new Error("extension name required");
            }
            if ("renderer" in ext) {
              const prevRenderer = extensions.renderers[ext.name];
              if (prevRenderer) {
                extensions.renderers[ext.name] = function(...args2) {
                  let ret = ext.renderer.apply(this, args2);
                  if (ret === false) {
                    ret = prevRenderer.apply(this, args2);
                  }
                  return ret;
                };
              } else {
                extensions.renderers[ext.name] = ext.renderer;
              }
            }
            if ("tokenizer" in ext) {
              if (!ext.level || ext.level !== "block" && ext.level !== "inline") {
                throw new Error("extension level must be 'block' or 'inline'");
              }
              const extLevel = extensions[ext.level];
              if (extLevel) {
                extLevel.unshift(ext.tokenizer);
              } else {
                extensions[ext.level] = [ext.tokenizer];
              }
              if (ext.start) {
                if (ext.level === "block") {
                  if (extensions.startBlock) {
                    extensions.startBlock.push(ext.start);
                  } else {
                    extensions.startBlock = [ext.start];
                  }
                } else if (ext.level === "inline") {
                  if (extensions.startInline) {
                    extensions.startInline.push(ext.start);
                  } else {
                    extensions.startInline = [ext.start];
                  }
                }
              }
            }
            if ("childTokens" in ext && ext.childTokens) {
              extensions.childTokens[ext.name] = ext.childTokens;
            }
          });
          opts.extensions = extensions;
        }
        if (pack.renderer) {
          const renderer = this.defaults.renderer || new _Renderer(this.defaults);
          for (const prop in pack.renderer) {
            if (!(prop in renderer)) {
              throw new Error(`renderer '${prop}' does not exist`);
            }
            if (["options", "parser"].includes(prop)) {
              continue;
            }
            const rendererProp = prop;
            const rendererFunc = pack.renderer[rendererProp];
            const prevRenderer = renderer[rendererProp];
            renderer[rendererProp] = (...args2) => {
              let ret = rendererFunc.apply(renderer, args2);
              if (ret === false) {
                ret = prevRenderer.apply(renderer, args2);
              }
              return ret || "";
            };
          }
          opts.renderer = renderer;
        }
        if (pack.tokenizer) {
          const tokenizer = this.defaults.tokenizer || new _Tokenizer(this.defaults);
          for (const prop in pack.tokenizer) {
            if (!(prop in tokenizer)) {
              throw new Error(`tokenizer '${prop}' does not exist`);
            }
            if (["options", "rules", "lexer"].includes(prop)) {
              continue;
            }
            const tokenizerProp = prop;
            const tokenizerFunc = pack.tokenizer[tokenizerProp];
            const prevTokenizer = tokenizer[tokenizerProp];
            tokenizer[tokenizerProp] = (...args2) => {
              let ret = tokenizerFunc.apply(tokenizer, args2);
              if (ret === false) {
                ret = prevTokenizer.apply(tokenizer, args2);
              }
              return ret;
            };
          }
          opts.tokenizer = tokenizer;
        }
        if (pack.hooks) {
          const hooks = this.defaults.hooks || new _Hooks();
          for (const prop in pack.hooks) {
            if (!(prop in hooks)) {
              throw new Error(`hook '${prop}' does not exist`);
            }
            if (prop === "options") {
              continue;
            }
            const hooksProp = prop;
            const hooksFunc = pack.hooks[hooksProp];
            const prevHook = hooks[hooksProp];
            if (_Hooks.passThroughHooks.has(prop)) {
              hooks[hooksProp] = (arg) => {
                if (this.defaults.async) {
                  return Promise.resolve(hooksFunc.call(hooks, arg)).then((ret2) => {
                    return prevHook.call(hooks, ret2);
                  });
                }
                const ret = hooksFunc.call(hooks, arg);
                return prevHook.call(hooks, ret);
              };
            } else {
              hooks[hooksProp] = (...args2) => {
                let ret = hooksFunc.apply(hooks, args2);
                if (ret === false) {
                  ret = prevHook.apply(hooks, args2);
                }
                return ret;
              };
            }
          }
          opts.hooks = hooks;
        }
        if (pack.walkTokens) {
          const walkTokens = this.defaults.walkTokens;
          const packWalktokens = pack.walkTokens;
          opts.walkTokens = function(token) {
            let values = [];
            values.push(packWalktokens.call(this, token));
            if (walkTokens) {
              values = values.concat(walkTokens.call(this, token));
            }
            return values;
          };
        }
        this.defaults = { ...this.defaults, ...opts };
      });
      return this;
    }
    setOptions(opt) {
      this.defaults = { ...this.defaults, ...opt };
      return this;
    }
    lexer(src, options) {
      return _Lexer.lex(src, options ?? this.defaults);
    }
    parser(tokens, options) {
      return _Parser.parse(tokens, options ?? this.defaults);
    }
    parseMarkdown(lexer2, parser) {
      const parse2 = (src, options) => {
        const origOpt = { ...options };
        const opt = { ...this.defaults, ...origOpt };
        const throwError = this.onError(!!opt.silent, !!opt.async);
        if (this.defaults.async === true && origOpt.async === false) {
          return throwError(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));
        }
        if (typeof src === "undefined" || src === null) {
          return throwError(new Error("marked(): input parameter is undefined or null"));
        }
        if (typeof src !== "string") {
          return throwError(new Error("marked(): input parameter is of type " + Object.prototype.toString.call(src) + ", string expected"));
        }
        if (opt.hooks) {
          opt.hooks.options = opt;
        }
        if (opt.async) {
          return Promise.resolve(opt.hooks ? opt.hooks.preprocess(src) : src).then((src2) => lexer2(src2, opt)).then((tokens) => opt.hooks ? opt.hooks.processAllTokens(tokens) : tokens).then((tokens) => opt.walkTokens ? Promise.all(this.walkTokens(tokens, opt.walkTokens)).then(() => tokens) : tokens).then((tokens) => parser(tokens, opt)).then((html2) => opt.hooks ? opt.hooks.postprocess(html2) : html2).catch(throwError);
        }
        try {
          if (opt.hooks) {
            src = opt.hooks.preprocess(src);
          }
          let tokens = lexer2(src, opt);
          if (opt.hooks) {
            tokens = opt.hooks.processAllTokens(tokens);
          }
          if (opt.walkTokens) {
            this.walkTokens(tokens, opt.walkTokens);
          }
          let html2 = parser(tokens, opt);
          if (opt.hooks) {
            html2 = opt.hooks.postprocess(html2);
          }
          return html2;
        } catch (e) {
          return throwError(e);
        }
      };
      return parse2;
    }
    onError(silent, async) {
      return (e) => {
        e.message += "\nPlease report this to https://github.com/markedjs/marked.";
        if (silent) {
          const msg = "<p>An error occurred:</p><pre>" + escape$1(e.message + "", true) + "</pre>";
          if (async) {
            return Promise.resolve(msg);
          }
          return msg;
        }
        if (async) {
          return Promise.reject(e);
        }
        throw e;
      };
    }
  }
  const markedInstance = new Marked();
  function marked(src, opt) {
    return markedInstance.parse(src, opt);
  }
  marked.options = marked.setOptions = function(options) {
    markedInstance.setOptions(options);
    marked.defaults = markedInstance.defaults;
    changeDefaults(marked.defaults);
    return marked;
  };
  marked.getDefaults = _getDefaults;
  marked.defaults = _defaults;
  marked.use = function(...args) {
    markedInstance.use(...args);
    marked.defaults = markedInstance.defaults;
    changeDefaults(marked.defaults);
    return marked;
  };
  marked.walkTokens = function(tokens, callback) {
    return markedInstance.walkTokens(tokens, callback);
  };
  marked.parseInline = markedInstance.parseInline;
  marked.Parser = _Parser;
  marked.parser = _Parser.parse;
  marked.Renderer = _Renderer;
  marked.TextRenderer = _TextRenderer;
  marked.Lexer = _Lexer;
  marked.lexer = _Lexer.lex;
  marked.Tokenizer = _Tokenizer;
  marked.Hooks = _Hooks;
  marked.parse = marked;
  marked.options;
  marked.setOptions;
  marked.use;
  marked.walkTokens;
  marked.parseInline;
  const parse$2 = marked;
  _Parser.parse;
  const lexer = _Lexer.lex;
  function stringify(obj) {
    return JSON.stringify(obj, replacer);
  }
  function parse$1(text2) {
    let data = JSON.parse(text2);
    data = revive(data);
    return data;
  }
  function replacer(key, value) {
    if (value instanceof RegExp) {
      return {
        $mid: 2,
        source: value.source,
        flags: value.flags
      };
    }
    return value;
  }
  function revive(obj, depth = 0) {
    if (!obj || depth > 200) {
      return obj;
    }
    if (typeof obj === "object") {
      switch (obj.$mid) {
        // eslint-disable-next-line local/code-no-any-casts
        case 1:
          return URI.revive(obj);
        // eslint-disable-next-line local/code-no-any-casts
        case 2:
          return new RegExp(obj.source, obj.flags);
        // eslint-disable-next-line local/code-no-any-casts
        case 17:
          return new Date(obj.source);
      }
      if (obj instanceof VSBuffer || obj instanceof Uint8Array) {
        return obj;
      }
      if (Array.isArray(obj)) {
        for (let i2 = 0; i2 < obj.length; ++i2) {
          obj[i2] = revive(obj[i2], depth + 1);
        }
      } else {
        for (const key in obj) {
          if (Object.hasOwnProperty.call(obj, key)) {
            obj[key] = revive(obj[key], depth + 1);
          }
        }
      }
    }
    return obj;
  }
  /*! @license DOMPurify 3.2.7 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.2.7/LICENSE */
  const {
    entries,
    setPrototypeOf,
    isFrozen,
    getPrototypeOf,
    getOwnPropertyDescriptor
  } = Object;
  let {
    freeze: freeze$1,
    seal,
    create: create$1
  } = Object;
  let {
    apply,
    construct
  } = typeof Reflect !== "undefined" && Reflect;
  if (!freeze$1) {
    freeze$1 = function freeze2(x) {
      return x;
    };
  }
  if (!seal) {
    seal = function seal2(x) {
      return x;
    };
  }
  if (!apply) {
    apply = function apply2(func, thisArg) {
      for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
        args[_key - 2] = arguments[_key];
      }
      return func.apply(thisArg, args);
    };
  }
  if (!construct) {
    construct = function construct2(Func) {
      for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
        args[_key2 - 1] = arguments[_key2];
      }
      return new Func(...args);
    };
  }
  const arrayForEach = unapply(Array.prototype.forEach);
  const arrayLastIndexOf = unapply(Array.prototype.lastIndexOf);
  const arrayPop = unapply(Array.prototype.pop);
  const arrayPush = unapply(Array.prototype.push);
  const arraySplice = unapply(Array.prototype.splice);
  const stringToLowerCase = unapply(String.prototype.toLowerCase);
  const stringToString = unapply(String.prototype.toString);
  const stringMatch = unapply(String.prototype.match);
  const stringReplace = unapply(String.prototype.replace);
  const stringIndexOf = unapply(String.prototype.indexOf);
  const stringTrim = unapply(String.prototype.trim);
  const objectHasOwnProperty = unapply(Object.prototype.hasOwnProperty);
  const regExpTest = unapply(RegExp.prototype.test);
  const typeErrorCreate = unconstruct(TypeError);
  function unapply(func) {
    return function(thisArg) {
      if (thisArg instanceof RegExp) {
        thisArg.lastIndex = 0;
      }
      for (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
        args[_key3 - 1] = arguments[_key3];
      }
      return apply(func, thisArg, args);
    };
  }
  function unconstruct(Func) {
    return function() {
      for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
        args[_key4] = arguments[_key4];
      }
      return construct(Func, args);
    };
  }
  function addToSet(set, array2) {
    let transformCaseFunc = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : stringToLowerCase;
    if (setPrototypeOf) {
      setPrototypeOf(set, null);
    }
    let l = array2.length;
    while (l--) {
      let element = array2[l];
      if (typeof element === "string") {
        const lcElement = transformCaseFunc(element);
        if (lcElement !== element) {
          if (!isFrozen(array2)) {
            array2[l] = lcElement;
          }
          element = lcElement;
        }
      }
      set[element] = true;
    }
    return set;
  }
  function cleanArray(array2) {
    for (let index = 0; index < array2.length; index++) {
      const isPropertyExist = objectHasOwnProperty(array2, index);
      if (!isPropertyExist) {
        array2[index] = null;
      }
    }
    return array2;
  }
  function clone(object) {
    const newObject = create$1(null);
    for (const [property, value] of entries(object)) {
      const isPropertyExist = objectHasOwnProperty(object, property);
      if (isPropertyExist) {
        if (Array.isArray(value)) {
          newObject[property] = cleanArray(value);
        } else if (value && typeof value === "object" && value.constructor === Object) {
          newObject[property] = clone(value);
        } else {
          newObject[property] = value;
        }
      }
    }
    return newObject;
  }
  function lookupGetter(object, prop) {
    while (object !== null) {
      const desc = getOwnPropertyDescriptor(object, prop);
      if (desc) {
        if (desc.get) {
          return unapply(desc.get);
        }
        if (typeof desc.value === "function") {
          return unapply(desc.value);
        }
      }
      object = getPrototypeOf(object);
    }
    function fallbackValue() {
      return null;
    }
    return fallbackValue;
  }
  const html$1 = freeze$1(["a", "abbr", "acronym", "address", "area", "article", "aside", "audio", "b", "bdi", "bdo", "big", "blink", "blockquote", "body", "br", "button", "canvas", "caption", "center", "cite", "code", "col", "colgroup", "content", "data", "datalist", "dd", "decorator", "del", "details", "dfn", "dialog", "dir", "div", "dl", "dt", "element", "em", "fieldset", "figcaption", "figure", "font", "footer", "form", "h1", "h2", "h3", "h4", "h5", "h6", "head", "header", "hgroup", "hr", "html", "i", "img", "input", "ins", "kbd", "label", "legend", "li", "main", "map", "mark", "marquee", "menu", "menuitem", "meter", "nav", "nobr", "ol", "optgroup", "option", "output", "p", "picture", "pre", "progress", "q", "rp", "rt", "ruby", "s", "samp", "search", "section", "select", "shadow", "slot", "small", "source", "spacer", "span", "strike", "strong", "style", "sub", "summary", "sup", "table", "tbody", "td", "template", "textarea", "tfoot", "th", "thead", "time", "tr", "track", "tt", "u", "ul", "var", "video", "wbr"]);
  const svg$1 = freeze$1(["svg", "a", "altglyph", "altglyphdef", "altglyphitem", "animatecolor", "animatemotion", "animatetransform", "circle", "clippath", "defs", "desc", "ellipse", "enterkeyhint", "exportparts", "filter", "font", "g", "glyph", "glyphref", "hkern", "image", "inputmode", "line", "lineargradient", "marker", "mask", "metadata", "mpath", "part", "path", "pattern", "polygon", "polyline", "radialgradient", "rect", "slot", "stop", "style", "switch", "symbol", "text", "textpath", "title", "tref", "tspan", "view", "vkern"]);
  const svgFilters = freeze$1(["feBlend", "feColorMatrix", "feComponentTransfer", "feComposite", "feConvolveMatrix", "feDiffuseLighting", "feDisplacementMap", "feDistantLight", "feDropShadow", "feFlood", "feFuncA", "feFuncB", "feFuncG", "feFuncR", "feGaussianBlur", "feImage", "feMerge", "feMergeNode", "feMorphology", "feOffset", "fePointLight", "feSpecularLighting", "feSpotLight", "feTile", "feTurbulence"]);
  const svgDisallowed = freeze$1(["animate", "color-profile", "cursor", "discard", "font-face", "font-face-format", "font-face-name", "font-face-src", "font-face-uri", "foreignobject", "hatch", "hatchpath", "mesh", "meshgradient", "meshpatch", "meshrow", "missing-glyph", "script", "set", "solidcolor", "unknown", "use"]);
  const mathMl$1 = freeze$1(["math", "menclose", "merror", "mfenced", "mfrac", "mglyph", "mi", "mlabeledtr", "mmultiscripts", "mn", "mo", "mover", "mpadded", "mphantom", "mroot", "mrow", "ms", "mspace", "msqrt", "mstyle", "msub", "msup", "msubsup", "mtable", "mtd", "mtext", "mtr", "munder", "munderover", "mprescripts"]);
  const mathMlDisallowed = freeze$1(["maction", "maligngroup", "malignmark", "mlongdiv", "mscarries", "mscarry", "msgroup", "mstack", "msline", "msrow", "semantics", "annotation", "annotation-xml", "mprescripts", "none"]);
  const text = freeze$1(["#text"]);
  const html = freeze$1(["accept", "action", "align", "alt", "autocapitalize", "autocomplete", "autopictureinpicture", "autoplay", "background", "bgcolor", "border", "capture", "cellpadding", "cellspacing", "checked", "cite", "class", "clear", "color", "cols", "colspan", "controls", "controlslist", "coords", "crossorigin", "datetime", "decoding", "default", "dir", "disabled", "disablepictureinpicture", "disableremoteplayback", "download", "draggable", "enctype", "enterkeyhint", "exportparts", "face", "for", "headers", "height", "hidden", "high", "href", "hreflang", "id", "inert", "inputmode", "integrity", "ismap", "kind", "label", "lang", "list", "loading", "loop", "low", "max", "maxlength", "media", "method", "min", "minlength", "multiple", "muted", "name", "nonce", "noshade", "novalidate", "nowrap", "open", "optimum", "part", "pattern", "placeholder", "playsinline", "popover", "popovertarget", "popovertargetaction", "poster", "preload", "pubdate", "radiogroup", "readonly", "rel", "required", "rev", "reversed", "role", "rows", "rowspan", "spellcheck", "scope", "selected", "shape", "size", "sizes", "slot", "span", "srclang", "start", "src", "srcset", "step", "style", "summary", "tabindex", "title", "translate", "type", "usemap", "valign", "value", "width", "wrap", "xmlns", "slot"]);
  const svg = freeze$1(["accent-height", "accumulate", "additive", "alignment-baseline", "amplitude", "ascent", "attributename", "attributetype", "azimuth", "basefrequency", "baseline-shift", "begin", "bias", "by", "class", "clip", "clippathunits", "clip-path", "clip-rule", "color", "color-interpolation", "color-interpolation-filters", "color-profile", "color-rendering", "cx", "cy", "d", "dx", "dy", "diffuseconstant", "direction", "display", "divisor", "dur", "edgemode", "elevation", "end", "exponent", "fill", "fill-opacity", "fill-rule", "filter", "filterunits", "flood-color", "flood-opacity", "font-family", "font-size", "font-size-adjust", "font-stretch", "font-style", "font-variant", "font-weight", "fx", "fy", "g1", "g2", "glyph-name", "glyphref", "gradientunits", "gradienttransform", "height", "href", "id", "image-rendering", "in", "in2", "intercept", "k", "k1", "k2", "k3", "k4", "kerning", "keypoints", "keysplines", "keytimes", "lang", "lengthadjust", "letter-spacing", "kernelmatrix", "kernelunitlength", "lighting-color", "local", "marker-end", "marker-mid", "marker-start", "markerheight", "markerunits", "markerwidth", "maskcontentunits", "maskunits", "max", "mask", "media", "method", "mode", "min", "name", "numoctaves", "offset", "operator", "opacity", "order", "orient", "orientation", "origin", "overflow", "paint-order", "path", "pathlength", "patterncontentunits", "patterntransform", "patternunits", "points", "preservealpha", "preserveaspectratio", "primitiveunits", "r", "rx", "ry", "radius", "refx", "refy", "repeatcount", "repeatdur", "restart", "result", "rotate", "scale", "seed", "shape-rendering", "slope", "specularconstant", "specularexponent", "spreadmethod", "startoffset", "stddeviation", "stitchtiles", "stop-color", "stop-opacity", "stroke-dasharray", "stroke-dashoffset", "stroke-linecap", "stroke-linejoin", "stroke-miterlimit", "stroke-opacity", "stroke", "stroke-width", "style", "surfacescale", "systemlanguage", "tabindex", "tablevalues", "targetx", "targety", "transform", "transform-origin", "text-anchor", "text-decoration", "text-rendering", "textlength", "type", "u1", "u2", "unicode", "values", "viewbox", "visibility", "version", "vert-adv-y", "vert-origin-x", "vert-origin-y", "width", "word-spacing", "wrap", "writing-mode", "xchannelselector", "ychannelselector", "x", "x1", "x2", "xmlns", "y", "y1", "y2", "z", "zoomandpan"]);
  const mathMl = freeze$1(["accent", "accentunder", "align", "bevelled", "close", "columnsalign", "columnlines", "columnspan", "denomalign", "depth", "dir", "display", "displaystyle", "encoding", "fence", "frame", "height", "href", "id", "largeop", "length", "linethickness", "lspace", "lquote", "mathbackground", "mathcolor", "mathsize", "mathvariant", "maxsize", "minsize", "movablelimits", "notation", "numalign", "open", "rowalign", "rowlines", "rowspacing", "rowspan", "rspace", "rquote", "scriptlevel", "scriptminsize", "scriptsizemultiplier", "selection", "separator", "separators", "stretchy", "subscriptshift", "supscriptshift", "symmetric", "voffset", "width", "xmlns"]);
  const xml = freeze$1(["xlink:href", "xml:id", "xlink:title", "xml:space", "xmlns:xlink"]);
  const MUSTACHE_EXPR = seal(/\{\{[\w\W]*|[\w\W]*\}\}/gm);
  const ERB_EXPR = seal(/<%[\w\W]*|[\w\W]*%>/gm);
  const TMPLIT_EXPR = seal(/\$\{[\w\W]*/gm);
  const DATA_ATTR = seal(/^data-[\-\w.\u00B7-\uFFFF]+$/);
  const ARIA_ATTR = seal(/^aria-[\-\w]+$/);
  const IS_ALLOWED_URI = seal(
    /^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i
    // eslint-disable-line no-useless-escape
  );
  const IS_SCRIPT_OR_DATA = seal(/^(?:\w+script|data):/i);
  const ATTR_WHITESPACE = seal(
    /[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g
    // eslint-disable-line no-control-regex
  );
  const DOCTYPE_NAME = seal(/^html$/i);
  const CUSTOM_ELEMENT = seal(/^[a-z][.\w]*(-[.\w]+)+$/i);
  var EXPRESSIONS = /* @__PURE__ */ Object.freeze({
    __proto__: null,
    ARIA_ATTR,
    ATTR_WHITESPACE,
    CUSTOM_ELEMENT,
    DATA_ATTR,
    DOCTYPE_NAME,
    ERB_EXPR,
    IS_ALLOWED_URI,
    IS_SCRIPT_OR_DATA,
    MUSTACHE_EXPR,
    TMPLIT_EXPR
  });
  const NODE_TYPE = {
    element: 1,
    text: 3,
    // Deprecated
    progressingInstruction: 7,
    comment: 8,
    document: 9
  };
  const getGlobal = function getGlobal2() {
    return typeof window === "undefined" ? null : window;
  };
  const _createTrustedTypesPolicy = function _createTrustedTypesPolicy2(trustedTypes, purifyHostElement) {
    if (typeof trustedTypes !== "object" || typeof trustedTypes.createPolicy !== "function") {
      return null;
    }
    let suffix = null;
    const ATTR_NAME = "data-tt-policy-suffix";
    if (purifyHostElement && purifyHostElement.hasAttribute(ATTR_NAME)) {
      suffix = purifyHostElement.getAttribute(ATTR_NAME);
    }
    const policyName = "dompurify" + (suffix ? "#" + suffix : "");
    try {
      return trustedTypes.createPolicy(policyName, {
        createHTML(html2) {
          return html2;
        },
        createScriptURL(scriptUrl) {
          return scriptUrl;
        }
      });
    } catch (_) {
      console.warn("TrustedTypes policy " + policyName + " could not be created.");
      return null;
    }
  };
  const _createHooksMap = function _createHooksMap2() {
    return {
      afterSanitizeAttributes: [],
      afterSanitizeElements: [],
      afterSanitizeShadowDOM: [],
      beforeSanitizeAttributes: [],
      beforeSanitizeElements: [],
      beforeSanitizeShadowDOM: [],
      uponSanitizeAttribute: [],
      uponSanitizeElement: [],
      uponSanitizeShadowNode: []
    };
  };
  function createDOMPurify() {
    let window2 = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : getGlobal();
    const DOMPurify = (root) => createDOMPurify(root);
    DOMPurify.version = "3.2.7";
    DOMPurify.removed = [];
    if (!window2 || !window2.document || window2.document.nodeType !== NODE_TYPE.document || !window2.Element) {
      DOMPurify.isSupported = false;
      return DOMPurify;
    }
    let {
      document: document2
    } = window2;
    const originalDocument = document2;
    const currentScript = originalDocument.currentScript;
    const {
      DocumentFragment,
      HTMLTemplateElement,
      Node: Node2,
      Element: Element2,
      NodeFilter,
      NamedNodeMap = window2.NamedNodeMap || window2.MozNamedAttrMap,
      HTMLFormElement,
      DOMParser,
      trustedTypes
    } = window2;
    const ElementPrototype = Element2.prototype;
    const cloneNode = lookupGetter(ElementPrototype, "cloneNode");
    const remove = lookupGetter(ElementPrototype, "remove");
    const getNextSibling = lookupGetter(ElementPrototype, "nextSibling");
    const getChildNodes = lookupGetter(ElementPrototype, "childNodes");
    const getParentNode = lookupGetter(ElementPrototype, "parentNode");
    if (typeof HTMLTemplateElement === "function") {
      const template = document2.createElement("template");
      if (template.content && template.content.ownerDocument) {
        document2 = template.content.ownerDocument;
      }
    }
    let trustedTypesPolicy;
    let emptyHTML = "";
    const {
      implementation,
      createNodeIterator,
      createDocumentFragment,
      getElementsByTagName
    } = document2;
    const {
      importNode
    } = originalDocument;
    let hooks = _createHooksMap();
    DOMPurify.isSupported = typeof entries === "function" && typeof getParentNode === "function" && implementation && implementation.createHTMLDocument !== void 0;
    const {
      MUSTACHE_EXPR: MUSTACHE_EXPR2,
      ERB_EXPR: ERB_EXPR2,
      TMPLIT_EXPR: TMPLIT_EXPR2,
      DATA_ATTR: DATA_ATTR2,
      ARIA_ATTR: ARIA_ATTR2,
      IS_SCRIPT_OR_DATA: IS_SCRIPT_OR_DATA2,
      ATTR_WHITESPACE: ATTR_WHITESPACE2,
      CUSTOM_ELEMENT: CUSTOM_ELEMENT2
    } = EXPRESSIONS;
    let {
      IS_ALLOWED_URI: IS_ALLOWED_URI$1
    } = EXPRESSIONS;
    let ALLOWED_TAGS = null;
    const DEFAULT_ALLOWED_TAGS = addToSet({}, [...html$1, ...svg$1, ...svgFilters, ...mathMl$1, ...text]);
    let ALLOWED_ATTR = null;
    const DEFAULT_ALLOWED_ATTR = addToSet({}, [...html, ...svg, ...mathMl, ...xml]);
    let CUSTOM_ELEMENT_HANDLING = Object.seal(create$1(null, {
      tagNameCheck: {
        writable: true,
        configurable: false,
        enumerable: true,
        value: null
      },
      attributeNameCheck: {
        writable: true,
        configurable: false,
        enumerable: true,
        value: null
      },
      allowCustomizedBuiltInElements: {
        writable: true,
        configurable: false,
        enumerable: true,
        value: false
      }
    }));
    let FORBID_TAGS = null;
    let FORBID_ATTR = null;
    let ALLOW_ARIA_ATTR = true;
    let ALLOW_DATA_ATTR = true;
    let ALLOW_UNKNOWN_PROTOCOLS = false;
    let ALLOW_SELF_CLOSE_IN_ATTR = true;
    let SAFE_FOR_TEMPLATES = false;
    let SAFE_FOR_XML = true;
    let WHOLE_DOCUMENT = false;
    let SET_CONFIG = false;
    let FORCE_BODY = false;
    let RETURN_DOM = false;
    let RETURN_DOM_FRAGMENT = false;
    let RETURN_TRUSTED_TYPE = false;
    let SANITIZE_DOM = true;
    let SANITIZE_NAMED_PROPS = false;
    const SANITIZE_NAMED_PROPS_PREFIX = "user-content-";
    let KEEP_CONTENT = true;
    let IN_PLACE = false;
    let USE_PROFILES = {};
    let FORBID_CONTENTS = null;
    const DEFAULT_FORBID_CONTENTS = addToSet({}, ["annotation-xml", "audio", "colgroup", "desc", "foreignobject", "head", "iframe", "math", "mi", "mn", "mo", "ms", "mtext", "noembed", "noframes", "noscript", "plaintext", "script", "style", "svg", "template", "thead", "title", "video", "xmp"]);
    let DATA_URI_TAGS = null;
    const DEFAULT_DATA_URI_TAGS = addToSet({}, ["audio", "video", "img", "source", "image", "track"]);
    let URI_SAFE_ATTRIBUTES = null;
    const DEFAULT_URI_SAFE_ATTRIBUTES = addToSet({}, ["alt", "class", "for", "id", "label", "name", "pattern", "placeholder", "role", "summary", "title", "value", "style", "xmlns"]);
    const MATHML_NAMESPACE = "http://www.w3.org/1998/Math/MathML";
    const SVG_NAMESPACE = "http://www.w3.org/2000/svg";
    const HTML_NAMESPACE = "http://www.w3.org/1999/xhtml";
    let NAMESPACE = HTML_NAMESPACE;
    let IS_EMPTY_INPUT = false;
    let ALLOWED_NAMESPACES = null;
    const DEFAULT_ALLOWED_NAMESPACES = addToSet({}, [MATHML_NAMESPACE, SVG_NAMESPACE, HTML_NAMESPACE], stringToString);
    let MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, ["mi", "mo", "mn", "ms", "mtext"]);
    let HTML_INTEGRATION_POINTS = addToSet({}, ["annotation-xml"]);
    const COMMON_SVG_AND_HTML_ELEMENTS = addToSet({}, ["title", "style", "font", "a", "script"]);
    let PARSER_MEDIA_TYPE = null;
    const SUPPORTED_PARSER_MEDIA_TYPES = ["application/xhtml+xml", "text/html"];
    const DEFAULT_PARSER_MEDIA_TYPE = "text/html";
    let transformCaseFunc = null;
    let CONFIG = null;
    const formElement = document2.createElement("form");
    const isRegexOrFunction = function isRegexOrFunction2(testValue) {
      return testValue instanceof RegExp || testValue instanceof Function;
    };
    const _parseConfig = function _parseConfig2() {
      let cfg = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
      if (CONFIG && CONFIG === cfg) {
        return;
      }
      if (!cfg || typeof cfg !== "object") {
        cfg = {};
      }
      cfg = clone(cfg);
      PARSER_MEDIA_TYPE = // eslint-disable-next-line unicorn/prefer-includes
      SUPPORTED_PARSER_MEDIA_TYPES.indexOf(cfg.PARSER_MEDIA_TYPE) === -1 ? DEFAULT_PARSER_MEDIA_TYPE : cfg.PARSER_MEDIA_TYPE;
      transformCaseFunc = PARSER_MEDIA_TYPE === "application/xhtml+xml" ? stringToString : stringToLowerCase;
      ALLOWED_TAGS = objectHasOwnProperty(cfg, "ALLOWED_TAGS") ? addToSet({}, cfg.ALLOWED_TAGS, transformCaseFunc) : DEFAULT_ALLOWED_TAGS;
      ALLOWED_ATTR = objectHasOwnProperty(cfg, "ALLOWED_ATTR") ? addToSet({}, cfg.ALLOWED_ATTR, transformCaseFunc) : DEFAULT_ALLOWED_ATTR;
      ALLOWED_NAMESPACES = objectHasOwnProperty(cfg, "ALLOWED_NAMESPACES") ? addToSet({}, cfg.ALLOWED_NAMESPACES, stringToString) : DEFAULT_ALLOWED_NAMESPACES;
      URI_SAFE_ATTRIBUTES = objectHasOwnProperty(cfg, "ADD_URI_SAFE_ATTR") ? addToSet(clone(DEFAULT_URI_SAFE_ATTRIBUTES), cfg.ADD_URI_SAFE_ATTR, transformCaseFunc) : DEFAULT_URI_SAFE_ATTRIBUTES;
      DATA_URI_TAGS = objectHasOwnProperty(cfg, "ADD_DATA_URI_TAGS") ? addToSet(clone(DEFAULT_DATA_URI_TAGS), cfg.ADD_DATA_URI_TAGS, transformCaseFunc) : DEFAULT_DATA_URI_TAGS;
      FORBID_CONTENTS = objectHasOwnProperty(cfg, "FORBID_CONTENTS") ? addToSet({}, cfg.FORBID_CONTENTS, transformCaseFunc) : DEFAULT_FORBID_CONTENTS;
      FORBID_TAGS = objectHasOwnProperty(cfg, "FORBID_TAGS") ? addToSet({}, cfg.FORBID_TAGS, transformCaseFunc) : clone({});
      FORBID_ATTR = objectHasOwnProperty(cfg, "FORBID_ATTR") ? addToSet({}, cfg.FORBID_ATTR, transformCaseFunc) : clone({});
      USE_PROFILES = objectHasOwnProperty(cfg, "USE_PROFILES") ? cfg.USE_PROFILES : false;
      ALLOW_ARIA_ATTR = cfg.ALLOW_ARIA_ATTR !== false;
      ALLOW_DATA_ATTR = cfg.ALLOW_DATA_ATTR !== false;
      ALLOW_UNKNOWN_PROTOCOLS = cfg.ALLOW_UNKNOWN_PROTOCOLS || false;
      ALLOW_SELF_CLOSE_IN_ATTR = cfg.ALLOW_SELF_CLOSE_IN_ATTR !== false;
      SAFE_FOR_TEMPLATES = cfg.SAFE_FOR_TEMPLATES || false;
      SAFE_FOR_XML = cfg.SAFE_FOR_XML !== false;
      WHOLE_DOCUMENT = cfg.WHOLE_DOCUMENT || false;
      RETURN_DOM = cfg.RETURN_DOM || false;
      RETURN_DOM_FRAGMENT = cfg.RETURN_DOM_FRAGMENT || false;
      RETURN_TRUSTED_TYPE = cfg.RETURN_TRUSTED_TYPE || false;
      FORCE_BODY = cfg.FORCE_BODY || false;
      SANITIZE_DOM = cfg.SANITIZE_DOM !== false;
      SANITIZE_NAMED_PROPS = cfg.SANITIZE_NAMED_PROPS || false;
      KEEP_CONTENT = cfg.KEEP_CONTENT !== false;
      IN_PLACE = cfg.IN_PLACE || false;
      IS_ALLOWED_URI$1 = cfg.ALLOWED_URI_REGEXP || IS_ALLOWED_URI;
      NAMESPACE = cfg.NAMESPACE || HTML_NAMESPACE;
      MATHML_TEXT_INTEGRATION_POINTS = cfg.MATHML_TEXT_INTEGRATION_POINTS || MATHML_TEXT_INTEGRATION_POINTS;
      HTML_INTEGRATION_POINTS = cfg.HTML_INTEGRATION_POINTS || HTML_INTEGRATION_POINTS;
      CUSTOM_ELEMENT_HANDLING = cfg.CUSTOM_ELEMENT_HANDLING || {};
      if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck)) {
        CUSTOM_ELEMENT_HANDLING.tagNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck;
      }
      if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)) {
        CUSTOM_ELEMENT_HANDLING.attributeNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck;
      }
      if (cfg.CUSTOM_ELEMENT_HANDLING && typeof cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements === "boolean") {
        CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements = cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements;
      }
      if (SAFE_FOR_TEMPLATES) {
        ALLOW_DATA_ATTR = false;
      }
      if (RETURN_DOM_FRAGMENT) {
        RETURN_DOM = true;
      }
      if (USE_PROFILES) {
        ALLOWED_TAGS = addToSet({}, text);
        ALLOWED_ATTR = [];
        if (USE_PROFILES.html === true) {
          addToSet(ALLOWED_TAGS, html$1);
          addToSet(ALLOWED_ATTR, html);
        }
        if (USE_PROFILES.svg === true) {
          addToSet(ALLOWED_TAGS, svg$1);
          addToSet(ALLOWED_ATTR, svg);
          addToSet(ALLOWED_ATTR, xml);
        }
        if (USE_PROFILES.svgFilters === true) {
          addToSet(ALLOWED_TAGS, svgFilters);
          addToSet(ALLOWED_ATTR, svg);
          addToSet(ALLOWED_ATTR, xml);
        }
        if (USE_PROFILES.mathMl === true) {
          addToSet(ALLOWED_TAGS, mathMl$1);
          addToSet(ALLOWED_ATTR, mathMl);
          addToSet(ALLOWED_ATTR, xml);
        }
      }
      if (cfg.ADD_TAGS) {
        if (ALLOWED_TAGS === DEFAULT_ALLOWED_TAGS) {
          ALLOWED_TAGS = clone(ALLOWED_TAGS);
        }
        addToSet(ALLOWED_TAGS, cfg.ADD_TAGS, transformCaseFunc);
      }
      if (cfg.ADD_ATTR) {
        if (ALLOWED_ATTR === DEFAULT_ALLOWED_ATTR) {
          ALLOWED_ATTR = clone(ALLOWED_ATTR);
        }
        addToSet(ALLOWED_ATTR, cfg.ADD_ATTR, transformCaseFunc);
      }
      if (cfg.ADD_URI_SAFE_ATTR) {
        addToSet(URI_SAFE_ATTRIBUTES, cfg.ADD_URI_SAFE_ATTR, transformCaseFunc);
      }
      if (cfg.FORBID_CONTENTS) {
        if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {
          FORBID_CONTENTS = clone(FORBID_CONTENTS);
        }
        addToSet(FORBID_CONTENTS, cfg.FORBID_CONTENTS, transformCaseFunc);
      }
      if (KEEP_CONTENT) {
        ALLOWED_TAGS["#text"] = true;
      }
      if (WHOLE_DOCUMENT) {
        addToSet(ALLOWED_TAGS, ["html", "head", "body"]);
      }
      if (ALLOWED_TAGS.table) {
        addToSet(ALLOWED_TAGS, ["tbody"]);
        delete FORBID_TAGS.tbody;
      }
      if (cfg.TRUSTED_TYPES_POLICY) {
        if (typeof cfg.TRUSTED_TYPES_POLICY.createHTML !== "function") {
          throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');
        }
        if (typeof cfg.TRUSTED_TYPES_POLICY.createScriptURL !== "function") {
          throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');
        }
        trustedTypesPolicy = cfg.TRUSTED_TYPES_POLICY;
        emptyHTML = trustedTypesPolicy.createHTML("");
      } else {
        if (trustedTypesPolicy === void 0) {
          trustedTypesPolicy = _createTrustedTypesPolicy(trustedTypes, currentScript);
        }
        if (trustedTypesPolicy !== null && typeof emptyHTML === "string") {
          emptyHTML = trustedTypesPolicy.createHTML("");
        }
      }
      if (freeze$1) {
        freeze$1(cfg);
      }
      CONFIG = cfg;
    };
    const ALL_SVG_TAGS = addToSet({}, [...svg$1, ...svgFilters, ...svgDisallowed]);
    const ALL_MATHML_TAGS = addToSet({}, [...mathMl$1, ...mathMlDisallowed]);
    const _checkValidNamespace = function _checkValidNamespace2(element) {
      let parent = getParentNode(element);
      if (!parent || !parent.tagName) {
        parent = {
          namespaceURI: NAMESPACE,
          tagName: "template"
        };
      }
      const tagName = stringToLowerCase(element.tagName);
      const parentTagName = stringToLowerCase(parent.tagName);
      if (!ALLOWED_NAMESPACES[element.namespaceURI]) {
        return false;
      }
      if (element.namespaceURI === SVG_NAMESPACE) {
        if (parent.namespaceURI === HTML_NAMESPACE) {
          return tagName === "svg";
        }
        if (parent.namespaceURI === MATHML_NAMESPACE) {
          return tagName === "svg" && (parentTagName === "annotation-xml" || MATHML_TEXT_INTEGRATION_POINTS[parentTagName]);
        }
        return Boolean(ALL_SVG_TAGS[tagName]);
      }
      if (element.namespaceURI === MATHML_NAMESPACE) {
        if (parent.namespaceURI === HTML_NAMESPACE) {
          return tagName === "math";
        }
        if (parent.namespaceURI === SVG_NAMESPACE) {
          return tagName === "math" && HTML_INTEGRATION_POINTS[parentTagName];
        }
        return Boolean(ALL_MATHML_TAGS[tagName]);
      }
      if (element.namespaceURI === HTML_NAMESPACE) {
        if (parent.namespaceURI === SVG_NAMESPACE && !HTML_INTEGRATION_POINTS[parentTagName]) {
          return false;
        }
        if (parent.namespaceURI === MATHML_NAMESPACE && !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]) {
          return false;
        }
        return !ALL_MATHML_TAGS[tagName] && (COMMON_SVG_AND_HTML_ELEMENTS[tagName] || !ALL_SVG_TAGS[tagName]);
      }
      if (PARSER_MEDIA_TYPE === "application/xhtml+xml" && ALLOWED_NAMESPACES[element.namespaceURI]) {
        return true;
      }
      return false;
    };
    const _forceRemove = function _forceRemove2(node) {
      arrayPush(DOMPurify.removed, {
        element: node
      });
      try {
        getParentNode(node).removeChild(node);
      } catch (_) {
        remove(node);
      }
    };
    const _removeAttribute = function _removeAttribute2(name, element) {
      try {
        arrayPush(DOMPurify.removed, {
          attribute: element.getAttributeNode(name),
          from: element
        });
      } catch (_) {
        arrayPush(DOMPurify.removed, {
          attribute: null,
          from: element
        });
      }
      element.removeAttribute(name);
      if (name === "is") {
        if (RETURN_DOM || RETURN_DOM_FRAGMENT) {
          try {
            _forceRemove(element);
          } catch (_) {
          }
        } else {
          try {
            element.setAttribute(name, "");
          } catch (_) {
          }
        }
      }
    };
    const _initDocument = function _initDocument2(dirty) {
      let doc = null;
      let leadingWhitespace = null;
      if (FORCE_BODY) {
        dirty = "<remove></remove>" + dirty;
      } else {
        const matches = stringMatch(dirty, /^[\r\n\t ]+/);
        leadingWhitespace = matches && matches[0];
      }
      if (PARSER_MEDIA_TYPE === "application/xhtml+xml" && NAMESPACE === HTML_NAMESPACE) {
        dirty = '<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>' + dirty + "</body></html>";
      }
      const dirtyPayload = trustedTypesPolicy ? trustedTypesPolicy.createHTML(dirty) : dirty;
      if (NAMESPACE === HTML_NAMESPACE) {
        try {
          doc = new DOMParser().parseFromString(dirtyPayload, PARSER_MEDIA_TYPE);
        } catch (_) {
        }
      }
      if (!doc || !doc.documentElement) {
        doc = implementation.createDocument(NAMESPACE, "template", null);
        try {
          doc.documentElement.innerHTML = IS_EMPTY_INPUT ? emptyHTML : dirtyPayload;
        } catch (_) {
        }
      }
      const body = doc.body || doc.documentElement;
      if (dirty && leadingWhitespace) {
        body.insertBefore(document2.createTextNode(leadingWhitespace), body.childNodes[0] || null);
      }
      if (NAMESPACE === HTML_NAMESPACE) {
        return getElementsByTagName.call(doc, WHOLE_DOCUMENT ? "html" : "body")[0];
      }
      return WHOLE_DOCUMENT ? doc.documentElement : body;
    };
    const _createNodeIterator = function _createNodeIterator2(root) {
      return createNodeIterator.call(
        root.ownerDocument || root,
        root,
        // eslint-disable-next-line no-bitwise
        NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_TEXT | NodeFilter.SHOW_PROCESSING_INSTRUCTION | NodeFilter.SHOW_CDATA_SECTION,
        null
      );
    };
    const _isClobbered = function _isClobbered2(element) {
      return element instanceof HTMLFormElement && (typeof element.nodeName !== "string" || typeof element.textContent !== "string" || typeof element.removeChild !== "function" || !(element.attributes instanceof NamedNodeMap) || typeof element.removeAttribute !== "function" || typeof element.setAttribute !== "function" || typeof element.namespaceURI !== "string" || typeof element.insertBefore !== "function" || typeof element.hasChildNodes !== "function");
    };
    const _isNode = function _isNode2(value) {
      return typeof Node2 === "function" && value instanceof Node2;
    };
    function _executeHooks(hooks2, currentNode, data) {
      arrayForEach(hooks2, (hook) => {
        hook.call(DOMPurify, currentNode, data, CONFIG);
      });
    }
    const _sanitizeElements = function _sanitizeElements2(currentNode) {
      let content = null;
      _executeHooks(hooks.beforeSanitizeElements, currentNode, null);
      if (_isClobbered(currentNode)) {
        _forceRemove(currentNode);
        return true;
      }
      const tagName = transformCaseFunc(currentNode.nodeName);
      _executeHooks(hooks.uponSanitizeElement, currentNode, {
        tagName,
        allowedTags: ALLOWED_TAGS
      });
      if (SAFE_FOR_XML && currentNode.hasChildNodes() && !_isNode(currentNode.firstElementChild) && regExpTest(/<[/\w!]/g, currentNode.innerHTML) && regExpTest(/<[/\w!]/g, currentNode.textContent)) {
        _forceRemove(currentNode);
        return true;
      }
      if (currentNode.nodeType === NODE_TYPE.progressingInstruction) {
        _forceRemove(currentNode);
        return true;
      }
      if (SAFE_FOR_XML && currentNode.nodeType === NODE_TYPE.comment && regExpTest(/<[/\w]/g, currentNode.data)) {
        _forceRemove(currentNode);
        return true;
      }
      if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {
        if (!FORBID_TAGS[tagName] && _isBasicCustomElement(tagName)) {
          if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, tagName)) {
            return false;
          }
          if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(tagName)) {
            return false;
          }
        }
        if (KEEP_CONTENT && !FORBID_CONTENTS[tagName]) {
          const parentNode = getParentNode(currentNode) || currentNode.parentNode;
          const childNodes = getChildNodes(currentNode) || currentNode.childNodes;
          if (childNodes && parentNode) {
            const childCount = childNodes.length;
            for (let i2 = childCount - 1; i2 >= 0; --i2) {
              const childClone = cloneNode(childNodes[i2], true);
              childClone.__removalCount = (currentNode.__removalCount || 0) + 1;
              parentNode.insertBefore(childClone, getNextSibling(currentNode));
            }
          }
        }
        _forceRemove(currentNode);
        return true;
      }
      if (currentNode instanceof Element2 && !_checkValidNamespace(currentNode)) {
        _forceRemove(currentNode);
        return true;
      }
      if ((tagName === "noscript" || tagName === "noembed" || tagName === "noframes") && regExpTest(/<\/no(script|embed|frames)/i, currentNode.innerHTML)) {
        _forceRemove(currentNode);
        return true;
      }
      if (SAFE_FOR_TEMPLATES && currentNode.nodeType === NODE_TYPE.text) {
        content = currentNode.textContent;
        arrayForEach([MUSTACHE_EXPR2, ERB_EXPR2, TMPLIT_EXPR2], (expr) => {
          content = stringReplace(content, expr, " ");
        });
        if (currentNode.textContent !== content) {
          arrayPush(DOMPurify.removed, {
            element: currentNode.cloneNode()
          });
          currentNode.textContent = content;
        }
      }
      _executeHooks(hooks.afterSanitizeElements, currentNode, null);
      return false;
    };
    const _isValidAttribute = function _isValidAttribute2(lcTag, lcName, value) {
      if (SANITIZE_DOM && (lcName === "id" || lcName === "name") && (value in document2 || value in formElement)) {
        return false;
      }
      if (ALLOW_DATA_ATTR && !FORBID_ATTR[lcName] && regExpTest(DATA_ATTR2, lcName)) ;
      else if (ALLOW_ARIA_ATTR && regExpTest(ARIA_ATTR2, lcName)) ;
      else if (!ALLOWED_ATTR[lcName] || FORBID_ATTR[lcName]) {
        if (
          // First condition does a very basic check if a) it's basically a valid custom element tagname AND
          // b) if the tagName passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck
          // and c) if the attribute name passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.attributeNameCheck
          _isBasicCustomElement(lcTag) && (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, lcTag) || CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(lcTag)) && (CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.attributeNameCheck, lcName) || CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.attributeNameCheck(lcName, lcTag)) || // Alternative, second condition checks if it's an `is`-attribute, AND
          // the value passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck
          lcName === "is" && CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements && (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, value) || CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(value))
        ) ;
        else {
          return false;
        }
      } else if (URI_SAFE_ATTRIBUTES[lcName]) ;
      else if (regExpTest(IS_ALLOWED_URI$1, stringReplace(value, ATTR_WHITESPACE2, ""))) ;
      else if ((lcName === "src" || lcName === "xlink:href" || lcName === "href") && lcTag !== "script" && stringIndexOf(value, "data:") === 0 && DATA_URI_TAGS[lcTag]) ;
      else if (ALLOW_UNKNOWN_PROTOCOLS && !regExpTest(IS_SCRIPT_OR_DATA2, stringReplace(value, ATTR_WHITESPACE2, ""))) ;
      else if (value) {
        return false;
      } else ;
      return true;
    };
    const _isBasicCustomElement = function _isBasicCustomElement2(tagName) {
      return tagName !== "annotation-xml" && stringMatch(tagName, CUSTOM_ELEMENT2);
    };
    const _sanitizeAttributes = function _sanitizeAttributes2(currentNode) {
      _executeHooks(hooks.beforeSanitizeAttributes, currentNode, null);
      const {
        attributes
      } = currentNode;
      if (!attributes || _isClobbered(currentNode)) {
        return;
      }
      const hookEvent = {
        attrName: "",
        attrValue: "",
        keepAttr: true,
        allowedAttributes: ALLOWED_ATTR,
        forceKeepAttr: void 0
      };
      let l = attributes.length;
      while (l--) {
        const attr = attributes[l];
        const {
          name,
          namespaceURI,
          value: attrValue
        } = attr;
        const lcName = transformCaseFunc(name);
        const initValue = attrValue;
        let value = name === "value" ? initValue : stringTrim(initValue);
        hookEvent.attrName = lcName;
        hookEvent.attrValue = value;
        hookEvent.keepAttr = true;
        hookEvent.forceKeepAttr = void 0;
        _executeHooks(hooks.uponSanitizeAttribute, currentNode, hookEvent);
        value = hookEvent.attrValue;
        if (SANITIZE_NAMED_PROPS && (lcName === "id" || lcName === "name")) {
          _removeAttribute(name, currentNode);
          value = SANITIZE_NAMED_PROPS_PREFIX + value;
        }
        if (SAFE_FOR_XML && regExpTest(/((--!?|])>)|<\/(style|title|textarea)/i, value)) {
          _removeAttribute(name, currentNode);
          continue;
        }
        if (lcName === "attributename" && stringMatch(value, "href")) {
          _removeAttribute(name, currentNode);
          continue;
        }
        if (hookEvent.forceKeepAttr) {
          continue;
        }
        if (!hookEvent.keepAttr) {
          _removeAttribute(name, currentNode);
          continue;
        }
        if (!ALLOW_SELF_CLOSE_IN_ATTR && regExpTest(/\/>/i, value)) {
          _removeAttribute(name, currentNode);
          continue;
        }
        if (SAFE_FOR_TEMPLATES) {
          arrayForEach([MUSTACHE_EXPR2, ERB_EXPR2, TMPLIT_EXPR2], (expr) => {
            value = stringReplace(value, expr, " ");
          });
        }
        const lcTag = transformCaseFunc(currentNode.nodeName);
        if (!_isValidAttribute(lcTag, lcName, value)) {
          _removeAttribute(name, currentNode);
          continue;
        }
        if (trustedTypesPolicy && typeof trustedTypes === "object" && typeof trustedTypes.getAttributeType === "function") {
          if (namespaceURI) ;
          else {
            switch (trustedTypes.getAttributeType(lcTag, lcName)) {
              case "TrustedHTML": {
                value = trustedTypesPolicy.createHTML(value);
                break;
              }
              case "TrustedScriptURL": {
                value = trustedTypesPolicy.createScriptURL(value);
                break;
              }
            }
          }
        }
        if (value !== initValue) {
          try {
            if (namespaceURI) {
              currentNode.setAttributeNS(namespaceURI, name, value);
            } else {
              currentNode.setAttribute(name, value);
            }
            if (_isClobbered(currentNode)) {
              _forceRemove(currentNode);
            } else {
              arrayPop(DOMPurify.removed);
            }
          } catch (_) {
            _removeAttribute(name, currentNode);
          }
        }
      }
      _executeHooks(hooks.afterSanitizeAttributes, currentNode, null);
    };
    const _sanitizeShadowDOM = function _sanitizeShadowDOM2(fragment) {
      let shadowNode = null;
      const shadowIterator = _createNodeIterator(fragment);
      _executeHooks(hooks.beforeSanitizeShadowDOM, fragment, null);
      while (shadowNode = shadowIterator.nextNode()) {
        _executeHooks(hooks.uponSanitizeShadowNode, shadowNode, null);
        _sanitizeElements(shadowNode);
        _sanitizeAttributes(shadowNode);
        if (shadowNode.content instanceof DocumentFragment) {
          _sanitizeShadowDOM2(shadowNode.content);
        }
      }
      _executeHooks(hooks.afterSanitizeShadowDOM, fragment, null);
    };
    DOMPurify.sanitize = function(dirty) {
      let cfg = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
      let body = null;
      let importedNode = null;
      let currentNode = null;
      let returnNode = null;
      IS_EMPTY_INPUT = !dirty;
      if (IS_EMPTY_INPUT) {
        dirty = "<!-->";
      }
      if (typeof dirty !== "string" && !_isNode(dirty)) {
        if (typeof dirty.toString === "function") {
          dirty = dirty.toString();
          if (typeof dirty !== "string") {
            throw typeErrorCreate("dirty is not a string, aborting");
          }
        } else {
          throw typeErrorCreate("toString is not a function");
        }
      }
      if (!DOMPurify.isSupported) {
        return dirty;
      }
      if (!SET_CONFIG) {
        _parseConfig(cfg);
      }
      DOMPurify.removed = [];
      if (typeof dirty === "string") {
        IN_PLACE = false;
      }
      if (IN_PLACE) {
        if (dirty.nodeName) {
          const tagName = transformCaseFunc(dirty.nodeName);
          if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {
            throw typeErrorCreate("root node is forbidden and cannot be sanitized in-place");
          }
        }
      } else if (dirty instanceof Node2) {
        body = _initDocument("<!---->");
        importedNode = body.ownerDocument.importNode(dirty, true);
        if (importedNode.nodeType === NODE_TYPE.element && importedNode.nodeName === "BODY") {
          body = importedNode;
        } else if (importedNode.nodeName === "HTML") {
          body = importedNode;
        } else {
          body.appendChild(importedNode);
        }
      } else {
        if (!RETURN_DOM && !SAFE_FOR_TEMPLATES && !WHOLE_DOCUMENT && // eslint-disable-next-line unicorn/prefer-includes
        dirty.indexOf("<") === -1) {
          return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(dirty) : dirty;
        }
        body = _initDocument(dirty);
        if (!body) {
          return RETURN_DOM ? null : RETURN_TRUSTED_TYPE ? emptyHTML : "";
        }
      }
      if (body && FORCE_BODY) {
        _forceRemove(body.firstChild);
      }
      const nodeIterator = _createNodeIterator(IN_PLACE ? dirty : body);
      while (currentNode = nodeIterator.nextNode()) {
        _sanitizeElements(currentNode);
        _sanitizeAttributes(currentNode);
        if (currentNode.content instanceof DocumentFragment) {
          _sanitizeShadowDOM(currentNode.content);
        }
      }
      if (IN_PLACE) {
        return dirty;
      }
      if (RETURN_DOM) {
        if (RETURN_DOM_FRAGMENT) {
          returnNode = createDocumentFragment.call(body.ownerDocument);
          while (body.firstChild) {
            returnNode.appendChild(body.firstChild);
          }
        } else {
          returnNode = body;
        }
        if (ALLOWED_ATTR.shadowroot || ALLOWED_ATTR.shadowrootmode) {
          returnNode = importNode.call(originalDocument, returnNode, true);
        }
        return returnNode;
      }
      let serializedHTML = WHOLE_DOCUMENT ? body.outerHTML : body.innerHTML;
      if (WHOLE_DOCUMENT && ALLOWED_TAGS["!doctype"] && body.ownerDocument && body.ownerDocument.doctype && body.ownerDocument.doctype.name && regExpTest(DOCTYPE_NAME, body.ownerDocument.doctype.name)) {
        serializedHTML = "<!DOCTYPE " + body.ownerDocument.doctype.name + ">\n" + serializedHTML;
      }
      if (SAFE_FOR_TEMPLATES) {
        arrayForEach([MUSTACHE_EXPR2, ERB_EXPR2, TMPLIT_EXPR2], (expr) => {
          serializedHTML = stringReplace(serializedHTML, expr, " ");
        });
      }
      return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(serializedHTML) : serializedHTML;
    };
    DOMPurify.setConfig = function() {
      let cfg = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
      _parseConfig(cfg);
      SET_CONFIG = true;
    };
    DOMPurify.clearConfig = function() {
      CONFIG = null;
      SET_CONFIG = false;
    };
    DOMPurify.isValidAttribute = function(tag2, attr, value) {
      if (!CONFIG) {
        _parseConfig({});
      }
      const lcTag = transformCaseFunc(tag2);
      const lcName = transformCaseFunc(attr);
      return _isValidAttribute(lcTag, lcName, value);
    };
    DOMPurify.addHook = function(entryPoint, hookFunction) {
      if (typeof hookFunction !== "function") {
        return;
      }
      arrayPush(hooks[entryPoint], hookFunction);
    };
    DOMPurify.removeHook = function(entryPoint, hookFunction) {
      if (hookFunction !== void 0) {
        const index = arrayLastIndexOf(hooks[entryPoint], hookFunction);
        return index === -1 ? void 0 : arraySplice(hooks[entryPoint], index, 1)[0];
      }
      return arrayPop(hooks[entryPoint]);
    };
    DOMPurify.removeHooks = function(entryPoint) {
      hooks[entryPoint] = [];
    };
    DOMPurify.removeAllHooks = function() {
      hooks = _createHooksMap();
    };
    return DOMPurify;
  }
  var purify = createDOMPurify();
  const basicMarkupHtmlTags = Object.freeze([
    "a",
    "abbr",
    "b",
    "bdo",
    "blockquote",
    "br",
    "caption",
    "cite",
    "code",
    "col",
    "colgroup",
    "dd",
    "del",
    "details",
    "dfn",
    "div",
    "dl",
    "dt",
    "em",
    "figcaption",
    "figure",
    "h1",
    "h2",
    "h3",
    "h4",
    "h5",
    "h6",
    "hr",
    "i",
    "img",
    "ins",
    "kbd",
    "label",
    "li",
    "mark",
    "ol",
    "p",
    "pre",
    "q",
    "rp",
    "rt",
    "ruby",
    "s",
    "samp",
    "small",
    "small",
    "source",
    "span",
    "strike",
    "strong",
    "sub",
    "summary",
    "sup",
    "table",
    "tbody",
    "td",
    "tfoot",
    "th",
    "thead",
    "time",
    "tr",
    "tt",
    "u",
    "ul",
    "var",
    "video",
    "wbr"
  ]);
  const defaultAllowedAttrs = Object.freeze([
    "href",
    "target",
    "src",
    "alt",
    "title",
    "for",
    "name",
    "role",
    "tabindex",
    "x-dispatch",
    "required",
    "checked",
    "placeholder",
    "type",
    "start",
    "width",
    "height",
    "align"
  ]);
  const fakeRelativeUrlProtocol = "vscode-relative-path";
  function validateLink(value, allowedProtocols) {
    if (allowedProtocols.override === "*") {
      return true;
    }
    try {
      const url = new URL(value, fakeRelativeUrlProtocol + "://");
      if (allowedProtocols.override.includes(url.protocol.replace(/:$/, ""))) {
        return true;
      }
      if (allowedProtocols.allowRelativePaths && url.protocol === fakeRelativeUrlProtocol + ":" && !value.trim().toLowerCase().startsWith(fakeRelativeUrlProtocol)) {
        return true;
      }
      return false;
    } catch (e) {
      return false;
    }
  }
  function hookDomPurifyHrefAndSrcSanitizer(allowedLinkProtocols, allowedMediaProtocols) {
    purify.addHook("afterSanitizeAttributes", (node) => {
      for (const attr of ["href", "src"]) {
        if (node.hasAttribute(attr)) {
          const attrValue = node.getAttribute(attr);
          if (attr === "href") {
            if (!attrValue.startsWith("#") && !validateLink(attrValue, allowedLinkProtocols)) {
              node.removeAttribute(attr);
            }
          } else {
            if (!validateLink(attrValue, allowedMediaProtocols)) {
              node.removeAttribute(attr);
            }
          }
        }
      }
    });
  }
  const defaultDomPurifyConfig = Object.freeze({
    ALLOWED_TAGS: [...basicMarkupHtmlTags],
    ALLOWED_ATTR: [...defaultAllowedAttrs],
    // We sanitize the src/href attributes later if needed
    ALLOW_UNKNOWN_PROTOCOLS: true
  });
  function sanitizeHtml(untrusted, config) {
    return doSanitizeHtml(untrusted, config, "trusted");
  }
  function doSanitizeHtml(untrusted, config, outputType) {
    try {
      const resolvedConfig = { ...defaultDomPurifyConfig };
      if (config?.allowedTags) {
        if (config.allowedTags.override) {
          resolvedConfig.ALLOWED_TAGS = [...config.allowedTags.override];
        }
        if (config.allowedTags.augment) {
          resolvedConfig.ALLOWED_TAGS = [...resolvedConfig.ALLOWED_TAGS ?? [], ...config.allowedTags.augment];
        }
      }
      let resolvedAttributes = [...defaultAllowedAttrs];
      if (config?.allowedAttributes) {
        if (config.allowedAttributes.override) {
          resolvedAttributes = [...config.allowedAttributes.override];
        }
        if (config.allowedAttributes.augment) {
          resolvedAttributes = [...resolvedAttributes, ...config.allowedAttributes.augment];
        }
      }
      resolvedAttributes = resolvedAttributes.map((attr) => {
        if (typeof attr === "string") {
          return attr.toLowerCase();
        }
        return {
          attributeName: attr.attributeName.toLowerCase(),
          shouldKeep: attr.shouldKeep
        };
      });
      const allowedAttrNames = new Set(resolvedAttributes.map((attr) => typeof attr === "string" ? attr : attr.attributeName));
      const allowedAttrPredicates = /* @__PURE__ */ new Map();
      for (const attr of resolvedAttributes) {
        if (typeof attr === "string") {
          allowedAttrPredicates.delete(attr);
        } else {
          allowedAttrPredicates.set(attr.attributeName, attr);
        }
      }
      resolvedConfig.ALLOWED_ATTR = Array.from(allowedAttrNames);
      hookDomPurifyHrefAndSrcSanitizer({
        override: config?.allowedLinkProtocols?.override ?? [Schemas.http, Schemas.https],
        allowRelativePaths: config?.allowRelativeLinkPaths ?? false
      }, {
        override: config?.allowedMediaProtocols?.override ?? [Schemas.http, Schemas.https],
        allowRelativePaths: config?.allowRelativeMediaPaths ?? false
      });
      if (config?.replaceWithPlaintext) {
        purify.addHook("uponSanitizeElement", replaceWithPlainTextHook);
      }
      if (allowedAttrPredicates.size) {
        purify.addHook("uponSanitizeAttribute", (node, e) => {
          const predicate = allowedAttrPredicates.get(e.attrName);
          if (predicate) {
            const result = predicate.shouldKeep(node, e);
            if (typeof result === "string") {
              e.keepAttr = true;
              e.attrValue = result;
            } else {
              e.keepAttr = result;
            }
          } else {
            e.keepAttr = allowedAttrNames.has(e.attrName);
          }
        });
      }
      if (outputType === "dom") {
        return purify.sanitize(untrusted, {
          ...resolvedConfig,
          RETURN_DOM_FRAGMENT: true
        });
      } else {
        return purify.sanitize(untrusted, {
          ...resolvedConfig,
          RETURN_TRUSTED_TYPE: true
        });
      }
    } finally {
      purify.removeAllHooks();
    }
  }
  const selfClosingTags = ["area", "base", "br", "col", "command", "embed", "hr", "img", "input", "keygen", "link", "meta", "param", "source", "track", "wbr"];
  const replaceWithPlainTextHook = (node, data, _config) => {
    if (!data.allowedTags[data.tagName] && data.tagName !== "body") {
      const replacement = convertTagToPlaintext(node);
      if (replacement) {
        if (node.nodeType === Node.COMMENT_NODE) {
          node.parentElement?.insertBefore(replacement, node);
        } else {
          node.parentElement?.replaceChild(replacement, node);
        }
      }
    }
  };
  function convertTagToPlaintext(node) {
    if (!node.ownerDocument) {
      return;
    }
    let startTagText;
    let endTagText;
    if (node.nodeType === Node.COMMENT_NODE) {
      startTagText = `<!--${node.textContent}-->`;
    } else if (node instanceof Element) {
      const tagName = node.tagName.toLowerCase();
      const isSelfClosing = selfClosingTags.includes(tagName);
      const attrString = node.attributes.length ? " " + Array.from(node.attributes).map((attr) => `${attr.name}="${attr.value}"`).join(" ") : "";
      startTagText = `<${tagName}${attrString}>`;
      if (!isSelfClosing) {
        endTagText = `</${tagName}>`;
      }
    } else {
      return;
    }
    const fragment = document.createDocumentFragment();
    const textNode = node.ownerDocument.createTextNode(startTagText);
    fragment.appendChild(textNode);
    while (node.firstChild) {
      fragment.appendChild(node.firstChild);
    }
    const endTagTextNode = endTagText ? node.ownerDocument.createTextNode(endTagText) : void 0;
    if (endTagTextNode) {
      fragment.appendChild(endTagTextNode);
    }
    return fragment;
  }
  function safeSetInnerHtml(node, untrusted, config) {
    const fragment = doSanitizeHtml(untrusted, config, "dom");
    reset(node, fragment);
  }
  const labelWithIconsRegex = new RegExp(`(\\\\)?\\$\\((${ThemeIcon.iconNameExpression}(?:${ThemeIcon.iconModifierExpression})?)\\)`, "g");
  function renderLabelWithIcons(text2) {
    const elements = new Array();
    let match2;
    let textStart = 0, textStop = 0;
    while ((match2 = labelWithIconsRegex.exec(text2)) !== null) {
      textStop = match2.index || 0;
      if (textStart < textStop) {
        elements.push(text2.substring(textStart, textStop));
      }
      textStart = (match2.index || 0) + match2[0].length;
      const [, escaped, codicon] = match2;
      elements.push(escaped ? `$(${codicon})` : renderIcon({ id: codicon }));
    }
    if (textStart < text2.length) {
      elements.push(text2.substring(textStart));
    }
    return elements;
  }
  function renderIcon(icon) {
    const node = $$l(`span`);
    node.classList.add(...ThemeIcon.asClassNameArray(icon));
    return node;
  }
  const defaultMarkedRenderers = Object.freeze({
    image: ({ href, title, text: text2 }) => {
      let dimensions = [];
      let attributes = [];
      if (href) {
        ({ href, dimensions } = parseHrefAndDimensions(href));
        attributes.push(`src="${escapeDoubleQuotes(href)}"`);
      }
      if (text2) {
        attributes.push(`alt="${escapeDoubleQuotes(text2)}"`);
      }
      if (title) {
        attributes.push(`title="${escapeDoubleQuotes(title)}"`);
      }
      if (dimensions.length) {
        attributes = attributes.concat(dimensions);
      }
      return "<img " + attributes.join(" ") + ">";
    },
    paragraph({ tokens }) {
      return `<p>${this.parser.parseInline(tokens)}</p>`;
    },
    link({ href, title, tokens }) {
      let text2 = this.parser.parseInline(tokens);
      if (typeof href !== "string") {
        return "";
      }
      if (href === text2) {
        text2 = removeMarkdownEscapes(text2);
      }
      title = typeof title === "string" ? escapeDoubleQuotes(removeMarkdownEscapes(title)) : "";
      href = removeMarkdownEscapes(href);
      href = href.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
      return `<a href="${href}" title="${title || href}" draggable="false">${text2}</a>`;
    }
  });
  function createAlertBlockquoteRenderer(fallbackRenderer) {
    return function(token) {
      const { tokens } = token;
      const firstToken = tokens[0];
      if (firstToken?.type !== "paragraph") {
        return fallbackRenderer.call(this, token);
      }
      const paragraphTokens = firstToken.tokens;
      if (!paragraphTokens || paragraphTokens.length === 0) {
        return fallbackRenderer.call(this, token);
      }
      const firstTextToken = paragraphTokens[0];
      if (firstTextToken?.type !== "text") {
        return fallbackRenderer.call(this, token);
      }
      const pattern = /^\s*\[!(NOTE|TIP|IMPORTANT|WARNING|CAUTION)\]\s*?\n*/i;
      const match2 = firstTextToken.raw.match(pattern);
      if (!match2) {
        return fallbackRenderer.call(this, token);
      }
      firstTextToken.raw = firstTextToken.raw.replace(pattern, "");
      firstTextToken.text = firstTextToken.text.replace(pattern, "");
      const alertIcons = {
        "note": "info",
        "tip": "light-bulb",
        "important": "comment",
        "warning": "alert",
        "caution": "stop"
      };
      const type = match2[1];
      const typeCapitalized = type.charAt(0).toUpperCase() + type.slice(1).toLowerCase();
      const severity = type.toLowerCase();
      const iconHtml = renderIcon({ id: alertIcons[severity] }).outerHTML;
      const content = this.parser.parse(tokens);
      return `<blockquote data-severity="${severity}"><p><span>${iconHtml}${typeCapitalized}</span>${content.substring(3)}</blockquote>
`;
    };
  }
  function renderMarkdown$1(markdown, options = {}, target) {
    const disposables = new DisposableStore();
    let isDisposed = false;
    const markedInstance2 = new Marked(...options.markedExtensions ?? []);
    const { renderer, codeBlocks, syncCodeBlocks } = createMarkdownRenderer(markedInstance2, options, markdown);
    const value = preprocessMarkdownString(markdown);
    let renderedMarkdown;
    if (options.fillInIncompleteTokens) {
      const opts = {
        ...markedInstance2.defaults,
        ...options.markedOptions,
        renderer
      };
      const tokens = markedInstance2.lexer(value, opts);
      const newTokens = fillInIncompleteTokens(tokens);
      renderedMarkdown = markedInstance2.parser(newTokens, opts);
    } else {
      renderedMarkdown = markedInstance2.parse(value, { ...options?.markedOptions, renderer, async: false });
    }
    if (markdown.supportThemeIcons) {
      const elements = renderLabelWithIcons(renderedMarkdown);
      renderedMarkdown = elements.map((e) => typeof e === "string" ? e : e.outerHTML).join("");
    }
    const renderedContent = document.createElement("div");
    const sanitizerConfig = getDomSanitizerConfig(markdown, options.sanitizerConfig ?? {});
    safeSetInnerHtml(renderedContent, renderedMarkdown, sanitizerConfig);
    rewriteRenderedLinks(markdown, options, renderedContent);
    let outElement;
    if (target) {
      outElement = target;
      reset(target, ...renderedContent.children);
    } else {
      outElement = renderedContent;
    }
    if (codeBlocks.length > 0) {
      Promise.all(codeBlocks).then((tuples) => {
        if (isDisposed) {
          return;
        }
        const renderedElements = new Map(tuples);
        const placeholderElements = outElement.querySelectorAll(`div[data-code]`);
        for (const placeholderElement of placeholderElements) {
          const renderedElement = renderedElements.get(placeholderElement.dataset["code"] ?? "");
          if (renderedElement) {
            reset(placeholderElement, renderedElement);
          }
        }
        options.asyncRenderCallback?.();
      });
    } else if (syncCodeBlocks.length > 0) {
      const renderedElements = new Map(syncCodeBlocks);
      const placeholderElements = outElement.querySelectorAll(`div[data-code]`);
      for (const placeholderElement of placeholderElements) {
        const renderedElement = renderedElements.get(placeholderElement.dataset["code"] ?? "");
        if (renderedElement) {
          reset(placeholderElement, renderedElement);
        }
      }
    }
    if (options.asyncRenderCallback) {
      for (const img of outElement.getElementsByTagName("img")) {
        const listener = disposables.add(addDisposableListener(img, "load", () => {
          listener.dispose();
          options.asyncRenderCallback();
        }));
      }
    }
    if (options.actionHandler) {
      const clickCb = (e) => {
        const mouseEvent = new StandardMouseEvent(getWindow(outElement), e);
        if (!mouseEvent.leftButton && !mouseEvent.middleButton) {
          return;
        }
        activateLink(markdown, options, mouseEvent);
      };
      disposables.add(addDisposableListener(outElement, "click", clickCb));
      disposables.add(addDisposableListener(outElement, "auxclick", clickCb));
      disposables.add(addDisposableListener(outElement, "keydown", (e) => {
        const keyboardEvent = new StandardKeyboardEvent(e);
        if (!keyboardEvent.equals(
          10
          /* KeyCode.Space */
        ) && !keyboardEvent.equals(
          3
          /* KeyCode.Enter */
        )) {
          return;
        }
        activateLink(markdown, options, keyboardEvent);
      }));
    }
    for (const input of [...outElement.getElementsByTagName("input")]) {
      if (input.attributes.getNamedItem("type")?.value === "checkbox") {
        input.setAttribute("disabled", "");
      } else {
        if (options.sanitizerConfig?.replaceWithPlaintext) {
          const replacement = convertTagToPlaintext(input);
          if (replacement) {
            input.parentElement?.replaceChild(replacement, input);
          } else {
            input.remove();
          }
        } else {
          input.remove();
        }
      }
    }
    return {
      element: outElement,
      dispose: () => {
        isDisposed = true;
        disposables.dispose();
      }
    };
  }
  function rewriteRenderedLinks(markdown, options, root) {
    for (const el of root.querySelectorAll("img, audio, video, source")) {
      const src = el.getAttribute("src");
      if (src) {
        let href = src;
        try {
          if (markdown.baseUri) {
            href = resolveWithBaseUri(URI.from(markdown.baseUri), href);
          }
        } catch (err) {
        }
        el.setAttribute("src", massageHref(markdown, href, true));
        if (options.sanitizerConfig?.remoteImageIsAllowed) {
          const uri = URI.parse(href);
          if (uri.scheme !== Schemas.file && uri.scheme !== Schemas.data && !options.sanitizerConfig.remoteImageIsAllowed(uri)) {
            el.replaceWith($$l("", void 0, el.outerHTML));
          }
        }
      }
    }
    for (const el of root.querySelectorAll("a")) {
      const href = el.getAttribute("href");
      el.setAttribute("href", "");
      if (!href || /^data:|javascript:/i.test(href) || /^command:/i.test(href) && !markdown.isTrusted || /^command:(\/\/\/)?_workbench\.downloadResource/i.test(href)) {
        el.replaceWith(...el.childNodes);
      } else {
        let resolvedHref = massageHref(markdown, href, false);
        if (markdown.baseUri) {
          resolvedHref = resolveWithBaseUri(URI.from(markdown.baseUri), href);
        }
        el.dataset.href = resolvedHref;
      }
    }
  }
  function createMarkdownRenderer(marked2, options, markdown) {
    const renderer = new marked2.Renderer(options.markedOptions);
    renderer.image = defaultMarkedRenderers.image;
    renderer.link = defaultMarkedRenderers.link;
    renderer.paragraph = defaultMarkedRenderers.paragraph;
    if (markdown.supportAlertSyntax) {
      renderer.blockquote = createAlertBlockquoteRenderer(renderer.blockquote);
    }
    const codeBlocks = [];
    const syncCodeBlocks = [];
    if (options.codeBlockRendererSync) {
      renderer.code = ({ text: text2, lang, raw }) => {
        const id = defaultGenerator.nextId();
        const value = options.codeBlockRendererSync(postProcessCodeBlockLanguageId(lang), text2, raw);
        syncCodeBlocks.push([id, value]);
        return `<div class="code" data-code="${id}">${escape$2(text2)}</div>`;
      };
    } else if (options.codeBlockRenderer) {
      renderer.code = ({ text: text2, lang }) => {
        const id = defaultGenerator.nextId();
        const value = options.codeBlockRenderer(postProcessCodeBlockLanguageId(lang), text2);
        codeBlocks.push(value.then((element) => [id, element]));
        return `<div class="code" data-code="${id}">${escape$2(text2)}</div>`;
      };
    }
    if (!markdown.supportHtml) {
      renderer.html = ({ text: text2 }) => {
        if (options.sanitizerConfig?.replaceWithPlaintext) {
          return escape$2(text2);
        }
        const match2 = markdown.isTrusted ? text2.match(/^(<span[^>]+>)|(<\/\s*span>)$/) : void 0;
        return match2 ? text2 : "";
      };
    }
    return { renderer, codeBlocks, syncCodeBlocks };
  }
  function preprocessMarkdownString(markdown) {
    let value = markdown.value;
    if (value.length > 1e5) {
      value = `${value.substr(0, 1e5)}…`;
    }
    if (markdown.supportThemeIcons) {
      value = markdownEscapeEscapedIcons(value);
    }
    return value;
  }
  function activateLink(mdStr, options, event) {
    const target = event.target.closest("a[data-href]");
    if (!isHTMLElement(target)) {
      return;
    }
    try {
      let href = target.dataset["href"];
      if (href) {
        if (mdStr.baseUri) {
          href = resolveWithBaseUri(URI.from(mdStr.baseUri), href);
        }
        options.actionHandler?.(href, mdStr);
      }
    } catch (err) {
      onUnexpectedError(err);
    } finally {
      event.preventDefault();
    }
  }
  function uriMassage(markdown, part) {
    let data;
    try {
      data = parse$1(decodeURIComponent(part));
    } catch (e) {
    }
    if (!data) {
      return part;
    }
    data = cloneAndChange(data, (value) => {
      if (markdown.uris && markdown.uris[value]) {
        return URI.revive(markdown.uris[value]);
      } else {
        return void 0;
      }
    });
    return encodeURIComponent(JSON.stringify(data));
  }
  function massageHref(markdown, href, isDomUri) {
    const data = markdown.uris && markdown.uris[href];
    let uri = URI.revive(data);
    if (isDomUri) {
      if (href.startsWith(Schemas.data + ":")) {
        return href;
      }
      if (!uri) {
        uri = URI.parse(href);
      }
      return FileAccess.uriToBrowserUri(uri).toString(true);
    }
    if (!uri) {
      return href;
    }
    if (URI.parse(href).toString() === uri.toString()) {
      return href;
    }
    if (uri.query) {
      uri = uri.with({ query: uriMassage(markdown, uri.query) });
    }
    return uri.toString();
  }
  function postProcessCodeBlockLanguageId(lang) {
    if (!lang) {
      return "";
    }
    const parts = lang.split(/[\s+|:|,|\{|\?]/, 1);
    if (parts.length) {
      return parts[0];
    }
    return lang;
  }
  function resolveWithBaseUri(baseUri, href) {
    const hasScheme = /^\w[\w\d+.-]*:/.test(href);
    if (hasScheme) {
      return href;
    }
    if (baseUri.path.endsWith("/")) {
      return resolvePath(baseUri, href).toString();
    } else {
      return resolvePath(dirname(baseUri), href).toString();
    }
  }
  function sanitizeRenderedMarkdown(renderedMarkdown, originalMdStrConfig, options = {}) {
    const sanitizerConfig = getDomSanitizerConfig(originalMdStrConfig, options);
    return sanitizeHtml(renderedMarkdown, sanitizerConfig);
  }
  const allowedMarkdownHtmlTags = Object.freeze([
    ...basicMarkupHtmlTags,
    "input"
    // Allow inputs for rendering checkboxes. Other types of inputs are removed and the inputs are always disabled
  ]);
  const allowedMarkdownHtmlAttributes = Object.freeze([
    "align",
    "autoplay",
    "alt",
    "colspan",
    "controls",
    "draggable",
    "height",
    "href",
    "loop",
    "muted",
    "playsinline",
    "poster",
    "rowspan",
    "src",
    "target",
    "title",
    "type",
    "width",
    "start",
    // Input (For disabled inputs)
    "checked",
    "disabled",
    "value",
    // Custom markdown attributes
    "data-code",
    "data-href",
    "data-severity",
    // Only allow very specific styles
    {
      attributeName: "style",
      shouldKeep: (element, data) => {
        if (element.tagName === "SPAN") {
          if (data.attrName === "style") {
            return /^(color\:(#[0-9a-fA-F]+|var\(--vscode(-[a-zA-Z0-9]+)+\));)?(background-color\:(#[0-9a-fA-F]+|var\(--vscode(-[a-zA-Z0-9]+)+\));)?(border-radius:[0-9]+px;)?$/.test(data.attrValue);
          }
        }
        return false;
      }
    },
    // Only allow codicons for classes
    {
      attributeName: "class",
      shouldKeep: (element, data) => {
        if (element.tagName === "SPAN") {
          if (data.attrName === "class") {
            return /^codicon codicon-[a-z\-]+( codicon-modifier-[a-z\-]+)?$/.test(data.attrValue);
          }
        }
        return false;
      }
    }
  ]);
  function getDomSanitizerConfig(mdStrConfig, options) {
    const isTrusted = mdStrConfig.isTrusted ?? false;
    const allowedLinkSchemes = [
      Schemas.http,
      Schemas.https,
      Schemas.mailto,
      Schemas.file,
      Schemas.vscodeFileResource,
      Schemas.vscodeRemote,
      Schemas.vscodeRemoteResource,
      Schemas.vscodeNotebookCell
    ];
    if (isTrusted) {
      allowedLinkSchemes.push(Schemas.command);
    }
    if (options.allowedLinkSchemes?.augment) {
      allowedLinkSchemes.push(...options.allowedLinkSchemes.augment);
    }
    return {
      // allowedTags should included everything that markdown renders to.
      // Since we have our own sanitize function for marked, it's possible we missed some tag so let dompurify make sure.
      // HTML tags that can result from markdown are from reading https://spec.commonmark.org/0.29/
      // HTML table tags that can result from markdown are from https://github.github.com/gfm/#tables-extension-
      allowedTags: {
        override: options.allowedTags?.override ?? allowedMarkdownHtmlTags
      },
      allowedAttributes: {
        override: options.allowedAttributes?.override ?? allowedMarkdownHtmlAttributes
      },
      allowedLinkProtocols: {
        override: allowedLinkSchemes
      },
      allowRelativeLinkPaths: !!mdStrConfig.baseUri,
      allowedMediaProtocols: {
        override: [
          Schemas.http,
          Schemas.https,
          Schemas.data,
          Schemas.file,
          Schemas.vscodeFileResource,
          Schemas.vscodeRemote,
          Schemas.vscodeRemoteResource
        ]
      },
      allowRelativeMediaPaths: !!mdStrConfig.baseUri,
      replaceWithPlaintext: options.replaceWithPlaintext
    };
  }
  function renderAsPlaintext(str, options) {
    if (typeof str === "string") {
      return str;
    }
    let value = str.value ?? "";
    if (value.length > 1e5) {
      value = `${value.substr(0, 1e5)}…`;
    }
    const html2 = parse$2(value, { async: false, renderer: plainTextRenderer.value });
    return sanitizeRenderedMarkdown(html2, { isTrusted: false }, {}).toString().replace(/&(#\d+|[a-zA-Z]+);/g, (m) => unescapeInfo.get(m) ?? m).trim();
  }
  const unescapeInfo = /* @__PURE__ */ new Map([
    ["&quot;", '"'],
    ["&nbsp;", " "],
    ["&amp;", "&"],
    ["&#39;", "'"],
    ["&lt;", "<"],
    ["&gt;", ">"]
  ]);
  function createPlainTextRenderer() {
    const renderer = new _Renderer();
    renderer.code = ({ text: text2 }) => {
      return escape$2(text2);
    };
    renderer.blockquote = ({ text: text2 }) => {
      return text2 + "\n";
    };
    renderer.html = (_) => {
      return "";
    };
    renderer.heading = function({ tokens }) {
      return this.parser.parseInline(tokens) + "\n";
    };
    renderer.hr = () => {
      return "";
    };
    renderer.list = function({ items }) {
      return items.map((x) => this.listitem(x)).join("\n") + "\n";
    };
    renderer.listitem = ({ text: text2 }) => {
      return text2 + "\n";
    };
    renderer.paragraph = function({ tokens }) {
      return this.parser.parseInline(tokens) + "\n";
    };
    renderer.table = function({ header: header2, rows }) {
      return header2.map((cell) => this.tablecell(cell)).join(" ") + "\n" + rows.map((cells) => cells.map((cell) => this.tablecell(cell)).join(" ")).join("\n") + "\n";
    };
    renderer.tablerow = ({ text: text2 }) => {
      return text2;
    };
    renderer.tablecell = function({ tokens }) {
      return this.parser.parseInline(tokens);
    };
    renderer.strong = ({ text: text2 }) => {
      return text2;
    };
    renderer.em = ({ text: text2 }) => {
      return text2;
    };
    renderer.codespan = ({ text: text2 }) => {
      return escape$2(text2);
    };
    renderer.br = (_) => {
      return "\n";
    };
    renderer.del = ({ text: text2 }) => {
      return text2;
    };
    renderer.image = (_) => {
      return "";
    };
    renderer.text = ({ text: text2 }) => {
      return text2;
    };
    renderer.link = ({ text: text2 }) => {
      return text2;
    };
    return renderer;
  }
  const plainTextRenderer = new Lazy(createPlainTextRenderer);
  new Lazy(() => {
    const renderer = createPlainTextRenderer();
    renderer.code = ({ text: text2 }) => {
      return `
\`\`\`
${escape$2(text2)}
\`\`\`
`;
    };
    return renderer;
  });
  function mergeRawTokenText(tokens) {
    let mergedTokenText = "";
    tokens.forEach((token) => {
      mergedTokenText += token.raw;
    });
    return mergedTokenText;
  }
  function completeSingleLinePattern(token) {
    if (!token.tokens) {
      return void 0;
    }
    for (let i2 = token.tokens.length - 1; i2 >= 0; i2--) {
      const subtoken = token.tokens[i2];
      if (subtoken.type === "text") {
        const lines = subtoken.raw.split("\n");
        const lastLine = lines[lines.length - 1];
        if (lastLine.includes("`")) {
          return completeCodespan(token);
        } else if (lastLine.includes("**")) {
          return completeDoublestar(token);
        } else if (lastLine.match(/\*\w/)) {
          return completeStar(token);
        } else if (lastLine.match(/(^|\s)__\w/)) {
          return completeDoubleUnderscore(token);
        } else if (lastLine.match(/(^|\s)_\w/)) {
          return completeUnderscore(token);
        } else if (
          // Text with start of link target
          hasLinkTextAndStartOfLinkTarget(lastLine) || // This token doesn't have the link text, eg if it contains other markdown constructs that are in other subtokens.
          // But some preceding token does have an unbalanced [ at least
          hasStartOfLinkTargetAndNoLinkText(lastLine) && token.tokens.slice(0, i2).some((t) => t.type === "text" && t.raw.match(/\[[^\]]*$/))
        ) {
          const nextTwoSubTokens = token.tokens.slice(i2 + 1);
          if (
            // If the link was parsed as a link, then look for a link token and a text token with a quote
            nextTwoSubTokens[0]?.type === "link" && nextTwoSubTokens[1]?.type === "text" && nextTwoSubTokens[1].raw.match(/^ *"[^"]*$/) || // And if the link was not parsed as a link (eg command link), just look for a single quote in this token
            lastLine.match(/^[^"]* +"[^"]*$/)
          ) {
            return completeLinkTargetArg(token);
          }
          return completeLinkTarget(token);
        } else if (lastLine.match(/(^|\s)\[\w*[^\]]*$/)) {
          return completeLinkText(token);
        }
      }
    }
    return void 0;
  }
  function hasLinkTextAndStartOfLinkTarget(str) {
    return !!str.match(/(^|\s)\[.*\]\(\w*/);
  }
  function hasStartOfLinkTargetAndNoLinkText(str) {
    return !!str.match(/^[^\[]*\]\([^\)]*$/);
  }
  function completeListItemPattern(list2) {
    const lastListItem = list2.items[list2.items.length - 1];
    const lastListSubToken = lastListItem.tokens ? lastListItem.tokens[lastListItem.tokens.length - 1] : void 0;
    const listEndsInHeading = (list3) => {
      const lastItem = list3.items.at(-1);
      const lastToken = lastItem?.tokens.at(-1);
      return lastToken?.type === "heading" || lastToken?.type === "list" && listEndsInHeading(lastToken);
    };
    let newToken;
    if (lastListSubToken?.type === "text" && !("inRawBlock" in lastListItem)) {
      newToken = completeSingleLinePattern(lastListSubToken);
    } else if (listEndsInHeading(list2)) {
      const newList2 = lexer(list2.raw.trim() + " &nbsp;")[0];
      if (newList2.type !== "list") {
        return;
      }
      return newList2;
    }
    if (!newToken || newToken.type !== "paragraph") {
      return;
    }
    const previousListItemsText = mergeRawTokenText(list2.items.slice(0, -1));
    const lastListItemLead = lastListItem.raw.match(/^(\s*(-|\d+\.|\*) +)/)?.[0];
    if (!lastListItemLead) {
      return;
    }
    const newListItemText = lastListItemLead + mergeRawTokenText(lastListItem.tokens.slice(0, -1)) + newToken.raw;
    const newList = lexer(previousListItemsText + newListItemText)[0];
    if (newList.type !== "list") {
      return;
    }
    return newList;
  }
  function completeHeading(token, fullRawText) {
    if (token.raw.match(/-\s*$/)) {
      return lexer(fullRawText + " &nbsp;");
    }
  }
  const maxIncompleteTokensFixRounds = 3;
  function fillInIncompleteTokens(tokens) {
    for (let i2 = 0; i2 < maxIncompleteTokensFixRounds; i2++) {
      const newTokens = fillInIncompleteTokensOnce(tokens);
      if (newTokens) {
        tokens = newTokens;
      } else {
        break;
      }
    }
    return tokens;
  }
  function fillInIncompleteTokensOnce(tokens) {
    let i2;
    let newTokens;
    for (i2 = 0; i2 < tokens.length; i2++) {
      const token = tokens[i2];
      if (token.type === "paragraph" && token.raw.match(/(\n|^)\|/)) {
        newTokens = completeTable(tokens.slice(i2));
        break;
      }
    }
    const lastToken = tokens.at(-1);
    if (!newTokens && lastToken?.type === "list") {
      const newListToken = completeListItemPattern(lastToken);
      if (newListToken) {
        newTokens = [newListToken];
        i2 = tokens.length - 1;
      }
    }
    if (!newTokens && lastToken?.type === "paragraph") {
      const newToken = completeSingleLinePattern(lastToken);
      if (newToken) {
        newTokens = [newToken];
        i2 = tokens.length - 1;
      }
    }
    if (newTokens) {
      const newTokensList = [
        ...tokens.slice(0, i2),
        ...newTokens
      ];
      newTokensList.links = tokens.links;
      return newTokensList;
    }
    if (lastToken?.type === "heading") {
      const completeTokens = completeHeading(lastToken, mergeRawTokenText(tokens));
      if (completeTokens) {
        return completeTokens;
      }
    }
    return null;
  }
  function completeCodespan(token) {
    return completeWithString(token, "`");
  }
  function completeStar(tokens) {
    return completeWithString(tokens, "*");
  }
  function completeUnderscore(tokens) {
    return completeWithString(tokens, "_");
  }
  function completeLinkTarget(tokens) {
    return completeWithString(tokens, ")", false);
  }
  function completeLinkTargetArg(tokens) {
    return completeWithString(tokens, '")', false);
  }
  function completeLinkText(tokens) {
    return completeWithString(tokens, "](https://microsoft.com)", false);
  }
  function completeDoublestar(tokens) {
    return completeWithString(tokens, "**");
  }
  function completeDoubleUnderscore(tokens) {
    return completeWithString(tokens, "__");
  }
  function completeWithString(tokens, closingString, shouldTrim = true) {
    const mergedRawText = mergeRawTokenText(Array.isArray(tokens) ? tokens : [tokens]);
    const trimmedRawText = shouldTrim ? mergedRawText.trimEnd() : mergedRawText;
    return lexer(trimmedRawText + closingString)[0];
  }
  function completeTable(tokens) {
    const mergedRawText = mergeRawTokenText(tokens);
    const lines = mergedRawText.split("\n");
    let numCols;
    let hasSeparatorRow = false;
    for (let i2 = 0; i2 < lines.length; i2++) {
      const line = lines[i2].trim();
      if (typeof numCols === "undefined" && line.match(/^\s*\|/)) {
        const line1Matches = line.match(/(\|[^\|]+)(?=\||$)/g);
        if (line1Matches) {
          numCols = line1Matches.length;
        }
      } else if (typeof numCols === "number") {
        if (line.match(/^\s*\|/)) {
          if (i2 !== lines.length - 1) {
            return void 0;
          }
          hasSeparatorRow = true;
        } else {
          return void 0;
        }
      }
    }
    if (typeof numCols === "number" && numCols > 0) {
      const prefixText = hasSeparatorRow ? lines.slice(0, -1).join("\n") : mergedRawText;
      const line1EndsInPipe = !!prefixText.match(/\|\s*$/);
      const newRawText = prefixText + (line1EndsInPipe ? "" : "|") + `
|${" --- |".repeat(numCols)}`;
      return lexer(newRawText);
    }
    return void 0;
  }
  let baseHoverDelegate = {
    showInstantHover: () => void 0,
    showDelayedHover: () => void 0,
    setupDelayedHover: () => Disposable.None,
    setupDelayedHoverAtMouse: () => Disposable.None,
    hideHover: () => void 0,
    showAndFocusLastHover: () => void 0,
    setupManagedHover: () => ({
      dispose: () => void 0,
      show: () => void 0,
      hide: () => void 0,
      update: () => void 0
    }),
    showManagedHover: () => void 0
  };
  function setBaseLayerHoverDelegate(hoverDelegate) {
    baseHoverDelegate = hoverDelegate;
  }
  function getBaseLayerHoverDelegate() {
    return baseHoverDelegate;
  }
  class CombinedSpliceable {
    constructor(spliceables) {
      this.spliceables = spliceables;
    }
    splice(start, deleteCount, elements) {
      this.spliceables.forEach((s) => s.splice(start, deleteCount, elements));
    }
  }
  function clamp(value, min, max) {
    return Math.min(Math.max(value, min), max);
  }
  class MovingAverage {
    constructor() {
      this._n = 1;
      this._val = 0;
    }
    update(value) {
      this._val = this._val + (value - this._val) / this._n;
      this._n += 1;
      return this._val;
    }
    get value() {
      return this._val;
    }
  }
  class SlidingWindowAverage {
    constructor(size2) {
      this._n = 0;
      this._val = 0;
      this._values = [];
      this._index = 0;
      this._sum = 0;
      this._values = new Array(size2);
      this._values.fill(0, 0, size2);
    }
    update(value) {
      const oldValue = this._values[this._index];
      this._values[this._index] = value;
      this._index = (this._index + 1) % this._values.length;
      this._sum -= oldValue;
      this._sum += value;
      if (this._n < this._values.length) {
        this._n += 1;
      }
      this._val = this._sum / this._n;
      return this._val;
    }
    get value() {
      return this._val;
    }
  }
  class ListError extends Error {
    constructor(user, message) {
      super(`ListError [${user}] ${message}`);
    }
  }
  var Range$1;
  (function(Range2) {
    function intersect(one, other) {
      if (one.start >= other.end || other.start >= one.end) {
        return { start: 0, end: 0 };
      }
      const start = Math.max(one.start, other.start);
      const end = Math.min(one.end, other.end);
      if (end - start <= 0) {
        return { start: 0, end: 0 };
      }
      return { start, end };
    }
    Range2.intersect = intersect;
    function isEmpty(range2) {
      return range2.end - range2.start <= 0;
    }
    Range2.isEmpty = isEmpty;
    function intersects2(one, other) {
      return !isEmpty(intersect(one, other));
    }
    Range2.intersects = intersects2;
    function relativeComplement2(one, other) {
      const result = [];
      const first2 = { start: one.start, end: Math.min(other.start, one.end) };
      const second = { start: Math.max(other.end, one.start), end: one.end };
      if (!isEmpty(first2)) {
        result.push(first2);
      }
      if (!isEmpty(second)) {
        result.push(second);
      }
      return result;
    }
    Range2.relativeComplement = relativeComplement2;
  })(Range$1 || (Range$1 = {}));
  function groupIntersect(range2, groups) {
    const result = [];
    for (const r of groups) {
      if (range2.start >= r.range.end) {
        continue;
      }
      if (range2.end < r.range.start) {
        break;
      }
      const intersection2 = Range$1.intersect(range2, r.range);
      if (Range$1.isEmpty(intersection2)) {
        continue;
      }
      result.push({
        range: intersection2,
        size: r.size
      });
    }
    return result;
  }
  function shift({ start, end }, much) {
    return { start: start + much, end: end + much };
  }
  function consolidate(groups) {
    const result = [];
    let previousGroup = null;
    for (const group of groups) {
      const start = group.range.start;
      const end = group.range.end;
      const size2 = group.size;
      if (previousGroup && size2 === previousGroup.size) {
        previousGroup.range.end = end;
        continue;
      }
      previousGroup = { range: { start, end }, size: size2 };
      result.push(previousGroup);
    }
    return result;
  }
  function concat(...groups) {
    return consolidate(groups.reduce((r, g) => r.concat(g), []));
  }
  class RangeMap {
    get paddingTop() {
      return this._paddingTop;
    }
    set paddingTop(paddingTop) {
      this._size = this._size + paddingTop - this._paddingTop;
      this._paddingTop = paddingTop;
    }
    constructor(topPadding) {
      this.groups = [];
      this._size = 0;
      this._paddingTop = 0;
      this._paddingTop = topPadding ?? 0;
      this._size = this._paddingTop;
    }
    splice(index, deleteCount, items = []) {
      const diff = items.length - deleteCount;
      const before = groupIntersect({ start: 0, end: index }, this.groups);
      const after2 = groupIntersect({ start: index + deleteCount, end: Number.POSITIVE_INFINITY }, this.groups).map((g) => ({ range: shift(g.range, diff), size: g.size }));
      const middle = items.map((item, i2) => ({
        range: { start: index + i2, end: index + i2 + 1 },
        size: item.size
      }));
      this.groups = concat(before, middle, after2);
      this._size = this._paddingTop + this.groups.reduce((t, g) => t + g.size * (g.range.end - g.range.start), 0);
    }
    /**
     * Returns the number of items in the range map.
     */
    get count() {
      const len = this.groups.length;
      if (!len) {
        return 0;
      }
      return this.groups[len - 1].range.end;
    }
    /**
     * Returns the sum of the sizes of all items in the range map.
     */
    get size() {
      return this._size;
    }
    /**
     * Returns the index of the item at the given position.
     */
    indexAt(position) {
      if (position < 0) {
        return -1;
      }
      if (position < this._paddingTop) {
        return 0;
      }
      let index = 0;
      let size2 = this._paddingTop;
      for (const group of this.groups) {
        const count = group.range.end - group.range.start;
        const newSize = size2 + count * group.size;
        if (position < newSize) {
          return index + Math.floor((position - size2) / group.size);
        }
        index += count;
        size2 = newSize;
      }
      return index;
    }
    /**
     * Returns the index of the item right after the item at the
     * index of the given position.
     */
    indexAfter(position) {
      return Math.min(this.indexAt(position) + 1, this.count);
    }
    /**
     * Returns the start position of the item at the given index.
     */
    positionAt(index) {
      if (index < 0) {
        return -1;
      }
      let position = 0;
      let count = 0;
      for (const group of this.groups) {
        const groupCount = group.range.end - group.range.start;
        const newCount = count + groupCount;
        if (index < newCount) {
          return this._paddingTop + position + (index - count) * group.size;
        }
        position += groupCount * group.size;
        count = newCount;
      }
      return -1;
    }
  }
  class RowCache {
    constructor(renderers) {
      this.renderers = renderers;
      this.cache = /* @__PURE__ */ new Map();
      this.transactionNodesPendingRemoval = /* @__PURE__ */ new Set();
      this.inTransaction = false;
    }
    /**
     * Returns a row either by creating a new one or reusing
     * a previously released row which shares the same templateId.
     *
     * @returns A row and `isReusingConnectedDomNode` if the row's node is already in the dom in a stale position.
     */
    alloc(templateId) {
      let result = this.getTemplateCache(templateId).pop();
      let isStale = false;
      if (result) {
        isStale = this.transactionNodesPendingRemoval.has(result.domNode);
        if (isStale) {
          this.transactionNodesPendingRemoval.delete(result.domNode);
        }
      } else {
        const domNode = $$l(".monaco-list-row");
        const renderer = this.getRenderer(templateId);
        const templateData = renderer.renderTemplate(domNode);
        result = { domNode, templateId, templateData };
      }
      return { row: result, isReusingConnectedDomNode: isStale };
    }
    /**
     * Releases the row for eventual reuse.
     */
    release(row) {
      if (!row) {
        return;
      }
      this.releaseRow(row);
    }
    /**
     * Begin a set of changes that use the cache. This lets us skip work when a row is removed and then inserted again.
     */
    transact(makeChanges) {
      if (this.inTransaction) {
        throw new Error("Already in transaction");
      }
      this.inTransaction = true;
      try {
        makeChanges();
      } finally {
        for (const domNode of this.transactionNodesPendingRemoval) {
          this.doRemoveNode(domNode);
        }
        this.transactionNodesPendingRemoval.clear();
        this.inTransaction = false;
      }
    }
    releaseRow(row) {
      const { domNode, templateId } = row;
      if (domNode) {
        if (this.inTransaction) {
          this.transactionNodesPendingRemoval.add(domNode);
        } else {
          this.doRemoveNode(domNode);
        }
      }
      const cache = this.getTemplateCache(templateId);
      cache.push(row);
    }
    doRemoveNode(domNode) {
      domNode.classList.remove("scrolling");
      domNode.remove();
    }
    getTemplateCache(templateId) {
      let result = this.cache.get(templateId);
      if (!result) {
        result = [];
        this.cache.set(templateId, result);
      }
      return result;
    }
    dispose() {
      this.cache.forEach((cachedRows, templateId) => {
        for (const cachedRow of cachedRows) {
          const renderer = this.getRenderer(templateId);
          renderer.disposeTemplate(cachedRow.templateData);
          cachedRow.templateData = null;
        }
      });
      this.cache.clear();
      this.transactionNodesPendingRemoval.clear();
    }
    getRenderer(templateId) {
      const renderer = this.renderers.get(templateId);
      if (!renderer) {
        throw new Error(`No renderer found for ${templateId}`);
      }
      return renderer;
    }
  }
  function applyDragImage(event, container, label, extraClasses = []) {
    if (!event.dataTransfer) {
      return;
    }
    const dragImage = $$l(".monaco-drag-image");
    dragImage.textContent = label;
    dragImage.classList.add(...extraClasses);
    const getDragImageContainer = (e) => {
      while (e && !e.classList.contains("monaco-workbench")) {
        e = e.parentElement;
      }
      return e || container.ownerDocument.body;
    };
    const dragContainer = getDragImageContainer(container);
    dragContainer.appendChild(dragImage);
    event.dataTransfer.setDragImage(dragImage, -10, -10);
    setTimeout(() => dragImage.remove(), 0);
  }
  var __decorate$2J = 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;
  };
  const StaticDND = {
    CurrentDragAndDropData: void 0
  };
  const DefaultOptions$1 = {
    useShadows: true,
    verticalScrollMode: 1,
    setRowLineHeight: true,
    setRowHeight: true,
    supportDynamicHeights: false,
    dnd: {
      getDragElements(e) {
        return [e];
      },
      getDragURI() {
        return null;
      },
      onDragStart() {
      },
      onDragOver() {
        return false;
      },
      drop() {
      },
      dispose() {
      }
    },
    horizontalScrolling: false,
    transformOptimization: true,
    alwaysConsumeMouseWheel: true
  };
  class ElementsDragAndDropData {
    constructor(elements) {
      this.elements = elements;
    }
    update() {
    }
    getData() {
      return this.elements;
    }
  }
  class ExternalElementsDragAndDropData {
    constructor(elements) {
      this.elements = elements;
    }
    update() {
    }
    getData() {
      return this.elements;
    }
  }
  class NativeDragAndDropData {
    constructor() {
      this.types = [];
      this.files = [];
    }
    update(dataTransfer) {
      if (dataTransfer.types) {
        this.types.splice(0, this.types.length, ...dataTransfer.types);
      }
      if (dataTransfer.files) {
        this.files.splice(0, this.files.length);
        for (let i2 = 0; i2 < dataTransfer.files.length; i2++) {
          const file = dataTransfer.files.item(i2);
          if (file && (file.size || file.type)) {
            this.files.push(file);
          }
        }
      }
    }
    getData() {
      return {
        types: this.types,
        files: this.files
      };
    }
  }
  function equalsDragFeedback(f1, f2) {
    if (Array.isArray(f1) && Array.isArray(f2)) {
      return equals$1(f1, f2);
    }
    return f1 === f2;
  }
  class ListViewAccessibilityProvider {
    constructor(accessibilityProvider) {
      if (accessibilityProvider?.getSetSize) {
        this.getSetSize = accessibilityProvider.getSetSize.bind(accessibilityProvider);
      } else {
        this.getSetSize = (e, i2, l) => l;
      }
      if (accessibilityProvider?.getPosInSet) {
        this.getPosInSet = accessibilityProvider.getPosInSet.bind(accessibilityProvider);
      } else {
        this.getPosInSet = (e, i2) => i2 + 1;
      }
      if (accessibilityProvider?.getRole) {
        this.getRole = accessibilityProvider.getRole.bind(accessibilityProvider);
      } else {
        this.getRole = (_) => "listitem";
      }
      if (accessibilityProvider?.isChecked) {
        this.isChecked = accessibilityProvider.isChecked.bind(accessibilityProvider);
      } else {
        this.isChecked = (_) => void 0;
      }
    }
  }
  const _ListView = class _ListView {
    get contentHeight() {
      return this.rangeMap.size;
    }
    get onDidScroll() {
      return this.scrollableElement.onScroll;
    }
    get scrollableElementDomNode() {
      return this.scrollableElement.getDomNode();
    }
    get horizontalScrolling() {
      return this._horizontalScrolling;
    }
    set horizontalScrolling(value) {
      if (value === this._horizontalScrolling) {
        return;
      }
      if (value && this.supportDynamicHeights) {
        throw new Error("Horizontal scrolling and dynamic heights not supported simultaneously");
      }
      this._horizontalScrolling = value;
      this.domNode.classList.toggle("horizontal-scrolling", this._horizontalScrolling);
      if (this._horizontalScrolling) {
        for (const item of this.items) {
          this.measureItemWidth(item);
        }
        this.updateScrollWidth();
        this.scrollableElement.setScrollDimensions({ width: getContentWidth(this.domNode) });
        this.rowsContainer.style.width = `${Math.max(this.scrollWidth || 0, this.renderWidth)}px`;
      } else {
        this.scrollableElementWidthDelayer.cancel();
        this.scrollableElement.setScrollDimensions({ width: this.renderWidth, scrollWidth: this.renderWidth });
        this.rowsContainer.style.width = "";
      }
    }
    constructor(container, virtualDelegate, renderers, options = DefaultOptions$1) {
      this.virtualDelegate = virtualDelegate;
      this.domId = `list_id_${++_ListView.InstanceCount}`;
      this.renderers = /* @__PURE__ */ new Map();
      this.renderWidth = 0;
      this._scrollHeight = 0;
      this.scrollableElementUpdateDisposable = null;
      this.scrollableElementWidthDelayer = new Delayer(50);
      this.splicing = false;
      this.dragOverAnimationStopDisposable = Disposable.None;
      this.dragOverMouseY = 0;
      this.canDrop = false;
      this.currentDragFeedbackDisposable = Disposable.None;
      this.onDragLeaveTimeout = Disposable.None;
      this.currentSelectionDisposable = Disposable.None;
      this.disposables = new DisposableStore();
      this._onDidChangeContentHeight = new Emitter$1();
      this._onDidChangeContentWidth = new Emitter$1();
      this.onDidChangeContentHeight = Event.latch(this._onDidChangeContentHeight.event, void 0, this.disposables);
      this._horizontalScrolling = false;
      if (options.horizontalScrolling && options.supportDynamicHeights) {
        throw new Error("Horizontal scrolling and dynamic heights not supported simultaneously");
      }
      this.items = [];
      this.itemId = 0;
      this.rangeMap = this.createRangeMap(options.paddingTop ?? 0);
      for (const renderer of renderers) {
        this.renderers.set(renderer.templateId, renderer);
      }
      this.cache = this.disposables.add(new RowCache(this.renderers));
      this.lastRenderTop = 0;
      this.lastRenderHeight = 0;
      this.domNode = document.createElement("div");
      this.domNode.className = "monaco-list";
      this.domNode.classList.add(this.domId);
      this.domNode.tabIndex = 0;
      this.domNode.classList.toggle("mouse-support", typeof options.mouseSupport === "boolean" ? options.mouseSupport : true);
      this._horizontalScrolling = options.horizontalScrolling ?? DefaultOptions$1.horizontalScrolling;
      this.domNode.classList.toggle("horizontal-scrolling", this._horizontalScrolling);
      this.paddingBottom = typeof options.paddingBottom === "undefined" ? 0 : options.paddingBottom;
      this.accessibilityProvider = new ListViewAccessibilityProvider(options.accessibilityProvider);
      this.rowsContainer = document.createElement("div");
      this.rowsContainer.className = "monaco-list-rows";
      const transformOptimization = options.transformOptimization ?? DefaultOptions$1.transformOptimization;
      if (transformOptimization) {
        this.rowsContainer.style.transform = "translate3d(0px, 0px, 0px)";
        this.rowsContainer.style.overflow = "hidden";
        this.rowsContainer.style.contain = "strict";
      }
      this.disposables.add(Gesture.addTarget(this.rowsContainer));
      this.scrollable = this.disposables.add(new Scrollable({
        forceIntegerValues: true,
        smoothScrollDuration: options.smoothScrolling ?? false ? 125 : 0,
        scheduleAtNextAnimationFrame: (cb) => scheduleAtNextAnimationFrame(getWindow(this.domNode), cb)
      }));
      this.scrollableElement = this.disposables.add(new SmoothScrollableElement(this.rowsContainer, {
        alwaysConsumeMouseWheel: options.alwaysConsumeMouseWheel ?? DefaultOptions$1.alwaysConsumeMouseWheel,
        horizontal: 1,
        vertical: options.verticalScrollMode ?? DefaultOptions$1.verticalScrollMode,
        useShadows: options.useShadows ?? DefaultOptions$1.useShadows,
        mouseWheelScrollSensitivity: options.mouseWheelScrollSensitivity,
        fastScrollSensitivity: options.fastScrollSensitivity,
        scrollByPage: options.scrollByPage
      }, this.scrollable));
      this.domNode.appendChild(this.scrollableElement.getDomNode());
      container.appendChild(this.domNode);
      this.scrollableElement.onScroll(this.onScroll, this, this.disposables);
      this.disposables.add(addDisposableListener(this.rowsContainer, EventType.Change, (e) => this.onTouchChange(e)));
      this.disposables.add(addDisposableListener(this.scrollableElement.getDomNode(), "scroll", (e) => {
        const element = e.target;
        const scrollValue = element.scrollTop;
        element.scrollTop = 0;
        if (options.scrollToActiveElement) {
          this.setScrollTop(this.scrollTop + scrollValue);
        }
      }));
      this.disposables.add(addDisposableListener(this.domNode, "dragover", (e) => this.onDragOver(this.toDragEvent(e))));
      this.disposables.add(addDisposableListener(this.domNode, "drop", (e) => this.onDrop(this.toDragEvent(e))));
      this.disposables.add(addDisposableListener(this.domNode, "dragleave", (e) => this.onDragLeave(this.toDragEvent(e))));
      this.disposables.add(addDisposableListener(this.domNode, "dragend", (e) => this.onDragEnd(e)));
      if (options.userSelection) {
        if (options.dnd) {
          throw new Error("DND and user selection cannot be used simultaneously");
        }
        this.disposables.add(addDisposableListener(this.domNode, "mousedown", (e) => this.onPotentialSelectionStart(e)));
      }
      this.setRowLineHeight = options.setRowLineHeight ?? DefaultOptions$1.setRowLineHeight;
      this.setRowHeight = options.setRowHeight ?? DefaultOptions$1.setRowHeight;
      this.supportDynamicHeights = options.supportDynamicHeights ?? DefaultOptions$1.supportDynamicHeights;
      this.dnd = options.dnd ?? this.disposables.add(DefaultOptions$1.dnd);
      this.layout(options.initialSize?.height, options.initialSize?.width);
      if (options.scrollToActiveElement) {
        this._setupFocusObserver(container);
      }
    }
    _setupFocusObserver(container) {
      this.disposables.add(addDisposableListener(container, "focus", () => {
        const element = getActiveElement();
        if (this.activeElement !== element && element !== null) {
          this.activeElement = element;
          this._scrollToActiveElement(this.activeElement, container);
        }
      }, true));
    }
    _scrollToActiveElement(element, container) {
      const containerRect = container.getBoundingClientRect();
      const elementRect = element.getBoundingClientRect();
      const topOffset = elementRect.top - containerRect.top;
      if (topOffset < 0) {
        this.setScrollTop(this.scrollTop + topOffset);
      }
    }
    updateOptions(options) {
      if (options.paddingBottom !== void 0) {
        this.paddingBottom = options.paddingBottom;
        this.scrollableElement.setScrollDimensions({ scrollHeight: this.scrollHeight });
      }
      if (options.smoothScrolling !== void 0) {
        this.scrollable.setSmoothScrollDuration(options.smoothScrolling ? 125 : 0);
      }
      if (options.horizontalScrolling !== void 0) {
        this.horizontalScrolling = options.horizontalScrolling;
      }
      let scrollableOptions;
      if (options.scrollByPage !== void 0) {
        scrollableOptions = { ...scrollableOptions ?? {}, scrollByPage: options.scrollByPage };
      }
      if (options.mouseWheelScrollSensitivity !== void 0) {
        scrollableOptions = { ...scrollableOptions ?? {}, mouseWheelScrollSensitivity: options.mouseWheelScrollSensitivity };
      }
      if (options.fastScrollSensitivity !== void 0) {
        scrollableOptions = { ...scrollableOptions ?? {}, fastScrollSensitivity: options.fastScrollSensitivity };
      }
      if (scrollableOptions) {
        this.scrollableElement.updateOptions(scrollableOptions);
      }
      if (options.paddingTop !== void 0 && options.paddingTop !== this.rangeMap.paddingTop) {
        const lastRenderRange = this.getRenderRange(this.lastRenderTop, this.lastRenderHeight);
        const offset = options.paddingTop - this.rangeMap.paddingTop;
        this.rangeMap.paddingTop = options.paddingTop;
        this.render(lastRenderRange, Math.max(0, this.lastRenderTop + offset), this.lastRenderHeight, void 0, void 0, true);
        this.setScrollTop(this.lastRenderTop);
        this.eventuallyUpdateScrollDimensions();
        if (this.supportDynamicHeights) {
          this._rerender(this.lastRenderTop, this.lastRenderHeight);
        }
      }
    }
    createRangeMap(paddingTop) {
      return new RangeMap(paddingTop);
    }
    splice(start, deleteCount, elements = []) {
      if (this.splicing) {
        throw new Error("Can't run recursive splices.");
      }
      this.splicing = true;
      try {
        return this._splice(start, deleteCount, elements);
      } finally {
        this.splicing = false;
        this._onDidChangeContentHeight.fire(this.contentHeight);
      }
    }
    _splice(start, deleteCount, elements = []) {
      const previousRenderRange = this.getRenderRange(this.lastRenderTop, this.lastRenderHeight);
      const deleteRange = { start, end: start + deleteCount };
      const removeRange = Range$1.intersect(previousRenderRange, deleteRange);
      const rowsToDispose = /* @__PURE__ */ new Map();
      for (let i2 = removeRange.end - 1; i2 >= removeRange.start; i2--) {
        const item = this.items[i2];
        item.dragStartDisposable.dispose();
        item.checkedDisposable.dispose();
        if (item.row) {
          let rows = rowsToDispose.get(item.templateId);
          if (!rows) {
            rows = [];
            rowsToDispose.set(item.templateId, rows);
          }
          const renderer = this.renderers.get(item.templateId);
          if (renderer && renderer.disposeElement) {
            renderer.disposeElement(item.element, i2, item.row.templateData, { height: item.size });
          }
          rows.unshift(item.row);
        }
        item.row = null;
        item.stale = true;
      }
      const previousRestRange = { start: start + deleteCount, end: this.items.length };
      const previousRenderedRestRange = Range$1.intersect(previousRestRange, previousRenderRange);
      const previousUnrenderedRestRanges = Range$1.relativeComplement(previousRestRange, previousRenderRange);
      const inserted = elements.map((element) => ({
        id: String(this.itemId++),
        element,
        templateId: this.virtualDelegate.getTemplateId(element),
        size: this.virtualDelegate.getHeight(element),
        width: void 0,
        hasDynamicHeight: !!this.virtualDelegate.hasDynamicHeight && this.virtualDelegate.hasDynamicHeight(element),
        lastDynamicHeightWidth: void 0,
        row: null,
        uri: void 0,
        dropTarget: false,
        dragStartDisposable: Disposable.None,
        checkedDisposable: Disposable.None,
        stale: false
      }));
      let deleted;
      if (start === 0 && deleteCount >= this.items.length) {
        this.rangeMap = this.createRangeMap(this.rangeMap.paddingTop);
        this.rangeMap.splice(0, 0, inserted);
        deleted = this.items;
        this.items = inserted;
      } else {
        this.rangeMap.splice(start, deleteCount, inserted);
        deleted = splice$1(this.items, start, deleteCount, inserted);
      }
      const delta = elements.length - deleteCount;
      const renderRange = this.getRenderRange(this.lastRenderTop, this.lastRenderHeight);
      const renderedRestRange = shift(previousRenderedRestRange, delta);
      const updateRange = Range$1.intersect(renderRange, renderedRestRange);
      for (let i2 = updateRange.start; i2 < updateRange.end; i2++) {
        this.updateItemInDOM(this.items[i2], i2);
      }
      const removeRanges = Range$1.relativeComplement(renderedRestRange, renderRange);
      for (const range2 of removeRanges) {
        for (let i2 = range2.start; i2 < range2.end; i2++) {
          this.removeItemFromDOM(i2);
        }
      }
      const unrenderedRestRanges = previousUnrenderedRestRanges.map((r) => shift(r, delta));
      const elementsRange = { start, end: start + elements.length };
      const insertRanges = [elementsRange, ...unrenderedRestRanges].map((r) => Range$1.intersect(renderRange, r)).reverse();
      for (const range2 of insertRanges) {
        for (let i2 = range2.end - 1; i2 >= range2.start; i2--) {
          const item = this.items[i2];
          const rows = rowsToDispose.get(item.templateId);
          const row = rows?.pop();
          this.insertItemInDOM(i2, row);
        }
      }
      for (const rows of rowsToDispose.values()) {
        for (const row of rows) {
          this.cache.release(row);
        }
      }
      this.eventuallyUpdateScrollDimensions();
      if (this.supportDynamicHeights) {
        this._rerender(this.scrollTop, this.renderHeight);
      }
      return deleted.map((i2) => i2.element);
    }
    eventuallyUpdateScrollDimensions() {
      this._scrollHeight = this.contentHeight;
      this.rowsContainer.style.height = `${this._scrollHeight}px`;
      if (!this.scrollableElementUpdateDisposable) {
        this.scrollableElementUpdateDisposable = scheduleAtNextAnimationFrame(getWindow(this.domNode), () => {
          this.scrollableElement.setScrollDimensions({ scrollHeight: this.scrollHeight });
          this.updateScrollWidth();
          this.scrollableElementUpdateDisposable = null;
        });
      }
    }
    eventuallyUpdateScrollWidth() {
      if (!this.horizontalScrolling) {
        this.scrollableElementWidthDelayer.cancel();
        return;
      }
      this.scrollableElementWidthDelayer.trigger(() => this.updateScrollWidth());
    }
    updateScrollWidth() {
      if (!this.horizontalScrolling) {
        return;
      }
      let scrollWidth = 0;
      for (const item of this.items) {
        if (typeof item.width !== "undefined") {
          scrollWidth = Math.max(scrollWidth, item.width);
        }
      }
      this.scrollWidth = scrollWidth;
      this.scrollableElement.setScrollDimensions({ scrollWidth: scrollWidth === 0 ? 0 : scrollWidth + 10 });
      this._onDidChangeContentWidth.fire(this.scrollWidth);
    }
    rerender() {
      if (!this.supportDynamicHeights) {
        return;
      }
      for (const item of this.items) {
        item.lastDynamicHeightWidth = void 0;
      }
      this._rerender(this.lastRenderTop, this.lastRenderHeight);
    }
    get length() {
      return this.items.length;
    }
    get renderHeight() {
      const scrollDimensions = this.scrollableElement.getScrollDimensions();
      return scrollDimensions.height;
    }
    get firstVisibleIndex() {
      const range2 = this.getVisibleRange(this.lastRenderTop, this.lastRenderHeight);
      return range2.start;
    }
    element(index) {
      return this.items[index].element;
    }
    indexOf(element) {
      return this.items.findIndex((item) => item.element === element);
    }
    domElement(index) {
      const row = this.items[index].row;
      return row && row.domNode;
    }
    elementHeight(index) {
      return this.items[index].size;
    }
    elementTop(index) {
      return this.rangeMap.positionAt(index);
    }
    indexAt(position) {
      return this.rangeMap.indexAt(position);
    }
    indexAfter(position) {
      return this.rangeMap.indexAfter(position);
    }
    layout(height, width2) {
      const scrollDimensions = {
        height: typeof height === "number" ? height : getContentHeight(this.domNode)
      };
      if (this.scrollableElementUpdateDisposable) {
        this.scrollableElementUpdateDisposable.dispose();
        this.scrollableElementUpdateDisposable = null;
        scrollDimensions.scrollHeight = this.scrollHeight;
      }
      this.scrollableElement.setScrollDimensions(scrollDimensions);
      if (typeof width2 !== "undefined") {
        this.renderWidth = width2;
        if (this.supportDynamicHeights) {
          this._rerender(this.scrollTop, this.renderHeight);
        }
      }
      if (this.horizontalScrolling) {
        this.scrollableElement.setScrollDimensions({
          width: typeof width2 === "number" ? width2 : getContentWidth(this.domNode)
        });
      }
    }
    // Render
    render(previousRenderRange, renderTop, renderHeight, renderLeft, scrollWidth, updateItemsInDOM = false, onScroll = false) {
      const renderRange = this.getRenderRange(renderTop, renderHeight);
      const rangesToInsert = Range$1.relativeComplement(renderRange, previousRenderRange).reverse();
      const rangesToRemove = Range$1.relativeComplement(previousRenderRange, renderRange);
      if (updateItemsInDOM) {
        const rangesToUpdate = Range$1.intersect(previousRenderRange, renderRange);
        for (let i2 = rangesToUpdate.start; i2 < rangesToUpdate.end; i2++) {
          this.updateItemInDOM(this.items[i2], i2);
        }
      }
      this.cache.transact(() => {
        for (const range2 of rangesToRemove) {
          for (let i2 = range2.start; i2 < range2.end; i2++) {
            this.removeItemFromDOM(i2, onScroll);
          }
        }
        for (const range2 of rangesToInsert) {
          for (let i2 = range2.end - 1; i2 >= range2.start; i2--) {
            this.insertItemInDOM(i2);
          }
        }
      });
      if (renderLeft !== void 0) {
        this.rowsContainer.style.left = `-${renderLeft}px`;
      }
      this.rowsContainer.style.top = `-${renderTop}px`;
      if (this.horizontalScrolling && scrollWidth !== void 0) {
        this.rowsContainer.style.width = `${Math.max(scrollWidth, this.renderWidth)}px`;
      }
      this.lastRenderTop = renderTop;
      this.lastRenderHeight = renderHeight;
    }
    // DOM operations
    insertItemInDOM(index, row) {
      const item = this.items[index];
      if (!item.row) {
        if (row) {
          item.row = row;
          item.stale = true;
        } else {
          const result = this.cache.alloc(item.templateId);
          item.row = result.row;
          item.stale ||= result.isReusingConnectedDomNode;
        }
      }
      const role = this.accessibilityProvider.getRole(item.element) || "listitem";
      item.row.domNode.setAttribute("role", role);
      const checked = this.accessibilityProvider.isChecked(item.element);
      const toAriaState = (value) => value === "mixed" ? "mixed" : String(!!value);
      if (typeof checked === "boolean" || checked === "mixed") {
        item.row.domNode.setAttribute("aria-checked", toAriaState(checked));
      } else if (checked) {
        const update = (value) => item.row.domNode.setAttribute("aria-checked", toAriaState(value));
        update(checked.value);
        item.checkedDisposable = checked.onDidChange(() => update(checked.value));
      }
      if (item.stale || !item.row.domNode.parentElement) {
        const referenceNode = this.items.at(index + 1)?.row?.domNode ?? null;
        if (item.row.domNode.parentElement !== this.rowsContainer || item.row.domNode.nextElementSibling !== referenceNode) {
          this.rowsContainer.insertBefore(item.row.domNode, referenceNode);
        }
        item.stale = false;
      }
      this.updateItemInDOM(item, index);
      const renderer = this.renderers.get(item.templateId);
      if (!renderer) {
        throw new Error(`No renderer found for template id ${item.templateId}`);
      }
      renderer?.renderElement(item.element, index, item.row.templateData, { height: item.size });
      const uri = this.dnd.getDragURI(item.element);
      item.dragStartDisposable.dispose();
      item.row.domNode.draggable = !!uri;
      if (uri) {
        item.dragStartDisposable = addDisposableListener(item.row.domNode, "dragstart", (event) => this.onDragStart(item.element, uri, event));
      }
      if (this.horizontalScrolling) {
        this.measureItemWidth(item);
        this.eventuallyUpdateScrollWidth();
      }
    }
    measureItemWidth(item) {
      if (!item.row || !item.row.domNode) {
        return;
      }
      item.row.domNode.style.width = "fit-content";
      item.width = getContentWidth(item.row.domNode);
      const style = getWindow(item.row.domNode).getComputedStyle(item.row.domNode);
      if (style.paddingLeft) {
        item.width += parseFloat(style.paddingLeft);
      }
      if (style.paddingRight) {
        item.width += parseFloat(style.paddingRight);
      }
      item.row.domNode.style.width = "";
    }
    updateItemInDOM(item, index) {
      item.row.domNode.style.top = `${this.elementTop(index)}px`;
      if (this.setRowHeight) {
        item.row.domNode.style.height = `${item.size}px`;
      }
      if (this.setRowLineHeight) {
        item.row.domNode.style.lineHeight = `${item.size}px`;
      }
      item.row.domNode.setAttribute("data-index", `${index}`);
      item.row.domNode.setAttribute("data-last-element", index === this.length - 1 ? "true" : "false");
      item.row.domNode.setAttribute("data-parity", index % 2 === 0 ? "even" : "odd");
      item.row.domNode.setAttribute("aria-setsize", String(this.accessibilityProvider.getSetSize(item.element, index, this.length)));
      item.row.domNode.setAttribute("aria-posinset", String(this.accessibilityProvider.getPosInSet(item.element, index)));
      item.row.domNode.setAttribute("id", this.getElementDomId(index));
      item.row.domNode.classList.toggle("drop-target", item.dropTarget);
    }
    removeItemFromDOM(index, onScroll) {
      const item = this.items[index];
      item.dragStartDisposable.dispose();
      item.checkedDisposable.dispose();
      if (item.row) {
        const renderer = this.renderers.get(item.templateId);
        if (renderer && renderer.disposeElement) {
          renderer.disposeElement(item.element, index, item.row.templateData, { height: item.size, onScroll });
        }
        this.cache.release(item.row);
        item.row = null;
      }
      if (this.horizontalScrolling) {
        this.eventuallyUpdateScrollWidth();
      }
    }
    getScrollTop() {
      const scrollPosition = this.scrollableElement.getScrollPosition();
      return scrollPosition.scrollTop;
    }
    setScrollTop(scrollTop, reuseAnimation) {
      if (this.scrollableElementUpdateDisposable) {
        this.scrollableElementUpdateDisposable.dispose();
        this.scrollableElementUpdateDisposable = null;
        this.scrollableElement.setScrollDimensions({ scrollHeight: this.scrollHeight });
      }
      this.scrollableElement.setScrollPosition({ scrollTop, reuseAnimation });
    }
    get scrollTop() {
      return this.getScrollTop();
    }
    set scrollTop(scrollTop) {
      this.setScrollTop(scrollTop);
    }
    get scrollHeight() {
      return this._scrollHeight + (this.horizontalScrolling ? 10 : 0) + this.paddingBottom;
    }
    // Events
    get onMouseClick() {
      return Event.map(this.disposables.add(new DomEmitter(this.domNode, "click")).event, (e) => this.toMouseEvent(e), this.disposables);
    }
    get onMouseDblClick() {
      return Event.map(this.disposables.add(new DomEmitter(this.domNode, "dblclick")).event, (e) => this.toMouseEvent(e), this.disposables);
    }
    get onMouseMiddleClick() {
      return Event.filter(Event.map(this.disposables.add(new DomEmitter(this.domNode, "auxclick")).event, (e) => this.toMouseEvent(e), this.disposables), (e) => e.browserEvent.button === 1, this.disposables);
    }
    get onMouseDown() {
      return Event.map(this.disposables.add(new DomEmitter(this.domNode, "mousedown")).event, (e) => this.toMouseEvent(e), this.disposables);
    }
    get onMouseOver() {
      return Event.map(this.disposables.add(new DomEmitter(this.domNode, "mouseover")).event, (e) => this.toMouseEvent(e), this.disposables);
    }
    get onMouseOut() {
      return Event.map(this.disposables.add(new DomEmitter(this.domNode, "mouseout")).event, (e) => this.toMouseEvent(e), this.disposables);
    }
    get onContextMenu() {
      return Event.any(Event.map(this.disposables.add(new DomEmitter(this.domNode, "contextmenu")).event, (e) => this.toMouseEvent(e), this.disposables), Event.map(this.disposables.add(new DomEmitter(this.domNode, EventType.Contextmenu)).event, (e) => this.toGestureEvent(e), this.disposables));
    }
    get onTouchStart() {
      return Event.map(this.disposables.add(new DomEmitter(this.domNode, "touchstart")).event, (e) => this.toTouchEvent(e), this.disposables);
    }
    get onTap() {
      return Event.map(this.disposables.add(new DomEmitter(this.rowsContainer, EventType.Tap)).event, (e) => this.toGestureEvent(e), this.disposables);
    }
    toMouseEvent(browserEvent) {
      const index = this.getItemIndexFromEventTarget(browserEvent.target || null);
      const item = typeof index === "undefined" ? void 0 : this.items[index];
      const element = item && item.element;
      return { browserEvent, index, element };
    }
    toTouchEvent(browserEvent) {
      const index = this.getItemIndexFromEventTarget(browserEvent.target || null);
      const item = typeof index === "undefined" ? void 0 : this.items[index];
      const element = item && item.element;
      return { browserEvent, index, element };
    }
    toGestureEvent(browserEvent) {
      const index = this.getItemIndexFromEventTarget(browserEvent.initialTarget || null);
      const item = typeof index === "undefined" ? void 0 : this.items[index];
      const element = item && item.element;
      return { browserEvent, index, element };
    }
    toDragEvent(browserEvent) {
      const index = this.getItemIndexFromEventTarget(browserEvent.target || null);
      const item = typeof index === "undefined" ? void 0 : this.items[index];
      const element = item && item.element;
      const sector = this.getTargetSector(browserEvent, index);
      return { browserEvent, index, element, sector };
    }
    onScroll(e) {
      try {
        const previousRenderRange = this.getRenderRange(this.lastRenderTop, this.lastRenderHeight);
        this.render(previousRenderRange, e.scrollTop, e.height, e.scrollLeft, e.scrollWidth, void 0, true);
        if (this.supportDynamicHeights) {
          this._rerender(e.scrollTop, e.height, e.inSmoothScrolling);
        }
      } catch (err) {
        console.error("Got bad scroll event:", e);
        throw err;
      }
    }
    onTouchChange(event) {
      event.preventDefault();
      event.stopPropagation();
      this.scrollTop -= event.translationY;
    }
    // DND
    onDragStart(element, uri, event) {
      if (!event.dataTransfer) {
        return;
      }
      const elements = this.dnd.getDragElements(element);
      event.dataTransfer.effectAllowed = "copyMove";
      event.dataTransfer.setData(DataTransfers.TEXT, uri);
      let label;
      if (this.dnd.getDragLabel) {
        label = this.dnd.getDragLabel(elements, event);
      }
      if (typeof label === "undefined") {
        label = String(elements.length);
      }
      applyDragImage(event, this.domNode, label, [
        this.domId
        /* add domId to get list specific styling */
      ]);
      this.domNode.classList.add("dragging");
      this.currentDragData = new ElementsDragAndDropData(elements);
      StaticDND.CurrentDragAndDropData = new ExternalElementsDragAndDropData(elements);
      this.dnd.onDragStart?.(this.currentDragData, event);
    }
    onPotentialSelectionStart(e) {
      this.currentSelectionDisposable.dispose();
      const doc = getDocument(this.domNode);
      const selectionStore = this.currentSelectionDisposable = new DisposableStore();
      const movementStore = selectionStore.add(new DisposableStore());
      movementStore.add(addDisposableListener(this.domNode, "selectstart", () => {
        movementStore.add(addDisposableListener(doc, "mousemove", (e2) => {
          if (doc.getSelection()?.isCollapsed === false) {
            this.setupDragAndDropScrollTopAnimation(e2);
          }
        }));
        selectionStore.add(toDisposable(() => {
          const previousRenderRange = this.getRenderRange(this.lastRenderTop, this.lastRenderHeight);
          this.currentSelectionBounds = void 0;
          this.render(previousRenderRange, this.lastRenderTop, this.lastRenderHeight, void 0, void 0);
        }));
        selectionStore.add(addDisposableListener(doc, "selectionchange", () => {
          const selection = doc.getSelection();
          if (!selection || selection.isCollapsed) {
            if (movementStore.isDisposed) {
              selectionStore.dispose();
            }
            return;
          }
          let start = this.getIndexOfListElement(selection.anchorNode);
          let end = this.getIndexOfListElement(selection.focusNode);
          if (start !== void 0 && end !== void 0) {
            if (end < start) {
              [start, end] = [end, start];
            }
            this.currentSelectionBounds = { start, end };
          }
        }));
      }));
      movementStore.add(addDisposableListener(doc, "mouseup", () => {
        movementStore.dispose();
        this.teardownDragAndDropScrollTopAnimation();
        if (doc.getSelection()?.isCollapsed !== false) {
          selectionStore.dispose();
        }
      }));
    }
    getIndexOfListElement(element) {
      if (!element || !this.domNode.contains(element)) {
        return void 0;
      }
      while (element && element !== this.domNode) {
        if (element.dataset?.index) {
          return Number(element.dataset.index);
        }
        element = element.parentElement;
      }
      return void 0;
    }
    onDragOver(event) {
      event.browserEvent.preventDefault();
      this.onDragLeaveTimeout.dispose();
      if (StaticDND.CurrentDragAndDropData && StaticDND.CurrentDragAndDropData.getData() === "vscode-ui") {
        return false;
      }
      this.setupDragAndDropScrollTopAnimation(event.browserEvent);
      if (!event.browserEvent.dataTransfer) {
        return false;
      }
      if (!this.currentDragData) {
        if (StaticDND.CurrentDragAndDropData) {
          this.currentDragData = StaticDND.CurrentDragAndDropData;
        } else {
          if (!event.browserEvent.dataTransfer.types) {
            return false;
          }
          this.currentDragData = new NativeDragAndDropData();
        }
      }
      const result = this.dnd.onDragOver(this.currentDragData, event.element, event.index, event.sector, event.browserEvent);
      this.canDrop = typeof result === "boolean" ? result : result.accept;
      if (!this.canDrop) {
        this.currentDragFeedback = void 0;
        this.currentDragFeedbackDisposable.dispose();
        return false;
      }
      event.browserEvent.dataTransfer.dropEffect = typeof result !== "boolean" && result.effect?.type === 0 ? "copy" : "move";
      let feedback;
      if (typeof result !== "boolean" && result.feedback) {
        feedback = result.feedback;
      } else {
        if (typeof event.index === "undefined") {
          feedback = [-1];
        } else {
          feedback = [event.index];
        }
      }
      feedback = distinct(feedback).filter((i2) => i2 >= -1 && i2 < this.length).sort((a, b) => a - b);
      feedback = feedback[0] === -1 ? [-1] : feedback;
      let dragOverEffectPosition = typeof result !== "boolean" && result.effect && result.effect.position ? result.effect.position : "drop-target";
      if (equalsDragFeedback(this.currentDragFeedback, feedback) && this.currentDragFeedbackPosition === dragOverEffectPosition) {
        return true;
      }
      this.currentDragFeedback = feedback;
      this.currentDragFeedbackPosition = dragOverEffectPosition;
      this.currentDragFeedbackDisposable.dispose();
      if (feedback[0] === -1) {
        this.domNode.classList.add(dragOverEffectPosition);
        this.rowsContainer.classList.add(dragOverEffectPosition);
        this.currentDragFeedbackDisposable = toDisposable(() => {
          this.domNode.classList.remove(dragOverEffectPosition);
          this.rowsContainer.classList.remove(dragOverEffectPosition);
        });
      } else {
        if (feedback.length > 1 && dragOverEffectPosition !== "drop-target") {
          throw new Error("Can't use multiple feedbacks with position different than 'over'");
        }
        if (dragOverEffectPosition === "drop-target-after") {
          if (feedback[0] < this.length - 1) {
            feedback[0] += 1;
            dragOverEffectPosition = "drop-target-before";
          }
        }
        for (const index of feedback) {
          const item = this.items[index];
          item.dropTarget = true;
          item.row?.domNode.classList.add(dragOverEffectPosition);
        }
        this.currentDragFeedbackDisposable = toDisposable(() => {
          for (const index of feedback) {
            const item = this.items[index];
            item.dropTarget = false;
            item.row?.domNode.classList.remove(dragOverEffectPosition);
          }
        });
      }
      return true;
    }
    onDragLeave(event) {
      this.onDragLeaveTimeout.dispose();
      this.onDragLeaveTimeout = disposableTimeout(() => this.clearDragOverFeedback(), 100, this.disposables);
      if (this.currentDragData) {
        this.dnd.onDragLeave?.(this.currentDragData, event.element, event.index, event.browserEvent);
      }
    }
    onDrop(event) {
      if (!this.canDrop) {
        return;
      }
      const dragData = this.currentDragData;
      this.teardownDragAndDropScrollTopAnimation();
      this.clearDragOverFeedback();
      this.domNode.classList.remove("dragging");
      this.currentDragData = void 0;
      StaticDND.CurrentDragAndDropData = void 0;
      if (!dragData || !event.browserEvent.dataTransfer) {
        return;
      }
      event.browserEvent.preventDefault();
      dragData.update(event.browserEvent.dataTransfer);
      this.dnd.drop(dragData, event.element, event.index, event.sector, event.browserEvent);
    }
    onDragEnd(event) {
      this.canDrop = false;
      this.teardownDragAndDropScrollTopAnimation();
      this.clearDragOverFeedback();
      this.domNode.classList.remove("dragging");
      this.currentDragData = void 0;
      StaticDND.CurrentDragAndDropData = void 0;
      this.dnd.onDragEnd?.(event);
    }
    clearDragOverFeedback() {
      this.currentDragFeedback = void 0;
      this.currentDragFeedbackPosition = void 0;
      this.currentDragFeedbackDisposable.dispose();
      this.currentDragFeedbackDisposable = Disposable.None;
    }
    // DND scroll top animation
    setupDragAndDropScrollTopAnimation(event) {
      if (!this.dragOverAnimationDisposable) {
        const viewTop = getTopLeftOffset(this.domNode).top;
        this.dragOverAnimationDisposable = animate(getWindow(this.domNode), this.animateDragAndDropScrollTop.bind(this, viewTop));
      }
      this.dragOverAnimationStopDisposable.dispose();
      this.dragOverAnimationStopDisposable = disposableTimeout(() => {
        if (this.dragOverAnimationDisposable) {
          this.dragOverAnimationDisposable.dispose();
          this.dragOverAnimationDisposable = void 0;
        }
      }, 1e3, this.disposables);
      this.dragOverMouseY = event.pageY;
    }
    animateDragAndDropScrollTop(viewTop) {
      if (this.dragOverMouseY === void 0) {
        return;
      }
      const diff = this.dragOverMouseY - viewTop;
      const upperLimit = this.renderHeight - 35;
      if (diff < 35) {
        this.scrollTop += Math.max(-14, Math.floor(0.3 * (diff - 35)));
      } else if (diff > upperLimit) {
        this.scrollTop += Math.min(14, Math.floor(0.3 * (diff - upperLimit)));
      }
    }
    teardownDragAndDropScrollTopAnimation() {
      this.dragOverAnimationStopDisposable.dispose();
      if (this.dragOverAnimationDisposable) {
        this.dragOverAnimationDisposable.dispose();
        this.dragOverAnimationDisposable = void 0;
      }
    }
    // Util
    getTargetSector(browserEvent, targetIndex) {
      if (targetIndex === void 0) {
        return void 0;
      }
      const relativePosition = browserEvent.offsetY / this.items[targetIndex].size;
      const sector = Math.floor(relativePosition / 0.25);
      return clamp(sector, 0, 3);
    }
    getItemIndexFromEventTarget(target) {
      const scrollableElement = this.scrollableElement.getDomNode();
      let element = target;
      while ((isHTMLElement(element) || isSVGElement(element)) && element !== this.rowsContainer && scrollableElement.contains(element)) {
        const rawIndex = element.getAttribute("data-index");
        if (rawIndex) {
          const index = Number(rawIndex);
          if (!isNaN(index)) {
            return index;
          }
        }
        element = element.parentElement;
      }
      return void 0;
    }
    getVisibleRange(renderTop, renderHeight) {
      return {
        start: this.rangeMap.indexAt(renderTop),
        end: this.rangeMap.indexAfter(renderTop + renderHeight - 1)
      };
    }
    getRenderRange(renderTop, renderHeight) {
      const range2 = this.getVisibleRange(renderTop, renderHeight);
      if (this.currentSelectionBounds) {
        const max = this.rangeMap.count;
        range2.start = Math.min(range2.start, this.currentSelectionBounds.start, max);
        range2.end = Math.min(Math.max(range2.end, this.currentSelectionBounds.end + 1), max);
      }
      return range2;
    }
    /**
     * Given a stable rendered state, checks every rendered element whether it needs
     * to be probed for dynamic height. Adjusts scroll height and top if necessary.
     */
    _rerender(renderTop, renderHeight, inSmoothScrolling) {
      const previousRenderRange = this.getRenderRange(renderTop, renderHeight);
      let anchorElementIndex;
      let anchorElementTopDelta;
      if (renderTop === this.elementTop(previousRenderRange.start)) {
        anchorElementIndex = previousRenderRange.start;
        anchorElementTopDelta = 0;
      } else if (previousRenderRange.end - previousRenderRange.start > 1) {
        anchorElementIndex = previousRenderRange.start + 1;
        anchorElementTopDelta = this.elementTop(anchorElementIndex) - renderTop;
      }
      let heightDiff2 = 0;
      while (true) {
        const renderRange = this.getRenderRange(renderTop, renderHeight);
        let didChange = false;
        for (let i2 = renderRange.start; i2 < renderRange.end; i2++) {
          const diff = this.probeDynamicHeight(i2);
          if (diff !== 0) {
            this.rangeMap.splice(i2, 1, [this.items[i2]]);
          }
          heightDiff2 += diff;
          didChange = didChange || diff !== 0;
        }
        if (!didChange) {
          if (heightDiff2 !== 0) {
            this.eventuallyUpdateScrollDimensions();
          }
          const unrenderRanges = Range$1.relativeComplement(previousRenderRange, renderRange);
          for (const range2 of unrenderRanges) {
            for (let i2 = range2.start; i2 < range2.end; i2++) {
              if (this.items[i2].row) {
                this.removeItemFromDOM(i2);
              }
            }
          }
          const renderRanges = Range$1.relativeComplement(renderRange, previousRenderRange).reverse();
          for (const range2 of renderRanges) {
            for (let i2 = range2.end - 1; i2 >= range2.start; i2--) {
              this.insertItemInDOM(i2);
            }
          }
          for (let i2 = renderRange.start; i2 < renderRange.end; i2++) {
            if (this.items[i2].row) {
              this.updateItemInDOM(this.items[i2], i2);
            }
          }
          if (typeof anchorElementIndex === "number") {
            const deltaScrollTop = this.scrollable.getFutureScrollPosition().scrollTop - renderTop;
            const newScrollTop = this.elementTop(anchorElementIndex) - anchorElementTopDelta + deltaScrollTop;
            this.setScrollTop(newScrollTop, inSmoothScrolling);
          }
          this._onDidChangeContentHeight.fire(this.contentHeight);
          return;
        }
      }
    }
    probeDynamicHeight(index) {
      const item = this.items[index];
      if (!!this.virtualDelegate.getDynamicHeight) {
        const newSize = this.virtualDelegate.getDynamicHeight(item.element);
        if (newSize !== null) {
          const size3 = item.size;
          item.size = newSize;
          item.lastDynamicHeightWidth = this.renderWidth;
          return newSize - size3;
        }
      }
      if (!item.hasDynamicHeight || item.lastDynamicHeightWidth === this.renderWidth) {
        return 0;
      }
      if (!!this.virtualDelegate.hasDynamicHeight && !this.virtualDelegate.hasDynamicHeight(item.element)) {
        return 0;
      }
      const size2 = item.size;
      if (item.row) {
        item.row.domNode.style.height = "";
        item.size = item.row.domNode.offsetHeight;
        if (item.size === 0 && !isAncestor$1(item.row.domNode, getWindow(item.row.domNode).document.body)) {
          console.warn("Measuring item node that is not in DOM! Add ListView to the DOM before measuring row height!", new Error().stack);
        }
        item.lastDynamicHeightWidth = this.renderWidth;
        return item.size - size2;
      }
      const { row } = this.cache.alloc(item.templateId);
      row.domNode.style.height = "";
      this.rowsContainer.appendChild(row.domNode);
      const renderer = this.renderers.get(item.templateId);
      if (!renderer) {
        throw new BugIndicatingError("Missing renderer for templateId: " + item.templateId);
      }
      renderer.renderElement(item.element, index, row.templateData);
      item.size = row.domNode.offsetHeight;
      renderer.disposeElement?.(item.element, index, row.templateData);
      this.virtualDelegate.setDynamicHeight?.(item.element, item.size);
      item.lastDynamicHeightWidth = this.renderWidth;
      row.domNode.remove();
      this.cache.release(row);
      return item.size - size2;
    }
    getElementDomId(index) {
      return `${this.domId}_${index}`;
    }
    // Dispose
    dispose() {
      for (const item of this.items) {
        item.dragStartDisposable.dispose();
        item.checkedDisposable.dispose();
        if (item.row) {
          const renderer = this.renderers.get(item.row.templateId);
          if (renderer) {
            renderer.disposeElement?.(item.element, -1, item.row.templateData, void 0);
            renderer.disposeTemplate(item.row.templateData);
          }
        }
      }
      this.items = [];
      this.domNode?.remove();
      this.dragOverAnimationDisposable?.dispose();
      this.disposables.dispose();
    }
  };
  _ListView.InstanceCount = 0;
  let ListView = _ListView;
  __decorate$2J([
    memoize
  ], ListView.prototype, "onMouseClick", null);
  __decorate$2J([
    memoize
  ], ListView.prototype, "onMouseDblClick", null);
  __decorate$2J([
    memoize
  ], ListView.prototype, "onMouseMiddleClick", null);
  __decorate$2J([
    memoize
  ], ListView.prototype, "onMouseDown", null);
  __decorate$2J([
    memoize
  ], ListView.prototype, "onMouseOver", null);
  __decorate$2J([
    memoize
  ], ListView.prototype, "onMouseOut", null);
  __decorate$2J([
    memoize
  ], ListView.prototype, "onContextMenu", null);
  __decorate$2J([
    memoize
  ], ListView.prototype, "onTouchStart", null);
  __decorate$2J([
    memoize
  ], ListView.prototype, "onTap", null);
  var __decorate$2I = 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;
  };
  class TraitRenderer {
    constructor(trait) {
      this.trait = trait;
      this.renderedElements = [];
    }
    get templateId() {
      return `template:${this.trait.name}`;
    }
    renderTemplate(container) {
      return container;
    }
    renderElement(element, index, templateData) {
      const renderedElementIndex = this.renderedElements.findIndex((el) => el.templateData === templateData);
      if (renderedElementIndex >= 0) {
        const rendered = this.renderedElements[renderedElementIndex];
        this.trait.unrender(templateData);
        rendered.index = index;
      } else {
        const rendered = { index, templateData };
        this.renderedElements.push(rendered);
      }
      this.trait.renderIndex(index, templateData);
    }
    splice(start, deleteCount, insertCount) {
      const rendered = [];
      for (const renderedElement of this.renderedElements) {
        if (renderedElement.index < start) {
          rendered.push(renderedElement);
        } else if (renderedElement.index >= start + deleteCount) {
          rendered.push({
            index: renderedElement.index + insertCount - deleteCount,
            templateData: renderedElement.templateData
          });
        }
      }
      this.renderedElements = rendered;
    }
    renderIndexes(indexes) {
      for (const { index, templateData } of this.renderedElements) {
        if (indexes.indexOf(index) > -1) {
          this.trait.renderIndex(index, templateData);
        }
      }
    }
    disposeTemplate(templateData) {
      const index = this.renderedElements.findIndex((el) => el.templateData === templateData);
      if (index < 0) {
        return;
      }
      this.renderedElements.splice(index, 1);
    }
  }
  let Trait$1 = class Trait {
    get onChange() {
      return this._onChange.event;
    }
    get name() {
      return this._trait;
    }
    get renderer() {
      return new TraitRenderer(this);
    }
    constructor(_trait) {
      this._trait = _trait;
      this.indexes = [];
      this.sortedIndexes = [];
      this._onChange = new Emitter$1();
    }
    splice(start, deleteCount, elements) {
      const diff = elements.length - deleteCount;
      const end = start + deleteCount;
      const sortedIndexes = [];
      let i2 = 0;
      while (i2 < this.sortedIndexes.length && this.sortedIndexes[i2] < start) {
        sortedIndexes.push(this.sortedIndexes[i2++]);
      }
      for (let j = 0; j < elements.length; j++) {
        if (elements[j]) {
          sortedIndexes.push(j + start);
        }
      }
      while (i2 < this.sortedIndexes.length && this.sortedIndexes[i2] >= end) {
        sortedIndexes.push(this.sortedIndexes[i2++] + diff);
      }
      this.renderer.splice(start, deleteCount, elements.length);
      this._set(sortedIndexes, sortedIndexes);
    }
    renderIndex(index, container) {
      container.classList.toggle(this._trait, this.contains(index));
    }
    unrender(container) {
      container.classList.remove(this._trait);
    }
    /**
     * Sets the indexes which should have this trait.
     *
     * @param indexes Indexes which should have this trait.
     * @return The old indexes which had this trait.
     */
    set(indexes, browserEvent) {
      return this._set(indexes, [...indexes].sort(numericSort), browserEvent);
    }
    _set(indexes, sortedIndexes, browserEvent) {
      const result = this.indexes;
      const sortedResult = this.sortedIndexes;
      this.indexes = indexes;
      this.sortedIndexes = sortedIndexes;
      const toRender = disjunction(sortedResult, indexes);
      this.renderer.renderIndexes(toRender);
      this._onChange.fire({ indexes, browserEvent });
      return result;
    }
    get() {
      return this.indexes;
    }
    contains(index) {
      return binarySearch(this.sortedIndexes, index, numericSort) >= 0;
    }
    dispose() {
      dispose(this._onChange);
    }
  };
  __decorate$2I([
    memoize
  ], Trait$1.prototype, "renderer", null);
  class SelectionTrait extends Trait$1 {
    constructor(setAriaSelected) {
      super("selected");
      this.setAriaSelected = setAriaSelected;
    }
    renderIndex(index, container) {
      super.renderIndex(index, container);
      if (this.setAriaSelected) {
        if (this.contains(index)) {
          container.setAttribute("aria-selected", "true");
        } else {
          container.setAttribute("aria-selected", "false");
        }
      }
    }
  }
  class TraitSpliceable {
    constructor(trait, view, identityProvider) {
      this.trait = trait;
      this.view = view;
      this.identityProvider = identityProvider;
    }
    splice(start, deleteCount, elements) {
      if (!this.identityProvider) {
        return this.trait.splice(start, deleteCount, new Array(elements.length).fill(false));
      }
      const pastElementsWithTrait = this.trait.get().map((i2) => this.identityProvider.getId(this.view.element(i2)).toString());
      if (pastElementsWithTrait.length === 0) {
        return this.trait.splice(start, deleteCount, new Array(elements.length).fill(false));
      }
      const pastElementsWithTraitSet = new Set(pastElementsWithTrait);
      const elementsWithTrait = elements.map((e) => pastElementsWithTraitSet.has(this.identityProvider.getId(e).toString()));
      this.trait.splice(start, deleteCount, elementsWithTrait);
    }
  }
  function isListElementDescendantOfClass(e, className2) {
    if (e.classList.contains(className2)) {
      return true;
    }
    if (e.classList.contains("monaco-list")) {
      return false;
    }
    if (!e.parentElement) {
      return false;
    }
    return isListElementDescendantOfClass(e.parentElement, className2);
  }
  function isMonacoEditor(e) {
    return isListElementDescendantOfClass(e, "monaco-editor");
  }
  function isMonacoCustomToggle(e) {
    return isListElementDescendantOfClass(e, "monaco-custom-toggle");
  }
  function isActionItem(e) {
    return isListElementDescendantOfClass(e, "action-item");
  }
  function isStickyScrollElement(e) {
    return isListElementDescendantOfClass(e, "monaco-tree-sticky-row");
  }
  function isStickyScrollContainer(e) {
    return e.classList.contains("monaco-tree-sticky-container");
  }
  function isButton(e) {
    if (e.tagName === "A" && e.classList.contains("monaco-button") || e.tagName === "DIV" && e.classList.contains("monaco-button-dropdown")) {
      return true;
    }
    if (e.classList.contains("monaco-list")) {
      return false;
    }
    if (!e.parentElement) {
      return false;
    }
    return isButton(e.parentElement);
  }
  class KeyboardController {
    get onKeyDown() {
      return Event.chain(this.disposables.add(new DomEmitter(this.view.domNode, "keydown")).event, ($2) => $2.filter((e) => !isEditableElement(e.target)).map((e) => new StandardKeyboardEvent(e)));
    }
    constructor(list2, view, options) {
      this.list = list2;
      this.view = view;
      this.disposables = new DisposableStore();
      this.multipleSelectionDisposables = new DisposableStore();
      this.multipleSelectionSupport = options.multipleSelectionSupport;
      this.disposables.add(this.onKeyDown((e) => {
        switch (e.keyCode) {
          case 3:
            return this.onEnter(e);
          case 16:
            return this.onUpArrow(e);
          case 18:
            return this.onDownArrow(e);
          case 11:
            return this.onPageUpArrow(e);
          case 12:
            return this.onPageDownArrow(e);
          case 9:
            return this.onEscape(e);
          case 31:
            if (this.multipleSelectionSupport && (isMacintosh ? e.metaKey : e.ctrlKey)) {
              this.onCtrlA(e);
            }
        }
      }));
    }
    updateOptions(optionsUpdate) {
      if (optionsUpdate.multipleSelectionSupport !== void 0) {
        this.multipleSelectionSupport = optionsUpdate.multipleSelectionSupport;
      }
    }
    onEnter(e) {
      e.preventDefault();
      e.stopPropagation();
      this.list.setSelection(this.list.getFocus(), e.browserEvent);
    }
    onUpArrow(e) {
      e.preventDefault();
      e.stopPropagation();
      this.list.focusPrevious(1, false, e.browserEvent);
      const el = this.list.getFocus()[0];
      this.list.setAnchor(el);
      this.list.reveal(el);
      this.view.domNode.focus();
    }
    onDownArrow(e) {
      e.preventDefault();
      e.stopPropagation();
      this.list.focusNext(1, false, e.browserEvent);
      const el = this.list.getFocus()[0];
      this.list.setAnchor(el);
      this.list.reveal(el);
      this.view.domNode.focus();
    }
    onPageUpArrow(e) {
      e.preventDefault();
      e.stopPropagation();
      this.list.focusPreviousPage(e.browserEvent);
      const el = this.list.getFocus()[0];
      this.list.setAnchor(el);
      this.list.reveal(el);
      this.view.domNode.focus();
    }
    onPageDownArrow(e) {
      e.preventDefault();
      e.stopPropagation();
      this.list.focusNextPage(e.browserEvent);
      const el = this.list.getFocus()[0];
      this.list.setAnchor(el);
      this.list.reveal(el);
      this.view.domNode.focus();
    }
    onCtrlA(e) {
      e.preventDefault();
      e.stopPropagation();
      this.list.setSelection(range(this.list.length), e.browserEvent);
      this.list.setAnchor(void 0);
      this.view.domNode.focus();
    }
    onEscape(e) {
      if (this.list.getSelection().length) {
        e.preventDefault();
        e.stopPropagation();
        this.list.setSelection([], e.browserEvent);
        this.list.setAnchor(void 0);
        this.view.domNode.focus();
      }
    }
    dispose() {
      this.disposables.dispose();
      this.multipleSelectionDisposables.dispose();
    }
  }
  __decorate$2I([
    memoize
  ], KeyboardController.prototype, "onKeyDown", null);
  var TypeNavigationMode;
  (function(TypeNavigationMode2) {
    TypeNavigationMode2[TypeNavigationMode2["Automatic"] = 0] = "Automatic";
    TypeNavigationMode2[TypeNavigationMode2["Trigger"] = 1] = "Trigger";
  })(TypeNavigationMode || (TypeNavigationMode = {}));
  var TypeNavigationControllerState;
  (function(TypeNavigationControllerState2) {
    TypeNavigationControllerState2[TypeNavigationControllerState2["Idle"] = 0] = "Idle";
    TypeNavigationControllerState2[TypeNavigationControllerState2["Typing"] = 1] = "Typing";
  })(TypeNavigationControllerState || (TypeNavigationControllerState = {}));
  const DefaultKeyboardNavigationDelegate = new class {
    mightProducePrintableCharacter(event) {
      if (event.ctrlKey || event.metaKey || event.altKey) {
        return false;
      }
      return event.keyCode >= 31 && event.keyCode <= 56 || event.keyCode >= 21 && event.keyCode <= 30 || event.keyCode >= 98 && event.keyCode <= 107 || event.keyCode >= 85 && event.keyCode <= 95;
    }
  }();
  class TypeNavigationController {
    constructor(list2, view, keyboardNavigationLabelProvider, keyboardNavigationEventFilter, delegate) {
      this.list = list2;
      this.view = view;
      this.keyboardNavigationLabelProvider = keyboardNavigationLabelProvider;
      this.keyboardNavigationEventFilter = keyboardNavigationEventFilter;
      this.delegate = delegate;
      this.enabled = false;
      this.state = TypeNavigationControllerState.Idle;
      this.mode = TypeNavigationMode.Automatic;
      this.triggered = false;
      this.previouslyFocused = -1;
      this.enabledDisposables = new DisposableStore();
      this.disposables = new DisposableStore();
      this.updateOptions(list2.options);
    }
    updateOptions(options) {
      if (options.typeNavigationEnabled ?? true) {
        this.enable();
      } else {
        this.disable();
      }
      this.mode = options.typeNavigationMode ?? TypeNavigationMode.Automatic;
    }
    enable() {
      if (this.enabled) {
        return;
      }
      let typing = false;
      const onChar = Event.chain(this.enabledDisposables.add(new DomEmitter(this.view.domNode, "keydown")).event, ($2) => $2.filter((e) => !isEditableElement(e.target)).filter(() => this.mode === TypeNavigationMode.Automatic || this.triggered).map((event) => new StandardKeyboardEvent(event)).filter((e) => typing || this.keyboardNavigationEventFilter(e)).filter((e) => this.delegate.mightProducePrintableCharacter(e)).forEach((e) => EventHelper.stop(e, true)).map((event) => event.browserEvent.key));
      const onClear = Event.debounce(onChar, () => null, 800, void 0, void 0, void 0, this.enabledDisposables);
      const onInput = Event.reduce(Event.any(onChar, onClear), (r, i2) => i2 === null ? null : (r || "") + i2, void 0, this.enabledDisposables);
      onInput(this.onInput, this, this.enabledDisposables);
      onClear(this.onClear, this, this.enabledDisposables);
      onChar(() => typing = true, void 0, this.enabledDisposables);
      onClear(() => typing = false, void 0, this.enabledDisposables);
      this.enabled = true;
      this.triggered = false;
    }
    disable() {
      if (!this.enabled) {
        return;
      }
      this.enabledDisposables.clear();
      this.enabled = false;
      this.triggered = false;
    }
    onClear() {
      const focus = this.list.getFocus();
      if (focus.length > 0 && focus[0] === this.previouslyFocused) {
        const ariaLabel = this.list.options.accessibilityProvider?.getAriaLabel(this.list.element(focus[0]));
        if (typeof ariaLabel === "string") {
          alert(ariaLabel);
        } else if (ariaLabel) {
          alert(ariaLabel.get());
        }
      }
      this.previouslyFocused = -1;
    }
    onInput(word) {
      if (!word) {
        this.state = TypeNavigationControllerState.Idle;
        this.triggered = false;
        return;
      }
      const focus = this.list.getFocus();
      const start = focus.length > 0 ? focus[0] : 0;
      const delta = this.state === TypeNavigationControllerState.Idle ? 1 : 0;
      this.state = TypeNavigationControllerState.Typing;
      for (let i2 = 0; i2 < this.list.length; i2++) {
        const index = (start + i2 + delta) % this.list.length;
        const label = this.keyboardNavigationLabelProvider.getKeyboardNavigationLabel(this.view.element(index));
        const labelStr = label && label.toString();
        if (this.list.options.typeNavigationEnabled) {
          if (typeof labelStr !== "undefined") {
            if (matchesPrefix(word, labelStr)) {
              this.previouslyFocused = start;
              this.list.setFocus([index]);
              this.list.reveal(index);
              return;
            }
            const fuzzy = matchesFuzzy2(word, labelStr);
            if (fuzzy) {
              const fuzzyScore2 = fuzzy[0].end - fuzzy[0].start;
              if (fuzzyScore2 > 1 && fuzzy.length === 1) {
                this.previouslyFocused = start;
                this.list.setFocus([index]);
                this.list.reveal(index);
                return;
              }
            }
          }
        } else if (typeof labelStr === "undefined" || matchesPrefix(word, labelStr)) {
          this.previouslyFocused = start;
          this.list.setFocus([index]);
          this.list.reveal(index);
          return;
        }
      }
    }
    dispose() {
      this.disable();
      this.enabledDisposables.dispose();
      this.disposables.dispose();
    }
  }
  class DOMFocusController {
    constructor(list2, view) {
      this.list = list2;
      this.view = view;
      this.disposables = new DisposableStore();
      const onKeyDown = Event.chain(this.disposables.add(new DomEmitter(view.domNode, "keydown")).event, ($2) => $2.filter((e) => !isEditableElement(e.target)).map((e) => new StandardKeyboardEvent(e)));
      const onTab = Event.chain(onKeyDown, ($2) => $2.filter((e) => e.keyCode === 2 && !e.ctrlKey && !e.metaKey && !e.shiftKey && !e.altKey));
      onTab(this.onTab, this, this.disposables);
    }
    onTab(e) {
      if (e.target !== this.view.domNode) {
        return;
      }
      const focus = this.list.getFocus();
      if (focus.length === 0) {
        return;
      }
      const focusedDomElement = this.view.domElement(focus[0]);
      if (!focusedDomElement) {
        return;
      }
      const tabIndexElement = focusedDomElement.querySelector("[tabIndex]");
      if (!tabIndexElement || !isHTMLElement(tabIndexElement) || tabIndexElement.tabIndex === -1) {
        return;
      }
      const style = getWindow(tabIndexElement).getComputedStyle(tabIndexElement);
      if (style.visibility === "hidden" || style.display === "none") {
        return;
      }
      e.preventDefault();
      e.stopPropagation();
      tabIndexElement.focus();
    }
    dispose() {
      this.disposables.dispose();
    }
  }
  function isSelectionSingleChangeEvent(event) {
    return isMacintosh ? event.browserEvent.metaKey : event.browserEvent.ctrlKey;
  }
  function isSelectionRangeChangeEvent(event) {
    return event.browserEvent.shiftKey;
  }
  function isMouseRightClick(event) {
    return isMouseEvent(event) && event.button === 2;
  }
  const DefaultMultipleSelectionController = {
    isSelectionSingleChangeEvent,
    isSelectionRangeChangeEvent
  };
  class MouseController {
    get onPointer() {
      return this._onPointer.event;
    }
    constructor(list2) {
      this.list = list2;
      this.disposables = new DisposableStore();
      this._onPointer = this.disposables.add(new Emitter$1());
      if (list2.options.multipleSelectionSupport !== false) {
        this.multipleSelectionController = this.list.options.multipleSelectionController || DefaultMultipleSelectionController;
      }
      this.mouseSupport = typeof list2.options.mouseSupport === "undefined" || !!list2.options.mouseSupport;
      if (this.mouseSupport) {
        list2.onMouseDown(this.onMouseDown, this, this.disposables);
        list2.onContextMenu(this.onContextMenu, this, this.disposables);
        list2.onMouseDblClick(this.onDoubleClick, this, this.disposables);
        list2.onTouchStart(this.onMouseDown, this, this.disposables);
        this.disposables.add(Gesture.addTarget(list2.getHTMLElement()));
      }
      Event.any(list2.onMouseClick, list2.onMouseMiddleClick, list2.onTap)(this.onViewPointer, this, this.disposables);
    }
    updateOptions(optionsUpdate) {
      if (optionsUpdate.multipleSelectionSupport !== void 0) {
        this.multipleSelectionController = void 0;
        if (optionsUpdate.multipleSelectionSupport) {
          this.multipleSelectionController = this.list.options.multipleSelectionController || DefaultMultipleSelectionController;
        }
      }
    }
    isSelectionSingleChangeEvent(event) {
      if (!this.multipleSelectionController) {
        return false;
      }
      return this.multipleSelectionController.isSelectionSingleChangeEvent(event);
    }
    isSelectionRangeChangeEvent(event) {
      if (!this.multipleSelectionController) {
        return false;
      }
      return this.multipleSelectionController.isSelectionRangeChangeEvent(event);
    }
    isSelectionChangeEvent(event) {
      return this.isSelectionSingleChangeEvent(event) || this.isSelectionRangeChangeEvent(event);
    }
    onMouseDown(e) {
      if (isMonacoEditor(e.browserEvent.target)) {
        return;
      }
      if (getActiveElement() !== e.browserEvent.target) {
        this.list.domFocus();
      }
    }
    onContextMenu(e) {
      if (isEditableElement(e.browserEvent.target) || isMonacoEditor(e.browserEvent.target)) {
        return;
      }
      const focus = typeof e.index === "undefined" ? [] : [e.index];
      this.list.setFocus(focus, e.browserEvent);
    }
    onViewPointer(e) {
      if (!this.mouseSupport) {
        return;
      }
      if (isEditableElement(e.browserEvent.target) || isMonacoEditor(e.browserEvent.target)) {
        return;
      }
      if (e.browserEvent.isHandledByList) {
        return;
      }
      e.browserEvent.isHandledByList = true;
      const focus = e.index;
      if (typeof focus === "undefined") {
        this.list.setFocus([], e.browserEvent);
        this.list.setSelection([], e.browserEvent);
        this.list.setAnchor(void 0);
        return;
      }
      if (this.isSelectionChangeEvent(e)) {
        return this.changeSelection(e);
      }
      this.list.setFocus([focus], e.browserEvent);
      this.list.setAnchor(focus);
      if (!isMouseRightClick(e.browserEvent)) {
        this.list.setSelection([focus], e.browserEvent);
      }
      this._onPointer.fire(e);
    }
    onDoubleClick(e) {
      if (isEditableElement(e.browserEvent.target) || isMonacoEditor(e.browserEvent.target)) {
        return;
      }
      if (this.isSelectionChangeEvent(e)) {
        return;
      }
      if (e.browserEvent.isHandledByList) {
        return;
      }
      e.browserEvent.isHandledByList = true;
      const focus = this.list.getFocus();
      this.list.setSelection(focus, e.browserEvent);
    }
    changeSelection(e) {
      const focus = e.index;
      let anchor = this.list.getAnchor();
      if (this.isSelectionRangeChangeEvent(e)) {
        if (typeof anchor === "undefined") {
          const currentFocus = this.list.getFocus()[0];
          anchor = currentFocus ?? focus;
          this.list.setAnchor(anchor);
        }
        const min = Math.min(anchor, focus);
        const max = Math.max(anchor, focus);
        const rangeSelection = range(min, max + 1);
        const selection = this.list.getSelection();
        const contiguousRange = getContiguousRangeContaining(disjunction(selection, [anchor]), anchor);
        if (contiguousRange.length === 0) {
          return;
        }
        const newSelection = disjunction(rangeSelection, relativeComplement(selection, contiguousRange));
        this.list.setSelection(newSelection, e.browserEvent);
        this.list.setFocus([focus], e.browserEvent);
      } else if (this.isSelectionSingleChangeEvent(e)) {
        const selection = this.list.getSelection();
        const newSelection = selection.filter((i2) => i2 !== focus);
        this.list.setFocus([focus]);
        this.list.setAnchor(focus);
        if (selection.length === newSelection.length) {
          this.list.setSelection([...newSelection, focus], e.browserEvent);
        } else {
          this.list.setSelection(newSelection, e.browserEvent);
        }
      }
    }
    dispose() {
      this.disposables.dispose();
    }
  }
  class DefaultStyleController {
    constructor(styleElement, selectorSuffix) {
      this.styleElement = styleElement;
      this.selectorSuffix = selectorSuffix;
    }
    style(styles) {
      const suffix = this.selectorSuffix && `.${this.selectorSuffix}`;
      const content = [];
      if (styles.listBackground) {
        content.push(`.monaco-list${suffix} .monaco-list-rows { background: ${styles.listBackground}; }`);
      }
      if (styles.listFocusBackground) {
        content.push(`.monaco-list${suffix}:focus .monaco-list-row.focused { background-color: ${styles.listFocusBackground}; }`);
        content.push(`.monaco-list${suffix}:focus .monaco-list-row.focused:hover { background-color: ${styles.listFocusBackground}; }`);
      }
      if (styles.listFocusForeground) {
        content.push(`.monaco-list${suffix}:focus .monaco-list-row.focused { color: ${styles.listFocusForeground}; }`);
      }
      if (styles.listActiveSelectionBackground) {
        content.push(`.monaco-list${suffix}:focus .monaco-list-row.selected { background-color: ${styles.listActiveSelectionBackground}; }`);
        content.push(`.monaco-list${suffix}:focus .monaco-list-row.selected:hover { background-color: ${styles.listActiveSelectionBackground}; }`);
      }
      if (styles.listActiveSelectionForeground) {
        content.push(`.monaco-list${suffix}:focus .monaco-list-row.selected { color: ${styles.listActiveSelectionForeground}; }`);
      }
      if (styles.listActiveSelectionIconForeground) {
        content.push(`.monaco-list${suffix}:focus .monaco-list-row.selected .codicon { color: ${styles.listActiveSelectionIconForeground}; }`);
      }
      if (styles.listFocusAndSelectionBackground) {
        content.push(`
				.monaco-drag-image${suffix},
				.monaco-list${suffix}:focus .monaco-list-row.selected.focused { background-color: ${styles.listFocusAndSelectionBackground}; }
			`);
      }
      if (styles.listFocusAndSelectionForeground) {
        content.push(`
				.monaco-drag-image${suffix},
				.monaco-list${suffix}:focus .monaco-list-row.selected.focused { color: ${styles.listFocusAndSelectionForeground}; }
			`);
      }
      if (styles.listInactiveFocusForeground) {
        content.push(`.monaco-list${suffix} .monaco-list-row.focused { color:  ${styles.listInactiveFocusForeground}; }`);
        content.push(`.monaco-list${suffix} .monaco-list-row.focused:hover { color:  ${styles.listInactiveFocusForeground}; }`);
      }
      if (styles.listInactiveSelectionIconForeground) {
        content.push(`.monaco-list${suffix} .monaco-list-row.focused .codicon { color:  ${styles.listInactiveSelectionIconForeground}; }`);
      }
      if (styles.listInactiveFocusBackground) {
        content.push(`.monaco-list${suffix} .monaco-list-row.focused { background-color:  ${styles.listInactiveFocusBackground}; }`);
        content.push(`.monaco-list${suffix} .monaco-list-row.focused:hover { background-color:  ${styles.listInactiveFocusBackground}; }`);
      }
      if (styles.listInactiveSelectionBackground) {
        content.push(`.monaco-list${suffix} .monaco-list-row.selected { background-color:  ${styles.listInactiveSelectionBackground}; }`);
        content.push(`.monaco-list${suffix} .monaco-list-row.selected:hover { background-color:  ${styles.listInactiveSelectionBackground}; }`);
      }
      if (styles.listInactiveSelectionForeground) {
        content.push(`.monaco-list${suffix} .monaco-list-row.selected { color: ${styles.listInactiveSelectionForeground}; }`);
      }
      if (styles.listHoverBackground) {
        content.push(`.monaco-list${suffix}:not(.drop-target):not(.dragging) .monaco-list-row:hover:not(.selected):not(.focused) { background-color: ${styles.listHoverBackground}; }`);
      }
      if (styles.listHoverForeground) {
        content.push(`.monaco-list${suffix}:not(.drop-target):not(.dragging) .monaco-list-row:hover:not(.selected):not(.focused) { color:  ${styles.listHoverForeground}; }`);
      }
      const focusAndSelectionOutline = asCssValueWithDefault(styles.listFocusAndSelectionOutline, asCssValueWithDefault(styles.listSelectionOutline, styles.listFocusOutline ?? ""));
      if (focusAndSelectionOutline) {
        content.push(`.monaco-list${suffix}:focus .monaco-list-row.focused.selected { outline: 1px solid ${focusAndSelectionOutline}; outline-offset: -1px;}`);
      }
      if (styles.listFocusOutline) {
        content.push(`
				.monaco-drag-image${suffix},
				.monaco-list${suffix}:focus .monaco-list-row.focused,
				.context-menu-visible .monaco-list${suffix}.last-focused .monaco-list-row.focused { outline: 1px solid ${styles.listFocusOutline}; outline-offset: -1px; }
			`);
      }
      const inactiveFocusAndSelectionOutline = asCssValueWithDefault(styles.listSelectionOutline, styles.listInactiveFocusOutline ?? "");
      if (inactiveFocusAndSelectionOutline) {
        content.push(`.monaco-list${suffix} .monaco-list-row.focused.selected { outline: 1px dotted ${inactiveFocusAndSelectionOutline}; outline-offset: -1px; }`);
      }
      if (styles.listSelectionOutline) {
        content.push(`.monaco-list${suffix} .monaco-list-row.selected { outline: 1px dotted ${styles.listSelectionOutline}; outline-offset: -1px; }`);
      }
      if (styles.listInactiveFocusOutline) {
        content.push(`.monaco-list${suffix} .monaco-list-row.focused { outline: 1px dotted ${styles.listInactiveFocusOutline}; outline-offset: -1px; }`);
      }
      if (styles.listHoverOutline) {
        content.push(`.monaco-list${suffix} .monaco-list-row:hover { outline: 1px dashed ${styles.listHoverOutline}; outline-offset: -1px; }`);
      }
      if (styles.listDropOverBackground) {
        content.push(`
				.monaco-list${suffix}.drop-target,
				.monaco-list${suffix} .monaco-list-rows.drop-target,
				.monaco-list${suffix} .monaco-list-row.drop-target { background-color: ${styles.listDropOverBackground} !important; color: inherit !important; }
			`);
      }
      if (styles.listDropBetweenBackground) {
        content.push(`
			.monaco-list${suffix} .monaco-list-rows.drop-target-before .monaco-list-row:first-child::before,
			.monaco-list${suffix} .monaco-list-row.drop-target-before::before {
				content: ""; position: absolute; top: 0px; left: 0px; width: 100%; height: 1px;
				background-color: ${styles.listDropBetweenBackground};
			}`);
        content.push(`
			.monaco-list${suffix} .monaco-list-rows.drop-target-after .monaco-list-row:last-child::after,
			.monaco-list${suffix} .monaco-list-row.drop-target-after::after {
				content: ""; position: absolute; bottom: 0px; left: 0px; width: 100%; height: 1px;
				background-color: ${styles.listDropBetweenBackground};
			}`);
      }
      if (styles.tableColumnsBorder) {
        content.push(`
				.monaco-table > .monaco-split-view2,
				.monaco-table > .monaco-split-view2 .monaco-sash.vertical::before,
				.monaco-enable-motion .monaco-table:hover > .monaco-split-view2,
				.monaco-enable-motion .monaco-table:hover > .monaco-split-view2 .monaco-sash.vertical::before {
					border-color: ${styles.tableColumnsBorder};
				}

				.monaco-enable-motion .monaco-table > .monaco-split-view2,
				.monaco-enable-motion .monaco-table > .monaco-split-view2 .monaco-sash.vertical::before {
					border-color: transparent;
				}
			`);
      }
      if (styles.tableOddRowsBackgroundColor) {
        content.push(`
				.monaco-table .monaco-list-row[data-parity=odd]:not(.focused):not(.selected):not(:hover) .monaco-table-tr,
				.monaco-table .monaco-list:not(:focus) .monaco-list-row[data-parity=odd].focused:not(.selected):not(:hover) .monaco-table-tr,
				.monaco-table .monaco-list:not(.focused) .monaco-list-row[data-parity=odd].focused:not(.selected):not(:hover) .monaco-table-tr {
					background-color: ${styles.tableOddRowsBackgroundColor};
				}
			`);
      }
      this.styleElement.textContent = content.join("\n");
    }
  }
  const unthemedListStyles = {
    listFocusBackground: "#7FB0D0",
    listActiveSelectionBackground: "#0E639C",
    listActiveSelectionForeground: "#FFFFFF",
    listActiveSelectionIconForeground: "#FFFFFF",
    listFocusAndSelectionOutline: "#90C2F9",
    listFocusAndSelectionBackground: "#094771",
    listFocusAndSelectionForeground: "#FFFFFF",
    listInactiveSelectionBackground: "#3F3F46",
    listInactiveSelectionIconForeground: "#FFFFFF",
    listHoverBackground: "#2A2D2E",
    listDropOverBackground: "#383B3D",
    listDropBetweenBackground: "#EEEEEE",
    treeIndentGuidesStroke: "#a9a9a9",
    treeInactiveIndentGuidesStroke: Color.fromHex("#a9a9a9").transparent(0.4).toString(),
    tableColumnsBorder: Color.fromHex("#cccccc").transparent(0.2).toString(),
    tableOddRowsBackgroundColor: Color.fromHex("#cccccc").transparent(0.04).toString(),
    listBackground: void 0,
    listFocusForeground: void 0,
    listInactiveSelectionForeground: void 0,
    listInactiveFocusForeground: void 0,
    listInactiveFocusBackground: void 0,
    listHoverForeground: void 0,
    listFocusOutline: void 0,
    listInactiveFocusOutline: void 0,
    listSelectionOutline: void 0,
    listHoverOutline: void 0,
    treeStickyScrollBackground: void 0,
    treeStickyScrollBorder: void 0,
    treeStickyScrollShadow: void 0
  };
  const DefaultOptions = {
    keyboardSupport: true,
    mouseSupport: true,
    multipleSelectionSupport: true,
    dnd: {
      getDragURI() {
        return null;
      },
      onDragStart() {
      },
      onDragOver() {
        return false;
      },
      drop() {
      },
      dispose() {
      }
    }
  };
  function getContiguousRangeContaining(range2, value) {
    const index = range2.indexOf(value);
    if (index === -1) {
      return [];
    }
    const result = [];
    let i2 = index - 1;
    while (i2 >= 0 && range2[i2] === value - (index - i2)) {
      result.push(range2[i2--]);
    }
    result.reverse();
    i2 = index;
    while (i2 < range2.length && range2[i2] === value + (i2 - index)) {
      result.push(range2[i2++]);
    }
    return result;
  }
  function disjunction(one, other) {
    const result = [];
    let i2 = 0, j = 0;
    while (i2 < one.length || j < other.length) {
      if (i2 >= one.length) {
        result.push(other[j++]);
      } else if (j >= other.length) {
        result.push(one[i2++]);
      } else if (one[i2] === other[j]) {
        result.push(one[i2]);
        i2++;
        j++;
        continue;
      } else if (one[i2] < other[j]) {
        result.push(one[i2++]);
      } else {
        result.push(other[j++]);
      }
    }
    return result;
  }
  function relativeComplement(one, other) {
    const result = [];
    let i2 = 0, j = 0;
    while (i2 < one.length || j < other.length) {
      if (i2 >= one.length) {
        result.push(other[j++]);
      } else if (j >= other.length) {
        result.push(one[i2++]);
      } else if (one[i2] === other[j]) {
        i2++;
        j++;
        continue;
      } else if (one[i2] < other[j]) {
        result.push(one[i2++]);
      } else {
        j++;
      }
    }
    return result;
  }
  const numericSort = (a, b) => a - b;
  class PipelineRenderer {
    constructor(_templateId, renderers) {
      this._templateId = _templateId;
      this.renderers = renderers;
    }
    get templateId() {
      return this._templateId;
    }
    renderTemplate(container) {
      return this.renderers.map((r) => r.renderTemplate(container));
    }
    renderElement(element, index, templateData, renderDetails) {
      let i2 = 0;
      for (const renderer of this.renderers) {
        renderer.renderElement(element, index, templateData[i2++], renderDetails);
      }
    }
    disposeElement(element, index, templateData, renderDetails) {
      let i2 = 0;
      for (const renderer of this.renderers) {
        renderer.disposeElement?.(element, index, templateData[i2], renderDetails);
        i2 += 1;
      }
    }
    disposeTemplate(templateData) {
      let i2 = 0;
      for (const renderer of this.renderers) {
        renderer.disposeTemplate(templateData[i2++]);
      }
    }
  }
  class AccessibiltyRenderer {
    constructor(accessibilityProvider) {
      this.accessibilityProvider = accessibilityProvider;
      this.templateId = "a18n";
    }
    renderTemplate(container) {
      return { container, disposables: new DisposableStore() };
    }
    renderElement(element, index, data) {
      const ariaLabel = this.accessibilityProvider.getAriaLabel(element);
      const observable = ariaLabel && typeof ariaLabel !== "string" ? ariaLabel : constObservable(ariaLabel);
      data.disposables.add(autorun((reader) => {
        this.setAriaLabel(reader.readObservable(observable), data.container);
      }));
      const ariaLevel = this.accessibilityProvider.getAriaLevel && this.accessibilityProvider.getAriaLevel(element);
      if (typeof ariaLevel === "number") {
        data.container.setAttribute("aria-level", `${ariaLevel}`);
      } else {
        data.container.removeAttribute("aria-level");
      }
    }
    setAriaLabel(ariaLabel, element) {
      if (ariaLabel) {
        element.setAttribute("aria-label", ariaLabel);
      } else {
        element.removeAttribute("aria-label");
      }
    }
    disposeElement(element, index, templateData) {
      templateData.disposables.clear();
    }
    disposeTemplate(templateData) {
      templateData.disposables.dispose();
    }
  }
  class ListViewDragAndDrop {
    constructor(list2, dnd) {
      this.list = list2;
      this.dnd = dnd;
    }
    getDragElements(element) {
      const selection = this.list.getSelectedElements();
      const elements = selection.indexOf(element) > -1 ? selection : [element];
      return elements;
    }
    getDragURI(element) {
      return this.dnd.getDragURI(element);
    }
    getDragLabel(elements, originalEvent) {
      if (this.dnd.getDragLabel) {
        return this.dnd.getDragLabel(elements, originalEvent);
      }
      return void 0;
    }
    onDragStart(data, originalEvent) {
      this.dnd.onDragStart?.(data, originalEvent);
    }
    onDragOver(data, targetElement, targetIndex, targetSector, originalEvent) {
      return this.dnd.onDragOver(data, targetElement, targetIndex, targetSector, originalEvent);
    }
    onDragLeave(data, targetElement, targetIndex, originalEvent) {
      this.dnd.onDragLeave?.(data, targetElement, targetIndex, originalEvent);
    }
    onDragEnd(originalEvent) {
      this.dnd.onDragEnd?.(originalEvent);
    }
    drop(data, targetElement, targetIndex, targetSector, originalEvent) {
      this.dnd.drop(data, targetElement, targetIndex, targetSector, originalEvent);
    }
    dispose() {
      this.dnd.dispose();
    }
  }
  class List {
    get onDidChangeFocus() {
      return Event.map(this.eventBufferer.wrapEvent(this.focus.onChange), (e) => this.toListEvent(e), this.disposables);
    }
    get onDidChangeSelection() {
      return Event.map(this.eventBufferer.wrapEvent(this.selection.onChange), (e) => this.toListEvent(e), this.disposables);
    }
    get domId() {
      return this.view.domId;
    }
    get onDidScroll() {
      return this.view.onDidScroll;
    }
    get onMouseClick() {
      return this.view.onMouseClick;
    }
    get onMouseDblClick() {
      return this.view.onMouseDblClick;
    }
    get onMouseMiddleClick() {
      return this.view.onMouseMiddleClick;
    }
    get onPointer() {
      return this.mouseController.onPointer;
    }
    get onMouseDown() {
      return this.view.onMouseDown;
    }
    get onMouseOver() {
      return this.view.onMouseOver;
    }
    get onMouseOut() {
      return this.view.onMouseOut;
    }
    get onTouchStart() {
      return this.view.onTouchStart;
    }
    get onTap() {
      return this.view.onTap;
    }
    /**
     * Possible context menu trigger events:
     * - ContextMenu key
     * - Shift F10
     * - Ctrl Option Shift M (macOS with VoiceOver)
     * - Mouse right click
     */
    get onContextMenu() {
      let didJustPressContextMenuKey = false;
      const fromKeyDown = Event.chain(this.disposables.add(new DomEmitter(this.view.domNode, "keydown")).event, ($2) => $2.map((e) => new StandardKeyboardEvent(e)).filter((e) => didJustPressContextMenuKey = e.keyCode === 58 || e.shiftKey && e.keyCode === 68).map((e) => EventHelper.stop(e, true)).filter(() => false));
      const fromKeyUp = Event.chain(this.disposables.add(new DomEmitter(this.view.domNode, "keyup")).event, ($2) => $2.forEach(() => didJustPressContextMenuKey = false).map((e) => new StandardKeyboardEvent(e)).filter((e) => e.keyCode === 58 || e.shiftKey && e.keyCode === 68).map((e) => EventHelper.stop(e, true)).map(({ browserEvent }) => {
        const focus = this.getFocus();
        const index = focus.length ? focus[0] : void 0;
        const element = typeof index !== "undefined" ? this.view.element(index) : void 0;
        const anchor = typeof index !== "undefined" ? this.view.domElement(index) : this.view.domNode;
        return { index, element, anchor, browserEvent };
      }));
      const fromMouse = Event.chain(this.view.onContextMenu, ($2) => $2.filter((_) => !didJustPressContextMenuKey).map(({ element, index, browserEvent }) => ({ element, index, anchor: new StandardMouseEvent(getWindow(this.view.domNode), browserEvent), browserEvent })));
      return Event.any(fromKeyDown, fromKeyUp, fromMouse);
    }
    get onKeyDown() {
      return this.disposables.add(new DomEmitter(this.view.domNode, "keydown")).event;
    }
    get onDidFocus() {
      return Event.signal(this.disposables.add(new DomEmitter(this.view.domNode, "focus", true)).event);
    }
    get onDidBlur() {
      return Event.signal(this.disposables.add(new DomEmitter(this.view.domNode, "blur", true)).event);
    }
    constructor(user, container, virtualDelegate, renderers, _options = DefaultOptions) {
      this.user = user;
      this._options = _options;
      this.focus = new Trait$1("focused");
      this.anchor = new Trait$1("anchor");
      this.eventBufferer = new EventBufferer();
      this._ariaLabel = "";
      this.disposables = new DisposableStore();
      this._onDidDispose = new Emitter$1();
      this.onDidDispose = this._onDidDispose.event;
      const role = this._options.accessibilityProvider && this._options.accessibilityProvider.getWidgetRole ? this._options.accessibilityProvider?.getWidgetRole() : "list";
      this.selection = new SelectionTrait(role !== "listbox");
      const baseRenderers = [this.focus.renderer, this.selection.renderer];
      this.accessibilityProvider = _options.accessibilityProvider;
      if (this.accessibilityProvider) {
        baseRenderers.push(new AccessibiltyRenderer(this.accessibilityProvider));
        this.accessibilityProvider.onDidChangeActiveDescendant?.(this.onDidChangeActiveDescendant, this, this.disposables);
      }
      renderers = renderers.map((r) => new PipelineRenderer(r.templateId, [...baseRenderers, r]));
      const viewOptions = {
        ..._options,
        dnd: _options.dnd && new ListViewDragAndDrop(this, _options.dnd)
      };
      this.view = this.createListView(container, virtualDelegate, renderers, viewOptions);
      this.view.domNode.setAttribute("role", role);
      if (_options.styleController) {
        this.styleController = _options.styleController(this.view.domId);
      } else {
        const styleElement = createStyleSheet(this.view.domNode);
        this.styleController = new DefaultStyleController(styleElement, this.view.domId);
      }
      this.spliceable = new CombinedSpliceable([
        new TraitSpliceable(this.focus, this.view, _options.identityProvider),
        new TraitSpliceable(this.selection, this.view, _options.identityProvider),
        new TraitSpliceable(this.anchor, this.view, _options.identityProvider),
        this.view
      ]);
      this.disposables.add(this.focus);
      this.disposables.add(this.selection);
      this.disposables.add(this.anchor);
      this.disposables.add(this.view);
      this.disposables.add(this._onDidDispose);
      this.disposables.add(new DOMFocusController(this, this.view));
      if (typeof _options.keyboardSupport !== "boolean" || _options.keyboardSupport) {
        this.keyboardController = new KeyboardController(this, this.view, _options);
        this.disposables.add(this.keyboardController);
      }
      if (_options.keyboardNavigationLabelProvider) {
        const delegate = _options.keyboardNavigationDelegate || DefaultKeyboardNavigationDelegate;
        this.typeNavigationController = new TypeNavigationController(this, this.view, _options.keyboardNavigationLabelProvider, _options.keyboardNavigationEventFilter ?? (() => true), delegate);
        this.disposables.add(this.typeNavigationController);
      }
      this.mouseController = this.createMouseController(_options);
      this.disposables.add(this.mouseController);
      this.onDidChangeFocus(this._onFocusChange, this, this.disposables);
      this.onDidChangeSelection(this._onSelectionChange, this, this.disposables);
      if (this.accessibilityProvider) {
        const ariaLabel = this.accessibilityProvider.getWidgetAriaLabel();
        const observable = ariaLabel && typeof ariaLabel !== "string" ? ariaLabel : constObservable(ariaLabel);
        this.disposables.add(autorun((reader) => {
          this.ariaLabel = reader.readObservable(observable);
        }));
      }
      if (this._options.multipleSelectionSupport !== false) {
        this.view.domNode.setAttribute("aria-multiselectable", "true");
      }
    }
    createListView(container, virtualDelegate, renderers, viewOptions) {
      return new ListView(container, virtualDelegate, renderers, viewOptions);
    }
    createMouseController(options) {
      return new MouseController(this);
    }
    updateOptions(optionsUpdate = {}) {
      this._options = { ...this._options, ...optionsUpdate };
      this.typeNavigationController?.updateOptions(this._options);
      if (this._options.multipleSelectionController !== void 0) {
        if (this._options.multipleSelectionSupport) {
          this.view.domNode.setAttribute("aria-multiselectable", "true");
        } else {
          this.view.domNode.removeAttribute("aria-multiselectable");
        }
      }
      this.mouseController.updateOptions(optionsUpdate);
      this.keyboardController?.updateOptions(optionsUpdate);
      this.view.updateOptions(optionsUpdate);
    }
    get options() {
      return this._options;
    }
    splice(start, deleteCount, elements = []) {
      if (start < 0 || start > this.view.length) {
        throw new ListError(this.user, `Invalid start index: ${start}`);
      }
      if (deleteCount < 0) {
        throw new ListError(this.user, `Invalid delete count: ${deleteCount}`);
      }
      if (deleteCount === 0 && elements.length === 0) {
        return;
      }
      this.eventBufferer.bufferEvents(() => this.spliceable.splice(start, deleteCount, elements));
    }
    rerender() {
      this.view.rerender();
    }
    element(index) {
      return this.view.element(index);
    }
    indexOf(element) {
      return this.view.indexOf(element);
    }
    indexAt(position) {
      return this.view.indexAt(position);
    }
    get length() {
      return this.view.length;
    }
    get contentHeight() {
      return this.view.contentHeight;
    }
    get onDidChangeContentHeight() {
      return this.view.onDidChangeContentHeight;
    }
    get scrollTop() {
      return this.view.getScrollTop();
    }
    set scrollTop(scrollTop) {
      this.view.setScrollTop(scrollTop);
    }
    get scrollHeight() {
      return this.view.scrollHeight;
    }
    get renderHeight() {
      return this.view.renderHeight;
    }
    get firstVisibleIndex() {
      return this.view.firstVisibleIndex;
    }
    get ariaLabel() {
      return this._ariaLabel;
    }
    set ariaLabel(value) {
      this._ariaLabel = value;
      this.view.domNode.setAttribute("aria-label", value);
    }
    domFocus() {
      this.view.domNode.focus({ preventScroll: true });
    }
    layout(height, width2) {
      this.view.layout(height, width2);
    }
    setSelection(indexes, browserEvent) {
      for (const index of indexes) {
        if (index < 0 || index >= this.length) {
          throw new ListError(this.user, `Invalid index ${index}`);
        }
      }
      this.selection.set(indexes, browserEvent);
    }
    getSelection() {
      return this.selection.get();
    }
    getSelectedElements() {
      return this.getSelection().map((i2) => this.view.element(i2));
    }
    setAnchor(index) {
      if (typeof index === "undefined") {
        this.anchor.set([]);
        return;
      }
      if (index < 0 || index >= this.length) {
        throw new ListError(this.user, `Invalid index ${index}`);
      }
      this.anchor.set([index]);
    }
    getAnchor() {
      return this.anchor.get().at(0);
    }
    getAnchorElement() {
      const anchor = this.getAnchor();
      return typeof anchor === "undefined" ? void 0 : this.element(anchor);
    }
    setFocus(indexes, browserEvent) {
      for (const index of indexes) {
        if (index < 0 || index >= this.length) {
          throw new ListError(this.user, `Invalid index ${index}`);
        }
      }
      this.focus.set(indexes, browserEvent);
    }
    focusNext(n2 = 1, loop = false, browserEvent, filter) {
      if (this.length === 0) {
        return;
      }
      const focus = this.focus.get();
      const index = this.findNextIndex(focus.length > 0 ? focus[0] + n2 : 0, loop, filter);
      if (index > -1) {
        this.setFocus([index], browserEvent);
      }
    }
    focusPrevious(n2 = 1, loop = false, browserEvent, filter) {
      if (this.length === 0) {
        return;
      }
      const focus = this.focus.get();
      const index = this.findPreviousIndex(focus.length > 0 ? focus[0] - n2 : 0, loop, filter);
      if (index > -1) {
        this.setFocus([index], browserEvent);
      }
    }
    async focusNextPage(browserEvent, filter) {
      let lastPageIndex = this.view.indexAt(this.view.getScrollTop() + this.view.renderHeight);
      lastPageIndex = lastPageIndex === 0 ? 0 : lastPageIndex - 1;
      const currentlyFocusedElementIndex = this.getFocus()[0];
      if (currentlyFocusedElementIndex !== lastPageIndex && (currentlyFocusedElementIndex === void 0 || lastPageIndex > currentlyFocusedElementIndex)) {
        const lastGoodPageIndex = this.findPreviousIndex(lastPageIndex, false, filter);
        if (lastGoodPageIndex > -1 && currentlyFocusedElementIndex !== lastGoodPageIndex) {
          this.setFocus([lastGoodPageIndex], browserEvent);
        } else {
          this.setFocus([lastPageIndex], browserEvent);
        }
      } else {
        const previousScrollTop = this.view.getScrollTop();
        let nextpageScrollTop = previousScrollTop + this.view.renderHeight;
        if (lastPageIndex > currentlyFocusedElementIndex) {
          nextpageScrollTop -= this.view.elementHeight(lastPageIndex);
        }
        this.view.setScrollTop(nextpageScrollTop);
        if (this.view.getScrollTop() !== previousScrollTop) {
          this.setFocus([]);
          await timeout(0);
          await this.focusNextPage(browserEvent, filter);
        }
      }
    }
    async focusPreviousPage(browserEvent, filter, getPaddingTop = () => 0) {
      let firstPageIndex;
      const paddingTop = getPaddingTop();
      const scrollTop = this.view.getScrollTop() + paddingTop;
      if (scrollTop === 0) {
        firstPageIndex = this.view.indexAt(scrollTop);
      } else {
        firstPageIndex = this.view.indexAfter(scrollTop - 1);
      }
      const currentlyFocusedElementIndex = this.getFocus()[0];
      if (currentlyFocusedElementIndex !== firstPageIndex && (currentlyFocusedElementIndex === void 0 || currentlyFocusedElementIndex >= firstPageIndex)) {
        const firstGoodPageIndex = this.findNextIndex(firstPageIndex, false, filter);
        if (firstGoodPageIndex > -1 && currentlyFocusedElementIndex !== firstGoodPageIndex) {
          this.setFocus([firstGoodPageIndex], browserEvent);
        } else {
          this.setFocus([firstPageIndex], browserEvent);
        }
      } else {
        const previousScrollTop = scrollTop;
        this.view.setScrollTop(scrollTop - this.view.renderHeight - paddingTop);
        if (this.view.getScrollTop() + getPaddingTop() !== previousScrollTop) {
          this.setFocus([]);
          await timeout(0);
          await this.focusPreviousPage(browserEvent, filter, getPaddingTop);
        }
      }
    }
    focusLast(browserEvent, filter) {
      if (this.length === 0) {
        return;
      }
      const index = this.findPreviousIndex(this.length - 1, false, filter);
      if (index > -1) {
        this.setFocus([index], browserEvent);
      }
    }
    focusFirst(browserEvent, filter) {
      this.focusNth(0, browserEvent, filter);
    }
    focusNth(n2, browserEvent, filter) {
      if (this.length === 0) {
        return;
      }
      const index = this.findNextIndex(n2, false, filter);
      if (index > -1) {
        this.setFocus([index], browserEvent);
      }
    }
    findNextIndex(index, loop = false, filter) {
      for (let i2 = 0; i2 < this.length; i2++) {
        if (index >= this.length && !loop) {
          return -1;
        }
        index = index % this.length;
        if (!filter || filter(this.element(index))) {
          return index;
        }
        index++;
      }
      return -1;
    }
    findPreviousIndex(index, loop = false, filter) {
      for (let i2 = 0; i2 < this.length; i2++) {
        if (index < 0 && !loop) {
          return -1;
        }
        index = (this.length + index % this.length) % this.length;
        if (!filter || filter(this.element(index))) {
          return index;
        }
        index--;
      }
      return -1;
    }
    getFocus() {
      return this.focus.get();
    }
    getFocusedElements() {
      return this.getFocus().map((i2) => this.view.element(i2));
    }
    reveal(index, relativeTop, paddingTop = 0) {
      if (index < 0 || index >= this.length) {
        throw new ListError(this.user, `Invalid index ${index}`);
      }
      const scrollTop = this.view.getScrollTop();
      const elementTop = this.view.elementTop(index);
      const elementHeight = this.view.elementHeight(index);
      if (isNumber$1(relativeTop)) {
        const m = elementHeight - this.view.renderHeight + paddingTop;
        this.view.setScrollTop(m * clamp(relativeTop, 0, 1) + elementTop - paddingTop);
      } else {
        const viewItemBottom = elementTop + elementHeight;
        const scrollBottom = scrollTop + this.view.renderHeight;
        if (elementTop < scrollTop + paddingTop && viewItemBottom >= scrollBottom) ;
        else if (elementTop < scrollTop + paddingTop || viewItemBottom >= scrollBottom && elementHeight >= this.view.renderHeight) {
          this.view.setScrollTop(elementTop - paddingTop);
        } else if (viewItemBottom >= scrollBottom) {
          this.view.setScrollTop(viewItemBottom - this.view.renderHeight);
        }
      }
    }
    /**
     * Returns the relative position of an element rendered in the list.
     * Returns `null` if the element isn't *entirely* in the visible viewport.
     */
    getRelativeTop(index, paddingTop = 0) {
      if (index < 0 || index >= this.length) {
        throw new ListError(this.user, `Invalid index ${index}`);
      }
      const scrollTop = this.view.getScrollTop();
      const elementTop = this.view.elementTop(index);
      const elementHeight = this.view.elementHeight(index);
      if (elementTop < scrollTop + paddingTop || elementTop + elementHeight > scrollTop + this.view.renderHeight) {
        return null;
      }
      const m = elementHeight - this.view.renderHeight + paddingTop;
      return Math.abs((scrollTop + paddingTop - elementTop) / m);
    }
    getHTMLElement() {
      return this.view.domNode;
    }
    getScrollableElement() {
      return this.view.scrollableElementDomNode;
    }
    getElementID(index) {
      return this.view.getElementDomId(index);
    }
    getElementTop(index) {
      return this.view.elementTop(index);
    }
    style(styles) {
      this.styleController.style(styles);
    }
    toListEvent({ indexes, browserEvent }) {
      return { indexes, elements: indexes.map((i2) => this.view.element(i2)), browserEvent };
    }
    _onFocusChange() {
      const focus = this.focus.get();
      this.view.domNode.classList.toggle("element-focused", focus.length > 0);
      this.onDidChangeActiveDescendant();
    }
    onDidChangeActiveDescendant() {
      const focus = this.focus.get();
      if (focus.length > 0) {
        let id;
        if (this.accessibilityProvider?.getActiveDescendantId) {
          id = this.accessibilityProvider.getActiveDescendantId(this.view.element(focus[0]));
        }
        this.view.domNode.setAttribute("aria-activedescendant", id || this.view.getElementDomId(focus[0]));
      } else {
        this.view.domNode.removeAttribute("aria-activedescendant");
      }
    }
    _onSelectionChange() {
      const selection = this.selection.get();
      this.view.domNode.classList.toggle("selection-none", selection.length === 0);
      this.view.domNode.classList.toggle("selection-single", selection.length === 1);
      this.view.domNode.classList.toggle("selection-multiple", selection.length > 1);
    }
    dispose() {
      this._onDidDispose.fire();
      this.disposables.dispose();
      this._onDidDispose.dispose();
    }
  }
  __decorate$2I([
    memoize
  ], List.prototype, "onDidChangeFocus", null);
  __decorate$2I([
    memoize
  ], List.prototype, "onDidChangeSelection", null);
  __decorate$2I([
    memoize
  ], List.prototype, "onContextMenu", null);
  __decorate$2I([
    memoize
  ], List.prototype, "onKeyDown", null);
  __decorate$2I([
    memoize
  ], List.prototype, "onDidFocus", null);
  __decorate$2I([
    memoize
  ], List.prototype, "onDidBlur", null);
  const $$k = $$l;
  const SELECT_OPTION_ENTRY_TEMPLATE_ID = "selectOption.entry.template";
  class SelectListRenderer {
    get templateId() {
      return SELECT_OPTION_ENTRY_TEMPLATE_ID;
    }
    renderTemplate(container) {
      const data = /* @__PURE__ */ Object.create(null);
      data.root = container;
      data.text = append$2(container, $$k(".option-text"));
      data.detail = append$2(container, $$k(".option-detail"));
      data.decoratorRight = append$2(container, $$k(".option-decorator-right"));
      return data;
    }
    renderElement(element, index, templateData) {
      const data = templateData;
      const text2 = element.text;
      const detail = element.detail;
      const decoratorRight = element.decoratorRight;
      const isDisabled = element.isDisabled;
      data.text.textContent = text2;
      data.detail.textContent = !!detail ? detail : "";
      data.decoratorRight.textContent = !!decoratorRight ? decoratorRight : "";
      if (isDisabled) {
        data.root.classList.add("option-disabled");
      } else {
        data.root.classList.remove("option-disabled");
      }
    }
    disposeTemplate(_templateData) {
    }
  }
  const _SelectBoxList = class _SelectBoxList extends Disposable {
    constructor(options, selected, contextViewProvider, styles, selectBoxOptions) {
      super();
      this.options = [];
      this._currentSelection = 0;
      this._hasDetails = false;
      this._selectionDetailsDisposables = this._register(new DisposableStore());
      this._skipLayout = false;
      this._sticky = false;
      this._isVisible = false;
      this.styles = styles;
      this.selectBoxOptions = selectBoxOptions || /* @__PURE__ */ Object.create(null);
      if (typeof this.selectBoxOptions.minBottomMargin !== "number") {
        this.selectBoxOptions.minBottomMargin = _SelectBoxList.DEFAULT_DROPDOWN_MINIMUM_BOTTOM_MARGIN;
      } else if (this.selectBoxOptions.minBottomMargin < 0) {
        this.selectBoxOptions.minBottomMargin = 0;
      }
      this.selectElement = document.createElement("select");
      this.selectElement.className = "monaco-select-box monaco-select-box-dropdown-padding";
      if (typeof this.selectBoxOptions.ariaLabel === "string") {
        this.selectElement.setAttribute("aria-label", this.selectBoxOptions.ariaLabel);
      }
      if (typeof this.selectBoxOptions.ariaDescription === "string") {
        this.selectElement.setAttribute("aria-description", this.selectBoxOptions.ariaDescription);
      }
      this._onDidSelect = new Emitter$1();
      this._register(this._onDidSelect);
      this.registerListeners();
      this.constructSelectDropDown(contextViewProvider);
      this.selected = selected || 0;
      if (options) {
        this.setOptions(options, selected);
      }
      this.initStyleSheet();
    }
    setTitle(title) {
      if (!this._hover && title) {
        this._hover = this._register(getBaseLayerHoverDelegate().setupManagedHover(getDefaultHoverDelegate("mouse"), this.selectElement, title));
      } else if (this._hover) {
        this._hover.update(title);
      }
    }
    // IDelegate - List renderer
    getHeight() {
      return 22;
    }
    getTemplateId() {
      return SELECT_OPTION_ENTRY_TEMPLATE_ID;
    }
    constructSelectDropDown(contextViewProvider) {
      this.contextViewProvider = contextViewProvider;
      this.selectDropDownContainer = $$l(".monaco-select-box-dropdown-container");
      this.selectDropDownContainer.classList.add("monaco-select-box-dropdown-padding");
      this.selectionDetailsPane = append$2(this.selectDropDownContainer, $$k(".select-box-details-pane"));
      const widthControlOuterDiv = append$2(this.selectDropDownContainer, $$k(".select-box-dropdown-container-width-control"));
      const widthControlInnerDiv = append$2(widthControlOuterDiv, $$k(".width-control-div"));
      this.widthControlElement = document.createElement("span");
      this.widthControlElement.className = "option-text-width-control";
      append$2(widthControlInnerDiv, this.widthControlElement);
      this._dropDownPosition = 0;
      this.styleElement = createStyleSheet(this.selectDropDownContainer);
      this.selectDropDownContainer.setAttribute("draggable", "true");
      this._register(addDisposableListener(this.selectDropDownContainer, EventType$1.DRAG_START, (e) => {
        EventHelper.stop(e, true);
      }));
    }
    registerListeners() {
      this._register(addStandardDisposableListener(this.selectElement, "change", (e) => {
        this.selected = e.target.selectedIndex;
        this._onDidSelect.fire({
          index: e.target.selectedIndex,
          selected: e.target.value
        });
        if (!!this.options[this.selected] && !!this.options[this.selected].text) {
          this.setTitle(this.options[this.selected].text);
        }
      }));
      this._register(addDisposableListener(this.selectElement, EventType$1.CLICK, (e) => {
        EventHelper.stop(e);
        if (this._isVisible) {
          this.hideSelectDropDown(true);
        } else {
          this.showSelectDropDown();
        }
      }));
      this._register(addDisposableListener(this.selectElement, EventType$1.MOUSE_DOWN, (e) => {
        EventHelper.stop(e);
      }));
      let listIsVisibleOnTouchStart;
      this._register(addDisposableListener(this.selectElement, "touchstart", (e) => {
        listIsVisibleOnTouchStart = this._isVisible;
      }));
      this._register(addDisposableListener(this.selectElement, "touchend", (e) => {
        EventHelper.stop(e);
        if (listIsVisibleOnTouchStart) {
          this.hideSelectDropDown(true);
        } else {
          this.showSelectDropDown();
        }
      }));
      this._register(addDisposableListener(this.selectElement, EventType$1.KEY_DOWN, (e) => {
        const event = new StandardKeyboardEvent(e);
        let showDropDown = false;
        if (isMacintosh) {
          if (event.keyCode === 18 || event.keyCode === 16 || event.keyCode === 10 || event.keyCode === 3) {
            showDropDown = true;
          }
        } else {
          if (event.keyCode === 18 && event.altKey || event.keyCode === 16 && event.altKey || event.keyCode === 10 || event.keyCode === 3) {
            showDropDown = true;
          }
        }
        if (showDropDown) {
          this.showSelectDropDown();
          EventHelper.stop(e, true);
        }
      }));
    }
    get onDidSelect() {
      return this._onDidSelect.event;
    }
    setOptions(options, selected) {
      if (!equals$1(this.options, options)) {
        this.options = options;
        this.selectElement.options.length = 0;
        this._hasDetails = false;
        this._cachedMaxDetailsHeight = void 0;
        this.options.forEach((option2, index) => {
          this.selectElement.add(this.createOption(option2.text, index, option2.isDisabled));
          if (typeof option2.description === "string") {
            this._hasDetails = true;
          }
        });
      }
      if (selected !== void 0) {
        this.select(selected);
        this._currentSelection = this.selected;
      }
    }
    setOptionsList() {
      this.selectList?.splice(0, this.selectList.length, this.options);
    }
    select(index) {
      if (index >= 0 && index < this.options.length) {
        this.selected = index;
      } else if (index > this.options.length - 1) {
        this.select(this.options.length - 1);
      } else if (this.selected < 0) {
        this.selected = 0;
      }
      this.selectElement.selectedIndex = this.selected;
      if (!!this.options[this.selected] && !!this.options[this.selected].text) {
        this.setTitle(this.options[this.selected].text);
      }
    }
    focus() {
      if (this.selectElement) {
        this.selectElement.tabIndex = 0;
        this.selectElement.focus();
      }
    }
    blur() {
      if (this.selectElement) {
        this.selectElement.tabIndex = -1;
        this.selectElement.blur();
      }
    }
    setFocusable(focusable) {
      this.selectElement.tabIndex = focusable ? 0 : -1;
    }
    render(container) {
      this.container = container;
      container.classList.add("select-container");
      container.appendChild(this.selectElement);
      this.styleSelectElement();
    }
    initStyleSheet() {
      const content = [];
      if (this.styles.listFocusBackground) {
        content.push(`.monaco-select-box-dropdown-container > .select-box-dropdown-list-container .monaco-list .monaco-list-row.focused { background-color: ${this.styles.listFocusBackground} !important; }`);
      }
      if (this.styles.listFocusForeground) {
        content.push(`.monaco-select-box-dropdown-container > .select-box-dropdown-list-container .monaco-list .monaco-list-row.focused { color: ${this.styles.listFocusForeground} !important; }`);
      }
      if (this.styles.decoratorRightForeground) {
        content.push(`.monaco-select-box-dropdown-container > .select-box-dropdown-list-container .monaco-list .monaco-list-row:not(.focused) .option-decorator-right { color: ${this.styles.decoratorRightForeground}; }`);
      }
      if (this.styles.selectBackground && this.styles.selectBorder && this.styles.selectBorder !== this.styles.selectBackground) {
        content.push(`.monaco-select-box-dropdown-container { border: 1px solid ${this.styles.selectBorder} } `);
        content.push(`.monaco-select-box-dropdown-container > .select-box-details-pane.border-top { border-top: 1px solid ${this.styles.selectBorder} } `);
        content.push(`.monaco-select-box-dropdown-container > .select-box-details-pane.border-bottom { border-bottom: 1px solid ${this.styles.selectBorder} } `);
      } else if (this.styles.selectListBorder) {
        content.push(`.monaco-select-box-dropdown-container > .select-box-details-pane.border-top { border-top: 1px solid ${this.styles.selectListBorder} } `);
        content.push(`.monaco-select-box-dropdown-container > .select-box-details-pane.border-bottom { border-bottom: 1px solid ${this.styles.selectListBorder} } `);
      }
      if (this.styles.listHoverForeground) {
        content.push(`.monaco-select-box-dropdown-container > .select-box-dropdown-list-container .monaco-list .monaco-list-row:not(.option-disabled):not(.focused):hover { color: ${this.styles.listHoverForeground} !important; }`);
      }
      if (this.styles.listHoverBackground) {
        content.push(`.monaco-select-box-dropdown-container > .select-box-dropdown-list-container .monaco-list .monaco-list-row:not(.option-disabled):not(.focused):hover { background-color: ${this.styles.listHoverBackground} !important; }`);
      }
      if (this.styles.listFocusOutline) {
        content.push(`.monaco-select-box-dropdown-container > .select-box-dropdown-list-container .monaco-list .monaco-list-row.focused { outline: 1.6px dotted ${this.styles.listFocusOutline} !important; outline-offset: -1.6px !important; }`);
      }
      if (this.styles.listHoverOutline) {
        content.push(`.monaco-select-box-dropdown-container > .select-box-dropdown-list-container .monaco-list .monaco-list-row:not(.option-disabled):not(.focused):hover { outline: 1.6px dashed ${this.styles.listHoverOutline} !important; outline-offset: -1.6px !important; }`);
      }
      content.push(`.monaco-select-box-dropdown-container > .select-box-dropdown-list-container .monaco-list .monaco-list-row.option-disabled.focused { background-color: transparent !important; color: inherit !important; outline: none !important; }`);
      content.push(`.monaco-select-box-dropdown-container > .select-box-dropdown-list-container .monaco-list .monaco-list-row.option-disabled:hover { background-color: transparent !important; color: inherit !important; outline: none !important; }`);
      this.styleElement.textContent = content.join("\n");
    }
    styleSelectElement() {
      const background = this.styles.selectBackground ?? "";
      const foreground2 = this.styles.selectForeground ?? "";
      const border = this.styles.selectBorder ?? "";
      this.selectElement.style.backgroundColor = background;
      this.selectElement.style.color = foreground2;
      this.selectElement.style.borderColor = border;
    }
    styleList() {
      const background = this.styles.selectBackground ?? "";
      const listBackground = asCssValueWithDefault(this.styles.selectListBackground, background);
      this.selectDropDownListContainer.style.backgroundColor = listBackground;
      this.selectionDetailsPane.style.backgroundColor = listBackground;
      const optionsBorder = this.styles.focusBorder ?? "";
      this.selectDropDownContainer.style.outlineColor = optionsBorder;
      this.selectDropDownContainer.style.outlineOffset = "-1px";
      this.selectList.style(this.styles);
    }
    createOption(value, index, disabled) {
      const option2 = document.createElement("option");
      option2.value = value;
      option2.text = value;
      option2.disabled = !!disabled;
      return option2;
    }
    // ContextView dropdown methods
    showSelectDropDown() {
      this.selectionDetailsPane.textContent = "";
      if (!this.contextViewProvider || this._isVisible) {
        return;
      }
      this.createSelectList(this.selectDropDownContainer);
      this.setOptionsList();
      this.contextViewProvider.showContextView({
        getAnchor: () => this.selectElement,
        render: (container) => this.renderSelectDropDown(container, true),
        layout: () => {
          this.layoutSelectDropDown();
        },
        onHide: () => {
          this.selectDropDownContainer.classList.remove("visible");
          this.selectElement.classList.remove("synthetic-focus");
        },
        anchorPosition: this._dropDownPosition
      }, this.selectBoxOptions.optionsAsChildren ? this.container : void 0);
      this._isVisible = true;
      this.hideSelectDropDown(false);
      this.contextViewProvider.showContextView({
        getAnchor: () => this.selectElement,
        render: (container) => this.renderSelectDropDown(container),
        layout: () => this.layoutSelectDropDown(),
        onHide: () => {
          this.selectDropDownContainer.classList.remove("visible");
          this.selectElement.classList.remove("synthetic-focus");
        },
        anchorPosition: this._dropDownPosition
      }, this.selectBoxOptions.optionsAsChildren ? this.container : void 0);
      this._currentSelection = this.selected;
      this._isVisible = true;
      this.selectElement.setAttribute("aria-expanded", "true");
    }
    hideSelectDropDown(focusSelect) {
      if (!this.contextViewProvider || !this._isVisible) {
        return;
      }
      this._isVisible = false;
      this.selectElement.setAttribute("aria-expanded", "false");
      if (focusSelect) {
        this.selectElement.focus();
      }
      this.contextViewProvider.hideContextView();
    }
    renderSelectDropDown(container, preLayoutPosition) {
      container.appendChild(this.selectDropDownContainer);
      this.layoutSelectDropDown(preLayoutPosition);
      return {
        dispose: () => {
          this.selectDropDownContainer.remove();
        }
      };
    }
    // Iterate over detailed descriptions, find max height
    measureMaxDetailsHeight() {
      let maxDetailsPaneHeight = 0;
      this.options.forEach((_option, index) => {
        this.updateDetail(index);
        if (this.selectionDetailsPane.offsetHeight > maxDetailsPaneHeight) {
          maxDetailsPaneHeight = this.selectionDetailsPane.offsetHeight;
        }
      });
      return maxDetailsPaneHeight;
    }
    layoutSelectDropDown(preLayoutPosition) {
      if (this._skipLayout) {
        return false;
      }
      if (this.selectList) {
        this.selectDropDownContainer.classList.add("visible");
        const window2 = getWindow(this.selectElement);
        const selectPosition = getDomNodePagePosition(this.selectElement);
        const styles = getWindow(this.selectElement).getComputedStyle(this.selectElement);
        const verticalPadding = parseFloat(styles.getPropertyValue("--dropdown-padding-top")) + parseFloat(styles.getPropertyValue("--dropdown-padding-bottom"));
        const maxSelectDropDownHeightBelow = window2.innerHeight - selectPosition.top - selectPosition.height - (this.selectBoxOptions.minBottomMargin || 0);
        const maxSelectDropDownHeightAbove = selectPosition.top - _SelectBoxList.DEFAULT_DROPDOWN_MINIMUM_TOP_MARGIN;
        const selectWidth = this.selectElement.offsetWidth;
        const selectMinWidth = this.setWidthControlElement(this.widthControlElement);
        const selectOptimalWidth = Math.max(selectMinWidth, Math.round(selectWidth)).toString() + "px";
        this.selectDropDownContainer.style.width = selectOptimalWidth;
        this.selectList.getHTMLElement().style.height = "";
        this.selectList.layout();
        let listHeight = this.selectList.contentHeight;
        if (this._hasDetails && this._cachedMaxDetailsHeight === void 0) {
          this._cachedMaxDetailsHeight = this.measureMaxDetailsHeight();
        }
        const maxDetailsPaneHeight = this._hasDetails ? this._cachedMaxDetailsHeight : 0;
        const minRequiredDropDownHeight = listHeight + verticalPadding + maxDetailsPaneHeight;
        const maxVisibleOptionsBelow = Math.floor((maxSelectDropDownHeightBelow - verticalPadding - maxDetailsPaneHeight) / this.getHeight());
        const maxVisibleOptionsAbove = Math.floor((maxSelectDropDownHeightAbove - verticalPadding - maxDetailsPaneHeight) / this.getHeight());
        if (preLayoutPosition) {
          if (selectPosition.top + selectPosition.height > window2.innerHeight - 22 || selectPosition.top < _SelectBoxList.DEFAULT_DROPDOWN_MINIMUM_TOP_MARGIN || maxVisibleOptionsBelow < 1 && maxVisibleOptionsAbove < 1) {
            return false;
          }
          if (maxVisibleOptionsBelow < _SelectBoxList.DEFAULT_MINIMUM_VISIBLE_OPTIONS && maxVisibleOptionsAbove > maxVisibleOptionsBelow && this.options.length > maxVisibleOptionsBelow) {
            this._dropDownPosition = 1;
            this.selectDropDownListContainer.remove();
            this.selectionDetailsPane.remove();
            this.selectDropDownContainer.appendChild(this.selectionDetailsPane);
            this.selectDropDownContainer.appendChild(this.selectDropDownListContainer);
            this.selectionDetailsPane.classList.remove("border-top");
            this.selectionDetailsPane.classList.add("border-bottom");
          } else {
            this._dropDownPosition = 0;
            this.selectDropDownListContainer.remove();
            this.selectionDetailsPane.remove();
            this.selectDropDownContainer.appendChild(this.selectDropDownListContainer);
            this.selectDropDownContainer.appendChild(this.selectionDetailsPane);
            this.selectionDetailsPane.classList.remove("border-bottom");
            this.selectionDetailsPane.classList.add("border-top");
          }
          return true;
        }
        if (selectPosition.top + selectPosition.height > window2.innerHeight - 22 || selectPosition.top < _SelectBoxList.DEFAULT_DROPDOWN_MINIMUM_TOP_MARGIN || this._dropDownPosition === 0 && maxVisibleOptionsBelow < 1 || this._dropDownPosition === 1 && maxVisibleOptionsAbove < 1) {
          this.hideSelectDropDown(true);
          return false;
        }
        if (this._dropDownPosition === 0) {
          if (this._isVisible && maxVisibleOptionsBelow + maxVisibleOptionsAbove < 1) {
            this.hideSelectDropDown(true);
            return false;
          }
          if (minRequiredDropDownHeight > maxSelectDropDownHeightBelow) {
            listHeight = maxVisibleOptionsBelow * this.getHeight();
          }
        } else {
          if (minRequiredDropDownHeight > maxSelectDropDownHeightAbove) {
            listHeight = maxVisibleOptionsAbove * this.getHeight();
          }
        }
        this.selectList.layout(listHeight);
        this.selectList.domFocus();
        if (this.selectList.length > 0) {
          this.selectList.setFocus([this.selected || 0]);
          this.selectList.reveal(this.selectList.getFocus()[0] || 0);
        }
        if (this._hasDetails) {
          this.selectList.getHTMLElement().style.height = listHeight + verticalPadding + "px";
          this.selectDropDownContainer.style.height = "";
        } else {
          this.selectDropDownContainer.style.height = listHeight + verticalPadding + "px";
        }
        this.updateDetail(this.selected);
        this.selectDropDownContainer.style.width = selectOptimalWidth;
        this.selectDropDownListContainer.setAttribute("tabindex", "0");
        this.selectElement.classList.add("synthetic-focus");
        this.selectDropDownContainer.classList.add("synthetic-focus");
        return true;
      } else {
        return false;
      }
    }
    setWidthControlElement(container) {
      let elementWidth = 0;
      if (container) {
        let longest = 0;
        let longestLength = 0;
        this.options.forEach((option2, index) => {
          const detailLength = !!option2.detail ? option2.detail.length : 0;
          const rightDecoratorLength = !!option2.decoratorRight ? option2.decoratorRight.length : 0;
          const len = option2.text.length + detailLength + rightDecoratorLength;
          if (len > longestLength) {
            longest = index;
            longestLength = len;
          }
        });
        container.textContent = this.options[longest].text + (!!this.options[longest].decoratorRight ? this.options[longest].decoratorRight + " " : "");
        elementWidth = getTotalWidth(container);
      }
      return elementWidth;
    }
    createSelectList(parent) {
      if (this.selectList) {
        return;
      }
      this.selectDropDownListContainer = append$2(parent, $$k(".select-box-dropdown-list-container"));
      this.listRenderer = new SelectListRenderer();
      this.selectList = this._register(new List("SelectBoxCustom", this.selectDropDownListContainer, this, [this.listRenderer], {
        useShadows: false,
        verticalScrollMode: 3,
        keyboardSupport: false,
        mouseSupport: false,
        accessibilityProvider: {
          getAriaLabel: (element) => {
            let label = element.text;
            if (element.detail) {
              label += `. ${element.detail}`;
            }
            if (element.decoratorRight) {
              label += `. ${element.decoratorRight}`;
            }
            if (element.description) {
              label += `. ${element.description}`;
            }
            return label;
          },
          getWidgetAriaLabel: () => localize(16, "Select Box"),
          getRole: () => isMacintosh ? "" : "option",
          getWidgetRole: () => "listbox"
        }
      }));
      if (this.selectBoxOptions.ariaLabel) {
        this.selectList.ariaLabel = this.selectBoxOptions.ariaLabel;
      }
      const onKeyDown = this._register(new DomEmitter(this.selectDropDownListContainer, "keydown"));
      const onSelectDropDownKeyDown = Event.chain(onKeyDown.event, ($2) => $2.filter(() => this.selectList.length > 0).map((e) => new StandardKeyboardEvent(e)));
      this._register(Event.chain(onSelectDropDownKeyDown, ($2) => $2.filter(
        (e) => e.keyCode === 3
        /* KeyCode.Enter */
      ))(this.onEnter, this));
      this._register(Event.chain(onSelectDropDownKeyDown, ($2) => $2.filter(
        (e) => e.keyCode === 2
        /* KeyCode.Tab */
      ))(this.onEnter, this));
      this._register(Event.chain(onSelectDropDownKeyDown, ($2) => $2.filter(
        (e) => e.keyCode === 9
        /* KeyCode.Escape */
      ))(this.onEscape, this));
      this._register(Event.chain(onSelectDropDownKeyDown, ($2) => $2.filter(
        (e) => e.keyCode === 16
        /* KeyCode.UpArrow */
      ))(this.onUpArrow, this));
      this._register(Event.chain(onSelectDropDownKeyDown, ($2) => $2.filter(
        (e) => e.keyCode === 18
        /* KeyCode.DownArrow */
      ))(this.onDownArrow, this));
      this._register(Event.chain(onSelectDropDownKeyDown, ($2) => $2.filter(
        (e) => e.keyCode === 12
        /* KeyCode.PageDown */
      ))(this.onPageDown, this));
      this._register(Event.chain(onSelectDropDownKeyDown, ($2) => $2.filter(
        (e) => e.keyCode === 11
        /* KeyCode.PageUp */
      ))(this.onPageUp, this));
      this._register(Event.chain(onSelectDropDownKeyDown, ($2) => $2.filter(
        (e) => e.keyCode === 14
        /* KeyCode.Home */
      ))(this.onHome, this));
      this._register(Event.chain(onSelectDropDownKeyDown, ($2) => $2.filter(
        (e) => e.keyCode === 13
        /* KeyCode.End */
      ))(this.onEnd, this));
      this._register(Event.chain(onSelectDropDownKeyDown, ($2) => $2.filter((e) => e.keyCode >= 21 && e.keyCode <= 56 || e.keyCode >= 85 && e.keyCode <= 113))(this.onCharacter, this));
      this._register(addDisposableListener(this.selectList.getHTMLElement(), EventType$1.POINTER_UP, (e) => this.onPointerUp(e)));
      this._register(this.selectList.onMouseOver((e) => typeof e.index !== "undefined" && this.selectList.setFocus([e.index])));
      this._register(this.selectList.onDidChangeFocus((e) => this.onListFocus(e)));
      this._register(addDisposableListener(this.selectDropDownContainer, EventType$1.FOCUS_OUT, (e) => {
        if (!this._isVisible || isAncestor$1(e.relatedTarget, this.selectDropDownContainer)) {
          return;
        }
        this.onListBlur();
      }));
      this.selectList.getHTMLElement().setAttribute("aria-label", this.selectBoxOptions.ariaLabel || "");
      this.selectList.getHTMLElement().setAttribute("aria-expanded", "true");
      this.styleList();
    }
    // List methods
    // List mouse controller - active exit, select option, fire onDidSelect if change, return focus to parent select
    // Also takes in touchend events
    onPointerUp(e) {
      if (!this.selectList.length) {
        return;
      }
      EventHelper.stop(e);
      const target = e.target;
      if (!target) {
        return;
      }
      if (target.classList.contains("slider")) {
        return;
      }
      const listRowElement = target.closest(".monaco-list-row");
      if (!listRowElement) {
        return;
      }
      const index = Number(listRowElement.getAttribute("data-index"));
      const disabled = listRowElement.classList.contains("option-disabled");
      if (index >= 0 && index < this.options.length && !disabled) {
        this.selected = index;
        this.select(this.selected);
        this.selectList.setFocus([this.selected]);
        this.selectList.reveal(this.selectList.getFocus()[0]);
        if (this.selected !== this._currentSelection) {
          this._currentSelection = this.selected;
          this._onDidSelect.fire({
            index: this.selectElement.selectedIndex,
            selected: this.options[this.selected].text
          });
          if (!!this.options[this.selected] && !!this.options[this.selected].text) {
            this.setTitle(this.options[this.selected].text);
          }
        }
        this.hideSelectDropDown(true);
      }
    }
    // List Exit - passive - implicit no selection change, hide drop-down
    onListBlur() {
      if (this._sticky) {
        return;
      }
      if (this.selected !== this._currentSelection) {
        this.select(this._currentSelection);
      }
      this.hideSelectDropDown(false);
    }
    renderDescriptionMarkdown(text2, actionHandler) {
      const cleanRenderedMarkdown = (element) => {
        for (let i2 = 0; i2 < element.childNodes.length; i2++) {
          const child = element.childNodes.item(i2);
          const tagName = child.tagName && child.tagName.toLowerCase();
          if (tagName === "img") {
            child.remove();
          } else {
            cleanRenderedMarkdown(child);
          }
        }
      };
      const rendered = renderMarkdown$1({ value: text2, supportThemeIcons: true }, { actionHandler });
      rendered.element.classList.add("select-box-description-markdown");
      cleanRenderedMarkdown(rendered.element);
      return rendered;
    }
    // List Focus Change - passive - update details pane with newly focused element's data
    onListFocus(e) {
      if (!this._isVisible || !this._hasDetails) {
        return;
      }
      this.updateDetail(e.indexes[0]);
    }
    updateDetail(selectedIndex) {
      this._selectionDetailsDisposables.clear();
      this.selectionDetailsPane.textContent = "";
      const option2 = this.options[selectedIndex];
      const description = option2?.description ?? "";
      const descriptionIsMarkdown = option2?.descriptionIsMarkdown ?? false;
      if (description) {
        if (descriptionIsMarkdown) {
          const actionHandler = option2.descriptionMarkdownActionHandler;
          const result = this._selectionDetailsDisposables.add(this.renderDescriptionMarkdown(description, actionHandler));
          this.selectionDetailsPane.appendChild(result.element);
        } else {
          this.selectionDetailsPane.textContent = description;
        }
        this.selectionDetailsPane.style.display = "block";
      } else {
        this.selectionDetailsPane.style.display = "none";
      }
      this._skipLayout = true;
      this.contextViewProvider.layout();
      this._skipLayout = false;
    }
    // List keyboard controller
    // List exit - active - hide ContextView dropdown, reset selection, return focus to parent select
    onEscape(e) {
      EventHelper.stop(e);
      this.select(this._currentSelection);
      this.hideSelectDropDown(true);
    }
    // List exit - active - hide ContextView dropdown, return focus to parent select, fire onDidSelect if change
    onEnter(e) {
      EventHelper.stop(e);
      if (this.selected !== this._currentSelection) {
        this._currentSelection = this.selected;
        this._onDidSelect.fire({
          index: this.selectElement.selectedIndex,
          selected: this.options[this.selected].text
        });
        if (!!this.options[this.selected] && !!this.options[this.selected].text) {
          this.setTitle(this.options[this.selected].text);
        }
      }
      this.hideSelectDropDown(true);
    }
    // List navigation - have to handle a disabled option (jump over)
    onDownArrow(e) {
      if (this.selected < this.options.length - 1) {
        EventHelper.stop(e, true);
        const nextOptionDisabled = this.options[this.selected + 1].isDisabled;
        if (nextOptionDisabled && this.options.length > this.selected + 2) {
          this.selected += 2;
        } else if (nextOptionDisabled) {
          return;
        } else {
          this.selected++;
        }
        this.select(this.selected);
        this.selectList.setFocus([this.selected]);
        this.selectList.reveal(this.selectList.getFocus()[0]);
      }
    }
    onUpArrow(e) {
      if (this.selected > 0) {
        EventHelper.stop(e, true);
        const previousOptionDisabled = this.options[this.selected - 1].isDisabled;
        if (previousOptionDisabled && this.selected > 1) {
          this.selected -= 2;
        } else {
          this.selected--;
        }
        this.select(this.selected);
        this.selectList.setFocus([this.selected]);
        this.selectList.reveal(this.selectList.getFocus()[0]);
      }
    }
    onPageUp(e) {
      EventHelper.stop(e);
      this.selectList.focusPreviousPage();
      setTimeout(() => {
        this.selected = this.selectList.getFocus()[0];
        if (this.options[this.selected].isDisabled && this.selected < this.options.length - 1) {
          this.selected++;
          this.selectList.setFocus([this.selected]);
        }
        this.selectList.reveal(this.selected);
        this.select(this.selected);
      }, 1);
    }
    onPageDown(e) {
      EventHelper.stop(e);
      this.selectList.focusNextPage();
      setTimeout(() => {
        this.selected = this.selectList.getFocus()[0];
        if (this.options[this.selected].isDisabled && this.selected > 0) {
          this.selected--;
          this.selectList.setFocus([this.selected]);
        }
        this.selectList.reveal(this.selected);
        this.select(this.selected);
      }, 1);
    }
    onHome(e) {
      EventHelper.stop(e);
      if (this.options.length < 2) {
        return;
      }
      this.selected = 0;
      if (this.options[this.selected].isDisabled && this.selected > 1) {
        this.selected++;
      }
      this.selectList.setFocus([this.selected]);
      this.selectList.reveal(this.selected);
      this.select(this.selected);
    }
    onEnd(e) {
      EventHelper.stop(e);
      if (this.options.length < 2) {
        return;
      }
      this.selected = this.options.length - 1;
      if (this.options[this.selected].isDisabled && this.selected > 1) {
        this.selected--;
      }
      this.selectList.setFocus([this.selected]);
      this.selectList.reveal(this.selected);
      this.select(this.selected);
    }
    // Mimic option first character navigation of native select
    onCharacter(e) {
      const ch = KeyCodeUtils.toString(e.keyCode);
      let optionIndex = -1;
      for (let i2 = 0; i2 < this.options.length - 1; i2++) {
        optionIndex = (i2 + this.selected + 1) % this.options.length;
        if (this.options[optionIndex].text.charAt(0).toUpperCase() === ch && !this.options[optionIndex].isDisabled) {
          this.select(optionIndex);
          this.selectList.setFocus([optionIndex]);
          this.selectList.reveal(this.selectList.getFocus()[0]);
          EventHelper.stop(e);
          break;
        }
      }
    }
    dispose() {
      this.hideSelectDropDown(false);
      super.dispose();
    }
  };
  _SelectBoxList.DEFAULT_DROPDOWN_MINIMUM_BOTTOM_MARGIN = 32;
  _SelectBoxList.DEFAULT_DROPDOWN_MINIMUM_TOP_MARGIN = 2;
  _SelectBoxList.DEFAULT_MINIMUM_VISIBLE_OPTIONS = 3;
  let SelectBoxList = _SelectBoxList;
  class SelectBoxNative extends Disposable {
    constructor(options, selected, styles, selectBoxOptions) {
      super();
      this.selected = 0;
      this.selectBoxOptions = selectBoxOptions || /* @__PURE__ */ Object.create(null);
      this.options = [];
      this.selectElement = document.createElement("select");
      this.selectElement.className = "monaco-select-box";
      if (typeof this.selectBoxOptions.ariaLabel === "string") {
        this.selectElement.setAttribute("aria-label", this.selectBoxOptions.ariaLabel);
      }
      if (typeof this.selectBoxOptions.ariaDescription === "string") {
        this.selectElement.setAttribute("aria-description", this.selectBoxOptions.ariaDescription);
      }
      this._onDidSelect = this._register(new Emitter$1());
      this.styles = styles;
      this.registerListeners();
      this.setOptions(options, selected);
    }
    registerListeners() {
      this._register(Gesture.addTarget(this.selectElement));
      [EventType.Tap].forEach((eventType) => {
        this._register(addDisposableListener(this.selectElement, eventType, (e) => {
          this.selectElement.focus();
        }));
      });
      this._register(addStandardDisposableListener(this.selectElement, "click", (e) => {
        EventHelper.stop(e, true);
      }));
      this._register(addStandardDisposableListener(this.selectElement, "change", (e) => {
        this.selectElement.title = e.target.value;
        this._onDidSelect.fire({
          index: e.target.selectedIndex,
          selected: e.target.value
        });
      }));
      this._register(addStandardDisposableListener(this.selectElement, "keydown", (e) => {
        let showSelect = false;
        if (isMacintosh) {
          if (e.keyCode === 18 || e.keyCode === 16 || e.keyCode === 10) {
            showSelect = true;
          }
        } else {
          if (e.keyCode === 18 && e.altKey || e.keyCode === 10 || e.keyCode === 3) {
            showSelect = true;
          }
        }
        if (showSelect) {
          e.stopPropagation();
        }
      }));
    }
    get onDidSelect() {
      return this._onDidSelect.event;
    }
    setOptions(options, selected) {
      if (!this.options || !equals$1(this.options, options)) {
        this.options = options;
        this.selectElement.options.length = 0;
        this.options.forEach((option2, index) => {
          this.selectElement.add(this.createOption(option2.text, index, option2.isDisabled));
        });
      }
      if (selected !== void 0) {
        this.select(selected);
      }
    }
    select(index) {
      if (this.options.length === 0) {
        this.selected = 0;
      } else if (index >= 0 && index < this.options.length) {
        this.selected = index;
      } else if (index > this.options.length - 1) {
        this.select(this.options.length - 1);
      } else if (this.selected < 0) {
        this.selected = 0;
      }
      this.selectElement.selectedIndex = this.selected;
      if (this.selected < this.options.length && typeof this.options[this.selected].text === "string") {
        this.selectElement.title = this.options[this.selected].text;
      } else {
        this.selectElement.title = "";
      }
    }
    focus() {
      if (this.selectElement) {
        this.selectElement.tabIndex = 0;
        this.selectElement.focus();
      }
    }
    blur() {
      if (this.selectElement) {
        this.selectElement.tabIndex = -1;
        this.selectElement.blur();
      }
    }
    setFocusable(focusable) {
      this.selectElement.tabIndex = focusable ? 0 : -1;
    }
    render(container) {
      container.classList.add("select-container");
      container.appendChild(this.selectElement);
      this.setOptions(this.options, this.selected);
      this.applyStyles();
    }
    applyStyles() {
      if (this.selectElement) {
        this.selectElement.style.backgroundColor = this.styles.selectBackground ?? "";
        this.selectElement.style.color = this.styles.selectForeground ?? "";
        this.selectElement.style.borderColor = this.styles.selectBorder ?? "";
      }
    }
    createOption(value, index, disabled) {
      const option2 = document.createElement("option");
      option2.value = value;
      option2.text = value;
      option2.disabled = !!disabled;
      return option2;
    }
  }
  class SelectBox extends Widget$1 {
    constructor(options, selected, contextViewProvider, styles, selectBoxOptions) {
      super();
      if (isMacintosh && !selectBoxOptions?.useCustomDrawn) {
        this.selectBoxDelegate = new SelectBoxNative(options, selected, styles, selectBoxOptions);
      } else {
        this.selectBoxDelegate = new SelectBoxList(options, selected, contextViewProvider, styles, selectBoxOptions);
      }
      this._register(this.selectBoxDelegate);
    }
    // Public SelectBox Methods - routed through delegate interface
    get onDidSelect() {
      return this.selectBoxDelegate.onDidSelect;
    }
    setOptions(options, selected) {
      this.selectBoxDelegate.setOptions(options, selected);
    }
    select(index) {
      this.selectBoxDelegate.select(index);
    }
    focus() {
      this.selectBoxDelegate.focus();
    }
    blur() {
      this.selectBoxDelegate.blur();
    }
    setFocusable(focusable) {
      this.selectBoxDelegate.setFocusable(focusable);
    }
    render(container) {
      this.selectBoxDelegate.render(container);
    }
  }
  class BaseActionViewItem extends Disposable {
    get action() {
      return this._action;
    }
    constructor(context, action, options = {}) {
      super();
      this.options = options;
      this._context = context || this;
      this._action = action;
      if (action instanceof Action) {
        this._register(action.onDidChange((event) => {
          if (!this.element) {
            return;
          }
          this.handleActionChangeEvent(event);
        }));
      }
    }
    handleActionChangeEvent(event) {
      if (event.enabled !== void 0) {
        this.updateEnabled();
      }
      if (event.checked !== void 0) {
        this.updateChecked();
      }
      if (event.class !== void 0) {
        this.updateClass();
      }
      if (event.label !== void 0) {
        this.updateLabel();
        this.updateTooltip();
      }
      if (event.tooltip !== void 0) {
        this.updateTooltip();
      }
    }
    get actionRunner() {
      if (!this._actionRunner) {
        this._actionRunner = this._register(new ActionRunner());
      }
      return this._actionRunner;
    }
    set actionRunner(actionRunner) {
      this._actionRunner = actionRunner;
    }
    isEnabled() {
      return this._action.enabled;
    }
    setActionContext(newContext) {
      this._context = newContext;
    }
    render(container) {
      const element = this.element = container;
      this._register(Gesture.addTarget(container));
      const enableDragging = this.options && this.options.draggable;
      if (enableDragging) {
        container.draggable = true;
        if (isFirefox$1) {
          this._register(addDisposableListener(container, EventType$1.DRAG_START, (e) => e.dataTransfer?.setData(DataTransfers.TEXT, this._action.label)));
        }
      }
      this._register(addDisposableListener(element, EventType.Tap, (e) => this.onClick(e, true)));
      this._register(addDisposableListener(element, EventType$1.MOUSE_DOWN, (e) => {
        if (!enableDragging) {
          EventHelper.stop(e, true);
        }
        if (this._action.enabled && e.button === 0) {
          element.classList.add("active");
        }
      }));
      if (isMacintosh) {
        this._register(addDisposableListener(element, EventType$1.CONTEXT_MENU, (e) => {
          if (e.button === 0 && e.ctrlKey === true) {
            this.onClick(e);
          }
        }));
      }
      this._register(addDisposableListener(element, EventType$1.CLICK, (e) => {
        EventHelper.stop(e, true);
        if (!(this.options && this.options.isMenu)) {
          this.onClick(e);
        }
      }));
      this._register(addDisposableListener(element, EventType$1.DBLCLICK, (e) => {
        EventHelper.stop(e, true);
      }));
      [EventType$1.MOUSE_UP, EventType$1.MOUSE_OUT].forEach((event) => {
        this._register(addDisposableListener(element, event, (e) => {
          EventHelper.stop(e);
          element.classList.remove("active");
        }));
      });
    }
    onClick(event, preserveFocus = false) {
      EventHelper.stop(event, true);
      const context = isUndefinedOrNull(this._context) ? this.options?.useEventAsContext ? event : { preserveFocus } : this._context;
      this.actionRunner.run(this._action, context);
    }
    // Only set the tabIndex on the element once it is about to get focused
    // That way this element wont be a tab stop when it is not needed #106441
    focus() {
      if (this.element) {
        this.element.tabIndex = 0;
        this.element.focus();
        this.element.classList.add("focused");
      }
    }
    blur() {
      if (this.element) {
        this.element.blur();
        this.element.tabIndex = -1;
        this.element.classList.remove("focused");
      }
    }
    setFocusable(focusable) {
      if (this.element) {
        this.element.tabIndex = focusable ? 0 : -1;
      }
    }
    get trapsArrowNavigation() {
      return false;
    }
    updateEnabled() {
    }
    updateLabel() {
    }
    getClass() {
      return this.action.class;
    }
    getTooltip() {
      return this.action.tooltip;
    }
    getHoverContents() {
      return this.getTooltip();
    }
    updateTooltip() {
      if (!this.element) {
        return;
      }
      const title = this.getHoverContents() ?? "";
      this.updateAriaLabel();
      if (!this.customHover && title !== "") {
        const hoverDelegate = this.options.hoverDelegate ?? getDefaultHoverDelegate("element");
        this.customHover = this._store.add(getBaseLayerHoverDelegate().setupManagedHover(hoverDelegate, this.element, title));
      } else if (this.customHover) {
        this.customHover.update(title);
      }
    }
    updateAriaLabel() {
      if (this.element) {
        const title = this.getTooltip() ?? "";
        this.element.setAttribute("aria-label", title);
      }
    }
    updateClass() {
    }
    updateChecked() {
    }
    dispose() {
      if (this.element) {
        this.element.remove();
        this.element = void 0;
      }
      this._context = void 0;
      super.dispose();
    }
  }
  class ActionViewItem extends BaseActionViewItem {
    constructor(context, action, options) {
      options = {
        ...options,
        icon: options.icon !== void 0 ? options.icon : false,
        label: options.label !== void 0 ? options.label : true
      };
      super(context, action, options);
      this.options = options;
      this.cssClass = "";
    }
    render(container) {
      super.render(container);
      assertType(this.element);
      const label = document.createElement("a");
      label.classList.add("action-label");
      label.setAttribute("role", this.getDefaultAriaRole());
      this.label = label;
      this.element.appendChild(label);
      if (this.options.label && this.options.keybinding && !this.options.keybindingNotRenderedWithLabel) {
        const kbLabel = document.createElement("span");
        kbLabel.classList.add("keybinding");
        kbLabel.textContent = this.options.keybinding;
        this.element.appendChild(kbLabel);
      }
      this.updateClass();
      this.updateLabel();
      this.updateTooltip();
      this.updateEnabled();
      this.updateChecked();
    }
    getDefaultAriaRole() {
      if (this._action.id === Separator.ID) {
        return "presentation";
      } else {
        if (this.options.isMenu) {
          return "menuitem";
        } else if (this.options.isTabList) {
          return "tab";
        } else {
          return "button";
        }
      }
    }
    // Only set the tabIndex on the element once it is about to get focused
    // That way this element wont be a tab stop when it is not needed #106441
    focus() {
      if (this.label) {
        this.label.tabIndex = 0;
        this.label.focus();
      }
    }
    blur() {
      if (this.label) {
        this.label.tabIndex = -1;
      }
    }
    setFocusable(focusable) {
      if (this.label) {
        this.label.tabIndex = focusable ? 0 : -1;
      }
    }
    updateLabel() {
      if (this.options.label && this.label) {
        this.label.textContent = this.action.label;
      }
    }
    getTooltip() {
      let title = null;
      if (this.action.tooltip) {
        title = this.action.tooltip;
      } else if (this.action.label) {
        title = this.action.label;
        if (this.options.keybinding) {
          title = localize(0, "{0} ({1})", title, this.options.keybinding);
        }
      }
      return title ?? void 0;
    }
    updateClass() {
      if (this.cssClass && this.label) {
        this.label.classList.remove(...this.cssClass.split(" "));
      }
      if (this.options.icon) {
        this.cssClass = this.getClass();
        if (this.label) {
          this.label.classList.add("codicon");
          if (this.cssClass) {
            this.label.classList.add(...this.cssClass.split(" "));
          }
        }
        this.updateEnabled();
      } else {
        this.label?.classList.remove("codicon");
      }
    }
    updateEnabled() {
      if (this.action.enabled) {
        if (this.label) {
          this.label.removeAttribute("aria-disabled");
          this.label.classList.remove("disabled");
        }
        this.element?.classList.remove("disabled");
      } else {
        if (this.label) {
          this.label.setAttribute("aria-disabled", "true");
          this.label.classList.add("disabled");
        }
        this.element?.classList.add("disabled");
      }
    }
    updateAriaLabel() {
      if (this.label) {
        const title = this.getTooltip() ?? "";
        this.label.setAttribute("aria-label", title);
      }
    }
    updateChecked() {
      if (this.label) {
        if (this.action.checked !== void 0) {
          this.label.classList.toggle("checked", this.action.checked);
          if (this.options.isTabList) {
            this.label.setAttribute("aria-selected", this.action.checked ? "true" : "false");
          } else {
            this.label.setAttribute("aria-checked", this.action.checked ? "true" : "false");
            this.label.setAttribute("role", "checkbox");
          }
        } else {
          this.label.classList.remove("checked");
          this.label.removeAttribute(this.options.isTabList ? "aria-selected" : "aria-checked");
          this.label.setAttribute("role", this.getDefaultAriaRole());
        }
      }
    }
  }
  class SelectActionViewItem extends BaseActionViewItem {
    constructor(ctx, action, options, selected, contextViewProvider, styles, selectBoxOptions) {
      super(ctx, action);
      this.selectBox = new SelectBox(options, selected, contextViewProvider, styles, selectBoxOptions);
      this.selectBox.setFocusable(false);
      this._register(this.selectBox);
      this.registerListeners();
    }
    select(index) {
      this.selectBox.select(index);
    }
    registerListeners() {
      this._register(this.selectBox.onDidSelect((e) => this.runAction(e.selected, e.index)));
    }
    runAction(option2, index) {
      this.actionRunner.run(this._action, this.getActionContext(option2, index));
    }
    getActionContext(option2, index) {
      return option2;
    }
    setFocusable(focusable) {
      this.selectBox.setFocusable(focusable);
    }
    focus() {
      this.selectBox?.focus();
    }
    blur() {
      this.selectBox?.blur();
    }
    render(container) {
      this.selectBox.render(container);
    }
  }
  class ActionBar extends Disposable {
    get onDidBlur() {
      return this._onDidBlur.event;
    }
    get onDidCancel() {
      return this._onDidCancel.event;
    }
    get onDidRun() {
      return this._onDidRun.event;
    }
    get onWillRun() {
      return this._onWillRun.event;
    }
    constructor(container, options = {}) {
      super();
      this._actionRunnerDisposables = this._register(new DisposableStore());
      this.viewItemDisposables = this._register(new DisposableMap());
      this.triggerKeyDown = false;
      this.focusable = true;
      this._onDidBlur = this._register(new Emitter$1());
      this._onDidCancel = this._register(new Emitter$1({ onWillAddFirstListener: () => this.cancelHasListener = true }));
      this.cancelHasListener = false;
      this._onDidRun = this._register(new Emitter$1());
      this._onWillRun = this._register(new Emitter$1());
      this.options = options;
      this._context = options.context ?? null;
      this._orientation = this.options.orientation ?? 0;
      this._triggerKeys = {
        keyDown: this.options.triggerKeys?.keyDown ?? false,
        keys: this.options.triggerKeys?.keys ?? [
          3,
          10
          /* KeyCode.Space */
        ]
      };
      this._hoverDelegate = options.hoverDelegate ?? this._register(createInstantHoverDelegate());
      if (this.options.actionRunner) {
        this._actionRunner = this.options.actionRunner;
      } else {
        this._actionRunner = new ActionRunner();
        this._actionRunnerDisposables.add(this._actionRunner);
      }
      this._actionRunnerDisposables.add(this._actionRunner.onDidRun((e) => this._onDidRun.fire(e)));
      this._actionRunnerDisposables.add(this._actionRunner.onWillRun((e) => this._onWillRun.fire(e)));
      this.viewItems = [];
      this.focusedItem = void 0;
      this.domNode = document.createElement("div");
      this.domNode.className = "monaco-action-bar";
      let previousKeys;
      let nextKeys;
      switch (this._orientation) {
        case 0:
          previousKeys = [
            15
            /* KeyCode.LeftArrow */
          ];
          nextKeys = [
            17
            /* KeyCode.RightArrow */
          ];
          break;
        case 1:
          previousKeys = [
            16
            /* KeyCode.UpArrow */
          ];
          nextKeys = [
            18
            /* KeyCode.DownArrow */
          ];
          this.domNode.className += " vertical";
          break;
      }
      this._register(addDisposableListener(this.domNode, EventType$1.KEY_DOWN, (e) => {
        const event = new StandardKeyboardEvent(e);
        let eventHandled = true;
        const focusedItem = typeof this.focusedItem === "number" ? this.viewItems[this.focusedItem] : void 0;
        if (previousKeys && (event.equals(previousKeys[0]) || event.equals(previousKeys[1]))) {
          eventHandled = this.focusPrevious();
        } else if (nextKeys && (event.equals(nextKeys[0]) || event.equals(nextKeys[1]))) {
          eventHandled = this.focusNext();
        } else if (event.equals(
          9
          /* KeyCode.Escape */
        ) && this.cancelHasListener) {
          this._onDidCancel.fire();
        } else if (event.equals(
          14
          /* KeyCode.Home */
        )) {
          eventHandled = this.focusFirst();
        } else if (event.equals(
          13
          /* KeyCode.End */
        )) {
          eventHandled = this.focusLast();
        } else if (event.equals(
          2
          /* KeyCode.Tab */
        ) && focusedItem instanceof BaseActionViewItem && focusedItem.trapsArrowNavigation) {
          eventHandled = this.focusNext(void 0, true);
        } else if (this.isTriggerKeyEvent(event)) {
          if (this._triggerKeys.keyDown) {
            this.doTrigger(event);
          } else {
            this.triggerKeyDown = true;
          }
        } else {
          eventHandled = false;
        }
        if (eventHandled) {
          event.preventDefault();
          event.stopPropagation();
        }
      }));
      this._register(addDisposableListener(this.domNode, EventType$1.KEY_UP, (e) => {
        const event = new StandardKeyboardEvent(e);
        if (this.isTriggerKeyEvent(event)) {
          if (!this._triggerKeys.keyDown && this.triggerKeyDown) {
            this.triggerKeyDown = false;
            this.doTrigger(event);
          }
          event.preventDefault();
          event.stopPropagation();
        } else if (event.equals(
          2
          /* KeyCode.Tab */
        ) || event.equals(
          1024 | 2
          /* KeyCode.Tab */
        ) || event.equals(
          16
          /* KeyCode.UpArrow */
        ) || event.equals(
          18
          /* KeyCode.DownArrow */
        ) || event.equals(
          15
          /* KeyCode.LeftArrow */
        ) || event.equals(
          17
          /* KeyCode.RightArrow */
        )) {
          this.updateFocusedItem();
        }
      }));
      this.focusTracker = this._register(trackFocus(this.domNode));
      this._register(this.focusTracker.onDidBlur(() => {
        if (getActiveElement() === this.domNode || !isAncestor$1(getActiveElement(), this.domNode)) {
          this._onDidBlur.fire();
          this.previouslyFocusedItem = this.focusedItem;
          this.focusedItem = void 0;
          this.triggerKeyDown = false;
        }
      }));
      this._register(this.focusTracker.onDidFocus(() => this.updateFocusedItem()));
      this.actionsList = document.createElement("ul");
      this.actionsList.className = "actions-container";
      if (this.options.highlightToggledItems) {
        this.actionsList.classList.add("highlight-toggled");
      }
      this.actionsList.setAttribute("role", this.options.ariaRole || "toolbar");
      if (this.options.ariaLabel) {
        this.actionsList.setAttribute("aria-label", this.options.ariaLabel);
      }
      this.domNode.appendChild(this.actionsList);
      container.appendChild(this.domNode);
    }
    refreshRole() {
      if (this.length() >= 1) {
        this.actionsList.setAttribute("role", this.options.ariaRole || "toolbar");
      } else {
        this.actionsList.setAttribute("role", "presentation");
      }
    }
    // Some action bars should not be focusable at times
    // When an action bar is not focusable make sure to make all the elements inside it not focusable
    // When an action bar is focusable again, make sure the first item can be focused
    setFocusable(focusable) {
      this.focusable = focusable;
      if (this.focusable) {
        const firstEnabled = this.viewItems.find((vi) => vi instanceof BaseActionViewItem && vi.isEnabled());
        if (firstEnabled instanceof BaseActionViewItem) {
          firstEnabled.setFocusable(true);
        }
      } else {
        this.viewItems.forEach((vi) => {
          if (vi instanceof BaseActionViewItem) {
            vi.setFocusable(false);
          }
        });
      }
    }
    isTriggerKeyEvent(event) {
      let ret = false;
      this._triggerKeys.keys.forEach((keyCode) => {
        ret = ret || event.equals(keyCode);
      });
      return ret;
    }
    updateFocusedItem() {
      for (let i2 = 0; i2 < this.actionsList.children.length; i2++) {
        const elem = this.actionsList.children[i2];
        if (isAncestor$1(getActiveElement(), elem)) {
          this.focusedItem = i2;
          this.viewItems[this.focusedItem]?.showHover?.();
          break;
        }
      }
    }
    get context() {
      return this._context;
    }
    set context(context) {
      this._context = context;
      this.viewItems.forEach((i2) => i2.setActionContext(context));
    }
    get actionRunner() {
      return this._actionRunner;
    }
    set actionRunner(actionRunner) {
      this._actionRunner = actionRunner;
      this._actionRunnerDisposables.clear();
      this._actionRunnerDisposables.add(this._actionRunner.onDidRun((e) => this._onDidRun.fire(e)));
      this._actionRunnerDisposables.add(this._actionRunner.onWillRun((e) => this._onWillRun.fire(e)));
      this.viewItems.forEach((item) => item.actionRunner = actionRunner);
    }
    getContainer() {
      return this.domNode;
    }
    getAction(indexOrElement) {
      if (typeof indexOrElement === "number") {
        return this.viewItems[indexOrElement]?.action;
      }
      if (isHTMLElement(indexOrElement)) {
        while (indexOrElement.parentElement !== this.actionsList) {
          if (!indexOrElement.parentElement) {
            return void 0;
          }
          indexOrElement = indexOrElement.parentElement;
        }
        for (let i2 = 0; i2 < this.actionsList.childNodes.length; i2++) {
          if (this.actionsList.childNodes[i2] === indexOrElement) {
            return this.viewItems[i2].action;
          }
        }
      }
      return void 0;
    }
    push(arg, options = {}) {
      const actions = Array.isArray(arg) ? arg : [arg];
      let index = isNumber$1(options.index) ? options.index : null;
      actions.forEach((action) => {
        const actionViewItemElement = document.createElement("li");
        actionViewItemElement.className = "action-item";
        actionViewItemElement.setAttribute("role", "presentation");
        let item;
        const viewItemOptions = { hoverDelegate: this._hoverDelegate, ...options, isTabList: this.options.ariaRole === "tablist" };
        if (this.options.actionViewItemProvider) {
          item = this.options.actionViewItemProvider(action, viewItemOptions);
        }
        if (!item) {
          item = new ActionViewItem(this.context, action, viewItemOptions);
        }
        if (!this.options.allowContextMenu) {
          this.viewItemDisposables.set(item, addDisposableListener(actionViewItemElement, EventType$1.CONTEXT_MENU, (e) => {
            EventHelper.stop(e, true);
          }));
        }
        item.actionRunner = this._actionRunner;
        item.setActionContext(this.context);
        item.render(actionViewItemElement);
        if (index === null || index < 0 || index >= this.actionsList.children.length) {
          this.actionsList.appendChild(actionViewItemElement);
          this.viewItems.push(item);
        } else {
          this.actionsList.insertBefore(actionViewItemElement, this.actionsList.children[index]);
          this.viewItems.splice(index, 0, item);
          index++;
        }
      });
      if (this.focusable) {
        let didFocus = false;
        for (const item of this.viewItems) {
          if (!(item instanceof BaseActionViewItem)) {
            continue;
          }
          let focus;
          if (didFocus) {
            focus = false;
          } else if (item.action.id === Separator.ID) {
            focus = false;
          } else if (!item.isEnabled() && this.options.focusOnlyEnabledItems) {
            focus = false;
          } else {
            focus = true;
          }
          if (focus) {
            item.setFocusable(true);
            didFocus = true;
          } else {
            item.setFocusable(false);
          }
        }
      }
      if (typeof this.focusedItem === "number") {
        this.focus(this.focusedItem);
      }
      this.refreshRole();
    }
    getWidth(index) {
      if (index >= 0 && index < this.actionsList.children.length) {
        const item = this.actionsList.children.item(index);
        if (item) {
          return item.clientWidth;
        }
      }
      return 0;
    }
    pull(index) {
      if (index >= 0 && index < this.viewItems.length) {
        this.actionsList.childNodes[index].remove();
        this.viewItemDisposables.deleteAndDispose(this.viewItems[index]);
        dispose(this.viewItems.splice(index, 1));
        this.refreshRole();
      }
    }
    clear() {
      if (this.isEmpty()) {
        return;
      }
      this.viewItems = dispose(this.viewItems);
      this.viewItemDisposables.clearAndDisposeAll();
      clearNode(this.actionsList);
      this.refreshRole();
    }
    length() {
      return this.viewItems.length;
    }
    isEmpty() {
      return this.viewItems.length === 0;
    }
    focus(arg) {
      let selectFirst = false;
      let index = void 0;
      if (arg === void 0) {
        selectFirst = true;
      } else if (typeof arg === "number") {
        index = arg;
      } else if (typeof arg === "boolean") {
        selectFirst = arg;
      }
      if (selectFirst && typeof this.focusedItem === "undefined") {
        const firstEnabled = this.viewItems.findIndex((item) => item.isEnabled());
        this.focusedItem = firstEnabled === -1 ? void 0 : firstEnabled;
        this.updateFocus(void 0, void 0, true);
      } else {
        if (index !== void 0) {
          this.focusedItem = index;
        }
        this.updateFocus(void 0, void 0, true);
      }
    }
    focusFirst() {
      this.focusedItem = this.length() - 1;
      return this.focusNext(true);
    }
    focusLast() {
      this.focusedItem = 0;
      return this.focusPrevious(true);
    }
    focusNext(forceLoop, forceFocus) {
      if (typeof this.focusedItem === "undefined") {
        this.focusedItem = this.viewItems.length - 1;
      } else if (this.viewItems.length <= 1) {
        return false;
      }
      const startIndex = this.focusedItem;
      let item;
      do {
        if (!forceLoop && this.options.preventLoopNavigation && this.focusedItem + 1 >= this.viewItems.length) {
          this.focusedItem = startIndex;
          return false;
        }
        this.focusedItem = (this.focusedItem + 1) % this.viewItems.length;
        item = this.viewItems[this.focusedItem];
      } while (this.focusedItem !== startIndex && (this.options.focusOnlyEnabledItems && !item.isEnabled() || item.action.id === Separator.ID));
      this.updateFocus(void 0, void 0, forceFocus);
      return true;
    }
    focusPrevious(forceLoop) {
      if (typeof this.focusedItem === "undefined") {
        this.focusedItem = 0;
      } else if (this.viewItems.length <= 1) {
        return false;
      }
      const startIndex = this.focusedItem;
      let item;
      do {
        this.focusedItem = this.focusedItem - 1;
        if (this.focusedItem < 0) {
          if (!forceLoop && this.options.preventLoopNavigation) {
            this.focusedItem = startIndex;
            return false;
          }
          this.focusedItem = this.viewItems.length - 1;
        }
        item = this.viewItems[this.focusedItem];
      } while (this.focusedItem !== startIndex && (this.options.focusOnlyEnabledItems && !item.isEnabled() || item.action.id === Separator.ID));
      this.updateFocus(true);
      return true;
    }
    updateFocus(fromRight, preventScroll, forceFocus = false) {
      if (typeof this.focusedItem === "undefined") {
        this.actionsList.focus({ preventScroll });
      }
      if (this.previouslyFocusedItem !== void 0 && this.previouslyFocusedItem !== this.focusedItem) {
        this.viewItems[this.previouslyFocusedItem]?.blur();
      }
      const actionViewItem = this.focusedItem !== void 0 ? this.viewItems[this.focusedItem] : void 0;
      if (actionViewItem) {
        let focusItem = true;
        if (!isFunction(actionViewItem.focus)) {
          focusItem = false;
        }
        if (this.options.focusOnlyEnabledItems && isFunction(actionViewItem.isEnabled) && !actionViewItem.isEnabled()) {
          focusItem = false;
        }
        if (actionViewItem.action.id === Separator.ID) {
          focusItem = false;
        }
        if (!focusItem) {
          this.actionsList.focus({ preventScroll });
          this.previouslyFocusedItem = void 0;
        } else if (forceFocus || this.previouslyFocusedItem !== this.focusedItem) {
          actionViewItem.focus(fromRight);
          this.previouslyFocusedItem = this.focusedItem;
        }
        if (focusItem) {
          actionViewItem.showHover?.();
        }
      }
    }
    doTrigger(event) {
      if (typeof this.focusedItem === "undefined") {
        return;
      }
      const actionViewItem = this.viewItems[this.focusedItem];
      if (actionViewItem instanceof BaseActionViewItem) {
        const context = actionViewItem._context === null || actionViewItem._context === void 0 ? event : actionViewItem._context;
        this.run(actionViewItem._action, context);
      }
    }
    async run(action, context) {
      await this._actionRunner.run(action, context);
    }
    dispose() {
      this._context = void 0;
      this.viewItems = dispose(this.viewItems);
      this.getContainer().remove();
      super.dispose();
    }
  }
  function joinCombine(arr1, arr2, keySelector, combine) {
    if (arr1.length === 0) {
      return arr2;
    }
    if (arr2.length === 0) {
      return arr1;
    }
    const result = [];
    let i2 = 0;
    let j = 0;
    while (i2 < arr1.length && j < arr2.length) {
      const val1 = arr1[i2];
      const val2 = arr2[j];
      const key1 = keySelector(val1);
      const key2 = keySelector(val2);
      if (key1 < key2) {
        result.push(val1);
        i2++;
      } else if (key1 > key2) {
        result.push(val2);
        j++;
      } else {
        result.push(combine(val1, val2));
        i2++;
        j++;
      }
    }
    while (i2 < arr1.length) {
      result.push(arr1[i2]);
      i2++;
    }
    while (j < arr2.length) {
      result.push(arr2[j]);
      j++;
    }
    return result;
  }
  function applyObservableDecorations(editor2, decorations) {
    const d = new DisposableStore();
    const decorationsCollection = editor2.createDecorationsCollection();
    d.add(autorunOpts({ debugName: () => `Apply decorations from ${decorations.debugName}` }, (reader) => {
      const d2 = decorations.read(reader);
      decorationsCollection.set(d2);
    }));
    d.add({
      dispose: () => {
        decorationsCollection.clear();
      }
    });
    return d;
  }
  function appendRemoveOnDispose(parent, child) {
    parent.appendChild(child);
    return toDisposable(() => {
      child.remove();
    });
  }
  function prependRemoveOnDispose(parent, child) {
    parent.prepend(child);
    return toDisposable(() => {
      child.remove();
    });
  }
  class ObservableElementSizeObserver extends Disposable {
    get width() {
      return this._width;
    }
    get height() {
      return this._height;
    }
    get automaticLayout() {
      return this._automaticLayout;
    }
    constructor(element, dimension) {
      super();
      this._automaticLayout = false;
      this.elementSizeObserver = this._register(new ElementSizeObserver(element, dimension));
      this._width = observableValue(this, this.elementSizeObserver.getWidth());
      this._height = observableValue(this, this.elementSizeObserver.getHeight());
      this._register(this.elementSizeObserver.onDidChange((e) => transaction((tx) => {
        this._width.set(this.elementSizeObserver.getWidth(), tx);
        this._height.set(this.elementSizeObserver.getHeight(), tx);
      })));
    }
    observe(dimension) {
      this.elementSizeObserver.observe(dimension);
    }
    setAutomaticLayout(automaticLayout) {
      this._automaticLayout = automaticLayout;
      if (automaticLayout) {
        this.elementSizeObserver.startObserving();
      } else {
        this.elementSizeObserver.stopObserving();
      }
    }
  }
  function animatedObservable(targetWindow, base, store) {
    let targetVal = base.get();
    let startVal = targetVal;
    let curVal = targetVal;
    const result = observableValue("animatedValue", targetVal);
    let animationStartMs = -1;
    const durationMs = 300;
    let animationFrame = void 0;
    store.add(autorunHandleChanges({
      changeTracker: {
        createChangeSummary: () => ({ animate: false }),
        handleChange: (ctx, s) => {
          if (ctx.didChange(base)) {
            s.animate = s.animate || ctx.change;
          }
          return true;
        }
      }
    }, (reader, s) => {
      if (animationFrame !== void 0) {
        targetWindow.cancelAnimationFrame(animationFrame);
        animationFrame = void 0;
      }
      startVal = curVal;
      targetVal = base.read(reader);
      animationStartMs = Date.now() - (s.animate ? 0 : durationMs);
      update();
    }));
    function update() {
      const passedMs = Date.now() - animationStartMs;
      curVal = Math.floor(easeOutExpo$1(passedMs, startVal, targetVal - startVal, durationMs));
      if (passedMs < durationMs) {
        animationFrame = targetWindow.requestAnimationFrame(update);
      } else {
        curVal = targetVal;
      }
      result.set(curVal, void 0);
    }
    return result;
  }
  function easeOutExpo$1(t, b, c, d) {
    return t === d ? b + c : c * (-Math.pow(2, -10 * t / d) + 1) + b;
  }
  class ViewZoneOverlayWidget extends Disposable {
    constructor(editor2, viewZone, htmlElement) {
      super();
      this._register(new ManagedOverlayWidget(editor2, htmlElement));
      this._register(applyStyle(htmlElement, {
        height: viewZone.actualHeight,
        top: viewZone.actualTop
      }));
    }
  }
  class PlaceholderViewZone {
    get afterLineNumber() {
      return this._afterLineNumber.get();
    }
    constructor(_afterLineNumber, heightInPx) {
      this._afterLineNumber = _afterLineNumber;
      this.heightInPx = heightInPx;
      this.domNode = document.createElement("div");
      this._actualTop = observableValue(this, void 0);
      this._actualHeight = observableValue(this, void 0);
      this.actualTop = this._actualTop;
      this.actualHeight = this._actualHeight;
      this.showInHiddenAreas = true;
      this.onChange = this._afterLineNumber;
      this.onDomNodeTop = (top) => {
        this._actualTop.set(top, void 0);
      };
      this.onComputedHeight = (height) => {
        this._actualHeight.set(height, void 0);
      };
    }
  }
  const _ManagedOverlayWidget = class _ManagedOverlayWidget {
    constructor(_editor, _domElement) {
      this._editor = _editor;
      this._domElement = _domElement;
      this._overlayWidgetId = `managedOverlayWidget-${_ManagedOverlayWidget._counter++}`;
      this._overlayWidget = {
        getId: () => this._overlayWidgetId,
        getDomNode: () => this._domElement,
        getPosition: () => null
      };
      this._editor.addOverlayWidget(this._overlayWidget);
    }
    dispose() {
      this._editor.removeOverlayWidget(this._overlayWidget);
    }
  };
  _ManagedOverlayWidget._counter = 0;
  let ManagedOverlayWidget = _ManagedOverlayWidget;
  function applyStyle(domNode, style) {
    return autorun((reader) => {
      for (let [key, val] of Object.entries(style)) {
        if (val && typeof val === "object" && "read" in val) {
          val = val.read(reader);
        }
        if (typeof val === "number") {
          val = `${val}px`;
        }
        key = key.replace(/[A-Z]/g, (m) => "-" + m.toLowerCase());
        domNode.style[key] = val;
      }
    });
  }
  function applyViewZones(editor2, viewZones, setIsUpdating, zoneIds) {
    const store = new DisposableStore();
    const lastViewZoneIds = [];
    store.add(autorunWithStore((reader, store2) => {
      const curViewZones = viewZones.read(reader);
      const viewZonIdsPerViewZone = /* @__PURE__ */ new Map();
      const viewZoneIdPerOnChangeObservable = /* @__PURE__ */ new Map();
      if (setIsUpdating) {
        setIsUpdating(true);
      }
      editor2.changeViewZones((a) => {
        for (const id of lastViewZoneIds) {
          a.removeZone(id);
          zoneIds?.delete(id);
        }
        lastViewZoneIds.length = 0;
        for (const z of curViewZones) {
          const id = a.addZone(z);
          if (z.setZoneId) {
            z.setZoneId(id);
          }
          lastViewZoneIds.push(id);
          zoneIds?.add(id);
          viewZonIdsPerViewZone.set(z, id);
        }
      });
      if (setIsUpdating) {
        setIsUpdating(false);
      }
      store2.add(autorunHandleChanges({
        changeTracker: {
          createChangeSummary() {
            return { zoneIds: [] };
          },
          handleChange(context, changeSummary) {
            const id = viewZoneIdPerOnChangeObservable.get(context.changedObservable);
            if (id !== void 0) {
              changeSummary.zoneIds.push(id);
            }
            return true;
          }
        }
      }, (reader2, changeSummary) => {
        for (const vz of curViewZones) {
          if (vz.onChange) {
            viewZoneIdPerOnChangeObservable.set(vz.onChange, viewZonIdsPerViewZone.get(vz));
            vz.onChange.read(reader2);
          }
        }
        if (setIsUpdating) {
          setIsUpdating(true);
        }
        editor2.changeViewZones((a) => {
          for (const id of changeSummary.zoneIds) {
            a.layoutZone(id);
          }
        });
        if (setIsUpdating) {
          setIsUpdating(false);
        }
      }));
    }));
    store.add({
      dispose() {
        if (setIsUpdating) {
          setIsUpdating(true);
        }
        editor2.changeViewZones((a) => {
          for (const id of lastViewZoneIds) {
            a.removeZone(id);
          }
        });
        zoneIds?.clear();
        if (setIsUpdating) {
          setIsUpdating(false);
        }
      }
    });
    return store;
  }
  class DisposableCancellationTokenSource extends CancellationTokenSource$1 {
    dispose() {
      super.dispose(true);
    }
  }
  function translatePosition(posInOriginal, mappings) {
    const mapping = findLast(mappings, (m) => m.original.startLineNumber <= posInOriginal.lineNumber);
    if (!mapping) {
      return Range$2.fromPositions(posInOriginal);
    }
    if (mapping.original.endLineNumberExclusive <= posInOriginal.lineNumber) {
      const newLineNumber = posInOriginal.lineNumber - mapping.original.endLineNumberExclusive + mapping.modified.endLineNumberExclusive;
      return Range$2.fromPositions(new Position$1(newLineNumber, posInOriginal.column));
    }
    if (!mapping.innerChanges) {
      return Range$2.fromPositions(new Position$1(mapping.modified.startLineNumber, 1));
    }
    const innerMapping = findLast(mapping.innerChanges, (m) => m.originalRange.getStartPosition().isBeforeOrEqual(posInOriginal));
    if (!innerMapping) {
      const newLineNumber = posInOriginal.lineNumber - mapping.original.startLineNumber + mapping.modified.startLineNumber;
      return Range$2.fromPositions(new Position$1(newLineNumber, posInOriginal.column));
    }
    if (innerMapping.originalRange.containsPosition(posInOriginal)) {
      return innerMapping.modifiedRange;
    } else {
      const l = lengthBetweenPositions(innerMapping.originalRange.getEndPosition(), posInOriginal);
      return Range$2.fromPositions(l.addToPosition(innerMapping.modifiedRange.getEndPosition()));
    }
  }
  function lengthBetweenPositions(position1, position2) {
    if (position1.lineNumber === position2.lineNumber) {
      return new TextLength(0, position2.column - position1.column);
    } else {
      return new TextLength(position2.lineNumber - position1.lineNumber, position2.column - 1);
    }
  }
  function filterWithPrevious(arr, filter) {
    let prev;
    return arr.filter((cur) => {
      const result = filter(cur, prev);
      prev = cur;
      return result;
    });
  }
  class RefCounted {
    static create(value, debugOwner = void 0) {
      return new BaseRefCounted(value, value, debugOwner);
    }
    static createWithDisposable(value, disposable, debugOwner = void 0) {
      const store = new DisposableStore();
      store.add(disposable);
      store.add(value);
      return new BaseRefCounted(value, store, debugOwner);
    }
  }
  class BaseRefCounted extends RefCounted {
    constructor(object, _disposable, _debugOwner) {
      super();
      this.object = object;
      this._disposable = _disposable;
      this._debugOwner = _debugOwner;
      this._refCount = 1;
      this._isDisposed = false;
      this._owners = [];
      if (_debugOwner) {
        this._addOwner(_debugOwner);
      }
    }
    _addOwner(debugOwner) {
      if (debugOwner) {
        this._owners.push(debugOwner);
      }
    }
    createNewRef(debugOwner) {
      this._refCount++;
      if (debugOwner) {
        this._addOwner(debugOwner);
      }
      return new ClonedRefCounted(this, debugOwner);
    }
    dispose() {
      if (this._isDisposed) {
        return;
      }
      this._isDisposed = true;
      this._decreaseRefCount(this._debugOwner);
    }
    _decreaseRefCount(debugOwner) {
      this._refCount--;
      if (this._refCount === 0) {
        this._disposable.dispose();
      }
      if (debugOwner) {
        const idx = this._owners.indexOf(debugOwner);
        if (idx !== -1) {
          this._owners.splice(idx, 1);
        }
      }
    }
  }
  class ClonedRefCounted extends RefCounted {
    constructor(_base, _debugOwner) {
      super();
      this._base = _base;
      this._debugOwner = _debugOwner;
      this._isDisposed = false;
    }
    get object() {
      return this._base.object;
    }
    createNewRef(debugOwner) {
      return this._base.createNewRef(debugOwner);
    }
    dispose() {
      if (this._isDisposed) {
        return;
      }
      this._isDisposed = true;
      this._base._decreaseRefCount(this._debugOwner);
    }
  }
  class LineRangeMapping {
    static inverse(mapping, originalLineCount, modifiedLineCount) {
      const result = [];
      let lastOriginalEndLineNumber = 1;
      let lastModifiedEndLineNumber = 1;
      for (const m of mapping) {
        const r2 = new LineRangeMapping(new LineRange(lastOriginalEndLineNumber, m.original.startLineNumber), new LineRange(lastModifiedEndLineNumber, m.modified.startLineNumber));
        if (!r2.modified.isEmpty) {
          result.push(r2);
        }
        lastOriginalEndLineNumber = m.original.endLineNumberExclusive;
        lastModifiedEndLineNumber = m.modified.endLineNumberExclusive;
      }
      const r = new LineRangeMapping(new LineRange(lastOriginalEndLineNumber, originalLineCount + 1), new LineRange(lastModifiedEndLineNumber, modifiedLineCount + 1));
      if (!r.modified.isEmpty) {
        result.push(r);
      }
      return result;
    }
    static clip(mapping, originalRange, modifiedRange) {
      const result = [];
      for (const m of mapping) {
        const original = m.original.intersect(originalRange);
        const modified = m.modified.intersect(modifiedRange);
        if (original && !original.isEmpty && modified && !modified.isEmpty) {
          result.push(new LineRangeMapping(original, modified));
        }
      }
      return result;
    }
    constructor(originalRange, modifiedRange) {
      this.original = originalRange;
      this.modified = modifiedRange;
    }
    toString() {
      return `{${this.original.toString()}->${this.modified.toString()}}`;
    }
    flip() {
      return new LineRangeMapping(this.modified, this.original);
    }
    join(other) {
      return new LineRangeMapping(this.original.join(other.original), this.modified.join(other.modified));
    }
    /**
     * This method assumes that the LineRangeMapping describes a valid diff!
     * I.e. if one range is empty, the other range cannot be the entire document.
     * It avoids various problems when the line range points to non-existing line-numbers.
    */
    toRangeMapping() {
      const origInclusiveRange = this.original.toInclusiveRange();
      const modInclusiveRange = this.modified.toInclusiveRange();
      if (origInclusiveRange && modInclusiveRange) {
        return new RangeMapping(origInclusiveRange, modInclusiveRange);
      } else if (this.original.startLineNumber === 1 || this.modified.startLineNumber === 1) {
        if (!(this.modified.startLineNumber === 1 && this.original.startLineNumber === 1)) {
          throw new BugIndicatingError("not a valid diff");
        }
        return new RangeMapping(new Range$2(this.original.startLineNumber, 1, this.original.endLineNumberExclusive, 1), new Range$2(this.modified.startLineNumber, 1, this.modified.endLineNumberExclusive, 1));
      } else {
        return new RangeMapping(new Range$2(this.original.startLineNumber - 1, Number.MAX_SAFE_INTEGER, this.original.endLineNumberExclusive - 1, Number.MAX_SAFE_INTEGER), new Range$2(this.modified.startLineNumber - 1, Number.MAX_SAFE_INTEGER, this.modified.endLineNumberExclusive - 1, Number.MAX_SAFE_INTEGER));
      }
    }
    /**
     * This method assumes that the LineRangeMapping describes a valid diff!
     * I.e. if one range is empty, the other range cannot be the entire document.
     * It avoids various problems when the line range points to non-existing line-numbers.
    */
    toRangeMapping2(original, modified) {
      if (isValidLineNumber(this.original.endLineNumberExclusive, original) && isValidLineNumber(this.modified.endLineNumberExclusive, modified)) {
        return new RangeMapping(new Range$2(this.original.startLineNumber, 1, this.original.endLineNumberExclusive, 1), new Range$2(this.modified.startLineNumber, 1, this.modified.endLineNumberExclusive, 1));
      }
      if (!this.original.isEmpty && !this.modified.isEmpty) {
        return new RangeMapping(Range$2.fromPositions(new Position$1(this.original.startLineNumber, 1), normalizePosition(new Position$1(this.original.endLineNumberExclusive - 1, Number.MAX_SAFE_INTEGER), original)), Range$2.fromPositions(new Position$1(this.modified.startLineNumber, 1), normalizePosition(new Position$1(this.modified.endLineNumberExclusive - 1, Number.MAX_SAFE_INTEGER), modified)));
      }
      if (this.original.startLineNumber > 1 && this.modified.startLineNumber > 1) {
        return new RangeMapping(Range$2.fromPositions(normalizePosition(new Position$1(this.original.startLineNumber - 1, Number.MAX_SAFE_INTEGER), original), normalizePosition(new Position$1(this.original.endLineNumberExclusive - 1, Number.MAX_SAFE_INTEGER), original)), Range$2.fromPositions(normalizePosition(new Position$1(this.modified.startLineNumber - 1, Number.MAX_SAFE_INTEGER), modified), normalizePosition(new Position$1(this.modified.endLineNumberExclusive - 1, Number.MAX_SAFE_INTEGER), modified)));
      }
      throw new BugIndicatingError();
    }
  }
  function normalizePosition(position, content) {
    if (position.lineNumber < 1) {
      return new Position$1(1, 1);
    }
    if (position.lineNumber > content.length) {
      return new Position$1(content.length, content[content.length - 1].length + 1);
    }
    const line = content[position.lineNumber - 1];
    if (position.column > line.length + 1) {
      return new Position$1(position.lineNumber, line.length + 1);
    }
    return position;
  }
  function isValidLineNumber(lineNumber, lines) {
    return lineNumber >= 1 && lineNumber <= lines.length;
  }
  class DetailedLineRangeMapping extends LineRangeMapping {
    static fromRangeMappings(rangeMappings) {
      const originalRange = LineRange.join(rangeMappings.map((r) => LineRange.fromRangeInclusive(r.originalRange)));
      const modifiedRange = LineRange.join(rangeMappings.map((r) => LineRange.fromRangeInclusive(r.modifiedRange)));
      return new DetailedLineRangeMapping(originalRange, modifiedRange, rangeMappings);
    }
    constructor(originalRange, modifiedRange, innerChanges) {
      super(originalRange, modifiedRange);
      this.innerChanges = innerChanges;
    }
    flip() {
      return new DetailedLineRangeMapping(this.modified, this.original, this.innerChanges?.map((c) => c.flip()));
    }
    withInnerChangesFromLineRanges() {
      return new DetailedLineRangeMapping(this.original, this.modified, [this.toRangeMapping()]);
    }
  }
  class RangeMapping {
    static fromEdit(edit2) {
      const newRanges = edit2.getNewRanges();
      const result = edit2.replacements.map((e, idx) => new RangeMapping(e.range, newRanges[idx]));
      return result;
    }
    static assertSorted(rangeMappings) {
      for (let i2 = 1; i2 < rangeMappings.length; i2++) {
        const previous = rangeMappings[i2 - 1];
        const current = rangeMappings[i2];
        if (!(previous.originalRange.getEndPosition().isBeforeOrEqual(current.originalRange.getStartPosition()) && previous.modifiedRange.getEndPosition().isBeforeOrEqual(current.modifiedRange.getStartPosition()))) {
          throw new BugIndicatingError("Range mappings must be sorted");
        }
      }
    }
    constructor(originalRange, modifiedRange) {
      this.originalRange = originalRange;
      this.modifiedRange = modifiedRange;
    }
    toString() {
      return `{${this.originalRange.toString()}->${this.modifiedRange.toString()}}`;
    }
    flip() {
      return new RangeMapping(this.modifiedRange, this.originalRange);
    }
    /**
     * Creates a single text edit that describes the change from the original to the modified text.
    */
    toTextEdit(modified) {
      const newText = modified.getValueOfRange(this.modifiedRange);
      return new TextReplacement(this.originalRange, newText);
    }
  }
  function lineRangeMappingFromRangeMappings(alignments, originalLines, modifiedLines, dontAssertStartLine = false) {
    const changes = [];
    for (const g of groupAdjacentBy(alignments.map((a) => getLineRangeMapping(a, originalLines, modifiedLines)), (a1, a2) => a1.original.intersectsOrTouches(a2.original) || a1.modified.intersectsOrTouches(a2.modified))) {
      const first2 = g[0];
      const last = g[g.length - 1];
      changes.push(new DetailedLineRangeMapping(first2.original.join(last.original), first2.modified.join(last.modified), g.map((a) => a.innerChanges[0])));
    }
    assertFn(() => {
      if (!dontAssertStartLine && changes.length > 0) {
        if (changes[0].modified.startLineNumber !== changes[0].original.startLineNumber) {
          return false;
        }
        if (modifiedLines.length.lineCount - changes[changes.length - 1].modified.endLineNumberExclusive !== originalLines.length.lineCount - changes[changes.length - 1].original.endLineNumberExclusive) {
          return false;
        }
      }
      return checkAdjacentItems(changes, (m1, m2) => m2.original.startLineNumber - m1.original.endLineNumberExclusive === m2.modified.startLineNumber - m1.modified.endLineNumberExclusive && // There has to be an unchanged line in between (otherwise both diffs should have been joined)
      m1.original.endLineNumberExclusive < m2.original.startLineNumber && m1.modified.endLineNumberExclusive < m2.modified.startLineNumber);
    });
    return changes;
  }
  function getLineRangeMapping(rangeMapping, originalLines, modifiedLines) {
    let lineStartDelta = 0;
    let lineEndDelta = 0;
    if (rangeMapping.modifiedRange.endColumn === 1 && rangeMapping.originalRange.endColumn === 1 && rangeMapping.originalRange.startLineNumber + lineStartDelta <= rangeMapping.originalRange.endLineNumber && rangeMapping.modifiedRange.startLineNumber + lineStartDelta <= rangeMapping.modifiedRange.endLineNumber) {
      lineEndDelta = -1;
    }
    if (rangeMapping.modifiedRange.startColumn - 1 >= modifiedLines.getLineLength(rangeMapping.modifiedRange.startLineNumber) && rangeMapping.originalRange.startColumn - 1 >= originalLines.getLineLength(rangeMapping.originalRange.startLineNumber) && rangeMapping.originalRange.startLineNumber <= rangeMapping.originalRange.endLineNumber + lineEndDelta && rangeMapping.modifiedRange.startLineNumber <= rangeMapping.modifiedRange.endLineNumber + lineEndDelta) {
      lineStartDelta = 1;
    }
    const originalLineRange = new LineRange(rangeMapping.originalRange.startLineNumber + lineStartDelta, rangeMapping.originalRange.endLineNumber + 1 + lineEndDelta);
    const modifiedLineRange = new LineRange(rangeMapping.modifiedRange.startLineNumber + lineStartDelta, rangeMapping.modifiedRange.endLineNumber + 1 + lineEndDelta);
    return new DetailedLineRangeMapping(originalLineRange, modifiedLineRange, [rangeMapping]);
  }
  const Extensions$2 = {
    IconContribution: "base.contributions.icons"
  };
  var IconContribution;
  (function(IconContribution2) {
    function getDefinition(contribution, registry) {
      let definition = contribution.defaults;
      while (ThemeIcon.isThemeIcon(definition)) {
        const c = iconRegistry.getIcon(definition.id);
        if (!c) {
          return void 0;
        }
        definition = c.defaults;
      }
      return definition;
    }
    IconContribution2.getDefinition = getDefinition;
  })(IconContribution || (IconContribution = {}));
  var IconFontDefinition;
  (function(IconFontDefinition2) {
    function toJSONObject(iconFont) {
      return {
        weight: iconFont.weight,
        style: iconFont.style,
        src: iconFont.src.map((s) => ({ format: s.format, location: s.location.toString() }))
      };
    }
    IconFontDefinition2.toJSONObject = toJSONObject;
    function fromJSONObject(json) {
      const stringOrUndef = (s) => isString$1(s) ? s : void 0;
      if (json && Array.isArray(json.src) && json.src.every((s) => isString$1(s.format) && isString$1(s.location))) {
        return {
          weight: stringOrUndef(json.weight),
          style: stringOrUndef(json.style),
          src: json.src.map((s) => ({ format: s.format, location: URI.parse(s.location) }))
        };
      }
      return void 0;
    }
    IconFontDefinition2.fromJSONObject = fromJSONObject;
  })(IconFontDefinition || (IconFontDefinition = {}));
  const fontIdRegex = /^([\w_-]+)$/;
  const fontIdErrorMessage = localize(2024, "The font ID must only contain letters, numbers, underscores and dashes.");
  class IconRegistry extends Disposable {
    constructor() {
      super();
      this._onDidChange = this._register(new Emitter$1());
      this.onDidChange = this._onDidChange.event;
      this.iconSchema = {
        definitions: {
          icons: {
            type: "object",
            properties: {
              fontId: { type: "string", description: localize(2025, "The id of the font to use. If not set, the font that is defined first is used."), pattern: fontIdRegex.source, patternErrorMessage: fontIdErrorMessage },
              fontCharacter: { type: "string", description: localize(2026, "The font character associated with the icon definition.") }
            },
            additionalProperties: false,
            defaultSnippets: [{ body: { fontCharacter: "\\\\e030" } }]
          }
        },
        type: "object",
        properties: {}
      };
      this.iconReferenceSchema = { type: "string", pattern: `^${ThemeIcon.iconNameExpression}$`, enum: [], enumDescriptions: [] };
      this.iconsById = {};
      this.iconFontsById = {};
    }
    registerIcon(id, defaults, description, deprecationMessage) {
      const existing = this.iconsById[id];
      if (existing) {
        if (description && !existing.description) {
          existing.description = description;
          this.iconSchema.properties[id].markdownDescription = `${description} $(${id})`;
          const enumIndex = this.iconReferenceSchema.enum.indexOf(id);
          if (enumIndex !== -1) {
            this.iconReferenceSchema.enumDescriptions[enumIndex] = description;
          }
          this._onDidChange.fire();
        }
        return existing;
      }
      const iconContribution = { id, description, defaults, deprecationMessage };
      this.iconsById[id] = iconContribution;
      const propertySchema = { $ref: "#/definitions/icons" };
      if (deprecationMessage) {
        propertySchema.deprecationMessage = deprecationMessage;
      }
      if (description) {
        propertySchema.markdownDescription = `${description}: $(${id})`;
      }
      this.iconSchema.properties[id] = propertySchema;
      this.iconReferenceSchema.enum.push(id);
      this.iconReferenceSchema.enumDescriptions.push(description || "");
      this._onDidChange.fire();
      return { id };
    }
    getIcons() {
      return Object.keys(this.iconsById).map((id) => this.iconsById[id]);
    }
    getIcon(id) {
      return this.iconsById[id];
    }
    getIconSchema() {
      return this.iconSchema;
    }
    toString() {
      const sorter2 = (i1, i2) => {
        return i1.id.localeCompare(i2.id);
      };
      const classNames2 = (i2) => {
        while (ThemeIcon.isThemeIcon(i2.defaults)) {
          i2 = this.iconsById[i2.defaults.id];
        }
        return `codicon codicon-${i2 ? i2.id : ""}`;
      };
      const reference = [];
      reference.push(`| preview     | identifier                        | default codicon ID                | description`);
      reference.push(`| ----------- | --------------------------------- | --------------------------------- | --------------------------------- |`);
      const contributions = Object.keys(this.iconsById).map((key) => this.iconsById[key]);
      for (const i2 of contributions.filter((i3) => !!i3.description).sort(sorter2)) {
        reference.push(`|<i class="${classNames2(i2)}"></i>|${i2.id}|${ThemeIcon.isThemeIcon(i2.defaults) ? i2.defaults.id : i2.id}|${i2.description || ""}|`);
      }
      reference.push(`| preview     | identifier                        `);
      reference.push(`| ----------- | --------------------------------- |`);
      for (const i2 of contributions.filter((i3) => !ThemeIcon.isThemeIcon(i3.defaults)).sort(sorter2)) {
        reference.push(`|<i class="${classNames2(i2)}"></i>|${i2.id}|`);
      }
      return reference.join("\n");
    }
  }
  const iconRegistry = new IconRegistry();
  Registry.add(Extensions$2.IconContribution, iconRegistry);
  function registerIcon(id, defaults, description, deprecationMessage) {
    return iconRegistry.registerIcon(id, defaults, description, deprecationMessage);
  }
  function getIconRegistry() {
    return iconRegistry;
  }
  function initialize() {
    const codiconFontCharacters = getCodiconFontCharacters();
    for (const icon in codiconFontCharacters) {
      const fontCharacter = "\\" + codiconFontCharacters[icon].toString(16);
      iconRegistry.registerIcon(icon, { fontCharacter });
    }
  }
  initialize();
  const iconsSchemaId = "vscode://schemas/icons";
  const schemaRegistry = Registry.as(Extensions$7.JSONContribution);
  schemaRegistry.registerSchema(iconsSchemaId, iconRegistry.getIconSchema());
  const delayer = new RunOnceScheduler(() => schemaRegistry.notifySchemaChanged(iconsSchemaId), 200);
  iconRegistry.onDidChange(() => {
    if (!delayer.isScheduled()) {
      delayer.schedule();
    }
  });
  const widgetClose = registerIcon("widget-close", Codicon.close, localize(2027, "Icon for the close action in widgets."));
  registerIcon("goto-previous-location", Codicon.arrowUp, localize(2028, "Icon for goto previous editor location."));
  registerIcon("goto-next-location", Codicon.arrowDown, localize(2029, "Icon for goto next editor location."));
  ThemeIcon.modify(Codicon.sync, "spin");
  ThemeIcon.modify(Codicon.loading, "spin");
  var __decorate$2H = 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$2E = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  const accessibleDiffViewerInsertIcon = registerIcon("diff-review-insert", Codicon.add, localize(97, "Icon for 'Insert' in accessible diff viewer."));
  const accessibleDiffViewerRemoveIcon = registerIcon("diff-review-remove", Codicon.remove, localize(98, "Icon for 'Remove' in accessible diff viewer."));
  const accessibleDiffViewerCloseIcon = registerIcon("diff-review-close", Codicon.close, localize(99, "Icon for 'Close' in accessible diff viewer."));
  let AccessibleDiffViewer = (_k = class extends Disposable {
    constructor(_parentNode, _visible, _setVisible, _canClose, _width, _height, _diffs, _models, _instantiationService) {
      super();
      this._parentNode = _parentNode;
      this._visible = _visible;
      this._setVisible = _setVisible;
      this._canClose = _canClose;
      this._width = _width;
      this._height = _height;
      this._diffs = _diffs;
      this._models = _models;
      this._instantiationService = _instantiationService;
      this._state = derived(this, (reader) => {
        const visible = this._visible.read(reader);
        this._parentNode.style.visibility = visible ? "visible" : "hidden";
        if (!visible) {
          return null;
        }
        const model = reader.store.add(this._instantiationService.createInstance(ViewModel, this._diffs, this._models, this._setVisible, this._canClose));
        const view = reader.store.add(this._instantiationService.createInstance(View, this._parentNode, model, this._width, this._height, this._models));
        return { model, view };
      }).recomputeInitiallyAndOnChange(this._store);
    }
    next() {
      transaction((tx) => {
        const isVisible = this._visible.get();
        this._setVisible(true, tx);
        if (isVisible) {
          this._state.get().model.nextGroup(tx);
        }
      });
    }
    prev() {
      transaction((tx) => {
        this._setVisible(true, tx);
        this._state.get().model.previousGroup(tx);
      });
    }
    close() {
      transaction((tx) => {
        this._setVisible(false, tx);
      });
    }
  }, _k._ttPolicy = createTrustedTypesPolicy("diffReview", { createHTML: (value) => value }), _k);
  AccessibleDiffViewer = __decorate$2H([
    __param$2E(8, IInstantiationService)
  ], AccessibleDiffViewer);
  let ViewModel = class ViewModel extends Disposable {
    constructor(_diffs, _models, _setVisible, canClose, _accessibilitySignalService) {
      super();
      this._diffs = _diffs;
      this._models = _models;
      this._setVisible = _setVisible;
      this.canClose = canClose;
      this._accessibilitySignalService = _accessibilitySignalService;
      this._groups = observableValue(this, []);
      this._currentGroupIdx = observableValue(this, 0);
      this._currentElementIdx = observableValue(this, 0);
      this.groups = this._groups;
      this.currentGroup = this._currentGroupIdx.map((idx, r) => this._groups.read(r)[idx]);
      this.currentGroupIndex = this._currentGroupIdx;
      this.currentElement = this._currentElementIdx.map((idx, r) => this.currentGroup.read(r)?.lines[idx]);
      this._register(autorun((reader) => {
        const diffs = this._diffs.read(reader);
        if (!diffs) {
          this._groups.set([], void 0);
          return;
        }
        const groups = computeViewElementGroups(diffs, this._models.getOriginalModel().getLineCount(), this._models.getModifiedModel().getLineCount());
        transaction((tx) => {
          const p = this._models.getModifiedPosition();
          if (p) {
            const nextGroup = groups.findIndex((g) => p?.lineNumber < g.range.modified.endLineNumberExclusive);
            if (nextGroup !== -1) {
              this._currentGroupIdx.set(nextGroup, tx);
            }
          }
          this._groups.set(groups, tx);
        });
      }));
      this._register(autorun((reader) => {
        const currentViewItem = this.currentElement.read(reader);
        if (currentViewItem?.type === LineType.Deleted) {
          this._accessibilitySignalService.playSignal(AccessibilitySignal.diffLineDeleted, { source: "accessibleDiffViewer.currentElementChanged" });
        } else if (currentViewItem?.type === LineType.Added) {
          this._accessibilitySignalService.playSignal(AccessibilitySignal.diffLineInserted, { source: "accessibleDiffViewer.currentElementChanged" });
        }
      }));
      this._register(autorun((reader) => {
        const currentViewItem = this.currentElement.read(reader);
        if (currentViewItem && currentViewItem.type !== LineType.Header) {
          const lineNumber = currentViewItem.modifiedLineNumber ?? currentViewItem.diff.modified.startLineNumber;
          this._models.modifiedSetSelection(Range$2.fromPositions(new Position$1(lineNumber, 1)));
        }
      }));
    }
    _goToGroupDelta(delta, tx) {
      const groups = this.groups.get();
      if (!groups || groups.length <= 1) {
        return;
      }
      subtransaction(tx, (tx2) => {
        this._currentGroupIdx.set(OffsetRange.ofLength(groups.length).clipCyclic(this._currentGroupIdx.get() + delta), tx2);
        this._currentElementIdx.set(0, tx2);
      });
    }
    nextGroup(tx) {
      this._goToGroupDelta(1, tx);
    }
    previousGroup(tx) {
      this._goToGroupDelta(-1, tx);
    }
    _goToLineDelta(delta) {
      const group = this.currentGroup.get();
      if (!group || group.lines.length <= 1) {
        return;
      }
      transaction((tx) => {
        this._currentElementIdx.set(OffsetRange.ofLength(group.lines.length).clip(this._currentElementIdx.get() + delta), tx);
      });
    }
    goToNextLine() {
      this._goToLineDelta(1);
    }
    goToPreviousLine() {
      this._goToLineDelta(-1);
    }
    goToLine(line) {
      const group = this.currentGroup.get();
      if (!group) {
        return;
      }
      const idx = group.lines.indexOf(line);
      if (idx === -1) {
        return;
      }
      transaction((tx) => {
        this._currentElementIdx.set(idx, tx);
      });
    }
    revealCurrentElementInEditor() {
      if (!this.canClose.get()) {
        return;
      }
      this._setVisible(false, void 0);
      const curElem = this.currentElement.get();
      if (curElem) {
        if (curElem.type === LineType.Deleted) {
          this._models.originalReveal(Range$2.fromPositions(new Position$1(curElem.originalLineNumber, 1)));
        } else {
          this._models.modifiedReveal(curElem.type !== LineType.Header ? Range$2.fromPositions(new Position$1(curElem.modifiedLineNumber, 1)) : void 0);
        }
      }
    }
    close() {
      if (!this.canClose.get()) {
        return;
      }
      this._setVisible(false, void 0);
      this._models.modifiedFocus();
    }
  };
  ViewModel = __decorate$2H([
    __param$2E(4, IAccessibilitySignalService)
  ], ViewModel);
  const viewElementGroupLineMargin = 3;
  function computeViewElementGroups(diffs, originalLineCount, modifiedLineCount) {
    const result = [];
    for (const g of groupAdjacentBy(diffs, (a, b) => b.modified.startLineNumber - a.modified.endLineNumberExclusive < 2 * viewElementGroupLineMargin)) {
      const viewElements = [];
      viewElements.push(new HeaderViewElement());
      const origFullRange = new LineRange(Math.max(1, g[0].original.startLineNumber - viewElementGroupLineMargin), Math.min(g[g.length - 1].original.endLineNumberExclusive + viewElementGroupLineMargin, originalLineCount + 1));
      const modifiedFullRange = new LineRange(Math.max(1, g[0].modified.startLineNumber - viewElementGroupLineMargin), Math.min(g[g.length - 1].modified.endLineNumberExclusive + viewElementGroupLineMargin, modifiedLineCount + 1));
      forEachAdjacent(g, (a, b) => {
        const origRange = new LineRange(a ? a.original.endLineNumberExclusive : origFullRange.startLineNumber, b ? b.original.startLineNumber : origFullRange.endLineNumberExclusive);
        const modifiedRange2 = new LineRange(a ? a.modified.endLineNumberExclusive : modifiedFullRange.startLineNumber, b ? b.modified.startLineNumber : modifiedFullRange.endLineNumberExclusive);
        origRange.forEach((origLineNumber) => {
          viewElements.push(new UnchangedLineViewElement(origLineNumber, modifiedRange2.startLineNumber + (origLineNumber - origRange.startLineNumber)));
        });
        if (b) {
          b.original.forEach((origLineNumber) => {
            viewElements.push(new DeletedLineViewElement(b, origLineNumber));
          });
          b.modified.forEach((modifiedLineNumber) => {
            viewElements.push(new AddedLineViewElement(b, modifiedLineNumber));
          });
        }
      });
      const modifiedRange = g[0].modified.join(g[g.length - 1].modified);
      const originalRange = g[0].original.join(g[g.length - 1].original);
      result.push(new ViewElementGroup(new LineRangeMapping(modifiedRange, originalRange), viewElements));
    }
    return result;
  }
  var LineType;
  (function(LineType2) {
    LineType2[LineType2["Header"] = 0] = "Header";
    LineType2[LineType2["Unchanged"] = 1] = "Unchanged";
    LineType2[LineType2["Deleted"] = 2] = "Deleted";
    LineType2[LineType2["Added"] = 3] = "Added";
  })(LineType || (LineType = {}));
  class ViewElementGroup {
    constructor(range2, lines) {
      this.range = range2;
      this.lines = lines;
    }
  }
  class HeaderViewElement {
    constructor() {
      this.type = LineType.Header;
    }
  }
  class DeletedLineViewElement {
    constructor(diff, originalLineNumber) {
      this.diff = diff;
      this.originalLineNumber = originalLineNumber;
      this.type = LineType.Deleted;
      this.modifiedLineNumber = void 0;
    }
  }
  class AddedLineViewElement {
    constructor(diff, modifiedLineNumber) {
      this.diff = diff;
      this.modifiedLineNumber = modifiedLineNumber;
      this.type = LineType.Added;
      this.originalLineNumber = void 0;
    }
  }
  class UnchangedLineViewElement {
    constructor(originalLineNumber, modifiedLineNumber) {
      this.originalLineNumber = originalLineNumber;
      this.modifiedLineNumber = modifiedLineNumber;
      this.type = LineType.Unchanged;
    }
  }
  let View = class View extends Disposable {
    constructor(_element, _model, _width, _height, _models, _languageService) {
      super();
      this._element = _element;
      this._model = _model;
      this._width = _width;
      this._height = _height;
      this._models = _models;
      this._languageService = _languageService;
      this.domNode = this._element;
      this.domNode.className = "monaco-component diff-review monaco-editor-background";
      const actionBarContainer = document.createElement("div");
      actionBarContainer.className = "diff-review-actions";
      this._actionBar = this._register(new ActionBar(actionBarContainer));
      this._register(autorun((reader) => {
        this._actionBar.clear();
        if (this._model.canClose.read(reader)) {
          this._actionBar.push(toAction({
            id: "diffreview.close",
            label: localize(100, "Close"),
            class: "close-diff-review " + ThemeIcon.asClassName(accessibleDiffViewerCloseIcon),
            enabled: true,
            run: async () => _model.close()
          }), { label: false, icon: true });
        }
      }));
      this._content = document.createElement("div");
      this._content.className = "diff-review-content";
      this._content.setAttribute("role", "code");
      this._scrollbar = this._register(new DomScrollableElement(this._content, {}));
      reset(this.domNode, this._scrollbar.getDomNode(), actionBarContainer);
      this._register(autorun((r) => {
        this._height.read(r);
        this._width.read(r);
        this._scrollbar.scanDomNode();
      }));
      this._register(toDisposable(() => {
        reset(this.domNode);
      }));
      this._register(applyStyle(this.domNode, { width: this._width, height: this._height }));
      this._register(applyStyle(this._content, { width: this._width, height: this._height }));
      this._register(autorunWithStore((reader, store) => {
        this._model.currentGroup.read(reader);
        this._render(store);
      }));
      this._register(addStandardDisposableListener(this.domNode, "keydown", (e) => {
        if (e.equals(
          18
          /* KeyCode.DownArrow */
        ) || e.equals(
          2048 | 18
          /* KeyCode.DownArrow */
        ) || e.equals(
          512 | 18
          /* KeyCode.DownArrow */
        )) {
          e.preventDefault();
          this._model.goToNextLine();
        }
        if (e.equals(
          16
          /* KeyCode.UpArrow */
        ) || e.equals(
          2048 | 16
          /* KeyCode.UpArrow */
        ) || e.equals(
          512 | 16
          /* KeyCode.UpArrow */
        )) {
          e.preventDefault();
          this._model.goToPreviousLine();
        }
        if (e.equals(
          9
          /* KeyCode.Escape */
        ) || e.equals(
          2048 | 9
          /* KeyCode.Escape */
        ) || e.equals(
          512 | 9
          /* KeyCode.Escape */
        ) || e.equals(
          1024 | 9
          /* KeyCode.Escape */
        )) {
          e.preventDefault();
          this._model.close();
        }
        if (e.equals(
          10
          /* KeyCode.Space */
        ) || e.equals(
          3
          /* KeyCode.Enter */
        )) {
          e.preventDefault();
          this._model.revealCurrentElementInEditor();
        }
      }));
    }
    _render(store) {
      const originalOptions = this._models.getOriginalOptions();
      const modifiedOptions = this._models.getModifiedOptions();
      const container = document.createElement("div");
      container.className = "diff-review-table";
      container.setAttribute("role", "list");
      container.setAttribute("aria-label", localize(101, "Accessible Diff Viewer. Use arrow up and down to navigate."));
      applyFontInfo(container, modifiedOptions.get(
        59
        /* EditorOption.fontInfo */
      ));
      reset(this._content, container);
      const originalModel = this._models.getOriginalModel();
      const modifiedModel = this._models.getModifiedModel();
      if (!originalModel || !modifiedModel) {
        return;
      }
      const originalModelOpts = originalModel.getOptions();
      const modifiedModelOpts = modifiedModel.getOptions();
      const lineHeight = modifiedOptions.get(
        75
        /* EditorOption.lineHeight */
      );
      const group = this._model.currentGroup.get();
      for (const viewItem of group?.lines || []) {
        if (!group) {
          break;
        }
        let row;
        if (viewItem.type === LineType.Header) {
          const header2 = document.createElement("div");
          header2.className = "diff-review-row";
          header2.setAttribute("role", "listitem");
          const r = group.range;
          const diffIndex = this._model.currentGroupIndex.get();
          const diffsLength = this._model.groups.get().length;
          const getAriaLines = (lines) => lines === 0 ? localize(102, "no lines changed") : lines === 1 ? localize(103, "1 line changed") : localize(104, "{0} lines changed", lines);
          const originalChangedLinesCntAria = getAriaLines(r.original.length);
          const modifiedChangedLinesCntAria = getAriaLines(r.modified.length);
          header2.setAttribute("aria-label", localize(105, "Difference {0} of {1}: original line {2}, {3}, modified line {4}, {5}", diffIndex + 1, diffsLength, r.original.startLineNumber, originalChangedLinesCntAria, r.modified.startLineNumber, modifiedChangedLinesCntAria));
          const cell = document.createElement("div");
          cell.className = "diff-review-cell diff-review-summary";
          cell.appendChild(document.createTextNode(`${diffIndex + 1}/${diffsLength}: @@ -${r.original.startLineNumber},${r.original.length} +${r.modified.startLineNumber},${r.modified.length} @@`));
          header2.appendChild(cell);
          row = header2;
        } else {
          row = this._createRow(viewItem, lineHeight, this._width.get(), originalOptions, originalModel, originalModelOpts, modifiedOptions, modifiedModel, modifiedModelOpts);
        }
        container.appendChild(row);
        const isSelectedObs = derived((reader) => (
          /** @description isSelected */
          this._model.currentElement.read(reader) === viewItem
        ));
        store.add(autorun((reader) => {
          const isSelected = isSelectedObs.read(reader);
          row.tabIndex = isSelected ? 0 : -1;
          if (isSelected) {
            row.focus();
          }
        }));
        store.add(addDisposableListener(row, "focus", () => {
          this._model.goToLine(viewItem);
        }));
      }
      this._scrollbar.scanDomNode();
    }
    _createRow(item, lineHeight, width2, originalOptions, originalModel, originalModelOpts, modifiedOptions, modifiedModel, modifiedModelOpts) {
      const originalLayoutInfo = originalOptions.get(
        165
        /* EditorOption.layoutInfo */
      );
      const originalLineNumbersWidth = originalLayoutInfo.glyphMarginWidth + originalLayoutInfo.lineNumbersWidth;
      const modifiedLayoutInfo = modifiedOptions.get(
        165
        /* EditorOption.layoutInfo */
      );
      const modifiedLineNumbersWidth = 10 + modifiedLayoutInfo.glyphMarginWidth + modifiedLayoutInfo.lineNumbersWidth;
      let rowClassName = "diff-review-row";
      let lineNumbersExtraClassName = "";
      const spacerClassName = "diff-review-spacer";
      let spacerIcon = null;
      switch (item.type) {
        case LineType.Added:
          rowClassName = "diff-review-row line-insert";
          lineNumbersExtraClassName = " char-insert";
          spacerIcon = accessibleDiffViewerInsertIcon;
          break;
        case LineType.Deleted:
          rowClassName = "diff-review-row line-delete";
          lineNumbersExtraClassName = " char-delete";
          spacerIcon = accessibleDiffViewerRemoveIcon;
          break;
      }
      const row = document.createElement("div");
      row.style.minWidth = width2 + "px";
      row.className = rowClassName;
      row.setAttribute("role", "listitem");
      row.ariaLevel = "";
      const cell = document.createElement("div");
      cell.className = "diff-review-cell";
      cell.style.height = `${lineHeight}px`;
      row.appendChild(cell);
      const originalLineNumber = document.createElement("span");
      originalLineNumber.style.width = originalLineNumbersWidth + "px";
      originalLineNumber.style.minWidth = originalLineNumbersWidth + "px";
      originalLineNumber.className = "diff-review-line-number" + lineNumbersExtraClassName;
      if (item.originalLineNumber !== void 0) {
        originalLineNumber.appendChild(document.createTextNode(String(item.originalLineNumber)));
      } else {
        originalLineNumber.innerText = " ";
      }
      cell.appendChild(originalLineNumber);
      const modifiedLineNumber = document.createElement("span");
      modifiedLineNumber.style.width = modifiedLineNumbersWidth + "px";
      modifiedLineNumber.style.minWidth = modifiedLineNumbersWidth + "px";
      modifiedLineNumber.style.paddingRight = "10px";
      modifiedLineNumber.className = "diff-review-line-number" + lineNumbersExtraClassName;
      if (item.modifiedLineNumber !== void 0) {
        modifiedLineNumber.appendChild(document.createTextNode(String(item.modifiedLineNumber)));
      } else {
        modifiedLineNumber.innerText = " ";
      }
      cell.appendChild(modifiedLineNumber);
      const spacer = document.createElement("span");
      spacer.className = spacerClassName;
      if (spacerIcon) {
        const spacerCodicon = document.createElement("span");
        spacerCodicon.className = ThemeIcon.asClassName(spacerIcon);
        spacerCodicon.innerText = "  ";
        spacer.appendChild(spacerCodicon);
      } else {
        spacer.innerText = "  ";
      }
      cell.appendChild(spacer);
      let lineContent;
      if (item.modifiedLineNumber !== void 0) {
        let html2 = this._getLineHtml(modifiedModel, modifiedOptions, modifiedModelOpts.tabSize, item.modifiedLineNumber, this._languageService.languageIdCodec);
        if (AccessibleDiffViewer._ttPolicy) {
          html2 = AccessibleDiffViewer._ttPolicy.createHTML(html2);
        }
        cell.insertAdjacentHTML("beforeend", html2);
        lineContent = modifiedModel.getLineContent(item.modifiedLineNumber);
      } else {
        let html2 = this._getLineHtml(originalModel, originalOptions, originalModelOpts.tabSize, item.originalLineNumber, this._languageService.languageIdCodec);
        if (AccessibleDiffViewer._ttPolicy) {
          html2 = AccessibleDiffViewer._ttPolicy.createHTML(html2);
        }
        cell.insertAdjacentHTML("beforeend", html2);
        lineContent = originalModel.getLineContent(item.originalLineNumber);
      }
      if (lineContent.length === 0) {
        lineContent = localize(106, "blank");
      }
      let ariaLabel = "";
      switch (item.type) {
        case LineType.Unchanged:
          if (item.originalLineNumber === item.modifiedLineNumber) {
            ariaLabel = localize(107, "{0} unchanged line {1}", lineContent, item.originalLineNumber);
          } else {
            ariaLabel = localize(108, "{0} original line {1} modified line {2}", lineContent, item.originalLineNumber, item.modifiedLineNumber);
          }
          break;
        case LineType.Added:
          ariaLabel = localize(109, "+ {0} modified line {1}", lineContent, item.modifiedLineNumber);
          break;
        case LineType.Deleted:
          ariaLabel = localize(110, "- {0} original line {1}", lineContent, item.originalLineNumber);
          break;
      }
      row.setAttribute("aria-label", ariaLabel);
      return row;
    }
    _getLineHtml(model, options, tabSize, lineNumber, languageIdCodec) {
      const lineContent = model.getLineContent(lineNumber);
      const fontInfo = options.get(
        59
        /* EditorOption.fontInfo */
      );
      const verticalScrollbarSize = options.get(
        117
        /* EditorOption.scrollbar */
      ).verticalScrollbarSize;
      const lineTokens = LineTokens.createEmpty(lineContent, languageIdCodec);
      const isBasicASCII2 = ViewLineRenderingData.isBasicASCII(lineContent, model.mightContainNonBasicASCII());
      const containsRTL2 = ViewLineRenderingData.containsRTL(lineContent, isBasicASCII2, model.mightContainRTL());
      const r = renderViewLine2(new RenderLineInput(fontInfo.isMonospace && !options.get(
        40
        /* EditorOption.disableMonospaceOptimizations */
      ), fontInfo.canUseHalfwidthRightwardsArrow, lineContent, false, isBasicASCII2, containsRTL2, 0, lineTokens, [], tabSize, 0, fontInfo.spaceWidth, fontInfo.middotWidth, fontInfo.wsmiddotWidth, options.get(
        133
        /* EditorOption.stopRenderingLineAfter */
      ), options.get(
        113
        /* EditorOption.renderWhitespace */
      ), options.get(
        108
        /* EditorOption.renderControlCharacters */
      ), options.get(
        60
        /* EditorOption.fontLigatures */
      ) !== EditorFontLigatures.OFF, null, null, verticalScrollbarSize));
      return r.html;
    }
  };
  View = __decorate$2H([
    __param$2E(5, ILanguageService)
  ], View);
  class AccessibleDiffViewerModelFromEditors {
    constructor(editors) {
      this.editors = editors;
    }
    getOriginalModel() {
      return this.editors.original.getModel();
    }
    getOriginalOptions() {
      return this.editors.original.getOptions();
    }
    originalReveal(range2) {
      this.editors.original.revealRange(range2);
      this.editors.original.setSelection(range2);
      this.editors.original.focus();
    }
    getModifiedModel() {
      return this.editors.modified.getModel();
    }
    getModifiedOptions() {
      return this.editors.modified.getOptions();
    }
    modifiedReveal(range2) {
      if (range2) {
        this.editors.modified.revealRange(range2);
        this.editors.modified.setSelection(range2);
      }
      this.editors.modified.focus();
    }
    modifiedSetSelection(range2) {
      this.editors.modified.setSelection(range2);
    }
    modifiedFocus() {
      this.editors.modified.focus();
    }
    getModifiedPosition() {
      return this.editors.modified.getPosition() ?? void 0;
    }
  }
  registerColor("diffEditor.move.border", "#8b8b8b9c", localize(137, "The border color for text that got moved in the diff editor."));
  registerColor("diffEditor.moveActive.border", "#FFA500", localize(138, "The active border color for text that got moved in the diff editor."));
  registerColor("diffEditor.unchangedRegionShadow", { dark: "#000000", light: "#737373BF", hcDark: "#000000", hcLight: "#737373BF" }, localize(139, "The color of the shadow around unchanged region widgets."));
  const diffInsertIcon = registerIcon("diff-insert", Codicon.add, localize(140, "Line decoration for inserts in the diff editor."));
  const diffRemoveIcon = registerIcon("diff-remove", Codicon.remove, localize(141, "Line decoration for removals in the diff editor."));
  const diffLineAddDecorationBackgroundWithIndicator = ModelDecorationOptions.register({
    className: "line-insert",
    description: "line-insert",
    isWholeLine: true,
    linesDecorationsClassName: "insert-sign " + ThemeIcon.asClassName(diffInsertIcon),
    marginClassName: "gutter-insert"
  });
  const diffLineDeleteDecorationBackgroundWithIndicator = ModelDecorationOptions.register({
    className: "line-delete",
    description: "line-delete",
    isWholeLine: true,
    linesDecorationsClassName: "delete-sign " + ThemeIcon.asClassName(diffRemoveIcon),
    marginClassName: "gutter-delete"
  });
  const diffLineAddDecorationBackground = ModelDecorationOptions.register({
    className: "line-insert",
    description: "line-insert",
    isWholeLine: true,
    marginClassName: "gutter-insert"
  });
  const diffLineDeleteDecorationBackground = ModelDecorationOptions.register({
    className: "line-delete",
    description: "line-delete",
    isWholeLine: true,
    marginClassName: "gutter-delete"
  });
  const diffAddDecoration = ModelDecorationOptions.register({
    className: "char-insert",
    description: "char-insert",
    shouldFillLineOnLineBreak: true
  });
  const diffWholeLineAddDecoration = ModelDecorationOptions.register({
    className: "char-insert",
    description: "char-insert",
    isWholeLine: true
  });
  const diffAddDecorationEmpty = ModelDecorationOptions.register({
    className: "char-insert diff-range-empty",
    description: "char-insert diff-range-empty"
  });
  const diffDeleteDecoration = ModelDecorationOptions.register({
    className: "char-delete",
    description: "char-delete",
    shouldFillLineOnLineBreak: true
  });
  const diffWholeLineDeleteDecoration = ModelDecorationOptions.register({
    className: "char-delete",
    description: "char-delete",
    isWholeLine: true
  });
  const diffDeleteDecorationEmpty = ModelDecorationOptions.register({
    className: "char-delete diff-range-empty",
    description: "char-delete diff-range-empty"
  });
  const IEditorWorkerService = createDecorator("editorWorkerService");
  var __decorate$2G = 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$2D = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  var WorkerBasedDocumentDiffProvider_1;
  const IDiffProviderFactoryService = createDecorator("diffProviderFactoryService");
  let WorkerBasedDiffProviderFactoryService = class WorkerBasedDiffProviderFactoryService {
    constructor(instantiationService) {
      this.instantiationService = instantiationService;
    }
    createDiffProvider(options) {
      return this.instantiationService.createInstance(WorkerBasedDocumentDiffProvider, options);
    }
  };
  WorkerBasedDiffProviderFactoryService = __decorate$2G([
    __param$2D(0, IInstantiationService)
  ], WorkerBasedDiffProviderFactoryService);
  registerSingleton(
    IDiffProviderFactoryService,
    WorkerBasedDiffProviderFactoryService,
    1
    /* InstantiationType.Delayed */
  );
  let WorkerBasedDocumentDiffProvider = (_l = class {
    constructor(options, editorWorkerService, telemetryService) {
      this.editorWorkerService = editorWorkerService;
      this.telemetryService = telemetryService;
      this.onDidChangeEventEmitter = new Emitter$1();
      this.onDidChange = this.onDidChangeEventEmitter.event;
      this.diffAlgorithm = "advanced";
      this.diffAlgorithmOnDidChangeSubscription = void 0;
      this.setOptions(options);
    }
    dispose() {
      this.diffAlgorithmOnDidChangeSubscription?.dispose();
    }
    async computeDiff(original, modified, options, cancellationToken) {
      if (typeof this.diffAlgorithm !== "string") {
        return this.diffAlgorithm.computeDiff(original, modified, options, cancellationToken);
      }
      if (original.isDisposed() || modified.isDisposed()) {
        return {
          changes: [],
          identical: true,
          quitEarly: false,
          moves: []
        };
      }
      if (original.getLineCount() === 1 && original.getLineMaxColumn(1) === 1) {
        if (modified.getLineCount() === 1 && modified.getLineMaxColumn(1) === 1) {
          return {
            changes: [],
            identical: true,
            quitEarly: false,
            moves: []
          };
        }
        return {
          changes: [
            new DetailedLineRangeMapping(new LineRange(1, 2), new LineRange(1, modified.getLineCount() + 1), [
              new RangeMapping(original.getFullModelRange(), modified.getFullModelRange())
            ])
          ],
          identical: false,
          quitEarly: false,
          moves: []
        };
      }
      const uriKey = JSON.stringify([original.uri.toString(), modified.uri.toString()]);
      const context = JSON.stringify([original.id, modified.id, original.getAlternativeVersionId(), modified.getAlternativeVersionId(), JSON.stringify(options)]);
      const c = WorkerBasedDocumentDiffProvider_1.diffCache.get(uriKey);
      if (c && c.context === context) {
        return c.result;
      }
      const sw = StopWatch.create();
      const result = await this.editorWorkerService.computeDiff(original.uri, modified.uri, options, this.diffAlgorithm);
      const timeMs = sw.elapsed();
      this.telemetryService.publicLog2("diffEditor.computeDiff", {
        timeMs,
        timedOut: result?.quitEarly ?? true,
        detectedMoves: options.computeMoves ? result?.moves.length ?? 0 : -1
      });
      if (cancellationToken.isCancellationRequested) {
        return {
          changes: [],
          identical: false,
          quitEarly: true,
          moves: []
        };
      }
      if (!result) {
        throw new Error("no diff result available");
      }
      if (WorkerBasedDocumentDiffProvider_1.diffCache.size > 10) {
        WorkerBasedDocumentDiffProvider_1.diffCache.delete(WorkerBasedDocumentDiffProvider_1.diffCache.keys().next().value);
      }
      WorkerBasedDocumentDiffProvider_1.diffCache.set(uriKey, { result, context });
      return result;
    }
    setOptions(newOptions) {
      let didChange = false;
      if (newOptions.diffAlgorithm) {
        if (this.diffAlgorithm !== newOptions.diffAlgorithm) {
          this.diffAlgorithmOnDidChangeSubscription?.dispose();
          this.diffAlgorithmOnDidChangeSubscription = void 0;
          this.diffAlgorithm = newOptions.diffAlgorithm;
          if (typeof newOptions.diffAlgorithm !== "string") {
            this.diffAlgorithmOnDidChangeSubscription = newOptions.diffAlgorithm.onDidChange(() => this.onDidChangeEventEmitter.fire());
          }
          didChange = true;
        }
      }
      if (didChange) {
        this.onDidChangeEventEmitter.fire();
      }
    }
  }, WorkerBasedDocumentDiffProvider_1 = _l, _l.diffCache = /* @__PURE__ */ new Map(), _l);
  WorkerBasedDocumentDiffProvider = WorkerBasedDocumentDiffProvider_1 = __decorate$2G([
    __param$2D(1, IEditorWorkerService),
    __param$2D(2, ITelemetryService)
  ], WorkerBasedDocumentDiffProvider);
  class LinesDiff {
    constructor(changes, moves, hitTimeout) {
      this.changes = changes;
      this.moves = moves;
      this.hitTimeout = hitTimeout;
    }
  }
  class MovedText {
    constructor(lineRangeMapping, changes) {
      this.lineRangeMapping = lineRangeMapping;
      this.changes = changes;
    }
  }
  class DiffAlgorithmResult {
    static trivial(seq1, seq2) {
      return new DiffAlgorithmResult([new SequenceDiff(OffsetRange.ofLength(seq1.length), OffsetRange.ofLength(seq2.length))], false);
    }
    static trivialTimedOut(seq1, seq2) {
      return new DiffAlgorithmResult([new SequenceDiff(OffsetRange.ofLength(seq1.length), OffsetRange.ofLength(seq2.length))], true);
    }
    constructor(diffs, hitTimeout) {
      this.diffs = diffs;
      this.hitTimeout = hitTimeout;
    }
  }
  class SequenceDiff {
    static invert(sequenceDiffs, doc1Length) {
      const result = [];
      forEachAdjacent(sequenceDiffs, (a, b) => {
        result.push(SequenceDiff.fromOffsetPairs(a ? a.getEndExclusives() : OffsetPair.zero, b ? b.getStarts() : new OffsetPair(doc1Length, (a ? a.seq2Range.endExclusive - a.seq1Range.endExclusive : 0) + doc1Length)));
      });
      return result;
    }
    static fromOffsetPairs(start, endExclusive) {
      return new SequenceDiff(new OffsetRange(start.offset1, endExclusive.offset1), new OffsetRange(start.offset2, endExclusive.offset2));
    }
    static assertSorted(sequenceDiffs) {
      let last = void 0;
      for (const cur of sequenceDiffs) {
        if (last) {
          if (!(last.seq1Range.endExclusive <= cur.seq1Range.start && last.seq2Range.endExclusive <= cur.seq2Range.start)) {
            throw new BugIndicatingError("Sequence diffs must be sorted");
          }
        }
        last = cur;
      }
    }
    constructor(seq1Range, seq2Range) {
      this.seq1Range = seq1Range;
      this.seq2Range = seq2Range;
    }
    swap() {
      return new SequenceDiff(this.seq2Range, this.seq1Range);
    }
    toString() {
      return `${this.seq1Range} <-> ${this.seq2Range}`;
    }
    join(other) {
      return new SequenceDiff(this.seq1Range.join(other.seq1Range), this.seq2Range.join(other.seq2Range));
    }
    delta(offset) {
      if (offset === 0) {
        return this;
      }
      return new SequenceDiff(this.seq1Range.delta(offset), this.seq2Range.delta(offset));
    }
    deltaStart(offset) {
      if (offset === 0) {
        return this;
      }
      return new SequenceDiff(this.seq1Range.deltaStart(offset), this.seq2Range.deltaStart(offset));
    }
    deltaEnd(offset) {
      if (offset === 0) {
        return this;
      }
      return new SequenceDiff(this.seq1Range.deltaEnd(offset), this.seq2Range.deltaEnd(offset));
    }
    intersect(other) {
      const i1 = this.seq1Range.intersect(other.seq1Range);
      const i2 = this.seq2Range.intersect(other.seq2Range);
      if (!i1 || !i2) {
        return void 0;
      }
      return new SequenceDiff(i1, i2);
    }
    getStarts() {
      return new OffsetPair(this.seq1Range.start, this.seq2Range.start);
    }
    getEndExclusives() {
      return new OffsetPair(this.seq1Range.endExclusive, this.seq2Range.endExclusive);
    }
  }
  const _OffsetPair = class _OffsetPair {
    constructor(offset1, offset2) {
      this.offset1 = offset1;
      this.offset2 = offset2;
    }
    toString() {
      return `${this.offset1} <-> ${this.offset2}`;
    }
    delta(offset) {
      if (offset === 0) {
        return this;
      }
      return new _OffsetPair(this.offset1 + offset, this.offset2 + offset);
    }
    equals(other) {
      return this.offset1 === other.offset1 && this.offset2 === other.offset2;
    }
  };
  _OffsetPair.zero = new _OffsetPair(0, 0);
  _OffsetPair.max = new _OffsetPair(Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER);
  let OffsetPair = _OffsetPair;
  const _InfiniteTimeout = class _InfiniteTimeout {
    isValid() {
      return true;
    }
  };
  _InfiniteTimeout.instance = new _InfiniteTimeout();
  let InfiniteTimeout = _InfiniteTimeout;
  class DateTimeout {
    constructor(timeout2) {
      this.timeout = timeout2;
      this.startTime = Date.now();
      this.valid = true;
      if (timeout2 <= 0) {
        throw new BugIndicatingError("timeout must be positive");
      }
    }
    // Recommendation: Set a log-point `{this.disable()}` in the body
    isValid() {
      const valid = Date.now() - this.startTime < this.timeout;
      if (!valid && this.valid) {
        this.valid = false;
      }
      return this.valid;
    }
  }
  class Array2D {
    constructor(width2, height) {
      this.width = width2;
      this.height = height;
      this.array = [];
      this.array = new Array(width2 * height);
    }
    get(x, y) {
      return this.array[x + y * this.width];
    }
    set(x, y, value) {
      this.array[x + y * this.width] = value;
    }
  }
  function isSpace(charCode) {
    return charCode === 32 || charCode === 9;
  }
  const _LineRangeFragment = class _LineRangeFragment {
    static getKey(chr) {
      let key = this.chrKeys.get(chr);
      if (key === void 0) {
        key = this.chrKeys.size;
        this.chrKeys.set(chr, key);
      }
      return key;
    }
    constructor(range2, lines, source) {
      this.range = range2;
      this.lines = lines;
      this.source = source;
      this.histogram = [];
      let counter = 0;
      for (let i2 = range2.startLineNumber - 1; i2 < range2.endLineNumberExclusive - 1; i2++) {
        const line = lines[i2];
        for (let j = 0; j < line.length; j++) {
          counter++;
          const chr = line[j];
          const key2 = _LineRangeFragment.getKey(chr);
          this.histogram[key2] = (this.histogram[key2] || 0) + 1;
        }
        counter++;
        const key = _LineRangeFragment.getKey("\n");
        this.histogram[key] = (this.histogram[key] || 0) + 1;
      }
      this.totalCount = counter;
    }
    computeSimilarity(other) {
      let sumDifferences = 0;
      const maxLength = Math.max(this.histogram.length, other.histogram.length);
      for (let i2 = 0; i2 < maxLength; i2++) {
        sumDifferences += Math.abs((this.histogram[i2] ?? 0) - (other.histogram[i2] ?? 0));
      }
      return 1 - sumDifferences / (this.totalCount + other.totalCount);
    }
  };
  _LineRangeFragment.chrKeys = /* @__PURE__ */ new Map();
  let LineRangeFragment = _LineRangeFragment;
  class DynamicProgrammingDiffing {
    compute(sequence1, sequence2, timeout2 = InfiniteTimeout.instance, equalityScore) {
      if (sequence1.length === 0 || sequence2.length === 0) {
        return DiffAlgorithmResult.trivial(sequence1, sequence2);
      }
      const lcsLengths = new Array2D(sequence1.length, sequence2.length);
      const directions = new Array2D(sequence1.length, sequence2.length);
      const lengths = new Array2D(sequence1.length, sequence2.length);
      for (let s12 = 0; s12 < sequence1.length; s12++) {
        for (let s22 = 0; s22 < sequence2.length; s22++) {
          if (!timeout2.isValid()) {
            return DiffAlgorithmResult.trivialTimedOut(sequence1, sequence2);
          }
          const horizontalLen = s12 === 0 ? 0 : lcsLengths.get(s12 - 1, s22);
          const verticalLen = s22 === 0 ? 0 : lcsLengths.get(s12, s22 - 1);
          let extendedSeqScore;
          if (sequence1.getElement(s12) === sequence2.getElement(s22)) {
            if (s12 === 0 || s22 === 0) {
              extendedSeqScore = 0;
            } else {
              extendedSeqScore = lcsLengths.get(s12 - 1, s22 - 1);
            }
            if (s12 > 0 && s22 > 0 && directions.get(s12 - 1, s22 - 1) === 3) {
              extendedSeqScore += lengths.get(s12 - 1, s22 - 1);
            }
            extendedSeqScore += equalityScore ? equalityScore(s12, s22) : 1;
          } else {
            extendedSeqScore = -1;
          }
          const newValue = Math.max(horizontalLen, verticalLen, extendedSeqScore);
          if (newValue === extendedSeqScore) {
            const prevLen = s12 > 0 && s22 > 0 ? lengths.get(s12 - 1, s22 - 1) : 0;
            lengths.set(s12, s22, prevLen + 1);
            directions.set(s12, s22, 3);
          } else if (newValue === horizontalLen) {
            lengths.set(s12, s22, 0);
            directions.set(s12, s22, 1);
          } else if (newValue === verticalLen) {
            lengths.set(s12, s22, 0);
            directions.set(s12, s22, 2);
          }
          lcsLengths.set(s12, s22, newValue);
        }
      }
      const result = [];
      let lastAligningPosS1 = sequence1.length;
      let lastAligningPosS2 = sequence2.length;
      function reportDecreasingAligningPositions(s12, s22) {
        if (s12 + 1 !== lastAligningPosS1 || s22 + 1 !== lastAligningPosS2) {
          result.push(new SequenceDiff(new OffsetRange(s12 + 1, lastAligningPosS1), new OffsetRange(s22 + 1, lastAligningPosS2)));
        }
        lastAligningPosS1 = s12;
        lastAligningPosS2 = s22;
      }
      let s1 = sequence1.length - 1;
      let s2 = sequence2.length - 1;
      while (s1 >= 0 && s2 >= 0) {
        if (directions.get(s1, s2) === 3) {
          reportDecreasingAligningPositions(s1, s2);
          s1--;
          s2--;
        } else {
          if (directions.get(s1, s2) === 1) {
            s1--;
          } else {
            s2--;
          }
        }
      }
      reportDecreasingAligningPositions(-1, -1);
      result.reverse();
      return new DiffAlgorithmResult(result, false);
    }
  }
  class MyersDiffAlgorithm {
    compute(seq1, seq2, timeout2 = InfiniteTimeout.instance) {
      if (seq1.length === 0 || seq2.length === 0) {
        return DiffAlgorithmResult.trivial(seq1, seq2);
      }
      const seqX = seq1;
      const seqY = seq2;
      function getXAfterSnake(x, y) {
        while (x < seqX.length && y < seqY.length && seqX.getElement(x) === seqY.getElement(y)) {
          x++;
          y++;
        }
        return x;
      }
      let d = 0;
      const V = new FastInt32Array();
      V.set(0, getXAfterSnake(0, 0));
      const paths = new FastArrayNegativeIndices();
      paths.set(0, V.get(0) === 0 ? null : new SnakePath(null, 0, 0, V.get(0)));
      let k = 0;
      loop: while (true) {
        d++;
        if (!timeout2.isValid()) {
          return DiffAlgorithmResult.trivialTimedOut(seqX, seqY);
        }
        const lowerBound = -Math.min(d, seqY.length + d % 2);
        const upperBound = Math.min(d, seqX.length + d % 2);
        for (k = lowerBound; k <= upperBound; k += 2) {
          const maxXofDLineTop = k === upperBound ? -1 : V.get(k + 1);
          const maxXofDLineLeft = k === lowerBound ? -1 : V.get(k - 1) + 1;
          const x = Math.min(Math.max(maxXofDLineTop, maxXofDLineLeft), seqX.length);
          const y = x - k;
          if (x > seqX.length || y > seqY.length) {
            continue;
          }
          const newMaxX = getXAfterSnake(x, y);
          V.set(k, newMaxX);
          const lastPath = x === maxXofDLineTop ? paths.get(k + 1) : paths.get(k - 1);
          paths.set(k, newMaxX !== x ? new SnakePath(lastPath, x, y, newMaxX - x) : lastPath);
          if (V.get(k) === seqX.length && V.get(k) - k === seqY.length) {
            break loop;
          }
        }
      }
      let path = paths.get(k);
      const result = [];
      let lastAligningPosS1 = seqX.length;
      let lastAligningPosS2 = seqY.length;
      while (true) {
        const endX = path ? path.x + path.length : 0;
        const endY = path ? path.y + path.length : 0;
        if (endX !== lastAligningPosS1 || endY !== lastAligningPosS2) {
          result.push(new SequenceDiff(new OffsetRange(endX, lastAligningPosS1), new OffsetRange(endY, lastAligningPosS2)));
        }
        if (!path) {
          break;
        }
        lastAligningPosS1 = path.x;
        lastAligningPosS2 = path.y;
        path = path.prev;
      }
      result.reverse();
      return new DiffAlgorithmResult(result, false);
    }
  }
  class SnakePath {
    constructor(prev, x, y, length) {
      this.prev = prev;
      this.x = x;
      this.y = y;
      this.length = length;
    }
  }
  class FastInt32Array {
    constructor() {
      this.positiveArr = new Int32Array(10);
      this.negativeArr = new Int32Array(10);
    }
    get(idx) {
      if (idx < 0) {
        idx = -idx - 1;
        return this.negativeArr[idx];
      } else {
        return this.positiveArr[idx];
      }
    }
    set(idx, value) {
      if (idx < 0) {
        idx = -idx - 1;
        if (idx >= this.negativeArr.length) {
          const arr = this.negativeArr;
          this.negativeArr = new Int32Array(arr.length * 2);
          this.negativeArr.set(arr);
        }
        this.negativeArr[idx] = value;
      } else {
        if (idx >= this.positiveArr.length) {
          const arr = this.positiveArr;
          this.positiveArr = new Int32Array(arr.length * 2);
          this.positiveArr.set(arr);
        }
        this.positiveArr[idx] = value;
      }
    }
  }
  class FastArrayNegativeIndices {
    constructor() {
      this.positiveArr = [];
      this.negativeArr = [];
    }
    get(idx) {
      if (idx < 0) {
        idx = -idx - 1;
        return this.negativeArr[idx];
      } else {
        return this.positiveArr[idx];
      }
    }
    set(idx, value) {
      if (idx < 0) {
        idx = -idx - 1;
        this.negativeArr[idx] = value;
      } else {
        this.positiveArr[idx] = value;
      }
    }
  }
  class LinesSliceCharSequence {
    constructor(lines, range2, considerWhitespaceChanges) {
      this.lines = lines;
      this.range = range2;
      this.considerWhitespaceChanges = considerWhitespaceChanges;
      this.elements = [];
      this.firstElementOffsetByLineIdx = [];
      this.lineStartOffsets = [];
      this.trimmedWsLengthsByLineIdx = [];
      this.firstElementOffsetByLineIdx.push(0);
      for (let lineNumber = this.range.startLineNumber; lineNumber <= this.range.endLineNumber; lineNumber++) {
        let line = lines[lineNumber - 1];
        let lineStartOffset = 0;
        if (lineNumber === this.range.startLineNumber && this.range.startColumn > 1) {
          lineStartOffset = this.range.startColumn - 1;
          line = line.substring(lineStartOffset);
        }
        this.lineStartOffsets.push(lineStartOffset);
        let trimmedWsLength = 0;
        if (!considerWhitespaceChanges) {
          const trimmedStartLine = line.trimStart();
          trimmedWsLength = line.length - trimmedStartLine.length;
          line = trimmedStartLine.trimEnd();
        }
        this.trimmedWsLengthsByLineIdx.push(trimmedWsLength);
        const lineLength = lineNumber === this.range.endLineNumber ? Math.min(this.range.endColumn - 1 - lineStartOffset - trimmedWsLength, line.length) : line.length;
        for (let i2 = 0; i2 < lineLength; i2++) {
          this.elements.push(line.charCodeAt(i2));
        }
        if (lineNumber < this.range.endLineNumber) {
          this.elements.push("\n".charCodeAt(0));
          this.firstElementOffsetByLineIdx.push(this.elements.length);
        }
      }
    }
    toString() {
      return `Slice: "${this.text}"`;
    }
    get text() {
      return this.getText(new OffsetRange(0, this.length));
    }
    getText(range2) {
      return this.elements.slice(range2.start, range2.endExclusive).map((e) => String.fromCharCode(e)).join("");
    }
    getElement(offset) {
      return this.elements[offset];
    }
    get length() {
      return this.elements.length;
    }
    getBoundaryScore(length) {
      const prevCategory = getCategory(length > 0 ? this.elements[length - 1] : -1);
      const nextCategory = getCategory(length < this.elements.length ? this.elements[length] : -1);
      if (prevCategory === 7 && nextCategory === 8) {
        return 0;
      }
      if (prevCategory === 8) {
        return 150;
      }
      let score2 = 0;
      if (prevCategory !== nextCategory) {
        score2 += 10;
        if (prevCategory === 0 && nextCategory === 1) {
          score2 += 1;
        }
      }
      score2 += getCategoryBoundaryScore(prevCategory);
      score2 += getCategoryBoundaryScore(nextCategory);
      return score2;
    }
    translateOffset(offset, preference = "right") {
      const i2 = findLastIdxMonotonous(this.firstElementOffsetByLineIdx, (value) => value <= offset);
      const lineOffset = offset - this.firstElementOffsetByLineIdx[i2];
      return new Position$1(this.range.startLineNumber + i2, 1 + this.lineStartOffsets[i2] + lineOffset + (lineOffset === 0 && preference === "left" ? 0 : this.trimmedWsLengthsByLineIdx[i2]));
    }
    translateRange(range2) {
      const pos1 = this.translateOffset(range2.start, "right");
      const pos2 = this.translateOffset(range2.endExclusive, "left");
      if (pos2.isBefore(pos1)) {
        return Range$2.fromPositions(pos2, pos2);
      }
      return Range$2.fromPositions(pos1, pos2);
    }
    /**
     * Finds the word that contains the character at the given offset
     */
    findWordContaining(offset) {
      if (offset < 0 || offset >= this.elements.length) {
        return void 0;
      }
      if (!isWordChar(this.elements[offset])) {
        return void 0;
      }
      let start = offset;
      while (start > 0 && isWordChar(this.elements[start - 1])) {
        start--;
      }
      let end = offset;
      while (end < this.elements.length && isWordChar(this.elements[end])) {
        end++;
      }
      return new OffsetRange(start, end);
    }
    /** fooBar has the two sub-words foo and bar */
    findSubWordContaining(offset) {
      if (offset < 0 || offset >= this.elements.length) {
        return void 0;
      }
      if (!isWordChar(this.elements[offset])) {
        return void 0;
      }
      let start = offset;
      while (start > 0 && isWordChar(this.elements[start - 1]) && !isUpperCase(this.elements[start])) {
        start--;
      }
      let end = offset;
      while (end < this.elements.length && isWordChar(this.elements[end]) && !isUpperCase(this.elements[end])) {
        end++;
      }
      return new OffsetRange(start, end);
    }
    countLinesIn(range2) {
      return this.translateOffset(range2.endExclusive).lineNumber - this.translateOffset(range2.start).lineNumber;
    }
    isStronglyEqual(offset1, offset2) {
      return this.elements[offset1] === this.elements[offset2];
    }
    extendToFullLines(range2) {
      const start = findLastMonotonous(this.firstElementOffsetByLineIdx, (x) => x <= range2.start) ?? 0;
      const end = findFirstMonotonous(this.firstElementOffsetByLineIdx, (x) => range2.endExclusive <= x) ?? this.elements.length;
      return new OffsetRange(start, end);
    }
  }
  function isWordChar(charCode) {
    return charCode >= 97 && charCode <= 122 || charCode >= 65 && charCode <= 90 || charCode >= 48 && charCode <= 57;
  }
  function isUpperCase(charCode) {
    return charCode >= 65 && charCode <= 90;
  }
  const score$1 = {
    [
      0
      /* CharBoundaryCategory.WordLower */
    ]: 0,
    [
      1
      /* CharBoundaryCategory.WordUpper */
    ]: 0,
    [
      2
      /* CharBoundaryCategory.WordNumber */
    ]: 0,
    [
      3
      /* CharBoundaryCategory.End */
    ]: 10,
    [
      4
      /* CharBoundaryCategory.Other */
    ]: 2,
    [
      5
      /* CharBoundaryCategory.Separator */
    ]: 30,
    [
      6
      /* CharBoundaryCategory.Space */
    ]: 3,
    [
      7
      /* CharBoundaryCategory.LineBreakCR */
    ]: 10,
    [
      8
      /* CharBoundaryCategory.LineBreakLF */
    ]: 10
  };
  function getCategoryBoundaryScore(category) {
    return score$1[category];
  }
  function getCategory(charCode) {
    if (charCode === 10) {
      return 8;
    } else if (charCode === 13) {
      return 7;
    } else if (isSpace(charCode)) {
      return 6;
    } else if (charCode >= 97 && charCode <= 122) {
      return 0;
    } else if (charCode >= 65 && charCode <= 90) {
      return 1;
    } else if (charCode >= 48 && charCode <= 57) {
      return 2;
    } else if (charCode === -1) {
      return 3;
    } else if (charCode === 44 || charCode === 59) {
      return 5;
    } else {
      return 4;
    }
  }
  function computeMovedLines(changes, originalLines, modifiedLines, hashedOriginalLines, hashedModifiedLines, timeout2) {
    let { moves, excludedChanges } = computeMovesFromSimpleDeletionsToSimpleInsertions(changes, originalLines, modifiedLines, timeout2);
    if (!timeout2.isValid()) {
      return [];
    }
    const filteredChanges = changes.filter((c) => !excludedChanges.has(c));
    const unchangedMoves = computeUnchangedMoves(filteredChanges, hashedOriginalLines, hashedModifiedLines, originalLines, modifiedLines, timeout2);
    pushMany(moves, unchangedMoves);
    moves = joinCloseConsecutiveMoves(moves);
    moves = moves.filter((current) => {
      const lines = current.original.toOffsetRange().slice(originalLines).map((l) => l.trim());
      const originalText = lines.join("\n");
      return originalText.length >= 15 && countWhere(lines, (l) => l.length >= 2) >= 2;
    });
    moves = removeMovesInSameDiff(changes, moves);
    return moves;
  }
  function countWhere(arr, predicate) {
    let count = 0;
    for (const t of arr) {
      if (predicate(t)) {
        count++;
      }
    }
    return count;
  }
  function computeMovesFromSimpleDeletionsToSimpleInsertions(changes, originalLines, modifiedLines, timeout2) {
    const moves = [];
    const deletions = changes.filter((c) => c.modified.isEmpty && c.original.length >= 3).map((d) => new LineRangeFragment(d.original, originalLines, d));
    const insertions = new Set(changes.filter((c) => c.original.isEmpty && c.modified.length >= 3).map((d) => new LineRangeFragment(d.modified, modifiedLines, d)));
    const excludedChanges = /* @__PURE__ */ new Set();
    for (const deletion of deletions) {
      let highestSimilarity = -1;
      let best;
      for (const insertion of insertions) {
        const similarity = deletion.computeSimilarity(insertion);
        if (similarity > highestSimilarity) {
          highestSimilarity = similarity;
          best = insertion;
        }
      }
      if (highestSimilarity > 0.9 && best) {
        insertions.delete(best);
        moves.push(new LineRangeMapping(deletion.range, best.range));
        excludedChanges.add(deletion.source);
        excludedChanges.add(best.source);
      }
      if (!timeout2.isValid()) {
        return { moves, excludedChanges };
      }
    }
    return { moves, excludedChanges };
  }
  function computeUnchangedMoves(changes, hashedOriginalLines, hashedModifiedLines, originalLines, modifiedLines, timeout2) {
    const moves = [];
    const original3LineHashes = new SetMap();
    for (const change of changes) {
      for (let i2 = change.original.startLineNumber; i2 < change.original.endLineNumberExclusive - 2; i2++) {
        const key = `${hashedOriginalLines[i2 - 1]}:${hashedOriginalLines[i2 + 1 - 1]}:${hashedOriginalLines[i2 + 2 - 1]}`;
        original3LineHashes.add(key, { range: new LineRange(i2, i2 + 3) });
      }
    }
    const possibleMappings = [];
    changes.sort(compareBy((c) => c.modified.startLineNumber, numberComparator));
    for (const change of changes) {
      let lastMappings = [];
      for (let i2 = change.modified.startLineNumber; i2 < change.modified.endLineNumberExclusive - 2; i2++) {
        const key = `${hashedModifiedLines[i2 - 1]}:${hashedModifiedLines[i2 + 1 - 1]}:${hashedModifiedLines[i2 + 2 - 1]}`;
        const currentModifiedRange = new LineRange(i2, i2 + 3);
        const nextMappings = [];
        original3LineHashes.forEach(key, ({ range: range2 }) => {
          for (const lastMapping of lastMappings) {
            if (lastMapping.originalLineRange.endLineNumberExclusive + 1 === range2.endLineNumberExclusive && lastMapping.modifiedLineRange.endLineNumberExclusive + 1 === currentModifiedRange.endLineNumberExclusive) {
              lastMapping.originalLineRange = new LineRange(lastMapping.originalLineRange.startLineNumber, range2.endLineNumberExclusive);
              lastMapping.modifiedLineRange = new LineRange(lastMapping.modifiedLineRange.startLineNumber, currentModifiedRange.endLineNumberExclusive);
              nextMappings.push(lastMapping);
              return;
            }
          }
          const mapping = {
            modifiedLineRange: currentModifiedRange,
            originalLineRange: range2
          };
          possibleMappings.push(mapping);
          nextMappings.push(mapping);
        });
        lastMappings = nextMappings;
      }
      if (!timeout2.isValid()) {
        return [];
      }
    }
    possibleMappings.sort(reverseOrder(compareBy((m) => m.modifiedLineRange.length, numberComparator)));
    const modifiedSet = new LineRangeSet();
    const originalSet = new LineRangeSet();
    for (const mapping of possibleMappings) {
      const diffOrigToMod = mapping.modifiedLineRange.startLineNumber - mapping.originalLineRange.startLineNumber;
      const modifiedSections = modifiedSet.subtractFrom(mapping.modifiedLineRange);
      const originalTranslatedSections = originalSet.subtractFrom(mapping.originalLineRange).getWithDelta(diffOrigToMod);
      const modifiedIntersectedSections = modifiedSections.getIntersection(originalTranslatedSections);
      for (const s of modifiedIntersectedSections.ranges) {
        if (s.length < 3) {
          continue;
        }
        const modifiedLineRange = s;
        const originalLineRange = s.delta(-diffOrigToMod);
        moves.push(new LineRangeMapping(originalLineRange, modifiedLineRange));
        modifiedSet.addRange(modifiedLineRange);
        originalSet.addRange(originalLineRange);
      }
    }
    moves.sort(compareBy((m) => m.original.startLineNumber, numberComparator));
    const monotonousChanges = new MonotonousArray(changes);
    for (let i2 = 0; i2 < moves.length; i2++) {
      const move = moves[i2];
      const firstTouchingChangeOrig = monotonousChanges.findLastMonotonous((c) => c.original.startLineNumber <= move.original.startLineNumber);
      const firstTouchingChangeMod = findLastMonotonous(changes, (c) => c.modified.startLineNumber <= move.modified.startLineNumber);
      const linesAbove = Math.max(move.original.startLineNumber - firstTouchingChangeOrig.original.startLineNumber, move.modified.startLineNumber - firstTouchingChangeMod.modified.startLineNumber);
      const lastTouchingChangeOrig = monotonousChanges.findLastMonotonous((c) => c.original.startLineNumber < move.original.endLineNumberExclusive);
      const lastTouchingChangeMod = findLastMonotonous(changes, (c) => c.modified.startLineNumber < move.modified.endLineNumberExclusive);
      const linesBelow = Math.max(lastTouchingChangeOrig.original.endLineNumberExclusive - move.original.endLineNumberExclusive, lastTouchingChangeMod.modified.endLineNumberExclusive - move.modified.endLineNumberExclusive);
      let extendToTop;
      for (extendToTop = 0; extendToTop < linesAbove; extendToTop++) {
        const origLine = move.original.startLineNumber - extendToTop - 1;
        const modLine = move.modified.startLineNumber - extendToTop - 1;
        if (origLine > originalLines.length || modLine > modifiedLines.length) {
          break;
        }
        if (modifiedSet.contains(modLine) || originalSet.contains(origLine)) {
          break;
        }
        if (!areLinesSimilar(originalLines[origLine - 1], modifiedLines[modLine - 1], timeout2)) {
          break;
        }
      }
      if (extendToTop > 0) {
        originalSet.addRange(new LineRange(move.original.startLineNumber - extendToTop, move.original.startLineNumber));
        modifiedSet.addRange(new LineRange(move.modified.startLineNumber - extendToTop, move.modified.startLineNumber));
      }
      let extendToBottom;
      for (extendToBottom = 0; extendToBottom < linesBelow; extendToBottom++) {
        const origLine = move.original.endLineNumberExclusive + extendToBottom;
        const modLine = move.modified.endLineNumberExclusive + extendToBottom;
        if (origLine > originalLines.length || modLine > modifiedLines.length) {
          break;
        }
        if (modifiedSet.contains(modLine) || originalSet.contains(origLine)) {
          break;
        }
        if (!areLinesSimilar(originalLines[origLine - 1], modifiedLines[modLine - 1], timeout2)) {
          break;
        }
      }
      if (extendToBottom > 0) {
        originalSet.addRange(new LineRange(move.original.endLineNumberExclusive, move.original.endLineNumberExclusive + extendToBottom));
        modifiedSet.addRange(new LineRange(move.modified.endLineNumberExclusive, move.modified.endLineNumberExclusive + extendToBottom));
      }
      if (extendToTop > 0 || extendToBottom > 0) {
        moves[i2] = new LineRangeMapping(new LineRange(move.original.startLineNumber - extendToTop, move.original.endLineNumberExclusive + extendToBottom), new LineRange(move.modified.startLineNumber - extendToTop, move.modified.endLineNumberExclusive + extendToBottom));
      }
    }
    return moves;
  }
  function areLinesSimilar(line1, line2, timeout2) {
    if (line1.trim() === line2.trim()) {
      return true;
    }
    if (line1.length > 300 && line2.length > 300) {
      return false;
    }
    const myersDiffingAlgorithm = new MyersDiffAlgorithm();
    const result = myersDiffingAlgorithm.compute(new LinesSliceCharSequence([line1], new Range$2(1, 1, 1, line1.length), false), new LinesSliceCharSequence([line2], new Range$2(1, 1, 1, line2.length), false), timeout2);
    let commonNonSpaceCharCount = 0;
    const inverted = SequenceDiff.invert(result.diffs, line1.length);
    for (const seq of inverted) {
      seq.seq1Range.forEach((idx) => {
        if (!isSpace(line1.charCodeAt(idx))) {
          commonNonSpaceCharCount++;
        }
      });
    }
    function countNonWsChars(str) {
      let count = 0;
      for (let i2 = 0; i2 < line1.length; i2++) {
        if (!isSpace(str.charCodeAt(i2))) {
          count++;
        }
      }
      return count;
    }
    const longerLineLength = countNonWsChars(line1.length > line2.length ? line1 : line2);
    const r = commonNonSpaceCharCount / longerLineLength > 0.6 && longerLineLength > 10;
    return r;
  }
  function joinCloseConsecutiveMoves(moves) {
    if (moves.length === 0) {
      return moves;
    }
    moves.sort(compareBy((m) => m.original.startLineNumber, numberComparator));
    const result = [moves[0]];
    for (let i2 = 1; i2 < moves.length; i2++) {
      const last = result[result.length - 1];
      const current = moves[i2];
      const originalDist = current.original.startLineNumber - last.original.endLineNumberExclusive;
      const modifiedDist = current.modified.startLineNumber - last.modified.endLineNumberExclusive;
      const currentMoveAfterLast = originalDist >= 0 && modifiedDist >= 0;
      if (currentMoveAfterLast && originalDist + modifiedDist <= 2) {
        result[result.length - 1] = last.join(current);
        continue;
      }
      result.push(current);
    }
    return result;
  }
  function removeMovesInSameDiff(changes, moves) {
    const changesMonotonous = new MonotonousArray(changes);
    moves = moves.filter((m) => {
      const diffBeforeEndOfMoveOriginal = changesMonotonous.findLastMonotonous((c) => c.original.startLineNumber < m.original.endLineNumberExclusive) || new LineRangeMapping(new LineRange(1, 1), new LineRange(1, 1));
      const diffBeforeEndOfMoveModified = findLastMonotonous(changes, (c) => c.modified.startLineNumber < m.modified.endLineNumberExclusive);
      const differentDiffs = diffBeforeEndOfMoveOriginal !== diffBeforeEndOfMoveModified;
      return differentDiffs;
    });
    return moves;
  }
  function optimizeSequenceDiffs(sequence1, sequence2, sequenceDiffs) {
    let result = sequenceDiffs;
    result = joinSequenceDiffsByShifting(sequence1, sequence2, result);
    result = joinSequenceDiffsByShifting(sequence1, sequence2, result);
    result = shiftSequenceDiffs(sequence1, sequence2, result);
    return result;
  }
  function joinSequenceDiffsByShifting(sequence1, sequence2, sequenceDiffs) {
    if (sequenceDiffs.length === 0) {
      return sequenceDiffs;
    }
    const result = [];
    result.push(sequenceDiffs[0]);
    for (let i2 = 1; i2 < sequenceDiffs.length; i2++) {
      const prevResult = result[result.length - 1];
      let cur = sequenceDiffs[i2];
      if (cur.seq1Range.isEmpty || cur.seq2Range.isEmpty) {
        const length = cur.seq1Range.start - prevResult.seq1Range.endExclusive;
        let d;
        for (d = 1; d <= length; d++) {
          if (sequence1.getElement(cur.seq1Range.start - d) !== sequence1.getElement(cur.seq1Range.endExclusive - d) || sequence2.getElement(cur.seq2Range.start - d) !== sequence2.getElement(cur.seq2Range.endExclusive - d)) {
            break;
          }
        }
        d--;
        if (d === length) {
          result[result.length - 1] = new SequenceDiff(new OffsetRange(prevResult.seq1Range.start, cur.seq1Range.endExclusive - length), new OffsetRange(prevResult.seq2Range.start, cur.seq2Range.endExclusive - length));
          continue;
        }
        cur = cur.delta(-d);
      }
      result.push(cur);
    }
    const result2 = [];
    for (let i2 = 0; i2 < result.length - 1; i2++) {
      const nextResult = result[i2 + 1];
      let cur = result[i2];
      if (cur.seq1Range.isEmpty || cur.seq2Range.isEmpty) {
        const length = nextResult.seq1Range.start - cur.seq1Range.endExclusive;
        let d;
        for (d = 0; d < length; d++) {
          if (!sequence1.isStronglyEqual(cur.seq1Range.start + d, cur.seq1Range.endExclusive + d) || !sequence2.isStronglyEqual(cur.seq2Range.start + d, cur.seq2Range.endExclusive + d)) {
            break;
          }
        }
        if (d === length) {
          result[i2 + 1] = new SequenceDiff(new OffsetRange(cur.seq1Range.start + length, nextResult.seq1Range.endExclusive), new OffsetRange(cur.seq2Range.start + length, nextResult.seq2Range.endExclusive));
          continue;
        }
        if (d > 0) {
          cur = cur.delta(d);
        }
      }
      result2.push(cur);
    }
    if (result.length > 0) {
      result2.push(result[result.length - 1]);
    }
    return result2;
  }
  function shiftSequenceDiffs(sequence1, sequence2, sequenceDiffs) {
    if (!sequence1.getBoundaryScore || !sequence2.getBoundaryScore) {
      return sequenceDiffs;
    }
    for (let i2 = 0; i2 < sequenceDiffs.length; i2++) {
      const prevDiff = i2 > 0 ? sequenceDiffs[i2 - 1] : void 0;
      const diff = sequenceDiffs[i2];
      const nextDiff = i2 + 1 < sequenceDiffs.length ? sequenceDiffs[i2 + 1] : void 0;
      const seq1ValidRange = new OffsetRange(prevDiff ? prevDiff.seq1Range.endExclusive + 1 : 0, nextDiff ? nextDiff.seq1Range.start - 1 : sequence1.length);
      const seq2ValidRange = new OffsetRange(prevDiff ? prevDiff.seq2Range.endExclusive + 1 : 0, nextDiff ? nextDiff.seq2Range.start - 1 : sequence2.length);
      if (diff.seq1Range.isEmpty) {
        sequenceDiffs[i2] = shiftDiffToBetterPosition(diff, sequence1, sequence2, seq1ValidRange, seq2ValidRange);
      } else if (diff.seq2Range.isEmpty) {
        sequenceDiffs[i2] = shiftDiffToBetterPosition(diff.swap(), sequence2, sequence1, seq2ValidRange, seq1ValidRange).swap();
      }
    }
    return sequenceDiffs;
  }
  function shiftDiffToBetterPosition(diff, sequence1, sequence2, seq1ValidRange, seq2ValidRange) {
    const maxShiftLimit = 100;
    let deltaBefore = 1;
    while (diff.seq1Range.start - deltaBefore >= seq1ValidRange.start && diff.seq2Range.start - deltaBefore >= seq2ValidRange.start && sequence2.isStronglyEqual(diff.seq2Range.start - deltaBefore, diff.seq2Range.endExclusive - deltaBefore) && deltaBefore < maxShiftLimit) {
      deltaBefore++;
    }
    deltaBefore--;
    let deltaAfter = 0;
    while (diff.seq1Range.start + deltaAfter < seq1ValidRange.endExclusive && diff.seq2Range.endExclusive + deltaAfter < seq2ValidRange.endExclusive && sequence2.isStronglyEqual(diff.seq2Range.start + deltaAfter, diff.seq2Range.endExclusive + deltaAfter) && deltaAfter < maxShiftLimit) {
      deltaAfter++;
    }
    if (deltaBefore === 0 && deltaAfter === 0) {
      return diff;
    }
    let bestDelta = 0;
    let bestScore = -1;
    for (let delta = -deltaBefore; delta <= deltaAfter; delta++) {
      const seq2OffsetStart = diff.seq2Range.start + delta;
      const seq2OffsetEndExclusive = diff.seq2Range.endExclusive + delta;
      const seq1Offset = diff.seq1Range.start + delta;
      const score2 = sequence1.getBoundaryScore(seq1Offset) + sequence2.getBoundaryScore(seq2OffsetStart) + sequence2.getBoundaryScore(seq2OffsetEndExclusive);
      if (score2 > bestScore) {
        bestScore = score2;
        bestDelta = delta;
      }
    }
    return diff.delta(bestDelta);
  }
  function removeShortMatches(sequence1, sequence2, sequenceDiffs) {
    const result = [];
    for (const s of sequenceDiffs) {
      const last = result[result.length - 1];
      if (!last) {
        result.push(s);
        continue;
      }
      if (s.seq1Range.start - last.seq1Range.endExclusive <= 2 || s.seq2Range.start - last.seq2Range.endExclusive <= 2) {
        result[result.length - 1] = new SequenceDiff(last.seq1Range.join(s.seq1Range), last.seq2Range.join(s.seq2Range));
      } else {
        result.push(s);
      }
    }
    return result;
  }
  function extendDiffsToEntireWordIfAppropriate(sequence1, sequence2, sequenceDiffs, findParent, force = false) {
    const equalMappings = SequenceDiff.invert(sequenceDiffs, sequence1.length);
    const additional = [];
    let lastPoint = new OffsetPair(0, 0);
    function scanWord(pair, equalMapping) {
      if (pair.offset1 < lastPoint.offset1 || pair.offset2 < lastPoint.offset2) {
        return;
      }
      const w1 = findParent(sequence1, pair.offset1);
      const w2 = findParent(sequence2, pair.offset2);
      if (!w1 || !w2) {
        return;
      }
      let w = new SequenceDiff(w1, w2);
      const equalPart = w.intersect(equalMapping);
      let equalChars1 = equalPart.seq1Range.length;
      let equalChars2 = equalPart.seq2Range.length;
      while (equalMappings.length > 0) {
        const next = equalMappings[0];
        const intersects2 = next.seq1Range.intersects(w.seq1Range) || next.seq2Range.intersects(w.seq2Range);
        if (!intersects2) {
          break;
        }
        const v1 = findParent(sequence1, next.seq1Range.start);
        const v2 = findParent(sequence2, next.seq2Range.start);
        const v = new SequenceDiff(v1, v2);
        const equalPart2 = v.intersect(next);
        equalChars1 += equalPart2.seq1Range.length;
        equalChars2 += equalPart2.seq2Range.length;
        w = w.join(v);
        if (w.seq1Range.endExclusive >= next.seq1Range.endExclusive) {
          equalMappings.shift();
        } else {
          break;
        }
      }
      if (force && equalChars1 + equalChars2 < w.seq1Range.length + w.seq2Range.length || equalChars1 + equalChars2 < (w.seq1Range.length + w.seq2Range.length) * 2 / 3) {
        additional.push(w);
      }
      lastPoint = w.getEndExclusives();
    }
    while (equalMappings.length > 0) {
      const next = equalMappings.shift();
      if (next.seq1Range.isEmpty) {
        continue;
      }
      scanWord(next.getStarts(), next);
      scanWord(next.getEndExclusives().delta(-1), next);
    }
    const merged = mergeSequenceDiffs(sequenceDiffs, additional);
    return merged;
  }
  function mergeSequenceDiffs(sequenceDiffs1, sequenceDiffs2) {
    const result = [];
    while (sequenceDiffs1.length > 0 || sequenceDiffs2.length > 0) {
      const sd1 = sequenceDiffs1[0];
      const sd2 = sequenceDiffs2[0];
      let next;
      if (sd1 && (!sd2 || sd1.seq1Range.start < sd2.seq1Range.start)) {
        next = sequenceDiffs1.shift();
      } else {
        next = sequenceDiffs2.shift();
      }
      if (result.length > 0 && result[result.length - 1].seq1Range.endExclusive >= next.seq1Range.start) {
        result[result.length - 1] = result[result.length - 1].join(next);
      } else {
        result.push(next);
      }
    }
    return result;
  }
  function removeVeryShortMatchingLinesBetweenDiffs(sequence1, _sequence2, sequenceDiffs) {
    let diffs = sequenceDiffs;
    if (diffs.length === 0) {
      return diffs;
    }
    let counter = 0;
    let shouldRepeat;
    do {
      shouldRepeat = false;
      const result = [
        diffs[0]
      ];
      for (let i2 = 1; i2 < diffs.length; i2++) {
        let shouldJoinDiffs = function(before, after2) {
          const unchangedRange = new OffsetRange(lastResult.seq1Range.endExclusive, cur.seq1Range.start);
          const unchangedText = sequence1.getText(unchangedRange);
          const unchangedTextWithoutWs = unchangedText.replace(/\s/g, "");
          if (unchangedTextWithoutWs.length <= 4 && (before.seq1Range.length + before.seq2Range.length > 5 || after2.seq1Range.length + after2.seq2Range.length > 5)) {
            return true;
          }
          return false;
        };
        const cur = diffs[i2];
        const lastResult = result[result.length - 1];
        const shouldJoin = shouldJoinDiffs(lastResult, cur);
        if (shouldJoin) {
          shouldRepeat = true;
          result[result.length - 1] = result[result.length - 1].join(cur);
        } else {
          result.push(cur);
        }
      }
      diffs = result;
    } while (counter++ < 10 && shouldRepeat);
    return diffs;
  }
  function removeVeryShortMatchingTextBetweenLongDiffs(sequence1, sequence2, sequenceDiffs) {
    let diffs = sequenceDiffs;
    if (diffs.length === 0) {
      return diffs;
    }
    let counter = 0;
    let shouldRepeat;
    do {
      shouldRepeat = false;
      const result = [
        diffs[0]
      ];
      for (let i2 = 1; i2 < diffs.length; i2++) {
        let shouldJoinDiffs = function(before, after2) {
          const unchangedRange = new OffsetRange(lastResult.seq1Range.endExclusive, cur.seq1Range.start);
          const unchangedLineCount = sequence1.countLinesIn(unchangedRange);
          if (unchangedLineCount > 5 || unchangedRange.length > 500) {
            return false;
          }
          const unchangedText = sequence1.getText(unchangedRange).trim();
          if (unchangedText.length > 20 || unchangedText.split(/\r\n|\r|\n/).length > 1) {
            return false;
          }
          const beforeLineCount1 = sequence1.countLinesIn(before.seq1Range);
          const beforeSeq1Length = before.seq1Range.length;
          const beforeLineCount2 = sequence2.countLinesIn(before.seq2Range);
          const beforeSeq2Length = before.seq2Range.length;
          const afterLineCount1 = sequence1.countLinesIn(after2.seq1Range);
          const afterSeq1Length = after2.seq1Range.length;
          const afterLineCount2 = sequence2.countLinesIn(after2.seq2Range);
          const afterSeq2Length = after2.seq2Range.length;
          const max = 2 * 40 + 50;
          function cap(v) {
            return Math.min(v, max);
          }
          if (Math.pow(Math.pow(cap(beforeLineCount1 * 40 + beforeSeq1Length), 1.5) + Math.pow(cap(beforeLineCount2 * 40 + beforeSeq2Length), 1.5), 1.5) + Math.pow(Math.pow(cap(afterLineCount1 * 40 + afterSeq1Length), 1.5) + Math.pow(cap(afterLineCount2 * 40 + afterSeq2Length), 1.5), 1.5) > (max ** 1.5) ** 1.5 * 1.3) {
            return true;
          }
          return false;
        };
        const cur = diffs[i2];
        const lastResult = result[result.length - 1];
        const shouldJoin = shouldJoinDiffs(lastResult, cur);
        if (shouldJoin) {
          shouldRepeat = true;
          result[result.length - 1] = result[result.length - 1].join(cur);
        } else {
          result.push(cur);
        }
      }
      diffs = result;
    } while (counter++ < 10 && shouldRepeat);
    const newDiffs = [];
    forEachWithNeighbors(diffs, (prev, cur, next) => {
      let newDiff = cur;
      function shouldMarkAsChanged(text2) {
        return text2.length > 0 && text2.trim().length <= 3 && cur.seq1Range.length + cur.seq2Range.length > 100;
      }
      const fullRange1 = sequence1.extendToFullLines(cur.seq1Range);
      const prefix = sequence1.getText(new OffsetRange(fullRange1.start, cur.seq1Range.start));
      if (shouldMarkAsChanged(prefix)) {
        newDiff = newDiff.deltaStart(-prefix.length);
      }
      const suffix = sequence1.getText(new OffsetRange(cur.seq1Range.endExclusive, fullRange1.endExclusive));
      if (shouldMarkAsChanged(suffix)) {
        newDiff = newDiff.deltaEnd(suffix.length);
      }
      const availableSpace = SequenceDiff.fromOffsetPairs(prev ? prev.getEndExclusives() : OffsetPair.zero, next ? next.getStarts() : OffsetPair.max);
      const result = newDiff.intersect(availableSpace);
      if (newDiffs.length > 0 && result.getStarts().equals(newDiffs[newDiffs.length - 1].getEndExclusives())) {
        newDiffs[newDiffs.length - 1] = newDiffs[newDiffs.length - 1].join(result);
      } else {
        newDiffs.push(result);
      }
    });
    return newDiffs;
  }
  let LineSequence$1 = class LineSequence {
    constructor(trimmedHash, lines) {
      this.trimmedHash = trimmedHash;
      this.lines = lines;
    }
    getElement(offset) {
      return this.trimmedHash[offset];
    }
    get length() {
      return this.trimmedHash.length;
    }
    getBoundaryScore(length) {
      const indentationBefore = length === 0 ? 0 : getIndentation(this.lines[length - 1]);
      const indentationAfter = length === this.lines.length ? 0 : getIndentation(this.lines[length]);
      return 1e3 - (indentationBefore + indentationAfter);
    }
    getText(range2) {
      return this.lines.slice(range2.start, range2.endExclusive).join("\n");
    }
    isStronglyEqual(offset1, offset2) {
      return this.lines[offset1] === this.lines[offset2];
    }
  };
  function getIndentation(str) {
    let i2 = 0;
    while (i2 < str.length && (str.charCodeAt(i2) === 32 || str.charCodeAt(i2) === 9)) {
      i2++;
    }
    return i2;
  }
  class DefaultLinesDiffComputer {
    constructor() {
      this.dynamicProgrammingDiffing = new DynamicProgrammingDiffing();
      this.myersDiffingAlgorithm = new MyersDiffAlgorithm();
    }
    computeDiff(originalLines, modifiedLines, options) {
      if (originalLines.length <= 1 && equals$1(originalLines, modifiedLines, (a, b) => a === b)) {
        return new LinesDiff([], [], false);
      }
      if (originalLines.length === 1 && originalLines[0].length === 0 || modifiedLines.length === 1 && modifiedLines[0].length === 0) {
        return new LinesDiff([
          new DetailedLineRangeMapping(new LineRange(1, originalLines.length + 1), new LineRange(1, modifiedLines.length + 1), [
            new RangeMapping(new Range$2(1, 1, originalLines.length, originalLines[originalLines.length - 1].length + 1), new Range$2(1, 1, modifiedLines.length, modifiedLines[modifiedLines.length - 1].length + 1))
          ])
        ], [], false);
      }
      const timeout2 = options.maxComputationTimeMs === 0 ? InfiniteTimeout.instance : new DateTimeout(options.maxComputationTimeMs);
      const considerWhitespaceChanges = !options.ignoreTrimWhitespace;
      const perfectHashes = /* @__PURE__ */ new Map();
      function getOrCreateHash(text2) {
        let hash2 = perfectHashes.get(text2);
        if (hash2 === void 0) {
          hash2 = perfectHashes.size;
          perfectHashes.set(text2, hash2);
        }
        return hash2;
      }
      const originalLinesHashes = originalLines.map((l) => getOrCreateHash(l.trim()));
      const modifiedLinesHashes = modifiedLines.map((l) => getOrCreateHash(l.trim()));
      const sequence1 = new LineSequence$1(originalLinesHashes, originalLines);
      const sequence2 = new LineSequence$1(modifiedLinesHashes, modifiedLines);
      const lineAlignmentResult = (() => {
        if (sequence1.length + sequence2.length < 1700) {
          return this.dynamicProgrammingDiffing.compute(sequence1, sequence2, timeout2, (offset1, offset2) => originalLines[offset1] === modifiedLines[offset2] ? modifiedLines[offset2].length === 0 ? 0.1 : 1 + Math.log(1 + modifiedLines[offset2].length) : 0.99);
        }
        return this.myersDiffingAlgorithm.compute(sequence1, sequence2, timeout2);
      })();
      let lineAlignments = lineAlignmentResult.diffs;
      let hitTimeout = lineAlignmentResult.hitTimeout;
      lineAlignments = optimizeSequenceDiffs(sequence1, sequence2, lineAlignments);
      lineAlignments = removeVeryShortMatchingLinesBetweenDiffs(sequence1, sequence2, lineAlignments);
      const alignments = [];
      const scanForWhitespaceChanges = (equalLinesCount) => {
        if (!considerWhitespaceChanges) {
          return;
        }
        for (let i2 = 0; i2 < equalLinesCount; i2++) {
          const seq1Offset = seq1LastStart + i2;
          const seq2Offset = seq2LastStart + i2;
          if (originalLines[seq1Offset] !== modifiedLines[seq2Offset]) {
            const characterDiffs = this.refineDiff(originalLines, modifiedLines, new SequenceDiff(new OffsetRange(seq1Offset, seq1Offset + 1), new OffsetRange(seq2Offset, seq2Offset + 1)), timeout2, considerWhitespaceChanges, options);
            for (const a of characterDiffs.mappings) {
              alignments.push(a);
            }
            if (characterDiffs.hitTimeout) {
              hitTimeout = true;
            }
          }
        }
      };
      let seq1LastStart = 0;
      let seq2LastStart = 0;
      for (const diff of lineAlignments) {
        assertFn(() => diff.seq1Range.start - seq1LastStart === diff.seq2Range.start - seq2LastStart);
        const equalLinesCount = diff.seq1Range.start - seq1LastStart;
        scanForWhitespaceChanges(equalLinesCount);
        seq1LastStart = diff.seq1Range.endExclusive;
        seq2LastStart = diff.seq2Range.endExclusive;
        const characterDiffs = this.refineDiff(originalLines, modifiedLines, diff, timeout2, considerWhitespaceChanges, options);
        if (characterDiffs.hitTimeout) {
          hitTimeout = true;
        }
        for (const a of characterDiffs.mappings) {
          alignments.push(a);
        }
      }
      scanForWhitespaceChanges(originalLines.length - seq1LastStart);
      const original = new ArrayText(originalLines);
      const modified = new ArrayText(modifiedLines);
      const changes = lineRangeMappingFromRangeMappings(alignments, original, modified);
      let moves = [];
      if (options.computeMoves) {
        moves = this.computeMoves(changes, originalLines, modifiedLines, originalLinesHashes, modifiedLinesHashes, timeout2, considerWhitespaceChanges, options);
      }
      assertFn(() => {
        function validatePosition(pos, lines) {
          if (pos.lineNumber < 1 || pos.lineNumber > lines.length) {
            return false;
          }
          const line = lines[pos.lineNumber - 1];
          if (pos.column < 1 || pos.column > line.length + 1) {
            return false;
          }
          return true;
        }
        function validateRange(range2, lines) {
          if (range2.startLineNumber < 1 || range2.startLineNumber > lines.length + 1) {
            return false;
          }
          if (range2.endLineNumberExclusive < 1 || range2.endLineNumberExclusive > lines.length + 1) {
            return false;
          }
          return true;
        }
        for (const c of changes) {
          if (!c.innerChanges) {
            return false;
          }
          for (const ic of c.innerChanges) {
            const valid = validatePosition(ic.modifiedRange.getStartPosition(), modifiedLines) && validatePosition(ic.modifiedRange.getEndPosition(), modifiedLines) && validatePosition(ic.originalRange.getStartPosition(), originalLines) && validatePosition(ic.originalRange.getEndPosition(), originalLines);
            if (!valid) {
              return false;
            }
          }
          if (!validateRange(c.modified, modifiedLines) || !validateRange(c.original, originalLines)) {
            return false;
          }
        }
        return true;
      });
      return new LinesDiff(changes, moves, hitTimeout);
    }
    computeMoves(changes, originalLines, modifiedLines, hashedOriginalLines, hashedModifiedLines, timeout2, considerWhitespaceChanges, options) {
      const moves = computeMovedLines(changes, originalLines, modifiedLines, hashedOriginalLines, hashedModifiedLines, timeout2);
      const movesWithDiffs = moves.map((m) => {
        const moveChanges = this.refineDiff(originalLines, modifiedLines, new SequenceDiff(m.original.toOffsetRange(), m.modified.toOffsetRange()), timeout2, considerWhitespaceChanges, options);
        const mappings = lineRangeMappingFromRangeMappings(moveChanges.mappings, new ArrayText(originalLines), new ArrayText(modifiedLines), true);
        return new MovedText(m, mappings);
      });
      return movesWithDiffs;
    }
    refineDiff(originalLines, modifiedLines, diff, timeout2, considerWhitespaceChanges, options) {
      const lineRangeMapping = toLineRangeMapping(diff);
      const rangeMapping = lineRangeMapping.toRangeMapping2(originalLines, modifiedLines);
      const slice1 = new LinesSliceCharSequence(originalLines, rangeMapping.originalRange, considerWhitespaceChanges);
      const slice2 = new LinesSliceCharSequence(modifiedLines, rangeMapping.modifiedRange, considerWhitespaceChanges);
      const diffResult = slice1.length + slice2.length < 500 ? this.dynamicProgrammingDiffing.compute(slice1, slice2, timeout2) : this.myersDiffingAlgorithm.compute(slice1, slice2, timeout2);
      let diffs = diffResult.diffs;
      diffs = optimizeSequenceDiffs(slice1, slice2, diffs);
      diffs = extendDiffsToEntireWordIfAppropriate(slice1, slice2, diffs, (seq, idx) => seq.findWordContaining(idx));
      if (options.extendToSubwords) {
        diffs = extendDiffsToEntireWordIfAppropriate(slice1, slice2, diffs, (seq, idx) => seq.findSubWordContaining(idx), true);
      }
      diffs = removeShortMatches(slice1, slice2, diffs);
      diffs = removeVeryShortMatchingTextBetweenLongDiffs(slice1, slice2, diffs);
      const result = diffs.map((d) => new RangeMapping(slice1.translateRange(d.seq1Range), slice2.translateRange(d.seq2Range)));
      return {
        mappings: result,
        hitTimeout: diffResult.hitTimeout
      };
    }
  }
  function toLineRangeMapping(sequenceDiff) {
    return new LineRangeMapping(new LineRange(sequenceDiff.seq1Range.start + 1, sequenceDiff.seq1Range.endExclusive + 1), new LineRange(sequenceDiff.seq2Range.start + 1, sequenceDiff.seq2Range.endExclusive + 1));
  }
  var __decorate$2F = 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$2C = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  let DiffEditorViewModel = class DiffEditorViewModel extends Disposable {
    setActiveMovedText(movedText) {
      this._activeMovedText.set(movedText, void 0);
    }
    constructor(model, _options, _diffProviderFactoryService) {
      super();
      this.model = model;
      this._options = _options;
      this._diffProviderFactoryService = _diffProviderFactoryService;
      this._isDiffUpToDate = observableValue(this, false);
      this.isDiffUpToDate = this._isDiffUpToDate;
      this._diff = observableValue(this, void 0);
      this.diff = this._diff;
      this._unchangedRegions = observableValue(this, void 0);
      this.unchangedRegions = derived(this, (r) => {
        if (this._options.hideUnchangedRegions.read(r)) {
          return this._unchangedRegions.read(r)?.regions ?? [];
        } else {
          transaction((tx) => {
            for (const r2 of this._unchangedRegions.read(void 0)?.regions || []) {
              r2.collapseAll(tx);
            }
          });
          return [];
        }
      });
      this.movedTextToCompare = observableValue(this, void 0);
      this._activeMovedText = observableValue(this, void 0);
      this._hoveredMovedText = observableValue(this, void 0);
      this.activeMovedText = derived(this, (r) => this.movedTextToCompare.read(r) ?? this._hoveredMovedText.read(r) ?? this._activeMovedText.read(r));
      this._cancellationTokenSource = new CancellationTokenSource$1();
      this._diffProvider = derived(this, (reader) => {
        const diffProvider = this._diffProviderFactoryService.createDiffProvider({
          diffAlgorithm: this._options.diffAlgorithm.read(reader)
        });
        const onChangeSignal = observableSignalFromEvent("onDidChange", diffProvider.onDidChange);
        return {
          diffProvider,
          onChangeSignal
        };
      });
      this._register(toDisposable(() => this._cancellationTokenSource.cancel()));
      const contentChangedSignal = observableSignal("contentChangedSignal");
      const debouncer = this._register(new RunOnceScheduler(() => contentChangedSignal.trigger(void 0), 200));
      this._register(autorun((reader) => {
        const lastUnchangedRegions = this._unchangedRegions.read(reader);
        if (!lastUnchangedRegions || lastUnchangedRegions.regions.some((r) => r.isDragged.read(reader))) {
          return;
        }
        const lastUnchangedRegionsOrigRanges = lastUnchangedRegions.originalDecorationIds.map((id) => model.original.getDecorationRange(id)).map((r) => r ? LineRange.fromRangeInclusive(r) : void 0);
        const lastUnchangedRegionsModRanges = lastUnchangedRegions.modifiedDecorationIds.map((id) => model.modified.getDecorationRange(id)).map((r) => r ? LineRange.fromRangeInclusive(r) : void 0);
        const updatedLastUnchangedRegions = lastUnchangedRegions.regions.map((r, idx) => !lastUnchangedRegionsOrigRanges[idx] || !lastUnchangedRegionsModRanges[idx] ? void 0 : new UnchangedRegion(lastUnchangedRegionsOrigRanges[idx].startLineNumber, lastUnchangedRegionsModRanges[idx].startLineNumber, lastUnchangedRegionsOrigRanges[idx].length, r.visibleLineCountTop.read(reader), r.visibleLineCountBottom.read(reader))).filter(isDefined);
        const newRanges = [];
        let didChange = false;
        for (const touching of groupAdjacentBy(updatedLastUnchangedRegions, (a, b) => a.getHiddenModifiedRange(reader).endLineNumberExclusive === b.getHiddenModifiedRange(reader).startLineNumber)) {
          if (touching.length > 1) {
            didChange = true;
            const sumLineCount = touching.reduce((sum2, r2) => sum2 + r2.lineCount, 0);
            const r = new UnchangedRegion(touching[0].originalLineNumber, touching[0].modifiedLineNumber, sumLineCount, touching[0].visibleLineCountTop.read(void 0), touching[touching.length - 1].visibleLineCountBottom.read(void 0));
            newRanges.push(r);
          } else {
            newRanges.push(touching[0]);
          }
        }
        if (didChange) {
          const originalDecorationIds = model.original.deltaDecorations(lastUnchangedRegions.originalDecorationIds, newRanges.map((r) => ({ range: r.originalUnchangedRange.toInclusiveRange(), options: { description: "unchanged" } })));
          const modifiedDecorationIds = model.modified.deltaDecorations(lastUnchangedRegions.modifiedDecorationIds, newRanges.map((r) => ({ range: r.modifiedUnchangedRange.toInclusiveRange(), options: { description: "unchanged" } })));
          transaction((tx) => {
            this._unchangedRegions.set({
              regions: newRanges,
              originalDecorationIds,
              modifiedDecorationIds
            }, tx);
          });
        }
      }));
      const updateUnchangedRegions = (result, tx, reader) => {
        const newUnchangedRegions = UnchangedRegion.fromDiffs(result.changes, model.original.getLineCount(), model.modified.getLineCount(), this._options.hideUnchangedRegionsMinimumLineCount.read(reader), this._options.hideUnchangedRegionsContextLineCount.read(reader));
        let visibleRegions = void 0;
        const lastUnchangedRegions = this._unchangedRegions.get();
        if (lastUnchangedRegions) {
          const lastUnchangedRegionsOrigRanges = lastUnchangedRegions.originalDecorationIds.map((id) => model.original.getDecorationRange(id)).map((r) => r ? LineRange.fromRangeInclusive(r) : void 0);
          const lastUnchangedRegionsModRanges = lastUnchangedRegions.modifiedDecorationIds.map((id) => model.modified.getDecorationRange(id)).map((r) => r ? LineRange.fromRangeInclusive(r) : void 0);
          const updatedLastUnchangedRegions = filterWithPrevious(lastUnchangedRegions.regions.map((r, idx) => {
            if (!lastUnchangedRegionsOrigRanges[idx] || !lastUnchangedRegionsModRanges[idx]) {
              return void 0;
            }
            const length = lastUnchangedRegionsOrigRanges[idx].length;
            return new UnchangedRegion(
              lastUnchangedRegionsOrigRanges[idx].startLineNumber,
              lastUnchangedRegionsModRanges[idx].startLineNumber,
              length,
              // The visible area can shrink by edits -> we have to account for this
              Math.min(r.visibleLineCountTop.get(), length),
              Math.min(r.visibleLineCountBottom.get(), length - r.visibleLineCountTop.get())
            );
          }).filter(isDefined), (cur, prev) => !prev || cur.modifiedLineNumber >= prev.modifiedLineNumber + prev.lineCount && cur.originalLineNumber >= prev.originalLineNumber + prev.lineCount);
          let hiddenRegions = updatedLastUnchangedRegions.map((r) => new LineRangeMapping(r.getHiddenOriginalRange(reader), r.getHiddenModifiedRange(reader)));
          hiddenRegions = LineRangeMapping.clip(hiddenRegions, LineRange.ofLength(1, model.original.getLineCount()), LineRange.ofLength(1, model.modified.getLineCount()));
          visibleRegions = LineRangeMapping.inverse(hiddenRegions, model.original.getLineCount(), model.modified.getLineCount());
        }
        const newUnchangedRegions2 = [];
        if (visibleRegions) {
          for (const r of newUnchangedRegions) {
            const intersecting = visibleRegions.filter((f) => f.original.intersectsStrict(r.originalUnchangedRange) && f.modified.intersectsStrict(r.modifiedUnchangedRange));
            newUnchangedRegions2.push(...r.setVisibleRanges(intersecting, tx));
          }
        } else {
          newUnchangedRegions2.push(...newUnchangedRegions);
        }
        const originalDecorationIds = model.original.deltaDecorations(lastUnchangedRegions?.originalDecorationIds || [], newUnchangedRegions2.map((r) => ({ range: r.originalUnchangedRange.toInclusiveRange(), options: { description: "unchanged" } })));
        const modifiedDecorationIds = model.modified.deltaDecorations(lastUnchangedRegions?.modifiedDecorationIds || [], newUnchangedRegions2.map((r) => ({ range: r.modifiedUnchangedRange.toInclusiveRange(), options: { description: "unchanged" } })));
        this._unchangedRegions.set({
          regions: newUnchangedRegions2,
          originalDecorationIds,
          modifiedDecorationIds
        }, tx);
      };
      this._register(model.modified.onDidChangeContent((e) => {
        const diff = this._diff.get();
        if (diff) {
          const textEdits = TextEditInfo.fromModelContentChanges(e.changes);
          applyModifiedEdits(this._lastDiff, textEdits, model.original, model.modified);
        }
        this._isDiffUpToDate.set(false, void 0);
        debouncer.schedule();
      }));
      this._register(model.original.onDidChangeContent((e) => {
        const diff = this._diff.get();
        if (diff) {
          const textEdits = TextEditInfo.fromModelContentChanges(e.changes);
          applyOriginalEdits(this._lastDiff, textEdits, model.original, model.modified);
        }
        this._isDiffUpToDate.set(false, void 0);
        debouncer.schedule();
      }));
      this._register(autorunWithStore(async (reader, store) => {
        this._options.hideUnchangedRegionsMinimumLineCount.read(reader);
        this._options.hideUnchangedRegionsContextLineCount.read(reader);
        debouncer.cancel();
        contentChangedSignal.read(reader);
        const documentDiffProvider = this._diffProvider.read(reader);
        documentDiffProvider.onChangeSignal.read(reader);
        this._isDiffUpToDate.set(false, void 0);
        let originalTextEditInfos = [];
        store.add(model.original.onDidChangeContent((e) => {
          const edits = TextEditInfo.fromModelContentChanges(e.changes);
          originalTextEditInfos = combineTextEditInfos(originalTextEditInfos, edits);
        }));
        let modifiedTextEditInfos = [];
        store.add(model.modified.onDidChangeContent((e) => {
          const edits = TextEditInfo.fromModelContentChanges(e.changes);
          modifiedTextEditInfos = combineTextEditInfos(modifiedTextEditInfos, edits);
        }));
        let result = await documentDiffProvider.diffProvider.computeDiff(model.original, model.modified, {
          ignoreTrimWhitespace: this._options.ignoreTrimWhitespace.read(reader),
          maxComputationTimeMs: this._options.maxComputationTimeMs.read(reader),
          computeMoves: this._options.showMoves.read(reader)
        }, this._cancellationTokenSource.token);
        if (this._cancellationTokenSource.token.isCancellationRequested) {
          return;
        }
        if (model.original.isDisposed() || model.modified.isDisposed()) {
          return;
        }
        result = normalizeDocumentDiff(result, model.original, model.modified);
        result = applyOriginalEdits(result, originalTextEditInfos, model.original, model.modified) ?? result;
        result = applyModifiedEdits(result, modifiedTextEditInfos, model.original, model.modified) ?? result;
        transaction((tx) => {
          updateUnchangedRegions(result, tx);
          this._lastDiff = result;
          const state = DiffState.fromDiffResult(result);
          this._diff.set(state, tx);
          this._isDiffUpToDate.set(true, tx);
          const currentSyncedMovedText = this.movedTextToCompare.read(void 0);
          this.movedTextToCompare.set(currentSyncedMovedText ? this._lastDiff.moves.find((m) => m.lineRangeMapping.modified.intersect(currentSyncedMovedText.lineRangeMapping.modified)) : void 0, tx);
        });
      }));
    }
    ensureModifiedLineIsVisible(lineNumber, preference, tx) {
      if (this.diff.get()?.mappings.length === 0) {
        return;
      }
      const unchangedRegions = this._unchangedRegions.get()?.regions || [];
      for (const r of unchangedRegions) {
        if (r.getHiddenModifiedRange(void 0).contains(lineNumber)) {
          r.showModifiedLine(lineNumber, preference, tx);
          return;
        }
      }
    }
    ensureOriginalLineIsVisible(lineNumber, preference, tx) {
      if (this.diff.get()?.mappings.length === 0) {
        return;
      }
      const unchangedRegions = this._unchangedRegions.get()?.regions || [];
      for (const r of unchangedRegions) {
        if (r.getHiddenOriginalRange(void 0).contains(lineNumber)) {
          r.showOriginalLine(lineNumber, preference, tx);
          return;
        }
      }
    }
    async waitForDiff() {
      await waitForState(this.isDiffUpToDate, (s) => s);
    }
    serializeState() {
      const regions = this._unchangedRegions.get();
      return {
        collapsedRegions: regions?.regions.map((r) => ({ range: r.getHiddenModifiedRange(void 0).serialize() }))
      };
    }
    restoreSerializedState(state) {
      const ranges = state.collapsedRegions?.map((r) => LineRange.deserialize(r.range));
      const regions = this._unchangedRegions.get();
      if (!regions || !ranges) {
        return;
      }
      transaction((tx) => {
        for (const r of regions.regions) {
          for (const range2 of ranges) {
            if (r.modifiedUnchangedRange.intersect(range2)) {
              r.setHiddenModifiedRange(range2, tx);
              break;
            }
          }
        }
      });
    }
  };
  DiffEditorViewModel = __decorate$2F([
    __param$2C(2, IDiffProviderFactoryService)
  ], DiffEditorViewModel);
  function normalizeDocumentDiff(diff, original, modified) {
    return {
      changes: diff.changes.map((c) => new DetailedLineRangeMapping(c.original, c.modified, c.innerChanges ? c.innerChanges.map((i2) => normalizeRangeMapping(i2, original, modified)) : void 0)),
      moves: diff.moves,
      identical: diff.identical,
      quitEarly: diff.quitEarly
    };
  }
  function normalizeRangeMapping(rangeMapping, original, modified) {
    let originalRange = rangeMapping.originalRange;
    let modifiedRange = rangeMapping.modifiedRange;
    if (originalRange.startColumn === 1 && modifiedRange.startColumn === 1 && (originalRange.endColumn !== 1 || modifiedRange.endColumn !== 1) && originalRange.endColumn === original.getLineMaxColumn(originalRange.endLineNumber) && modifiedRange.endColumn === modified.getLineMaxColumn(modifiedRange.endLineNumber) && originalRange.endLineNumber < original.getLineCount() && modifiedRange.endLineNumber < modified.getLineCount()) {
      originalRange = originalRange.setEndPosition(originalRange.endLineNumber + 1, 1);
      modifiedRange = modifiedRange.setEndPosition(modifiedRange.endLineNumber + 1, 1);
    }
    return new RangeMapping(originalRange, modifiedRange);
  }
  class DiffState {
    static fromDiffResult(result) {
      return new DiffState(result.changes.map((c) => new DiffMapping(c)), result.moves || [], result.identical, result.quitEarly);
    }
    constructor(mappings, movedTexts, identical, quitEarly) {
      this.mappings = mappings;
      this.movedTexts = movedTexts;
      this.identical = identical;
      this.quitEarly = quitEarly;
    }
  }
  class DiffMapping {
    constructor(lineRangeMapping) {
      this.lineRangeMapping = lineRangeMapping;
    }
  }
  class UnchangedRegion {
    static fromDiffs(changes, originalLineCount, modifiedLineCount, minHiddenLineCount, minContext) {
      const inversedMappings = DetailedLineRangeMapping.inverse(changes, originalLineCount, modifiedLineCount);
      const result = [];
      for (const mapping of inversedMappings) {
        let origStart = mapping.original.startLineNumber;
        let modStart = mapping.modified.startLineNumber;
        let length = mapping.original.length;
        const atStart = origStart === 1 && modStart === 1;
        const atEnd = origStart + length === originalLineCount + 1 && modStart + length === modifiedLineCount + 1;
        if ((atStart || atEnd) && length >= minContext + minHiddenLineCount) {
          if (atStart && !atEnd) {
            length -= minContext;
          }
          if (atEnd && !atStart) {
            origStart += minContext;
            modStart += minContext;
            length -= minContext;
          }
          result.push(new UnchangedRegion(origStart, modStart, length, 0, 0));
        } else if (length >= minContext * 2 + minHiddenLineCount) {
          origStart += minContext;
          modStart += minContext;
          length -= minContext * 2;
          result.push(new UnchangedRegion(origStart, modStart, length, 0, 0));
        }
      }
      return result;
    }
    get originalUnchangedRange() {
      return LineRange.ofLength(this.originalLineNumber, this.lineCount);
    }
    get modifiedUnchangedRange() {
      return LineRange.ofLength(this.modifiedLineNumber, this.lineCount);
    }
    constructor(originalLineNumber, modifiedLineNumber, lineCount, visibleLineCountTop, visibleLineCountBottom) {
      this.originalLineNumber = originalLineNumber;
      this.modifiedLineNumber = modifiedLineNumber;
      this.lineCount = lineCount;
      this._visibleLineCountTop = observableValue(this, 0);
      this.visibleLineCountTop = this._visibleLineCountTop;
      this._visibleLineCountBottom = observableValue(this, 0);
      this.visibleLineCountBottom = this._visibleLineCountBottom;
      this._shouldHideControls = derived(this, (reader) => (
        /** @description isVisible */
        this.visibleLineCountTop.read(reader) + this.visibleLineCountBottom.read(reader) === this.lineCount && !this.isDragged.read(reader)
      ));
      this.isDragged = observableValue(this, void 0);
      const visibleLineCountTop2 = Math.max(Math.min(visibleLineCountTop, this.lineCount), 0);
      const visibleLineCountBottom2 = Math.max(Math.min(visibleLineCountBottom, this.lineCount - visibleLineCountTop), 0);
      softAssert(visibleLineCountTop === visibleLineCountTop2);
      softAssert(visibleLineCountBottom === visibleLineCountBottom2);
      this._visibleLineCountTop.set(visibleLineCountTop2, void 0);
      this._visibleLineCountBottom.set(visibleLineCountBottom2, void 0);
    }
    setVisibleRanges(visibleRanges, tx) {
      const result = [];
      const hiddenModified = new LineRangeSet(visibleRanges.map((r) => r.modified)).subtractFrom(this.modifiedUnchangedRange);
      let originalStartLineNumber = this.originalLineNumber;
      let modifiedStartLineNumber = this.modifiedLineNumber;
      const modifiedEndLineNumberEx = this.modifiedLineNumber + this.lineCount;
      if (hiddenModified.ranges.length === 0) {
        this.showAll(tx);
        result.push(this);
      } else {
        let i2 = 0;
        for (const r of hiddenModified.ranges) {
          const isLast = i2 === hiddenModified.ranges.length - 1;
          i2++;
          const length = (isLast ? modifiedEndLineNumberEx : r.endLineNumberExclusive) - modifiedStartLineNumber;
          const newR = new UnchangedRegion(originalStartLineNumber, modifiedStartLineNumber, length, 0, 0);
          newR.setHiddenModifiedRange(r, tx);
          result.push(newR);
          originalStartLineNumber = newR.originalUnchangedRange.endLineNumberExclusive;
          modifiedStartLineNumber = newR.modifiedUnchangedRange.endLineNumberExclusive;
        }
      }
      return result;
    }
    shouldHideControls(reader) {
      return this._shouldHideControls.read(reader);
    }
    getHiddenOriginalRange(reader) {
      return LineRange.ofLength(this.originalLineNumber + this._visibleLineCountTop.read(reader), this.lineCount - this._visibleLineCountTop.read(reader) - this._visibleLineCountBottom.read(reader));
    }
    getHiddenModifiedRange(reader) {
      return LineRange.ofLength(this.modifiedLineNumber + this._visibleLineCountTop.read(reader), this.lineCount - this._visibleLineCountTop.read(reader) - this._visibleLineCountBottom.read(reader));
    }
    setHiddenModifiedRange(range2, tx) {
      const visibleLineCountTop = range2.startLineNumber - this.modifiedLineNumber;
      const visibleLineCountBottom = this.modifiedLineNumber + this.lineCount - range2.endLineNumberExclusive;
      this.setState(visibleLineCountTop, visibleLineCountBottom, tx);
    }
    getMaxVisibleLineCountTop() {
      return this.lineCount - this._visibleLineCountBottom.get();
    }
    getMaxVisibleLineCountBottom() {
      return this.lineCount - this._visibleLineCountTop.get();
    }
    showMoreAbove(count = 10, tx) {
      const maxVisibleLineCountTop = this.getMaxVisibleLineCountTop();
      this._visibleLineCountTop.set(Math.min(this._visibleLineCountTop.get() + count, maxVisibleLineCountTop), tx);
    }
    showMoreBelow(count = 10, tx) {
      const maxVisibleLineCountBottom = this.lineCount - this._visibleLineCountTop.get();
      this._visibleLineCountBottom.set(Math.min(this._visibleLineCountBottom.get() + count, maxVisibleLineCountBottom), tx);
    }
    showAll(tx) {
      this._visibleLineCountBottom.set(this.lineCount - this._visibleLineCountTop.get(), tx);
    }
    showModifiedLine(lineNumber, preference, tx) {
      const top = lineNumber + 1 - (this.modifiedLineNumber + this._visibleLineCountTop.get());
      const bottom = this.modifiedLineNumber - this._visibleLineCountBottom.get() + this.lineCount - lineNumber;
      if (preference === 0 && top < bottom || preference === 1) {
        this._visibleLineCountTop.set(this._visibleLineCountTop.get() + top, tx);
      } else {
        this._visibleLineCountBottom.set(this._visibleLineCountBottom.get() + bottom, tx);
      }
    }
    showOriginalLine(lineNumber, preference, tx) {
      const top = lineNumber - this.originalLineNumber;
      const bottom = this.originalLineNumber + this.lineCount - lineNumber;
      if (preference === 0 && top < bottom || preference === 1) {
        this._visibleLineCountTop.set(Math.min(this._visibleLineCountTop.get() + bottom - top, this.getMaxVisibleLineCountTop()), tx);
      } else {
        this._visibleLineCountBottom.set(Math.min(this._visibleLineCountBottom.get() + top - bottom, this.getMaxVisibleLineCountBottom()), tx);
      }
    }
    collapseAll(tx) {
      this._visibleLineCountTop.set(0, tx);
      this._visibleLineCountBottom.set(0, tx);
    }
    setState(visibleLineCountTop, visibleLineCountBottom, tx) {
      visibleLineCountTop = Math.max(Math.min(visibleLineCountTop, this.lineCount), 0);
      visibleLineCountBottom = Math.max(Math.min(visibleLineCountBottom, this.lineCount - visibleLineCountTop), 0);
      this._visibleLineCountTop.set(visibleLineCountTop, tx);
      this._visibleLineCountBottom.set(visibleLineCountBottom, tx);
    }
  }
  function applyOriginalEdits(diff, textEdits, originalTextModel, modifiedTextModel) {
    return void 0;
  }
  function applyModifiedEdits(diff, textEdits, originalTextModel, modifiedTextModel) {
    return void 0;
  }
  function enableCopySelection(options) {
    const { domNode, renderLinesResult, diffEntry, originalModel, clipboardService } = options;
    const viewZoneDisposable = new DisposableStore();
    viewZoneDisposable.add(addDisposableListener(domNode, "copy", (e) => {
      e.preventDefault();
      const selection = domNode.ownerDocument.getSelection();
      if (!selection || selection.rangeCount === 0) {
        return;
      }
      const domRange = selection.getRangeAt(0);
      if (!domRange || domRange.collapsed) {
        return;
      }
      const startElement = domRange.startContainer.nodeType === Node.TEXT_NODE ? domRange.startContainer.parentElement : domRange.startContainer;
      const endElement = domRange.endContainer.nodeType === Node.TEXT_NODE ? domRange.endContainer.parentElement : domRange.endContainer;
      if (!startElement || !endElement) {
        return;
      }
      const startPosition = renderLinesResult.getModelPositionAt(startElement, domRange.startOffset);
      const endPosition = renderLinesResult.getModelPositionAt(endElement, domRange.endOffset);
      if (!startPosition || !endPosition) {
        return;
      }
      const adjustedStart = startPosition.delta(diffEntry.original.startLineNumber - 1);
      const adjustedEnd = endPosition.delta(diffEntry.original.startLineNumber - 1);
      const range2 = adjustedEnd.isBefore(adjustedStart) ? Range$2.fromPositions(adjustedEnd, adjustedStart) : Range$2.fromPositions(adjustedStart, adjustedEnd);
      const selectedText = originalModel.getValueInRange(range2);
      clipboardService.writeText(selectedText);
    }));
    return viewZoneDisposable;
  }
  class InlineDiffDeletedCodeMargin extends Disposable {
    get visibility() {
      return this._visibility;
    }
    set visibility(_visibility) {
      if (this._visibility !== _visibility) {
        this._visibility = _visibility;
        this._diffActions.style.visibility = _visibility ? "visible" : "hidden";
      }
    }
    constructor(_getViewZoneId, _marginDomNode, _deletedCodeDomNode, _modifiedEditor, _diff, _editor, _renderLinesResult, _originalTextModel, _contextMenuService, _clipboardService) {
      super();
      this._getViewZoneId = _getViewZoneId;
      this._marginDomNode = _marginDomNode;
      this._deletedCodeDomNode = _deletedCodeDomNode;
      this._modifiedEditor = _modifiedEditor;
      this._diff = _diff;
      this._editor = _editor;
      this._renderLinesResult = _renderLinesResult;
      this._originalTextModel = _originalTextModel;
      this._contextMenuService = _contextMenuService;
      this._clipboardService = _clipboardService;
      this._visibility = false;
      this._marginDomNode.style.zIndex = "10";
      this._diffActions = document.createElement("div");
      this._diffActions.className = ThemeIcon.asClassName(Codicon.lightBulb) + " lightbulb-glyph";
      this._diffActions.style.position = "absolute";
      const lineHeight = this._modifiedEditor.getOption(
        75
        /* EditorOption.lineHeight */
      );
      this._diffActions.style.right = "0px";
      this._diffActions.style.visibility = "hidden";
      this._diffActions.style.height = `${lineHeight}px`;
      this._diffActions.style.lineHeight = `${lineHeight}px`;
      this._marginDomNode.appendChild(this._diffActions);
      let currentLineNumberOffset = 0;
      const useShadowDOM = _modifiedEditor.getOption(
        144
        /* EditorOption.useShadowDOM */
      ) && !isIOS;
      const showContextMenu = (anchor, baseActions, onHide) => {
        this._contextMenuService.showContextMenu({
          domForShadowRoot: useShadowDOM ? _modifiedEditor.getDomNode() ?? void 0 : void 0,
          getAnchor: () => anchor,
          onHide,
          getActions: () => {
            const actions = [];
            const isDeletion2 = _diff.modified.isEmpty;
            actions.push(new Action("diff.clipboard.copyDeletedContent", isDeletion2 ? _diff.original.length > 1 ? localize(112, "Copy deleted lines") : localize(113, "Copy deleted line") : _diff.original.length > 1 ? localize(114, "Copy changed lines") : localize(115, "Copy changed line"), void 0, true, async () => {
              const originalText = this._originalTextModel.getValueInRange(_diff.original.toExclusiveRange());
              await this._clipboardService.writeText(originalText);
            }));
            if (_diff.original.length > 1) {
              actions.push(new Action("diff.clipboard.copyDeletedLineContent", isDeletion2 ? localize(116, "Copy deleted line ({0})", _diff.original.startLineNumber + currentLineNumberOffset) : localize(117, "Copy changed line ({0})", _diff.original.startLineNumber + currentLineNumberOffset), void 0, true, async () => {
                let lineContent = this._originalTextModel.getLineContent(_diff.original.startLineNumber + currentLineNumberOffset);
                if (lineContent === "") {
                  const eof = this._originalTextModel.getEndOfLineSequence();
                  lineContent = eof === 0 ? "\n" : "\r\n";
                }
                await this._clipboardService.writeText(lineContent);
              }));
            }
            const readOnly = _modifiedEditor.getOption(
              104
              /* EditorOption.readOnly */
            );
            if (!readOnly) {
              actions.push(new Action("diff.inline.revertChange", localize(118, "Revert this change"), void 0, true, async () => {
                this._editor.revert(this._diff);
              }));
            }
            return actions;
          },
          autoSelectFirstItem: true
        });
      };
      this._register(addStandardDisposableListener(this._diffActions, "mousedown", (e) => {
        if (!e.leftButton) {
          return;
        }
        const { top, height } = getDomNodePagePosition(this._diffActions);
        const pad = Math.floor(lineHeight / 3);
        e.preventDefault();
        showContextMenu({ x: e.posx, y: top + height + pad });
      }));
      this._register(_modifiedEditor.onMouseMove((e) => {
        if ((e.target.type === 8 || e.target.type === 5) && e.target.detail.viewZoneId === this._getViewZoneId()) {
          currentLineNumberOffset = this._updateLightBulbPosition(this._marginDomNode, e.event.browserEvent.y, lineHeight);
          this.visibility = true;
        } else {
          this.visibility = false;
        }
      }));
      this._register(enableCopySelection({
        domNode: this._deletedCodeDomNode,
        diffEntry: _diff,
        originalModel: this._originalTextModel,
        renderLinesResult: this._renderLinesResult,
        clipboardService: _clipboardService
      }));
    }
    _updateLightBulbPosition(marginDomNode, y, lineHeight) {
      const { top } = getDomNodePagePosition(marginDomNode);
      const offset = y - top;
      const lineNumberOffset = Math.floor(offset / lineHeight);
      const newTop = lineNumberOffset * lineHeight;
      this._diffActions.style.top = `${newTop}px`;
      if (this._renderLinesResult.viewLineCounts) {
        let acc = 0;
        for (let i2 = 0; i2 < this._renderLinesResult.viewLineCounts.length; i2++) {
          acc += this._renderLinesResult.viewLineCounts[i2];
          if (lineNumberOffset < acc) {
            return i2;
          }
        }
      }
      return lineNumberOffset;
    }
  }
  const ttPolicy$3 = createTrustedTypesPolicy("diffEditorWidget", { createHTML: (value) => value });
  function renderLines$1(source, options, decorations, domNode, noExtra = false) {
    applyFontInfo(domNode, options.fontInfo);
    const hasCharChanges = decorations.length > 0;
    const sb = new StringBuilder(1e4);
    let maxCharsPerLine = 0;
    let renderedLineCount = 0;
    const viewLineCounts = [];
    const renderOutputs = [];
    for (let lineIndex = 0; lineIndex < source.lineTokens.length; lineIndex++) {
      const lineNumber = lineIndex + 1;
      const lineTokens = source.lineTokens[lineIndex];
      const lineBreakData = source.lineBreakData[lineIndex];
      const actualDecorations = LineDecoration.filter(decorations, lineNumber, 1, Number.MAX_SAFE_INTEGER);
      if (lineBreakData) {
        let lastBreakOffset = 0;
        for (const breakOffset of lineBreakData.breakOffsets) {
          const viewLineTokens = lineTokens.sliceAndInflate(lastBreakOffset, breakOffset, 0);
          const result = renderOriginalLine(renderedLineCount, viewLineTokens, LineDecoration.extractWrapped(actualDecorations, lastBreakOffset, breakOffset), hasCharChanges, source.mightContainNonBasicASCII, source.mightContainRTL, options, sb, noExtra);
          maxCharsPerLine = Math.max(maxCharsPerLine, result.maxCharWidth);
          renderOutputs.push(new RenderLineOutputWithOffset(result.output.characterMapping, result.output.containsForeignElements, lastBreakOffset));
          renderedLineCount++;
          lastBreakOffset = breakOffset;
        }
        viewLineCounts.push(lineBreakData.breakOffsets.length);
      } else {
        viewLineCounts.push(1);
        const result = renderOriginalLine(renderedLineCount, lineTokens, actualDecorations, hasCharChanges, source.mightContainNonBasicASCII, source.mightContainRTL, options, sb, noExtra);
        maxCharsPerLine = Math.max(maxCharsPerLine, result.maxCharWidth);
        renderOutputs.push(new RenderLineOutputWithOffset(result.output.characterMapping, result.output.containsForeignElements, 0));
        renderedLineCount++;
      }
    }
    maxCharsPerLine += options.scrollBeyondLastColumn;
    const html2 = sb.build();
    const trustedhtml = ttPolicy$3 ? ttPolicy$3.createHTML(html2) : html2;
    domNode.innerHTML = trustedhtml;
    const minWidthInPx = maxCharsPerLine * options.typicalHalfwidthCharacterWidth;
    return new RenderLinesResult(renderedLineCount, minWidthInPx, viewLineCounts, renderOutputs, source);
  }
  class LineSource {
    constructor(lineTokens, lineBreakData = lineTokens.map((t) => null), mightContainNonBasicASCII = true, mightContainRTL = true) {
      this.lineTokens = lineTokens;
      this.lineBreakData = lineBreakData;
      this.mightContainNonBasicASCII = mightContainNonBasicASCII;
      this.mightContainRTL = mightContainRTL;
    }
  }
  class RenderOptions {
    static fromEditor(editor2) {
      const modifiedEditorOptions = editor2.getOptions();
      const fontInfo = modifiedEditorOptions.get(
        59
        /* EditorOption.fontInfo */
      );
      const layoutInfo = modifiedEditorOptions.get(
        165
        /* EditorOption.layoutInfo */
      );
      return new RenderOptions(editor2.getModel()?.getOptions().tabSize || 0, fontInfo, modifiedEditorOptions.get(
        40
        /* EditorOption.disableMonospaceOptimizations */
      ), fontInfo.typicalHalfwidthCharacterWidth, modifiedEditorOptions.get(
        118
        /* EditorOption.scrollBeyondLastColumn */
      ), modifiedEditorOptions.get(
        75
        /* EditorOption.lineHeight */
      ), layoutInfo.decorationsWidth, modifiedEditorOptions.get(
        133
        /* EditorOption.stopRenderingLineAfter */
      ), modifiedEditorOptions.get(
        113
        /* EditorOption.renderWhitespace */
      ), modifiedEditorOptions.get(
        108
        /* EditorOption.renderControlCharacters */
      ), modifiedEditorOptions.get(
        60
        /* EditorOption.fontLigatures */
      ), modifiedEditorOptions.get(
        117
        /* EditorOption.scrollbar */
      ).verticalScrollbarSize);
    }
    constructor(tabSize, fontInfo, disableMonospaceOptimizations, typicalHalfwidthCharacterWidth, scrollBeyondLastColumn, lineHeight, lineDecorationsWidth, stopRenderingLineAfter, renderWhitespace, renderControlCharacters, fontLigatures, verticalScrollbarSize, setWidth = true) {
      this.tabSize = tabSize;
      this.fontInfo = fontInfo;
      this.disableMonospaceOptimizations = disableMonospaceOptimizations;
      this.typicalHalfwidthCharacterWidth = typicalHalfwidthCharacterWidth;
      this.scrollBeyondLastColumn = scrollBeyondLastColumn;
      this.lineHeight = lineHeight;
      this.lineDecorationsWidth = lineDecorationsWidth;
      this.stopRenderingLineAfter = stopRenderingLineAfter;
      this.renderWhitespace = renderWhitespace;
      this.renderControlCharacters = renderControlCharacters;
      this.fontLigatures = fontLigatures;
      this.verticalScrollbarSize = verticalScrollbarSize;
      this.setWidth = setWidth;
    }
    withSetWidth(setWidth) {
      return new RenderOptions(this.tabSize, this.fontInfo, this.disableMonospaceOptimizations, this.typicalHalfwidthCharacterWidth, this.scrollBeyondLastColumn, this.lineHeight, this.lineDecorationsWidth, this.stopRenderingLineAfter, this.renderWhitespace, this.renderControlCharacters, this.fontLigatures, this.verticalScrollbarSize, setWidth);
    }
    withScrollBeyondLastColumn(scrollBeyondLastColumn) {
      return new RenderOptions(this.tabSize, this.fontInfo, this.disableMonospaceOptimizations, this.typicalHalfwidthCharacterWidth, scrollBeyondLastColumn, this.lineHeight, this.lineDecorationsWidth, this.stopRenderingLineAfter, this.renderWhitespace, this.renderControlCharacters, this.fontLigatures, this.verticalScrollbarSize, this.setWidth);
    }
  }
  class RenderLinesResult {
    constructor(heightInLines, minWidthInPx, viewLineCounts, _renderOutputs, _source) {
      this.heightInLines = heightInLines;
      this.minWidthInPx = minWidthInPx;
      this.viewLineCounts = viewLineCounts;
      this._renderOutputs = _renderOutputs;
      this._source = _source;
    }
    /**
     * Returns the model position for a given DOM node and offset within that node.
     * @param domNode The span node within a view-line where the offset is located
     * @param offset The offset within the span node
     * @returns The Position in the model, or undefined if the position cannot be determined
     */
    getModelPositionAt(domNode, offset) {
      let viewLineElement = domNode;
      while (viewLineElement && !viewLineElement.classList.contains("view-line")) {
        viewLineElement = viewLineElement.parentElement;
      }
      if (!viewLineElement) {
        return void 0;
      }
      const container = viewLineElement.parentElement;
      if (!container) {
        return void 0;
      }
      const viewLines = container.querySelectorAll(".view-line");
      let viewLineIndex = -1;
      for (let i2 = 0; i2 < viewLines.length; i2++) {
        if (viewLines[i2] === viewLineElement) {
          viewLineIndex = i2;
          break;
        }
      }
      if (viewLineIndex === -1 || viewLineIndex >= this._renderOutputs.length) {
        return void 0;
      }
      let modelLineNumber = 1;
      let remainingViewLines = viewLineIndex;
      for (let i2 = 0; i2 < this.viewLineCounts.length; i2++) {
        if (remainingViewLines < this.viewLineCounts[i2]) {
          modelLineNumber = i2 + 1;
          break;
        }
        remainingViewLines -= this.viewLineCounts[i2];
      }
      if (modelLineNumber > this._source.lineTokens.length) {
        return void 0;
      }
      const renderOutput = this._renderOutputs[viewLineIndex];
      if (!renderOutput) {
        return void 0;
      }
      const column = getColumnOfNodeOffset(renderOutput.characterMapping, domNode, offset) + renderOutput.offset;
      return new Position$1(modelLineNumber, column);
    }
  }
  class RenderLineOutputWithOffset extends RenderLineOutput {
    constructor(characterMapping, containsForeignElements, offset) {
      super(characterMapping, containsForeignElements);
      this.offset = offset;
    }
  }
  function renderOriginalLine(viewLineIdx, lineTokens, decorations, hasCharChanges, mightContainNonBasicASCII, mightContainRTL, options, sb, noExtra) {
    sb.appendString('<div class="view-line');
    if (!noExtra && !hasCharChanges) {
      sb.appendString(" char-delete");
    }
    sb.appendString('" style="top:');
    sb.appendString(String(viewLineIdx * options.lineHeight));
    if (options.setWidth) {
      sb.appendString('px;width:1000000px;">');
    } else {
      sb.appendString('px;">');
    }
    const lineContent = lineTokens.getLineContent();
    const isBasicASCII2 = ViewLineRenderingData.isBasicASCII(lineContent, mightContainNonBasicASCII);
    const containsRTL2 = ViewLineRenderingData.containsRTL(lineContent, isBasicASCII2, mightContainRTL);
    const output = renderViewLine(new RenderLineInput(
      options.fontInfo.isMonospace && !options.disableMonospaceOptimizations,
      options.fontInfo.canUseHalfwidthRightwardsArrow,
      lineContent,
      false,
      isBasicASCII2,
      containsRTL2,
      0,
      lineTokens,
      decorations,
      options.tabSize,
      0,
      options.fontInfo.spaceWidth,
      options.fontInfo.middotWidth,
      options.fontInfo.wsmiddotWidth,
      options.stopRenderingLineAfter,
      options.renderWhitespace,
      options.renderControlCharacters,
      options.fontLigatures !== EditorFontLigatures.OFF,
      null,
      // Send no selections, original line cannot be selected
      null,
      options.verticalScrollbarSize
    ), sb);
    sb.appendString("</div>");
    const maxCharWidth = output.characterMapping.getHorizontalOffset(output.characterMapping.length);
    return { output, maxCharWidth };
  }
  const IClipboardService = createDecorator("clipboardService");
  const IContextViewService = createDecorator("contextViewService");
  const IContextMenuService = createDecorator("contextMenuService");
  var __decorate$2E = 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$2B = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  let DiffEditorViewZones = class DiffEditorViewZones extends Disposable {
    constructor(_targetWindow, _editors, _diffModel, _options, _diffEditorWidget, _canIgnoreViewZoneUpdateEvent, _origViewZonesToIgnore, _modViewZonesToIgnore, _clipboardService, _contextMenuService) {
      super();
      this._targetWindow = _targetWindow;
      this._editors = _editors;
      this._diffModel = _diffModel;
      this._options = _options;
      this._diffEditorWidget = _diffEditorWidget;
      this._canIgnoreViewZoneUpdateEvent = _canIgnoreViewZoneUpdateEvent;
      this._origViewZonesToIgnore = _origViewZonesToIgnore;
      this._modViewZonesToIgnore = _modViewZonesToIgnore;
      this._clipboardService = _clipboardService;
      this._contextMenuService = _contextMenuService;
      this._originalTopPadding = observableValue(this, 0);
      this._originalScrollOffset = observableValue(this, 0);
      this._originalScrollOffsetAnimated = animatedObservable(this._targetWindow, this._originalScrollOffset, this._store);
      this._modifiedTopPadding = observableValue(this, 0);
      this._modifiedScrollOffset = observableValue(this, 0);
      this._modifiedScrollOffsetAnimated = animatedObservable(this._targetWindow, this._modifiedScrollOffset, this._store);
      const state = observableValue("invalidateAlignmentsState", 0);
      const updateImmediately = this._register(new RunOnceScheduler(() => {
        state.set(state.get() + 1, void 0);
      }, 0));
      this._register(this._editors.original.onDidChangeViewZones((_args) => {
        if (!this._canIgnoreViewZoneUpdateEvent()) {
          updateImmediately.schedule();
        }
      }));
      this._register(this._editors.modified.onDidChangeViewZones((_args) => {
        if (!this._canIgnoreViewZoneUpdateEvent()) {
          updateImmediately.schedule();
        }
      }));
      this._register(this._editors.original.onDidChangeConfiguration((args) => {
        if (args.hasChanged(
          166
          /* EditorOption.wrappingInfo */
        ) || args.hasChanged(
          75
          /* EditorOption.lineHeight */
        )) {
          updateImmediately.schedule();
        }
      }));
      this._register(this._editors.modified.onDidChangeConfiguration((args) => {
        if (args.hasChanged(
          166
          /* EditorOption.wrappingInfo */
        ) || args.hasChanged(
          75
          /* EditorOption.lineHeight */
        )) {
          updateImmediately.schedule();
        }
      }));
      const originalModelTokenizationCompleted = this._diffModel.map((m) => m ? observableFromEvent(
        this,
        m.model.original.onDidChangeTokens,
        () => m.model.original.tokenization.backgroundTokenizationState === 2
        /* BackgroundTokenizationState.Completed */
      ) : void 0).map((m, reader) => m?.read(reader));
      const alignments = derived((reader) => {
        const diffModel = this._diffModel.read(reader);
        const diff = diffModel?.diff.read(reader);
        if (!diffModel || !diff) {
          return null;
        }
        state.read(reader);
        const renderSideBySide = this._options.renderSideBySide.read(reader);
        const innerHunkAlignment = renderSideBySide;
        return computeRangeAlignment(this._editors.original, this._editors.modified, diff.mappings, this._origViewZonesToIgnore, this._modViewZonesToIgnore, innerHunkAlignment);
      });
      const alignmentsSyncedMovedText = derived((reader) => {
        const syncedMovedText = this._diffModel.read(reader)?.movedTextToCompare.read(reader);
        if (!syncedMovedText) {
          return null;
        }
        state.read(reader);
        const mappings = syncedMovedText.changes.map((c) => new DiffMapping(c));
        return computeRangeAlignment(this._editors.original, this._editors.modified, mappings, this._origViewZonesToIgnore, this._modViewZonesToIgnore, true);
      });
      function createFakeLinesDiv() {
        const r = document.createElement("div");
        r.className = "diagonal-fill";
        return r;
      }
      const alignmentViewZonesDisposables = this._register(new DisposableStore());
      this.viewZones = derived(this, (reader) => {
        alignmentViewZonesDisposables.clear();
        const alignmentsVal = alignments.read(reader) || [];
        const origViewZones = [];
        const modViewZones = [];
        const modifiedTopPaddingVal = this._modifiedTopPadding.read(reader);
        if (modifiedTopPaddingVal > 0) {
          modViewZones.push({
            afterLineNumber: 0,
            domNode: document.createElement("div"),
            heightInPx: modifiedTopPaddingVal,
            showInHiddenAreas: true,
            suppressMouseDown: true
          });
        }
        const originalTopPaddingVal = this._originalTopPadding.read(reader);
        if (originalTopPaddingVal > 0) {
          origViewZones.push({
            afterLineNumber: 0,
            domNode: document.createElement("div"),
            heightInPx: originalTopPaddingVal,
            showInHiddenAreas: true,
            suppressMouseDown: true
          });
        }
        const renderSideBySide = this._options.renderSideBySide.read(reader);
        const deletedCodeLineBreaksComputer = !renderSideBySide ? this._editors.modified._getViewModel()?.createLineBreaksComputer() : void 0;
        if (deletedCodeLineBreaksComputer) {
          const originalModel = this._editors.original.getModel();
          for (const a of alignmentsVal) {
            if (a.diff) {
              for (let i2 = a.originalRange.startLineNumber; i2 < a.originalRange.endLineNumberExclusive; i2++) {
                if (i2 > originalModel.getLineCount()) {
                  return { orig: origViewZones, mod: modViewZones };
                }
                deletedCodeLineBreaksComputer?.addRequest(originalModel.getLineContent(i2), null, null);
              }
            }
          }
        }
        const lineBreakData = deletedCodeLineBreaksComputer?.finalize() ?? [];
        let lineBreakDataIdx = 0;
        const modLineHeight = this._editors.modified.getOption(
          75
          /* EditorOption.lineHeight */
        );
        const syncedMovedText = this._diffModel.read(reader)?.movedTextToCompare.read(reader);
        const mightContainNonBasicASCII = this._editors.original.getModel()?.mightContainNonBasicASCII() ?? false;
        const mightContainRTL = this._editors.original.getModel()?.mightContainRTL() ?? false;
        const renderOptions = RenderOptions.fromEditor(this._editors.modified);
        for (const a of alignmentsVal) {
          if (a.diff && !renderSideBySide && (!this._options.useTrueInlineDiffRendering.read(reader) || !allowsTrueInlineDiffRendering$1(a.diff))) {
            if (!a.originalRange.isEmpty) {
              originalModelTokenizationCompleted.read(reader);
              const deletedCodeDomNode = document.createElement("div");
              deletedCodeDomNode.classList.add("view-lines", "line-delete", "line-delete-selectable", "monaco-mouse-cursor-text");
              const originalModel = this._editors.original.getModel();
              if (a.originalRange.endLineNumberExclusive - 1 > originalModel.getLineCount()) {
                return { orig: origViewZones, mod: modViewZones };
              }
              const source = new LineSource(a.originalRange.mapToLineArray((l) => originalModel.tokenization.getLineTokens(l)), a.originalRange.mapToLineArray((_) => lineBreakData[lineBreakDataIdx++]), mightContainNonBasicASCII, mightContainRTL);
              const decorations = [];
              for (const i2 of a.diff.innerChanges || []) {
                decorations.push(new InlineDecoration(
                  i2.originalRange.delta(-(a.diff.original.startLineNumber - 1)),
                  diffDeleteDecoration.className,
                  0
                  /* InlineDecorationType.Regular */
                ));
              }
              const result = renderLines$1(source, renderOptions, decorations, deletedCodeDomNode);
              const marginDomNode2 = document.createElement("div");
              marginDomNode2.className = "inline-deleted-margin-view-zone";
              applyFontInfo(marginDomNode2, renderOptions.fontInfo);
              if (this._options.renderIndicators.read(reader)) {
                for (let i2 = 0; i2 < result.heightInLines; i2++) {
                  const marginElement = document.createElement("div");
                  marginElement.className = `delete-sign ${ThemeIcon.asClassName(diffRemoveIcon)}`;
                  marginElement.setAttribute("style", `position:absolute;top:${i2 * modLineHeight}px;width:${renderOptions.lineDecorationsWidth}px;height:${modLineHeight}px;right:0;`);
                  marginDomNode2.appendChild(marginElement);
                }
              }
              let zoneId = void 0;
              alignmentViewZonesDisposables.add(new InlineDiffDeletedCodeMargin(() => assertReturnsDefined(zoneId), marginDomNode2, deletedCodeDomNode, this._editors.modified, a.diff, this._diffEditorWidget, result, this._editors.original.getModel(), this._contextMenuService, this._clipboardService));
              for (let i2 = 0; i2 < result.viewLineCounts.length; i2++) {
                const count = result.viewLineCounts[i2];
                if (count > 1) {
                  origViewZones.push({
                    afterLineNumber: a.originalRange.startLineNumber + i2,
                    domNode: createFakeLinesDiv(),
                    heightInPx: (count - 1) * modLineHeight,
                    showInHiddenAreas: true,
                    suppressMouseDown: true
                  });
                }
              }
              modViewZones.push({
                afterLineNumber: a.modifiedRange.startLineNumber - 1,
                domNode: deletedCodeDomNode,
                heightInPx: result.heightInLines * modLineHeight,
                minWidthInPx: result.minWidthInPx,
                marginDomNode: marginDomNode2,
                setZoneId(id) {
                  zoneId = id;
                },
                showInHiddenAreas: true,
                suppressMouseDown: false
              });
            }
            const marginDomNode = document.createElement("div");
            marginDomNode.className = "gutter-delete";
            origViewZones.push({
              afterLineNumber: a.originalRange.endLineNumberExclusive - 1,
              domNode: createFakeLinesDiv(),
              heightInPx: a.modifiedHeightInPx,
              marginDomNode,
              showInHiddenAreas: true,
              suppressMouseDown: true
            });
          } else {
            const delta = a.modifiedHeightInPx - a.originalHeightInPx;
            if (delta > 0) {
              if (syncedMovedText?.lineRangeMapping.original.delta(-1).deltaLength(2).contains(a.originalRange.endLineNumberExclusive - 1)) {
                continue;
              }
              origViewZones.push({
                afterLineNumber: a.originalRange.endLineNumberExclusive - 1,
                domNode: createFakeLinesDiv(),
                heightInPx: delta,
                showInHiddenAreas: true,
                suppressMouseDown: true
              });
            } else {
              let createViewZoneMarginArrow = function() {
                const arrow = document.createElement("div");
                arrow.className = "arrow-revert-change " + ThemeIcon.asClassName(Codicon.arrowRight);
                reader.store.add(addDisposableListener(arrow, "mousedown", (e) => e.stopPropagation()));
                reader.store.add(addDisposableListener(arrow, "click", (e) => {
                  e.stopPropagation();
                  _diffEditorWidget.revert(a.diff);
                }));
                return $$l("div", {}, arrow);
              };
              if (syncedMovedText?.lineRangeMapping.modified.delta(-1).deltaLength(2).contains(a.modifiedRange.endLineNumberExclusive - 1)) {
                continue;
              }
              let marginDomNode = void 0;
              if (a.diff && a.diff.modified.isEmpty && this._options.shouldRenderOldRevertArrows.read(reader)) {
                marginDomNode = createViewZoneMarginArrow();
              }
              modViewZones.push({
                afterLineNumber: a.modifiedRange.endLineNumberExclusive - 1,
                domNode: createFakeLinesDiv(),
                heightInPx: -delta,
                marginDomNode,
                showInHiddenAreas: true,
                suppressMouseDown: true
              });
            }
          }
        }
        for (const a of alignmentsSyncedMovedText.read(reader) ?? []) {
          if (!syncedMovedText?.lineRangeMapping.original.intersect(a.originalRange) || !syncedMovedText?.lineRangeMapping.modified.intersect(a.modifiedRange)) {
            continue;
          }
          const delta = a.modifiedHeightInPx - a.originalHeightInPx;
          if (delta > 0) {
            origViewZones.push({
              afterLineNumber: a.originalRange.endLineNumberExclusive - 1,
              domNode: createFakeLinesDiv(),
              heightInPx: delta,
              showInHiddenAreas: true,
              suppressMouseDown: true
            });
          } else {
            modViewZones.push({
              afterLineNumber: a.modifiedRange.endLineNumberExclusive - 1,
              domNode: createFakeLinesDiv(),
              heightInPx: -delta,
              showInHiddenAreas: true,
              suppressMouseDown: true
            });
          }
        }
        return { orig: origViewZones, mod: modViewZones };
      });
      let ignoreChange = false;
      this._register(this._editors.original.onDidScrollChange((e) => {
        if (e.scrollLeftChanged && !ignoreChange) {
          ignoreChange = true;
          this._editors.modified.setScrollLeft(e.scrollLeft);
          ignoreChange = false;
        }
      }));
      this._register(this._editors.modified.onDidScrollChange((e) => {
        if (e.scrollLeftChanged && !ignoreChange) {
          ignoreChange = true;
          this._editors.original.setScrollLeft(e.scrollLeft);
          ignoreChange = false;
        }
      }));
      this._originalScrollTop = observableFromEvent(this._editors.original.onDidScrollChange, () => (
        /** @description original.getScrollTop */
        this._editors.original.getScrollTop()
      ));
      this._modifiedScrollTop = observableFromEvent(this._editors.modified.onDidScrollChange, () => (
        /** @description modified.getScrollTop */
        this._editors.modified.getScrollTop()
      ));
      this._register(autorun((reader) => {
        const newScrollTopModified = this._originalScrollTop.read(reader) - (this._originalScrollOffsetAnimated.read(void 0) - this._modifiedScrollOffsetAnimated.read(reader)) - (this._originalTopPadding.read(void 0) - this._modifiedTopPadding.read(reader));
        if (newScrollTopModified !== this._editors.modified.getScrollTop()) {
          this._editors.modified.setScrollTop(
            newScrollTopModified,
            1
            /* ScrollType.Immediate */
          );
        }
      }));
      this._register(autorun((reader) => {
        const newScrollTopOriginal = this._modifiedScrollTop.read(reader) - (this._modifiedScrollOffsetAnimated.read(void 0) - this._originalScrollOffsetAnimated.read(reader)) - (this._modifiedTopPadding.read(void 0) - this._originalTopPadding.read(reader));
        if (newScrollTopOriginal !== this._editors.original.getScrollTop()) {
          this._editors.original.setScrollTop(
            newScrollTopOriginal,
            1
            /* ScrollType.Immediate */
          );
        }
      }));
      this._register(autorun((reader) => {
        const m = this._diffModel.read(reader)?.movedTextToCompare.read(reader);
        let deltaOrigToMod = 0;
        if (m) {
          const trueTopOriginal = this._editors.original.getTopForLineNumber(m.lineRangeMapping.original.startLineNumber, true) - this._originalTopPadding.read(void 0);
          const trueTopModified = this._editors.modified.getTopForLineNumber(m.lineRangeMapping.modified.startLineNumber, true) - this._modifiedTopPadding.read(void 0);
          deltaOrigToMod = trueTopModified - trueTopOriginal;
        }
        if (deltaOrigToMod > 0) {
          this._modifiedTopPadding.set(0, void 0);
          this._originalTopPadding.set(deltaOrigToMod, void 0);
        } else if (deltaOrigToMod < 0) {
          this._modifiedTopPadding.set(-deltaOrigToMod, void 0);
          this._originalTopPadding.set(0, void 0);
        } else {
          setTimeout(() => {
            this._modifiedTopPadding.set(0, void 0);
            this._originalTopPadding.set(0, void 0);
          }, 400);
        }
        if (this._editors.modified.hasTextFocus()) {
          this._originalScrollOffset.set(this._modifiedScrollOffset.read(void 0) - deltaOrigToMod, void 0, true);
        } else {
          this._modifiedScrollOffset.set(this._originalScrollOffset.read(void 0) + deltaOrigToMod, void 0, true);
        }
      }));
    }
  };
  DiffEditorViewZones = __decorate$2E([
    __param$2B(8, IClipboardService),
    __param$2B(9, IContextMenuService)
  ], DiffEditorViewZones);
  function computeRangeAlignment(originalEditor, modifiedEditor, diffs, originalEditorAlignmentViewZones, modifiedEditorAlignmentViewZones, innerHunkAlignment) {
    const originalLineHeightOverrides = new ArrayQueue(getAdditionalLineHeights(originalEditor, originalEditorAlignmentViewZones));
    const modifiedLineHeightOverrides = new ArrayQueue(getAdditionalLineHeights(modifiedEditor, modifiedEditorAlignmentViewZones));
    const origLineHeight = originalEditor.getOption(
      75
      /* EditorOption.lineHeight */
    );
    const modLineHeight = modifiedEditor.getOption(
      75
      /* EditorOption.lineHeight */
    );
    const result = [];
    let lastOriginalLineNumber = 0;
    let lastModifiedLineNumber = 0;
    function handleAlignmentsOutsideOfDiffs(untilOriginalLineNumberExclusive, untilModifiedLineNumberExclusive) {
      while (true) {
        let origNext = originalLineHeightOverrides.peek();
        let modNext = modifiedLineHeightOverrides.peek();
        if (origNext && origNext.lineNumber >= untilOriginalLineNumberExclusive) {
          origNext = void 0;
        }
        if (modNext && modNext.lineNumber >= untilModifiedLineNumberExclusive) {
          modNext = void 0;
        }
        if (!origNext && !modNext) {
          break;
        }
        const distOrig = origNext ? origNext.lineNumber - lastOriginalLineNumber : Number.MAX_VALUE;
        const distNext = modNext ? modNext.lineNumber - lastModifiedLineNumber : Number.MAX_VALUE;
        if (distOrig < distNext) {
          originalLineHeightOverrides.dequeue();
          modNext = {
            lineNumber: origNext.lineNumber - lastOriginalLineNumber + lastModifiedLineNumber,
            heightInPx: 0
          };
        } else if (distOrig > distNext) {
          modifiedLineHeightOverrides.dequeue();
          origNext = {
            lineNumber: modNext.lineNumber - lastModifiedLineNumber + lastOriginalLineNumber,
            heightInPx: 0
          };
        } else {
          originalLineHeightOverrides.dequeue();
          modifiedLineHeightOverrides.dequeue();
        }
        result.push({
          originalRange: LineRange.ofLength(origNext.lineNumber, 1),
          modifiedRange: LineRange.ofLength(modNext.lineNumber, 1),
          originalHeightInPx: origLineHeight + origNext.heightInPx,
          modifiedHeightInPx: modLineHeight + modNext.heightInPx,
          diff: void 0
        });
      }
    }
    for (const m of diffs) {
      let emitAlignment = function(origLineNumberExclusive, modLineNumberExclusive, forceAlignment = false) {
        if (origLineNumberExclusive < lastOrigLineNumber || modLineNumberExclusive < lastModLineNumber) {
          return;
        }
        if (first2) {
          first2 = false;
        } else if (!forceAlignment && (origLineNumberExclusive === lastOrigLineNumber || modLineNumberExclusive === lastModLineNumber)) {
          return;
        }
        const originalRange = new LineRange(lastOrigLineNumber, origLineNumberExclusive);
        const modifiedRange = new LineRange(lastModLineNumber, modLineNumberExclusive);
        if (originalRange.isEmpty && modifiedRange.isEmpty) {
          return;
        }
        const originalAdditionalHeight = originalLineHeightOverrides.takeWhile((v) => v.lineNumber < origLineNumberExclusive)?.reduce((p, c2) => p + c2.heightInPx, 0) ?? 0;
        const modifiedAdditionalHeight = modifiedLineHeightOverrides.takeWhile((v) => v.lineNumber < modLineNumberExclusive)?.reduce((p, c2) => p + c2.heightInPx, 0) ?? 0;
        result.push({
          originalRange,
          modifiedRange,
          originalHeightInPx: originalRange.length * origLineHeight + originalAdditionalHeight,
          modifiedHeightInPx: modifiedRange.length * modLineHeight + modifiedAdditionalHeight,
          diff: m.lineRangeMapping
        });
        lastOrigLineNumber = origLineNumberExclusive;
        lastModLineNumber = modLineNumberExclusive;
      };
      const c = m.lineRangeMapping;
      handleAlignmentsOutsideOfDiffs(c.original.startLineNumber, c.modified.startLineNumber);
      let first2 = true;
      let lastModLineNumber = c.modified.startLineNumber;
      let lastOrigLineNumber = c.original.startLineNumber;
      if (innerHunkAlignment) {
        for (const i2 of c.innerChanges || []) {
          if (i2.originalRange.startColumn > 1 && i2.modifiedRange.startColumn > 1) {
            emitAlignment(i2.originalRange.startLineNumber, i2.modifiedRange.startLineNumber);
          }
          const originalModel = originalEditor.getModel();
          const maxColumn = i2.originalRange.endLineNumber <= originalModel.getLineCount() ? originalModel.getLineMaxColumn(i2.originalRange.endLineNumber) : Number.MAX_SAFE_INTEGER;
          if (i2.originalRange.endColumn < maxColumn) {
            emitAlignment(i2.originalRange.endLineNumber, i2.modifiedRange.endLineNumber);
          }
        }
      }
      emitAlignment(c.original.endLineNumberExclusive, c.modified.endLineNumberExclusive, true);
      lastOriginalLineNumber = c.original.endLineNumberExclusive;
      lastModifiedLineNumber = c.modified.endLineNumberExclusive;
    }
    handleAlignmentsOutsideOfDiffs(Number.MAX_VALUE, Number.MAX_VALUE);
    return result;
  }
  function getAdditionalLineHeights(editor2, viewZonesToIgnore) {
    const viewZoneHeights = [];
    const wrappingZoneHeights = [];
    const hasWrapping = editor2.getOption(
      166
      /* EditorOption.wrappingInfo */
    ).wrappingColumn !== -1;
    const coordinatesConverter = editor2._getViewModel().coordinatesConverter;
    const editorLineHeight = editor2.getOption(
      75
      /* EditorOption.lineHeight */
    );
    if (hasWrapping) {
      for (let i2 = 1; i2 <= editor2.getModel().getLineCount(); i2++) {
        const lineCount = coordinatesConverter.getModelLineViewLineCount(i2);
        if (lineCount > 1) {
          wrappingZoneHeights.push({ lineNumber: i2, heightInPx: editorLineHeight * (lineCount - 1) });
        }
      }
    }
    for (const w of editor2.getWhitespaces()) {
      if (viewZonesToIgnore.has(w.id)) {
        continue;
      }
      const modelLineNumber = w.afterLineNumber === 0 ? 0 : coordinatesConverter.convertViewPositionToModelPosition(new Position$1(w.afterLineNumber, 1)).lineNumber;
      viewZoneHeights.push({ lineNumber: modelLineNumber, heightInPx: w.height });
    }
    const result = joinCombine(viewZoneHeights, wrappingZoneHeights, (v) => v.lineNumber, (v1, v2) => ({ lineNumber: v1.lineNumber, heightInPx: v1.heightInPx + v2.heightInPx }));
    return result;
  }
  function allowsTrueInlineDiffRendering$1(mapping) {
    if (!mapping.innerChanges) {
      return false;
    }
    return mapping.innerChanges.every((c) => rangeIsSingleLine(c.modifiedRange) && rangeIsSingleLine(c.originalRange) || c.originalRange.equalsRange(new Range$2(1, 1, 1, 1)));
  }
  function rangeIsSingleLine(range2) {
    return range2.startLineNumber === range2.endLineNumber;
  }
  const _MovedBlocksLinesFeature = class _MovedBlocksLinesFeature extends Disposable {
    constructor(_rootElement, _diffModel, _originalEditorLayoutInfo, _modifiedEditorLayoutInfo, _editors) {
      super();
      this._rootElement = _rootElement;
      this._diffModel = _diffModel;
      this._originalEditorLayoutInfo = _originalEditorLayoutInfo;
      this._modifiedEditorLayoutInfo = _modifiedEditorLayoutInfo;
      this._editors = _editors;
      this._originalScrollTop = observableFromEvent(this, this._editors.original.onDidScrollChange, () => this._editors.original.getScrollTop());
      this._modifiedScrollTop = observableFromEvent(this, this._editors.modified.onDidScrollChange, () => this._editors.modified.getScrollTop());
      this._viewZonesChanged = observableSignalFromEvent("onDidChangeViewZones", this._editors.modified.onDidChangeViewZones);
      this.width = observableValue(this, 0);
      this._modifiedViewZonesChangedSignal = observableSignalFromEvent("modified.onDidChangeViewZones", this._editors.modified.onDidChangeViewZones);
      this._originalViewZonesChangedSignal = observableSignalFromEvent("original.onDidChangeViewZones", this._editors.original.onDidChangeViewZones);
      this._state = derived(this, (reader) => {
        this._element.replaceChildren();
        const model = this._diffModel.read(reader);
        const moves = model?.diff.read(reader)?.movedTexts;
        if (!moves || moves.length === 0) {
          this.width.set(0, void 0);
          return;
        }
        this._viewZonesChanged.read(reader);
        const infoOrig = this._originalEditorLayoutInfo.read(reader);
        const infoMod = this._modifiedEditorLayoutInfo.read(reader);
        if (!infoOrig || !infoMod) {
          this.width.set(0, void 0);
          return;
        }
        this._modifiedViewZonesChangedSignal.read(reader);
        this._originalViewZonesChangedSignal.read(reader);
        const lines = moves.map((move) => {
          function computeLineStart(range2, editor2) {
            const t1 = editor2.getTopForLineNumber(range2.startLineNumber, true);
            const t2 = editor2.getTopForLineNumber(range2.endLineNumberExclusive, true);
            return (t1 + t2) / 2;
          }
          const start = computeLineStart(move.lineRangeMapping.original, this._editors.original);
          const startOffset = this._originalScrollTop.read(reader);
          const end = computeLineStart(move.lineRangeMapping.modified, this._editors.modified);
          const endOffset = this._modifiedScrollTop.read(reader);
          const from = start - startOffset;
          const to = end - endOffset;
          const top = Math.min(start, end);
          const bottom = Math.max(start, end);
          return { range: new OffsetRange(top, bottom), from, to, fromWithoutScroll: start, toWithoutScroll: end, move };
        });
        lines.sort(tieBreakComparators(compareBy((l) => l.fromWithoutScroll > l.toWithoutScroll, booleanComparator), compareBy((l) => l.fromWithoutScroll > l.toWithoutScroll ? l.fromWithoutScroll : -l.toWithoutScroll, numberComparator)));
        const layout2 = LinesLayout.compute(lines.map((l) => l.range));
        const padding = 10;
        const lineAreaLeft = infoOrig.verticalScrollbarWidth;
        const lineAreaWidth = (layout2.getTrackCount() - 1) * 10 + padding * 2;
        const width2 = lineAreaLeft + lineAreaWidth + (infoMod.contentLeft - _MovedBlocksLinesFeature.movedCodeBlockPadding);
        let idx = 0;
        for (const line of lines) {
          const track = layout2.getTrack(idx);
          const verticalY = lineAreaLeft + padding + track * 10;
          const arrowHeight = 15;
          const arrowWidth = 15;
          const right = width2;
          const rectWidth = infoMod.glyphMarginWidth + infoMod.lineNumbersWidth;
          const rectHeight = 18;
          const rect = document.createElementNS("http://www.w3.org/2000/svg", "rect");
          rect.classList.add("arrow-rectangle");
          rect.setAttribute("x", `${right - rectWidth}`);
          rect.setAttribute("y", `${line.to - rectHeight / 2}`);
          rect.setAttribute("width", `${rectWidth}`);
          rect.setAttribute("height", `${rectHeight}`);
          this._element.appendChild(rect);
          const g = document.createElementNS("http://www.w3.org/2000/svg", "g");
          const path = document.createElementNS("http://www.w3.org/2000/svg", "path");
          path.setAttribute("d", `M ${0} ${line.from} L ${verticalY} ${line.from} L ${verticalY} ${line.to} L ${right - arrowWidth} ${line.to}`);
          path.setAttribute("fill", "none");
          g.appendChild(path);
          const arrowRight = document.createElementNS("http://www.w3.org/2000/svg", "polygon");
          arrowRight.classList.add("arrow");
          reader.store.add(autorun((reader2) => {
            path.classList.toggle("currentMove", line.move === model.activeMovedText.read(reader2));
            arrowRight.classList.toggle("currentMove", line.move === model.activeMovedText.read(reader2));
          }));
          arrowRight.setAttribute("points", `${right - arrowWidth},${line.to - arrowHeight / 2} ${right},${line.to} ${right - arrowWidth},${line.to + arrowHeight / 2}`);
          g.appendChild(arrowRight);
          this._element.appendChild(g);
          idx++;
        }
        this.width.set(lineAreaWidth, void 0);
      });
      this._element = document.createElementNS("http://www.w3.org/2000/svg", "svg");
      this._element.setAttribute("class", "moved-blocks-lines");
      this._rootElement.appendChild(this._element);
      this._register(toDisposable(() => this._element.remove()));
      this._register(autorun((reader) => {
        const info = this._originalEditorLayoutInfo.read(reader);
        const info2 = this._modifiedEditorLayoutInfo.read(reader);
        if (!info || !info2) {
          return;
        }
        this._element.style.left = `${info.width - info.verticalScrollbarWidth}px`;
        this._element.style.height = `${info.height}px`;
        this._element.style.width = `${info.verticalScrollbarWidth + info.contentLeft - _MovedBlocksLinesFeature.movedCodeBlockPadding + this.width.read(reader)}px`;
      }));
      this._register(recomputeInitiallyAndOnChange(this._state));
      const movedBlockViewZones = derived((reader) => {
        const model = this._diffModel.read(reader);
        const d = model?.diff.read(reader);
        if (!d) {
          return [];
        }
        return d.movedTexts.map((move) => ({
          move,
          original: new PlaceholderViewZone(constObservable(move.lineRangeMapping.original.startLineNumber - 1), 18),
          modified: new PlaceholderViewZone(constObservable(move.lineRangeMapping.modified.startLineNumber - 1), 18)
        }));
      });
      this._register(applyViewZones(this._editors.original, movedBlockViewZones.map((zones) => (
        /** @description movedBlockViewZones.original */
        zones.map((z) => z.original)
      ))));
      this._register(applyViewZones(this._editors.modified, movedBlockViewZones.map((zones) => (
        /** @description movedBlockViewZones.modified */
        zones.map((z) => z.modified)
      ))));
      this._register(autorunWithStore((reader, store) => {
        const blocks = movedBlockViewZones.read(reader);
        for (const b of blocks) {
          store.add(new MovedBlockOverlayWidget(this._editors.original, b.original, b.move, "original", this._diffModel.get()));
          store.add(new MovedBlockOverlayWidget(this._editors.modified, b.modified, b.move, "modified", this._diffModel.get()));
        }
      }));
      const originalHasFocus = observableSignalFromEvent("original.onDidFocusEditorWidget", (e) => this._editors.original.onDidFocusEditorWidget(() => setTimeout(() => e(void 0), 0)));
      const modifiedHasFocus = observableSignalFromEvent("modified.onDidFocusEditorWidget", (e) => this._editors.modified.onDidFocusEditorWidget(() => setTimeout(() => e(void 0), 0)));
      let lastChangedEditor = "modified";
      this._register(autorunHandleChanges({
        changeTracker: {
          createChangeSummary: () => void 0,
          handleChange: (ctx, summary) => {
            if (ctx.didChange(originalHasFocus)) {
              lastChangedEditor = "original";
            }
            if (ctx.didChange(modifiedHasFocus)) {
              lastChangedEditor = "modified";
            }
            return true;
          }
        }
      }, (reader) => {
        originalHasFocus.read(reader);
        modifiedHasFocus.read(reader);
        const m = this._diffModel.read(reader);
        if (!m) {
          return;
        }
        const diff = m.diff.read(reader);
        let movedText = void 0;
        if (diff && lastChangedEditor === "original") {
          const originalPos = this._editors.originalCursor.read(reader);
          if (originalPos) {
            movedText = diff.movedTexts.find((m2) => m2.lineRangeMapping.original.contains(originalPos.lineNumber));
          }
        }
        if (diff && lastChangedEditor === "modified") {
          const modifiedPos = this._editors.modifiedCursor.read(reader);
          if (modifiedPos) {
            movedText = diff.movedTexts.find((m2) => m2.lineRangeMapping.modified.contains(modifiedPos.lineNumber));
          }
        }
        if (movedText !== m.movedTextToCompare.read(void 0)) {
          m.movedTextToCompare.set(void 0, void 0);
        }
        m.setActiveMovedText(movedText);
      }));
    }
  };
  _MovedBlocksLinesFeature.movedCodeBlockPadding = 4;
  let MovedBlocksLinesFeature = _MovedBlocksLinesFeature;
  class LinesLayout {
    static compute(lines) {
      const setsPerTrack = [];
      const trackPerLineIdx = [];
      for (const line of lines) {
        let trackIdx = setsPerTrack.findIndex((set) => !set.intersectsStrict(line));
        if (trackIdx === -1) {
          const maxTrackCount = 6;
          if (setsPerTrack.length >= maxTrackCount) {
            trackIdx = findMaxIdx(setsPerTrack, compareBy((set) => set.intersectWithRangeLength(line), numberComparator));
          } else {
            trackIdx = setsPerTrack.length;
            setsPerTrack.push(new OffsetRangeSet());
          }
        }
        setsPerTrack[trackIdx].addRange(line);
        trackPerLineIdx.push(trackIdx);
      }
      return new LinesLayout(setsPerTrack.length, trackPerLineIdx);
    }
    constructor(_trackCount, trackPerLineIdx) {
      this._trackCount = _trackCount;
      this.trackPerLineIdx = trackPerLineIdx;
    }
    getTrack(lineIdx) {
      return this.trackPerLineIdx[lineIdx];
    }
    getTrackCount() {
      return this._trackCount;
    }
  }
  class MovedBlockOverlayWidget extends ViewZoneOverlayWidget {
    constructor(_editor, _viewZone, _move, _kind, _diffModel) {
      const root = h("div.diff-hidden-lines-widget");
      super(_editor, _viewZone, root.root);
      this._editor = _editor;
      this._move = _move;
      this._kind = _kind;
      this._diffModel = _diffModel;
      this._nodes = h("div.diff-moved-code-block", { style: { marginRight: "4px" } }, [
        h("div.text-content@textContent"),
        h("div.action-bar@actionBar")
      ]);
      root.root.appendChild(this._nodes.root);
      const editorLayout = observableFromEvent(this._editor.onDidLayoutChange, () => this._editor.getLayoutInfo());
      this._register(applyStyle(this._nodes.root, {
        paddingRight: editorLayout.map((l) => l.verticalScrollbarWidth)
      }));
      let text2;
      if (_move.changes.length > 0) {
        text2 = this._kind === "original" ? localize(131, "Code moved with changes to line {0}-{1}", this._move.lineRangeMapping.modified.startLineNumber, this._move.lineRangeMapping.modified.endLineNumberExclusive - 1) : localize(132, "Code moved with changes from line {0}-{1}", this._move.lineRangeMapping.original.startLineNumber, this._move.lineRangeMapping.original.endLineNumberExclusive - 1);
      } else {
        text2 = this._kind === "original" ? localize(133, "Code moved to line {0}-{1}", this._move.lineRangeMapping.modified.startLineNumber, this._move.lineRangeMapping.modified.endLineNumberExclusive - 1) : localize(134, "Code moved from line {0}-{1}", this._move.lineRangeMapping.original.startLineNumber, this._move.lineRangeMapping.original.endLineNumberExclusive - 1);
      }
      const actionBar2 = this._register(new ActionBar(this._nodes.actionBar, {
        highlightToggledItems: true
      }));
      const caption = new Action("", text2, "", false);
      actionBar2.push(caption, { icon: false, label: true });
      const actionCompare = new Action("", "Compare", ThemeIcon.asClassName(Codicon.compareChanges), true, () => {
        this._editor.focus();
        this._diffModel.movedTextToCompare.set(this._diffModel.movedTextToCompare.get() === _move ? void 0 : this._move, void 0);
      });
      this._register(autorun((reader) => {
        const isActive = this._diffModel.movedTextToCompare.read(reader) === _move;
        actionCompare.checked = isActive;
      }));
      actionBar2.push(actionCompare, { icon: false, label: true });
    }
  }
  class DiffEditorDecorations extends Disposable {
    constructor(_editors, _diffModel, _options, widget) {
      super();
      this._editors = _editors;
      this._diffModel = _diffModel;
      this._options = _options;
      this._decorations = derived(this, (reader) => {
        const diffModel = this._diffModel.read(reader);
        const diff = diffModel?.diff.read(reader);
        if (!diff) {
          return null;
        }
        const movedTextToCompare = this._diffModel.read(reader).movedTextToCompare.read(reader);
        const renderIndicators = this._options.renderIndicators.read(reader);
        const showEmptyDecorations = this._options.showEmptyDecorations.read(reader);
        const originalDecorations = [];
        const modifiedDecorations = [];
        if (!movedTextToCompare) {
          for (const m of diff.mappings) {
            if (!m.lineRangeMapping.original.isEmpty) {
              originalDecorations.push({ range: m.lineRangeMapping.original.toInclusiveRange(), options: renderIndicators ? diffLineDeleteDecorationBackgroundWithIndicator : diffLineDeleteDecorationBackground });
            }
            if (!m.lineRangeMapping.modified.isEmpty) {
              modifiedDecorations.push({ range: m.lineRangeMapping.modified.toInclusiveRange(), options: renderIndicators ? diffLineAddDecorationBackgroundWithIndicator : diffLineAddDecorationBackground });
            }
            if (m.lineRangeMapping.modified.isEmpty || m.lineRangeMapping.original.isEmpty) {
              if (!m.lineRangeMapping.original.isEmpty) {
                originalDecorations.push({ range: m.lineRangeMapping.original.toInclusiveRange(), options: diffWholeLineDeleteDecoration });
              }
              if (!m.lineRangeMapping.modified.isEmpty) {
                modifiedDecorations.push({ range: m.lineRangeMapping.modified.toInclusiveRange(), options: diffWholeLineAddDecoration });
              }
            } else {
              const useInlineDiff = this._options.useTrueInlineDiffRendering.read(reader) && allowsTrueInlineDiffRendering$1(m.lineRangeMapping);
              for (const i2 of m.lineRangeMapping.innerChanges || []) {
                if (m.lineRangeMapping.original.contains(i2.originalRange.startLineNumber)) {
                  originalDecorations.push({ range: i2.originalRange, options: i2.originalRange.isEmpty() && showEmptyDecorations ? diffDeleteDecorationEmpty : diffDeleteDecoration });
                }
                if (m.lineRangeMapping.modified.contains(i2.modifiedRange.startLineNumber)) {
                  modifiedDecorations.push({ range: i2.modifiedRange, options: i2.modifiedRange.isEmpty() && showEmptyDecorations && !useInlineDiff ? diffAddDecorationEmpty : diffAddDecoration });
                }
                if (useInlineDiff) {
                  const deletedText = diffModel.model.original.getValueInRange(i2.originalRange);
                  modifiedDecorations.push({
                    range: i2.modifiedRange,
                    options: {
                      description: "deleted-text",
                      before: {
                        content: deletedText,
                        inlineClassName: "inline-deleted-text"
                      },
                      zIndex: 1e5,
                      showIfCollapsed: true
                    }
                  });
                }
              }
            }
          }
        }
        if (movedTextToCompare) {
          for (const m of movedTextToCompare.changes) {
            const fullRangeOriginal = m.original.toInclusiveRange();
            if (fullRangeOriginal) {
              originalDecorations.push({ range: fullRangeOriginal, options: renderIndicators ? diffLineDeleteDecorationBackgroundWithIndicator : diffLineDeleteDecorationBackground });
            }
            const fullRangeModified = m.modified.toInclusiveRange();
            if (fullRangeModified) {
              modifiedDecorations.push({ range: fullRangeModified, options: renderIndicators ? diffLineAddDecorationBackgroundWithIndicator : diffLineAddDecorationBackground });
            }
            for (const i2 of m.innerChanges || []) {
              originalDecorations.push({ range: i2.originalRange, options: diffDeleteDecoration });
              modifiedDecorations.push({ range: i2.modifiedRange, options: diffAddDecoration });
            }
          }
        }
        const activeMovedText = this._diffModel.read(reader).activeMovedText.read(reader);
        for (const m of diff.movedTexts) {
          originalDecorations.push({
            range: m.lineRangeMapping.original.toInclusiveRange(),
            options: {
              description: "moved",
              blockClassName: "movedOriginal" + (m === activeMovedText ? " currentMove" : ""),
              blockPadding: [MovedBlocksLinesFeature.movedCodeBlockPadding, 0, MovedBlocksLinesFeature.movedCodeBlockPadding, MovedBlocksLinesFeature.movedCodeBlockPadding]
            }
          });
          modifiedDecorations.push({
            range: m.lineRangeMapping.modified.toInclusiveRange(),
            options: {
              description: "moved",
              blockClassName: "movedModified" + (m === activeMovedText ? " currentMove" : ""),
              blockPadding: [4, 0, 4, 4]
            }
          });
        }
        return { originalDecorations, modifiedDecorations };
      });
      this._register(applyObservableDecorations(this._editors.original, this._decorations.map((d) => d?.originalDecorations || [])));
      this._register(applyObservableDecorations(this._editors.modified, this._decorations.map((d) => d?.modifiedDecorations || [])));
    }
  }
  class Point {
    static equals(a, b) {
      return a.x === b.x && a.y === b.y;
    }
    constructor(x, y) {
      this.x = x;
      this.y = y;
    }
    add(other) {
      return new Point(this.x + other.x, this.y + other.y);
    }
    deltaX(delta) {
      return new Point(this.x + delta, this.y);
    }
    deltaY(delta) {
      return new Point(this.x, this.y + delta);
    }
    toString() {
      return `(${this.x},${this.y})`;
    }
    subtract(other) {
      return new Point(this.x - other.x, this.y - other.y);
    }
    scale(factor2) {
      return new Point(this.x * factor2, this.y * factor2);
    }
    mapComponents(map) {
      return new Point(map(this.x), map(this.y));
    }
    isZero() {
      return this.x === 0 && this.y === 0;
    }
    withThreshold(threshold) {
      return this.mapComponents((axisVal) => {
        if (axisVal > threshold) {
          return axisVal - threshold;
        } else if (axisVal < -threshold) {
          return axisVal + threshold;
        }
        return 0;
      });
    }
  }
  function observableCodeEditor(editor2) {
    return ObservableCodeEditor.get(editor2);
  }
  const _ObservableCodeEditor = class _ObservableCodeEditor extends Disposable {
    /**
     * Make sure that editor is not disposed yet!
    */
    static get(editor2) {
      let result = _ObservableCodeEditor._map.get(editor2);
      if (!result) {
        result = new _ObservableCodeEditor(editor2);
        _ObservableCodeEditor._map.set(editor2, result);
        const d = editor2.onDidDispose(() => {
          const item = _ObservableCodeEditor._map.get(editor2);
          if (item) {
            _ObservableCodeEditor._map.delete(editor2);
            item.dispose();
            d.dispose();
          }
        });
      }
      return result;
    }
    _beginUpdate() {
      this._updateCounter++;
      if (this._updateCounter === 1) {
        this._currentTransaction = new TransactionImpl(() => {
        });
      }
    }
    _endUpdate() {
      this._updateCounter--;
      if (this._updateCounter === 0) {
        const t = this._currentTransaction;
        this._currentTransaction = void 0;
        t.finish();
      }
    }
    constructor(editor2) {
      super();
      this.editor = editor2;
      this._updateCounter = 0;
      this._currentTransaction = void 0;
      this._model = observableValue(this, this.editor.getModel());
      this.model = this._model;
      this.isReadonly = observableFromEvent(this, this.editor.onDidChangeConfiguration, () => this.editor.getOption(
        104
        /* EditorOption.readOnly */
      ));
      this._versionId = observableValueOpts({ owner: this, lazy: true }, this.editor.getModel()?.getVersionId() ?? null);
      this.versionId = this._versionId;
      this._selections = observableValueOpts({ owner: this, equalsFn: equalsIfDefined(itemsEquals(Selection$1.selectionsEqual)), lazy: true }, this.editor.getSelections() ?? null);
      this.selections = this._selections;
      this.positions = derivedOpts({ owner: this, equalsFn: equalsIfDefined(itemsEquals(Position$1.equals)) }, (reader) => this.selections.read(reader)?.map((s) => s.getStartPosition()) ?? null);
      this.isFocused = observableFromEvent(this, (e) => {
        const d1 = this.editor.onDidFocusEditorWidget(e);
        const d2 = this.editor.onDidBlurEditorWidget(e);
        return {
          dispose() {
            d1.dispose();
            d2.dispose();
          }
        };
      }, () => this.editor.hasWidgetFocus());
      this.isTextFocused = observableFromEvent(this, (e) => {
        const d1 = this.editor.onDidFocusEditorText(e);
        const d2 = this.editor.onDidBlurEditorText(e);
        return {
          dispose() {
            d1.dispose();
            d2.dispose();
          }
        };
      }, () => this.editor.hasTextFocus());
      this.inComposition = observableFromEvent(this, (e) => {
        const d1 = this.editor.onDidCompositionStart(() => {
          e(void 0);
        });
        const d2 = this.editor.onDidCompositionEnd(() => {
          e(void 0);
        });
        return {
          dispose() {
            d1.dispose();
            d2.dispose();
          }
        };
      }, () => this.editor.inComposition);
      this.value = derivedWithSetter(this, (reader) => {
        this.versionId.read(reader);
        return this.model.read(reader)?.getValue() ?? "";
      }, (value, tx) => {
        const model = this.model.get();
        if (model !== null) {
          if (value !== model.getValue()) {
            model.setValue(value);
          }
        }
      });
      this.valueIsEmpty = derived(this, (reader) => {
        this.versionId.read(reader);
        return this.editor.getModel()?.getValueLength() === 0;
      });
      this.cursorSelection = derivedOpts({ owner: this, equalsFn: equalsIfDefined(Selection$1.selectionsEqual) }, (reader) => this.selections.read(reader)?.[0] ?? null);
      this.cursorPosition = derivedOpts({ owner: this, equalsFn: Position$1.equals }, (reader) => this.selections.read(reader)?.[0]?.getPosition() ?? null);
      this.cursorLineNumber = derived(this, (reader) => this.cursorPosition.read(reader)?.lineNumber ?? null);
      this.onDidType = observableSignal(this);
      this.onDidPaste = observableSignal(this);
      this.scrollTop = observableFromEvent(this.editor.onDidScrollChange, () => this.editor.getScrollTop());
      this.scrollLeft = observableFromEvent(this.editor.onDidScrollChange, () => this.editor.getScrollLeft());
      this.layoutInfo = observableFromEvent(this.editor.onDidLayoutChange, () => this.editor.getLayoutInfo());
      this.layoutInfoContentLeft = this.layoutInfo.map((l) => l.contentLeft);
      this.layoutInfoDecorationsLeft = this.layoutInfo.map((l) => l.decorationsLeft);
      this.layoutInfoWidth = this.layoutInfo.map((l) => l.width);
      this.layoutInfoHeight = this.layoutInfo.map((l) => l.height);
      this.layoutInfoMinimap = this.layoutInfo.map((l) => l.minimap);
      this.layoutInfoVerticalScrollbarWidth = this.layoutInfo.map((l) => l.verticalScrollbarWidth);
      this.contentWidth = observableFromEvent(this.editor.onDidContentSizeChange, () => this.editor.getContentWidth());
      this.contentHeight = observableFromEvent(this.editor.onDidContentSizeChange, () => this.editor.getContentHeight());
      this._widgetCounter = 0;
      this.openedPeekWidgets = observableValue(this, 0);
      this._register(this.editor.onBeginUpdate(() => this._beginUpdate()));
      this._register(this.editor.onEndUpdate(() => this._endUpdate()));
      this._register(this.editor.onDidChangeModel(() => {
        this._beginUpdate();
        try {
          this._model.set(this.editor.getModel(), this._currentTransaction);
          this._forceUpdate();
        } finally {
          this._endUpdate();
        }
      }));
      this._register(this.editor.onDidType((e) => {
        this._beginUpdate();
        try {
          this._forceUpdate();
          this.onDidType.trigger(this._currentTransaction, e);
        } finally {
          this._endUpdate();
        }
      }));
      this._register(this.editor.onDidPaste((e) => {
        this._beginUpdate();
        try {
          this._forceUpdate();
          this.onDidPaste.trigger(this._currentTransaction, e);
        } finally {
          this._endUpdate();
        }
      }));
      this._register(this.editor.onDidChangeModelContent((e) => {
        this._beginUpdate();
        try {
          this._versionId.set(this.editor.getModel()?.getVersionId() ?? null, this._currentTransaction, e);
          this._forceUpdate();
        } finally {
          this._endUpdate();
        }
      }));
      this._register(this.editor.onDidChangeCursorSelection((e) => {
        this._beginUpdate();
        try {
          this._selections.set(this.editor.getSelections(), this._currentTransaction, e);
          this._forceUpdate();
        } finally {
          this._endUpdate();
        }
      }));
      this.domNode = derived((reader) => {
        this.model.read(reader);
        return this.editor.getDomNode();
      });
    }
    forceUpdate(cb) {
      this._beginUpdate();
      try {
        this._forceUpdate();
        if (!cb) {
          return void 0;
        }
        return cb(this._currentTransaction);
      } finally {
        this._endUpdate();
      }
    }
    _forceUpdate() {
      this._beginUpdate();
      try {
        this._model.set(this.editor.getModel(), this._currentTransaction);
        this._versionId.set(this.editor.getModel()?.getVersionId() ?? null, this._currentTransaction, void 0);
        this._selections.set(this.editor.getSelections(), this._currentTransaction, void 0);
      } finally {
        this._endUpdate();
      }
    }
    getOption(id, debugLocation = DebugLocation.ofCaller()) {
      return observableFromEvent(this, (cb) => this.editor.onDidChangeConfiguration((e) => {
        if (e.hasChanged(id)) {
          cb(void 0);
        }
      }), () => this.editor.getOption(id), debugLocation);
    }
    setDecorations(decorations) {
      const d = new DisposableStore();
      const decorationsCollection = this.editor.createDecorationsCollection();
      d.add(autorunOpts({ owner: this, debugName: () => `Apply decorations from ${decorations.debugName}` }, (reader) => {
        const d2 = decorations.read(reader);
        decorationsCollection.set(d2);
      }));
      d.add({
        dispose: () => {
          decorationsCollection.clear();
        }
      });
      return d;
    }
    createOverlayWidget(widget) {
      const overlayWidgetId = "observableOverlayWidget" + this._widgetCounter++;
      const w = {
        getDomNode: () => widget.domNode,
        getPosition: () => widget.position.get(),
        getId: () => overlayWidgetId,
        allowEditorOverflow: widget.allowEditorOverflow,
        getMinContentWidthInPx: () => widget.minContentWidthInPx.get()
      };
      this.editor.addOverlayWidget(w);
      const d = autorun((reader) => {
        widget.position.read(reader);
        widget.minContentWidthInPx.read(reader);
        this.editor.layoutOverlayWidget(w);
      });
      return toDisposable(() => {
        d.dispose();
        this.editor.removeOverlayWidget(w);
      });
    }
    createContentWidget(widget) {
      const contentWidgetId = "observableContentWidget" + this._widgetCounter++;
      const w = {
        getDomNode: () => widget.domNode,
        getPosition: () => widget.position.get(),
        getId: () => contentWidgetId,
        allowEditorOverflow: widget.allowEditorOverflow
      };
      this.editor.addContentWidget(w);
      const d = autorun((reader) => {
        widget.position.read(reader);
        this.editor.layoutContentWidget(w);
      });
      return toDisposable(() => {
        d.dispose();
        this.editor.removeContentWidget(w);
      });
    }
    observeLineOffsetRange(lineRange, store) {
      const start = this.observePosition(lineRange.map((r) => new Position$1(r.startLineNumber, 1)), store);
      const end = this.observePosition(lineRange.map((r) => new Position$1(r.endLineNumberExclusive + 1, 1)), store);
      return derived((reader) => {
        start.read(reader);
        end.read(reader);
        const range2 = lineRange.read(reader);
        const lineCount = this.model.read(reader)?.getLineCount();
        const s = (typeof lineCount !== "undefined" && range2.startLineNumber > lineCount ? this.editor.getBottomForLineNumber(lineCount) : this.editor.getTopForLineNumber(range2.startLineNumber)) - this.scrollTop.read(reader);
        const e = range2.isEmpty ? s : this.editor.getBottomForLineNumber(range2.endLineNumberExclusive - 1) - this.scrollTop.read(reader);
        return new OffsetRange(s, e);
      });
    }
    observePosition(position, store) {
      let pos = position.get();
      const result = observableValueOpts({ owner: this, debugName: () => `topLeftOfPosition${pos?.toString()}`, equalsFn: equalsIfDefined(Point.equals) }, new Point(0, 0));
      const contentWidgetId = `observablePositionWidget` + this._widgetCounter++;
      const domNode = document.createElement("div");
      const w = {
        getDomNode: () => domNode,
        getPosition: () => {
          return pos ? { preference: [
            0
            /* ContentWidgetPositionPreference.EXACT */
          ], position: position.get() } : null;
        },
        getId: () => contentWidgetId,
        allowEditorOverflow: false,
        afterRender: (position2, coordinate) => {
          const model = this._model.get();
          if (model && pos && pos.lineNumber > model.getLineCount()) {
            result.set(new Point(0, this.editor.getBottomForLineNumber(model.getLineCount()) - this.scrollTop.get()), void 0);
          } else {
            result.set(coordinate ? new Point(coordinate.left, coordinate.top) : null, void 0);
          }
        }
      };
      this.editor.addContentWidget(w);
      store.add(autorun((reader) => {
        pos = position.read(reader);
        this.editor.layoutContentWidget(w);
      }));
      store.add(toDisposable(() => {
        this.editor.removeContentWidget(w);
      }));
      return result;
    }
    isTargetHovered(predicate, store) {
      const isHovered = observableValue("isInjectedTextHovered", false);
      store.add(this.editor.onMouseMove((e) => {
        const val = predicate(e);
        isHovered.set(val, void 0);
      }));
      store.add(this.editor.onMouseLeave((E) => {
        isHovered.set(false, void 0);
      }));
      return isHovered;
    }
    observeLineHeightForPosition(position) {
      return derived((reader) => {
        const pos = position instanceof Position$1 ? position : position.read(reader);
        if (pos === null) {
          return null;
        }
        this.getOption(
          75
          /* EditorOption.lineHeight */
        ).read(reader);
        return this.editor.getLineHeightForPosition(pos);
      });
    }
    observeLineHeightForLine(lineNumber) {
      if (typeof lineNumber === "number") {
        return this.observeLineHeightForPosition(new Position$1(lineNumber, 1));
      }
      return derived((reader) => {
        const line = lineNumber.read(reader);
        if (line === null) {
          return null;
        }
        return this.observeLineHeightForPosition(new Position$1(line, 1)).read(reader);
      });
    }
    observeLineHeightsForLineRange(lineNumber) {
      return derived((reader) => {
        const range2 = lineNumber instanceof LineRange ? lineNumber : lineNumber.read(reader);
        const heights = [];
        for (let i2 = range2.startLineNumber; i2 < range2.endLineNumberExclusive; i2++) {
          heights.push(this.observeLineHeightForLine(i2).read(reader));
        }
        return heights;
      });
    }
  };
  _ObservableCodeEditor._map = /* @__PURE__ */ new Map();
  let ObservableCodeEditor = _ObservableCodeEditor;
  var __decorate$2D = 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$2A = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  var OverviewRulerFeature_1;
  let OverviewRulerFeature = (_m = class extends Disposable {
    constructor(_editors, _rootElement, _diffModel, _rootWidth, _rootHeight, _modifiedEditorLayoutInfo, _themeService) {
      super();
      this._editors = _editors;
      this._rootElement = _rootElement;
      this._diffModel = _diffModel;
      this._rootWidth = _rootWidth;
      this._rootHeight = _rootHeight;
      this._modifiedEditorLayoutInfo = _modifiedEditorLayoutInfo;
      this._themeService = _themeService;
      this.width = OverviewRulerFeature_1.ENTIRE_DIFF_OVERVIEW_WIDTH;
      const currentColorTheme = observableFromEvent(this._themeService.onDidColorThemeChange, () => this._themeService.getColorTheme());
      const currentColors = derived((reader) => {
        const theme = currentColorTheme.read(reader);
        const insertColor = theme.getColor(diffOverviewRulerInserted) || (theme.getColor(diffInserted) || defaultInsertColor).transparent(2);
        const removeColor = theme.getColor(diffOverviewRulerRemoved) || (theme.getColor(diffRemoved) || defaultRemoveColor).transparent(2);
        return { insertColor, removeColor };
      });
      const viewportDomElement = createFastDomNode(document.createElement("div"));
      viewportDomElement.setClassName("diffViewport");
      viewportDomElement.setPosition("absolute");
      const diffOverviewRoot = h("div.diffOverview", {
        style: { position: "absolute", top: "0px", width: OverviewRulerFeature_1.ENTIRE_DIFF_OVERVIEW_WIDTH + "px" }
      }).root;
      this._register(appendRemoveOnDispose(diffOverviewRoot, viewportDomElement.domNode));
      this._register(addStandardDisposableListener(diffOverviewRoot, EventType$1.POINTER_DOWN, (e) => {
        this._editors.modified.delegateVerticalScrollbarPointerDown(e);
      }));
      this._register(addDisposableListener(diffOverviewRoot, EventType$1.MOUSE_WHEEL, (e) => {
        this._editors.modified.delegateScrollFromMouseWheelEvent(e);
      }, { passive: false }));
      this._register(appendRemoveOnDispose(this._rootElement, diffOverviewRoot));
      this._register(autorunWithStore((reader, store) => {
        const m = this._diffModel.read(reader);
        const originalOverviewRuler = this._editors.original.createOverviewRuler("original diffOverviewRuler");
        if (originalOverviewRuler) {
          store.add(originalOverviewRuler);
          store.add(appendRemoveOnDispose(diffOverviewRoot, originalOverviewRuler.getDomNode()));
        }
        const modifiedOverviewRuler = this._editors.modified.createOverviewRuler("modified diffOverviewRuler");
        if (modifiedOverviewRuler) {
          store.add(modifiedOverviewRuler);
          store.add(appendRemoveOnDispose(diffOverviewRoot, modifiedOverviewRuler.getDomNode()));
        }
        if (!originalOverviewRuler || !modifiedOverviewRuler) {
          return;
        }
        const origViewZonesChanged = observableSignalFromEvent("viewZoneChanged", this._editors.original.onDidChangeViewZones);
        const modViewZonesChanged = observableSignalFromEvent("viewZoneChanged", this._editors.modified.onDidChangeViewZones);
        const origHiddenRangesChanged = observableSignalFromEvent("hiddenRangesChanged", this._editors.original.onDidChangeHiddenAreas);
        const modHiddenRangesChanged = observableSignalFromEvent("hiddenRangesChanged", this._editors.modified.onDidChangeHiddenAreas);
        store.add(autorun((reader2) => {
          origViewZonesChanged.read(reader2);
          modViewZonesChanged.read(reader2);
          origHiddenRangesChanged.read(reader2);
          modHiddenRangesChanged.read(reader2);
          const colors = currentColors.read(reader2);
          const diff = m?.diff.read(reader2)?.mappings;
          function createZones(ranges, color, editor2) {
            const vm = editor2._getViewModel();
            if (!vm) {
              return [];
            }
            return ranges.filter((d) => d.length > 0).map((r) => {
              const start = vm.coordinatesConverter.convertModelPositionToViewPosition(new Position$1(r.startLineNumber, 1));
              const end = vm.coordinatesConverter.convertModelPositionToViewPosition(new Position$1(r.endLineNumberExclusive, 1));
              const lineCount = end.lineNumber - start.lineNumber;
              return new OverviewRulerZone(start.lineNumber, end.lineNumber, lineCount, color.toString());
            });
          }
          const originalZones = createZones((diff || []).map((d) => d.lineRangeMapping.original), colors.removeColor, this._editors.original);
          const modifiedZones = createZones((diff || []).map((d) => d.lineRangeMapping.modified), colors.insertColor, this._editors.modified);
          originalOverviewRuler?.setZones(originalZones);
          modifiedOverviewRuler?.setZones(modifiedZones);
        }));
        store.add(autorun((reader2) => {
          const height = this._rootHeight.read(reader2);
          const width2 = this._rootWidth.read(reader2);
          const layoutInfo = this._modifiedEditorLayoutInfo.read(reader2);
          if (layoutInfo) {
            const freeSpace = OverviewRulerFeature_1.ENTIRE_DIFF_OVERVIEW_WIDTH - 2 * OverviewRulerFeature_1.ONE_OVERVIEW_WIDTH;
            originalOverviewRuler.setLayout({
              top: 0,
              height,
              right: freeSpace + OverviewRulerFeature_1.ONE_OVERVIEW_WIDTH,
              width: OverviewRulerFeature_1.ONE_OVERVIEW_WIDTH
            });
            modifiedOverviewRuler.setLayout({
              top: 0,
              height,
              right: 0,
              width: OverviewRulerFeature_1.ONE_OVERVIEW_WIDTH
            });
            const scrollTop = this._editors.modifiedScrollTop.read(reader2);
            const scrollHeight = this._editors.modifiedScrollHeight.read(reader2);
            const scrollBarOptions = this._editors.modified.getOption(
              117
              /* EditorOption.scrollbar */
            );
            const state = new ScrollbarState(scrollBarOptions.verticalHasArrows ? scrollBarOptions.arrowSize : 0, scrollBarOptions.verticalScrollbarSize, 0, layoutInfo.height, scrollHeight, scrollTop);
            viewportDomElement.setTop(state.getSliderPosition());
            viewportDomElement.setHeight(state.getSliderSize());
          } else {
            viewportDomElement.setTop(0);
            viewportDomElement.setHeight(0);
          }
          diffOverviewRoot.style.height = height + "px";
          diffOverviewRoot.style.left = width2 - OverviewRulerFeature_1.ENTIRE_DIFF_OVERVIEW_WIDTH + "px";
          viewportDomElement.setWidth(OverviewRulerFeature_1.ENTIRE_DIFF_OVERVIEW_WIDTH);
        }));
      }));
    }
  }, OverviewRulerFeature_1 = _m, _m.ONE_OVERVIEW_WIDTH = 15, _m.ENTIRE_DIFF_OVERVIEW_WIDTH = _m.ONE_OVERVIEW_WIDTH * 2, _m);
  OverviewRulerFeature = OverviewRulerFeature_1 = __decorate$2D([
    __param$2A(6, IThemeService)
  ], OverviewRulerFeature);
  var __decorate$2C = 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);
    };
  };
  let DiffEditorEditors = class DiffEditorEditors extends Disposable {
    get onDidContentSizeChange() {
      return this._onDidContentSizeChange.event;
    }
    constructor(originalEditorElement, modifiedEditorElement, _options, _argCodeEditorWidgetOptions, _createInnerEditor, _contextKeyService, _instantiationService, _keybindingService) {
      super();
      this.originalEditorElement = originalEditorElement;
      this.modifiedEditorElement = modifiedEditorElement;
      this._options = _options;
      this._argCodeEditorWidgetOptions = _argCodeEditorWidgetOptions;
      this._createInnerEditor = _createInnerEditor;
      this._contextKeyService = _contextKeyService;
      this._instantiationService = _instantiationService;
      this._keybindingService = _keybindingService;
      this.original = this._register(this._createLeftHandSideEditor(this._options.editorOptions.get(), this._argCodeEditorWidgetOptions.originalEditor || {}));
      this.modified = this._register(this._createRightHandSideEditor(this._options.editorOptions.get(), this._argCodeEditorWidgetOptions.modifiedEditor || {}));
      this._onDidContentSizeChange = this._register(new Emitter$1());
      this.modifiedScrollTop = observableFromEvent(this, this.modified.onDidScrollChange, () => (
        /** @description modified.getScrollTop */
        this.modified.getScrollTop()
      ));
      this.modifiedScrollHeight = observableFromEvent(this, this.modified.onDidScrollChange, () => (
        /** @description modified.getScrollHeight */
        this.modified.getScrollHeight()
      ));
      this.modifiedObs = observableCodeEditor(this.modified);
      this.originalObs = observableCodeEditor(this.original);
      this.modifiedModel = this.modifiedObs.model;
      this.modifiedSelections = observableFromEvent(this, this.modified.onDidChangeCursorSelection, () => this.modified.getSelections() ?? []);
      this.modifiedCursor = derivedOpts({ owner: this, equalsFn: Position$1.equals }, (reader) => this.modifiedSelections.read(reader)[0]?.getPosition() ?? new Position$1(1, 1));
      this.originalCursor = observableFromEvent(this, this.original.onDidChangeCursorPosition, () => this.original.getPosition() ?? new Position$1(1, 1));
      this.isOriginalFocused = observableCodeEditor(this.original).isFocused;
      this.isModifiedFocused = observableCodeEditor(this.modified).isFocused;
      this.isFocused = derived(this, (reader) => this.isOriginalFocused.read(reader) || this.isModifiedFocused.read(reader));
      this._argCodeEditorWidgetOptions = null;
      this._register(autorunHandleChanges({
        changeTracker: {
          createChangeSummary: () => ({}),
          handleChange: (ctx, changeSummary) => {
            if (ctx.didChange(_options.editorOptions)) {
              Object.assign(changeSummary, ctx.change.changedOptions);
            }
            return true;
          }
        }
      }, (reader, changeSummary) => {
        _options.editorOptions.read(reader);
        this._options.renderSideBySide.read(reader);
        this.modified.updateOptions(this._adjustOptionsForRightHandSide(reader, changeSummary));
        this.original.updateOptions(this._adjustOptionsForLeftHandSide(reader, changeSummary));
      }));
    }
    _createLeftHandSideEditor(options, codeEditorWidgetOptions) {
      const leftHandSideOptions = this._adjustOptionsForLeftHandSide(void 0, options);
      const editor2 = this._constructInnerEditor(this._instantiationService, this.originalEditorElement, leftHandSideOptions, codeEditorWidgetOptions);
      const isInDiffLeftEditorKey = this._contextKeyService.createKey("isInDiffLeftEditor", editor2.hasWidgetFocus());
      this._register(editor2.onDidFocusEditorWidget(() => isInDiffLeftEditorKey.set(true)));
      this._register(editor2.onDidBlurEditorWidget(() => isInDiffLeftEditorKey.set(false)));
      return editor2;
    }
    _createRightHandSideEditor(options, codeEditorWidgetOptions) {
      const rightHandSideOptions = this._adjustOptionsForRightHandSide(void 0, options);
      const editor2 = this._constructInnerEditor(this._instantiationService, this.modifiedEditorElement, rightHandSideOptions, codeEditorWidgetOptions);
      const isInDiffRightEditorKey = this._contextKeyService.createKey("isInDiffRightEditor", editor2.hasWidgetFocus());
      this._register(editor2.onDidFocusEditorWidget(() => isInDiffRightEditorKey.set(true)));
      this._register(editor2.onDidBlurEditorWidget(() => isInDiffRightEditorKey.set(false)));
      return editor2;
    }
    _constructInnerEditor(instantiationService, container, options, editorWidgetOptions) {
      const editor2 = this._createInnerEditor(instantiationService, container, options, editorWidgetOptions);
      this._register(editor2.onDidContentSizeChange((e) => {
        const width2 = this.original.getContentWidth() + this.modified.getContentWidth() + OverviewRulerFeature.ENTIRE_DIFF_OVERVIEW_WIDTH;
        const height = Math.max(this.modified.getContentHeight(), this.original.getContentHeight());
        this._onDidContentSizeChange.fire({
          contentHeight: height,
          contentWidth: width2,
          contentHeightChanged: e.contentHeightChanged,
          contentWidthChanged: e.contentWidthChanged
        });
      }));
      return editor2;
    }
    _adjustOptionsForLeftHandSide(_reader, changedOptions) {
      const result = this._adjustOptionsForSubEditor(changedOptions);
      if (!this._options.renderSideBySide.get()) {
        result.wordWrapOverride1 = "off";
        result.wordWrapOverride2 = "off";
        result.stickyScroll = { enabled: false };
        result.unicodeHighlight = { nonBasicASCII: false, ambiguousCharacters: false, invisibleCharacters: false };
      } else {
        result.unicodeHighlight = this._options.editorOptions.get().unicodeHighlight || {};
        result.wordWrapOverride1 = this._options.diffWordWrap.get();
      }
      result.glyphMargin = this._options.renderSideBySide.get();
      if (changedOptions.originalAriaLabel) {
        result.ariaLabel = changedOptions.originalAriaLabel;
      }
      result.ariaLabel = this._updateAriaLabel(result.ariaLabel);
      result.readOnly = !this._options.originalEditable.get();
      result.dropIntoEditor = { enabled: !result.readOnly };
      result.extraEditorClassName = "original-in-monaco-diff-editor";
      return result;
    }
    _adjustOptionsForRightHandSide(reader, changedOptions) {
      const result = this._adjustOptionsForSubEditor(changedOptions);
      if (changedOptions.modifiedAriaLabel) {
        result.ariaLabel = changedOptions.modifiedAriaLabel;
      }
      result.ariaLabel = this._updateAriaLabel(result.ariaLabel);
      result.wordWrapOverride1 = this._options.diffWordWrap.get();
      result.revealHorizontalRightPadding = EditorOptions.revealHorizontalRightPadding.defaultValue + OverviewRulerFeature.ENTIRE_DIFF_OVERVIEW_WIDTH;
      result.scrollbar.verticalHasArrows = false;
      result.extraEditorClassName = "modified-in-monaco-diff-editor";
      return result;
    }
    _adjustOptionsForSubEditor(options) {
      const clonedOptions = {
        ...options,
        dimension: {
          height: 0,
          width: 0
        }
      };
      clonedOptions.inDiffEditor = true;
      clonedOptions.automaticLayout = false;
      clonedOptions.allowVariableLineHeights = false;
      clonedOptions.allowVariableFonts = false;
      clonedOptions.allowVariableFontsInAccessibilityMode = false;
      clonedOptions.scrollbar = { ...clonedOptions.scrollbar || {} };
      clonedOptions.folding = false;
      clonedOptions.codeLens = this._options.diffCodeLens.get();
      clonedOptions.fixedOverflowWidgets = true;
      clonedOptions.minimap = { ...clonedOptions.minimap || {} };
      clonedOptions.minimap.enabled = false;
      if (this._options.hideUnchangedRegions.get()) {
        clonedOptions.stickyScroll = { enabled: false };
      } else {
        clonedOptions.stickyScroll = this._options.editorOptions.get().stickyScroll;
      }
      return clonedOptions;
    }
    _updateAriaLabel(ariaLabel) {
      if (!ariaLabel) {
        ariaLabel = "";
      }
      const ariaNavigationTip = localize(111, " use {0} to open the accessibility help.", this._keybindingService.lookupKeybinding("editor.action.accessibilityHelp")?.getAriaLabel());
      if (this._options.accessibilityVerbose.get()) {
        return ariaLabel + ariaNavigationTip;
      } else if (ariaLabel) {
        return ariaLabel.replaceAll(ariaNavigationTip, "");
      }
      return "";
    }
  };
  DiffEditorEditors = __decorate$2C([
    __param$2z(5, IContextKeyService),
    __param$2z(6, IInstantiationService),
    __param$2z(7, IKeybindingService)
  ], DiffEditorEditors);
  var __decorate$2B = 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;
  };
  const DEBUG = false;
  var OrthogonalEdge;
  (function(OrthogonalEdge2) {
    OrthogonalEdge2["North"] = "north";
    OrthogonalEdge2["South"] = "south";
    OrthogonalEdge2["East"] = "east";
    OrthogonalEdge2["West"] = "west";
  })(OrthogonalEdge || (OrthogonalEdge = {}));
  let globalSize = 4;
  const onDidChangeGlobalSize = new Emitter$1();
  let globalHoverDelay = 300;
  const onDidChangeHoverDelay = new Emitter$1();
  class MouseEventFactory {
    constructor(el) {
      this.el = el;
      this.disposables = new DisposableStore();
    }
    get onPointerMove() {
      return this.disposables.add(new DomEmitter(getWindow(this.el), "mousemove")).event;
    }
    get onPointerUp() {
      return this.disposables.add(new DomEmitter(getWindow(this.el), "mouseup")).event;
    }
    dispose() {
      this.disposables.dispose();
    }
  }
  __decorate$2B([
    memoize
  ], MouseEventFactory.prototype, "onPointerMove", null);
  __decorate$2B([
    memoize
  ], MouseEventFactory.prototype, "onPointerUp", null);
  class GestureEventFactory {
    get onPointerMove() {
      return this.disposables.add(new DomEmitter(this.el, EventType.Change)).event;
    }
    get onPointerUp() {
      return this.disposables.add(new DomEmitter(this.el, EventType.End)).event;
    }
    constructor(el) {
      this.el = el;
      this.disposables = new DisposableStore();
    }
    dispose() {
      this.disposables.dispose();
    }
  }
  __decorate$2B([
    memoize
  ], GestureEventFactory.prototype, "onPointerMove", null);
  __decorate$2B([
    memoize
  ], GestureEventFactory.prototype, "onPointerUp", null);
  class OrthogonalPointerEventFactory {
    get onPointerMove() {
      return this.factory.onPointerMove;
    }
    get onPointerUp() {
      return this.factory.onPointerUp;
    }
    constructor(factory) {
      this.factory = factory;
    }
    dispose() {
    }
  }
  __decorate$2B([
    memoize
  ], OrthogonalPointerEventFactory.prototype, "onPointerMove", null);
  __decorate$2B([
    memoize
  ], OrthogonalPointerEventFactory.prototype, "onPointerUp", null);
  const PointerEventsDisabledCssClass = "pointer-events-disabled";
  class Sash extends Disposable {
    get state() {
      return this._state;
    }
    get orthogonalStartSash() {
      return this._orthogonalStartSash;
    }
    get orthogonalEndSash() {
      return this._orthogonalEndSash;
    }
    /**
     * The state of a sash defines whether it can be interacted with by the user
     * as well as what mouse cursor to use, when hovered.
     */
    set state(state) {
      if (this._state === state) {
        return;
      }
      this.el.classList.toggle(
        "disabled",
        state === 0
        /* SashState.Disabled */
      );
      this.el.classList.toggle(
        "minimum",
        state === 1
        /* SashState.AtMinimum */
      );
      this.el.classList.toggle(
        "maximum",
        state === 2
        /* SashState.AtMaximum */
      );
      this._state = state;
      this.onDidEnablementChange.fire(state);
    }
    /**
     * An event which fires whenever the user starts dragging this sash.
     */
    get onDidStart() {
      return this._onDidStart.event;
    }
    /**
     * An event which fires whenever the user moves the mouse while
     * dragging this sash.
     */
    get onDidChange() {
      return this._onDidChange.event;
    }
    /**
     * An event which fires whenever the user double clicks this sash.
     */
    get onDidReset() {
      return this._onDidReset.event;
    }
    /**
     * An event which fires whenever the user stops dragging this sash.
     */
    get onDidEnd() {
      return this._onDidEnd.event;
    }
    /**
     * A reference to another sash, perpendicular to this one, which
     * aligns at the start of this one. A corner sash will be created
     * automatically at that location.
     *
     * The start of a horizontal sash is its left-most position.
     * The start of a vertical sash is its top-most position.
     */
    set orthogonalStartSash(sash) {
      if (this._orthogonalStartSash === sash) {
        return;
      }
      this.orthogonalStartDragHandleDisposables.clear();
      this.orthogonalStartSashDisposables.clear();
      if (sash) {
        const onChange = (state) => {
          this.orthogonalStartDragHandleDisposables.clear();
          if (state !== 0) {
            this._orthogonalStartDragHandle = append$2(this.el, $$l(".orthogonal-drag-handle.start"));
            this.orthogonalStartDragHandleDisposables.add(toDisposable(() => this._orthogonalStartDragHandle.remove()));
            this.orthogonalStartDragHandleDisposables.add(addDisposableListener(this._orthogonalStartDragHandle, "mouseenter", () => Sash.onMouseEnter(sash)));
            this.orthogonalStartDragHandleDisposables.add(addDisposableListener(this._orthogonalStartDragHandle, "mouseleave", () => Sash.onMouseLeave(sash)));
          }
        };
        this.orthogonalStartSashDisposables.add(sash.onDidEnablementChange.event(onChange, this));
        onChange(sash.state);
      }
      this._orthogonalStartSash = sash;
    }
    /**
     * A reference to another sash, perpendicular to this one, which
     * aligns at the end of this one. A corner sash will be created
     * automatically at that location.
     *
     * The end of a horizontal sash is its right-most position.
     * The end of a vertical sash is its bottom-most position.
     */
    set orthogonalEndSash(sash) {
      if (this._orthogonalEndSash === sash) {
        return;
      }
      this.orthogonalEndDragHandleDisposables.clear();
      this.orthogonalEndSashDisposables.clear();
      if (sash) {
        const onChange = (state) => {
          this.orthogonalEndDragHandleDisposables.clear();
          if (state !== 0) {
            this._orthogonalEndDragHandle = append$2(this.el, $$l(".orthogonal-drag-handle.end"));
            this.orthogonalEndDragHandleDisposables.add(toDisposable(() => this._orthogonalEndDragHandle.remove()));
            this.orthogonalEndDragHandleDisposables.add(addDisposableListener(this._orthogonalEndDragHandle, "mouseenter", () => Sash.onMouseEnter(sash)));
            this.orthogonalEndDragHandleDisposables.add(addDisposableListener(this._orthogonalEndDragHandle, "mouseleave", () => Sash.onMouseLeave(sash)));
          }
        };
        this.orthogonalEndSashDisposables.add(sash.onDidEnablementChange.event(onChange, this));
        onChange(sash.state);
      }
      this._orthogonalEndSash = sash;
    }
    constructor(container, layoutProvider, options) {
      super();
      this.hoverDelay = globalHoverDelay;
      this.hoverDelayer = this._register(new Delayer(this.hoverDelay));
      this._state = 3;
      this.onDidEnablementChange = this._register(new Emitter$1());
      this._onDidStart = this._register(new Emitter$1());
      this._onDidChange = this._register(new Emitter$1());
      this._onDidReset = this._register(new Emitter$1());
      this._onDidEnd = this._register(new Emitter$1());
      this.orthogonalStartSashDisposables = this._register(new DisposableStore());
      this.orthogonalStartDragHandleDisposables = this._register(new DisposableStore());
      this.orthogonalEndSashDisposables = this._register(new DisposableStore());
      this.orthogonalEndDragHandleDisposables = this._register(new DisposableStore());
      this.linkedSash = void 0;
      this.el = append$2(container, $$l(".monaco-sash"));
      if (options.orthogonalEdge) {
        this.el.classList.add(`orthogonal-edge-${options.orthogonalEdge}`);
      }
      if (isMacintosh) {
        this.el.classList.add("mac");
      }
      this._register(addDisposableListener(this.el, "mousedown", (e) => this.onPointerStart(e, new MouseEventFactory(container))));
      this._register(addDisposableListener(this.el, "dblclick", (e) => this.onPointerDoublePress(e)));
      this._register(addDisposableListener(this.el, "mouseenter", () => Sash.onMouseEnter(this)));
      this._register(addDisposableListener(this.el, "mouseleave", () => Sash.onMouseLeave(this)));
      this._register(Gesture.addTarget(this.el));
      this._register(addDisposableListener(this.el, EventType.Start, (e) => this.onPointerStart(e, new GestureEventFactory(this.el))));
      let doubleTapTimeout = void 0;
      this._register(addDisposableListener(this.el, EventType.Tap, (event) => {
        if (doubleTapTimeout) {
          clearTimeout(doubleTapTimeout);
          doubleTapTimeout = void 0;
          this.onPointerDoublePress(event);
          return;
        }
        clearTimeout(doubleTapTimeout);
        doubleTapTimeout = setTimeout(() => doubleTapTimeout = void 0, 250);
      }));
      if (typeof options.size === "number") {
        this.size = options.size;
        if (options.orientation === 0) {
          this.el.style.width = `${this.size}px`;
        } else {
          this.el.style.height = `${this.size}px`;
        }
      } else {
        this.size = globalSize;
        this._register(onDidChangeGlobalSize.event((size2) => {
          this.size = size2;
          this.layout();
        }));
      }
      this._register(onDidChangeHoverDelay.event((delay) => this.hoverDelay = delay));
      this.layoutProvider = layoutProvider;
      this.orthogonalStartSash = options.orthogonalStartSash;
      this.orthogonalEndSash = options.orthogonalEndSash;
      this.orientation = options.orientation || 0;
      if (this.orientation === 1) {
        this.el.classList.add("horizontal");
        this.el.classList.remove("vertical");
      } else {
        this.el.classList.remove("horizontal");
        this.el.classList.add("vertical");
      }
      this.el.classList.toggle("debug", DEBUG);
      this.layout();
    }
    onPointerStart(event, pointerEventFactory) {
      EventHelper.stop(event);
      let isMultisashResize = false;
      if (!event.__orthogonalSashEvent) {
        const orthogonalSash = this.getOrthogonalSash(event);
        if (orthogonalSash) {
          isMultisashResize = true;
          event.__orthogonalSashEvent = true;
          orthogonalSash.onPointerStart(event, new OrthogonalPointerEventFactory(pointerEventFactory));
        }
      }
      if (this.linkedSash && !event.__linkedSashEvent) {
        event.__linkedSashEvent = true;
        this.linkedSash.onPointerStart(event, new OrthogonalPointerEventFactory(pointerEventFactory));
      }
      if (!this.state) {
        return;
      }
      const iframes = this.el.ownerDocument.getElementsByTagName("iframe");
      for (const iframe of iframes) {
        iframe.classList.add(PointerEventsDisabledCssClass);
      }
      const startX = event.pageX;
      const startY = event.pageY;
      const altKey = event.altKey;
      const startEvent = { startX, currentX: startX, startY, currentY: startY, altKey };
      this.el.classList.add("active");
      this._onDidStart.fire(startEvent);
      const style = createStyleSheet(this.el);
      const updateStyle = () => {
        let cursor = "";
        if (isMultisashResize) {
          cursor = "all-scroll";
        } else if (this.orientation === 1) {
          if (this.state === 1) {
            cursor = "s-resize";
          } else if (this.state === 2) {
            cursor = "n-resize";
          } else {
            cursor = isMacintosh ? "row-resize" : "ns-resize";
          }
        } else {
          if (this.state === 1) {
            cursor = "e-resize";
          } else if (this.state === 2) {
            cursor = "w-resize";
          } else {
            cursor = isMacintosh ? "col-resize" : "ew-resize";
          }
        }
        style.textContent = `* { cursor: ${cursor} !important; }`;
      };
      const disposables = new DisposableStore();
      updateStyle();
      if (!isMultisashResize) {
        this.onDidEnablementChange.event(updateStyle, null, disposables);
      }
      const onPointerMove = (e) => {
        EventHelper.stop(e, false);
        const event2 = { startX, currentX: e.pageX, startY, currentY: e.pageY, altKey };
        this._onDidChange.fire(event2);
      };
      const onPointerUp = (e) => {
        EventHelper.stop(e, false);
        style.remove();
        this.el.classList.remove("active");
        this._onDidEnd.fire();
        disposables.dispose();
        for (const iframe of iframes) {
          iframe.classList.remove(PointerEventsDisabledCssClass);
        }
      };
      pointerEventFactory.onPointerMove(onPointerMove, null, disposables);
      pointerEventFactory.onPointerUp(onPointerUp, null, disposables);
      disposables.add(pointerEventFactory);
    }
    onPointerDoublePress(e) {
      const orthogonalSash = this.getOrthogonalSash(e);
      if (orthogonalSash) {
        orthogonalSash._onDidReset.fire();
      }
      if (this.linkedSash) {
        this.linkedSash._onDidReset.fire();
      }
      this._onDidReset.fire();
    }
    static onMouseEnter(sash, fromLinkedSash = false) {
      if (sash.el.classList.contains("active")) {
        sash.hoverDelayer.cancel();
        sash.el.classList.add("hover");
      } else {
        sash.hoverDelayer.trigger(() => sash.el.classList.add("hover"), sash.hoverDelay).then(void 0, () => {
        });
      }
      if (!fromLinkedSash && sash.linkedSash) {
        Sash.onMouseEnter(sash.linkedSash, true);
      }
    }
    static onMouseLeave(sash, fromLinkedSash = false) {
      sash.hoverDelayer.cancel();
      sash.el.classList.remove("hover");
      if (!fromLinkedSash && sash.linkedSash) {
        Sash.onMouseLeave(sash.linkedSash, true);
      }
    }
    /**
     * Forcefully stop any user interactions with this sash.
     * Useful when hiding a parent component, while the user is still
     * interacting with the sash.
     */
    clearSashHoverState() {
      Sash.onMouseLeave(this);
    }
    /**
     * Layout the sash. The sash will size and position itself
     * based on its provided {@link ISashLayoutProvider layout provider}.
     */
    layout() {
      if (this.orientation === 0) {
        const verticalProvider = this.layoutProvider;
        this.el.style.left = verticalProvider.getVerticalSashLeft(this) - this.size / 2 + "px";
        if (verticalProvider.getVerticalSashTop) {
          this.el.style.top = verticalProvider.getVerticalSashTop(this) + "px";
        }
        if (verticalProvider.getVerticalSashHeight) {
          this.el.style.height = verticalProvider.getVerticalSashHeight(this) + "px";
        }
      } else {
        const horizontalProvider = this.layoutProvider;
        this.el.style.top = horizontalProvider.getHorizontalSashTop(this) - this.size / 2 + "px";
        if (horizontalProvider.getHorizontalSashLeft) {
          this.el.style.left = horizontalProvider.getHorizontalSashLeft(this) + "px";
        }
        if (horizontalProvider.getHorizontalSashWidth) {
          this.el.style.width = horizontalProvider.getHorizontalSashWidth(this) + "px";
        }
      }
    }
    getOrthogonalSash(e) {
      const target = e.initialTarget ?? e.target;
      if (!target || !isHTMLElement(target)) {
        return void 0;
      }
      if (target.classList.contains("orthogonal-drag-handle")) {
        return target.classList.contains("start") ? this.orthogonalStartSash : this.orthogonalEndSash;
      }
      return void 0;
    }
    dispose() {
      super.dispose();
      this.el.remove();
    }
  }
  class SashLayout {
    resetSash() {
      this._sashRatio.set(void 0, void 0);
    }
    constructor(_options, dimensions) {
      this._options = _options;
      this.dimensions = dimensions;
      this.sashLeft = derivedWithSetter(this, (reader) => {
        const ratio = this._sashRatio.read(reader) ?? this._options.splitViewDefaultRatio.read(reader);
        return this._computeSashLeft(ratio, reader);
      }, (value, tx) => {
        const contentWidth = this.dimensions.width.get();
        this._sashRatio.set(value / contentWidth, tx);
      });
      this._sashRatio = observableValue(this, void 0);
    }
    /** @pure */
    _computeSashLeft(desiredRatio, reader) {
      const contentWidth = this.dimensions.width.read(reader);
      const midPoint = Math.floor(this._options.splitViewDefaultRatio.read(reader) * contentWidth);
      const sashLeft = this._options.enableSplitViewResizing.read(reader) ? Math.floor(desiredRatio * contentWidth) : midPoint;
      const MINIMUM_EDITOR_WIDTH = 100;
      if (contentWidth <= MINIMUM_EDITOR_WIDTH * 2) {
        return midPoint;
      }
      if (sashLeft < MINIMUM_EDITOR_WIDTH) {
        return MINIMUM_EDITOR_WIDTH;
      }
      if (sashLeft > contentWidth - MINIMUM_EDITOR_WIDTH) {
        return contentWidth - MINIMUM_EDITOR_WIDTH;
      }
      return sashLeft;
    }
  }
  class DiffEditorSash extends Disposable {
    constructor(_domNode, _dimensions, _enabled, _boundarySashes, sashLeft, _resetSash) {
      super();
      this._domNode = _domNode;
      this._dimensions = _dimensions;
      this._enabled = _enabled;
      this._boundarySashes = _boundarySashes;
      this.sashLeft = sashLeft;
      this._resetSash = _resetSash;
      this._sash = this._register(new Sash(this._domNode, {
        getVerticalSashTop: (_sash) => 0,
        getVerticalSashLeft: (_sash) => this.sashLeft.get(),
        getVerticalSashHeight: (_sash) => this._dimensions.height.get()
      }, {
        orientation: 0
        /* Orientation.VERTICAL */
      }));
      this._startSashPosition = void 0;
      this._register(this._sash.onDidStart(() => {
        this._startSashPosition = this.sashLeft.get();
      }));
      this._register(this._sash.onDidChange((e) => {
        this.sashLeft.set(this._startSashPosition + (e.currentX - e.startX), void 0);
      }));
      this._register(this._sash.onDidEnd(() => this._sash.layout()));
      this._register(this._sash.onDidReset(() => this._resetSash()));
      this._register(autorun((reader) => {
        const sashes = this._boundarySashes.read(reader);
        if (sashes) {
          this._sash.orthogonalEndSash = sashes.bottom;
        }
      }));
      this._register(autorun((reader) => {
        const enabled = this._enabled.read(reader);
        this._sash.state = enabled ? 3 : 0;
        this.sashLeft.read(reader);
        this._dimensions.height.read(reader);
        this._sash.layout();
      }));
    }
  }
  const _DelegatingEditor = class _DelegatingEditor extends Disposable {
    constructor() {
      super(...arguments);
      this._id = ++_DelegatingEditor.idCounter;
      this._onDidDispose = this._register(new Emitter$1());
      this.onDidDispose = this._onDidDispose.event;
    }
    getId() {
      return this.getEditorType() + ":v2:" + this._id;
    }
    // #region editorBrowser.IDiffEditor: Delegating to modified Editor
    getVisibleColumnFromPosition(position) {
      return this._targetEditor.getVisibleColumnFromPosition(position);
    }
    getPosition() {
      return this._targetEditor.getPosition();
    }
    setPosition(position, source = "api") {
      this._targetEditor.setPosition(position, source);
    }
    revealLine(lineNumber, scrollType = 0) {
      this._targetEditor.revealLine(lineNumber, scrollType);
    }
    revealLineInCenter(lineNumber, scrollType = 0) {
      this._targetEditor.revealLineInCenter(lineNumber, scrollType);
    }
    revealLineInCenterIfOutsideViewport(lineNumber, scrollType = 0) {
      this._targetEditor.revealLineInCenterIfOutsideViewport(lineNumber, scrollType);
    }
    revealLineNearTop(lineNumber, scrollType = 0) {
      this._targetEditor.revealLineNearTop(lineNumber, scrollType);
    }
    revealPosition(position, scrollType = 0) {
      this._targetEditor.revealPosition(position, scrollType);
    }
    revealPositionInCenter(position, scrollType = 0) {
      this._targetEditor.revealPositionInCenter(position, scrollType);
    }
    revealPositionInCenterIfOutsideViewport(position, scrollType = 0) {
      this._targetEditor.revealPositionInCenterIfOutsideViewport(position, scrollType);
    }
    revealPositionNearTop(position, scrollType = 0) {
      this._targetEditor.revealPositionNearTop(position, scrollType);
    }
    getSelection() {
      return this._targetEditor.getSelection();
    }
    getSelections() {
      return this._targetEditor.getSelections();
    }
    setSelection(something, source = "api") {
      this._targetEditor.setSelection(something, source);
    }
    setSelections(ranges, source = "api") {
      this._targetEditor.setSelections(ranges, source);
    }
    revealLines(startLineNumber, endLineNumber, scrollType = 0) {
      this._targetEditor.revealLines(startLineNumber, endLineNumber, scrollType);
    }
    revealLinesInCenter(startLineNumber, endLineNumber, scrollType = 0) {
      this._targetEditor.revealLinesInCenter(startLineNumber, endLineNumber, scrollType);
    }
    revealLinesInCenterIfOutsideViewport(startLineNumber, endLineNumber, scrollType = 0) {
      this._targetEditor.revealLinesInCenterIfOutsideViewport(startLineNumber, endLineNumber, scrollType);
    }
    revealLinesNearTop(startLineNumber, endLineNumber, scrollType = 0) {
      this._targetEditor.revealLinesNearTop(startLineNumber, endLineNumber, scrollType);
    }
    revealRange(range2, scrollType = 0, revealVerticalInCenter = false, revealHorizontal = true) {
      this._targetEditor.revealRange(range2, scrollType, revealVerticalInCenter, revealHorizontal);
    }
    revealRangeInCenter(range2, scrollType = 0) {
      this._targetEditor.revealRangeInCenter(range2, scrollType);
    }
    revealRangeInCenterIfOutsideViewport(range2, scrollType = 0) {
      this._targetEditor.revealRangeInCenterIfOutsideViewport(range2, scrollType);
    }
    revealRangeNearTop(range2, scrollType = 0) {
      this._targetEditor.revealRangeNearTop(range2, scrollType);
    }
    revealRangeNearTopIfOutsideViewport(range2, scrollType = 0) {
      this._targetEditor.revealRangeNearTopIfOutsideViewport(range2, scrollType);
    }
    revealRangeAtTop(range2, scrollType = 0) {
      this._targetEditor.revealRangeAtTop(range2, scrollType);
    }
    getSupportedActions() {
      return this._targetEditor.getSupportedActions();
    }
    focus() {
      this._targetEditor.focus();
    }
    trigger(source, handlerId, payload) {
      this._targetEditor.trigger(source, handlerId, payload);
    }
    createDecorationsCollection(decorations) {
      return this._targetEditor.createDecorationsCollection(decorations);
    }
    changeDecorations(callback) {
      return this._targetEditor.changeDecorations(callback);
    }
  };
  _DelegatingEditor.idCounter = 0;
  let DelegatingEditor = _DelegatingEditor;
  const diffEditorDefaultOptions = {
    enableSplitViewResizing: true,
    renderSideBySide: true,
    renderMarginRevertIcon: true,
    renderGutterMenu: true,
    maxComputationTime: 5e3,
    maxFileSize: 50,
    ignoreTrimWhitespace: true,
    renderIndicators: true,
    originalEditable: false,
    diffCodeLens: false,
    renderOverviewRuler: true,
    diffWordWrap: "inherit",
    diffAlgorithm: "advanced",
    accessibilityVerbose: false,
    experimental: {
      showMoves: false,
      showEmptyDecorations: true,
      useTrueInlineView: false
    },
    hideUnchangedRegions: {
      enabled: false,
      contextLineCount: 3,
      minimumLineCount: 3,
      revealLineCount: 20
    },
    isInEmbeddedEditor: false,
    onlyShowAccessibleDiffViewer: false,
    renderSideBySideInlineBreakpoint: 900,
    useInlineViewWhenSpaceIsLimited: true,
    compactMode: false
  };
  var __decorate$2A = 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);
    };
  };
  let DiffEditorOptions = class DiffEditorOptions {
    get editorOptions() {
      return this._options;
    }
    constructor(options, _accessibilityService) {
      this._accessibilityService = _accessibilityService;
      this._diffEditorWidth = observableValue(this, 0);
      this._screenReaderMode = observableFromEvent(this, this._accessibilityService.onDidChangeScreenReaderOptimized, () => this._accessibilityService.isScreenReaderOptimized());
      this.couldShowInlineViewBecauseOfSize = derived(this, (reader) => this._options.read(reader).renderSideBySide && this._diffEditorWidth.read(reader) <= this._options.read(reader).renderSideBySideInlineBreakpoint);
      this.renderOverviewRuler = derived(this, (reader) => this._options.read(reader).renderOverviewRuler);
      this.renderSideBySide = derived(this, (reader) => {
        if (this.compactMode.read(reader)) {
          if (this.shouldRenderInlineViewInSmartMode.read(reader)) {
            return false;
          }
        }
        return this._options.read(reader).renderSideBySide && !(this._options.read(reader).useInlineViewWhenSpaceIsLimited && this.couldShowInlineViewBecauseOfSize.read(reader) && !this._screenReaderMode.read(reader));
      });
      this.readOnly = derived(this, (reader) => this._options.read(reader).readOnly);
      this.shouldRenderOldRevertArrows = derived(this, (reader) => {
        if (!this._options.read(reader).renderMarginRevertIcon) {
          return false;
        }
        if (!this.renderSideBySide.read(reader)) {
          return false;
        }
        if (this.readOnly.read(reader)) {
          return false;
        }
        if (this.shouldRenderGutterMenu.read(reader)) {
          return false;
        }
        return true;
      });
      this.shouldRenderGutterMenu = derived(this, (reader) => this._options.read(reader).renderGutterMenu);
      this.renderIndicators = derived(this, (reader) => this._options.read(reader).renderIndicators);
      this.enableSplitViewResizing = derived(this, (reader) => this._options.read(reader).enableSplitViewResizing);
      this.splitViewDefaultRatio = derived(this, (reader) => this._options.read(reader).splitViewDefaultRatio);
      this.ignoreTrimWhitespace = derived(this, (reader) => this._options.read(reader).ignoreTrimWhitespace);
      this.maxComputationTimeMs = derived(this, (reader) => this._options.read(reader).maxComputationTime);
      this.showMoves = derived(this, (reader) => this._options.read(reader).experimental.showMoves && this.renderSideBySide.read(reader));
      this.isInEmbeddedEditor = derived(this, (reader) => this._options.read(reader).isInEmbeddedEditor);
      this.diffWordWrap = derived(this, (reader) => this._options.read(reader).diffWordWrap);
      this.originalEditable = derived(this, (reader) => this._options.read(reader).originalEditable);
      this.diffCodeLens = derived(this, (reader) => this._options.read(reader).diffCodeLens);
      this.accessibilityVerbose = derived(this, (reader) => this._options.read(reader).accessibilityVerbose);
      this.diffAlgorithm = derived(this, (reader) => this._options.read(reader).diffAlgorithm);
      this.showEmptyDecorations = derived(this, (reader) => this._options.read(reader).experimental.showEmptyDecorations);
      this.onlyShowAccessibleDiffViewer = derived(this, (reader) => this._options.read(reader).onlyShowAccessibleDiffViewer);
      this.compactMode = derived(this, (reader) => this._options.read(reader).compactMode);
      this.trueInlineDiffRenderingEnabled = derived(this, (reader) => this._options.read(reader).experimental.useTrueInlineView);
      this.useTrueInlineDiffRendering = derived(this, (reader) => !this.renderSideBySide.read(reader) && this.trueInlineDiffRenderingEnabled.read(reader));
      this.hideUnchangedRegions = derived(this, (reader) => this._options.read(reader).hideUnchangedRegions.enabled);
      this.hideUnchangedRegionsRevealLineCount = derived(this, (reader) => this._options.read(reader).hideUnchangedRegions.revealLineCount);
      this.hideUnchangedRegionsContextLineCount = derived(this, (reader) => this._options.read(reader).hideUnchangedRegions.contextLineCount);
      this.hideUnchangedRegionsMinimumLineCount = derived(this, (reader) => this._options.read(reader).hideUnchangedRegions.minimumLineCount);
      this._model = observableValue(this, void 0);
      this.shouldRenderInlineViewInSmartMode = this._model.map(this, (model) => derivedConstOnceDefined(this, (reader) => {
        const diffs = model?.diff.read(reader);
        return diffs ? isSimpleDiff(diffs, this.trueInlineDiffRenderingEnabled.read(reader)) : void 0;
      })).flatten().map(this, (v) => !!v);
      this.inlineViewHideOriginalLineNumbers = this.compactMode;
      const optionsCopy = { ...options, ...validateDiffEditorOptions(options, diffEditorDefaultOptions) };
      this._options = observableValue(this, optionsCopy);
    }
    updateOptions(changedOptions) {
      const newDiffEditorOptions = validateDiffEditorOptions(changedOptions, this._options.get());
      const newOptions = { ...this._options.get(), ...changedOptions, ...newDiffEditorOptions };
      this._options.set(newOptions, void 0, { changedOptions });
    }
    setWidth(width2) {
      this._diffEditorWidth.set(width2, void 0);
    }
    setModel(model) {
      this._model.set(model, void 0);
    }
  };
  DiffEditorOptions = __decorate$2A([
    __param$2y(1, IAccessibilityService)
  ], DiffEditorOptions);
  function isSimpleDiff(diff, supportsTrueDiffRendering) {
    return diff.mappings.every((m) => isInsertion(m.lineRangeMapping) || isDeletion$1(m.lineRangeMapping) || supportsTrueDiffRendering && allowsTrueInlineDiffRendering$1(m.lineRangeMapping));
  }
  function isInsertion(mapping) {
    return mapping.original.length === 0;
  }
  function isDeletion$1(mapping) {
    return mapping.modified.length === 0;
  }
  function validateDiffEditorOptions(options, defaults) {
    return {
      enableSplitViewResizing: boolean(options.enableSplitViewResizing, defaults.enableSplitViewResizing),
      splitViewDefaultRatio: clampedFloat(options.splitViewDefaultRatio, 0.5, 0.1, 0.9),
      renderSideBySide: boolean(options.renderSideBySide, defaults.renderSideBySide),
      renderMarginRevertIcon: boolean(options.renderMarginRevertIcon, defaults.renderMarginRevertIcon),
      maxComputationTime: clampedInt(
        options.maxComputationTime,
        defaults.maxComputationTime,
        0,
        1073741824
        /* Constants.MAX_SAFE_SMALL_INTEGER */
      ),
      maxFileSize: clampedInt(
        options.maxFileSize,
        defaults.maxFileSize,
        0,
        1073741824
        /* Constants.MAX_SAFE_SMALL_INTEGER */
      ),
      ignoreTrimWhitespace: boolean(options.ignoreTrimWhitespace, defaults.ignoreTrimWhitespace),
      renderIndicators: boolean(options.renderIndicators, defaults.renderIndicators),
      originalEditable: boolean(options.originalEditable, defaults.originalEditable),
      diffCodeLens: boolean(options.diffCodeLens, defaults.diffCodeLens),
      renderOverviewRuler: boolean(options.renderOverviewRuler, defaults.renderOverviewRuler),
      diffWordWrap: stringSet(options.diffWordWrap, defaults.diffWordWrap, ["off", "on", "inherit"]),
      diffAlgorithm: stringSet(options.diffAlgorithm, defaults.diffAlgorithm, ["legacy", "advanced"], { "smart": "legacy", "experimental": "advanced" }),
      accessibilityVerbose: boolean(options.accessibilityVerbose, defaults.accessibilityVerbose),
      experimental: {
        showMoves: boolean(options.experimental?.showMoves, defaults.experimental.showMoves),
        showEmptyDecorations: boolean(options.experimental?.showEmptyDecorations, defaults.experimental.showEmptyDecorations),
        useTrueInlineView: boolean(options.experimental?.useTrueInlineView, defaults.experimental.useTrueInlineView)
      },
      hideUnchangedRegions: {
        // eslint-disable-next-line local/code-no-any-casts, @typescript-eslint/no-explicit-any
        enabled: boolean(options.hideUnchangedRegions?.enabled ?? options.experimental?.collapseUnchangedRegions, defaults.hideUnchangedRegions.enabled),
        contextLineCount: clampedInt(
          options.hideUnchangedRegions?.contextLineCount,
          defaults.hideUnchangedRegions.contextLineCount,
          0,
          1073741824
          /* Constants.MAX_SAFE_SMALL_INTEGER */
        ),
        minimumLineCount: clampedInt(
          options.hideUnchangedRegions?.minimumLineCount,
          defaults.hideUnchangedRegions.minimumLineCount,
          0,
          1073741824
          /* Constants.MAX_SAFE_SMALL_INTEGER */
        ),
        revealLineCount: clampedInt(
          options.hideUnchangedRegions?.revealLineCount,
          defaults.hideUnchangedRegions.revealLineCount,
          0,
          1073741824
          /* Constants.MAX_SAFE_SMALL_INTEGER */
        )
      },
      isInEmbeddedEditor: boolean(options.isInEmbeddedEditor, defaults.isInEmbeddedEditor),
      onlyShowAccessibleDiffViewer: boolean(options.onlyShowAccessibleDiffViewer, defaults.onlyShowAccessibleDiffViewer),
      renderSideBySideInlineBreakpoint: clampedInt(
        options.renderSideBySideInlineBreakpoint,
        defaults.renderSideBySideInlineBreakpoint,
        0,
        1073741824
        /* Constants.MAX_SAFE_SMALL_INTEGER */
      ),
      useInlineViewWhenSpaceIsLimited: boolean(options.useInlineViewWhenSpaceIsLimited, defaults.useInlineViewWhenSpaceIsLimited),
      renderGutterMenu: boolean(options.renderGutterMenu, defaults.renderGutterMenu),
      compactMode: boolean(options.compactMode, defaults.compactMode)
    };
  }
  class BaseDropdown extends ActionRunner {
    constructor(container, options) {
      super();
      this._onDidChangeVisibility = this._register(new Emitter$1());
      this.onDidChangeVisibility = this._onDidChangeVisibility.event;
      this._element = append$2(container, $$l(".monaco-dropdown"));
      this._label = append$2(this._element, $$l(".dropdown-label"));
      let labelRenderer = options.labelRenderer;
      if (!labelRenderer) {
        labelRenderer = (container2) => {
          container2.textContent = options.label || "";
          return null;
        };
      }
      for (const event of [EventType$1.CLICK, EventType$1.MOUSE_DOWN, EventType.Tap]) {
        this._register(addDisposableListener(this.element, event, (e) => EventHelper.stop(e, true)));
      }
      for (const event of [EventType$1.MOUSE_DOWN, EventType.Tap]) {
        this._register(addDisposableListener(this._label, event, (e) => {
          if (isMouseEvent(e) && e.button !== 0) {
            return;
          }
          if (this.visible) {
            this.hide();
          } else {
            this.show();
          }
        }));
      }
      this._register(addDisposableListener(this._label, EventType$1.KEY_DOWN, (e) => {
        const event = new StandardKeyboardEvent(e);
        if (event.equals(
          3
          /* KeyCode.Enter */
        ) || event.equals(
          10
          /* KeyCode.Space */
        )) {
          EventHelper.stop(e, true);
          if (this.visible) {
            this.hide();
          } else {
            this.show();
          }
        }
      }));
      const cleanupFn = labelRenderer(this._label);
      if (cleanupFn) {
        this._register(cleanupFn);
      }
      this._register(Gesture.addTarget(this._label));
    }
    get element() {
      return this._element;
    }
    show() {
      if (!this.visible) {
        this.visible = true;
        this._onDidChangeVisibility.fire(true);
      }
    }
    hide() {
      if (this.visible) {
        this.visible = false;
        this._onDidChangeVisibility.fire(false);
      }
    }
    dispose() {
      super.dispose();
      this.hide();
      if (this.boxContainer) {
        this.boxContainer.remove();
        this.boxContainer = void 0;
      }
      if (this.contents) {
        this.contents.remove();
        this.contents = void 0;
      }
      if (this._label) {
        this._label.remove();
        this._label = void 0;
      }
    }
  }
  class DropdownMenu extends BaseDropdown {
    constructor(container, _options) {
      super(container, _options);
      this._options = _options;
      this._actions = [];
      this.actions = _options.actions || [];
    }
    set menuOptions(options) {
      this._menuOptions = options;
    }
    get menuOptions() {
      return this._menuOptions;
    }
    get actions() {
      if (this._options.actionProvider) {
        return this._options.actionProvider.getActions();
      }
      return this._actions;
    }
    set actions(actions) {
      this._actions = actions;
    }
    show() {
      super.show();
      this.element.classList.add("active");
      this._options.contextMenuProvider.showContextMenu({
        getAnchor: () => this.element,
        getActions: () => this.actions,
        getActionsContext: () => this.menuOptions ? this.menuOptions.context : null,
        getActionViewItem: (action, options) => this.menuOptions && this.menuOptions.actionViewItemProvider ? this.menuOptions.actionViewItemProvider(action, options) : void 0,
        getKeyBinding: (action) => this.menuOptions && this.menuOptions.getKeyBinding ? this.menuOptions.getKeyBinding(action) : void 0,
        getMenuClassName: () => this._options.menuClassName || "",
        onHide: () => this.onHide(),
        actionRunner: this.menuOptions ? this.menuOptions.actionRunner : void 0,
        anchorAlignment: this.menuOptions ? this.menuOptions.anchorAlignment : 0,
        domForShadowRoot: this._options.menuAsChild ? this.element : void 0,
        skipTelemetry: this._options.skipTelemetry
      });
    }
    hide() {
      super.hide();
    }
    onHide() {
      this.hide();
      this.element.classList.remove("active");
    }
  }
  class DropdownMenuActionViewItem extends BaseActionViewItem {
    get onDidChangeVisibility() {
      return this._onDidChangeVisibility.event;
    }
    constructor(action, menuActionsOrProvider, contextMenuProvider, options = /* @__PURE__ */ Object.create(null)) {
      super(null, action, options);
      this.actionItem = null;
      this._onDidChangeVisibility = this._register(new Emitter$1());
      this.menuActionsOrProvider = menuActionsOrProvider;
      this.contextMenuProvider = contextMenuProvider;
      this.options = options;
      if (this.options.actionRunner) {
        this.actionRunner = this.options.actionRunner;
      }
    }
    render(container) {
      this.actionItem = container;
      const labelRenderer = (el) => {
        this.element = append$2(el, $$l("a.action-label"));
        return this.renderLabel(this.element);
      };
      const isActionsArray = Array.isArray(this.menuActionsOrProvider);
      const options = {
        contextMenuProvider: this.contextMenuProvider,
        labelRenderer,
        menuAsChild: this.options.menuAsChild,
        actions: isActionsArray ? this.menuActionsOrProvider : void 0,
        actionProvider: isActionsArray ? void 0 : this.menuActionsOrProvider,
        skipTelemetry: this.options.skipTelemetry
      };
      this.dropdownMenu = this._register(new DropdownMenu(container, options));
      this._register(this.dropdownMenu.onDidChangeVisibility((visible) => {
        this.element?.setAttribute("aria-expanded", `${visible}`);
        this._onDidChangeVisibility.fire(visible);
      }));
      this.dropdownMenu.menuOptions = {
        actionViewItemProvider: this.options.actionViewItemProvider,
        actionRunner: this.actionRunner,
        getKeyBinding: this.options.keybindingProvider,
        context: this._context
      };
      if (this.options.anchorAlignmentProvider) {
        const that = this;
        this.dropdownMenu.menuOptions = {
          ...this.dropdownMenu.menuOptions,
          get anchorAlignment() {
            return that.options.anchorAlignmentProvider();
          }
        };
      }
      this.updateTooltip();
      this.updateEnabled();
    }
    renderLabel(element) {
      let classNames2 = [];
      if (typeof this.options.classNames === "string") {
        classNames2 = this.options.classNames.split(/\s+/g).filter((s) => !!s);
      } else if (this.options.classNames) {
        classNames2 = this.options.classNames;
      }
      if (!classNames2.find((c) => c === "icon")) {
        classNames2.push("codicon");
      }
      element.classList.add(...classNames2);
      if (this._action.label) {
        this._register(getBaseLayerHoverDelegate().setupManagedHover(this.options.hoverDelegate ?? getDefaultHoverDelegate("mouse"), element, this._action.label));
      }
      return null;
    }
    getTooltip() {
      let title = null;
      if (this.action.tooltip) {
        title = this.action.tooltip;
      } else if (this.action.label) {
        title = this.action.label;
      }
      return title ?? void 0;
    }
    setActionContext(newContext) {
      super.setActionContext(newContext);
      if (this.dropdownMenu) {
        if (this.dropdownMenu.menuOptions) {
          this.dropdownMenu.menuOptions.context = newContext;
        } else {
          this.dropdownMenu.menuOptions = { context: newContext };
        }
      }
    }
    show() {
      this.dropdownMenu?.show();
    }
    updateEnabled() {
      const disabled = !this.action.enabled;
      this.actionItem?.classList.toggle("disabled", disabled);
      this.element?.classList.toggle("disabled", disabled);
    }
  }
  const ACTION_MIN_WIDTH = 24;
  class ToolBar extends Disposable {
    get onDidChangeDropdownVisibility() {
      return this._onDidChangeDropdownVisibility.event;
    }
    constructor(container, contextMenuProvider, options = {
      orientation: 0
      /* ActionsOrientation.HORIZONTAL */
    }) {
      super();
      this.submenuActionViewItems = [];
      this.hasSecondaryActions = false;
      this._onDidChangeDropdownVisibility = this._register(new EventMultiplexer());
      this.originalPrimaryActions = [];
      this.originalSecondaryActions = [];
      this.hiddenActions = [];
      this.disposables = this._register(new DisposableStore());
      options.hoverDelegate = options.hoverDelegate ?? this._register(createInstantHoverDelegate());
      this.options = options;
      this.toggleMenuAction = this._register(new ToggleMenuAction(() => this.toggleMenuActionViewItem?.show(), options.toggleMenuTitle));
      this.element = document.createElement("div");
      this.element.className = "monaco-toolbar";
      container.appendChild(this.element);
      this.actionBar = this._register(new ActionBar(this.element, {
        orientation: options.orientation,
        ariaLabel: options.ariaLabel,
        actionRunner: options.actionRunner,
        allowContextMenu: options.allowContextMenu,
        highlightToggledItems: options.highlightToggledItems,
        hoverDelegate: options.hoverDelegate,
        actionViewItemProvider: (action, viewItemOptions) => {
          if (action.id === ToggleMenuAction.ID) {
            this.toggleMenuActionViewItem = new DropdownMenuActionViewItem(action, { getActions: () => this.toggleMenuAction.menuActions }, contextMenuProvider, {
              actionViewItemProvider: this.options.actionViewItemProvider,
              actionRunner: this.actionRunner,
              keybindingProvider: this.options.getKeyBinding,
              classNames: ThemeIcon.asClassNameArray(options.moreIcon ?? Codicon.toolBarMore),
              anchorAlignmentProvider: this.options.anchorAlignmentProvider,
              menuAsChild: !!this.options.renderDropdownAsChildElement,
              skipTelemetry: this.options.skipTelemetry,
              isMenu: true,
              hoverDelegate: this.options.hoverDelegate
            });
            this.toggleMenuActionViewItem.setActionContext(this.actionBar.context);
            this.disposables.add(this._onDidChangeDropdownVisibility.add(this.toggleMenuActionViewItem.onDidChangeVisibility));
            return this.toggleMenuActionViewItem;
          }
          if (options.actionViewItemProvider) {
            const result = options.actionViewItemProvider(action, viewItemOptions);
            if (result) {
              return result;
            }
          }
          if (action instanceof SubmenuAction) {
            const result = new DropdownMenuActionViewItem(action, action.actions, contextMenuProvider, {
              actionViewItemProvider: this.options.actionViewItemProvider,
              actionRunner: this.actionRunner,
              keybindingProvider: this.options.getKeyBinding,
              classNames: action.class,
              anchorAlignmentProvider: this.options.anchorAlignmentProvider,
              menuAsChild: !!this.options.renderDropdownAsChildElement,
              skipTelemetry: this.options.skipTelemetry,
              hoverDelegate: this.options.hoverDelegate
            });
            result.setActionContext(this.actionBar.context);
            this.submenuActionViewItems.push(result);
            this.disposables.add(this._onDidChangeDropdownVisibility.add(result.onDidChangeVisibility));
            return result;
          }
          return void 0;
        }
      }));
      if (this.options.responsive) {
        this.element.classList.add("responsive");
        const observer = new ResizeObserver(() => {
          this.setToolbarMaxWidth(this.element.getBoundingClientRect().width);
        });
        observer.observe(this.element);
        this._store.add(toDisposable(() => observer.disconnect()));
      }
    }
    set actionRunner(actionRunner) {
      this.actionBar.actionRunner = actionRunner;
    }
    get actionRunner() {
      return this.actionBar.actionRunner;
    }
    set context(context) {
      this.actionBar.context = context;
      this.toggleMenuActionViewItem?.setActionContext(context);
      for (const actionViewItem of this.submenuActionViewItems) {
        actionViewItem.setActionContext(context);
      }
    }
    getElement() {
      return this.element;
    }
    getItemAction(indexOrElement) {
      return this.actionBar.getAction(indexOrElement);
    }
    getItemWidth(index) {
      return this.actionBar.getWidth(index);
    }
    setActions(primaryActions, secondaryActions) {
      this.clear();
      this.originalPrimaryActions = primaryActions ? primaryActions.slice(0) : [];
      this.originalSecondaryActions = secondaryActions ? secondaryActions.slice(0) : [];
      const primaryActionsToSet = primaryActions ? primaryActions.slice(0) : [];
      this.hasSecondaryActions = !!(secondaryActions && secondaryActions.length > 0);
      if (this.hasSecondaryActions && secondaryActions) {
        this.toggleMenuAction.menuActions = secondaryActions.slice(0);
        primaryActionsToSet.push(this.toggleMenuAction);
      }
      if (primaryActionsToSet.length > 0 && this.options.trailingSeparator) {
        primaryActionsToSet.push(new Separator());
      }
      primaryActionsToSet.forEach((action) => {
        this.actionBar.push(action, { icon: this.options.icon ?? true, label: this.options.label ?? false, keybinding: this.getKeybindingLabel(action) });
      });
      if (this.options.responsive) {
        this.hiddenActions.length = 0;
        this.setToolbarMaxWidth(this.element.getBoundingClientRect().width);
      }
    }
    getKeybindingLabel(action) {
      const key = this.options.getKeyBinding?.(action);
      return key?.getLabel() ?? void 0;
    }
    getItemsWidthResponsive() {
      return this.actionBar.length() * ACTION_MIN_WIDTH;
    }
    setToolbarMaxWidth(maxWidth) {
      if (this.actionBar.isEmpty() || this.getItemsWidthResponsive() <= maxWidth && this.hiddenActions.length === 0) {
        return;
      }
      if (this.getItemsWidthResponsive() > maxWidth) {
        while (this.getItemsWidthResponsive() > maxWidth && this.actionBar.length() > 0) {
          const index = this.originalPrimaryActions.length - this.hiddenActions.length - 1;
          if (index < 0) {
            break;
          }
          const size2 = Math.min(ACTION_MIN_WIDTH, this.getItemWidth(index));
          const action = this.originalPrimaryActions[index];
          this.hiddenActions.unshift({ action, size: size2 });
          this.actionBar.pull(index);
          if (this.originalSecondaryActions.length === 0 && this.hiddenActions.length === 1) {
            this.actionBar.push(this.toggleMenuAction, {
              icon: this.options.icon ?? true,
              label: this.options.label ?? false,
              keybinding: this.getKeybindingLabel(this.toggleMenuAction)
            });
          }
        }
      } else {
        while (this.hiddenActions.length > 0) {
          const entry = this.hiddenActions.shift();
          if (this.getItemsWidthResponsive() + entry.size > maxWidth) {
            this.hiddenActions.unshift(entry);
            break;
          }
          this.actionBar.push(entry.action, {
            icon: this.options.icon ?? true,
            label: this.options.label ?? false,
            keybinding: this.getKeybindingLabel(entry.action),
            index: this.originalPrimaryActions.length - this.hiddenActions.length - 1
          });
          if (this.originalSecondaryActions.length === 0 && this.hiddenActions.length === 1) {
            this.toggleMenuAction.menuActions = [];
            this.actionBar.pull(this.actionBar.length() - 1);
          }
        }
      }
      const hiddenActions = this.hiddenActions.map((entry) => entry.action);
      if (this.originalSecondaryActions.length > 0 || hiddenActions.length > 0) {
        const secondaryActions = this.originalSecondaryActions.slice(0);
        this.toggleMenuAction.menuActions = Separator.join(hiddenActions, secondaryActions);
      }
    }
    clear() {
      this.submenuActionViewItems = [];
      this.disposables.clear();
      this.actionBar.clear();
    }
    dispose() {
      this.clear();
      this.disposables.dispose();
      super.dispose();
    }
  }
  const _ToggleMenuAction = class _ToggleMenuAction extends Action {
    constructor(toggleDropdownMenu, title) {
      title = title || localize(17, "More Actions...");
      super(_ToggleMenuAction.ID, title, void 0, true);
      this._menuActions = [];
      this.toggleDropdownMenu = toggleDropdownMenu;
    }
    async run() {
      this.toggleDropdownMenu();
    }
    get menuActions() {
      return this._menuActions;
    }
    set menuActions(actions) {
      this._menuActions = actions;
    }
  };
  _ToggleMenuAction.ID = "toolbar.toggle.more";
  let ToggleMenuAction = _ToggleMenuAction;
  class ModifierLabelProvider {
    constructor(mac, windows, linux = windows) {
      this.modifierLabels = [null];
      this.modifierLabels[
        2
        /* OperatingSystem.Macintosh */
      ] = mac;
      this.modifierLabels[
        1
        /* OperatingSystem.Windows */
      ] = windows;
      this.modifierLabels[
        3
        /* OperatingSystem.Linux */
      ] = linux;
    }
    toLabel(OS2, chords, keyLabelProvider) {
      if (chords.length === 0) {
        return null;
      }
      const result = [];
      for (let i2 = 0, len = chords.length; i2 < len; i2++) {
        const chord = chords[i2];
        const keyLabel = keyLabelProvider(chord);
        if (keyLabel === null) {
          return null;
        }
        result[i2] = _simpleAsString(chord, keyLabel, this.modifierLabels[OS2]);
      }
      return result.join(" ");
    }
  }
  const UILabelProvider = new ModifierLabelProvider({
    ctrlKey: "⌃",
    shiftKey: "⇧",
    altKey: "⌥",
    metaKey: "⌘",
    separator: ""
  }, {
    ctrlKey: localize(35, "Ctrl"),
    shiftKey: localize(36, "Shift"),
    altKey: localize(37, "Alt"),
    metaKey: localize(38, "Windows"),
    separator: "+"
  }, {
    ctrlKey: localize(39, "Ctrl"),
    shiftKey: localize(40, "Shift"),
    altKey: localize(41, "Alt"),
    metaKey: localize(42, "Super"),
    separator: "+"
  });
  const AriaLabelProvider = new ModifierLabelProvider({
    ctrlKey: localize(43, "Control"),
    shiftKey: localize(44, "Shift"),
    altKey: localize(45, "Option"),
    metaKey: localize(46, "Command"),
    separator: "+"
  }, {
    ctrlKey: localize(47, "Control"),
    shiftKey: localize(48, "Shift"),
    altKey: localize(49, "Alt"),
    metaKey: localize(50, "Windows"),
    separator: "+"
  }, {
    ctrlKey: localize(51, "Control"),
    shiftKey: localize(52, "Shift"),
    altKey: localize(53, "Alt"),
    metaKey: localize(54, "Super"),
    separator: "+"
  });
  const ElectronAcceleratorLabelProvider = new ModifierLabelProvider({
    ctrlKey: "Ctrl",
    shiftKey: "Shift",
    altKey: "Alt",
    metaKey: "Cmd",
    separator: "+"
  }, {
    ctrlKey: "Ctrl",
    shiftKey: "Shift",
    altKey: "Alt",
    metaKey: "Super",
    separator: "+"
  });
  const UserSettingsLabelProvider = new ModifierLabelProvider({
    ctrlKey: "ctrl",
    shiftKey: "shift",
    altKey: "alt",
    metaKey: "cmd",
    separator: "+"
  }, {
    ctrlKey: "ctrl",
    shiftKey: "shift",
    altKey: "alt",
    metaKey: "win",
    separator: "+"
  }, {
    ctrlKey: "ctrl",
    shiftKey: "shift",
    altKey: "alt",
    metaKey: "meta",
    separator: "+"
  });
  function _simpleAsString(modifiers, key, labels) {
    if (key === null) {
      return "";
    }
    const result = [];
    if (modifiers.ctrlKey) {
      result.push(labels.ctrlKey);
    }
    if (modifiers.shiftKey) {
      result.push(labels.shiftKey);
    }
    if (modifiers.altKey) {
      result.push(labels.altKey);
    }
    if (modifiers.metaKey) {
      result.push(labels.metaKey);
    }
    if (key !== "") {
      result.push(key);
    }
    return result.join(labels.separator);
  }
  function isLocalizedString(thing) {
    return !!thing && typeof thing === "object" && typeof thing.original === "string" && typeof thing.value === "string";
  }
  function isICommandActionToggleInfo(thing) {
    return thing ? thing.condition !== void 0 : false;
  }
  var StorageHint;
  (function(StorageHint2) {
    StorageHint2[StorageHint2["STORAGE_DOES_NOT_EXIST"] = 0] = "STORAGE_DOES_NOT_EXIST";
    StorageHint2[StorageHint2["STORAGE_IN_MEMORY"] = 1] = "STORAGE_IN_MEMORY";
  })(StorageHint || (StorageHint = {}));
  var StorageState;
  (function(StorageState2) {
    StorageState2[StorageState2["None"] = 0] = "None";
    StorageState2[StorageState2["Initialized"] = 1] = "Initialized";
    StorageState2[StorageState2["Closed"] = 2] = "Closed";
  })(StorageState || (StorageState = {}));
  const _Storage = class _Storage extends Disposable {
    constructor(database, options = /* @__PURE__ */ Object.create(null)) {
      super();
      this.database = database;
      this.options = options;
      this._onDidChangeStorage = this._register(new PauseableEmitter());
      this.onDidChangeStorage = this._onDidChangeStorage.event;
      this.state = StorageState.None;
      this.cache = /* @__PURE__ */ new Map();
      this.flushDelayer = this._register(new ThrottledDelayer(_Storage.DEFAULT_FLUSH_DELAY));
      this.pendingDeletes = /* @__PURE__ */ new Set();
      this.pendingInserts = /* @__PURE__ */ new Map();
      this.pendingClose = void 0;
      this.whenFlushedCallbacks = [];
      this.registerListeners();
    }
    registerListeners() {
      this._register(this.database.onDidChangeItemsExternal((e) => this.onDidChangeItemsExternal(e)));
    }
    onDidChangeItemsExternal(e) {
      this._onDidChangeStorage.pause();
      try {
        e.changed?.forEach((value, key) => this.acceptExternal(key, value));
        e.deleted?.forEach((key) => this.acceptExternal(key, void 0));
      } finally {
        this._onDidChangeStorage.resume();
      }
    }
    acceptExternal(key, value) {
      if (this.state === StorageState.Closed) {
        return;
      }
      let changed = false;
      if (isUndefinedOrNull(value)) {
        changed = this.cache.delete(key);
      } else {
        const currentValue = this.cache.get(key);
        if (currentValue !== value) {
          this.cache.set(key, value);
          changed = true;
        }
      }
      if (changed) {
        this._onDidChangeStorage.fire({ key, external: true });
      }
    }
    get(key, fallbackValue) {
      const value = this.cache.get(key);
      if (isUndefinedOrNull(value)) {
        return fallbackValue;
      }
      return value;
    }
    getBoolean(key, fallbackValue) {
      const value = this.get(key);
      if (isUndefinedOrNull(value)) {
        return fallbackValue;
      }
      return value === "true";
    }
    getNumber(key, fallbackValue) {
      const value = this.get(key);
      if (isUndefinedOrNull(value)) {
        return fallbackValue;
      }
      return parseInt(value, 10);
    }
    async set(key, value, external = false) {
      if (this.state === StorageState.Closed) {
        return;
      }
      if (isUndefinedOrNull(value)) {
        return this.delete(key, external);
      }
      const valueStr = isObject(value) || Array.isArray(value) ? stringify(value) : String(value);
      const currentValue = this.cache.get(key);
      if (currentValue === valueStr) {
        return;
      }
      this.cache.set(key, valueStr);
      this.pendingInserts.set(key, valueStr);
      this.pendingDeletes.delete(key);
      this._onDidChangeStorage.fire({ key, external });
      return this.doFlush();
    }
    async delete(key, external = false) {
      if (this.state === StorageState.Closed) {
        return;
      }
      const wasDeleted = this.cache.delete(key);
      if (!wasDeleted) {
        return;
      }
      if (!this.pendingDeletes.has(key)) {
        this.pendingDeletes.add(key);
      }
      this.pendingInserts.delete(key);
      this._onDidChangeStorage.fire({ key, external });
      return this.doFlush();
    }
    get hasPending() {
      return this.pendingInserts.size > 0 || this.pendingDeletes.size > 0;
    }
    async flushPending() {
      if (!this.hasPending) {
        return;
      }
      const updateRequest = { insert: this.pendingInserts, delete: this.pendingDeletes };
      this.pendingDeletes = /* @__PURE__ */ new Set();
      this.pendingInserts = /* @__PURE__ */ new Map();
      return this.database.updateItems(updateRequest).finally(() => {
        if (!this.hasPending) {
          while (this.whenFlushedCallbacks.length) {
            this.whenFlushedCallbacks.pop()?.();
          }
        }
      });
    }
    async flush(delay) {
      if (this.state === StorageState.Closed || // Return early if we are already closed
      this.pendingClose) {
        return;
      }
      return this.doFlush(delay);
    }
    async doFlush(delay) {
      if (this.options.hint === StorageHint.STORAGE_IN_MEMORY) {
        return this.flushPending();
      }
      return this.flushDelayer.trigger(() => this.flushPending(), delay);
    }
    async whenFlushed() {
      if (!this.hasPending) {
        return;
      }
      return new Promise((resolve2) => this.whenFlushedCallbacks.push(resolve2));
    }
  };
  _Storage.DEFAULT_FLUSH_DELAY = 100;
  let Storage = _Storage;
  class InMemoryStorageDatabase {
    constructor() {
      this.onDidChangeItemsExternal = Event.None;
      this.items = /* @__PURE__ */ new Map();
    }
    async updateItems(request) {
      request.insert?.forEach((value, key) => this.items.set(key, value));
      request.delete?.forEach((key) => this.items.delete(key));
    }
  }
  const TARGET_KEY = "__$__targetStorageMarker";
  const IStorageService = createDecorator("storageService");
  var WillSaveStateReason;
  (function(WillSaveStateReason2) {
    WillSaveStateReason2[WillSaveStateReason2["NONE"] = 0] = "NONE";
    WillSaveStateReason2[WillSaveStateReason2["SHUTDOWN"] = 1] = "SHUTDOWN";
  })(WillSaveStateReason || (WillSaveStateReason = {}));
  function loadKeyTargets(storage) {
    const keysRaw = storage.get(TARGET_KEY);
    if (keysRaw) {
      try {
        return JSON.parse(keysRaw);
      } catch (error) {
      }
    }
    return /* @__PURE__ */ Object.create(null);
  }
  const _AbstractStorageService = class _AbstractStorageService extends Disposable {
    // every minute
    constructor(options = { flushInterval: _AbstractStorageService.DEFAULT_FLUSH_INTERVAL }) {
      super();
      this._onDidChangeValue = this._register(new PauseableEmitter());
      this._onDidChangeTarget = this._register(new PauseableEmitter());
      this._onWillSaveState = this._register(new Emitter$1());
      this.onWillSaveState = this._onWillSaveState.event;
      this.runFlushWhenIdle = this._register(new MutableDisposable());
      this._workspaceKeyTargets = void 0;
      this._profileKeyTargets = void 0;
      this._applicationKeyTargets = void 0;
      this.flushWhenIdleScheduler = this._register(new RunOnceScheduler(() => this.doFlushWhenIdle(), options.flushInterval));
    }
    onDidChangeValue(scope, key, disposable) {
      return Event.filter(this._onDidChangeValue.event, (e) => e.scope === scope && (key === void 0 || e.key === key), disposable);
    }
    doFlushWhenIdle() {
      this.runFlushWhenIdle.value = runWhenGlobalIdle(() => {
        if (this.shouldFlushWhenIdle()) {
          this.flush();
        }
        this.flushWhenIdleScheduler.schedule();
      });
    }
    shouldFlushWhenIdle() {
      return true;
    }
    emitDidChangeValue(scope, event) {
      const { key, external } = event;
      if (key === TARGET_KEY) {
        switch (scope) {
          case -1:
            this._applicationKeyTargets = void 0;
            break;
          case 0:
            this._profileKeyTargets = void 0;
            break;
          case 1:
            this._workspaceKeyTargets = void 0;
            break;
        }
        this._onDidChangeTarget.fire({ scope });
      } else {
        this._onDidChangeValue.fire({ scope, key, target: this.getKeyTargets(scope)[key], external });
      }
    }
    get(key, scope, fallbackValue) {
      return this.getStorage(scope)?.get(key, fallbackValue);
    }
    getBoolean(key, scope, fallbackValue) {
      return this.getStorage(scope)?.getBoolean(key, fallbackValue);
    }
    getNumber(key, scope, fallbackValue) {
      return this.getStorage(scope)?.getNumber(key, fallbackValue);
    }
    store(key, value, scope, target, external = false) {
      if (isUndefinedOrNull(value)) {
        this.remove(key, scope, external);
        return;
      }
      this.withPausedEmitters(() => {
        this.updateKeyTarget(key, scope, target);
        this.getStorage(scope)?.set(key, value, external);
      });
    }
    remove(key, scope, external = false) {
      this.withPausedEmitters(() => {
        this.updateKeyTarget(key, scope, void 0);
        this.getStorage(scope)?.delete(key, external);
      });
    }
    withPausedEmitters(fn) {
      this._onDidChangeValue.pause();
      this._onDidChangeTarget.pause();
      try {
        fn();
      } finally {
        this._onDidChangeValue.resume();
        this._onDidChangeTarget.resume();
      }
    }
    updateKeyTarget(key, scope, target, external = false) {
      const keyTargets = this.getKeyTargets(scope);
      if (typeof target === "number") {
        if (keyTargets[key] !== target) {
          keyTargets[key] = target;
          this.getStorage(scope)?.set(TARGET_KEY, JSON.stringify(keyTargets), external);
        }
      } else {
        if (typeof keyTargets[key] === "number") {
          delete keyTargets[key];
          this.getStorage(scope)?.set(TARGET_KEY, JSON.stringify(keyTargets), external);
        }
      }
    }
    get workspaceKeyTargets() {
      if (!this._workspaceKeyTargets) {
        this._workspaceKeyTargets = this.loadKeyTargets(
          1
          /* StorageScope.WORKSPACE */
        );
      }
      return this._workspaceKeyTargets;
    }
    get profileKeyTargets() {
      if (!this._profileKeyTargets) {
        this._profileKeyTargets = this.loadKeyTargets(
          0
          /* StorageScope.PROFILE */
        );
      }
      return this._profileKeyTargets;
    }
    get applicationKeyTargets() {
      if (!this._applicationKeyTargets) {
        this._applicationKeyTargets = this.loadKeyTargets(
          -1
          /* StorageScope.APPLICATION */
        );
      }
      return this._applicationKeyTargets;
    }
    getKeyTargets(scope) {
      switch (scope) {
        case -1:
          return this.applicationKeyTargets;
        case 0:
          return this.profileKeyTargets;
        default:
          return this.workspaceKeyTargets;
      }
    }
    loadKeyTargets(scope) {
      const storage = this.getStorage(scope);
      return storage ? loadKeyTargets(storage) : /* @__PURE__ */ Object.create(null);
    }
    async flush(reason = WillSaveStateReason.NONE) {
      this._onWillSaveState.fire({ reason });
      const applicationStorage = this.getStorage(
        -1
        /* StorageScope.APPLICATION */
      );
      const profileStorage = this.getStorage(
        0
        /* StorageScope.PROFILE */
      );
      const workspaceStorage = this.getStorage(
        1
        /* StorageScope.WORKSPACE */
      );
      switch (reason) {
        // Unspecific reason: just wait when data is flushed
        case WillSaveStateReason.NONE:
          await Promises.settled([
            applicationStorage?.whenFlushed() ?? Promise.resolve(),
            profileStorage?.whenFlushed() ?? Promise.resolve(),
            workspaceStorage?.whenFlushed() ?? Promise.resolve()
          ]);
          break;
        // Shutdown: we want to flush as soon as possible
        // and not hit any delays that might be there
        case WillSaveStateReason.SHUTDOWN:
          await Promises.settled([
            applicationStorage?.flush(0) ?? Promise.resolve(),
            profileStorage?.flush(0) ?? Promise.resolve(),
            workspaceStorage?.flush(0) ?? Promise.resolve()
          ]);
          break;
      }
    }
  };
  _AbstractStorageService.DEFAULT_FLUSH_INTERVAL = 60 * 1e3;
  let AbstractStorageService = _AbstractStorageService;
  class InMemoryStorageService extends AbstractStorageService {
    constructor() {
      super();
      this.applicationStorage = this._register(new Storage(new InMemoryStorageDatabase(), { hint: StorageHint.STORAGE_IN_MEMORY }));
      this.profileStorage = this._register(new Storage(new InMemoryStorageDatabase(), { hint: StorageHint.STORAGE_IN_MEMORY }));
      this.workspaceStorage = this._register(new Storage(new InMemoryStorageDatabase(), { hint: StorageHint.STORAGE_IN_MEMORY }));
      this._register(this.workspaceStorage.onDidChangeStorage((e) => this.emitDidChangeValue(1, e)));
      this._register(this.profileStorage.onDidChangeStorage((e) => this.emitDidChangeValue(0, e)));
      this._register(this.applicationStorage.onDidChangeStorage((e) => this.emitDidChangeValue(-1, e)));
    }
    getStorage(scope) {
      switch (scope) {
        case -1:
          return this.applicationStorage;
        case 0:
          return this.profileStorage;
        default:
          return this.workspaceStorage;
      }
    }
    shouldFlushWhenIdle() {
      return false;
    }
  }
  function overrideStyles(override, styles) {
    const result = { ...styles };
    for (const key in override) {
      const val = override[key];
      result[key] = val !== void 0 ? asCssVariable(val) : void 0;
    }
    return result;
  }
  const defaultKeybindingLabelStyles = {
    keybindingLabelBackground: asCssVariable(keybindingLabelBackground),
    keybindingLabelForeground: asCssVariable(keybindingLabelForeground),
    keybindingLabelBorder: asCssVariable(keybindingLabelBorder),
    keybindingLabelBottomBorder: asCssVariable(keybindingLabelBottomBorder),
    keybindingLabelShadow: asCssVariable(widgetShadow)
  };
  const defaultButtonStyles = {
    buttonForeground: asCssVariable(buttonForeground),
    buttonSeparator: asCssVariable(buttonSeparator),
    buttonBackground: asCssVariable(buttonBackground),
    buttonHoverBackground: asCssVariable(buttonHoverBackground),
    buttonSecondaryForeground: asCssVariable(buttonSecondaryForeground),
    buttonSecondaryBackground: asCssVariable(buttonSecondaryBackground),
    buttonSecondaryHoverBackground: asCssVariable(buttonSecondaryHoverBackground),
    buttonBorder: asCssVariable(buttonBorder)
  };
  const defaultProgressBarStyles = {
    progressBarBackground: asCssVariable(progressBarBackground)
  };
  const defaultToggleStyles = {
    inputActiveOptionBorder: asCssVariable(inputActiveOptionBorder),
    inputActiveOptionForeground: asCssVariable(inputActiveOptionForeground),
    inputActiveOptionBackground: asCssVariable(inputActiveOptionBackground)
  };
  ({
    activeForeground: asCssVariable(radioActiveForeground),
    activeBackground: asCssVariable(radioActiveBackground),
    activeBorder: asCssVariable(radioActiveBorder),
    inactiveForeground: asCssVariable(radioInactiveForeground),
    inactiveBackground: asCssVariable(radioInactiveBackground),
    inactiveBorder: asCssVariable(radioInactiveBorder),
    inactiveHoverBackground: asCssVariable(radioInactiveHoverBackground)
  });
  const defaultCheckboxStyles = {
    checkboxBackground: asCssVariable(checkboxBackground),
    checkboxBorder: asCssVariable(checkboxBorder),
    checkboxForeground: asCssVariable(checkboxForeground),
    checkboxDisabledBackground: asCssVariable(checkboxDisabledBackground),
    checkboxDisabledForeground: asCssVariable(checkboxDisabledForeground)
  };
  ({
    dialogBackground: asCssVariable(editorWidgetBackground),
    dialogForeground: asCssVariable(editorWidgetForeground),
    dialogShadow: asCssVariable(widgetShadow),
    dialogBorder: asCssVariable(widgetBorder),
    errorIconForeground: asCssVariable(problemsErrorIconForeground),
    warningIconForeground: asCssVariable(problemsWarningIconForeground),
    infoIconForeground: asCssVariable(problemsInfoIconForeground),
    textLinkForeground: asCssVariable(textLinkForeground)
  });
  const defaultInputBoxStyles = {
    inputBackground: asCssVariable(inputBackground),
    inputForeground: asCssVariable(inputForeground),
    inputBorder: asCssVariable(inputBorder),
    inputValidationInfoBorder: asCssVariable(inputValidationInfoBorder),
    inputValidationInfoBackground: asCssVariable(inputValidationInfoBackground),
    inputValidationInfoForeground: asCssVariable(inputValidationInfoForeground),
    inputValidationWarningBorder: asCssVariable(inputValidationWarningBorder),
    inputValidationWarningBackground: asCssVariable(inputValidationWarningBackground),
    inputValidationWarningForeground: asCssVariable(inputValidationWarningForeground),
    inputValidationErrorBorder: asCssVariable(inputValidationErrorBorder),
    inputValidationErrorBackground: asCssVariable(inputValidationErrorBackground),
    inputValidationErrorForeground: asCssVariable(inputValidationErrorForeground)
  };
  const defaultFindWidgetStyles = {
    listFilterWidgetBackground: asCssVariable(listFilterWidgetBackground),
    listFilterWidgetOutline: asCssVariable(listFilterWidgetOutline),
    listFilterWidgetNoMatchesOutline: asCssVariable(listFilterWidgetNoMatchesOutline),
    listFilterWidgetShadow: asCssVariable(listFilterWidgetShadow),
    inputBoxStyles: defaultInputBoxStyles,
    toggleStyles: defaultToggleStyles
  };
  const defaultCountBadgeStyles = {
    badgeBackground: asCssVariable(badgeBackground),
    badgeForeground: asCssVariable(badgeForeground),
    badgeBorder: asCssVariable(contrastBorder)
  };
  ({
    breadcrumbsBackground: asCssVariable(breadcrumbsBackground),
    breadcrumbsForeground: asCssVariable(breadcrumbsForeground),
    breadcrumbsHoverForeground: asCssVariable(breadcrumbsFocusForeground),
    breadcrumbsFocusForeground: asCssVariable(breadcrumbsFocusForeground),
    breadcrumbsFocusAndSelectionForeground: asCssVariable(breadcrumbsActiveSelectionForeground)
  });
  const defaultListStyles = {
    listBackground: void 0,
    listInactiveFocusForeground: void 0,
    listFocusBackground: asCssVariable(listFocusBackground),
    listFocusForeground: asCssVariable(listFocusForeground),
    listFocusOutline: asCssVariable(listFocusOutline),
    listActiveSelectionBackground: asCssVariable(listActiveSelectionBackground),
    listActiveSelectionForeground: asCssVariable(listActiveSelectionForeground),
    listActiveSelectionIconForeground: asCssVariable(listActiveSelectionIconForeground),
    listFocusAndSelectionOutline: asCssVariable(listFocusAndSelectionOutline),
    listFocusAndSelectionBackground: asCssVariable(listActiveSelectionBackground),
    listFocusAndSelectionForeground: asCssVariable(listActiveSelectionForeground),
    listInactiveSelectionBackground: asCssVariable(listInactiveSelectionBackground),
    listInactiveSelectionIconForeground: asCssVariable(listInactiveSelectionIconForeground),
    listInactiveSelectionForeground: asCssVariable(listInactiveSelectionForeground),
    listInactiveFocusBackground: asCssVariable(listInactiveFocusBackground),
    listInactiveFocusOutline: asCssVariable(listInactiveFocusOutline),
    listHoverBackground: asCssVariable(listHoverBackground),
    listHoverForeground: asCssVariable(listHoverForeground),
    listDropOverBackground: asCssVariable(listDropOverBackground),
    listDropBetweenBackground: asCssVariable(listDropBetweenBackground),
    listSelectionOutline: asCssVariable(activeContrastBorder),
    listHoverOutline: asCssVariable(activeContrastBorder),
    treeIndentGuidesStroke: asCssVariable(treeIndentGuidesStroke),
    treeInactiveIndentGuidesStroke: asCssVariable(treeInactiveIndentGuidesStroke),
    treeStickyScrollBackground: void 0,
    treeStickyScrollBorder: void 0,
    treeStickyScrollShadow: asCssVariable(scrollbarShadow),
    tableColumnsBorder: asCssVariable(tableColumnsBorder),
    tableOddRowsBackgroundColor: asCssVariable(tableOddRowsBackgroundColor)
  };
  function getListStyles(override) {
    return overrideStyles(override, defaultListStyles);
  }
  const defaultSelectBoxStyles = {
    selectBackground: asCssVariable(selectBackground),
    selectListBackground: asCssVariable(selectListBackground),
    selectForeground: asCssVariable(selectForeground),
    decoratorRightForeground: asCssVariable(pickerGroupForeground),
    selectBorder: asCssVariable(selectBorder),
    focusBorder: asCssVariable(focusBorder),
    listFocusBackground: asCssVariable(quickInputListFocusBackground),
    listInactiveSelectionIconForeground: asCssVariable(quickInputListFocusIconForeground),
    listFocusForeground: asCssVariable(quickInputListFocusForeground),
    listFocusOutline: asCssVariableWithDefault(activeContrastBorder, Color.transparent.toString()),
    listHoverBackground: asCssVariable(listHoverBackground),
    listHoverForeground: asCssVariable(listHoverForeground),
    listHoverOutline: asCssVariable(activeContrastBorder),
    selectListBorder: asCssVariable(editorWidgetBorder),
    listBackground: void 0,
    listActiveSelectionBackground: void 0,
    listActiveSelectionForeground: void 0,
    listActiveSelectionIconForeground: void 0,
    listFocusAndSelectionBackground: void 0,
    listDropOverBackground: void 0,
    listDropBetweenBackground: void 0,
    listInactiveSelectionBackground: void 0,
    listInactiveSelectionForeground: void 0,
    listInactiveFocusBackground: void 0,
    listInactiveFocusOutline: void 0,
    listSelectionOutline: void 0,
    listFocusAndSelectionForeground: void 0,
    listFocusAndSelectionOutline: void 0,
    listInactiveFocusForeground: void 0,
    tableColumnsBorder: void 0,
    tableOddRowsBackgroundColor: void 0,
    treeIndentGuidesStroke: void 0,
    treeInactiveIndentGuidesStroke: void 0,
    treeStickyScrollBackground: void 0,
    treeStickyScrollBorder: void 0,
    treeStickyScrollShadow: void 0
  };
  const defaultMenuStyles = {
    shadowColor: asCssVariable(widgetShadow),
    borderColor: asCssVariable(menuBorder),
    foregroundColor: asCssVariable(menuForeground),
    backgroundColor: asCssVariable(menuBackground),
    selectionForegroundColor: asCssVariable(menuSelectionForeground),
    selectionBackgroundColor: asCssVariable(menuSelectionBackground),
    selectionBorderColor: asCssVariable(menuSelectionBorder),
    separatorColor: asCssVariable(menuSeparatorBackground),
    scrollbarShadow: asCssVariable(scrollbarShadow),
    scrollbarSliderBackground: asCssVariable(scrollbarSliderBackground),
    scrollbarSliderHoverBackground: asCssVariable(scrollbarSliderHoverBackground),
    scrollbarSliderActiveBackground: asCssVariable(scrollbarSliderActiveBackground)
  };
  function hasNativeContextMenu(configurationService, titleBarStyle) {
    if (isWeb) {
      return false;
    }
    const nativeTitle = hasNativeTitlebar(configurationService, titleBarStyle);
    const windowConfigurations = configurationService.getValue("window");
    if (windowConfigurations?.menuStyle === "native") {
      if (!isMacintosh && !nativeTitle) {
        return false;
      }
      return true;
    }
    if (windowConfigurations?.menuStyle === "custom") {
      return false;
    }
    return nativeTitle;
  }
  function hasNativeTitlebar(configurationService, titleBarStyle) {
    if (!titleBarStyle) {
      titleBarStyle = getTitleBarStyle(configurationService);
    }
    return titleBarStyle === "native";
  }
  function getTitleBarStyle(configurationService) {
    if (isWeb) {
      return "custom";
    }
    const configuration = configurationService.getValue("window");
    if (configuration) {
      const useNativeTabs = isMacintosh && configuration.nativeTabs === true;
      if (useNativeTabs) {
        return "native";
      }
      const useSimpleFullScreen = isMacintosh && configuration.nativeFullScreen === false;
      if (useSimpleFullScreen) {
        return "native";
      }
      const style = configuration.titleBarStyle;
      if (style === "native" || style === "custom") {
        return style;
      }
    }
    return "custom";
  }
  function getWindowControlsStyle(configurationService) {
    if (isWeb || isMacintosh || getTitleBarStyle(configurationService) === "native") {
      return "native";
    }
    const configuration = configurationService.getValue("window");
    const style = configuration?.controlsStyle;
    if (style === "custom" || style === "hidden") {
      return style;
    }
    return "native";
  }
  var __decorate$2z = 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);
    };
  };
  function getFlatContextMenuActions(groups, primaryGroup) {
    const target = [];
    getContextMenuActionsImpl(groups, target);
    return target;
  }
  function getContextMenuActionsImpl(groups, target, primaryGroup) {
    const modifierKeyEmitter = ModifierKeyEmitter.getInstance();
    const useAlternativeActions = modifierKeyEmitter.keyStatus.altKey || (isWindows || isLinux) && modifierKeyEmitter.keyStatus.shiftKey;
    fillInActions(groups, target, useAlternativeActions, (actionGroup) => actionGroup === "navigation");
  }
  function getActionBarActions(groups, primaryGroup, shouldInlineSubmenu, useSeparatorsInPrimaryActions) {
    const target = { primary: [], secondary: [] };
    fillInActionBarActions(groups, target, primaryGroup, shouldInlineSubmenu, useSeparatorsInPrimaryActions);
    return target;
  }
  function getFlatActionBarActions(groups, primaryGroup, shouldInlineSubmenu, useSeparatorsInPrimaryActions) {
    const target = [];
    fillInActionBarActions(groups, target, primaryGroup, shouldInlineSubmenu, useSeparatorsInPrimaryActions);
    return target;
  }
  function fillInActionBarActions(groups, target, primaryGroup, shouldInlineSubmenu, useSeparatorsInPrimaryActions) {
    const isPrimaryAction = typeof primaryGroup === "string" ? (actionGroup) => actionGroup === primaryGroup : primaryGroup;
    fillInActions(groups, target, false, isPrimaryAction, shouldInlineSubmenu, useSeparatorsInPrimaryActions);
  }
  function fillInActions(groups, target, useAlternativeActions, isPrimaryAction = (actionGroup) => actionGroup === "navigation", shouldInlineSubmenu = () => false, useSeparatorsInPrimaryActions = false) {
    let primaryBucket;
    let secondaryBucket;
    if (Array.isArray(target)) {
      primaryBucket = target;
      secondaryBucket = target;
    } else {
      primaryBucket = target.primary;
      secondaryBucket = target.secondary;
    }
    const submenuInfo = /* @__PURE__ */ new Set();
    for (const [group, actions] of groups) {
      let target2;
      if (isPrimaryAction(group)) {
        target2 = primaryBucket;
        if (target2.length > 0 && useSeparatorsInPrimaryActions) {
          target2.push(new Separator());
        }
      } else {
        target2 = secondaryBucket;
        if (target2.length > 0) {
          target2.push(new Separator());
        }
      }
      for (let action of actions) {
        if (useAlternativeActions) {
          action = action instanceof MenuItemAction && action.alt ? action.alt : action;
        }
        const newLen = target2.push(action);
        if (action instanceof SubmenuAction) {
          submenuInfo.add({ group, action, index: newLen - 1 });
        }
      }
    }
    for (const { group, action, index } of submenuInfo) {
      const target2 = isPrimaryAction(group) ? primaryBucket : secondaryBucket;
      const submenuActions = action.actions;
      if (shouldInlineSubmenu(action, group, target2.length)) {
        target2.splice(index, 1, ...submenuActions);
      }
    }
  }
  let MenuEntryActionViewItem = class MenuEntryActionViewItem extends ActionViewItem {
    constructor(action, _options, _keybindingService, _notificationService, _contextKeyService, _themeService, _contextMenuService, _accessibilityService) {
      super(void 0, action, { icon: !!(action.class || action.item.icon), label: !action.class && !action.item.icon, draggable: _options?.draggable, keybinding: _options?.keybinding, hoverDelegate: _options?.hoverDelegate, keybindingNotRenderedWithLabel: _options?.keybindingNotRenderedWithLabel });
      this._options = _options;
      this._keybindingService = _keybindingService;
      this._notificationService = _notificationService;
      this._contextKeyService = _contextKeyService;
      this._themeService = _themeService;
      this._contextMenuService = _contextMenuService;
      this._accessibilityService = _accessibilityService;
      this._wantsAltCommand = false;
      this._itemClassDispose = this._register(new MutableDisposable());
      this._altKey = ModifierKeyEmitter.getInstance();
    }
    get _menuItemAction() {
      return this._action;
    }
    get _commandAction() {
      return this._wantsAltCommand && this._menuItemAction.alt || this._menuItemAction;
    }
    async onClick(event) {
      event.preventDefault();
      event.stopPropagation();
      try {
        await this.actionRunner.run(this._commandAction, this._context);
      } catch (err) {
        this._notificationService.error(err);
      }
    }
    render(container) {
      super.render(container);
      container.classList.add("menu-entry");
      if (this.options.icon) {
        this._updateItemClass(this._menuItemAction.item);
      }
      if (this._menuItemAction.alt) {
        let isMouseOver = false;
        const updateAltState = () => {
          const wantsAltCommand = !!this._menuItemAction.alt?.enabled && (!this._accessibilityService.isMotionReduced() || isMouseOver) && (this._altKey.keyStatus.altKey || this._altKey.keyStatus.shiftKey && isMouseOver);
          if (wantsAltCommand !== this._wantsAltCommand) {
            this._wantsAltCommand = wantsAltCommand;
            this.updateLabel();
            this.updateTooltip();
            this.updateClass();
          }
        };
        this._register(this._altKey.event(updateAltState));
        this._register(addDisposableListener(container, "mouseleave", (_) => {
          isMouseOver = false;
          updateAltState();
        }));
        this._register(addDisposableListener(container, "mouseenter", (_) => {
          isMouseOver = true;
          updateAltState();
        }));
        updateAltState();
      }
    }
    updateLabel() {
      if (this.options.label && this.label) {
        this.label.textContent = this._commandAction.label;
      }
    }
    getTooltip() {
      const keybinding = this._keybindingService.lookupKeybinding(this._commandAction.id, this._contextKeyService);
      const keybindingLabel = keybinding && keybinding.getLabel();
      const tooltip = this._commandAction.tooltip || this._commandAction.label;
      let title = keybindingLabel ? localize(1644, "{0} ({1})", tooltip, keybindingLabel) : tooltip;
      if (!this._wantsAltCommand && this._menuItemAction.alt?.enabled) {
        const altTooltip = this._menuItemAction.alt.tooltip || this._menuItemAction.alt.label;
        const altKeybinding = this._keybindingService.lookupKeybinding(this._menuItemAction.alt.id, this._contextKeyService);
        const altKeybindingLabel = altKeybinding && altKeybinding.getLabel();
        const altTitleSection = altKeybindingLabel ? localize(1645, "{0} ({1})", altTooltip, altKeybindingLabel) : altTooltip;
        title = localize(1646, "{0}\n[{1}] {2}", title, UILabelProvider.modifierLabels[OS].altKey, altTitleSection);
      }
      return title;
    }
    updateClass() {
      if (this.options.icon) {
        if (this._commandAction !== this._menuItemAction) {
          if (this._menuItemAction.alt) {
            this._updateItemClass(this._menuItemAction.alt.item);
          }
        } else {
          this._updateItemClass(this._menuItemAction.item);
        }
      }
    }
    _updateItemClass(item) {
      this._itemClassDispose.value = void 0;
      const { element, label } = this;
      if (!element || !label) {
        return;
      }
      const icon = this._commandAction.checked && isICommandActionToggleInfo(item.toggled) && item.toggled.icon ? item.toggled.icon : item.icon;
      if (!icon) {
        return;
      }
      if (ThemeIcon.isThemeIcon(icon)) {
        const iconClasses = ThemeIcon.asClassNameArray(icon);
        label.classList.add(...iconClasses);
        this._itemClassDispose.value = toDisposable(() => {
          label.classList.remove(...iconClasses);
        });
      } else {
        label.style.backgroundImage = isDark(this._themeService.getColorTheme().type) ? asCSSUrl(icon.dark) : asCSSUrl(icon.light);
        label.classList.add("icon");
        this._itemClassDispose.value = combinedDisposable(toDisposable(() => {
          label.style.backgroundImage = "";
          label.classList.remove("icon");
        }), this._themeService.onDidColorThemeChange(() => {
          this.updateClass();
        }));
      }
    }
  };
  MenuEntryActionViewItem = __decorate$2z([
    __param$2x(2, IKeybindingService),
    __param$2x(3, INotificationService),
    __param$2x(4, IContextKeyService),
    __param$2x(5, IThemeService),
    __param$2x(6, IContextMenuService),
    __param$2x(7, IAccessibilityService)
  ], MenuEntryActionViewItem);
  class TextOnlyMenuEntryActionViewItem extends MenuEntryActionViewItem {
    render(container) {
      this.options.label = true;
      this.options.icon = false;
      super.render(container);
      container.classList.add("text-only");
      container.classList.toggle("use-comma", this._options?.useComma ?? false);
    }
    updateLabel() {
      const kb = this._keybindingService.lookupKeybinding(this._action.id, this._contextKeyService);
      if (!kb) {
        return super.updateLabel();
      }
      if (this.label) {
        const kb2 = TextOnlyMenuEntryActionViewItem._symbolPrintEnter(kb);
        if (this._options?.conversational) {
          this.label.textContent = localize(1647, "{1} to {0}", this._action.label, kb2);
        } else {
          this.label.textContent = localize(1648, "{0} ({1})", this._action.label, kb2);
        }
      }
    }
    static _symbolPrintEnter(kb) {
      return kb.getLabel()?.replace(/\benter\b/gi, "⏎").replace(/\bEscape\b/gi, "Esc");
    }
  }
  let SubmenuEntryActionViewItem = class SubmenuEntryActionViewItem extends DropdownMenuActionViewItem {
    constructor(action, options, _keybindingService, _contextMenuService, _themeService) {
      const dropdownOptions = {
        ...options,
        menuAsChild: options?.menuAsChild ?? false,
        classNames: options?.classNames ?? (ThemeIcon.isThemeIcon(action.item.icon) ? ThemeIcon.asClassName(action.item.icon) : void 0),
        keybindingProvider: options?.keybindingProvider ?? ((action2) => _keybindingService.lookupKeybinding(action2.id))
      };
      super(action, { getActions: () => action.actions }, _contextMenuService, dropdownOptions);
      this._keybindingService = _keybindingService;
      this._contextMenuService = _contextMenuService;
      this._themeService = _themeService;
    }
    render(container) {
      super.render(container);
      assertType(this.element);
      container.classList.add("menu-entry");
      const action = this._action;
      const { icon } = action.item;
      if (icon && !ThemeIcon.isThemeIcon(icon)) {
        this.element.classList.add("icon");
        const setBackgroundImage = () => {
          if (this.element) {
            this.element.style.backgroundImage = isDark(this._themeService.getColorTheme().type) ? asCSSUrl(icon.dark) : asCSSUrl(icon.light);
          }
        };
        setBackgroundImage();
        this._register(this._themeService.onDidColorThemeChange(() => {
          setBackgroundImage();
        }));
      }
    }
  };
  SubmenuEntryActionViewItem = __decorate$2z([
    __param$2x(2, IKeybindingService),
    __param$2x(3, IContextMenuService),
    __param$2x(4, IThemeService)
  ], SubmenuEntryActionViewItem);
  let DropdownWithDefaultActionViewItem = class DropdownWithDefaultActionViewItem extends BaseActionViewItem {
    constructor(submenuAction, options, _keybindingService, _notificationService, _contextMenuService, _menuService, _instaService, _storageService) {
      super(null, submenuAction);
      this._keybindingService = _keybindingService;
      this._notificationService = _notificationService;
      this._contextMenuService = _contextMenuService;
      this._menuService = _menuService;
      this._instaService = _instaService;
      this._storageService = _storageService;
      this._defaultActionDisposables = this._register(new DisposableStore());
      this._container = null;
      this._options = options;
      this._storageKey = `${submenuAction.item.submenu.id}_lastActionId`;
      let defaultAction;
      const defaultActionId = options?.togglePrimaryAction ? _storageService.get(
        this._storageKey,
        1
        /* StorageScope.WORKSPACE */
      ) : void 0;
      if (defaultActionId) {
        defaultAction = submenuAction.actions.find((a) => defaultActionId === a.id);
      }
      if (!defaultAction) {
        defaultAction = submenuAction.actions[0];
      }
      this._defaultAction = this._defaultActionDisposables.add(this._instaService.createInstance(MenuEntryActionViewItem, defaultAction, { keybinding: this._getDefaultActionKeybindingLabel(defaultAction) }));
      const dropdownOptions = {
        keybindingProvider: (action) => this._keybindingService.lookupKeybinding(action.id),
        ...options,
        menuAsChild: options?.menuAsChild ?? true,
        classNames: options?.classNames ?? ["codicon", "codicon-chevron-down"],
        actionRunner: options?.actionRunner ?? this._register(new ActionRunner())
      };
      this._dropdown = this._register(new DropdownMenuActionViewItem(submenuAction, submenuAction.actions, this._contextMenuService, dropdownOptions));
      if (options?.togglePrimaryAction) {
        this._register(this._dropdown.actionRunner.onDidRun((e) => {
          if (e.action instanceof MenuItemAction) {
            this.update(e.action);
          }
        }));
      }
    }
    update(lastAction) {
      if (this._options?.togglePrimaryAction) {
        this._storageService.store(
          this._storageKey,
          lastAction.id,
          1,
          1
          /* StorageTarget.MACHINE */
        );
      }
      this._defaultActionDisposables.clear();
      this._defaultAction = this._defaultActionDisposables.add(this._instaService.createInstance(MenuEntryActionViewItem, lastAction, { keybinding: this._getDefaultActionKeybindingLabel(lastAction) }));
      this._defaultAction.actionRunner = this._defaultActionDisposables.add(new class extends ActionRunner {
        async runAction(action, context) {
          await action.run(void 0);
        }
      }());
      if (this._container) {
        this._defaultAction.render(prepend$2(this._container, $$l(".action-container")));
      }
    }
    _getDefaultActionKeybindingLabel(defaultAction) {
      let defaultActionKeybinding;
      if (this._options?.renderKeybindingWithDefaultActionLabel) {
        const kb = this._keybindingService.lookupKeybinding(defaultAction.id);
        if (kb) {
          defaultActionKeybinding = `(${kb.getLabel()})`;
        }
      }
      return defaultActionKeybinding;
    }
    setActionContext(newContext) {
      super.setActionContext(newContext);
      this._defaultAction.setActionContext(newContext);
      this._dropdown.setActionContext(newContext);
    }
    set actionRunner(actionRunner) {
      super.actionRunner = actionRunner;
      this._defaultAction.actionRunner = actionRunner;
      this._dropdown.actionRunner = actionRunner;
    }
    get actionRunner() {
      return super.actionRunner;
    }
    render(container) {
      this._container = container;
      super.render(this._container);
      this._container.classList.add("monaco-dropdown-with-default");
      const primaryContainer = $$l(".action-container");
      this._defaultAction.render(append$2(this._container, primaryContainer));
      this._register(addDisposableListener(primaryContainer, EventType$1.KEY_DOWN, (e) => {
        const event = new StandardKeyboardEvent(e);
        if (event.equals(
          17
          /* KeyCode.RightArrow */
        )) {
          this._defaultAction.element.tabIndex = -1;
          this._dropdown.focus();
          event.stopPropagation();
        }
      }));
      const dropdownContainer = $$l(".dropdown-action-container");
      this._dropdown.render(append$2(this._container, dropdownContainer));
      this._register(addDisposableListener(dropdownContainer, EventType$1.KEY_DOWN, (e) => {
        const event = new StandardKeyboardEvent(e);
        if (event.equals(
          15
          /* KeyCode.LeftArrow */
        )) {
          this._defaultAction.element.tabIndex = 0;
          this._dropdown.setFocusable(false);
          this._defaultAction.element?.focus();
          event.stopPropagation();
        }
      }));
    }
    focus(fromRight) {
      if (fromRight) {
        this._dropdown.focus();
      } else {
        this._defaultAction.element.tabIndex = 0;
        this._defaultAction.element.focus();
      }
    }
    blur() {
      this._defaultAction.element.tabIndex = -1;
      this._dropdown.blur();
      this._container.blur();
    }
    setFocusable(focusable) {
      if (focusable) {
        this._defaultAction.element.tabIndex = 0;
      } else {
        this._defaultAction.element.tabIndex = -1;
        this._dropdown.setFocusable(false);
      }
    }
  };
  DropdownWithDefaultActionViewItem = __decorate$2z([
    __param$2x(2, IKeybindingService),
    __param$2x(3, INotificationService),
    __param$2x(4, IContextMenuService),
    __param$2x(5, IMenuService),
    __param$2x(6, IInstantiationService),
    __param$2x(7, IStorageService)
  ], DropdownWithDefaultActionViewItem);
  let SubmenuEntrySelectActionViewItem = class SubmenuEntrySelectActionViewItem extends SelectActionViewItem {
    constructor(action, contextViewService, configurationService) {
      super(null, action, action.actions.map((a) => ({
        text: a.id === Separator.ID ? "─────────" : a.label,
        isDisabled: !a.enabled
      })), 0, contextViewService, defaultSelectBoxStyles, { ariaLabel: action.tooltip, optionsAsChildren: true, useCustomDrawn: !hasNativeContextMenu(configurationService) });
      this.select(Math.max(0, action.actions.findIndex((a) => a.checked)));
    }
    render(container) {
      super.render(container);
      container.style.borderColor = asCssVariable(selectBorder);
    }
    runAction(option2, index) {
      const action = this.action.actions[index];
      if (action) {
        this.actionRunner.run(action);
      }
    }
  };
  SubmenuEntrySelectActionViewItem = __decorate$2z([
    __param$2x(1, IContextViewService),
    __param$2x(2, IConfigurationService)
  ], SubmenuEntrySelectActionViewItem);
  function createActionViewItem(instaService, action, options) {
    if (action instanceof MenuItemAction) {
      return instaService.createInstance(MenuEntryActionViewItem, action, options);
    } else if (action instanceof SubmenuItemAction) {
      if (action.item.isSelection) {
        return instaService.createInstance(SubmenuEntrySelectActionViewItem, action);
      } else if (action.item.isSplitButton) {
        return instaService.createInstance(DropdownWithDefaultActionViewItem, action, {
          ...options,
          togglePrimaryAction: typeof action.item.isSplitButton !== "boolean" ? action.item.isSplitButton.togglePrimaryAction : false
        });
      } else {
        return instaService.createInstance(SubmenuEntryActionViewItem, action, options);
      }
    } else {
      return void 0;
    }
  }
  var __decorate$2y = 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$2w = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  var PersistedMenuHideState_1, MenuInfo_1;
  let MenuService = class MenuService {
    constructor(_commandService, _keybindingService, storageService) {
      this._commandService = _commandService;
      this._keybindingService = _keybindingService;
      this._hiddenStates = new PersistedMenuHideState(storageService);
    }
    createMenu(id, contextKeyService, options) {
      return new MenuImpl(id, this._hiddenStates, { emitEventsForSubmenuChanges: false, eventDebounceDelay: 50, ...options }, this._commandService, this._keybindingService, contextKeyService);
    }
    getMenuActions(id, contextKeyService, options) {
      const menu = new MenuImpl(id, this._hiddenStates, { emitEventsForSubmenuChanges: false, eventDebounceDelay: 50, ...options }, this._commandService, this._keybindingService, contextKeyService);
      const actions = menu.getActions(options);
      menu.dispose();
      return actions;
    }
    resetHiddenStates(ids) {
      this._hiddenStates.reset(ids);
    }
  };
  MenuService = __decorate$2y([
    __param$2w(0, ICommandService),
    __param$2w(1, IKeybindingService),
    __param$2w(2, IStorageService)
  ], MenuService);
  let PersistedMenuHideState = (_n = class {
    constructor(_storageService) {
      this._storageService = _storageService;
      this._disposables = new DisposableStore();
      this._onDidChange = new Emitter$1();
      this.onDidChange = this._onDidChange.event;
      this._ignoreChangeEvent = false;
      this._hiddenByDefaultCache = /* @__PURE__ */ new Map();
      try {
        const raw = _storageService.get(PersistedMenuHideState_1._key, 0, "{}");
        this._data = JSON.parse(raw);
      } catch (err) {
        this._data = /* @__PURE__ */ Object.create(null);
      }
      this._disposables.add(_storageService.onDidChangeValue(0, PersistedMenuHideState_1._key, this._disposables)(() => {
        if (!this._ignoreChangeEvent) {
          try {
            const raw = _storageService.get(PersistedMenuHideState_1._key, 0, "{}");
            this._data = JSON.parse(raw);
          } catch (err) {
            console.log("FAILED to read storage after UPDATE", err);
          }
        }
        this._onDidChange.fire();
      }));
    }
    dispose() {
      this._onDidChange.dispose();
      this._disposables.dispose();
    }
    _isHiddenByDefault(menu, commandId) {
      return this._hiddenByDefaultCache.get(`${menu.id}/${commandId}`) ?? false;
    }
    setDefaultState(menu, commandId, hidden) {
      this._hiddenByDefaultCache.set(`${menu.id}/${commandId}`, hidden);
    }
    isHidden(menu, commandId) {
      const hiddenByDefault = this._isHiddenByDefault(menu, commandId);
      const state = this._data[menu.id]?.includes(commandId) ?? false;
      return hiddenByDefault ? !state : state;
    }
    updateHidden(menu, commandId, hidden) {
      const hiddenByDefault = this._isHiddenByDefault(menu, commandId);
      if (hiddenByDefault) {
        hidden = !hidden;
      }
      const entries2 = this._data[menu.id];
      if (!hidden) {
        if (entries2) {
          const idx = entries2.indexOf(commandId);
          if (idx >= 0) {
            removeFastWithoutKeepingOrder(entries2, idx);
          }
          if (entries2.length === 0) {
            delete this._data[menu.id];
          }
        }
      } else {
        if (!entries2) {
          this._data[menu.id] = [commandId];
        } else {
          const idx = entries2.indexOf(commandId);
          if (idx < 0) {
            entries2.push(commandId);
          }
        }
      }
      this._persist();
    }
    reset(menus) {
      if (menus === void 0) {
        this._data = /* @__PURE__ */ Object.create(null);
        this._persist();
      } else {
        for (const { id } of menus) {
          if (this._data[id]) {
            delete this._data[id];
          }
        }
        this._persist();
      }
    }
    _persist() {
      try {
        this._ignoreChangeEvent = true;
        const raw = JSON.stringify(this._data);
        this._storageService.store(
          PersistedMenuHideState_1._key,
          raw,
          0,
          0
          /* StorageTarget.USER */
        );
      } finally {
        this._ignoreChangeEvent = false;
      }
    }
  }, PersistedMenuHideState_1 = _n, _n._key = "menu.hiddenCommands", _n);
  PersistedMenuHideState = PersistedMenuHideState_1 = __decorate$2y([
    __param$2w(0, IStorageService)
  ], PersistedMenuHideState);
  class MenuInfoSnapshot {
    constructor(_id, _collectContextKeysForSubmenus) {
      this._id = _id;
      this._collectContextKeysForSubmenus = _collectContextKeysForSubmenus;
      this._menuGroups = [];
      this._allMenuIds = /* @__PURE__ */ new Set();
      this._structureContextKeys = /* @__PURE__ */ new Set();
      this._preconditionContextKeys = /* @__PURE__ */ new Set();
      this._toggledContextKeys = /* @__PURE__ */ new Set();
      this.refresh();
    }
    get allMenuIds() {
      return this._allMenuIds;
    }
    get structureContextKeys() {
      return this._structureContextKeys;
    }
    get preconditionContextKeys() {
      return this._preconditionContextKeys;
    }
    get toggledContextKeys() {
      return this._toggledContextKeys;
    }
    refresh() {
      this._menuGroups.length = 0;
      this._allMenuIds.clear();
      this._structureContextKeys.clear();
      this._preconditionContextKeys.clear();
      this._toggledContextKeys.clear();
      const menuItems = this._sort(MenuRegistry.getMenuItems(this._id));
      let group;
      for (const item of menuItems) {
        const groupName = item.group || "";
        if (!group || group[0] !== groupName) {
          group = [groupName, []];
          this._menuGroups.push(group);
        }
        group[1].push(item);
        this._collectContextKeysAndSubmenuIds(item);
      }
      this._allMenuIds.add(this._id);
    }
    _sort(menuItems) {
      return menuItems;
    }
    _collectContextKeysAndSubmenuIds(item) {
      MenuInfoSnapshot._fillInKbExprKeys(item.when, this._structureContextKeys);
      if (isIMenuItem(item)) {
        if (item.command.precondition) {
          MenuInfoSnapshot._fillInKbExprKeys(item.command.precondition, this._preconditionContextKeys);
        }
        if (item.command.toggled) {
          const toggledExpression = item.command.toggled.condition || item.command.toggled;
          MenuInfoSnapshot._fillInKbExprKeys(toggledExpression, this._toggledContextKeys);
        }
      } else if (this._collectContextKeysForSubmenus) {
        MenuRegistry.getMenuItems(item.submenu).forEach(this._collectContextKeysAndSubmenuIds, this);
        this._allMenuIds.add(item.submenu);
      }
    }
    static _fillInKbExprKeys(exp, set) {
      if (exp) {
        for (const key of exp.keys()) {
          set.add(key);
        }
      }
    }
  }
  let MenuInfo = MenuInfo_1 = class MenuInfo extends MenuInfoSnapshot {
    constructor(_id, _hiddenStates, _collectContextKeysForSubmenus, _commandService, _keybindingService, _contextKeyService) {
      super(_id, _collectContextKeysForSubmenus);
      this._hiddenStates = _hiddenStates;
      this._commandService = _commandService;
      this._keybindingService = _keybindingService;
      this._contextKeyService = _contextKeyService;
      this.refresh();
    }
    createActionGroups(options) {
      const result = [];
      for (const group of this._menuGroups) {
        const [id, items] = group;
        let activeActions;
        for (const item of items) {
          if (this._contextKeyService.contextMatchesRules(item.when)) {
            const isMenuItem = isIMenuItem(item);
            if (isMenuItem) {
              this._hiddenStates.setDefaultState(this._id, item.command.id, !!item.isHiddenByDefault);
            }
            const menuHide = createMenuHide(this._id, isMenuItem ? item.command : item, this._hiddenStates);
            if (isMenuItem) {
              const menuKeybinding = createConfigureKeybindingAction(this._commandService, this._keybindingService, item.command.id, item.when);
              (activeActions ??= []).push(new MenuItemAction(item.command, item.alt, options, menuHide, menuKeybinding, this._contextKeyService, this._commandService));
            } else {
              const groups = new MenuInfo_1(item.submenu, this._hiddenStates, this._collectContextKeysForSubmenus, this._commandService, this._keybindingService, this._contextKeyService).createActionGroups(options);
              const submenuActions = Separator.join(...groups.map((g) => g[1]));
              if (submenuActions.length > 0) {
                (activeActions ??= []).push(new SubmenuItemAction(item, menuHide, submenuActions));
              }
            }
          }
        }
        if (activeActions && activeActions.length > 0) {
          result.push([id, activeActions]);
        }
      }
      return result;
    }
    _sort(menuItems) {
      return menuItems.sort(MenuInfo_1._compareMenuItems);
    }
    static _compareMenuItems(a, b) {
      const aGroup = a.group;
      const bGroup = b.group;
      if (aGroup !== bGroup) {
        if (!aGroup) {
          return 1;
        } else if (!bGroup) {
          return -1;
        }
        if (aGroup === "navigation") {
          return -1;
        } else if (bGroup === "navigation") {
          return 1;
        }
        const value = aGroup.localeCompare(bGroup);
        if (value !== 0) {
          return value;
        }
      }
      const aPrio = a.order || 0;
      const bPrio = b.order || 0;
      if (aPrio < bPrio) {
        return -1;
      } else if (aPrio > bPrio) {
        return 1;
      }
      return MenuInfo_1._compareTitles(isIMenuItem(a) ? a.command.title : a.title, isIMenuItem(b) ? b.command.title : b.title);
    }
    static _compareTitles(a, b) {
      const aStr = typeof a === "string" ? a : a.original;
      const bStr = typeof b === "string" ? b : b.original;
      return aStr.localeCompare(bStr);
    }
  };
  MenuInfo = MenuInfo_1 = __decorate$2y([
    __param$2w(3, ICommandService),
    __param$2w(4, IKeybindingService),
    __param$2w(5, IContextKeyService)
  ], MenuInfo);
  let MenuImpl = class MenuImpl {
    constructor(id, hiddenStates, options, commandService, keybindingService, contextKeyService) {
      this._disposables = new DisposableStore();
      this._menuInfo = new MenuInfo(id, hiddenStates, options.emitEventsForSubmenuChanges, commandService, keybindingService, contextKeyService);
      const rebuildMenuSoon = new RunOnceScheduler(() => {
        this._menuInfo.refresh();
        this._onDidChange.fire({ menu: this, isStructuralChange: true, isEnablementChange: true, isToggleChange: true });
      }, options.eventDebounceDelay);
      this._disposables.add(rebuildMenuSoon);
      this._disposables.add(MenuRegistry.onDidChangeMenu((e) => {
        for (const id2 of this._menuInfo.allMenuIds) {
          if (e.has(id2)) {
            rebuildMenuSoon.schedule();
            break;
          }
        }
      }));
      const lazyListener = this._disposables.add(new DisposableStore());
      const merge = (events) => {
        let isStructuralChange = false;
        let isEnablementChange = false;
        let isToggleChange = false;
        for (const item of events) {
          isStructuralChange = isStructuralChange || item.isStructuralChange;
          isEnablementChange = isEnablementChange || item.isEnablementChange;
          isToggleChange = isToggleChange || item.isToggleChange;
          if (isStructuralChange && isEnablementChange && isToggleChange) {
            break;
          }
        }
        return { menu: this, isStructuralChange, isEnablementChange, isToggleChange };
      };
      const startLazyListener = () => {
        lazyListener.add(contextKeyService.onDidChangeContext((e) => {
          const isStructuralChange = e.affectsSome(this._menuInfo.structureContextKeys);
          const isEnablementChange = e.affectsSome(this._menuInfo.preconditionContextKeys);
          const isToggleChange = e.affectsSome(this._menuInfo.toggledContextKeys);
          if (isStructuralChange || isEnablementChange || isToggleChange) {
            this._onDidChange.fire({ menu: this, isStructuralChange, isEnablementChange, isToggleChange });
          }
        }));
        lazyListener.add(hiddenStates.onDidChange((e) => {
          this._onDidChange.fire({ menu: this, isStructuralChange: true, isEnablementChange: false, isToggleChange: false });
        }));
      };
      this._onDidChange = new DebounceEmitter({
        // start/stop context key listener
        onWillAddFirstListener: startLazyListener,
        onDidRemoveLastListener: lazyListener.clear.bind(lazyListener),
        delay: options.eventDebounceDelay,
        merge
      });
      this.onDidChange = this._onDidChange.event;
    }
    getActions(options) {
      return this._menuInfo.createActionGroups(options);
    }
    dispose() {
      this._disposables.dispose();
      this._onDidChange.dispose();
    }
  };
  MenuImpl = __decorate$2y([
    __param$2w(3, ICommandService),
    __param$2w(4, IKeybindingService),
    __param$2w(5, IContextKeyService)
  ], MenuImpl);
  function createMenuHide(menu, command, states) {
    const id = isISubmenuItem(command) ? command.submenu.id : command.id;
    const title = typeof command.title === "string" ? command.title : command.title.value;
    const hide2 = toAction({
      id: `hide/${menu.id}/${id}`,
      label: localize(1651, "Hide '{0}'", title),
      run() {
        states.updateHidden(menu, id, true);
      }
    });
    const toggle = toAction({
      id: `toggle/${menu.id}/${id}`,
      label: title,
      get checked() {
        return !states.isHidden(menu, id);
      },
      run() {
        states.updateHidden(menu, id, !!this.checked);
      }
    });
    return {
      hide: hide2,
      toggle,
      get isHidden() {
        return !toggle.checked;
      }
    };
  }
  function createConfigureKeybindingAction(commandService, keybindingService, commandId, when = void 0, enabled = true) {
    return toAction({
      id: `configureKeybinding/${commandId}`,
      label: localize(1652, "Configure Keybinding"),
      enabled,
      run() {
        const hasKeybinding = !!keybindingService.lookupKeybinding(commandId);
        const whenValue = !hasKeybinding && when ? when.serialize() : void 0;
        commandService.executeCommand("workbench.action.openGlobalKeybindings", `@command:${commandId}` + (whenValue ? ` +when:${whenValue}` : ""));
      }
    });
  }
  const IActionViewItemService = createDecorator("IActionViewItemService");
  class ActionViewItemService {
    constructor() {
      this._providers = /* @__PURE__ */ new Map();
      this._onDidChange = new Emitter$1();
      this.onDidChange = this._onDidChange.event;
    }
    dispose() {
      this._onDidChange.dispose();
    }
    lookUp(menu, commandOrMenuId) {
      return this._providers.get(this._makeKey(menu, commandOrMenuId));
    }
    _makeKey(menu, commandOrMenuId) {
      return `${menu.id}/${commandOrMenuId instanceof MenuId ? commandOrMenuId.id : commandOrMenuId}`;
    }
  }
  registerSingleton(
    IActionViewItemService,
    ActionViewItemService,
    1
    /* InstantiationType.Delayed */
  );
  var __decorate$2x = 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$2v = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  let WorkbenchToolBar = class WorkbenchToolBar extends ToolBar {
    constructor(container, _options, _menuService, _contextKeyService, _contextMenuService, _keybindingService, _commandService, telemetryService) {
      super(container, _contextMenuService, {
        // defaults
        getKeyBinding: (action) => _keybindingService.lookupKeybinding(action.id) ?? void 0,
        // options (override defaults)
        ..._options,
        // mandatory (overide options)
        allowContextMenu: true,
        skipTelemetry: typeof _options?.telemetrySource === "string"
      });
      this._options = _options;
      this._menuService = _menuService;
      this._contextKeyService = _contextKeyService;
      this._contextMenuService = _contextMenuService;
      this._keybindingService = _keybindingService;
      this._commandService = _commandService;
      this._sessionDisposables = this._store.add(new DisposableStore());
      const telemetrySource = _options?.telemetrySource;
      if (telemetrySource) {
        this._store.add(this.actionBar.onDidRun((e) => telemetryService.publicLog2("workbenchActionExecuted", { id: e.action.id, from: telemetrySource })));
      }
    }
    setActions(_primary, _secondary = [], menuIds) {
      this._sessionDisposables.clear();
      const primary = _primary.slice();
      const secondary = _secondary.slice();
      const toggleActions = [];
      let toggleActionsCheckedCount = 0;
      const extraSecondary = [];
      let someAreHidden = false;
      if (this._options?.hiddenItemStrategy !== -1) {
        for (let i2 = 0; i2 < primary.length; i2++) {
          const action = primary[i2];
          if (!(action instanceof MenuItemAction) && !(action instanceof SubmenuItemAction)) {
            continue;
          }
          if (!action.hideActions) {
            continue;
          }
          toggleActions.push(action.hideActions.toggle);
          if (action.hideActions.toggle.checked) {
            toggleActionsCheckedCount++;
          }
          if (action.hideActions.isHidden) {
            someAreHidden = true;
            primary[i2] = void 0;
            if (this._options?.hiddenItemStrategy !== 0) {
              extraSecondary[i2] = action;
            }
          }
        }
      }
      if (this._options?.overflowBehavior !== void 0) {
        const exemptedIds = intersection(new Set(this._options.overflowBehavior.exempted), Iterable.map(primary, (a) => a?.id));
        const maxItems = this._options.overflowBehavior.maxItems - exemptedIds.size;
        let count = 0;
        for (let i2 = 0; i2 < primary.length; i2++) {
          const action = primary[i2];
          if (!action) {
            continue;
          }
          count++;
          if (exemptedIds.has(action.id)) {
            continue;
          }
          if (count >= maxItems) {
            primary[i2] = void 0;
            extraSecondary[i2] = action;
          }
        }
      }
      coalesceInPlace(primary);
      coalesceInPlace(extraSecondary);
      super.setActions(primary, Separator.join(extraSecondary, secondary));
      if (toggleActions.length > 0 || primary.length > 0) {
        this._sessionDisposables.add(addDisposableListener(this.getElement(), "contextmenu", (e) => {
          const event = new StandardMouseEvent(getWindow(this.getElement()), e);
          const action = this.getItemAction(event.target);
          if (!action) {
            return;
          }
          event.preventDefault();
          event.stopPropagation();
          const primaryActions = [];
          if (action instanceof MenuItemAction && action.menuKeybinding) {
            primaryActions.push(action.menuKeybinding);
          } else if (!(action instanceof SubmenuItemAction || action instanceof ToggleMenuAction)) {
            const supportsKeybindings = !!this._keybindingService.lookupKeybinding(action.id);
            primaryActions.push(createConfigureKeybindingAction(this._commandService, this._keybindingService, action.id, void 0, supportsKeybindings));
          }
          if (toggleActions.length > 0) {
            let noHide = false;
            if (toggleActionsCheckedCount === 1 && this._options?.hiddenItemStrategy === 0) {
              noHide = true;
              for (let i2 = 0; i2 < toggleActions.length; i2++) {
                if (toggleActions[i2].checked) {
                  toggleActions[i2] = toAction({
                    id: action.id,
                    label: action.label,
                    checked: true,
                    enabled: false,
                    run() {
                    }
                  });
                  break;
                }
              }
            }
            if (!noHide && (action instanceof MenuItemAction || action instanceof SubmenuItemAction)) {
              if (!action.hideActions) {
                return;
              }
              primaryActions.push(action.hideActions.hide);
            } else {
              primaryActions.push(toAction({
                id: "label",
                label: localize(1649, "Hide"),
                enabled: false,
                run() {
                }
              }));
            }
          }
          const actions = Separator.join(primaryActions, toggleActions);
          if (this._options?.resetMenu && !menuIds) {
            menuIds = [this._options.resetMenu];
          }
          if (someAreHidden && menuIds) {
            actions.push(new Separator());
            actions.push(toAction({
              id: "resetThisMenu",
              label: localize(1650, "Reset Menu"),
              run: () => this._menuService.resetHiddenStates(menuIds)
            }));
          }
          if (actions.length === 0) {
            return;
          }
          this._contextMenuService.showContextMenu({
            getAnchor: () => event,
            getActions: () => actions,
            // add context menu actions (iff appicable)
            menuId: this._options?.contextMenu,
            menuActionOptions: { renderShortTitle: true, ...this._options?.menuOptions },
            skipTelemetry: typeof this._options?.telemetrySource === "string",
            contextKeyService: this._contextKeyService
          });
        }));
      }
    }
  };
  WorkbenchToolBar = __decorate$2x([
    __param$2v(2, IMenuService),
    __param$2v(3, IContextKeyService),
    __param$2v(4, IContextMenuService),
    __param$2v(5, IKeybindingService),
    __param$2v(6, ICommandService),
    __param$2v(7, ITelemetryService)
  ], WorkbenchToolBar);
  let MenuWorkbenchToolBar = class MenuWorkbenchToolBar extends WorkbenchToolBar {
    get onDidChangeMenuItems() {
      return this._onDidChangeMenuItems.event;
    }
    constructor(container, menuId, options, menuService, contextKeyService, contextMenuService, keybindingService, commandService, telemetryService, actionViewService, instantiationService) {
      super(container, {
        resetMenu: menuId,
        ...options,
        actionViewItemProvider: (action, opts) => {
          let provider = actionViewService.lookUp(menuId, action instanceof SubmenuItemAction ? action.item.submenu.id : action.id);
          if (!provider) {
            provider = options?.actionViewItemProvider;
          }
          const viewItem = provider?.(action, opts, instantiationService, getWindow(container).vscodeWindowId);
          if (viewItem) {
            return viewItem;
          }
          return createActionViewItem(instantiationService, action, opts);
        }
      }, menuService, contextKeyService, contextMenuService, keybindingService, commandService, telemetryService);
      this._onDidChangeMenuItems = this._store.add(new Emitter$1());
      const menu = this._store.add(menuService.createMenu(menuId, contextKeyService, { emitEventsForSubmenuChanges: true, eventDebounceDelay: options?.eventDebounceDelay }));
      const updateToolbar = () => {
        const { primary, secondary } = getActionBarActions(menu.getActions(options?.menuOptions), options?.toolbarOptions?.primaryGroup, options?.toolbarOptions?.shouldInlineSubmenu, options?.toolbarOptions?.useSeparatorsInPrimaryActions);
        container.classList.toggle("has-no-actions", primary.length === 0 && secondary.length === 0);
        super.setActions(primary, secondary);
      };
      this._store.add(menu.onDidChange(() => {
        updateToolbar();
        this._onDidChangeMenuItems.fire(this);
      }));
      this._store.add(actionViewService.onDidChange((e) => {
        if (e === menuId) {
          updateToolbar();
        }
      }));
      updateToolbar();
    }
    /**
     * @deprecated The WorkbenchToolBar does not support this method because it works with menus.
     */
    setActions() {
      throw new BugIndicatingError("This toolbar is populated from a menu.");
    }
  };
  MenuWorkbenchToolBar = __decorate$2x([
    __param$2v(3, IMenuService),
    __param$2v(4, IContextKeyService),
    __param$2v(5, IContextMenuService),
    __param$2v(6, IKeybindingService),
    __param$2v(7, ICommandService),
    __param$2v(8, ITelemetryService),
    __param$2v(9, IActionViewItemService),
    __param$2v(10, IInstantiationService)
  ], MenuWorkbenchToolBar);
  var __decorate$2w = 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$2u = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  const IHoverService = createDecorator("hoverService");
  let WorkbenchHoverDelegate = class WorkbenchHoverDelegate extends Disposable {
    get delay() {
      if (this.isInstantlyHovering()) {
        return 0;
      }
      if (this.hoverOptions?.dynamicDelay) {
        return (content) => this.hoverOptions?.dynamicDelay?.(content) ?? this._delay;
      }
      return this._delay;
    }
    constructor(placement, hoverOptions, overrideOptions = {}, configurationService, hoverService) {
      super();
      this.placement = placement;
      this.hoverOptions = hoverOptions;
      this.overrideOptions = overrideOptions;
      this.configurationService = configurationService;
      this.hoverService = hoverService;
      this.lastHoverHideTime = 0;
      this.timeLimit = 200;
      this.hoverDisposables = this._register(new DisposableStore());
      this._delay = this.configurationService.getValue("workbench.hover.delay");
      this._register(this.configurationService.onDidChangeConfiguration((e) => {
        if (e.affectsConfiguration("workbench.hover.delay")) {
          this._delay = this.configurationService.getValue("workbench.hover.delay");
        }
      }));
    }
    showHover(options, focus) {
      const overrideOptions = typeof this.overrideOptions === "function" ? this.overrideOptions(options, focus) : this.overrideOptions;
      this.hoverDisposables.clear();
      const targets = isHTMLElement(options.target) ? [options.target] : options.target.targetElements;
      for (const target of targets) {
        this.hoverDisposables.add(addStandardDisposableListener(target, "keydown", (e) => {
          if (e.equals(
            9
            /* KeyCode.Escape */
          )) {
            this.hoverService.hideHover();
          }
        }));
      }
      const id = isHTMLElement(options.content) ? void 0 : typeof options.content === "string" ? options.content.toString() : options.content.value;
      return this.hoverService.showInstantHover({
        ...options,
        ...overrideOptions,
        persistence: {
          hideOnKeyDown: true,
          ...overrideOptions.persistence
        },
        id,
        appearance: {
          ...options.appearance,
          compact: true,
          skipFadeInAnimation: this.isInstantlyHovering(),
          ...overrideOptions.appearance
        }
      }, focus);
    }
    isInstantlyHovering() {
      return !!this.hoverOptions?.instantHover && Date.now() - this.lastHoverHideTime < this.timeLimit;
    }
    onDidHideHover() {
      this.hoverDisposables.clear();
      if (this.hoverOptions?.instantHover) {
        this.lastHoverHideTime = Date.now();
      }
    }
  };
  WorkbenchHoverDelegate = __decorate$2w([
    __param$2u(3, IConfigurationService),
    __param$2u(4, IHoverService)
  ], WorkbenchHoverDelegate);
  const nativeHoverDelegate = {
    showHover: function() {
      throw new Error("Native hover function not implemented.");
    },
    delay: 0,
    showNativeHover: true
  };
  class TextModelText extends AbstractText {
    constructor(_textModel) {
      super();
      this._textModel = _textModel;
    }
    getValueOfRange(range2) {
      return this._textModel.getValueInRange(range2);
    }
    getLineLength(lineNumber) {
      return this._textModel.getLineLength(lineNumber);
    }
    get length() {
      const lastLineNumber = this._textModel.getLineCount();
      const lastLineLen = this._textModel.getLineLength(lastLineNumber);
      return new TextLength(lastLineNumber - 1, lastLineLen);
    }
  }
  class ActionRunnerWithContext extends ActionRunner {
    constructor(_getContext) {
      super();
      this._getContext = _getContext;
    }
    runAction(action, _context) {
      const ctx = this._getContext();
      return super.runAction(action, ctx);
    }
  }
  class EditorGutter extends Disposable {
    constructor(_editor, _domNode, itemProvider) {
      super();
      this._editor = _editor;
      this._domNode = _domNode;
      this.itemProvider = itemProvider;
      this.scrollTop = observableFromEvent(this, this._editor.onDidScrollChange, (e) => (
        /** @description editor.onDidScrollChange */
        this._editor.getScrollTop()
      ));
      this.isScrollTopZero = this.scrollTop.map((scrollTop) => (
        /** @description isScrollTopZero */
        scrollTop === 0
      ));
      this.modelAttached = observableFromEvent(this, this._editor.onDidChangeModel, (e) => (
        /** @description editor.onDidChangeModel */
        this._editor.hasModel()
      ));
      this.editorOnDidChangeViewZones = observableSignalFromEvent("onDidChangeViewZones", this._editor.onDidChangeViewZones);
      this.editorOnDidContentSizeChange = observableSignalFromEvent("onDidContentSizeChange", this._editor.onDidContentSizeChange);
      this.domNodeSizeChanged = observableSignal("domNodeSizeChanged");
      this.views = /* @__PURE__ */ new Map();
      this._domNode.className = "gutter monaco-editor";
      const scrollDecoration = this._domNode.appendChild(h("div.scroll-decoration", { role: "presentation", ariaHidden: "true", style: { width: "100%" } }).root);
      const o = new ResizeObserver(() => {
        transaction((tx) => {
          this.domNodeSizeChanged.trigger(tx);
        });
      });
      o.observe(this._domNode);
      this._register(toDisposable(() => o.disconnect()));
      this._register(autorun((reader) => {
        scrollDecoration.className = this.isScrollTopZero.read(reader) ? "" : "scroll-decoration";
      }));
      this._register(autorun((reader) => (
        /** @description EditorGutter.Render */
        this.render(reader)
      )));
    }
    dispose() {
      super.dispose();
      reset(this._domNode);
    }
    render(reader) {
      if (!this.modelAttached.read(reader)) {
        return;
      }
      this.domNodeSizeChanged.read(reader);
      this.editorOnDidChangeViewZones.read(reader);
      this.editorOnDidContentSizeChange.read(reader);
      const scrollTop = this.scrollTop.read(reader);
      const visibleRanges = this._editor.getVisibleRanges();
      const unusedIds = new Set(this.views.keys());
      const viewRange = OffsetRange.ofStartAndLength(0, this._domNode.clientHeight);
      if (!viewRange.isEmpty) {
        for (const visibleRange of visibleRanges) {
          const visibleRange2 = new LineRange(visibleRange.startLineNumber, visibleRange.endLineNumber + 1);
          const gutterItems = this.itemProvider.getIntersectingGutterItems(visibleRange2, reader);
          transaction((tx) => {
            for (const gutterItem of gutterItems) {
              if (!gutterItem.range.intersect(visibleRange2)) {
                continue;
              }
              unusedIds.delete(gutterItem.id);
              let view = this.views.get(gutterItem.id);
              if (!view) {
                const viewDomNode = document.createElement("div");
                this._domNode.appendChild(viewDomNode);
                const gutterItemObs = observableValue("item", gutterItem);
                const itemView = this.itemProvider.createView(gutterItemObs, viewDomNode);
                view = new ManagedGutterItemView(gutterItemObs, itemView, viewDomNode);
                this.views.set(gutterItem.id, view);
              } else {
                view.item.set(gutterItem, tx);
              }
              const top = gutterItem.range.startLineNumber <= this._editor.getModel().getLineCount() ? this._editor.getTopForLineNumber(gutterItem.range.startLineNumber, true) - scrollTop : gutterItem.range.startLineNumber > 1 ? this._editor.getBottomForLineNumber(gutterItem.range.startLineNumber - 1, false) - scrollTop : 0;
              const bottom = gutterItem.range.endLineNumberExclusive === 1 ? Math.max(top, this._editor.getTopForLineNumber(gutterItem.range.startLineNumber, false) - scrollTop) : Math.max(top, this._editor.getBottomForLineNumber(gutterItem.range.endLineNumberExclusive - 1, true) - scrollTop);
              const height = bottom - top;
              view.domNode.style.top = `${top}px`;
              view.domNode.style.height = `${height}px`;
              view.gutterItemView.layout(OffsetRange.ofStartAndLength(top, height), viewRange);
            }
          });
        }
      }
      for (const id of unusedIds) {
        const view = this.views.get(id);
        view.gutterItemView.dispose();
        view.domNode.remove();
        this.views.delete(id);
      }
    }
  }
  class ManagedGutterItemView {
    constructor(item, gutterItemView, domNode) {
      this.item = item;
      this.gutterItemView = gutterItemView;
      this.domNode = domNode;
    }
  }
  var __decorate$2v = 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$2t = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  const emptyArr$1 = [];
  const width = 35;
  let DiffEditorGutter = class DiffEditorGutter extends Disposable {
    constructor(diffEditorRoot, _diffModel, _editors, _options, _sashLayout, _boundarySashes, _instantiationService, _contextKeyService, _menuService) {
      super();
      this._diffModel = _diffModel;
      this._editors = _editors;
      this._options = _options;
      this._sashLayout = _sashLayout;
      this._boundarySashes = _boundarySashes;
      this._instantiationService = _instantiationService;
      this._contextKeyService = _contextKeyService;
      this._menuService = _menuService;
      this._menu = this._register(this._menuService.createMenu(MenuId.DiffEditorHunkToolbar, this._contextKeyService));
      this._actions = observableFromEvent(this, this._menu.onDidChange, () => this._menu.getActions());
      this._hasActions = this._actions.map((a) => a.length > 0);
      this._showSash = derived(this, (reader) => this._options.renderSideBySide.read(reader) && this._hasActions.read(reader));
      this.width = derived(this, (reader) => this._hasActions.read(reader) ? width : 0);
      this.elements = h("div.gutter@gutter", { style: { position: "absolute", height: "100%", width: width + "px" } }, []);
      this._currentDiff = derived(this, (reader) => {
        const model = this._diffModel.read(reader);
        if (!model) {
          return void 0;
        }
        const mappings = model.diff.read(reader)?.mappings;
        const cursorPosition = this._editors.modifiedCursor.read(reader);
        if (!cursorPosition) {
          return void 0;
        }
        return mappings?.find((m) => m.lineRangeMapping.modified.contains(cursorPosition.lineNumber));
      });
      this._selectedDiffs = derived(this, (reader) => {
        const model = this._diffModel.read(reader);
        const diff = model?.diff.read(reader);
        if (!diff) {
          return emptyArr$1;
        }
        const selections = this._editors.modifiedSelections.read(reader);
        if (selections.every((s) => s.isEmpty())) {
          return emptyArr$1;
        }
        const selectedLineNumbers = new LineRangeSet(selections.map((s) => LineRange.fromRangeInclusive(s)));
        const selectedMappings = diff.mappings.filter((m) => m.lineRangeMapping.innerChanges && selectedLineNumbers.intersects(m.lineRangeMapping.modified));
        const result = selectedMappings.map((mapping) => ({
          mapping,
          rangeMappings: mapping.lineRangeMapping.innerChanges.filter((c) => selections.some((s) => Range$2.areIntersecting(c.modifiedRange, s)))
        }));
        if (result.length === 0 || result.every((r) => r.rangeMappings.length === 0)) {
          return emptyArr$1;
        }
        return result;
      });
      this._register(prependRemoveOnDispose(diffEditorRoot, this.elements.root));
      this._register(addDisposableListener(this.elements.root, "click", () => {
        this._editors.modified.focus();
      }));
      this._register(applyStyle(this.elements.root, { display: this._hasActions.map((a) => a ? "block" : "none") }));
      derivedDisposable(this, (reader) => {
        const showSash = this._showSash.read(reader);
        return !showSash ? void 0 : new DiffEditorSash(diffEditorRoot, this._sashLayout.dimensions, this._options.enableSplitViewResizing, this._boundarySashes, derivedWithSetter(this, (reader2) => this._sashLayout.sashLeft.read(reader2) - width, (v, tx) => this._sashLayout.sashLeft.set(v + width, tx)), () => this._sashLayout.resetSash());
      }).recomputeInitiallyAndOnChange(this._store);
      const gutterItems = derived(this, (reader) => {
        const model = this._diffModel.read(reader);
        if (!model) {
          return [];
        }
        const diffs = model.diff.read(reader);
        if (!diffs) {
          return [];
        }
        const selection = this._selectedDiffs.read(reader);
        if (selection.length > 0) {
          const m = DetailedLineRangeMapping.fromRangeMappings(selection.flatMap((s) => s.rangeMappings));
          return [
            new DiffGutterItem(m, true, MenuId.DiffEditorSelectionToolbar, void 0, model.model.original.uri, model.model.modified.uri)
          ];
        }
        const currentDiff = this._currentDiff.read(reader);
        return diffs.mappings.map((m) => new DiffGutterItem(m.lineRangeMapping.withInnerChangesFromLineRanges(), m.lineRangeMapping === currentDiff?.lineRangeMapping, MenuId.DiffEditorHunkToolbar, void 0, model.model.original.uri, model.model.modified.uri));
      });
      this._register(new EditorGutter(this._editors.modified, this.elements.root, {
        getIntersectingGutterItems: (range2, reader) => gutterItems.read(reader),
        createView: (item, target) => {
          return this._instantiationService.createInstance(DiffToolBar, item, target, this);
        }
      }));
      this._register(addDisposableListener(this.elements.gutter, EventType$1.MOUSE_WHEEL, (e) => {
        if (this._editors.modified.getOption(
          117
          /* EditorOption.scrollbar */
        ).handleMouseWheel) {
          this._editors.modified.delegateScrollFromMouseWheelEvent(e);
        }
      }, { passive: false }));
    }
    computeStagedValue(mapping) {
      const c = mapping.innerChanges ?? [];
      const modified = new TextModelText(this._editors.modifiedModel.get());
      const original = new TextModelText(this._editors.original.getModel());
      const edit2 = new TextEdit(c.map((c2) => c2.toTextEdit(modified)));
      const value = edit2.apply(original);
      return value;
    }
    layout(left) {
      this.elements.gutter.style.left = left + "px";
    }
  };
  DiffEditorGutter = __decorate$2v([
    __param$2t(6, IInstantiationService),
    __param$2t(7, IContextKeyService),
    __param$2t(8, IMenuService)
  ], DiffEditorGutter);
  class DiffGutterItem {
    constructor(mapping, showAlways, menuId, rangeOverride, originalUri, modifiedUri) {
      this.mapping = mapping;
      this.showAlways = showAlways;
      this.menuId = menuId;
      this.rangeOverride = rangeOverride;
      this.originalUri = originalUri;
      this.modifiedUri = modifiedUri;
    }
    get id() {
      return this.mapping.modified.toString();
    }
    get range() {
      return this.rangeOverride ?? this.mapping.modified;
    }
  }
  let DiffToolBar = class DiffToolBar extends Disposable {
    constructor(_item, target, gutter, instantiationService) {
      super();
      this._item = _item;
      this._elements = h("div.gutterItem", { style: { height: "20px", width: "34px" } }, [
        h("div.background@background", {}, []),
        h("div.buttons@buttons", {}, [])
      ]);
      this._showAlways = this._item.map(this, (item) => item.showAlways);
      this._menuId = this._item.map(this, (item) => item.menuId);
      this._isSmall = observableValue(this, false);
      this._lastItemRange = void 0;
      this._lastViewRange = void 0;
      const hoverDelegate = this._register(instantiationService.createInstance(WorkbenchHoverDelegate, "element", { instantHover: true }, { position: {
        hoverPosition: 1
        /* HoverPosition.RIGHT */
      } }));
      this._register(appendRemoveOnDispose(target, this._elements.root));
      this._register(autorun((reader) => {
        const showAlways = this._showAlways.read(reader);
        this._elements.root.classList.toggle("noTransition", true);
        this._elements.root.classList.toggle("showAlways", showAlways);
        setTimeout(() => {
          this._elements.root.classList.toggle("noTransition", false);
        }, 0);
      }));
      this._register(autorunWithStore((reader, store) => {
        this._elements.buttons.replaceChildren();
        const i2 = store.add(instantiationService.createInstance(MenuWorkbenchToolBar, this._elements.buttons, this._menuId.read(reader), {
          orientation: 1,
          hoverDelegate,
          toolbarOptions: {
            primaryGroup: (g) => g.startsWith("primary")
          },
          overflowBehavior: { maxItems: this._isSmall.read(reader) ? 1 : 3 },
          hiddenItemStrategy: 0,
          actionRunner: store.add(new ActionRunnerWithContext(() => {
            const item = this._item.read(void 0);
            const mapping = item.mapping;
            return {
              mapping,
              originalWithModifiedChanges: gutter.computeStagedValue(mapping),
              originalUri: item.originalUri,
              modifiedUri: item.modifiedUri
            };
          })),
          menuOptions: {
            shouldForwardArgs: true
          }
        }));
        store.add(i2.onDidChangeMenuItems(() => {
          if (this._lastItemRange) {
            this.layout(this._lastItemRange, this._lastViewRange);
          }
        }));
      }));
    }
    layout(itemRange, viewRange) {
      this._lastItemRange = itemRange;
      this._lastViewRange = viewRange;
      let itemHeight = this._elements.buttons.clientHeight;
      this._isSmall.set(this._item.get().mapping.original.startLineNumber === 1 && itemRange.length < 30, void 0);
      itemHeight = this._elements.buttons.clientHeight;
      const middleHeight = itemRange.length / 2 - itemHeight / 2;
      const margin = itemHeight;
      let effectiveCheckboxTop = itemRange.start + middleHeight;
      const preferredViewPortRange = OffsetRange.tryCreate(margin, viewRange.endExclusive - margin - itemHeight);
      const preferredParentRange = OffsetRange.tryCreate(itemRange.start + margin, itemRange.endExclusive - itemHeight - margin);
      if (preferredParentRange && preferredViewPortRange && preferredParentRange.start < preferredParentRange.endExclusive) {
        effectiveCheckboxTop = preferredViewPortRange.clip(effectiveCheckboxTop);
        effectiveCheckboxTop = preferredParentRange.clip(effectiveCheckboxTop);
      }
      this._elements.buttons.style.top = `${effectiveCheckboxTop - itemRange.start}px`;
    }
  };
  DiffToolBar = __decorate$2v([
    __param$2t(3, IInstantiationService)
  ], DiffToolBar);
  var __decorate$2u = 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$2s = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  var HideUnchangedRegionsFeature_1;
  let HideUnchangedRegionsFeature = (_o = class extends Disposable {
    static setBreadcrumbsSourceFactory(factory) {
      this._breadcrumbsSourceFactory.set(factory, void 0);
    }
    get isUpdatingHiddenAreas() {
      return this._isUpdatingHiddenAreas;
    }
    constructor(_editors, _diffModel, _options, _instantiationService) {
      super();
      this._editors = _editors;
      this._diffModel = _diffModel;
      this._options = _options;
      this._instantiationService = _instantiationService;
      this._modifiedOutlineSource = derivedDisposable(this, (reader) => {
        const m = this._editors.modifiedModel.read(reader);
        const factory = HideUnchangedRegionsFeature_1._breadcrumbsSourceFactory.read(reader);
        return !m || !factory ? void 0 : factory(m, this._instantiationService);
      });
      this._isUpdatingHiddenAreas = false;
      this._register(this._editors.original.onDidChangeCursorPosition((e) => {
        if (e.reason === 1) {
          return;
        }
        const m = this._diffModel.get();
        transaction((tx) => {
          for (const s of this._editors.original.getSelections() || []) {
            m?.ensureOriginalLineIsVisible(s.getStartPosition().lineNumber, 0, tx);
            m?.ensureOriginalLineIsVisible(s.getEndPosition().lineNumber, 0, tx);
          }
        });
      }));
      this._register(this._editors.modified.onDidChangeCursorPosition((e) => {
        if (e.reason === 1) {
          return;
        }
        const m = this._diffModel.get();
        transaction((tx) => {
          for (const s of this._editors.modified.getSelections() || []) {
            m?.ensureModifiedLineIsVisible(s.getStartPosition().lineNumber, 0, tx);
            m?.ensureModifiedLineIsVisible(s.getEndPosition().lineNumber, 0, tx);
          }
        });
      }));
      const unchangedRegions = this._diffModel.map((m, reader) => {
        const regions = m?.unchangedRegions.read(reader) ?? [];
        if (regions.length === 1 && regions[0].modifiedLineNumber === 1 && regions[0].lineCount === this._editors.modifiedModel.read(reader)?.getLineCount()) {
          return [];
        }
        return regions;
      });
      this.viewZones = derived(this, (reader) => {
        const modifiedOutlineSource = this._modifiedOutlineSource.read(reader);
        if (!modifiedOutlineSource) {
          return { origViewZones: [], modViewZones: [] };
        }
        const origViewZones = [];
        const modViewZones = [];
        const sideBySide = this._options.renderSideBySide.read(reader);
        const compactMode = this._options.compactMode.read(reader);
        const curUnchangedRegions = unchangedRegions.read(reader);
        for (let i2 = 0; i2 < curUnchangedRegions.length; i2++) {
          const r = curUnchangedRegions[i2];
          if (r.shouldHideControls(reader)) {
            continue;
          }
          if (compactMode && (i2 === 0 || i2 === curUnchangedRegions.length - 1)) {
            continue;
          }
          if (compactMode) {
            {
              const d = derived(this, (reader2) => (
                /** @description hiddenOriginalRangeStart */
                r.getHiddenOriginalRange(reader2).startLineNumber - 1
              ));
              const origVz = new PlaceholderViewZone(d, 12);
              origViewZones.push(origVz);
              reader.store.add(new CompactCollapsedCodeOverlayWidget(this._editors.original, origVz, r, !sideBySide));
            }
            {
              const d = derived(this, (reader2) => (
                /** @description hiddenModifiedRangeStart */
                r.getHiddenModifiedRange(reader2).startLineNumber - 1
              ));
              const modViewZone = new PlaceholderViewZone(d, 12);
              modViewZones.push(modViewZone);
              reader.store.add(new CompactCollapsedCodeOverlayWidget(this._editors.modified, modViewZone, r));
            }
          } else {
            {
              const d = derived(this, (reader2) => (
                /** @description hiddenOriginalRangeStart */
                r.getHiddenOriginalRange(reader2).startLineNumber - 1
              ));
              const origVz = new PlaceholderViewZone(d, 24);
              origViewZones.push(origVz);
              reader.store.add(new CollapsedCodeOverlayWidget(this._editors.original, origVz, r, r.originalUnchangedRange, !sideBySide, modifiedOutlineSource, (l) => this._diffModel.get().ensureModifiedLineIsVisible(l, 2, void 0), this._options));
            }
            {
              const d = derived(this, (reader2) => (
                /** @description hiddenModifiedRangeStart */
                r.getHiddenModifiedRange(reader2).startLineNumber - 1
              ));
              const modViewZone = new PlaceholderViewZone(d, 24);
              modViewZones.push(modViewZone);
              reader.store.add(new CollapsedCodeOverlayWidget(this._editors.modified, modViewZone, r, r.modifiedUnchangedRange, false, modifiedOutlineSource, (l) => this._diffModel.get().ensureModifiedLineIsVisible(l, 2, void 0), this._options));
            }
          }
        }
        return { origViewZones, modViewZones };
      });
      const unchangedLinesDecoration = {
        description: "unchanged lines",
        className: "diff-unchanged-lines",
        isWholeLine: true
      };
      const unchangedLinesDecorationShow = {
        description: "Fold Unchanged",
        glyphMarginHoverMessage: new MarkdownString(void 0, { isTrusted: true, supportThemeIcons: true }).appendMarkdown(localize(124, "Fold Unchanged Region")),
        glyphMarginClassName: "fold-unchanged " + ThemeIcon.asClassName(Codicon.fold),
        zIndex: 10001
      };
      this._register(applyObservableDecorations(this._editors.original, derived(this, (reader) => {
        const curUnchangedRegions = unchangedRegions.read(reader);
        const result = curUnchangedRegions.map((r) => ({
          range: r.originalUnchangedRange.toInclusiveRange(),
          options: unchangedLinesDecoration
        }));
        for (const r of curUnchangedRegions) {
          if (r.shouldHideControls(reader)) {
            result.push({
              range: Range$2.fromPositions(new Position$1(r.originalLineNumber, 1)),
              options: unchangedLinesDecorationShow
            });
          }
        }
        return result;
      })));
      this._register(applyObservableDecorations(this._editors.modified, derived(this, (reader) => {
        const curUnchangedRegions = unchangedRegions.read(reader);
        const result = curUnchangedRegions.map((r) => ({
          range: r.modifiedUnchangedRange.toInclusiveRange(),
          options: unchangedLinesDecoration
        }));
        for (const r of curUnchangedRegions) {
          if (r.shouldHideControls(reader)) {
            result.push({
              range: LineRange.ofLength(r.modifiedLineNumber, 1).toInclusiveRange(),
              options: unchangedLinesDecorationShow
            });
          }
        }
        return result;
      })));
      this._register(autorun((reader) => {
        const curUnchangedRegions = unchangedRegions.read(reader);
        this._isUpdatingHiddenAreas = true;
        try {
          this._editors.original.setHiddenAreas(curUnchangedRegions.map((r) => r.getHiddenOriginalRange(reader).toInclusiveRange()).filter(isDefined));
          this._editors.modified.setHiddenAreas(curUnchangedRegions.map((r) => r.getHiddenModifiedRange(reader).toInclusiveRange()).filter(isDefined));
        } finally {
          this._isUpdatingHiddenAreas = false;
        }
      }));
      this._register(this._editors.modified.onMouseUp((event) => {
        if (!event.event.rightButton && event.target.position && event.target.element?.className.includes("fold-unchanged")) {
          const lineNumber = event.target.position.lineNumber;
          const model = this._diffModel.get();
          if (!model) {
            return;
          }
          const region = model.unchangedRegions.get().find((r) => r.modifiedUnchangedRange.contains(lineNumber));
          if (!region) {
            return;
          }
          region.collapseAll(void 0);
          event.event.stopPropagation();
          event.event.preventDefault();
        }
      }));
      this._register(this._editors.original.onMouseUp((event) => {
        if (!event.event.rightButton && event.target.position && event.target.element?.className.includes("fold-unchanged")) {
          const lineNumber = event.target.position.lineNumber;
          const model = this._diffModel.get();
          if (!model) {
            return;
          }
          const region = model.unchangedRegions.get().find((r) => r.originalUnchangedRange.contains(lineNumber));
          if (!region) {
            return;
          }
          region.collapseAll(void 0);
          event.event.stopPropagation();
          event.event.preventDefault();
        }
      }));
    }
  }, HideUnchangedRegionsFeature_1 = _o, _o._breadcrumbsSourceFactory = observableValue(_o, () => ({
    dispose() {
    },
    getBreadcrumbItems(startRange, reader) {
      return [];
    }
  })), _o);
  HideUnchangedRegionsFeature = HideUnchangedRegionsFeature_1 = __decorate$2u([
    __param$2s(3, IInstantiationService)
  ], HideUnchangedRegionsFeature);
  class CompactCollapsedCodeOverlayWidget extends ViewZoneOverlayWidget {
    constructor(editor2, _viewZone, _unchangedRegion, _hide = false) {
      const root = h("div.diff-hidden-lines-widget");
      super(editor2, _viewZone, root.root);
      this._unchangedRegion = _unchangedRegion;
      this._hide = _hide;
      this._nodes = h("div.diff-hidden-lines-compact", [
        h("div.line-left", []),
        h("div.text@text", []),
        h("div.line-right", [])
      ]);
      root.root.appendChild(this._nodes.root);
      if (this._hide) {
        this._nodes.root.replaceChildren();
      }
      this._register(autorun((reader) => {
        if (!this._hide) {
          const lineCount = this._unchangedRegion.getHiddenModifiedRange(reader).length;
          const linesHiddenText = localize(125, "{0} hidden lines", lineCount);
          this._nodes.text.innerText = linesHiddenText;
        }
      }));
    }
  }
  class CollapsedCodeOverlayWidget extends ViewZoneOverlayWidget {
    constructor(_editor, _viewZone, _unchangedRegion, _unchangedRegionRange, _hide, _modifiedOutlineSource, _revealModifiedHiddenLine, _options) {
      const root = h("div.diff-hidden-lines-widget");
      super(_editor, _viewZone, root.root);
      this._editor = _editor;
      this._unchangedRegion = _unchangedRegion;
      this._unchangedRegionRange = _unchangedRegionRange;
      this._hide = _hide;
      this._modifiedOutlineSource = _modifiedOutlineSource;
      this._revealModifiedHiddenLine = _revealModifiedHiddenLine;
      this._options = _options;
      this._nodes = h("div.diff-hidden-lines", [
        h("div.top@top", { title: localize(126, "Click or drag to show more above") }),
        h("div.center@content", { style: { display: "flex" } }, [
          h("div@first", { style: { display: "flex", justifyContent: "center", alignItems: "center", flexShrink: "0" } }, [$$l("a", { title: localize(127, "Show Unchanged Region"), role: "button", onclick: () => {
            this._unchangedRegion.showAll(void 0);
          } }, ...renderLabelWithIcons("$(unfold)"))]),
          h("div@others", { style: { display: "flex", justifyContent: "center", alignItems: "center" } })
        ]),
        h("div.bottom@bottom", { title: localize(128, "Click or drag to show more below"), role: "button" })
      ]);
      root.root.appendChild(this._nodes.root);
      if (!this._hide) {
        this._register(applyStyle(this._nodes.first, { width: observableCodeEditor(this._editor).layoutInfoContentLeft }));
      } else {
        reset(this._nodes.first);
      }
      this._register(autorun((reader) => {
        const isFullyRevealed = this._unchangedRegion.visibleLineCountTop.read(reader) + this._unchangedRegion.visibleLineCountBottom.read(reader) === this._unchangedRegion.lineCount;
        this._nodes.bottom.classList.toggle("canMoveTop", !isFullyRevealed);
        this._nodes.bottom.classList.toggle("canMoveBottom", this._unchangedRegion.visibleLineCountBottom.read(reader) > 0);
        this._nodes.top.classList.toggle("canMoveTop", this._unchangedRegion.visibleLineCountTop.read(reader) > 0);
        this._nodes.top.classList.toggle("canMoveBottom", !isFullyRevealed);
        const isDragged = this._unchangedRegion.isDragged.read(reader);
        const domNode = this._editor.getDomNode();
        if (domNode) {
          domNode.classList.toggle("draggingUnchangedRegion", !!isDragged);
          if (isDragged === "top") {
            domNode.classList.toggle("canMoveTop", this._unchangedRegion.visibleLineCountTop.read(reader) > 0);
            domNode.classList.toggle("canMoveBottom", !isFullyRevealed);
          } else if (isDragged === "bottom") {
            domNode.classList.toggle("canMoveTop", !isFullyRevealed);
            domNode.classList.toggle("canMoveBottom", this._unchangedRegion.visibleLineCountBottom.read(reader) > 0);
          } else {
            domNode.classList.toggle("canMoveTop", false);
            domNode.classList.toggle("canMoveBottom", false);
          }
        }
      }));
      const editor2 = this._editor;
      this._register(addDisposableListener(this._nodes.top, "mousedown", (e) => {
        if (e.button !== 0) {
          return;
        }
        this._nodes.top.classList.toggle("dragging", true);
        this._nodes.root.classList.toggle("dragging", true);
        e.preventDefault();
        const startTop = e.clientY;
        let didMove = false;
        const cur = this._unchangedRegion.visibleLineCountTop.get();
        this._unchangedRegion.isDragged.set("top", void 0);
        const window2 = getWindow(this._nodes.top);
        const mouseMoveListener = addDisposableListener(window2, "mousemove", (e2) => {
          const currentTop = e2.clientY;
          const delta = currentTop - startTop;
          didMove = didMove || Math.abs(delta) > 2;
          const lineDelta = Math.round(delta / editor2.getOption(
            75
            /* EditorOption.lineHeight */
          ));
          const newVal = Math.max(0, Math.min(cur + lineDelta, this._unchangedRegion.getMaxVisibleLineCountTop()));
          this._unchangedRegion.visibleLineCountTop.set(newVal, void 0);
        });
        const mouseUpListener = addDisposableListener(window2, "mouseup", (e2) => {
          if (!didMove) {
            this._unchangedRegion.showMoreAbove(this._options.hideUnchangedRegionsRevealLineCount.get(), void 0);
          }
          this._nodes.top.classList.toggle("dragging", false);
          this._nodes.root.classList.toggle("dragging", false);
          this._unchangedRegion.isDragged.set(void 0, void 0);
          mouseMoveListener.dispose();
          mouseUpListener.dispose();
        });
      }));
      this._register(addDisposableListener(this._nodes.bottom, "mousedown", (e) => {
        if (e.button !== 0) {
          return;
        }
        this._nodes.bottom.classList.toggle("dragging", true);
        this._nodes.root.classList.toggle("dragging", true);
        e.preventDefault();
        const startTop = e.clientY;
        let didMove = false;
        const cur = this._unchangedRegion.visibleLineCountBottom.get();
        this._unchangedRegion.isDragged.set("bottom", void 0);
        const window2 = getWindow(this._nodes.bottom);
        const mouseMoveListener = addDisposableListener(window2, "mousemove", (e2) => {
          const currentTop = e2.clientY;
          const delta = currentTop - startTop;
          didMove = didMove || Math.abs(delta) > 2;
          const lineDelta = Math.round(delta / editor2.getOption(
            75
            /* EditorOption.lineHeight */
          ));
          const newVal = Math.max(0, Math.min(cur - lineDelta, this._unchangedRegion.getMaxVisibleLineCountBottom()));
          const top = this._unchangedRegionRange.endLineNumberExclusive > editor2.getModel().getLineCount() ? editor2.getContentHeight() : editor2.getTopForLineNumber(this._unchangedRegionRange.endLineNumberExclusive);
          this._unchangedRegion.visibleLineCountBottom.set(newVal, void 0);
          const top2 = this._unchangedRegionRange.endLineNumberExclusive > editor2.getModel().getLineCount() ? editor2.getContentHeight() : editor2.getTopForLineNumber(this._unchangedRegionRange.endLineNumberExclusive);
          editor2.setScrollTop(editor2.getScrollTop() + (top2 - top));
        });
        const mouseUpListener = addDisposableListener(window2, "mouseup", (e2) => {
          this._unchangedRegion.isDragged.set(void 0, void 0);
          if (!didMove) {
            const top = editor2.getTopForLineNumber(this._unchangedRegionRange.endLineNumberExclusive);
            this._unchangedRegion.showMoreBelow(this._options.hideUnchangedRegionsRevealLineCount.get(), void 0);
            const top2 = editor2.getTopForLineNumber(this._unchangedRegionRange.endLineNumberExclusive);
            editor2.setScrollTop(editor2.getScrollTop() + (top2 - top));
          }
          this._nodes.bottom.classList.toggle("dragging", false);
          this._nodes.root.classList.toggle("dragging", false);
          mouseMoveListener.dispose();
          mouseUpListener.dispose();
        });
      }));
      this._register(autorun((reader) => {
        const children = [];
        if (!this._hide) {
          const lineCount = _unchangedRegion.getHiddenModifiedRange(reader).length;
          const linesHiddenText = localize(129, "{0} hidden lines", lineCount);
          const span = $$l("span", { title: localize(130, "Double click to unfold") }, linesHiddenText);
          span.addEventListener("dblclick", (e) => {
            if (e.button !== 0) {
              return;
            }
            e.preventDefault();
            this._unchangedRegion.showAll(void 0);
          });
          children.push(span);
          const range2 = this._unchangedRegion.getHiddenModifiedRange(reader);
          const items = this._modifiedOutlineSource.getBreadcrumbItems(range2, reader);
          if (items.length > 0) {
            children.push($$l("span", void 0, "  |  "));
            for (let i2 = 0; i2 < items.length; i2++) {
              const item = items[i2];
              const icon = SymbolKinds.toIcon(item.kind);
              const divItem = h("div.breadcrumb-item", {
                style: { display: "flex", alignItems: "center" }
              }, [
                renderIcon(icon),
                " ",
                item.name,
                ...i2 === items.length - 1 ? [] : [renderIcon(Codicon.chevronRight)]
              ]).root;
              children.push(divItem);
              divItem.onclick = () => {
                this._revealModifiedHiddenLine(item.startLineNumber);
              };
            }
          }
        }
        reset(this._nodes.others, ...children);
      }));
    }
  }
  const emptyArr = [];
  class RevertButtonsFeature extends Disposable {
    constructor(_editors, _diffModel, _options, _widget) {
      super();
      this._editors = _editors;
      this._diffModel = _diffModel;
      this._options = _options;
      this._widget = _widget;
      this._selectedDiffs = derived(this, (reader) => {
        const model = this._diffModel.read(reader);
        const diff = model?.diff.read(reader);
        if (!diff) {
          return emptyArr;
        }
        const selections = this._editors.modifiedSelections.read(reader);
        if (selections.every((s) => s.isEmpty())) {
          return emptyArr;
        }
        const selectedLineNumbers = new LineRangeSet(selections.map((s) => LineRange.fromRangeInclusive(s)));
        const selectedMappings = diff.mappings.filter((m) => m.lineRangeMapping.innerChanges && selectedLineNumbers.intersects(m.lineRangeMapping.modified));
        const result = selectedMappings.map((mapping) => ({
          mapping,
          rangeMappings: mapping.lineRangeMapping.innerChanges.filter((c) => selections.some((s) => Range$2.areIntersecting(c.modifiedRange, s)))
        }));
        if (result.length === 0 || result.every((r) => r.rangeMappings.length === 0)) {
          return emptyArr;
        }
        return result;
      });
      this._register(autorunWithStore((reader, store) => {
        if (!this._options.shouldRenderOldRevertArrows.read(reader)) {
          return;
        }
        const model = this._diffModel.read(reader);
        const diff = model?.diff.read(reader);
        if (!model || !diff) {
          return;
        }
        if (model.movedTextToCompare.read(reader)) {
          return;
        }
        const glyphWidgetsModified = [];
        const selectedDiffs = this._selectedDiffs.read(reader);
        const selectedDiffsSet = new Set(selectedDiffs.map((d) => d.mapping));
        if (selectedDiffs.length > 0) {
          const selections = this._editors.modifiedSelections.read(reader);
          const btn = store.add(new RevertButton(selections[selections.length - 1].positionLineNumber, this._widget, selectedDiffs.flatMap((d) => d.rangeMappings), true));
          this._editors.modified.addGlyphMarginWidget(btn);
          glyphWidgetsModified.push(btn);
        }
        for (const m of diff.mappings) {
          if (selectedDiffsSet.has(m)) {
            continue;
          }
          if (!m.lineRangeMapping.modified.isEmpty && m.lineRangeMapping.innerChanges) {
            const btn = store.add(new RevertButton(m.lineRangeMapping.modified.startLineNumber, this._widget, m.lineRangeMapping, false));
            this._editors.modified.addGlyphMarginWidget(btn);
            glyphWidgetsModified.push(btn);
          }
        }
        store.add(toDisposable(() => {
          for (const w of glyphWidgetsModified) {
            this._editors.modified.removeGlyphMarginWidget(w);
          }
        }));
      }));
    }
  }
  const _RevertButton = class _RevertButton extends Disposable {
    getId() {
      return this._id;
    }
    constructor(_lineNumber, _widget, _diffs, _revertSelection) {
      super();
      this._lineNumber = _lineNumber;
      this._widget = _widget;
      this._diffs = _diffs;
      this._revertSelection = _revertSelection;
      this._id = `revertButton${_RevertButton.counter++}`;
      this._domNode = h("div.revertButton", {
        title: this._revertSelection ? localize(135, "Revert Selected Changes") : localize(136, "Revert Change")
      }, [renderIcon(Codicon.arrowRight)]).root;
      this._register(addDisposableListener(this._domNode, EventType$1.MOUSE_DOWN, (e) => {
        if (e.button !== 2) {
          e.stopPropagation();
          e.preventDefault();
        }
      }));
      this._register(addDisposableListener(this._domNode, EventType$1.MOUSE_UP, (e) => {
        e.stopPropagation();
        e.preventDefault();
      }));
      this._register(addDisposableListener(this._domNode, EventType$1.CLICK, (e) => {
        if (this._diffs instanceof LineRangeMapping) {
          this._widget.revert(this._diffs);
        } else {
          this._widget.revertRangeMappings(this._diffs);
        }
        e.stopPropagation();
        e.preventDefault();
      }));
    }
    /**
     * Get the dom node of the glyph widget.
     */
    getDomNode() {
      return this._domNode;
    }
    /**
     * Get the placement of the glyph widget.
     */
    getPosition() {
      return {
        lane: GlyphMarginLane$1.Right,
        range: {
          startColumn: 1,
          startLineNumber: this._lineNumber,
          endColumn: 1,
          endLineNumber: this._lineNumber
        },
        zIndex: 10001
      };
    }
  };
  _RevertButton.counter = 0;
  let RevertButton = _RevertButton;
  var __decorate$2t = 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$2r = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  let DiffEditorWidget = class DiffEditorWidget extends DelegatingEditor {
    get onDidContentSizeChange() {
      return this._editors.onDidContentSizeChange;
    }
    constructor(_domElement, options, codeEditorWidgetOptions, _parentContextKeyService, _parentInstantiationService, _codeEditorService, _accessibilitySignalService, _editorProgressService) {
      super();
      this._domElement = _domElement;
      this._parentContextKeyService = _parentContextKeyService;
      this._parentInstantiationService = _parentInstantiationService;
      this._codeEditorService = _codeEditorService;
      this._accessibilitySignalService = _accessibilitySignalService;
      this._editorProgressService = _editorProgressService;
      this.elements = h("div.monaco-diff-editor.side-by-side", { style: { position: "relative", height: "100%" } }, [
        h("div.editor.original@original", { style: { position: "absolute", height: "100%" } }),
        h("div.editor.modified@modified", { style: { position: "absolute", height: "100%" } }),
        h("div.accessibleDiffViewer@accessibleDiffViewer", { style: { position: "absolute", height: "100%" } })
      ]);
      this._diffModelSrc = this._register(disposableObservableValue(this, void 0));
      this._diffModel = derived(this, (reader) => this._diffModelSrc.read(reader)?.object);
      this.onDidChangeModel = Event.fromObservableLight(this._diffModel);
      this._contextKeyService = this._register(this._parentContextKeyService.createScoped(this._domElement));
      this._instantiationService = this._register(this._parentInstantiationService.createChild(new ServiceCollection([IContextKeyService, this._contextKeyService])));
      this._boundarySashes = observableValue(this, void 0);
      this._accessibleDiffViewerShouldBeVisible = observableValue(this, false);
      this._accessibleDiffViewerVisible = derived(this, (reader) => this._options.onlyShowAccessibleDiffViewer.read(reader) ? true : this._accessibleDiffViewerShouldBeVisible.read(reader));
      this._movedBlocksLinesPart = observableValue(this, void 0);
      this._layoutInfo = derived(this, (reader) => {
        const fullWidth = this._rootSizeObserver.width.read(reader);
        const fullHeight = this._rootSizeObserver.height.read(reader);
        if (this._rootSizeObserver.automaticLayout) {
          this.elements.root.style.height = "100%";
        } else {
          this.elements.root.style.height = fullHeight + "px";
        }
        const sash = this._sash.read(reader);
        const gutter = this._gutter.read(reader);
        const gutterWidth = gutter?.width.read(reader) ?? 0;
        const overviewRulerPartWidth = this._overviewRulerPart.read(reader)?.width ?? 0;
        let originalLeft, originalWidth, modifiedLeft, modifiedWidth, gutterLeft;
        const sideBySide = !!sash;
        if (sideBySide) {
          const sashLeft = sash.sashLeft.read(reader);
          const movedBlocksLinesWidth = this._movedBlocksLinesPart.read(reader)?.width.read(reader) ?? 0;
          originalLeft = 0;
          originalWidth = sashLeft - gutterWidth - movedBlocksLinesWidth;
          gutterLeft = sashLeft - gutterWidth;
          modifiedLeft = sashLeft;
          modifiedWidth = fullWidth - modifiedLeft - overviewRulerPartWidth;
        } else {
          gutterLeft = 0;
          const shouldHideOriginalLineNumbers = this._options.inlineViewHideOriginalLineNumbers.read(reader);
          originalLeft = gutterWidth;
          if (shouldHideOriginalLineNumbers) {
            originalWidth = 0;
          } else {
            originalWidth = Math.max(5, this._editors.originalObs.layoutInfoDecorationsLeft.read(reader));
          }
          modifiedLeft = gutterWidth + originalWidth;
          modifiedWidth = fullWidth - modifiedLeft - overviewRulerPartWidth;
        }
        this.elements.original.style.left = originalLeft + "px";
        this.elements.original.style.width = originalWidth + "px";
        this._editors.original.layout({ width: originalWidth, height: fullHeight }, true);
        gutter?.layout(gutterLeft);
        this.elements.modified.style.left = modifiedLeft + "px";
        this.elements.modified.style.width = modifiedWidth + "px";
        this._editors.modified.layout({ width: modifiedWidth, height: fullHeight }, true);
        return {
          modifiedEditor: this._editors.modified.getLayoutInfo(),
          originalEditor: this._editors.original.getLayoutInfo()
        };
      });
      this._diffValue = this._diffModel.map((m, r) => m?.diff.read(r));
      this.onDidUpdateDiff = Event.fromObservableLight(this._diffValue);
      this._codeEditorService.willCreateDiffEditor();
      this._contextKeyService.createKey("isInDiffEditor", true);
      this._domElement.appendChild(this.elements.root);
      this._register(toDisposable(() => this.elements.root.remove()));
      this._rootSizeObserver = this._register(new ObservableElementSizeObserver(this.elements.root, options.dimension));
      this._rootSizeObserver.setAutomaticLayout(options.automaticLayout ?? false);
      this._options = this._instantiationService.createInstance(DiffEditorOptions, options);
      this._register(autorun((reader) => {
        this._options.setWidth(this._rootSizeObserver.width.read(reader));
      }));
      this._contextKeyService.createKey(EditorContextKeys.isEmbeddedDiffEditor.key, false);
      this._register(bindContextKey(EditorContextKeys.isEmbeddedDiffEditor, this._contextKeyService, (reader) => this._options.isInEmbeddedEditor.read(reader)));
      this._register(bindContextKey(EditorContextKeys.comparingMovedCode, this._contextKeyService, (reader) => !!this._diffModel.read(reader)?.movedTextToCompare.read(reader)));
      this._register(bindContextKey(EditorContextKeys.diffEditorRenderSideBySideInlineBreakpointReached, this._contextKeyService, (reader) => this._options.couldShowInlineViewBecauseOfSize.read(reader)));
      this._register(bindContextKey(EditorContextKeys.diffEditorInlineMode, this._contextKeyService, (reader) => !this._options.renderSideBySide.read(reader)));
      this._register(bindContextKey(EditorContextKeys.hasChanges, this._contextKeyService, (reader) => (this._diffModel.read(reader)?.diff.read(reader)?.mappings.length ?? 0) > 0));
      this._editors = this._register(this._instantiationService.createInstance(DiffEditorEditors, this.elements.original, this.elements.modified, this._options, codeEditorWidgetOptions, (i2, c, o, o2) => this._createInnerEditor(i2, c, o, o2)));
      this._register(bindContextKey(EditorContextKeys.diffEditorOriginalWritable, this._contextKeyService, (reader) => this._options.originalEditable.read(reader)));
      this._register(bindContextKey(EditorContextKeys.diffEditorModifiedWritable, this._contextKeyService, (reader) => !this._options.readOnly.read(reader)));
      this._register(bindContextKey(EditorContextKeys.diffEditorOriginalUri, this._contextKeyService, (reader) => this._diffModel.read(reader)?.model.original.uri.toString() ?? ""));
      this._register(bindContextKey(EditorContextKeys.diffEditorModifiedUri, this._contextKeyService, (reader) => this._diffModel.read(reader)?.model.modified.uri.toString() ?? ""));
      this._overviewRulerPart = derivedDisposable(this, (reader) => !this._options.renderOverviewRuler.read(reader) ? void 0 : this._instantiationService.createInstance(readHotReloadableExport(OverviewRulerFeature), this._editors, this.elements.root, this._diffModel, this._rootSizeObserver.width, this._rootSizeObserver.height, this._layoutInfo.map((i2) => i2.modifiedEditor))).recomputeInitiallyAndOnChange(this._store);
      const dimensions = {
        height: this._rootSizeObserver.height,
        width: this._rootSizeObserver.width.map((w, reader) => w - (this._overviewRulerPart.read(reader)?.width ?? 0))
      };
      this._sashLayout = new SashLayout(this._options, dimensions);
      this._sash = derivedDisposable(this, (reader) => {
        const showSash = this._options.renderSideBySide.read(reader);
        this.elements.root.classList.toggle("side-by-side", showSash);
        return !showSash ? void 0 : new DiffEditorSash(this.elements.root, dimensions, this._options.enableSplitViewResizing, this._boundarySashes, this._sashLayout.sashLeft, () => this._sashLayout.resetSash());
      }).recomputeInitiallyAndOnChange(this._store);
      const unchangedRangesFeature = derivedDisposable(this, (reader) => (
        /** @description UnchangedRangesFeature */
        this._instantiationService.createInstance(readHotReloadableExport(HideUnchangedRegionsFeature), this._editors, this._diffModel, this._options)
      )).recomputeInitiallyAndOnChange(this._store);
      derivedDisposable(this, (reader) => (
        /** @description DiffEditorDecorations */
        this._instantiationService.createInstance(readHotReloadableExport(DiffEditorDecorations), this._editors, this._diffModel, this._options, this)
      )).recomputeInitiallyAndOnChange(this._store);
      const origViewZoneIdsToIgnore = /* @__PURE__ */ new Set();
      const modViewZoneIdsToIgnore = /* @__PURE__ */ new Set();
      let isUpdatingViewZones = false;
      const viewZoneManager = derivedDisposable(this, (reader) => (
        /** @description ViewZoneManager */
        this._instantiationService.createInstance(readHotReloadableExport(DiffEditorViewZones), getWindow(this._domElement), this._editors, this._diffModel, this._options, this, () => isUpdatingViewZones || unchangedRangesFeature.read(void 0).isUpdatingHiddenAreas, origViewZoneIdsToIgnore, modViewZoneIdsToIgnore)
      )).recomputeInitiallyAndOnChange(this._store);
      const originalViewZones = derived(this, (reader) => {
        const orig = viewZoneManager.read(reader).viewZones.read(reader).orig;
        const orig2 = unchangedRangesFeature.read(reader).viewZones.read(reader).origViewZones;
        return orig.concat(orig2);
      });
      const modifiedViewZones = derived(this, (reader) => {
        const mod = viewZoneManager.read(reader).viewZones.read(reader).mod;
        const mod2 = unchangedRangesFeature.read(reader).viewZones.read(reader).modViewZones;
        return mod.concat(mod2);
      });
      this._register(applyViewZones(this._editors.original, originalViewZones, (isUpdatingOrigViewZones) => {
        isUpdatingViewZones = isUpdatingOrigViewZones;
      }, origViewZoneIdsToIgnore));
      let scrollState;
      this._register(applyViewZones(this._editors.modified, modifiedViewZones, (isUpdatingModViewZones) => {
        isUpdatingViewZones = isUpdatingModViewZones;
        if (isUpdatingViewZones) {
          scrollState = StableEditorScrollState.capture(this._editors.modified);
        } else {
          scrollState?.restore(this._editors.modified);
          scrollState = void 0;
        }
      }, modViewZoneIdsToIgnore));
      this._accessibleDiffViewer = derivedDisposable(this, (reader) => this._instantiationService.createInstance(readHotReloadableExport(AccessibleDiffViewer), this.elements.accessibleDiffViewer, this._accessibleDiffViewerVisible, (visible, tx) => this._accessibleDiffViewerShouldBeVisible.set(visible, tx), this._options.onlyShowAccessibleDiffViewer.map((v) => !v), this._rootSizeObserver.width, this._rootSizeObserver.height, this._diffModel.map((m, r) => m?.diff.read(r)?.mappings.map((m2) => m2.lineRangeMapping)), new AccessibleDiffViewerModelFromEditors(this._editors))).recomputeInitiallyAndOnChange(this._store);
      const visibility = this._accessibleDiffViewerVisible.map((v) => v ? "hidden" : "visible");
      this._register(applyStyle(this.elements.modified, { visibility }));
      this._register(applyStyle(this.elements.original, { visibility }));
      this._createDiffEditorContributions();
      this._codeEditorService.addDiffEditor(this);
      this._register(toDisposable(() => {
        this._codeEditorService.removeDiffEditor(this);
      }));
      this._gutter = derivedDisposable(this, (reader) => {
        return this._options.shouldRenderGutterMenu.read(reader) ? this._instantiationService.createInstance(readHotReloadableExport(DiffEditorGutter), this.elements.root, this._diffModel, this._editors, this._options, this._sashLayout, this._boundarySashes) : void 0;
      });
      this._register(recomputeInitiallyAndOnChange(this._layoutInfo));
      derivedDisposable(this, (reader) => (
        /** @description MovedBlocksLinesPart */
        new (readHotReloadableExport(MovedBlocksLinesFeature))(this.elements.root, this._diffModel, this._layoutInfo.map((i2) => i2.originalEditor), this._layoutInfo.map((i2) => i2.modifiedEditor), this._editors)
      )).recomputeInitiallyAndOnChange(this._store, (value) => {
        this._movedBlocksLinesPart.set(value, void 0);
      });
      this._register(Event.runAndSubscribe(this._editors.modified.onDidChangeCursorPosition, (e) => this._handleCursorPositionChange(e, true)));
      this._register(Event.runAndSubscribe(this._editors.original.onDidChangeCursorPosition, (e) => this._handleCursorPositionChange(e, false)));
      const isInitializingDiff = this._diffModel.map(this, (m, reader) => {
        if (!m) {
          return void 0;
        }
        return m.diff.read(reader) === void 0 && !m.isDiffUpToDate.read(reader);
      });
      this._register(autorunWithStore((reader, store) => {
        if (isInitializingDiff.read(reader) === true) {
          const r = this._editorProgressService.show(true, 1e3);
          store.add(toDisposable(() => r.done()));
        }
      }));
      this._register(autorunWithStore((reader, store) => {
        store.add(new (readHotReloadableExport(RevertButtonsFeature))(this._editors, this._diffModel, this._options, this));
      }));
      this._register(autorunWithStore((reader, store) => {
        const model = this._diffModel.read(reader);
        if (!model) {
          return;
        }
        for (const m of [model.model.original, model.model.modified]) {
          store.add(m.onWillDispose((e) => {
            onUnexpectedError(new BugIndicatingError("TextModel got disposed before DiffEditorWidget model got reset"));
            this.setModel(null);
          }));
        }
      }));
      this._register(autorun((reader) => {
        this._options.setModel(this._diffModel.read(reader));
      }));
    }
    _createInnerEditor(instantiationService, container, options, editorWidgetOptions) {
      const editor2 = instantiationService.createInstance(CodeEditorWidget, container, options, editorWidgetOptions);
      return editor2;
    }
    _createDiffEditorContributions() {
      const contributions = EditorExtensionsRegistry.getDiffEditorContributions();
      for (const desc of contributions) {
        try {
          this._register(this._instantiationService.createInstance(desc.ctor, this));
        } catch (err) {
          onUnexpectedError(err);
        }
      }
    }
    get _targetEditor() {
      return this._editors.modified;
    }
    getEditorType() {
      return EditorType.IDiffEditor;
    }
    layout(dimension) {
      this._rootSizeObserver.observe(dimension);
    }
    hasTextFocus() {
      return this._editors.original.hasTextFocus() || this._editors.modified.hasTextFocus();
    }
    saveViewState() {
      const originalViewState = this._editors.original.saveViewState();
      const modifiedViewState = this._editors.modified.saveViewState();
      return {
        original: originalViewState,
        modified: modifiedViewState,
        modelState: this._diffModel.get()?.serializeState()
      };
    }
    restoreViewState(s) {
      if (s && s.original && s.modified) {
        const diffEditorState = s;
        this._editors.original.restoreViewState(diffEditorState.original);
        this._editors.modified.restoreViewState(diffEditorState.modified);
        if (diffEditorState.modelState) {
          this._diffModel.get()?.restoreSerializedState(diffEditorState.modelState);
        }
      }
    }
    handleInitialized() {
      this._editors.original.handleInitialized();
      this._editors.modified.handleInitialized();
    }
    createViewModel(model) {
      return this._instantiationService.createInstance(DiffEditorViewModel, model, this._options);
    }
    getModel() {
      return this._diffModel.get()?.model ?? null;
    }
    setModel(model) {
      const vm = !model ? null : "model" in model ? RefCounted.create(model).createNewRef(this) : RefCounted.create(this.createViewModel(model), this);
      this.setDiffModel(vm);
    }
    setDiffModel(viewModel, tx) {
      const currentModel = this._diffModel.get();
      if (!viewModel && currentModel) {
        this._accessibleDiffViewer.get().close();
      }
      if (this._diffModel.get() !== viewModel?.object) {
        subtransaction(tx, (tx2) => {
          const vm = viewModel?.object;
          observableFromEvent.batchEventsGlobally(tx2, () => {
            this._editors.original.setModel(vm ? vm.model.original : null);
            this._editors.modified.setModel(vm ? vm.model.modified : null);
          });
          const prevValueRef = this._diffModelSrc.get()?.createNewRef(this);
          this._diffModelSrc.set(viewModel?.createNewRef(this), tx2);
          setTimeout(() => {
            prevValueRef?.dispose();
          }, 0);
        });
      }
    }
    /**
     * @param changedOptions Only has values for top-level options that have actually changed.
     */
    updateOptions(changedOptions) {
      this._options.updateOptions(changedOptions);
    }
    getContainerDomNode() {
      return this._domElement;
    }
    getOriginalEditor() {
      return this._editors.original;
    }
    getModifiedEditor() {
      return this._editors.modified;
    }
    /**
     * @deprecated Use `this.getDiffComputationResult().changes2` instead.
     */
    getLineChanges() {
      const diffState = this._diffModel.get()?.diff.get();
      if (!diffState) {
        return null;
      }
      return toLineChanges(diffState);
    }
    getDiffComputationResult() {
      const diffState = this._diffModel.get()?.diff.get();
      if (!diffState) {
        return null;
      }
      return {
        changes: this.getLineChanges(),
        changes2: diffState.mappings.map((m) => m.lineRangeMapping),
        identical: diffState.identical,
        quitEarly: diffState.quitEarly
      };
    }
    revert(diff) {
      const model = this._diffModel.get();
      if (!model || !model.isDiffUpToDate.get()) {
        return;
      }
      this._editors.modified.pushUndoStop();
      this._editors.modified.executeEdits("diffEditor", [
        {
          range: diff.modified.toExclusiveRange(),
          text: model.model.original.getValueInRange(diff.original.toExclusiveRange())
        }
      ]);
      this._editors.modified.pushUndoStop();
    }
    revertRangeMappings(diffs) {
      const model = this._diffModel.get();
      if (!model || !model.isDiffUpToDate.get()) {
        return;
      }
      const changes = diffs.map((c) => ({
        range: c.modifiedRange,
        text: model.model.original.getValueInRange(c.originalRange)
      }));
      this._editors.modified.pushUndoStop();
      this._editors.modified.executeEdits("diffEditor", changes);
      this._editors.modified.pushUndoStop();
    }
    revertFocusedRangeMappings() {
      const model = this._diffModel.get();
      if (!model || !model.isDiffUpToDate.get()) {
        return;
      }
      const diffs = this._diffModel.get()?.diff.get()?.mappings;
      if (!diffs || diffs.length === 0) {
        return;
      }
      const modifiedEditor = this._editors.modified;
      if (!modifiedEditor.hasTextFocus()) {
        return;
      }
      const curLineNumber = modifiedEditor.getPosition().lineNumber;
      const selection = modifiedEditor.getSelection();
      const selectedRange = LineRange.fromRange(selection || new Range$2(curLineNumber, 0, curLineNumber, 0));
      const diffsToRevert = diffs.filter((d) => {
        return d.lineRangeMapping.modified.intersect(selectedRange);
      });
      modifiedEditor.pushUndoStop();
      modifiedEditor.executeEdits("diffEditor", diffsToRevert.map((d) => ({
        range: d.lineRangeMapping.modified.toExclusiveRange(),
        text: model.model.original.getValueInRange(d.lineRangeMapping.original.toExclusiveRange())
      })));
      modifiedEditor.pushUndoStop();
    }
    _goTo(diff) {
      this._editors.modified.setPosition(new Position$1(diff.lineRangeMapping.modified.startLineNumber, 1));
      this._editors.modified.revealRangeInCenter(diff.lineRangeMapping.modified.toExclusiveRange());
    }
    goToDiff(target) {
      const diffs = this._diffModel.get()?.diff.get()?.mappings;
      if (!diffs || diffs.length === 0) {
        return;
      }
      const curLineNumber = this._editors.modified.getPosition().lineNumber;
      let diff;
      if (target === "next") {
        const modifiedLineCount = this._editors.modified.getModel().getLineCount();
        if (modifiedLineCount === curLineNumber) {
          diff = diffs[0];
        } else {
          diff = diffs.find((d) => d.lineRangeMapping.modified.startLineNumber > curLineNumber) ?? diffs[0];
        }
      } else {
        diff = findLast(diffs, (d) => d.lineRangeMapping.modified.startLineNumber < curLineNumber) ?? diffs[diffs.length - 1];
      }
      this._goTo(diff);
      if (diff.lineRangeMapping.modified.isEmpty) {
        this._accessibilitySignalService.playSignal(AccessibilitySignal.diffLineDeleted, { source: "diffEditor.goToDiff" });
      } else if (diff.lineRangeMapping.original.isEmpty) {
        this._accessibilitySignalService.playSignal(AccessibilitySignal.diffLineInserted, { source: "diffEditor.goToDiff" });
      } else if (diff) {
        this._accessibilitySignalService.playSignal(AccessibilitySignal.diffLineModified, { source: "diffEditor.goToDiff" });
      }
    }
    revealFirstDiff() {
      const diffModel = this._diffModel.get();
      if (!diffModel) {
        return;
      }
      this.waitForDiff().then(() => {
        const diffs = diffModel.diff.get()?.mappings;
        if (!diffs || diffs.length === 0) {
          return;
        }
        this._goTo(diffs[0]);
      });
    }
    accessibleDiffViewerNext() {
      this._accessibleDiffViewer.get().next();
    }
    accessibleDiffViewerPrev() {
      this._accessibleDiffViewer.get().prev();
    }
    async waitForDiff() {
      const diffModel = this._diffModel.get();
      if (!diffModel) {
        return;
      }
      await diffModel.waitForDiff();
    }
    mapToOtherSide() {
      const isModifiedFocus = this._editors.modified.hasWidgetFocus();
      const source = isModifiedFocus ? this._editors.modified : this._editors.original;
      const destination = isModifiedFocus ? this._editors.original : this._editors.modified;
      let destinationSelection;
      const sourceSelection = source.getSelection();
      if (sourceSelection) {
        const mappings = this._diffModel.get()?.diff.get()?.mappings.map((m) => isModifiedFocus ? m.lineRangeMapping.flip() : m.lineRangeMapping);
        if (mappings) {
          const newRange1 = translatePosition(sourceSelection.getStartPosition(), mappings);
          const newRange2 = translatePosition(sourceSelection.getEndPosition(), mappings);
          destinationSelection = Range$2.plusRange(newRange1, newRange2);
        }
      }
      return { destination, destinationSelection };
    }
    switchSide() {
      const { destination, destinationSelection } = this.mapToOtherSide();
      destination.focus();
      if (destinationSelection) {
        destination.setSelection(destinationSelection);
      }
    }
    exitCompareMove() {
      const model = this._diffModel.get();
      if (!model) {
        return;
      }
      model.movedTextToCompare.set(void 0, void 0);
    }
    collapseAllUnchangedRegions() {
      const unchangedRegions = this._diffModel.get()?.unchangedRegions.get();
      if (!unchangedRegions) {
        return;
      }
      transaction((tx) => {
        for (const region of unchangedRegions) {
          region.collapseAll(tx);
        }
      });
    }
    showAllUnchangedRegions() {
      const unchangedRegions = this._diffModel.get()?.unchangedRegions.get();
      if (!unchangedRegions) {
        return;
      }
      transaction((tx) => {
        for (const region of unchangedRegions) {
          region.showAll(tx);
        }
      });
    }
    _handleCursorPositionChange(e, isModifiedEditor) {
      if (e?.reason === 3) {
        const diff = this._diffModel.get()?.diff.get()?.mappings.find((m) => isModifiedEditor ? m.lineRangeMapping.modified.contains(e.position.lineNumber) : m.lineRangeMapping.original.contains(e.position.lineNumber));
        if (diff?.lineRangeMapping.modified.isEmpty) {
          this._accessibilitySignalService.playSignal(AccessibilitySignal.diffLineDeleted, { source: "diffEditor.cursorPositionChanged" });
        } else if (diff?.lineRangeMapping.original.isEmpty) {
          this._accessibilitySignalService.playSignal(AccessibilitySignal.diffLineInserted, { source: "diffEditor.cursorPositionChanged" });
        } else if (diff) {
          this._accessibilitySignalService.playSignal(AccessibilitySignal.diffLineModified, { source: "diffEditor.cursorPositionChanged" });
        }
      }
    }
  };
  DiffEditorWidget = __decorate$2t([
    __param$2r(3, IContextKeyService),
    __param$2r(4, IInstantiationService),
    __param$2r(5, ICodeEditorService),
    __param$2r(6, IAccessibilitySignalService),
    __param$2r(7, IEditorProgressService)
  ], DiffEditorWidget);
  function toLineChanges(state) {
    return state.mappings.map((x) => {
      const m = x.lineRangeMapping;
      let originalStartLineNumber;
      let originalEndLineNumber;
      let modifiedStartLineNumber;
      let modifiedEndLineNumber;
      let innerChanges = m.innerChanges;
      if (m.original.isEmpty) {
        originalStartLineNumber = m.original.startLineNumber - 1;
        originalEndLineNumber = 0;
        innerChanges = void 0;
      } else {
        originalStartLineNumber = m.original.startLineNumber;
        originalEndLineNumber = m.original.endLineNumberExclusive - 1;
      }
      if (m.modified.isEmpty) {
        modifiedStartLineNumber = m.modified.startLineNumber - 1;
        modifiedEndLineNumber = 0;
        innerChanges = void 0;
      } else {
        modifiedStartLineNumber = m.modified.startLineNumber;
        modifiedEndLineNumber = m.modified.endLineNumberExclusive - 1;
      }
      return {
        originalStartLineNumber,
        originalEndLineNumber,
        modifiedStartLineNumber,
        modifiedEndLineNumber,
        charChanges: innerChanges?.map((m2) => ({
          originalStartLineNumber: m2.originalRange.startLineNumber,
          originalStartColumn: m2.originalRange.startColumn,
          originalEndLineNumber: m2.originalRange.endLineNumber,
          originalEndColumn: m2.originalRange.endColumn,
          modifiedStartLineNumber: m2.modifiedRange.startLineNumber,
          modifiedStartColumn: m2.modifiedRange.startColumn,
          modifiedEndLineNumber: m2.modifiedRange.endLineNumber,
          modifiedEndColumn: m2.modifiedRange.endColumn
        }))
      };
    });
  }
  class ToggleCollapseUnchangedRegions extends Action2 {
    constructor() {
      super({
        id: "diffEditor.toggleCollapseUnchangedRegions",
        title: localize2(85, "Toggle Collapse Unchanged Regions"),
        icon: Codicon.map,
        toggled: ContextKeyExpr.has("config.diffEditor.hideUnchangedRegions.enabled"),
        precondition: ContextKeyExpr.has("isInDiffEditor"),
        menu: {
          when: ContextKeyExpr.has("isInDiffEditor"),
          id: MenuId.EditorTitle,
          order: 22,
          group: "navigation"
        }
      });
    }
    run(accessor, ...args) {
      const configurationService = accessor.get(IConfigurationService);
      const newValue = !configurationService.getValue("diffEditor.hideUnchangedRegions.enabled");
      configurationService.updateValue("diffEditor.hideUnchangedRegions.enabled", newValue);
    }
  }
  class ToggleShowMovedCodeBlocks extends Action2 {
    constructor() {
      super({
        id: "diffEditor.toggleShowMovedCodeBlocks",
        title: localize2(86, "Toggle Show Moved Code Blocks"),
        precondition: ContextKeyExpr.has("isInDiffEditor")
      });
    }
    run(accessor, ...args) {
      const configurationService = accessor.get(IConfigurationService);
      const newValue = !configurationService.getValue("diffEditor.experimental.showMoves");
      configurationService.updateValue("diffEditor.experimental.showMoves", newValue);
    }
  }
  class ToggleUseInlineViewWhenSpaceIsLimited extends Action2 {
    constructor() {
      super({
        id: "diffEditor.toggleUseInlineViewWhenSpaceIsLimited",
        title: localize2(87, "Toggle Use Inline View When Space Is Limited"),
        precondition: ContextKeyExpr.has("isInDiffEditor")
      });
    }
    run(accessor, ...args) {
      const configurationService = accessor.get(IConfigurationService);
      const newValue = !configurationService.getValue("diffEditor.useInlineViewWhenSpaceIsLimited");
      configurationService.updateValue("diffEditor.useInlineViewWhenSpaceIsLimited", newValue);
    }
  }
  const diffEditorCategory = localize2(88, "Diff Editor");
  class SwitchSide extends EditorAction2 {
    constructor() {
      super({
        id: "diffEditor.switchSide",
        title: localize2(89, "Switch Side"),
        icon: Codicon.arrowSwap,
        precondition: ContextKeyExpr.has("isInDiffEditor"),
        f1: true,
        category: diffEditorCategory
      });
    }
    runEditorCommand(accessor, editor2, arg) {
      const diffEditor = findFocusedDiffEditor(accessor);
      if (diffEditor instanceof DiffEditorWidget) {
        if (arg && arg.dryRun) {
          return { destinationSelection: diffEditor.mapToOtherSide().destinationSelection };
        } else {
          diffEditor.switchSide();
        }
      }
      return void 0;
    }
  }
  class ExitCompareMove extends EditorAction2 {
    constructor() {
      super({
        id: "diffEditor.exitCompareMove",
        title: localize2(90, "Exit Compare Move"),
        icon: Codicon.close,
        precondition: EditorContextKeys.comparingMovedCode,
        f1: false,
        category: diffEditorCategory,
        keybinding: {
          weight: 1e4,
          primary: 9
        }
      });
    }
    runEditorCommand(accessor, editor2, ...args) {
      const diffEditor = findFocusedDiffEditor(accessor);
      if (diffEditor instanceof DiffEditorWidget) {
        diffEditor.exitCompareMove();
      }
    }
  }
  class CollapseAllUnchangedRegions extends EditorAction2 {
    constructor() {
      super({
        id: "diffEditor.collapseAllUnchangedRegions",
        title: localize2(91, "Collapse All Unchanged Regions"),
        icon: Codicon.fold,
        precondition: ContextKeyExpr.has("isInDiffEditor"),
        f1: true,
        category: diffEditorCategory
      });
    }
    runEditorCommand(accessor, editor2, ...args) {
      const diffEditor = findFocusedDiffEditor(accessor);
      if (diffEditor instanceof DiffEditorWidget) {
        diffEditor.collapseAllUnchangedRegions();
      }
    }
  }
  class ShowAllUnchangedRegions extends EditorAction2 {
    constructor() {
      super({
        id: "diffEditor.showAllUnchangedRegions",
        title: localize2(92, "Show All Unchanged Regions"),
        icon: Codicon.unfold,
        precondition: ContextKeyExpr.has("isInDiffEditor"),
        f1: true,
        category: diffEditorCategory
      });
    }
    runEditorCommand(accessor, editor2, ...args) {
      const diffEditor = findFocusedDiffEditor(accessor);
      if (diffEditor instanceof DiffEditorWidget) {
        diffEditor.showAllUnchangedRegions();
      }
    }
  }
  class RevertHunkOrSelection extends Action2 {
    constructor() {
      super({
        id: "diffEditor.revert",
        title: localize2(93, "Revert"),
        f1: true,
        category: diffEditorCategory,
        precondition: ContextKeyExpr.has("isInDiffEditor")
      });
    }
    run(accessor, arg) {
      return arg ? this.runViaToolbarContext(accessor, arg) : this.runViaCursorOrSelection(accessor);
    }
    runViaCursorOrSelection(accessor) {
      const diffEditor = findFocusedDiffEditor(accessor);
      if (diffEditor instanceof DiffEditorWidget) {
        diffEditor.revertFocusedRangeMappings();
      }
      return void 0;
    }
    runViaToolbarContext(accessor, arg) {
      const diffEditor = findDiffEditor(accessor, arg.originalUri, arg.modifiedUri);
      if (diffEditor instanceof DiffEditorWidget) {
        diffEditor.revertRangeMappings(arg.mapping.innerChanges ?? []);
      }
      return void 0;
    }
  }
  const accessibleDiffViewerCategory = localize2(94, "Accessible Diff Viewer");
  const _AccessibleDiffViewerNext = class _AccessibleDiffViewerNext extends Action2 {
    constructor() {
      super({
        id: _AccessibleDiffViewerNext.id,
        title: localize2(95, "Go to Next Difference"),
        category: accessibleDiffViewerCategory,
        precondition: ContextKeyExpr.has("isInDiffEditor"),
        keybinding: {
          primary: 65,
          weight: 100
          /* KeybindingWeight.EditorContrib */
        },
        f1: true
      });
    }
    run(accessor) {
      const diffEditor = findFocusedDiffEditor(accessor);
      diffEditor?.accessibleDiffViewerNext();
    }
  };
  _AccessibleDiffViewerNext.id = "editor.action.accessibleDiffViewer.next";
  let AccessibleDiffViewerNext = _AccessibleDiffViewerNext;
  const _AccessibleDiffViewerPrev = class _AccessibleDiffViewerPrev extends Action2 {
    constructor() {
      super({
        id: _AccessibleDiffViewerPrev.id,
        title: localize2(96, "Go to Previous Difference"),
        category: accessibleDiffViewerCategory,
        precondition: ContextKeyExpr.has("isInDiffEditor"),
        keybinding: {
          primary: 1024 | 65,
          weight: 100
          /* KeybindingWeight.EditorContrib */
        },
        f1: true
      });
    }
    run(accessor) {
      const diffEditor = findFocusedDiffEditor(accessor);
      diffEditor?.accessibleDiffViewerPrev();
    }
  };
  _AccessibleDiffViewerPrev.id = "editor.action.accessibleDiffViewer.prev";
  let AccessibleDiffViewerPrev = _AccessibleDiffViewerPrev;
  function findDiffEditor(accessor, originalUri, modifiedUri) {
    const codeEditorService = accessor.get(ICodeEditorService);
    const diffEditors = codeEditorService.listDiffEditors();
    return diffEditors.find((diffEditor) => {
      const modified = diffEditor.getModifiedEditor();
      const original = diffEditor.getOriginalEditor();
      return modified && modified.getModel()?.uri.toString() === modifiedUri.toString() && original && original.getModel()?.uri.toString() === originalUri.toString();
    }) || null;
  }
  function findFocusedDiffEditor(accessor) {
    const codeEditorService = accessor.get(ICodeEditorService);
    const diffEditors = codeEditorService.listDiffEditors();
    const activeElement = getActiveElement();
    if (activeElement) {
      for (const d of diffEditors) {
        const container = d.getContainerDomNode();
        if (container.contains(activeElement)) {
          return d;
        }
      }
    }
    return null;
  }
  registerAction2(ToggleCollapseUnchangedRegions);
  registerAction2(ToggleShowMovedCodeBlocks);
  registerAction2(ToggleUseInlineViewWhenSpaceIsLimited);
  MenuRegistry.appendMenuItem(MenuId.EditorTitle, {
    command: {
      id: new ToggleUseInlineViewWhenSpaceIsLimited().desc.id,
      title: localize(119, "Use Inline View When Space Is Limited"),
      toggled: ContextKeyExpr.has("config.diffEditor.useInlineViewWhenSpaceIsLimited"),
      precondition: ContextKeyExpr.has("isInDiffEditor")
    },
    order: 11,
    group: "1_diff",
    when: ContextKeyExpr.and(EditorContextKeys.diffEditorRenderSideBySideInlineBreakpointReached, ContextKeyExpr.has("isInDiffEditor"))
  });
  MenuRegistry.appendMenuItem(MenuId.EditorTitle, {
    command: {
      id: new ToggleShowMovedCodeBlocks().desc.id,
      title: localize(120, "Show Moved Code Blocks"),
      icon: Codicon.move,
      toggled: ContextKeyEqualsExpr.create("config.diffEditor.experimental.showMoves", true),
      precondition: ContextKeyExpr.has("isInDiffEditor")
    },
    order: 10,
    group: "1_diff",
    when: ContextKeyExpr.has("isInDiffEditor")
  });
  registerAction2(RevertHunkOrSelection);
  for (const ctx of [
    { icon: Codicon.arrowRight, key: EditorContextKeys.diffEditorInlineMode.toNegated() },
    { icon: Codicon.discard, key: EditorContextKeys.diffEditorInlineMode }
  ]) {
    MenuRegistry.appendMenuItem(MenuId.DiffEditorHunkToolbar, {
      command: {
        id: new RevertHunkOrSelection().desc.id,
        title: localize(121, "Revert Block"),
        icon: ctx.icon
      },
      when: ContextKeyExpr.and(EditorContextKeys.diffEditorModifiedWritable, ctx.key),
      order: 5,
      group: "primary"
    });
    MenuRegistry.appendMenuItem(MenuId.DiffEditorSelectionToolbar, {
      command: {
        id: new RevertHunkOrSelection().desc.id,
        title: localize(122, "Revert Selection"),
        icon: ctx.icon
      },
      when: ContextKeyExpr.and(EditorContextKeys.diffEditorModifiedWritable, ctx.key),
      order: 5,
      group: "primary"
    });
  }
  registerAction2(SwitchSide);
  registerAction2(ExitCompareMove);
  registerAction2(CollapseAllUnchangedRegions);
  registerAction2(ShowAllUnchangedRegions);
  MenuRegistry.appendMenuItem(MenuId.EditorTitle, {
    command: {
      id: AccessibleDiffViewerNext.id,
      title: localize(123, "Open Accessible Diff Viewer"),
      precondition: ContextKeyExpr.has("isInDiffEditor")
    },
    order: 10,
    group: "2_diff",
    when: ContextKeyExpr.and(EditorContextKeys.accessibleDiffViewerVisible.negate(), ContextKeyExpr.has("isInDiffEditor"))
  });
  CommandsRegistry.registerCommandAlias("editor.action.diffReview.next", AccessibleDiffViewerNext.id);
  registerAction2(AccessibleDiffViewerNext);
  CommandsRegistry.registerCommandAlias("editor.action.diffReview.prev", AccessibleDiffViewerPrev.id);
  registerAction2(AccessibleDiffViewerPrev);
  var __decorate$2s = 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$2q = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  var SelectionAnchorController_1;
  const SelectionAnchorSet = new RawContextKey("selectionAnchorSet", false);
  let SelectionAnchorController = (_p = class {
    static get(editor2) {
      return editor2.getContribution(SelectionAnchorController_1.ID);
    }
    constructor(editor2, contextKeyService) {
      this.editor = editor2;
      this.selectionAnchorSetContextKey = SelectionAnchorSet.bindTo(contextKeyService);
      this.modelChangeListener = editor2.onDidChangeModel(() => this.selectionAnchorSetContextKey.reset());
    }
    setSelectionAnchor() {
      if (this.editor.hasModel()) {
        const position = this.editor.getPosition();
        this.editor.changeDecorations((accessor) => {
          if (this.decorationId) {
            accessor.removeDecoration(this.decorationId);
          }
          this.decorationId = accessor.addDecoration(Selection$1.fromPositions(position, position), {
            description: "selection-anchor",
            stickiness: 1,
            hoverMessage: new MarkdownString().appendText(localize(798, "Selection Anchor")),
            className: "selection-anchor"
          });
        });
        this.selectionAnchorSetContextKey.set(!!this.decorationId);
        alert(localize(799, "Anchor set at {0}:{1}", position.lineNumber, position.column));
      }
    }
    goToSelectionAnchor() {
      if (this.editor.hasModel() && this.decorationId) {
        const anchorPosition = this.editor.getModel().getDecorationRange(this.decorationId);
        if (anchorPosition) {
          this.editor.setPosition(anchorPosition.getStartPosition());
        }
      }
    }
    selectFromAnchorToCursor() {
      if (this.editor.hasModel() && this.decorationId) {
        const start = this.editor.getModel().getDecorationRange(this.decorationId);
        if (start) {
          const end = this.editor.getPosition();
          this.editor.setSelection(Selection$1.fromPositions(start.getStartPosition(), end));
          this.cancelSelectionAnchor();
        }
      }
    }
    cancelSelectionAnchor() {
      if (this.decorationId) {
        const decorationId = this.decorationId;
        this.editor.changeDecorations((accessor) => {
          accessor.removeDecoration(decorationId);
          this.decorationId = void 0;
        });
        this.selectionAnchorSetContextKey.set(false);
      }
    }
    dispose() {
      this.cancelSelectionAnchor();
      this.modelChangeListener.dispose();
    }
  }, SelectionAnchorController_1 = _p, _p.ID = "editor.contrib.selectionAnchorController", _p);
  SelectionAnchorController = SelectionAnchorController_1 = __decorate$2s([
    __param$2q(1, IContextKeyService)
  ], SelectionAnchorController);
  class SetSelectionAnchor extends EditorAction {
    constructor() {
      super({
        id: "editor.action.setSelectionAnchor",
        label: localize2(800, "Set Selection Anchor"),
        precondition: void 0,
        kbOpts: {
          kbExpr: EditorContextKeys.editorTextFocus,
          primary: KeyChord(
            2048 | 41,
            2048 | 32
            /* KeyCode.KeyB */
          ),
          weight: 100
          /* KeybindingWeight.EditorContrib */
        }
      });
    }
    async run(_accessor, editor2) {
      SelectionAnchorController.get(editor2)?.setSelectionAnchor();
    }
  }
  class GoToSelectionAnchor extends EditorAction {
    constructor() {
      super({
        id: "editor.action.goToSelectionAnchor",
        label: localize2(801, "Go to Selection Anchor"),
        precondition: SelectionAnchorSet
      });
    }
    async run(_accessor, editor2) {
      SelectionAnchorController.get(editor2)?.goToSelectionAnchor();
    }
  }
  class SelectFromAnchorToCursor extends EditorAction {
    constructor() {
      super({
        id: "editor.action.selectFromAnchorToCursor",
        label: localize2(802, "Select from Anchor to Cursor"),
        precondition: SelectionAnchorSet,
        kbOpts: {
          kbExpr: EditorContextKeys.editorTextFocus,
          primary: KeyChord(
            2048 | 41,
            2048 | 41
            /* KeyCode.KeyK */
          ),
          weight: 100
          /* KeybindingWeight.EditorContrib */
        }
      });
    }
    async run(_accessor, editor2) {
      SelectionAnchorController.get(editor2)?.selectFromAnchorToCursor();
    }
  }
  class CancelSelectionAnchor extends EditorAction {
    constructor() {
      super({
        id: "editor.action.cancelSelectionAnchor",
        label: localize2(803, "Cancel Selection Anchor"),
        precondition: SelectionAnchorSet,
        kbOpts: {
          kbExpr: EditorContextKeys.editorTextFocus,
          primary: 9,
          weight: 100
          /* KeybindingWeight.EditorContrib */
        }
      });
    }
    async run(_accessor, editor2) {
      SelectionAnchorController.get(editor2)?.cancelSelectionAnchor();
    }
  }
  registerEditorContribution(
    SelectionAnchorController.ID,
    SelectionAnchorController,
    4
    /* EditorContributionInstantiation.Lazy */
  );
  registerEditorAction(SetSelectionAnchor);
  registerEditorAction(GoToSelectionAnchor);
  registerEditorAction(SelectFromAnchorToCursor);
  registerEditorAction(CancelSelectionAnchor);
  const overviewRulerBracketMatchForeground = registerColor("editorOverviewRuler.bracketMatchForeground", "#A0A0A0", localize(804, "Overview ruler marker color for matching brackets."));
  class JumpToBracketAction extends EditorAction {
    constructor() {
      super({
        id: "editor.action.jumpToBracket",
        label: localize2(806, "Go to Bracket"),
        precondition: void 0,
        kbOpts: {
          kbExpr: EditorContextKeys.editorTextFocus,
          primary: 2048 | 1024 | 93,
          weight: 100
          /* KeybindingWeight.EditorContrib */
        }
      });
    }
    run(accessor, editor2) {
      BracketMatchingController.get(editor2)?.jumpToBracket();
    }
  }
  class SelectToBracketAction extends EditorAction {
    constructor() {
      super({
        id: "editor.action.selectToBracket",
        label: localize2(807, "Select to Bracket"),
        precondition: void 0,
        metadata: {
          description: localize2(808, "Select the text inside and including the brackets or curly braces"),
          args: [{
            name: "args",
            schema: {
              type: "object",
              properties: {
                "selectBrackets": {
                  type: "boolean",
                  default: true
                }
              }
            }
          }]
        }
      });
    }
    run(accessor, editor2, args) {
      let selectBrackets = true;
      if (args && args.selectBrackets === false) {
        selectBrackets = false;
      }
      BracketMatchingController.get(editor2)?.selectToBracket(selectBrackets);
    }
  }
  class RemoveBracketsAction extends EditorAction {
    constructor() {
      super({
        id: "editor.action.removeBrackets",
        label: localize2(809, "Remove Brackets"),
        precondition: void 0,
        kbOpts: {
          kbExpr: EditorContextKeys.editorTextFocus,
          primary: 2048 | 512 | 1,
          weight: 100
          /* KeybindingWeight.EditorContrib */
        },
        canTriggerInlineEdits: true
      });
    }
    run(accessor, editor2) {
      BracketMatchingController.get(editor2)?.removeBrackets(this.id);
    }
  }
  class BracketsData {
    constructor(position, brackets, options) {
      this.position = position;
      this.brackets = brackets;
      this.options = options;
    }
  }
  const _BracketMatchingController = class _BracketMatchingController extends Disposable {
    static get(editor2) {
      return editor2.getContribution(_BracketMatchingController.ID);
    }
    constructor(editor2) {
      super();
      this._editor = editor2;
      this._lastBracketsData = [];
      this._lastVersionId = 0;
      this._decorations = this._editor.createDecorationsCollection();
      this._updateBracketsSoon = this._register(new RunOnceScheduler(() => this._updateBrackets(), 50));
      this._matchBrackets = this._editor.getOption(
        80
        /* EditorOption.matchBrackets */
      );
      this._updateBracketsSoon.schedule();
      this._register(editor2.onDidChangeCursorPosition((e) => {
        if (this._matchBrackets === "never") {
          return;
        }
        this._updateBracketsSoon.schedule();
      }));
      this._register(editor2.onDidChangeModelContent((e) => {
        this._updateBracketsSoon.schedule();
      }));
      this._register(editor2.onDidChangeModel((e) => {
        this._lastBracketsData = [];
        this._updateBracketsSoon.schedule();
      }));
      this._register(editor2.onDidChangeModelLanguageConfiguration((e) => {
        this._lastBracketsData = [];
        this._updateBracketsSoon.schedule();
      }));
      this._register(editor2.onDidChangeConfiguration((e) => {
        if (e.hasChanged(
          80
          /* EditorOption.matchBrackets */
        )) {
          this._matchBrackets = this._editor.getOption(
            80
            /* EditorOption.matchBrackets */
          );
          this._decorations.clear();
          this._lastBracketsData = [];
          this._lastVersionId = 0;
          this._updateBracketsSoon.schedule();
        }
      }));
      this._register(editor2.onDidBlurEditorWidget(() => {
        this._updateBracketsSoon.schedule();
      }));
      this._register(editor2.onDidFocusEditorWidget(() => {
        this._updateBracketsSoon.schedule();
      }));
    }
    jumpToBracket() {
      if (!this._editor.hasModel()) {
        return;
      }
      const model = this._editor.getModel();
      const newSelections = this._editor.getSelections().map((selection) => {
        const position = selection.getStartPosition();
        const brackets = model.bracketPairs.matchBracket(position);
        let newCursorPosition = null;
        if (brackets) {
          if (brackets[0].containsPosition(position) && !brackets[1].containsPosition(position)) {
            newCursorPosition = brackets[1].getStartPosition();
          } else if (brackets[1].containsPosition(position)) {
            newCursorPosition = brackets[0].getStartPosition();
          }
        } else {
          const enclosingBrackets = model.bracketPairs.findEnclosingBrackets(position);
          if (enclosingBrackets) {
            newCursorPosition = enclosingBrackets[1].getStartPosition();
          } else {
            const nextBracket = model.bracketPairs.findNextBracket(position);
            if (nextBracket && nextBracket.range) {
              newCursorPosition = nextBracket.range.getStartPosition();
            }
          }
        }
        if (newCursorPosition) {
          return new Selection$1(newCursorPosition.lineNumber, newCursorPosition.column, newCursorPosition.lineNumber, newCursorPosition.column);
        }
        return new Selection$1(position.lineNumber, position.column, position.lineNumber, position.column);
      });
      this._editor.setSelections(newSelections);
      this._editor.revealRange(newSelections[0]);
    }
    selectToBracket(selectBrackets) {
      if (!this._editor.hasModel()) {
        return;
      }
      const model = this._editor.getModel();
      const newSelections = [];
      this._editor.getSelections().forEach((selection) => {
        const position = selection.getStartPosition();
        let brackets = model.bracketPairs.matchBracket(position);
        if (!brackets) {
          brackets = model.bracketPairs.findEnclosingBrackets(position);
          if (!brackets) {
            const nextBracket = model.bracketPairs.findNextBracket(position);
            if (nextBracket && nextBracket.range) {
              brackets = model.bracketPairs.matchBracket(nextBracket.range.getStartPosition());
            }
          }
        }
        let selectFrom = null;
        let selectTo = null;
        if (brackets) {
          brackets.sort(Range$2.compareRangesUsingStarts);
          const [open, close] = brackets;
          selectFrom = selectBrackets ? open.getStartPosition() : open.getEndPosition();
          selectTo = selectBrackets ? close.getEndPosition() : close.getStartPosition();
          if (close.containsPosition(position)) {
            const tmp = selectFrom;
            selectFrom = selectTo;
            selectTo = tmp;
          }
        }
        if (selectFrom && selectTo) {
          newSelections.push(new Selection$1(selectFrom.lineNumber, selectFrom.column, selectTo.lineNumber, selectTo.column));
        }
      });
      if (newSelections.length > 0) {
        this._editor.setSelections(newSelections);
        this._editor.revealRange(newSelections[0]);
      }
    }
    removeBrackets(editSource) {
      if (!this._editor.hasModel()) {
        return;
      }
      const model = this._editor.getModel();
      this._editor.getSelections().forEach((selection) => {
        const position = selection.getPosition();
        let brackets = model.bracketPairs.matchBracket(position);
        if (!brackets) {
          brackets = model.bracketPairs.findEnclosingBrackets(position);
        }
        if (brackets) {
          this._editor.pushUndoStop();
          this._editor.executeEdits(editSource, [
            { range: brackets[0], text: "" },
            { range: brackets[1], text: "" }
          ]);
          this._editor.pushUndoStop();
        }
      });
    }
    _updateBrackets() {
      if (this._matchBrackets === "never") {
        return;
      }
      this._recomputeBrackets();
      const newDecorations = [];
      let newDecorationsLen = 0;
      for (const bracketData of this._lastBracketsData) {
        const brackets = bracketData.brackets;
        if (brackets) {
          newDecorations[newDecorationsLen++] = { range: brackets[0], options: bracketData.options };
          newDecorations[newDecorationsLen++] = { range: brackets[1], options: bracketData.options };
        }
      }
      this._decorations.set(newDecorations);
    }
    _recomputeBrackets() {
      if (!this._editor.hasModel() || !this._editor.hasWidgetFocus()) {
        this._lastBracketsData = [];
        this._lastVersionId = 0;
        return;
      }
      const selections = this._editor.getSelections();
      if (selections.length > 100) {
        this._lastBracketsData = [];
        this._lastVersionId = 0;
        return;
      }
      const model = this._editor.getModel();
      const versionId = model.getVersionId();
      let previousData = [];
      if (this._lastVersionId === versionId) {
        previousData = this._lastBracketsData;
      }
      const positions = [];
      let positionsLen = 0;
      for (let i2 = 0, len = selections.length; i2 < len; i2++) {
        const selection = selections[i2];
        if (selection.isEmpty()) {
          positions[positionsLen++] = selection.getStartPosition();
        }
      }
      if (positions.length > 1) {
        positions.sort(Position$1.compare);
      }
      const newData = [];
      let newDataLen = 0;
      let previousIndex = 0;
      const previousLen = previousData.length;
      for (let i2 = 0, len = positions.length; i2 < len; i2++) {
        const position = positions[i2];
        while (previousIndex < previousLen && previousData[previousIndex].position.isBefore(position)) {
          previousIndex++;
        }
        if (previousIndex < previousLen && previousData[previousIndex].position.equals(position)) {
          newData[newDataLen++] = previousData[previousIndex];
        } else {
          let brackets = model.bracketPairs.matchBracket(
            position,
            20
            /* give at most 20ms to compute */
          );
          let options = _BracketMatchingController._DECORATION_OPTIONS_WITH_OVERVIEW_RULER;
          if (!brackets && this._matchBrackets === "always") {
            brackets = model.bracketPairs.findEnclosingBrackets(
              position,
              20
              /* give at most 20ms to compute */
            );
            options = _BracketMatchingController._DECORATION_OPTIONS_WITHOUT_OVERVIEW_RULER;
          }
          newData[newDataLen++] = new BracketsData(position, brackets, options);
        }
      }
      this._lastBracketsData = newData;
      this._lastVersionId = versionId;
    }
  };
  _BracketMatchingController.ID = "editor.contrib.bracketMatchingController";
  _BracketMatchingController._DECORATION_OPTIONS_WITH_OVERVIEW_RULER = ModelDecorationOptions.register({
    description: "bracket-match-overview",
    stickiness: 1,
    className: "bracket-match",
    overviewRuler: {
      color: themeColorFromId(overviewRulerBracketMatchForeground),
      position: OverviewRulerLane$1.Center
    }
  });
  _BracketMatchingController._DECORATION_OPTIONS_WITHOUT_OVERVIEW_RULER = ModelDecorationOptions.register({
    description: "bracket-match-no-overview",
    stickiness: 1,
    className: "bracket-match"
  });
  let BracketMatchingController = _BracketMatchingController;
  registerEditorContribution(
    BracketMatchingController.ID,
    BracketMatchingController,
    1
    /* EditorContributionInstantiation.AfterFirstRender */
  );
  registerEditorAction(SelectToBracketAction);
  registerEditorAction(JumpToBracketAction);
  registerEditorAction(RemoveBracketsAction);
  MenuRegistry.appendMenuItem(MenuId.MenubarGoMenu, {
    group: "5_infile_nav",
    command: {
      id: "editor.action.jumpToBracket",
      title: localize(805, "Go to &&Bracket")
    },
    order: 2
  });
  class MoveCaretCommand {
    constructor(selection, isMovingLeft) {
      this._selection = selection;
      this._isMovingLeft = isMovingLeft;
    }
    getEditOperations(model, builder) {
      if (this._selection.startLineNumber !== this._selection.endLineNumber || this._selection.isEmpty()) {
        return;
      }
      const lineNumber = this._selection.startLineNumber;
      const startColumn = this._selection.startColumn;
      const endColumn = this._selection.endColumn;
      if (this._isMovingLeft && startColumn === 1) {
        return;
      }
      if (!this._isMovingLeft && endColumn === model.getLineMaxColumn(lineNumber)) {
        return;
      }
      if (this._isMovingLeft) {
        const rangeBefore = new Range$2(lineNumber, startColumn - 1, lineNumber, startColumn);
        const charBefore = model.getValueInRange(rangeBefore);
        builder.addEditOperation(rangeBefore, null);
        builder.addEditOperation(new Range$2(lineNumber, endColumn, lineNumber, endColumn), charBefore);
      } else {
        const rangeAfter = new Range$2(lineNumber, endColumn, lineNumber, endColumn + 1);
        const charAfter = model.getValueInRange(rangeAfter);
        builder.addEditOperation(rangeAfter, null);
        builder.addEditOperation(new Range$2(lineNumber, startColumn, lineNumber, startColumn), charAfter);
      }
    }
    computeCursorState(model, helper) {
      if (this._isMovingLeft) {
        return new Selection$1(this._selection.startLineNumber, this._selection.startColumn - 1, this._selection.endLineNumber, this._selection.endColumn - 1);
      } else {
        return new Selection$1(this._selection.startLineNumber, this._selection.startColumn + 1, this._selection.endLineNumber, this._selection.endColumn + 1);
      }
    }
  }
  class MoveCaretAction extends EditorAction {
    constructor(left, opts) {
      super(opts);
      this.left = left;
    }
    run(accessor, editor2) {
      if (!editor2.hasModel()) {
        return;
      }
      const commands = [];
      const selections = editor2.getSelections();
      for (const selection of selections) {
        commands.push(new MoveCaretCommand(selection, this.left));
      }
      editor2.pushUndoStop();
      editor2.executeCommands(this.id, commands);
      editor2.pushUndoStop();
    }
  }
  class MoveCaretLeftAction extends MoveCaretAction {
    constructor() {
      super(true, {
        id: "editor.action.moveCarretLeftAction",
        label: localize2(810, "Move Selected Text Left"),
        precondition: EditorContextKeys.writable
      });
    }
  }
  class MoveCaretRightAction extends MoveCaretAction {
    constructor() {
      super(false, {
        id: "editor.action.moveCarretRightAction",
        label: localize2(811, "Move Selected Text Right"),
        precondition: EditorContextKeys.writable
      });
    }
  }
  registerEditorAction(MoveCaretLeftAction);
  registerEditorAction(MoveCaretRightAction);
  class TransposeLettersAction extends EditorAction {
    constructor() {
      super({
        id: "editor.action.transposeLetters",
        label: localize2(812, "Transpose Letters"),
        precondition: EditorContextKeys.writable,
        kbOpts: {
          kbExpr: EditorContextKeys.textInputFocus,
          primary: 0,
          mac: {
            primary: 256 | 50
            /* KeyCode.KeyT */
          },
          weight: 100
          /* KeybindingWeight.EditorContrib */
        }
      });
    }
    run(accessor, editor2) {
      if (!editor2.hasModel()) {
        return;
      }
      const model = editor2.getModel();
      const commands = [];
      const selections = editor2.getSelections();
      for (const selection of selections) {
        if (!selection.isEmpty()) {
          continue;
        }
        const lineNumber = selection.startLineNumber;
        const column = selection.startColumn;
        const lastColumn = model.getLineMaxColumn(lineNumber);
        if (lineNumber === 1 && (column === 1 || column === 2 && lastColumn === 2)) {
          continue;
        }
        const endPosition = column === lastColumn ? selection.getPosition() : MoveOperations.rightPosition(model, selection.getPosition().lineNumber, selection.getPosition().column);
        const middlePosition = MoveOperations.leftPosition(model, endPosition);
        const beginPosition = MoveOperations.leftPosition(model, middlePosition);
        const leftChar = model.getValueInRange(Range$2.fromPositions(beginPosition, middlePosition));
        const rightChar = model.getValueInRange(Range$2.fromPositions(middlePosition, endPosition));
        const replaceRange = Range$2.fromPositions(beginPosition, endPosition);
        commands.push(new ReplaceCommand(replaceRange, rightChar + leftChar));
      }
      if (commands.length > 0) {
        editor2.pushUndoStop();
        editor2.executeCommands(this.id, commands);
        editor2.pushUndoStop();
      }
    }
  }
  registerEditorAction(TransposeLettersAction);
  const IProductService = createDecorator("productService");
  function createStringDataTransferItem(stringOrPromise, id) {
    return {
      id,
      asString: async () => stringOrPromise,
      asFile: () => void 0,
      value: typeof stringOrPromise === "string" ? stringOrPromise : void 0
    };
  }
  function createFileDataTransferItem(fileName, uri, data, id) {
    const file = { id: generateUuid(), name: fileName, uri, data };
    return {
      id,
      asString: async () => "",
      asFile: () => file,
      value: void 0
    };
  }
  class VSDataTransfer {
    constructor() {
      this._entries = /* @__PURE__ */ new Map();
    }
    get size() {
      let size2 = 0;
      for (const _ of this._entries) {
        size2++;
      }
      return size2;
    }
    has(mimeType) {
      return this._entries.has(this.toKey(mimeType));
    }
    matches(pattern) {
      const mimes = [...this._entries.keys()];
      if (Iterable.some(this, ([_, item]) => item.asFile())) {
        mimes.push("files");
      }
      return matchesMimeType_normalized(normalizeMimeType(pattern), mimes);
    }
    get(mimeType) {
      return this._entries.get(this.toKey(mimeType))?.[0];
    }
    /**
     * Add a new entry to this data transfer.
     *
     * This does not replace existing entries for `mimeType`.
     */
    append(mimeType, value) {
      const existing = this._entries.get(mimeType);
      if (existing) {
        existing.push(value);
      } else {
        this._entries.set(this.toKey(mimeType), [value]);
      }
    }
    /**
     * Set the entry for a given mime type.
     *
     * This replaces all existing entries for `mimeType`.
     */
    replace(mimeType, value) {
      this._entries.set(this.toKey(mimeType), [value]);
    }
    /**
     * Remove all entries for `mimeType`.
     */
    delete(mimeType) {
      this._entries.delete(this.toKey(mimeType));
    }
    /**
     * Iterate over all `[mime, item]` pairs in this data transfer.
     *
     * There may be multiple entries for each mime type.
     */
    *[Symbol.iterator]() {
      for (const [mine, items] of this._entries) {
        for (const item of items) {
          yield [mine, item];
        }
      }
    }
    toKey(mimeType) {
      return normalizeMimeType(mimeType);
    }
  }
  function normalizeMimeType(mimeType) {
    return mimeType.toLowerCase();
  }
  function matchesMimeType(pattern, mimeTypes) {
    return matchesMimeType_normalized(normalizeMimeType(pattern), mimeTypes.map(normalizeMimeType));
  }
  function matchesMimeType_normalized(normalizedPattern, normalizedMimeTypes) {
    if (normalizedPattern === "*/*") {
      return normalizedMimeTypes.length > 0;
    }
    if (normalizedMimeTypes.includes(normalizedPattern)) {
      return true;
    }
    const wildcard = normalizedPattern.match(/^([a-z]+)\/([a-z]+|\*)$/i);
    if (!wildcard) {
      return false;
    }
    const [_, type, subtype] = wildcard;
    if (subtype === "*") {
      return normalizedMimeTypes.some((mime) => mime.startsWith(type + "/"));
    }
    return false;
  }
  const UriList = Object.freeze({
    // http://amundsen.com/hypermedia/urilist/
    create: (entries2) => {
      return distinct(entries2.map((x) => x.toString())).join("\r\n");
    },
    split: (str) => {
      return str.split("\r\n");
    },
    parse: (str) => {
      return UriList.split(str).filter((value) => !value.startsWith("#"));
    }
  });
  const _HierarchicalKind = class _HierarchicalKind {
    constructor(value) {
      this.value = value;
    }
    equals(other) {
      return this.value === other.value;
    }
    contains(other) {
      return this.equals(other) || this.value === "" || other.value.startsWith(this.value + _HierarchicalKind.sep);
    }
    intersects(other) {
      return this.contains(other) || other.contains(this);
    }
    append(...parts) {
      return new _HierarchicalKind((this.value ? [this.value, ...parts] : parts).join(_HierarchicalKind.sep));
    }
  };
  _HierarchicalKind.sep = ".";
  _HierarchicalKind.None = new _HierarchicalKind("@@none@@");
  _HierarchicalKind.Empty = new _HierarchicalKind("");
  let HierarchicalKind = _HierarchicalKind;
  const NO_KEY_MODS = { ctrlCmd: false, alt: false };
  var QuickInputHideReason;
  (function(QuickInputHideReason2) {
    QuickInputHideReason2[QuickInputHideReason2["Blur"] = 1] = "Blur";
    QuickInputHideReason2[QuickInputHideReason2["Gesture"] = 2] = "Gesture";
    QuickInputHideReason2[QuickInputHideReason2["Other"] = 3] = "Other";
  })(QuickInputHideReason || (QuickInputHideReason = {}));
  var ItemActivation;
  (function(ItemActivation2) {
    ItemActivation2[ItemActivation2["NONE"] = 0] = "NONE";
    ItemActivation2[ItemActivation2["FIRST"] = 1] = "FIRST";
    ItemActivation2[ItemActivation2["SECOND"] = 2] = "SECOND";
    ItemActivation2[ItemActivation2["LAST"] = 3] = "LAST";
  })(ItemActivation || (ItemActivation = {}));
  var QuickPickFocus;
  (function(QuickPickFocus2) {
    QuickPickFocus2[QuickPickFocus2["First"] = 1] = "First";
    QuickPickFocus2[QuickPickFocus2["Second"] = 2] = "Second";
    QuickPickFocus2[QuickPickFocus2["Last"] = 3] = "Last";
    QuickPickFocus2[QuickPickFocus2["Next"] = 4] = "Next";
    QuickPickFocus2[QuickPickFocus2["Previous"] = 5] = "Previous";
    QuickPickFocus2[QuickPickFocus2["NextPage"] = 6] = "NextPage";
    QuickPickFocus2[QuickPickFocus2["PreviousPage"] = 7] = "PreviousPage";
    QuickPickFocus2[QuickPickFocus2["NextSeparator"] = 8] = "NextSeparator";
    QuickPickFocus2[QuickPickFocus2["PreviousSeparator"] = 9] = "PreviousSeparator";
  })(QuickPickFocus || (QuickPickFocus = {}));
  var QuickInputButtonLocation;
  (function(QuickInputButtonLocation2) {
    QuickInputButtonLocation2[QuickInputButtonLocation2["Title"] = 1] = "Title";
    QuickInputButtonLocation2[QuickInputButtonLocation2["Inline"] = 2] = "Inline";
    QuickInputButtonLocation2[QuickInputButtonLocation2["Input"] = 3] = "Input";
  })(QuickInputButtonLocation || (QuickInputButtonLocation = {}));
  const IQuickInputService = createDecorator("quickInputService");
  const CodeDataTransfers = {
    EDITORS: "CodeEditors",
    FILES: "CodeFiles"
  };
  class DragAndDropContributionRegistry {
  }
  const Extensions$1 = {
    DragAndDropContribution: "workbench.contributions.dragAndDrop"
  };
  Registry.add(Extensions$1.DragAndDropContribution, new DragAndDropContributionRegistry());
  const _LocalSelectionTransfer = class _LocalSelectionTransfer {
    constructor() {
    }
    static getInstance() {
      return _LocalSelectionTransfer.INSTANCE;
    }
    hasData(proto) {
      return proto && proto === this.proto;
    }
    getData(proto) {
      if (this.hasData(proto)) {
        return this.data;
      }
      return void 0;
    }
  };
  _LocalSelectionTransfer.INSTANCE = new _LocalSelectionTransfer();
  let LocalSelectionTransfer = _LocalSelectionTransfer;
  function getPathForFile(file) {
    if (isNative && typeof globalThis.vscode?.webUtils?.getPathForFile === "function") {
      return globalThis.vscode?.webUtils?.getPathForFile(file);
    }
    return void 0;
  }
  function toVSDataTransfer(dataTransfer) {
    const vsDataTransfer = new VSDataTransfer();
    for (const item of dataTransfer.items) {
      const type = item.type;
      if (item.kind === "string") {
        const asStringValue = new Promise((resolve2) => item.getAsString(resolve2));
        vsDataTransfer.append(type, createStringDataTransferItem(asStringValue));
      } else if (item.kind === "file") {
        const file = item.getAsFile();
        if (file) {
          vsDataTransfer.append(type, createFileDataTransferItemFromFile(file));
        }
      }
    }
    return vsDataTransfer;
  }
  function createFileDataTransferItemFromFile(file) {
    const path = getPathForFile(file);
    const uri = path ? URI.parse(path) : void 0;
    return createFileDataTransferItem(file.name, uri, async () => {
      return new Uint8Array(await file.arrayBuffer());
    });
  }
  const INTERNAL_DND_MIME_TYPES = Object.freeze([
    CodeDataTransfers.EDITORS,
    CodeDataTransfers.FILES,
    DataTransfers.RESOURCES,
    DataTransfers.INTERNAL_URI_LIST
  ]);
  function toExternalVSDataTransfer(sourceDataTransfer, overwriteUriList = false) {
    const vsDataTransfer = toVSDataTransfer(sourceDataTransfer);
    const uriList = vsDataTransfer.get(DataTransfers.INTERNAL_URI_LIST);
    if (uriList) {
      vsDataTransfer.replace(Mimes.uriList, uriList);
    } else {
      if (overwriteUriList || !vsDataTransfer.has(Mimes.uriList)) {
        const editorData = [];
        for (const item of sourceDataTransfer.items) {
          const file = item.getAsFile();
          if (file) {
            const path = getPathForFile(file);
            try {
              if (path) {
                editorData.push(URI.file(path).toString());
              } else {
                editorData.push(URI.parse(file.name, true).toString());
              }
            } catch {
            }
          }
        }
        if (editorData.length) {
          vsDataTransfer.replace(Mimes.uriList, createStringDataTransferItem(UriList.create(editorData)));
        }
      }
    }
    for (const internal of INTERNAL_DND_MIME_TYPES) {
      vsDataTransfer.delete(internal);
    }
    return vsDataTransfer;
  }
  const IBulkEditService = createDecorator("IWorkspaceEditService");
  class ResourceEdit {
    constructor(metadata) {
      this.metadata = metadata;
    }
    static convert(edit2) {
      return edit2.edits.map((edit3) => {
        if (ResourceTextEdit.is(edit3)) {
          return ResourceTextEdit.lift(edit3);
        }
        if (ResourceFileEdit.is(edit3)) {
          return ResourceFileEdit.lift(edit3);
        }
        throw new Error("Unsupported edit");
      });
    }
  }
  class ResourceTextEdit extends ResourceEdit {
    static is(candidate) {
      if (candidate instanceof ResourceTextEdit) {
        return true;
      }
      return isObject(candidate) && URI.isUri(candidate.resource) && isObject(candidate.textEdit);
    }
    static lift(edit2) {
      if (edit2 instanceof ResourceTextEdit) {
        return edit2;
      } else {
        return new ResourceTextEdit(edit2.resource, edit2.textEdit, edit2.versionId, edit2.metadata);
      }
    }
    constructor(resource, textEdit, versionId = void 0, metadata) {
      super(metadata);
      this.resource = resource;
      this.textEdit = textEdit;
      this.versionId = versionId;
    }
  }
  class ResourceFileEdit extends ResourceEdit {
    static is(candidate) {
      if (candidate instanceof ResourceFileEdit) {
        return true;
      } else {
        return isObject(candidate) && (Boolean(candidate.newResource) || Boolean(candidate.oldResource));
      }
    }
    static lift(edit2) {
      if (edit2 instanceof ResourceFileEdit) {
        return edit2;
      } else {
        return new ResourceFileEdit(edit2.oldResource, edit2.newResource, edit2.options, edit2.metadata);
      }
    }
    constructor(oldResource, newResource, options = {}, metadata) {
      super(metadata);
      this.oldResource = oldResource;
      this.newResource = newResource;
      this.options = options;
    }
  }
  const IEditorCancellationTokens = createDecorator("IEditorCancelService");
  const ctxCancellableOperation = new RawContextKey("cancellableOperation", false, localize(939, "Whether the editor runs a cancellable operation, e.g. like 'Peek References'"));
  registerSingleton(
    IEditorCancellationTokens,
    class {
      constructor() {
        this._tokens = /* @__PURE__ */ new WeakMap();
      }
      add(editor2, cts) {
        let data = this._tokens.get(editor2);
        if (!data) {
          data = editor2.invokeWithinContext((accessor) => {
            const key = ctxCancellableOperation.bindTo(accessor.get(IContextKeyService));
            const tokens = new LinkedList();
            return { key, tokens };
          });
          this._tokens.set(editor2, data);
        }
        let removeFn;
        data.key.set(true);
        removeFn = data.tokens.push(cts);
        return () => {
          if (removeFn) {
            removeFn();
            data.key.set(!data.tokens.isEmpty());
            removeFn = void 0;
          }
        };
      }
      cancel(editor2) {
        const data = this._tokens.get(editor2);
        if (!data) {
          return;
        }
        const cts = data.tokens.pop();
        if (cts) {
          cts.cancel();
          data.key.set(!data.tokens.isEmpty());
        }
      }
    },
    1
    /* InstantiationType.Delayed */
  );
  class EditorKeybindingCancellationTokenSource extends CancellationTokenSource$1 {
    constructor(editor2, parent) {
      super(parent);
      this.editor = editor2;
      this._unregister = editor2.invokeWithinContext((accessor) => accessor.get(IEditorCancellationTokens).add(editor2, this));
    }
    dispose() {
      this._unregister();
      super.dispose();
    }
  }
  registerEditorCommand(new class extends EditorCommand {
    constructor() {
      super({
        id: "editor.cancelOperation",
        kbOpts: {
          weight: 100,
          primary: 9
          /* KeyCode.Escape */
        },
        precondition: ctxCancellableOperation
      });
    }
    runEditorCommand(accessor, editor2) {
      accessor.get(IEditorCancellationTokens).cancel(editor2);
    }
  }());
  let EditorState$1 = class EditorState2 {
    constructor(editor2, flags) {
      this.flags = flags;
      if ((this.flags & 1) !== 0) {
        const model = editor2.getModel();
        this.modelVersionId = model ? format("{0}#{1}", model.uri.toString(), model.getVersionId()) : null;
      } else {
        this.modelVersionId = null;
      }
      if ((this.flags & 4) !== 0) {
        this.position = editor2.getPosition();
      } else {
        this.position = null;
      }
      if ((this.flags & 2) !== 0) {
        this.selection = editor2.getSelection();
      } else {
        this.selection = null;
      }
      if ((this.flags & 8) !== 0) {
        this.scrollLeft = editor2.getScrollLeft();
        this.scrollTop = editor2.getScrollTop();
      } else {
        this.scrollLeft = -1;
        this.scrollTop = -1;
      }
    }
    _equals(other) {
      if (!(other instanceof EditorState2)) {
        return false;
      }
      const state = other;
      if (this.modelVersionId !== state.modelVersionId) {
        return false;
      }
      if (this.scrollLeft !== state.scrollLeft || this.scrollTop !== state.scrollTop) {
        return false;
      }
      if (!this.position && state.position || this.position && !state.position || this.position && state.position && !this.position.equals(state.position)) {
        return false;
      }
      if (!this.selection && state.selection || this.selection && !state.selection || this.selection && state.selection && !this.selection.equalsRange(state.selection)) {
        return false;
      }
      return true;
    }
    validate(editor2) {
      return this._equals(new EditorState2(editor2, this.flags));
    }
  };
  class EditorStateCancellationTokenSource extends EditorKeybindingCancellationTokenSource {
    constructor(editor2, flags, range2, parent) {
      super(editor2, parent);
      this._listener = new DisposableStore();
      if (flags & 4) {
        this._listener.add(editor2.onDidChangeCursorPosition((e) => {
          if (!range2 || !Range$2.containsPosition(range2, e.position)) {
            this.cancel();
          }
        }));
      }
      if (flags & 2) {
        this._listener.add(editor2.onDidChangeCursorSelection((e) => {
          if (!range2 || !Range$2.containsRange(range2, e.selection)) {
            this.cancel();
          }
        }));
      }
      if (flags & 8) {
        this._listener.add(editor2.onDidScrollChange((_) => this.cancel()));
      }
      if (flags & 1) {
        this._listener.add(editor2.onDidChangeModel((_) => this.cancel()));
        this._listener.add(editor2.onDidChangeModelContent((_) => this.cancel()));
      }
    }
    dispose() {
      this._listener.dispose();
      super.dispose();
    }
  }
  class TextModelCancellationTokenSource extends CancellationTokenSource$1 {
    constructor(model, parent) {
      super(parent);
      this._listener = model.onDidChangeContent(() => this.cancel());
    }
    dispose() {
      this._listener.dispose();
      super.dispose();
    }
  }
  var __decorate$2r = 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$2p = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  const inlineProgressDecoration = ModelDecorationOptions.register({
    description: "inline-progress-widget",
    stickiness: 1,
    showIfCollapsed: true,
    after: {
      content: noBreakWhitespace,
      inlineClassName: "inline-editor-progress-decoration",
      inlineClassNameAffectsLetterSpacing: true
    }
  });
  const _InlineProgressWidget = class _InlineProgressWidget extends Disposable {
    constructor(typeId, editor2, range2, title, delegate) {
      super();
      this.typeId = typeId;
      this.editor = editor2;
      this.range = range2;
      this.delegate = delegate;
      this.allowEditorOverflow = false;
      this.suppressMouseDown = true;
      this.create(title);
      this.editor.addContentWidget(this);
      this.editor.layoutContentWidget(this);
    }
    create(title) {
      this.domNode = $$l(".inline-progress-widget");
      this.domNode.role = "button";
      this.domNode.title = title;
      const iconElement = $$l("span.icon");
      this.domNode.append(iconElement);
      iconElement.classList.add(...ThemeIcon.asClassNameArray(Codicon.loading), "codicon-modifier-spin");
      const updateSize = () => {
        const lineHeight = this.editor.getOption(
          75
          /* EditorOption.lineHeight */
        );
        this.domNode.style.height = `${lineHeight}px`;
        this.domNode.style.width = `${Math.ceil(0.8 * lineHeight)}px`;
      };
      updateSize();
      this._register(this.editor.onDidChangeConfiguration((c) => {
        if (c.hasChanged(
          61
          /* EditorOption.fontSize */
        ) || c.hasChanged(
          75
          /* EditorOption.lineHeight */
        )) {
          updateSize();
        }
      }));
      this._register(addDisposableListener(this.domNode, EventType$1.CLICK, (e) => {
        this.delegate.cancel();
      }));
    }
    getId() {
      return _InlineProgressWidget.baseId + "." + this.typeId;
    }
    getDomNode() {
      return this.domNode;
    }
    getPosition() {
      return {
        position: { lineNumber: this.range.startLineNumber, column: this.range.startColumn },
        preference: [
          0
          /* ContentWidgetPositionPreference.EXACT */
        ]
      };
    }
    dispose() {
      super.dispose();
      this.editor.removeContentWidget(this);
    }
  };
  _InlineProgressWidget.baseId = "editor.widget.inlineProgressWidget";
  let InlineProgressWidget = _InlineProgressWidget;
  let InlineProgressManager = class InlineProgressManager extends Disposable {
    constructor(id, _editor, _instantiationService) {
      super();
      this.id = id;
      this._editor = _editor;
      this._instantiationService = _instantiationService;
      this._showDelay = 500;
      this._showPromise = this._register(new MutableDisposable());
      this._currentWidget = this._register(new MutableDisposable());
      this._operationIdPool = 0;
      this._currentDecorations = _editor.createDecorationsCollection();
    }
    dispose() {
      super.dispose();
      this._currentDecorations.clear();
    }
    async showWhile(position, title, promise, delegate, delayOverride) {
      const operationId = this._operationIdPool++;
      this._currentOperation = operationId;
      this.clear();
      this._showPromise.value = disposableTimeout(() => {
        const range2 = Range$2.fromPositions(position);
        const decorationIds = this._currentDecorations.set([{
          range: range2,
          options: inlineProgressDecoration
        }]);
        if (decorationIds.length > 0) {
          this._currentWidget.value = this._instantiationService.createInstance(InlineProgressWidget, this.id, this._editor, range2, title, delegate);
        }
      }, delayOverride ?? this._showDelay);
      try {
        return await promise;
      } finally {
        if (this._currentOperation === operationId) {
          this.clear();
          this._currentOperation = void 0;
        }
      }
    }
    clear() {
      this._showPromise.clear();
      this._currentDecorations.clear();
      this._currentWidget.clear();
    }
  };
  InlineProgressManager = __decorate$2r([
    __param$2p(2, IInstantiationService)
  ], InlineProgressManager);
  const IOpenerService = createDecorator("openerService");
  function withSelection(uri, selection) {
    return uri.with({ fragment: `${selection.startLineNumber},${selection.startColumn}${selection.endLineNumber ? `-${selection.endLineNumber}${selection.endColumn ? `,${selection.endColumn}` : ""}` : ""}` });
  }
  function extractSelection(uri) {
    let selection = void 0;
    const match2 = /^L?(\d+)(?:,(\d+))?(-L?(\d+)(?:,(\d+))?)?/.exec(uri.fragment);
    if (match2) {
      selection = {
        startLineNumber: parseInt(match2[1]),
        startColumn: match2[2] ? parseInt(match2[2]) : 1,
        endLineNumber: match2[4] ? parseInt(match2[4]) : void 0,
        endColumn: match2[4] ? match2[5] ? parseInt(match2[5]) : 1 : void 0
      };
      uri = uri.with({ fragment: "" });
    }
    return { selection, uri };
  }
  var __decorate$2q = 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$2o = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  const IMarkdownRendererService = createDecorator("markdownRendererService");
  let MarkdownRendererService = class MarkdownRendererService {
    constructor(_openerService) {
      this._openerService = _openerService;
    }
    render(markdown, options, outElement) {
      const resolvedOptions = { ...options };
      if (!resolvedOptions.actionHandler) {
        resolvedOptions.actionHandler = (link2, mdStr) => {
          return openLinkFromMarkdown(this._openerService, link2, mdStr.isTrusted);
        };
      }
      if (!resolvedOptions.codeBlockRenderer) {
        resolvedOptions.codeBlockRenderer = (alias, value) => {
          return this._defaultCodeBlockRenderer?.renderCodeBlock(alias, value, resolvedOptions ?? {}) ?? Promise.resolve(document.createElement("span"));
        };
      }
      const rendered = renderMarkdown$1(markdown, resolvedOptions, outElement);
      rendered.element.classList.add("rendered-markdown");
      return rendered;
    }
    setDefaultCodeBlockRenderer(renderer) {
      this._defaultCodeBlockRenderer = renderer;
    }
  };
  MarkdownRendererService = __decorate$2q([
    __param$2o(0, IOpenerService)
  ], MarkdownRendererService);
  async function openLinkFromMarkdown(openerService, link2, isTrusted, skipValidation) {
    try {
      return await openerService.open(link2, {
        fromUserGesture: true,
        allowContributedOpeners: true,
        allowCommands: toAllowCommandsOption(isTrusted),
        skipValidation
      });
    } catch (e) {
      onUnexpectedError(e);
      return false;
    }
  }
  function toAllowCommandsOption(isTrusted) {
    if (isTrusted === true) {
      return true;
    }
    if (isTrusted && Array.isArray(isTrusted.enabledCommands)) {
      return isTrusted.enabledCommands;
    }
    return false;
  }
  registerSingleton(
    IMarkdownRendererService,
    MarkdownRendererService,
    1
    /* InstantiationType.Delayed */
  );
  var __decorate$2p = 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$2n = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  var MessageController_1;
  let MessageController = (_q = class {
    static get(editor2) {
      return editor2.getContribution(MessageController_1.ID);
    }
    constructor(editor2, contextKeyService, _openerService) {
      this._openerService = _openerService;
      this._messageWidget = new MutableDisposable();
      this._messageListeners = new DisposableStore();
      this._mouseOverMessage = false;
      this._editor = editor2;
      this._visible = MessageController_1.MESSAGE_VISIBLE.bindTo(contextKeyService);
    }
    dispose() {
      this._messageListeners.dispose();
      this._messageWidget.dispose();
      this._visible.reset();
    }
    showMessage(message, position) {
      alert(isMarkdownString(message) ? message.value : message);
      this._visible.set(true);
      this._messageWidget.clear();
      this._messageListeners.clear();
      if (isMarkdownString(message)) {
        const renderedMessage = this._messageListeners.add(renderMarkdown$1(message, {
          actionHandler: (url, mdStr) => {
            this.closeMessage();
            openLinkFromMarkdown(this._openerService, url, mdStr.isTrusted);
          }
        }));
        this._messageWidget.value = new MessageWidget$1(this._editor, position, renderedMessage.element);
      } else {
        this._messageWidget.value = new MessageWidget$1(this._editor, position, message);
      }
      this._messageListeners.add(Event.debounce(this._editor.onDidBlurEditorText, (last, event) => event, 0)(() => {
        if (this._mouseOverMessage) {
          return;
        }
        if (this._messageWidget.value && isAncestor$1(getActiveElement(), this._messageWidget.value.getDomNode())) {
          return;
        }
        this.closeMessage();
      }));
      this._messageListeners.add(this._editor.onDidChangeCursorPosition(() => this.closeMessage()));
      this._messageListeners.add(this._editor.onDidDispose(() => this.closeMessage()));
      this._messageListeners.add(this._editor.onDidChangeModel(() => this.closeMessage()));
      this._messageListeners.add(addDisposableListener(this._messageWidget.value.getDomNode(), EventType$1.MOUSE_ENTER, () => this._mouseOverMessage = true, true));
      this._messageListeners.add(addDisposableListener(this._messageWidget.value.getDomNode(), EventType$1.MOUSE_LEAVE, () => this._mouseOverMessage = false, true));
      let bounds;
      this._messageListeners.add(this._editor.onMouseMove((e) => {
        if (!e.target.position) {
          return;
        }
        if (!bounds) {
          bounds = new Range$2(position.lineNumber - 3, 1, e.target.position.lineNumber + 3, 1);
        } else if (!bounds.containsPosition(e.target.position)) {
          this.closeMessage();
        }
      }));
    }
    closeMessage() {
      this._visible.reset();
      this._messageListeners.clear();
      if (this._messageWidget.value) {
        this._messageListeners.add(MessageWidget$1.fadeOut(this._messageWidget.value));
      }
    }
  }, MessageController_1 = _q, _q.ID = "editor.contrib.messageController", _q.MESSAGE_VISIBLE = new RawContextKey("messageVisible", false, localize(1287, "Whether the editor is currently showing an inline message")), _q);
  MessageController = MessageController_1 = __decorate$2p([
    __param$2n(1, IContextKeyService),
    __param$2n(2, IOpenerService)
  ], MessageController);
  const MessageCommand = EditorCommand.bindToContribution(MessageController.get);
  registerEditorCommand(new MessageCommand({
    id: "leaveEditorMessage",
    precondition: MessageController.MESSAGE_VISIBLE,
    handler: (c) => c.closeMessage(),
    kbOpts: {
      weight: 100 + 30,
      primary: 9
      /* KeyCode.Escape */
    }
  }));
  let MessageWidget$1 = class MessageWidget {
    static fadeOut(messageWidget) {
      const dispose2 = () => {
        messageWidget.dispose();
        clearTimeout(handle);
        messageWidget.getDomNode().removeEventListener("animationend", dispose2);
      };
      const handle = setTimeout(dispose2, 110);
      messageWidget.getDomNode().addEventListener("animationend", dispose2);
      messageWidget.getDomNode().classList.add("fadeOut");
      return { dispose: dispose2 };
    }
    constructor(editor2, { lineNumber, column }, text2) {
      this.allowEditorOverflow = true;
      this.suppressMouseDown = false;
      this._editor = editor2;
      this._editor.revealLinesInCenterIfOutsideViewport(
        lineNumber,
        lineNumber,
        0
        /* ScrollType.Smooth */
      );
      this._position = { lineNumber, column };
      this._domNode = document.createElement("div");
      this._domNode.classList.add("monaco-editor-overlaymessage");
      this._domNode.style.marginLeft = "-6px";
      const anchorTop = document.createElement("div");
      anchorTop.classList.add("anchor", "top");
      this._domNode.appendChild(anchorTop);
      const message = document.createElement("div");
      if (typeof text2 === "string") {
        message.classList.add("message");
        message.textContent = text2;
      } else {
        text2.classList.add("message");
        message.appendChild(text2);
      }
      this._domNode.appendChild(message);
      const anchorBottom = document.createElement("div");
      anchorBottom.classList.add("anchor", "below");
      this._domNode.appendChild(anchorBottom);
      this._editor.addContentWidget(this);
      this._domNode.classList.add("fadeIn");
    }
    dispose() {
      this._editor.removeContentWidget(this);
    }
    getId() {
      return "messageoverlay";
    }
    getDomNode() {
      return this._domNode;
    }
    getPosition() {
      return {
        position: this._position,
        preference: [
          1,
          2
        ],
        positionAffinity: 1
      };
    }
    afterRender(position) {
      this._domNode.classList.toggle(
        "below",
        position === 2
        /* ContentWidgetPositionPreference.BELOW */
      );
    }
  };
  registerEditorContribution(
    MessageController.ID,
    MessageController,
    4
    /* EditorContributionInstantiation.Lazy */
  );
  class StringIterator {
    constructor() {
      this._value = "";
      this._pos = 0;
    }
    reset(key) {
      this._value = key;
      this._pos = 0;
      return this;
    }
    next() {
      this._pos += 1;
      return this;
    }
    hasNext() {
      return this._pos < this._value.length - 1;
    }
    cmp(a) {
      const aCode = a.charCodeAt(0);
      const thisCode = this._value.charCodeAt(this._pos);
      return aCode - thisCode;
    }
    value() {
      return this._value[this._pos];
    }
  }
  class ConfigKeysIterator {
    constructor(_caseSensitive = true) {
      this._caseSensitive = _caseSensitive;
    }
    reset(key) {
      this._value = key;
      this._from = 0;
      this._to = 0;
      return this.next();
    }
    hasNext() {
      return this._to < this._value.length;
    }
    next() {
      this._from = this._to;
      let justSeps = true;
      for (; this._to < this._value.length; this._to++) {
        const ch = this._value.charCodeAt(this._to);
        if (ch === 46) {
          if (justSeps) {
            this._from++;
          } else {
            break;
          }
        } else {
          justSeps = false;
        }
      }
      return this;
    }
    cmp(a) {
      return this._caseSensitive ? compareSubstring(a, this._value, 0, a.length, this._from, this._to) : compareSubstringIgnoreCase(a, this._value, 0, a.length, this._from, this._to);
    }
    value() {
      return this._value.substring(this._from, this._to);
    }
  }
  class PathIterator {
    constructor(_splitOnBackslash = true, _caseSensitive = true) {
      this._splitOnBackslash = _splitOnBackslash;
      this._caseSensitive = _caseSensitive;
    }
    reset(key) {
      this._from = 0;
      this._to = 0;
      this._value = key;
      this._valueLen = key.length;
      for (let pos = key.length - 1; pos >= 0; pos--, this._valueLen--) {
        const ch = this._value.charCodeAt(pos);
        if (!(ch === 47 || this._splitOnBackslash && ch === 92)) {
          break;
        }
      }
      return this.next();
    }
    hasNext() {
      return this._to < this._valueLen;
    }
    next() {
      this._from = this._to;
      let justSeps = true;
      for (; this._to < this._valueLen; this._to++) {
        const ch = this._value.charCodeAt(this._to);
        if (ch === 47 || this._splitOnBackslash && ch === 92) {
          if (justSeps) {
            this._from++;
          } else {
            break;
          }
        } else {
          justSeps = false;
        }
      }
      return this;
    }
    cmp(a) {
      return this._caseSensitive ? compareSubstring(a, this._value, 0, a.length, this._from, this._to) : compareSubstringIgnoreCase(a, this._value, 0, a.length, this._from, this._to);
    }
    value() {
      return this._value.substring(this._from, this._to);
    }
  }
  class UriIterator {
    constructor(_ignorePathCasing, _ignoreQueryAndFragment) {
      this._ignorePathCasing = _ignorePathCasing;
      this._ignoreQueryAndFragment = _ignoreQueryAndFragment;
      this._states = [];
      this._stateIdx = 0;
    }
    reset(key) {
      this._value = key;
      this._states = [];
      if (this._value.scheme) {
        this._states.push(
          1
          /* UriIteratorState.Scheme */
        );
      }
      if (this._value.authority) {
        this._states.push(
          2
          /* UriIteratorState.Authority */
        );
      }
      if (this._value.path) {
        this._pathIterator = new PathIterator(false, !this._ignorePathCasing(key));
        this._pathIterator.reset(key.path);
        if (this._pathIterator.value()) {
          this._states.push(
            3
            /* UriIteratorState.Path */
          );
        }
      }
      if (!this._ignoreQueryAndFragment(key)) {
        if (this._value.query) {
          this._states.push(
            4
            /* UriIteratorState.Query */
          );
        }
        if (this._value.fragment) {
          this._states.push(
            5
            /* UriIteratorState.Fragment */
          );
        }
      }
      this._stateIdx = 0;
      return this;
    }
    next() {
      if (this._states[this._stateIdx] === 3 && this._pathIterator.hasNext()) {
        this._pathIterator.next();
      } else {
        this._stateIdx += 1;
      }
      return this;
    }
    hasNext() {
      return this._states[this._stateIdx] === 3 && this._pathIterator.hasNext() || this._stateIdx < this._states.length - 1;
    }
    cmp(a) {
      if (this._states[this._stateIdx] === 1) {
        return compareIgnoreCase(a, this._value.scheme);
      } else if (this._states[this._stateIdx] === 2) {
        return compareIgnoreCase(a, this._value.authority);
      } else if (this._states[this._stateIdx] === 3) {
        return this._pathIterator.cmp(a);
      } else if (this._states[this._stateIdx] === 4) {
        return compare(a, this._value.query);
      } else if (this._states[this._stateIdx] === 5) {
        return compare(a, this._value.fragment);
      }
      throw new Error();
    }
    value() {
      if (this._states[this._stateIdx] === 1) {
        return this._value.scheme;
      } else if (this._states[this._stateIdx] === 2) {
        return this._value.authority;
      } else if (this._states[this._stateIdx] === 3) {
        return this._pathIterator.value();
      } else if (this._states[this._stateIdx] === 4) {
        return this._value.query;
      } else if (this._states[this._stateIdx] === 5) {
        return this._value.fragment;
      }
      throw new Error();
    }
  }
  const _Undef = class _Undef {
    static wrap(value) {
      return value === void 0 ? _Undef.Val : value;
    }
    static unwrap(value) {
      return value === _Undef.Val ? void 0 : value;
    }
  };
  _Undef.Val = Symbol("undefined_placeholder");
  let Undef = _Undef;
  class TernarySearchTreeNode {
    constructor() {
      this.height = 1;
      this.value = void 0;
      this.key = void 0;
      this.left = void 0;
      this.mid = void 0;
      this.right = void 0;
    }
    rotateLeft() {
      const tmp = this.right;
      this.right = tmp.left;
      tmp.left = this;
      this.updateHeight();
      tmp.updateHeight();
      return tmp;
    }
    rotateRight() {
      const tmp = this.left;
      this.left = tmp.right;
      tmp.right = this;
      this.updateHeight();
      tmp.updateHeight();
      return tmp;
    }
    updateHeight() {
      this.height = 1 + Math.max(this.heightLeft, this.heightRight);
    }
    balanceFactor() {
      return this.heightRight - this.heightLeft;
    }
    get heightLeft() {
      return this.left?.height ?? 0;
    }
    get heightRight() {
      return this.right?.height ?? 0;
    }
  }
  class TernarySearchTree {
    static forUris(ignorePathCasing = () => false, ignoreQueryAndFragment = () => false) {
      return new TernarySearchTree(new UriIterator(ignorePathCasing, ignoreQueryAndFragment));
    }
    static forStrings() {
      return new TernarySearchTree(new StringIterator());
    }
    static forConfigKeys() {
      return new TernarySearchTree(new ConfigKeysIterator());
    }
    constructor(segments) {
      this._iter = segments;
    }
    clear() {
      this._root = void 0;
    }
    set(key, element) {
      const iter = this._iter.reset(key);
      let node;
      if (!this._root) {
        this._root = new TernarySearchTreeNode();
        this._root.segment = iter.value();
      }
      const stack = [];
      node = this._root;
      while (true) {
        const val = iter.cmp(node.segment);
        if (val > 0) {
          if (!node.left) {
            node.left = new TernarySearchTreeNode();
            node.left.segment = iter.value();
          }
          stack.push([-1, node]);
          node = node.left;
        } else if (val < 0) {
          if (!node.right) {
            node.right = new TernarySearchTreeNode();
            node.right.segment = iter.value();
          }
          stack.push([1, node]);
          node = node.right;
        } else if (iter.hasNext()) {
          iter.next();
          if (!node.mid) {
            node.mid = new TernarySearchTreeNode();
            node.mid.segment = iter.value();
          }
          stack.push([0, node]);
          node = node.mid;
        } else {
          break;
        }
      }
      const oldElement = Undef.unwrap(node.value);
      node.value = Undef.wrap(element);
      node.key = key;
      for (let i2 = stack.length - 1; i2 >= 0; i2--) {
        const node2 = stack[i2][1];
        node2.updateHeight();
        const bf = node2.balanceFactor();
        if (bf < -1 || bf > 1) {
          const d1 = stack[i2][0];
          const d2 = stack[i2 + 1][0];
          if (d1 === 1 && d2 === 1) {
            stack[i2][1] = node2.rotateLeft();
          } else if (d1 === -1 && d2 === -1) {
            stack[i2][1] = node2.rotateRight();
          } else if (d1 === 1 && d2 === -1) {
            node2.right = stack[i2 + 1][1] = stack[i2 + 1][1].rotateRight();
            stack[i2][1] = node2.rotateLeft();
          } else if (d1 === -1 && d2 === 1) {
            node2.left = stack[i2 + 1][1] = stack[i2 + 1][1].rotateLeft();
            stack[i2][1] = node2.rotateRight();
          } else {
            throw new Error();
          }
          if (i2 > 0) {
            switch (stack[i2 - 1][0]) {
              case -1:
                stack[i2 - 1][1].left = stack[i2][1];
                break;
              case 1:
                stack[i2 - 1][1].right = stack[i2][1];
                break;
              case 0:
                stack[i2 - 1][1].mid = stack[i2][1];
                break;
            }
          } else {
            this._root = stack[0][1];
          }
        }
      }
      return oldElement;
    }
    get(key) {
      return Undef.unwrap(this._getNode(key)?.value);
    }
    _getNode(key) {
      const iter = this._iter.reset(key);
      let node = this._root;
      while (node) {
        const val = iter.cmp(node.segment);
        if (val > 0) {
          node = node.left;
        } else if (val < 0) {
          node = node.right;
        } else if (iter.hasNext()) {
          iter.next();
          node = node.mid;
        } else {
          break;
        }
      }
      return node;
    }
    has(key) {
      const node = this._getNode(key);
      return !(node?.value === void 0 && node?.mid === void 0);
    }
    delete(key) {
      return this._delete(key, false);
    }
    deleteSuperstr(key) {
      return this._delete(key, true);
    }
    _delete(key, superStr) {
      const iter = this._iter.reset(key);
      const stack = [];
      let node = this._root;
      while (node) {
        const val = iter.cmp(node.segment);
        if (val > 0) {
          stack.push([-1, node]);
          node = node.left;
        } else if (val < 0) {
          stack.push([1, node]);
          node = node.right;
        } else if (iter.hasNext()) {
          iter.next();
          stack.push([0, node]);
          node = node.mid;
        } else {
          break;
        }
      }
      if (!node) {
        return;
      }
      if (superStr) {
        node.left = void 0;
        node.mid = void 0;
        node.right = void 0;
        node.height = 1;
      } else {
        node.key = void 0;
        node.value = void 0;
      }
      if (!node.mid && !node.value) {
        if (node.left && node.right) {
          const stack2 = [[1, node]];
          const min = this._min(node.right, stack2);
          if (min.key) {
            node.key = min.key;
            node.value = min.value;
            node.segment = min.segment;
            const newChild = min.right;
            if (stack2.length > 1) {
              const [dir, parent] = stack2[stack2.length - 1];
              switch (dir) {
                case -1:
                  parent.left = newChild;
                  break;
                case 0:
                  assert(false);
                case 1:
                  assert(false);
              }
            } else {
              node.right = newChild;
            }
            const newChild2 = this._balanceByStack(stack2);
            if (stack.length > 0) {
              const [dir, parent] = stack[stack.length - 1];
              switch (dir) {
                case -1:
                  parent.left = newChild2;
                  break;
                case 0:
                  parent.mid = newChild2;
                  break;
                case 1:
                  parent.right = newChild2;
                  break;
              }
            } else {
              this._root = newChild2;
            }
          }
        } else {
          const newChild = node.left ?? node.right;
          if (stack.length > 0) {
            const [dir, parent] = stack[stack.length - 1];
            switch (dir) {
              case -1:
                parent.left = newChild;
                break;
              case 0:
                parent.mid = newChild;
                break;
              case 1:
                parent.right = newChild;
                break;
            }
          } else {
            this._root = newChild;
          }
        }
      }
      this._root = this._balanceByStack(stack) ?? this._root;
    }
    _min(node, stack) {
      while (node.left) {
        stack.push([-1, node]);
        node = node.left;
      }
      return node;
    }
    _balanceByStack(stack) {
      for (let i2 = stack.length - 1; i2 >= 0; i2--) {
        const node = stack[i2][1];
        node.updateHeight();
        const bf = node.balanceFactor();
        if (bf > 1) {
          if (node.right.balanceFactor() >= 0) {
            stack[i2][1] = node.rotateLeft();
          } else {
            node.right = node.right.rotateRight();
            stack[i2][1] = node.rotateLeft();
          }
        } else if (bf < -1) {
          if (node.left.balanceFactor() <= 0) {
            stack[i2][1] = node.rotateRight();
          } else {
            node.left = node.left.rotateLeft();
            stack[i2][1] = node.rotateRight();
          }
        }
        if (i2 > 0) {
          switch (stack[i2 - 1][0]) {
            case -1:
              stack[i2 - 1][1].left = stack[i2][1];
              break;
            case 1:
              stack[i2 - 1][1].right = stack[i2][1];
              break;
            case 0:
              stack[i2 - 1][1].mid = stack[i2][1];
              break;
          }
        } else {
          return stack[0][1];
        }
      }
      return void 0;
    }
    findSubstr(key) {
      const iter = this._iter.reset(key);
      let node = this._root;
      let candidate = void 0;
      while (node) {
        const val = iter.cmp(node.segment);
        if (val > 0) {
          node = node.left;
        } else if (val < 0) {
          node = node.right;
        } else if (iter.hasNext()) {
          iter.next();
          candidate = Undef.unwrap(node.value) || candidate;
          node = node.mid;
        } else {
          break;
        }
      }
      return node && Undef.unwrap(node.value) || candidate;
    }
    findSuperstr(key) {
      return this._findSuperstrOrElement(key, false);
    }
    _findSuperstrOrElement(key, allowValue) {
      const iter = this._iter.reset(key);
      let node = this._root;
      while (node) {
        const val = iter.cmp(node.segment);
        if (val > 0) {
          node = node.left;
        } else if (val < 0) {
          node = node.right;
        } else if (iter.hasNext()) {
          iter.next();
          node = node.mid;
        } else {
          if (!node.mid) {
            if (allowValue) {
              return Undef.unwrap(node.value);
            } else {
              return void 0;
            }
          } else {
            return this._entries(node.mid);
          }
        }
      }
      return void 0;
    }
    forEach(callback) {
      for (const [key, value] of this) {
        callback(value, key);
      }
    }
    *[Symbol.iterator]() {
      yield* this._entries(this._root);
    }
    _entries(node) {
      const result = [];
      this._dfsEntries(node, result);
      return result[Symbol.iterator]();
    }
    _dfsEntries(node, bucket) {
      if (!node) {
        return;
      }
      if (node.left) {
        this._dfsEntries(node.left, bucket);
      }
      if (node.value !== void 0) {
        bucket.push([node.key, Undef.unwrap(node.value)]);
      }
      if (node.mid) {
        this._dfsEntries(node.mid, bucket);
      }
      if (node.right) {
        this._dfsEntries(node.right, bucket);
      }
    }
  }
  const IWorkspaceContextService = createDecorator("contextService");
  function isSingleFolderWorkspaceIdentifier(obj) {
    const singleFolderIdentifier = obj;
    return typeof singleFolderIdentifier?.id === "string" && URI.isUri(singleFolderIdentifier.uri);
  }
  function isEmptyWorkspaceIdentifier(obj) {
    const emptyWorkspaceIdentifier = obj;
    return typeof emptyWorkspaceIdentifier?.id === "string" && !isSingleFolderWorkspaceIdentifier(obj) && !isWorkspaceIdentifier(obj);
  }
  const UNKNOWN_EMPTY_WINDOW_WORKSPACE = { id: "empty-window" };
  function toWorkspaceIdentifier(arg0, isExtensionDevelopment) {
    if (typeof arg0 === "string" || typeof arg0 === "undefined") {
      if (typeof arg0 === "string") {
        return {
          id: basename$1(arg0)
        };
      }
      return UNKNOWN_EMPTY_WINDOW_WORKSPACE;
    }
    const workspace = arg0;
    if (workspace.configuration) {
      return {
        id: workspace.id,
        configPath: workspace.configuration
      };
    }
    if (workspace.folders.length === 1) {
      return {
        id: workspace.id,
        uri: workspace.folders[0].uri
      };
    }
    return {
      id: workspace.id
    };
  }
  function isWorkspaceIdentifier(obj) {
    const workspaceIdentifier = obj;
    return typeof workspaceIdentifier?.id === "string" && URI.isUri(workspaceIdentifier.configPath);
  }
  class WorkspaceFolder {
    constructor(data, raw) {
      this.raw = raw;
      this.uri = data.uri;
      this.index = data.index;
      this.name = data.name;
    }
    toJSON() {
      return { uri: this.uri, name: this.name, index: this.index };
    }
  }
  const WORKSPACE_EXTENSION = "code-workspace";
  [{ name: localize(2050, "Code Workspace"), extensions: [WORKSPACE_EXTENSION] }];
  const STANDALONE_EDITOR_WORKSPACE_ID = "4064f6ec-cb38-4ad0-af64-ee6467e63c82";
  function isStandaloneEditorWorkspace(workspace) {
    return workspace.id === STANDALONE_EDITOR_WORKSPACE_ID;
  }
  var __decorate$2o = 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$2m = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  class SimplePasteAndDropProvider {
    constructor(kind) {
      this.copyMimeTypes = [];
      this.kind = kind;
      this.providedDropEditKinds = [this.kind];
      this.providedPasteEditKinds = [this.kind];
    }
    async provideDocumentPasteEdits(_model, _ranges, dataTransfer, context, token) {
      const edit2 = await this.getEdit(dataTransfer, token);
      if (!edit2) {
        return void 0;
      }
      return {
        edits: [{ insertText: edit2.insertText, title: edit2.title, kind: edit2.kind, handledMimeType: edit2.handledMimeType, yieldTo: edit2.yieldTo }],
        dispose() {
        }
      };
    }
    async provideDocumentDropEdits(_model, _position, dataTransfer, token) {
      const edit2 = await this.getEdit(dataTransfer, token);
      if (!edit2) {
        return;
      }
      return {
        edits: [{ insertText: edit2.insertText, title: edit2.title, kind: edit2.kind, handledMimeType: edit2.handledMimeType, yieldTo: edit2.yieldTo }],
        dispose() {
        }
      };
    }
  }
  const _DefaultTextPasteOrDropEditProvider = class _DefaultTextPasteOrDropEditProvider extends SimplePasteAndDropProvider {
    constructor() {
      super(HierarchicalKind.Empty.append("text", "plain"));
      this.id = _DefaultTextPasteOrDropEditProvider.id;
      this.dropMimeTypes = [Mimes.text];
      this.pasteMimeTypes = [Mimes.text];
    }
    async getEdit(dataTransfer, _token) {
      const textEntry = dataTransfer.get(Mimes.text);
      if (!textEntry) {
        return;
      }
      if (dataTransfer.has(Mimes.uriList)) {
        return;
      }
      const insertText = await textEntry.asString();
      return {
        handledMimeType: Mimes.text,
        title: localize(926, "Insert Plain Text"),
        insertText,
        kind: this.kind
      };
    }
  };
  _DefaultTextPasteOrDropEditProvider.id = "text";
  let DefaultTextPasteOrDropEditProvider = _DefaultTextPasteOrDropEditProvider;
  class PathProvider extends SimplePasteAndDropProvider {
    constructor() {
      super(HierarchicalKind.Empty.append("uri", "path", "absolute"));
      this.dropMimeTypes = [Mimes.uriList];
      this.pasteMimeTypes = [Mimes.uriList];
    }
    async getEdit(dataTransfer, token) {
      const entries2 = await extractUriList(dataTransfer);
      if (!entries2.length || token.isCancellationRequested) {
        return;
      }
      let uriCount = 0;
      const insertText = entries2.map(({ uri, originalText }) => {
        if (uri.scheme === Schemas.file) {
          return uri.fsPath;
        } else {
          uriCount++;
          return originalText;
        }
      }).join(" ");
      let label;
      if (uriCount > 0) {
        label = entries2.length > 1 ? localize(927, "Insert Uris") : localize(928, "Insert Uri");
      } else {
        label = entries2.length > 1 ? localize(929, "Insert Paths") : localize(930, "Insert Path");
      }
      return {
        handledMimeType: Mimes.uriList,
        insertText,
        title: label,
        kind: this.kind
      };
    }
  }
  let RelativePathProvider = class RelativePathProvider extends SimplePasteAndDropProvider {
    constructor(_workspaceContextService) {
      super(HierarchicalKind.Empty.append("uri", "path", "relative"));
      this._workspaceContextService = _workspaceContextService;
      this.dropMimeTypes = [Mimes.uriList];
      this.pasteMimeTypes = [Mimes.uriList];
    }
    async getEdit(dataTransfer, token) {
      const entries2 = await extractUriList(dataTransfer);
      if (!entries2.length || token.isCancellationRequested) {
        return;
      }
      const relativeUris = coalesce(entries2.map(({ uri }) => {
        const root = this._workspaceContextService.getWorkspaceFolder(uri);
        return root ? relativePath(root.uri, uri) : void 0;
      }));
      if (!relativeUris.length) {
        return;
      }
      return {
        handledMimeType: Mimes.uriList,
        insertText: relativeUris.join(" "),
        title: entries2.length > 1 ? localize(931, "Insert Relative Paths") : localize(932, "Insert Relative Path"),
        kind: this.kind
      };
    }
  };
  RelativePathProvider = __decorate$2o([
    __param$2m(0, IWorkspaceContextService)
  ], RelativePathProvider);
  class PasteHtmlProvider {
    constructor() {
      this.kind = new HierarchicalKind("html");
      this.providedPasteEditKinds = [this.kind];
      this.copyMimeTypes = [];
      this.pasteMimeTypes = ["text/html"];
      this._yieldTo = [{ mimeType: Mimes.text }];
    }
    async provideDocumentPasteEdits(_model, _ranges, dataTransfer, context, token) {
      if (context.triggerKind !== DocumentPasteTriggerKind.PasteAs && !context.only?.contains(this.kind)) {
        return;
      }
      const entry = dataTransfer.get("text/html");
      const htmlText = await entry?.asString();
      if (!htmlText || token.isCancellationRequested) {
        return;
      }
      return {
        dispose() {
        },
        edits: [{
          insertText: htmlText,
          yieldTo: this._yieldTo,
          title: localize(933, "Insert HTML"),
          kind: this.kind
        }]
      };
    }
  }
  async function extractUriList(dataTransfer) {
    const urlListEntry = dataTransfer.get(Mimes.uriList);
    if (!urlListEntry) {
      return [];
    }
    const strUriList = await urlListEntry.asString();
    const entries2 = [];
    for (const entry of UriList.parse(strUriList)) {
      try {
        entries2.push({ uri: URI.parse(entry), originalText: entry });
      } catch {
      }
    }
    return entries2;
  }
  const genericLanguageSelector = { scheme: "*", hasAccessToAllModels: true };
  let DefaultDropProvidersFeature = class DefaultDropProvidersFeature extends Disposable {
    constructor(languageFeaturesService, workspaceContextService) {
      super();
      this._register(languageFeaturesService.documentDropEditProvider.register(genericLanguageSelector, new DefaultTextPasteOrDropEditProvider()));
      this._register(languageFeaturesService.documentDropEditProvider.register(genericLanguageSelector, new PathProvider()));
      this._register(languageFeaturesService.documentDropEditProvider.register(genericLanguageSelector, new RelativePathProvider(workspaceContextService)));
    }
  };
  DefaultDropProvidersFeature = __decorate$2o([
    __param$2m(0, ILanguageFeaturesService),
    __param$2m(1, IWorkspaceContextService)
  ], DefaultDropProvidersFeature);
  let DefaultPasteProvidersFeature = class DefaultPasteProvidersFeature extends Disposable {
    constructor(languageFeaturesService, workspaceContextService) {
      super();
      this._register(languageFeaturesService.documentPasteEditProvider.register(genericLanguageSelector, new DefaultTextPasteOrDropEditProvider()));
      this._register(languageFeaturesService.documentPasteEditProvider.register(genericLanguageSelector, new PathProvider()));
      this._register(languageFeaturesService.documentPasteEditProvider.register(genericLanguageSelector, new RelativePathProvider(workspaceContextService)));
      this._register(languageFeaturesService.documentPasteEditProvider.register(genericLanguageSelector, new PasteHtmlProvider()));
    }
  };
  DefaultPasteProvidersFeature = __decorate$2o([
    __param$2m(0, ILanguageFeaturesService),
    __param$2m(1, IWorkspaceContextService)
  ], DefaultPasteProvidersFeature);
  const _Scanner = class _Scanner {
    constructor() {
      this.value = "";
      this.pos = 0;
    }
    static isDigitCharacter(ch) {
      return ch >= 48 && ch <= 57;
    }
    static isVariableCharacter(ch) {
      return ch === 95 || ch >= 97 && ch <= 122 || ch >= 65 && ch <= 90;
    }
    text(value) {
      this.value = value;
      this.pos = 0;
    }
    tokenText(token) {
      return this.value.substr(token.pos, token.len);
    }
    next() {
      if (this.pos >= this.value.length) {
        return { type: 14, pos: this.pos, len: 0 };
      }
      const pos = this.pos;
      let len = 0;
      let ch = this.value.charCodeAt(pos);
      let type;
      type = _Scanner._table[ch];
      if (typeof type === "number") {
        this.pos += 1;
        return { type, pos, len: 1 };
      }
      if (_Scanner.isDigitCharacter(ch)) {
        type = 8;
        do {
          len += 1;
          ch = this.value.charCodeAt(pos + len);
        } while (_Scanner.isDigitCharacter(ch));
        this.pos += len;
        return { type, pos, len };
      }
      if (_Scanner.isVariableCharacter(ch)) {
        type = 9;
        do {
          ch = this.value.charCodeAt(pos + ++len);
        } while (_Scanner.isVariableCharacter(ch) || _Scanner.isDigitCharacter(ch));
        this.pos += len;
        return { type, pos, len };
      }
      type = 10;
      do {
        len += 1;
        ch = this.value.charCodeAt(pos + len);
      } while (!isNaN(ch) && typeof _Scanner._table[ch] === "undefined" && !_Scanner.isDigitCharacter(ch) && !_Scanner.isVariableCharacter(ch));
      this.pos += len;
      return { type, pos, len };
    }
  };
  _Scanner._table = {
    [
      36
      /* CharCode.DollarSign */
    ]: 0,
    [
      58
      /* CharCode.Colon */
    ]: 1,
    [
      44
      /* CharCode.Comma */
    ]: 2,
    [
      123
      /* CharCode.OpenCurlyBrace */
    ]: 3,
    [
      125
      /* CharCode.CloseCurlyBrace */
    ]: 4,
    [
      92
      /* CharCode.Backslash */
    ]: 5,
    [
      47
      /* CharCode.Slash */
    ]: 6,
    [
      124
      /* CharCode.Pipe */
    ]: 7,
    [
      43
      /* CharCode.Plus */
    ]: 11,
    [
      45
      /* CharCode.Dash */
    ]: 12,
    [
      63
      /* CharCode.QuestionMark */
    ]: 13
  };
  let Scanner = _Scanner;
  class Marker {
    constructor() {
      this._children = [];
    }
    appendChild(child) {
      if (child instanceof Text && this._children[this._children.length - 1] instanceof Text) {
        this._children[this._children.length - 1].value += child.value;
      } else {
        child.parent = this;
        this._children.push(child);
      }
      return this;
    }
    replace(child, others) {
      const { parent } = child;
      const idx = parent.children.indexOf(child);
      const newChildren = parent.children.slice(0);
      newChildren.splice(idx, 1, ...others);
      parent._children = newChildren;
      (function _fixParent(children, parent2) {
        for (const child2 of children) {
          child2.parent = parent2;
          _fixParent(child2.children, child2);
        }
      })(others, parent);
    }
    get children() {
      return this._children;
    }
    get rightMostDescendant() {
      if (this._children.length > 0) {
        return this._children[this._children.length - 1].rightMostDescendant;
      }
      return this;
    }
    get snippet() {
      let candidate = this;
      while (true) {
        if (!candidate) {
          return void 0;
        }
        if (candidate instanceof TextmateSnippet) {
          return candidate;
        }
        candidate = candidate.parent;
      }
    }
    toString() {
      return this.children.reduce((prev, cur) => prev + cur.toString(), "");
    }
    len() {
      return 0;
    }
  }
  class Text extends Marker {
    constructor(value) {
      super();
      this.value = value;
    }
    toString() {
      return this.value;
    }
    len() {
      return this.value.length;
    }
    clone() {
      return new Text(this.value);
    }
  }
  class TransformableMarker extends Marker {
  }
  class Placeholder extends TransformableMarker {
    static compareByIndex(a, b) {
      if (a.index === b.index) {
        return 0;
      } else if (a.isFinalTabstop) {
        return 1;
      } else if (b.isFinalTabstop) {
        return -1;
      } else if (a.index < b.index) {
        return -1;
      } else if (a.index > b.index) {
        return 1;
      } else {
        return 0;
      }
    }
    constructor(index) {
      super();
      this.index = index;
    }
    get isFinalTabstop() {
      return this.index === 0;
    }
    get choice() {
      return this._children.length === 1 && this._children[0] instanceof Choice ? this._children[0] : void 0;
    }
    clone() {
      const ret = new Placeholder(this.index);
      if (this.transform) {
        ret.transform = this.transform.clone();
      }
      ret._children = this.children.map((child) => child.clone());
      return ret;
    }
  }
  class Choice extends Marker {
    constructor() {
      super(...arguments);
      this.options = [];
    }
    appendChild(marker) {
      if (marker instanceof Text) {
        marker.parent = this;
        this.options.push(marker);
      }
      return this;
    }
    toString() {
      return this.options[0].value;
    }
    len() {
      return this.options[0].len();
    }
    clone() {
      const ret = new Choice();
      this.options.forEach(ret.appendChild, ret);
      return ret;
    }
  }
  class Transform extends Marker {
    constructor() {
      super(...arguments);
      this.regexp = new RegExp("");
    }
    resolve(value) {
      const _this = this;
      let didMatch = false;
      let ret = value.replace(this.regexp, function() {
        didMatch = true;
        return _this._replace(Array.prototype.slice.call(arguments, 0, -2));
      });
      if (!didMatch && this._children.some((child) => child instanceof FormatString && Boolean(child.elseValue))) {
        ret = this._replace([]);
      }
      return ret;
    }
    _replace(groups) {
      let ret = "";
      for (const marker of this._children) {
        if (marker instanceof FormatString) {
          let value = groups[marker.index] || "";
          value = marker.resolve(value);
          ret += value;
        } else {
          ret += marker.toString();
        }
      }
      return ret;
    }
    toString() {
      return "";
    }
    clone() {
      const ret = new Transform();
      ret.regexp = new RegExp(this.regexp.source, (this.regexp.ignoreCase ? "i" : "") + (this.regexp.global ? "g" : ""));
      ret._children = this.children.map((child) => child.clone());
      return ret;
    }
  }
  class FormatString extends Marker {
    constructor(index, shorthandName, ifValue, elseValue) {
      super();
      this.index = index;
      this.shorthandName = shorthandName;
      this.ifValue = ifValue;
      this.elseValue = elseValue;
    }
    resolve(value) {
      if (this.shorthandName === "upcase") {
        return !value ? "" : value.toLocaleUpperCase();
      } else if (this.shorthandName === "downcase") {
        return !value ? "" : value.toLocaleLowerCase();
      } else if (this.shorthandName === "capitalize") {
        return !value ? "" : value[0].toLocaleUpperCase() + value.substr(1);
      } else if (this.shorthandName === "pascalcase") {
        return !value ? "" : this._toPascalCase(value);
      } else if (this.shorthandName === "camelcase") {
        return !value ? "" : this._toCamelCase(value);
      } else if (Boolean(value) && typeof this.ifValue === "string") {
        return this.ifValue;
      } else if (!Boolean(value) && typeof this.elseValue === "string") {
        return this.elseValue;
      } else {
        return value || "";
      }
    }
    _toPascalCase(value) {
      const match2 = value.match(/[a-z0-9]+/gi);
      if (!match2) {
        return value;
      }
      return match2.map((word) => {
        return word.charAt(0).toUpperCase() + word.substr(1);
      }).join("");
    }
    _toCamelCase(value) {
      const match2 = value.match(/[a-z0-9]+/gi);
      if (!match2) {
        return value;
      }
      return match2.map((word, index) => {
        if (index === 0) {
          return word.charAt(0).toLowerCase() + word.substr(1);
        }
        return word.charAt(0).toUpperCase() + word.substr(1);
      }).join("");
    }
    clone() {
      const ret = new FormatString(this.index, this.shorthandName, this.ifValue, this.elseValue);
      return ret;
    }
  }
  class Variable extends TransformableMarker {
    constructor(name) {
      super();
      this.name = name;
    }
    resolve(resolver) {
      let value = resolver.resolve(this);
      if (this.transform) {
        value = this.transform.resolve(value || "");
      }
      if (value !== void 0) {
        this._children = [new Text(value)];
        return true;
      }
      return false;
    }
    clone() {
      const ret = new Variable(this.name);
      if (this.transform) {
        ret.transform = this.transform.clone();
      }
      ret._children = this.children.map((child) => child.clone());
      return ret;
    }
  }
  function walk(marker, visitor) {
    const stack = [...marker];
    while (stack.length > 0) {
      const marker2 = stack.shift();
      const recurse = visitor(marker2);
      if (!recurse) {
        break;
      }
      stack.unshift(...marker2.children);
    }
  }
  class TextmateSnippet extends Marker {
    get placeholderInfo() {
      if (!this._placeholders) {
        const all = [];
        let last;
        this.walk(function(candidate) {
          if (candidate instanceof Placeholder) {
            all.push(candidate);
            last = !last || last.index < candidate.index ? candidate : last;
          }
          return true;
        });
        this._placeholders = { all, last };
      }
      return this._placeholders;
    }
    get placeholders() {
      const { all } = this.placeholderInfo;
      return all;
    }
    offset(marker) {
      let pos = 0;
      let found = false;
      this.walk((candidate) => {
        if (candidate === marker) {
          found = true;
          return false;
        }
        pos += candidate.len();
        return true;
      });
      if (!found) {
        return -1;
      }
      return pos;
    }
    fullLen(marker) {
      let ret = 0;
      walk([marker], (marker2) => {
        ret += marker2.len();
        return true;
      });
      return ret;
    }
    enclosingPlaceholders(placeholder) {
      const ret = [];
      let { parent } = placeholder;
      while (parent) {
        if (parent instanceof Placeholder) {
          ret.push(parent);
        }
        parent = parent.parent;
      }
      return ret;
    }
    resolveVariables(resolver) {
      this.walk((candidate) => {
        if (candidate instanceof Variable) {
          if (candidate.resolve(resolver)) {
            this._placeholders = void 0;
          }
        }
        return true;
      });
      return this;
    }
    appendChild(child) {
      this._placeholders = void 0;
      return super.appendChild(child);
    }
    replace(child, others) {
      this._placeholders = void 0;
      return super.replace(child, others);
    }
    clone() {
      const ret = new TextmateSnippet();
      this._children = this.children.map((child) => child.clone());
      return ret;
    }
    walk(visitor) {
      walk(this.children, visitor);
    }
  }
  class SnippetParser {
    constructor() {
      this._scanner = new Scanner();
      this._token = { type: 14, pos: 0, len: 0 };
    }
    static escape(value) {
      return value.replace(/\$|}|\\/g, "\\$&");
    }
    static guessNeedsClipboard(template) {
      return /\${?CLIPBOARD/.test(template);
    }
    parse(value, insertFinalTabstop, enforceFinalTabstop) {
      const snippet = new TextmateSnippet();
      this.parseFragment(value, snippet);
      this.ensureFinalTabstop(snippet, enforceFinalTabstop ?? false, insertFinalTabstop ?? false);
      return snippet;
    }
    parseFragment(value, snippet) {
      const offset = snippet.children.length;
      this._scanner.text(value);
      this._token = this._scanner.next();
      while (this._parse(snippet)) {
      }
      const placeholderDefaultValues = /* @__PURE__ */ new Map();
      const incompletePlaceholders = [];
      snippet.walk((marker) => {
        if (marker instanceof Placeholder) {
          if (marker.isFinalTabstop) {
            placeholderDefaultValues.set(0, void 0);
          } else if (!placeholderDefaultValues.has(marker.index) && marker.children.length > 0) {
            placeholderDefaultValues.set(marker.index, marker.children);
          } else {
            incompletePlaceholders.push(marker);
          }
        }
        return true;
      });
      const fillInIncompletePlaceholder = (placeholder, stack2) => {
        const defaultValues = placeholderDefaultValues.get(placeholder.index);
        if (!defaultValues) {
          return;
        }
        const clone2 = new Placeholder(placeholder.index);
        clone2.transform = placeholder.transform;
        for (const child of defaultValues) {
          const newChild = child.clone();
          clone2.appendChild(newChild);
          if (newChild instanceof Placeholder && placeholderDefaultValues.has(newChild.index) && !stack2.has(newChild.index)) {
            stack2.add(newChild.index);
            fillInIncompletePlaceholder(newChild, stack2);
            stack2.delete(newChild.index);
          }
        }
        snippet.replace(placeholder, [clone2]);
      };
      const stack = /* @__PURE__ */ new Set();
      for (const placeholder of incompletePlaceholders) {
        fillInIncompletePlaceholder(placeholder, stack);
      }
      return snippet.children.slice(offset);
    }
    ensureFinalTabstop(snippet, enforceFinalTabstop, insertFinalTabstop) {
      if (enforceFinalTabstop || insertFinalTabstop && snippet.placeholders.length > 0) {
        const finalTabstop = snippet.placeholders.find((p) => p.index === 0);
        if (!finalTabstop) {
          snippet.appendChild(new Placeholder(0));
        }
      }
    }
    _accept(type, value) {
      if (type === void 0 || this._token.type === type) {
        const ret = !value ? true : this._scanner.tokenText(this._token);
        this._token = this._scanner.next();
        return ret;
      }
      return false;
    }
    _backTo(token) {
      this._scanner.pos = token.pos + token.len;
      this._token = token;
      return false;
    }
    _until(type) {
      const start = this._token;
      while (this._token.type !== type) {
        if (this._token.type === 14) {
          return false;
        } else if (this._token.type === 5) {
          const nextToken = this._scanner.next();
          if (nextToken.type !== 0 && nextToken.type !== 4 && nextToken.type !== 5) {
            return false;
          }
        }
        this._token = this._scanner.next();
      }
      const value = this._scanner.value.substring(start.pos, this._token.pos).replace(/\\(\$|}|\\)/g, "$1");
      this._token = this._scanner.next();
      return value;
    }
    _parse(marker) {
      return this._parseEscaped(marker) || this._parseTabstopOrVariableName(marker) || this._parseComplexPlaceholder(marker) || this._parseComplexVariable(marker) || this._parseAnything(marker);
    }
    // \$, \\, \} -> just text
    _parseEscaped(marker) {
      let value;
      if (value = this._accept(5, true)) {
        value = this._accept(0, true) || this._accept(4, true) || this._accept(5, true) || value;
        marker.appendChild(new Text(value));
        return true;
      }
      return false;
    }
    // $foo -> variable, $1 -> tabstop
    _parseTabstopOrVariableName(parent) {
      let value;
      const token = this._token;
      const match2 = this._accept(
        0
        /* TokenType.Dollar */
      ) && (value = this._accept(9, true) || this._accept(8, true));
      if (!match2) {
        return this._backTo(token);
      }
      parent.appendChild(/^\d+$/.test(value) ? new Placeholder(Number(value)) : new Variable(value));
      return true;
    }
    // ${1:<children>}, ${1} -> placeholder
    _parseComplexPlaceholder(parent) {
      let index;
      const token = this._token;
      const match2 = this._accept(
        0
        /* TokenType.Dollar */
      ) && this._accept(
        3
        /* TokenType.CurlyOpen */
      ) && (index = this._accept(8, true));
      if (!match2) {
        return this._backTo(token);
      }
      const placeholder = new Placeholder(Number(index));
      if (this._accept(
        1
        /* TokenType.Colon */
      )) {
        while (true) {
          if (this._accept(
            4
            /* TokenType.CurlyClose */
          )) {
            parent.appendChild(placeholder);
            return true;
          }
          if (this._parse(placeholder)) {
            continue;
          }
          parent.appendChild(new Text("${" + index + ":"));
          placeholder.children.forEach(parent.appendChild, parent);
          return true;
        }
      } else if (placeholder.index > 0 && this._accept(
        7
        /* TokenType.Pipe */
      )) {
        const choice = new Choice();
        while (true) {
          if (this._parseChoiceElement(choice)) {
            if (this._accept(
              2
              /* TokenType.Comma */
            )) {
              continue;
            }
            if (this._accept(
              7
              /* TokenType.Pipe */
            )) {
              placeholder.appendChild(choice);
              if (this._accept(
                4
                /* TokenType.CurlyClose */
              )) {
                parent.appendChild(placeholder);
                return true;
              }
            }
          }
          this._backTo(token);
          return false;
        }
      } else if (this._accept(
        6
        /* TokenType.Forwardslash */
      )) {
        if (this._parseTransform(placeholder)) {
          parent.appendChild(placeholder);
          return true;
        }
        this._backTo(token);
        return false;
      } else if (this._accept(
        4
        /* TokenType.CurlyClose */
      )) {
        parent.appendChild(placeholder);
        return true;
      } else {
        return this._backTo(token);
      }
    }
    _parseChoiceElement(parent) {
      const token = this._token;
      const values = [];
      while (true) {
        if (this._token.type === 2 || this._token.type === 7) {
          break;
        }
        let value;
        if (value = this._accept(5, true)) {
          value = this._accept(2, true) || this._accept(7, true) || this._accept(5, true) || value;
        } else {
          value = this._accept(void 0, true);
        }
        if (!value) {
          this._backTo(token);
          return false;
        }
        values.push(value);
      }
      if (values.length === 0) {
        this._backTo(token);
        return false;
      }
      parent.appendChild(new Text(values.join("")));
      return true;
    }
    // ${foo:<children>}, ${foo} -> variable
    _parseComplexVariable(parent) {
      let name;
      const token = this._token;
      const match2 = this._accept(
        0
        /* TokenType.Dollar */
      ) && this._accept(
        3
        /* TokenType.CurlyOpen */
      ) && (name = this._accept(9, true));
      if (!match2) {
        return this._backTo(token);
      }
      const variable = new Variable(name);
      if (this._accept(
        1
        /* TokenType.Colon */
      )) {
        while (true) {
          if (this._accept(
            4
            /* TokenType.CurlyClose */
          )) {
            parent.appendChild(variable);
            return true;
          }
          if (this._parse(variable)) {
            continue;
          }
          parent.appendChild(new Text("${" + name + ":"));
          variable.children.forEach(parent.appendChild, parent);
          return true;
        }
      } else if (this._accept(
        6
        /* TokenType.Forwardslash */
      )) {
        if (this._parseTransform(variable)) {
          parent.appendChild(variable);
          return true;
        }
        this._backTo(token);
        return false;
      } else if (this._accept(
        4
        /* TokenType.CurlyClose */
      )) {
        parent.appendChild(variable);
        return true;
      } else {
        return this._backTo(token);
      }
    }
    _parseTransform(parent) {
      const transform = new Transform();
      let regexValue = "";
      let regexOptions = "";
      while (true) {
        if (this._accept(
          6
          /* TokenType.Forwardslash */
        )) {
          break;
        }
        let escaped;
        if (escaped = this._accept(5, true)) {
          escaped = this._accept(6, true) || escaped;
          regexValue += escaped;
          continue;
        }
        if (this._token.type !== 14) {
          regexValue += this._accept(void 0, true);
          continue;
        }
        return false;
      }
      while (true) {
        if (this._accept(
          6
          /* TokenType.Forwardslash */
        )) {
          break;
        }
        let escaped;
        if (escaped = this._accept(5, true)) {
          escaped = this._accept(5, true) || this._accept(6, true) || escaped;
          transform.appendChild(new Text(escaped));
          continue;
        }
        if (this._parseFormatString(transform) || this._parseAnything(transform)) {
          continue;
        }
        return false;
      }
      while (true) {
        if (this._accept(
          4
          /* TokenType.CurlyClose */
        )) {
          break;
        }
        if (this._token.type !== 14) {
          regexOptions += this._accept(void 0, true);
          continue;
        }
        return false;
      }
      try {
        transform.regexp = new RegExp(regexValue, regexOptions);
      } catch (e) {
        return false;
      }
      parent.transform = transform;
      return true;
    }
    _parseFormatString(parent) {
      const token = this._token;
      if (!this._accept(
        0
        /* TokenType.Dollar */
      )) {
        return false;
      }
      let complex = false;
      if (this._accept(
        3
        /* TokenType.CurlyOpen */
      )) {
        complex = true;
      }
      const index = this._accept(8, true);
      if (!index) {
        this._backTo(token);
        return false;
      } else if (!complex) {
        parent.appendChild(new FormatString(Number(index)));
        return true;
      } else if (this._accept(
        4
        /* TokenType.CurlyClose */
      )) {
        parent.appendChild(new FormatString(Number(index)));
        return true;
      } else if (!this._accept(
        1
        /* TokenType.Colon */
      )) {
        this._backTo(token);
        return false;
      }
      if (this._accept(
        6
        /* TokenType.Forwardslash */
      )) {
        const shorthand = this._accept(9, true);
        if (!shorthand || !this._accept(
          4
          /* TokenType.CurlyClose */
        )) {
          this._backTo(token);
          return false;
        } else {
          parent.appendChild(new FormatString(Number(index), shorthand));
          return true;
        }
      } else if (this._accept(
        11
        /* TokenType.Plus */
      )) {
        const ifValue = this._until(
          4
          /* TokenType.CurlyClose */
        );
        if (ifValue) {
          parent.appendChild(new FormatString(Number(index), void 0, ifValue, void 0));
          return true;
        }
      } else if (this._accept(
        12
        /* TokenType.Dash */
      )) {
        const elseValue = this._until(
          4
          /* TokenType.CurlyClose */
        );
        if (elseValue) {
          parent.appendChild(new FormatString(Number(index), void 0, void 0, elseValue));
          return true;
        }
      } else if (this._accept(
        13
        /* TokenType.QuestionMark */
      )) {
        const ifValue = this._until(
          1
          /* TokenType.Colon */
        );
        if (ifValue) {
          const elseValue = this._until(
            4
            /* TokenType.CurlyClose */
          );
          if (elseValue) {
            parent.appendChild(new FormatString(Number(index), void 0, ifValue, elseValue));
            return true;
          }
        }
      } else {
        const elseValue = this._until(
          4
          /* TokenType.CurlyClose */
        );
        if (elseValue) {
          parent.appendChild(new FormatString(Number(index), void 0, void 0, elseValue));
          return true;
        }
      }
      this._backTo(token);
      return false;
    }
    _parseAnything(marker) {
      if (this._token.type !== 14) {
        marker.appendChild(new Text(this._scanner.tokenText(this._token)));
        this._accept(void 0);
        return true;
      }
      return false;
    }
  }
  function createCombinedWorkspaceEdit(uri, ranges, edit2) {
    if (typeof edit2.insertText === "string" ? edit2.insertText === "" : edit2.insertText.snippet === "") {
      return {
        edits: edit2.additionalEdit?.edits ?? []
      };
    }
    return {
      edits: [
        ...ranges.map((range2) => new ResourceTextEdit(uri, { range: range2, text: typeof edit2.insertText === "string" ? SnippetParser.escape(edit2.insertText) + "$0" : edit2.insertText.snippet, insertAsSnippet: true })),
        ...edit2.additionalEdit?.edits ?? []
      ]
    };
  }
  function sortEditsByYieldTo(edits) {
    function yieldsTo(yTo, other) {
      if ("mimeType" in yTo) {
        return yTo.mimeType === other.handledMimeType;
      }
      return !!other.kind && yTo.kind.contains(other.kind);
    }
    const yieldsToMap = /* @__PURE__ */ new Map();
    for (const edit2 of edits) {
      for (const yTo of edit2.yieldTo ?? []) {
        for (const other of edits) {
          if (other === edit2) {
            continue;
          }
          if (yieldsTo(yTo, other)) {
            let arr = yieldsToMap.get(edit2);
            if (!arr) {
              arr = [];
              yieldsToMap.set(edit2, arr);
            }
            arr.push(other);
          }
        }
      }
    }
    if (!yieldsToMap.size) {
      return Array.from(edits);
    }
    const visited = /* @__PURE__ */ new Set();
    const tempStack = [];
    function visit(nodes) {
      if (!nodes.length) {
        return [];
      }
      const node = nodes[0];
      if (tempStack.includes(node)) {
        console.warn("Yield to cycle detected", node);
        return nodes;
      }
      if (visited.has(node)) {
        return visit(nodes.slice(1));
      }
      let pre = [];
      const yTo = yieldsToMap.get(node);
      if (yTo) {
        tempStack.push(node);
        pre = visit(yTo);
        tempStack.pop();
      }
      visited.add(node);
      return [...pre, node, ...visit(nodes.slice(1))];
    }
    return visit(Array.from(edits));
  }
  ({
    buttonSeparator: Color.white.toString(),
    buttonForeground: Color.white.toString()
  });
  const buttonSanitizerConfig = Object.freeze({
    allowedTags: {
      override: ["b", "i", "u", "code", "span"]
    },
    allowedAttributes: {
      override: ["class"]
    }
  });
  class Button extends Disposable {
    get onDidClick() {
      return this._onDidClick.event;
    }
    constructor(container, options) {
      super();
      this._label = "";
      this._onDidClick = this._register(new Emitter$1());
      this._onDidEscape = this._register(new Emitter$1());
      this.options = options;
      this._element = document.createElement("a");
      this._element.classList.add("monaco-button");
      this._element.tabIndex = 0;
      this._element.setAttribute("role", "button");
      this._element.classList.toggle("secondary", !!options.secondary);
      const background = options.secondary ? options.buttonSecondaryBackground : options.buttonBackground;
      const foreground2 = options.secondary ? options.buttonSecondaryForeground : options.buttonForeground;
      this._element.style.color = foreground2 || "";
      this._element.style.backgroundColor = background || "";
      if (options.supportShortLabel) {
        this._labelShortElement = document.createElement("div");
        this._labelShortElement.classList.add("monaco-button-label-short");
        this._element.appendChild(this._labelShortElement);
        this._labelElement = document.createElement("div");
        this._labelElement.classList.add("monaco-button-label");
        this._element.appendChild(this._labelElement);
        this._element.classList.add("monaco-text-button-with-short-label");
      }
      if (typeof options.title === "string") {
        this.setTitle(options.title);
      }
      if (typeof options.ariaLabel === "string") {
        this._element.setAttribute("aria-label", options.ariaLabel);
      }
      container.appendChild(this._element);
      this.enabled = !options.disabled;
      this._register(Gesture.addTarget(this._element));
      [EventType$1.CLICK, EventType.Tap].forEach((eventType) => {
        this._register(addDisposableListener(this._element, eventType, (e) => {
          if (!this.enabled) {
            EventHelper.stop(e);
            return;
          }
          this._onDidClick.fire(e);
        }));
      });
      this._register(addDisposableListener(this._element, EventType$1.KEY_DOWN, (e) => {
        const event = new StandardKeyboardEvent(e);
        let eventHandled = false;
        if (this.enabled && (event.equals(
          3
          /* KeyCode.Enter */
        ) || event.equals(
          10
          /* KeyCode.Space */
        ))) {
          this._onDidClick.fire(e);
          eventHandled = true;
        } else if (event.equals(
          9
          /* KeyCode.Escape */
        )) {
          this._onDidEscape.fire(e);
          this._element.blur();
          eventHandled = true;
        }
        if (eventHandled) {
          EventHelper.stop(event, true);
        }
      }));
      this._register(addDisposableListener(this._element, EventType$1.MOUSE_OVER, (e) => {
        if (!this._element.classList.contains("disabled")) {
          this.updateBackground(true);
        }
      }));
      this._register(addDisposableListener(this._element, EventType$1.MOUSE_OUT, (e) => {
        this.updateBackground(false);
      }));
      this.focusTracker = this._register(trackFocus(this._element));
      this._register(this.focusTracker.onDidFocus(() => {
        if (this.enabled) {
          this.updateBackground(true);
        }
      }));
      this._register(this.focusTracker.onDidBlur(() => {
        if (this.enabled) {
          this.updateBackground(false);
        }
      }));
    }
    dispose() {
      super.dispose();
      this._element.remove();
    }
    getContentElements(content) {
      const elements = [];
      for (let segment of renderLabelWithIcons(content)) {
        if (typeof segment === "string") {
          segment = segment.trim();
          if (segment === "") {
            continue;
          }
          const node = document.createElement("span");
          node.textContent = segment;
          elements.push(node);
        } else {
          elements.push(segment);
        }
      }
      return elements;
    }
    updateBackground(hover) {
      let background;
      if (this.options.secondary) {
        background = hover ? this.options.buttonSecondaryHoverBackground : this.options.buttonSecondaryBackground;
      } else {
        background = hover ? this.options.buttonHoverBackground : this.options.buttonBackground;
      }
      if (background) {
        this._element.style.backgroundColor = background;
      }
    }
    get element() {
      return this._element;
    }
    set label(value) {
      if (this._label === value) {
        return;
      }
      if (isMarkdownString(this._label) && isMarkdownString(value) && markdownStringEqual(this._label, value)) {
        return;
      }
      this._element.classList.add("monaco-text-button");
      const labelElement = this.options.supportShortLabel ? this._labelElement : this._element;
      if (isMarkdownString(value)) {
        const rendered = renderMarkdown$1(value, void 0, document.createElement("span"));
        rendered.dispose();
        const root = rendered.element.querySelector("p")?.innerHTML;
        if (root) {
          safeSetInnerHtml(labelElement, root, buttonSanitizerConfig);
        } else {
          reset(labelElement);
        }
      } else {
        if (this.options.supportIcons) {
          reset(labelElement, ...this.getContentElements(value));
        } else {
          labelElement.textContent = value;
        }
      }
      let title = "";
      if (typeof this.options.title === "string") {
        title = this.options.title;
      } else if (this.options.title) {
        title = renderAsPlaintext(value);
      }
      this.setTitle(title);
      this._setAriaLabel();
      this._label = value;
    }
    get label() {
      return this._label;
    }
    _setAriaLabel() {
      if (typeof this.options.ariaLabel === "string") {
        this._element.setAttribute("aria-label", this.options.ariaLabel);
      } else if (typeof this.options.title === "string") {
        this._element.setAttribute("aria-label", this.options.title);
      }
    }
    set icon(icon) {
      this._setAriaLabel();
      const oldIcons = Array.from(this._element.classList).filter((item) => item.startsWith("codicon-"));
      this._element.classList.remove(...oldIcons);
      this._element.classList.add(...ThemeIcon.asClassNameArray(icon));
    }
    set enabled(value) {
      if (value) {
        this._element.classList.remove("disabled");
        this._element.setAttribute("aria-disabled", String(false));
        this._element.tabIndex = 0;
      } else {
        this._element.classList.add("disabled");
        this._element.setAttribute("aria-disabled", String(true));
      }
    }
    get enabled() {
      return !this._element.classList.contains("disabled");
    }
    setTitle(title) {
      if (!this._hover && title !== "") {
        this._hover = this._register(getBaseLayerHoverDelegate().setupManagedHover(this.options.hoverDelegate ?? getDefaultHoverDelegate("element"), this._element, title));
      } else if (this._hover) {
        this._hover.update(title);
      }
    }
  }
  function exceptionToErrorMessage(exception, verbose) {
    if (verbose && (exception.stack || exception.stacktrace)) {
      return localize(29, "{0}: {1}", detectSystemErrorMessage(exception), stackToString(exception.stack) || stackToString(exception.stacktrace));
    }
    return detectSystemErrorMessage(exception);
  }
  function stackToString(stack) {
    if (Array.isArray(stack)) {
      return stack.join("\n");
    }
    return stack;
  }
  function detectSystemErrorMessage(exception) {
    if (exception.code === "ERR_UNC_HOST_NOT_ALLOWED") {
      return `${exception.message}. Please update the 'security.allowedUNCHosts' setting if you want to allow this host.`;
    }
    if (typeof exception.code === "string" && typeof exception.errno === "number" && typeof exception.syscall === "string") {
      return localize(30, "A system error occurred ({0})", exception.message);
    }
    return exception.message || localize(31, "An unknown error occurred. Please consult the log for more details.");
  }
  function toErrorMessage(error = null, verbose = false) {
    if (!error) {
      return localize(32, "An unknown error occurred. Please consult the log for more details.");
    }
    if (Array.isArray(error)) {
      const errors = coalesce(error);
      const msg = toErrorMessage(errors[0], verbose);
      if (errors.length > 1) {
        return localize(33, "{0} ({1} errors in total)", msg, errors.length);
      }
      return msg;
    }
    if (isString$1(error)) {
      return error;
    }
    if (error.detail) {
      const detail = error.detail;
      if (detail.error) {
        return exceptionToErrorMessage(detail.error, verbose);
      }
      if (detail.exception) {
        return exceptionToErrorMessage(detail.exception, verbose);
      }
    }
    if (error.stack) {
      return exceptionToErrorMessage(error, verbose);
    }
    if (error.message) {
      return error.message;
    }
    return localize(34, "An unknown error occurred. Please consult the log for more details.");
  }
  const $$j = $$l;
  const unthemedKeybindingLabelOptions = {
    keybindingLabelBackground: void 0,
    keybindingLabelForeground: void 0,
    keybindingLabelBorder: void 0,
    keybindingLabelBottomBorder: void 0,
    keybindingLabelShadow: void 0
  };
  class KeybindingLabel extends Disposable {
    constructor(container, os, options) {
      super();
      this.os = os;
      this.keyElements = /* @__PURE__ */ new Set();
      this.options = options || /* @__PURE__ */ Object.create(null);
      const labelForeground = this.options.keybindingLabelForeground;
      this.domNode = append$2(container, $$j(".monaco-keybinding"));
      if (labelForeground) {
        this.domNode.style.color = labelForeground;
      }
      this.hover = this._register(getBaseLayerHoverDelegate().setupManagedHover(getDefaultHoverDelegate("mouse"), this.domNode, ""));
      this.didEverRender = false;
      container.appendChild(this.domNode);
    }
    set(keybinding, matches) {
      if (this.didEverRender && this.keybinding === keybinding && KeybindingLabel.areSame(this.matches, matches)) {
        return;
      }
      this.keybinding = keybinding;
      this.matches = matches;
      this.render();
    }
    render() {
      this.clear();
      if (this.keybinding) {
        const chords = this.keybinding.getChords();
        if (chords[0]) {
          this.renderChord(this.domNode, chords[0], this.matches ? this.matches.firstPart : null);
        }
        for (let i2 = 1; i2 < chords.length; i2++) {
          append$2(this.domNode, $$j("span.monaco-keybinding-key-chord-separator", void 0, " "));
          this.renderChord(this.domNode, chords[i2], this.matches ? this.matches.chordPart : null);
        }
        const title = this.options.disableTitle ?? false ? void 0 : this.keybinding.getAriaLabel() || void 0;
        this.hover.update(title);
        this.domNode.setAttribute("aria-label", title || "");
      } else if (this.options && this.options.renderUnboundKeybindings) {
        this.renderUnbound(this.domNode);
      }
      this.didEverRender = true;
    }
    clear() {
      clearNode(this.domNode);
      this.keyElements.clear();
    }
    renderChord(parent, chord, match2) {
      const modifierLabels = UILabelProvider.modifierLabels[this.os];
      if (chord.ctrlKey) {
        this.renderKey(parent, modifierLabels.ctrlKey, Boolean(match2?.ctrlKey), modifierLabels.separator);
      }
      if (chord.shiftKey) {
        this.renderKey(parent, modifierLabels.shiftKey, Boolean(match2?.shiftKey), modifierLabels.separator);
      }
      if (chord.altKey) {
        this.renderKey(parent, modifierLabels.altKey, Boolean(match2?.altKey), modifierLabels.separator);
      }
      if (chord.metaKey) {
        this.renderKey(parent, modifierLabels.metaKey, Boolean(match2?.metaKey), modifierLabels.separator);
      }
      const keyLabel = chord.keyLabel;
      if (keyLabel) {
        this.renderKey(parent, keyLabel, Boolean(match2?.keyCode), "");
      }
    }
    renderKey(parent, label, highlight, separator2) {
      append$2(parent, this.createKeyElement(label, highlight ? ".highlight" : ""));
      if (separator2) {
        append$2(parent, $$j("span.monaco-keybinding-key-separator", void 0, separator2));
      }
    }
    renderUnbound(parent) {
      append$2(parent, this.createKeyElement(localize(15, "Unbound")));
    }
    createKeyElement(label, extraClass = "") {
      const keyElement = $$j("span.monaco-keybinding-key" + extraClass, void 0, label);
      this.keyElements.add(keyElement);
      if (this.options.keybindingLabelBackground) {
        keyElement.style.backgroundColor = this.options.keybindingLabelBackground;
      }
      if (this.options.keybindingLabelBorder) {
        keyElement.style.borderColor = this.options.keybindingLabelBorder;
      }
      if (this.options.keybindingLabelBottomBorder) {
        keyElement.style.borderBottomColor = this.options.keybindingLabelBottomBorder;
      }
      if (this.options.keybindingLabelShadow) {
        keyElement.style.boxShadow = `inset 0 -1px 0 ${this.options.keybindingLabelShadow}`;
      }
      return keyElement;
    }
    static areSame(a, b) {
      if (a === b || !a && !b) {
        return true;
      }
      return !!a && !!b && equals(a.firstPart, b.firstPart) && equals(a.chordPart, b.chordPart);
    }
  }
  const ILayoutService = createDecorator("layoutService");
  var __decorate$2n = 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$2l = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  const acceptSelectedActionCommand = "acceptSelectedCodeAction";
  const previewSelectedActionCommand = "previewSelectedCodeAction";
  class HeaderRenderer {
    get templateId() {
      return "header";
    }
    renderTemplate(container) {
      container.classList.add("group-header");
      const text2 = document.createElement("span");
      container.append(text2);
      return { container, text: text2 };
    }
    renderElement(element, _index, templateData) {
      templateData.text.textContent = element.group?.title ?? element.label ?? "";
    }
    disposeTemplate(_templateData) {
    }
  }
  class SeparatorRenderer {
    get templateId() {
      return "separator";
    }
    renderTemplate(container) {
      container.classList.add("separator");
      const text2 = document.createElement("span");
      container.append(text2);
      return { container, text: text2 };
    }
    renderElement(element, _index, templateData) {
      templateData.text.textContent = element.label ?? "";
    }
    disposeTemplate(_templateData) {
    }
  }
  let ActionItemRenderer = class ActionItemRenderer {
    get templateId() {
      return "action";
    }
    constructor(_supportsPreview, _keybindingService) {
      this._supportsPreview = _supportsPreview;
      this._keybindingService = _keybindingService;
    }
    renderTemplate(container) {
      container.classList.add(this.templateId);
      const icon = document.createElement("div");
      icon.className = "icon";
      container.append(icon);
      const text2 = document.createElement("span");
      text2.className = "title";
      container.append(text2);
      const description = document.createElement("span");
      description.className = "description";
      container.append(description);
      const keybinding = new KeybindingLabel(container, OS);
      return { container, icon, text: text2, description, keybinding };
    }
    renderElement(element, _index, data) {
      if (element.group?.icon) {
        data.icon.className = ThemeIcon.asClassName(element.group.icon);
        if (element.group.icon.color) {
          data.icon.style.color = asCssVariable(element.group.icon.color.id);
        }
      } else {
        data.icon.className = ThemeIcon.asClassName(Codicon.lightBulb);
        data.icon.style.color = "var(--vscode-editorLightBulb-foreground)";
      }
      if (!element.item || !element.label) {
        return;
      }
      setVisibility(!element.hideIcon, data.icon);
      data.text.textContent = stripNewlines(element.label);
      if (element.keybinding) {
        data.description.textContent = element.keybinding.getLabel();
        data.description.style.display = "inline";
        data.description.style.letterSpacing = "0.5px";
      } else if (element.description) {
        data.description.textContent = stripNewlines(element.description);
        data.description.style.display = "inline";
      } else {
        data.description.textContent = "";
        data.description.style.display = "none";
      }
      const actionTitle = this._keybindingService.lookupKeybinding(acceptSelectedActionCommand)?.getLabel();
      const previewTitle = this._keybindingService.lookupKeybinding(previewSelectedActionCommand)?.getLabel();
      data.container.classList.toggle("option-disabled", element.disabled);
      if (element.tooltip) {
        data.container.title = element.tooltip;
      } else if (element.disabled) {
        data.container.title = element.label;
      } else if (actionTitle && previewTitle) {
        if (this._supportsPreview && element.canPreview) {
          data.container.title = localize(1653, "{0} to Apply, {1} to Preview", actionTitle, previewTitle);
        } else {
          data.container.title = localize(1654, "{0} to Apply", actionTitle);
        }
      } else {
        data.container.title = "";
      }
    }
    disposeTemplate(templateData) {
      templateData.keybinding.dispose();
    }
  };
  ActionItemRenderer = __decorate$2n([
    __param$2l(1, IKeybindingService)
  ], ActionItemRenderer);
  class AcceptSelectedEvent extends UIEvent {
    constructor() {
      super("acceptSelectedAction");
    }
  }
  class PreviewSelectedEvent extends UIEvent {
    constructor() {
      super("previewSelectedAction");
    }
  }
  function getKeyboardNavigationLabel(item) {
    if (item.kind === "action") {
      return item.label;
    }
    return void 0;
  }
  let ActionList = class ActionList extends Disposable {
    constructor(user, preview, items, _delegate, accessibilityProvider, _contextViewService, _keybindingService, _layoutService) {
      super();
      this._delegate = _delegate;
      this._contextViewService = _contextViewService;
      this._keybindingService = _keybindingService;
      this._layoutService = _layoutService;
      this._actionLineHeight = 28;
      this._headerLineHeight = 28;
      this._separatorLineHeight = 8;
      this.cts = this._register(new CancellationTokenSource$1());
      this.domNode = document.createElement("div");
      this.domNode.classList.add("actionList");
      const virtualDelegate = {
        getHeight: (element) => {
          switch (element.kind) {
            case "header":
              return this._headerLineHeight;
            case "separator":
              return this._separatorLineHeight;
            default:
              return this._actionLineHeight;
          }
        },
        getTemplateId: (element) => element.kind
      };
      this._list = this._register(new List(user, this.domNode, virtualDelegate, [
        new ActionItemRenderer(preview, this._keybindingService),
        new HeaderRenderer(),
        new SeparatorRenderer()
      ], {
        keyboardSupport: false,
        typeNavigationEnabled: true,
        keyboardNavigationLabelProvider: { getKeyboardNavigationLabel },
        accessibilityProvider: {
          getAriaLabel: (element) => {
            if (element.kind === "action") {
              let label = element.label ? stripNewlines(element?.label) : "";
              if (element.description) {
                label = label + ", " + stripNewlines(element.description);
              }
              if (element.disabled) {
                label = localize(1655, "{0}, Disabled Reason: {1}", label, element.disabled);
              }
              return label;
            }
            return null;
          },
          getWidgetAriaLabel: () => localize(1656, "Action Widget"),
          getRole: (e) => {
            switch (e.kind) {
              case "action":
                return "option";
              case "separator":
                return "separator";
              default:
                return "separator";
            }
          },
          getWidgetRole: () => "listbox",
          ...accessibilityProvider
        }
      }));
      this._list.style(defaultListStyles);
      this._register(this._list.onMouseClick((e) => this.onListClick(e)));
      this._register(this._list.onMouseOver((e) => this.onListHover(e)));
      this._register(this._list.onDidChangeFocus(() => this.onFocus()));
      this._register(this._list.onDidChangeSelection((e) => this.onListSelection(e)));
      this._allMenuItems = items;
      this._list.splice(0, this._list.length, this._allMenuItems);
      if (this._list.length) {
        this.focusNext();
      }
    }
    focusCondition(element) {
      return !element.disabled && element.kind === "action";
    }
    hide(didCancel) {
      this._delegate.onHide(didCancel);
      this.cts.cancel();
      this._contextViewService.hideContextView();
    }
    layout(minWidth) {
      const numHeaders = this._allMenuItems.filter((item) => item.kind === "header").length;
      const numSeparators = this._allMenuItems.filter((item) => item.kind === "separator").length;
      const itemsHeight = this._allMenuItems.length * this._actionLineHeight;
      const heightWithHeaders = itemsHeight + numHeaders * this._headerLineHeight - numHeaders * this._actionLineHeight;
      const heightWithSeparators = heightWithHeaders + numSeparators * this._separatorLineHeight - numSeparators * this._actionLineHeight;
      this._list.layout(heightWithSeparators);
      let maxWidth = minWidth;
      if (this._allMenuItems.length >= 50) {
        maxWidth = 380;
      } else {
        const itemWidths = this._allMenuItems.map((_, index) => {
          const element = this.domNode.ownerDocument.getElementById(this._list.getElementID(index));
          if (element) {
            element.style.width = "auto";
            const width2 = element.getBoundingClientRect().width;
            element.style.width = "";
            return width2;
          }
          return 0;
        });
        maxWidth = Math.max(...itemWidths, minWidth);
      }
      const maxVhPrecentage = 0.7;
      const height = Math.min(heightWithSeparators, this._layoutService.getContainer(getWindow(this.domNode)).clientHeight * maxVhPrecentage);
      this._list.layout(height, maxWidth);
      this.domNode.style.height = `${height}px`;
      this._list.domFocus();
      return maxWidth;
    }
    focusPrevious() {
      this._list.focusPrevious(1, true, void 0, this.focusCondition);
    }
    focusNext() {
      this._list.focusNext(1, true, void 0, this.focusCondition);
    }
    acceptSelected(preview) {
      const focused = this._list.getFocus();
      if (focused.length === 0) {
        return;
      }
      const focusIndex = focused[0];
      const element = this._list.element(focusIndex);
      if (!this.focusCondition(element)) {
        return;
      }
      const event = preview ? new PreviewSelectedEvent() : new AcceptSelectedEvent();
      this._list.setSelection([focusIndex], event);
    }
    onListSelection(e) {
      if (!e.elements.length) {
        return;
      }
      const element = e.elements[0];
      if (element.item && this.focusCondition(element)) {
        this._delegate.onSelect(element.item, e.browserEvent instanceof PreviewSelectedEvent);
      } else {
        this._list.setSelection([]);
      }
    }
    onFocus() {
      const focused = this._list.getFocus();
      if (focused.length === 0) {
        return;
      }
      const focusIndex = focused[0];
      const element = this._list.element(focusIndex);
      this._delegate.onFocus?.(element.item);
    }
    async onListHover(e) {
      const element = e.element;
      if (element && element.item && this.focusCondition(element)) {
        if (this._delegate.onHover && !element.disabled && element.kind === "action") {
          const result = await this._delegate.onHover(element.item, this.cts.token);
          element.canPreview = result ? result.canPreview : void 0;
        }
        if (e.index) {
          this._list.splice(e.index, 1, [element]);
        }
      }
      this._list.setFocus(typeof e.index === "number" ? [e.index] : []);
    }
    onListClick(e) {
      if (e.element && this.focusCondition(e.element)) {
        this._list.setFocus([]);
      }
    }
  };
  ActionList = __decorate$2n([
    __param$2l(5, IContextViewService),
    __param$2l(6, IKeybindingService),
    __param$2l(7, ILayoutService)
  ], ActionList);
  function stripNewlines(str) {
    return str.replace(/\r\n|\r|\n/g, " ");
  }
  var __decorate$2m = 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$2k = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  registerColor("actionBar.toggledBackground", inputActiveOptionBackground, localize(1657, "Background color for toggled action items in action bar."));
  const ActionWidgetContextKeys = {
    Visible: new RawContextKey("codeActionMenuVisible", false, localize(1658, "Whether the action widget list is visible"))
  };
  const IActionWidgetService = createDecorator("actionWidgetService");
  let ActionWidgetService = class ActionWidgetService extends Disposable {
    get isVisible() {
      return ActionWidgetContextKeys.Visible.getValue(this._contextKeyService) || false;
    }
    constructor(_contextViewService, _contextKeyService, _instantiationService) {
      super();
      this._contextViewService = _contextViewService;
      this._contextKeyService = _contextKeyService;
      this._instantiationService = _instantiationService;
      this._list = this._register(new MutableDisposable());
    }
    show(user, supportsPreview, items, delegate, anchor, container, actionBarActions, accessibilityProvider) {
      const visibleContext = ActionWidgetContextKeys.Visible.bindTo(this._contextKeyService);
      const list2 = this._instantiationService.createInstance(ActionList, user, supportsPreview, items, delegate, accessibilityProvider);
      this._contextViewService.showContextView({
        getAnchor: () => anchor,
        render: (container2) => {
          visibleContext.set(true);
          return this._renderWidget(container2, list2, actionBarActions ?? []);
        },
        onHide: (didCancel) => {
          visibleContext.reset();
          this._onWidgetClosed(didCancel);
        }
      }, container, false);
    }
    acceptSelected(preview) {
      this._list.value?.acceptSelected(preview);
    }
    focusPrevious() {
      this._list?.value?.focusPrevious();
    }
    focusNext() {
      this._list?.value?.focusNext();
    }
    hide(didCancel) {
      this._list.value?.hide(didCancel);
      this._list.clear();
    }
    _renderWidget(element, list2, actionBarActions) {
      const widget = document.createElement("div");
      widget.classList.add("action-widget");
      element.appendChild(widget);
      this._list.value = list2;
      if (this._list.value) {
        widget.appendChild(this._list.value.domNode);
      } else {
        throw new Error("List has no value");
      }
      const renderDisposables = new DisposableStore();
      const menuBlock = document.createElement("div");
      const block2 = element.appendChild(menuBlock);
      block2.classList.add("context-view-block");
      renderDisposables.add(addDisposableListener(block2, EventType$1.MOUSE_DOWN, (e) => e.stopPropagation()));
      const pointerBlockDiv = document.createElement("div");
      const pointerBlock = element.appendChild(pointerBlockDiv);
      pointerBlock.classList.add("context-view-pointerBlock");
      renderDisposables.add(addDisposableListener(pointerBlock, EventType$1.POINTER_MOVE, () => pointerBlock.remove()));
      renderDisposables.add(addDisposableListener(pointerBlock, EventType$1.MOUSE_DOWN, () => pointerBlock.remove()));
      let actionBarWidth = 0;
      if (actionBarActions.length) {
        const actionBar2 = this._createActionBar(".action-widget-action-bar", actionBarActions);
        if (actionBar2) {
          widget.appendChild(actionBar2.getContainer().parentElement);
          renderDisposables.add(actionBar2);
          actionBarWidth = actionBar2.getContainer().offsetWidth;
        }
      }
      const width2 = this._list.value?.layout(actionBarWidth);
      widget.style.width = `${width2}px`;
      const focusTracker = renderDisposables.add(trackFocus(element));
      renderDisposables.add(focusTracker.onDidBlur(() => this.hide(true)));
      return renderDisposables;
    }
    _createActionBar(className2, actions) {
      if (!actions.length) {
        return void 0;
      }
      const container = $$l(className2);
      const actionBar2 = new ActionBar(container);
      actionBar2.push(actions, { icon: false, label: true });
      return actionBar2;
    }
    _onWidgetClosed(didCancel) {
      this._list.value?.hide(didCancel);
    }
  };
  ActionWidgetService = __decorate$2m([
    __param$2k(0, IContextViewService),
    __param$2k(1, IContextKeyService),
    __param$2k(2, IInstantiationService)
  ], ActionWidgetService);
  registerSingleton(
    IActionWidgetService,
    ActionWidgetService,
    1
    /* InstantiationType.Delayed */
  );
  const weight$3 = 100 + 1e3;
  registerAction2(class extends Action2 {
    constructor() {
      super({
        id: "hideCodeActionWidget",
        title: localize2(1659, "Hide action widget"),
        precondition: ActionWidgetContextKeys.Visible,
        keybinding: {
          weight: weight$3,
          primary: 9,
          secondary: [
            1024 | 9
            /* KeyCode.Escape */
          ]
        }
      });
    }
    run(accessor) {
      accessor.get(IActionWidgetService).hide(true);
    }
  });
  registerAction2(class extends Action2 {
    constructor() {
      super({
        id: "selectPrevCodeAction",
        title: localize2(1660, "Select previous action"),
        precondition: ActionWidgetContextKeys.Visible,
        keybinding: {
          weight: weight$3,
          primary: 16,
          secondary: [
            2048 | 16
            /* KeyCode.UpArrow */
          ],
          mac: { primary: 16, secondary: [
            2048 | 16,
            256 | 46
            /* KeyCode.KeyP */
          ] }
        }
      });
    }
    run(accessor) {
      const widgetService = accessor.get(IActionWidgetService);
      if (widgetService instanceof ActionWidgetService) {
        widgetService.focusPrevious();
      }
    }
  });
  registerAction2(class extends Action2 {
    constructor() {
      super({
        id: "selectNextCodeAction",
        title: localize2(1661, "Select next action"),
        precondition: ActionWidgetContextKeys.Visible,
        keybinding: {
          weight: weight$3,
          primary: 18,
          secondary: [
            2048 | 18
            /* KeyCode.DownArrow */
          ],
          mac: { primary: 18, secondary: [
            2048 | 18,
            256 | 44
            /* KeyCode.KeyN */
          ] }
        }
      });
    }
    run(accessor) {
      const widgetService = accessor.get(IActionWidgetService);
      if (widgetService instanceof ActionWidgetService) {
        widgetService.focusNext();
      }
    }
  });
  registerAction2(class extends Action2 {
    constructor() {
      super({
        id: acceptSelectedActionCommand,
        title: localize2(1662, "Accept selected action"),
        precondition: ActionWidgetContextKeys.Visible,
        keybinding: {
          weight: weight$3,
          primary: 3,
          secondary: [
            2048 | 89
            /* KeyCode.Period */
          ]
        }
      });
    }
    run(accessor) {
      const widgetService = accessor.get(IActionWidgetService);
      if (widgetService instanceof ActionWidgetService) {
        widgetService.acceptSelected();
      }
    }
  });
  registerAction2(class extends Action2 {
    constructor() {
      super({
        id: previewSelectedActionCommand,
        title: localize2(1663, "Preview selected action"),
        precondition: ActionWidgetContextKeys.Visible,
        keybinding: {
          weight: weight$3,
          primary: 2048 | 3
        }
      });
    }
    run(accessor) {
      const widgetService = accessor.get(IActionWidgetService);
      if (widgetService instanceof ActionWidgetService) {
        widgetService.acceptSelected(true);
      }
    }
  });
  var __decorate$2l = 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$2j = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  var PostEditWidget_1;
  let PostEditWidget = (_r = class extends Disposable {
    constructor(typeId, editor2, visibleContext, showCommand, range2, edits, onSelectNewEdit, additionalActions, contextKeyService, _keybindingService, _actionWidgetService) {
      super();
      this.typeId = typeId;
      this.editor = editor2;
      this.showCommand = showCommand;
      this.range = range2;
      this.edits = edits;
      this.onSelectNewEdit = onSelectNewEdit;
      this.additionalActions = additionalActions;
      this._keybindingService = _keybindingService;
      this._actionWidgetService = _actionWidgetService;
      this.allowEditorOverflow = true;
      this.suppressMouseDown = true;
      this.create();
      this.visibleContext = visibleContext.bindTo(contextKeyService);
      this.visibleContext.set(true);
      this._register(toDisposable(() => this.visibleContext.reset()));
      this.editor.addContentWidget(this);
      this.editor.layoutContentWidget(this);
      this._register(toDisposable((() => this.editor.removeContentWidget(this))));
      this._register(this.editor.onDidChangeCursorPosition((e) => {
        this.dispose();
      }));
      this._register(Event.runAndSubscribe(_keybindingService.onDidUpdateKeybindings, () => {
        this._updateButtonTitle();
      }));
    }
    _updateButtonTitle() {
      const binding = this._keybindingService.lookupKeybinding(this.showCommand.id)?.getLabel();
      this.button.element.title = this.showCommand.label + (binding ? ` (${binding})` : "");
    }
    create() {
      this.domNode = $$l(".post-edit-widget");
      this.button = this._register(new Button(this.domNode, {
        supportIcons: true
      }));
      this.button.label = "$(insert)";
      this._register(addDisposableListener(this.domNode, EventType$1.CLICK, () => this.showSelector()));
    }
    getId() {
      return PostEditWidget_1.baseId + "." + this.typeId;
    }
    getDomNode() {
      return this.domNode;
    }
    getPosition() {
      return {
        position: this.range.getEndPosition(),
        preference: [
          2
          /* ContentWidgetPositionPreference.BELOW */
        ]
      };
    }
    showSelector() {
      const pos = getDomNodePagePosition(this.button.element);
      const anchor = { x: pos.left + pos.width, y: pos.top + pos.height };
      this._actionWidgetService.show("postEditWidget", false, this.edits.allEdits.map((edit2, i2) => {
        return {
          kind: "action",
          item: edit2,
          label: edit2.title,
          disabled: false,
          canPreview: false,
          group: { title: "", icon: ThemeIcon.fromId(i2 === this.edits.activeEditIndex ? Codicon.check.id : Codicon.blank.id) }
        };
      }), {
        onHide: () => {
          this.editor.focus();
        },
        onSelect: (item) => {
          this._actionWidgetService.hide(false);
          const i2 = this.edits.allEdits.findIndex((edit2) => edit2 === item);
          if (i2 !== this.edits.activeEditIndex) {
            return this.onSelectNewEdit(i2);
          }
        }
      }, anchor, this.editor.getDomNode() ?? void 0, this.additionalActions);
    }
  }, PostEditWidget_1 = _r, _r.baseId = "editor.widget.postEditWidget", _r);
  PostEditWidget = PostEditWidget_1 = __decorate$2l([
    __param$2j(8, IContextKeyService),
    __param$2j(9, IKeybindingService),
    __param$2j(10, IActionWidgetService)
  ], PostEditWidget);
  let PostEditWidgetManager = class PostEditWidgetManager extends Disposable {
    constructor(_id, _editor, _visibleContext, _showCommand, _getAdditionalActions, _instantiationService, _bulkEditService, _notificationService) {
      super();
      this._id = _id;
      this._editor = _editor;
      this._visibleContext = _visibleContext;
      this._showCommand = _showCommand;
      this._getAdditionalActions = _getAdditionalActions;
      this._instantiationService = _instantiationService;
      this._bulkEditService = _bulkEditService;
      this._notificationService = _notificationService;
      this._currentWidget = this._register(new MutableDisposable());
      this._register(Event.any(_editor.onDidChangeModel, _editor.onDidChangeModelContent)(() => this.clear()));
    }
    async applyEditAndShowIfNeeded(ranges, edits, canShowWidget, resolve2, token) {
      if (!ranges.length || !this._editor.hasModel()) {
        return;
      }
      const model = this._editor.getModel();
      const edit2 = edits.allEdits.at(edits.activeEditIndex);
      if (!edit2) {
        return;
      }
      const onDidSelectEdit = async (newEditIndex) => {
        const model2 = this._editor.getModel();
        if (!model2) {
          return;
        }
        await model2.undo();
        this.applyEditAndShowIfNeeded(ranges, { activeEditIndex: newEditIndex, allEdits: edits.allEdits }, canShowWidget, resolve2, token);
      };
      const handleError = (e, message) => {
        if (isCancellationError(e)) {
          return;
        }
        this._notificationService.error(message);
        if (canShowWidget) {
          this.show(ranges[0], edits, onDidSelectEdit);
        }
      };
      const editorStateCts = new EditorStateCancellationTokenSource(this._editor, 1 | 2, void 0, token);
      let resolvedEdit;
      try {
        resolvedEdit = await raceCancellationError(resolve2(edit2, editorStateCts.token), editorStateCts.token);
      } catch (e) {
        return handleError(e, localize(937, "Error resolving edit '{0}':\n{1}", edit2.title, toErrorMessage(e)));
      } finally {
        editorStateCts.dispose();
      }
      if (token.isCancellationRequested) {
        return;
      }
      const combinedWorkspaceEdit = createCombinedWorkspaceEdit(model.uri, ranges, resolvedEdit);
      const primaryRange = ranges[0];
      const editTrackingDecoration = model.deltaDecorations([], [{
        range: primaryRange,
        options: {
          description: "paste-line-suffix",
          stickiness: 0
          /* TrackedRangeStickiness.AlwaysGrowsWhenTypingAtEdges */
        }
      }]);
      this._editor.focus();
      let editResult;
      let editRange;
      try {
        editResult = await this._bulkEditService.apply(combinedWorkspaceEdit, { editor: this._editor, token });
        editRange = model.getDecorationRange(editTrackingDecoration[0]);
      } catch (e) {
        return handleError(e, localize(938, "Error applying edit '{0}':\n{1}", edit2.title, toErrorMessage(e)));
      } finally {
        model.deltaDecorations(editTrackingDecoration, []);
      }
      if (token.isCancellationRequested) {
        return;
      }
      if (canShowWidget && editResult.isApplied && edits.allEdits.length > 1) {
        this.show(editRange ?? primaryRange, edits, onDidSelectEdit);
      }
    }
    show(range2, edits, onDidSelectEdit) {
      this.clear();
      if (this._editor.hasModel()) {
        this._currentWidget.value = this._instantiationService.createInstance(PostEditWidget, this._id, this._editor, this._visibleContext, this._showCommand, range2, edits, onDidSelectEdit, this._getAdditionalActions());
      }
    }
    clear() {
      this._currentWidget.clear();
    }
    tryShowSelector() {
      this._currentWidget.value?.showSelector();
    }
  };
  PostEditWidgetManager = __decorate$2l([
    __param$2j(5, IInstantiationService),
    __param$2j(6, IBulkEditService),
    __param$2j(7, INotificationService)
  ], PostEditWidgetManager);
  var __decorate$2k = 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$2i = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  var CopyPasteController_1;
  const changePasteTypeCommandId = "editor.changePasteType";
  const pasteAsPreferenceConfig = "editor.pasteAs.preferences";
  const pasteWidgetVisibleCtx = new RawContextKey("pasteWidgetVisible", false, localize(917, "Whether the paste widget is showing"));
  const vscodeClipboardMime = "application/vnd.code.copymetadata";
  let CopyPasteController = (_s = class extends Disposable {
    static get(editor2) {
      return editor2.getContribution(CopyPasteController_1.ID);
    }
    constructor(editor2, instantiationService, _logService, _bulkEditService, _clipboardService, _commandService, _configService, _languageFeaturesService, _quickInputService, _progressService) {
      super();
      this._logService = _logService;
      this._bulkEditService = _bulkEditService;
      this._clipboardService = _clipboardService;
      this._commandService = _commandService;
      this._configService = _configService;
      this._languageFeaturesService = _languageFeaturesService;
      this._quickInputService = _quickInputService;
      this._progressService = _progressService;
      this._editor = editor2;
      const container = editor2.getContainerDomNode();
      this._register(addDisposableListener(container, "copy", (e) => this.handleCopy(e)));
      this._register(addDisposableListener(container, "cut", (e) => this.handleCopy(e)));
      this._register(addDisposableListener(container, "paste", (e) => this.handlePaste(e), true));
      this._pasteProgressManager = this._register(new InlineProgressManager("pasteIntoEditor", editor2, instantiationService));
      this._postPasteWidgetManager = this._register(instantiationService.createInstance(PostEditWidgetManager, "pasteIntoEditor", editor2, pasteWidgetVisibleCtx, { id: changePasteTypeCommandId, label: localize(918, "Show paste options...") }, () => CopyPasteController_1._configureDefaultAction ? [CopyPasteController_1._configureDefaultAction] : []));
    }
    changePasteType() {
      this._postPasteWidgetManager.tryShowSelector();
    }
    async pasteAs(preferred) {
      this._logService.trace("CopyPasteController.pasteAs");
      this._editor.focus();
      try {
        this._logService.trace("Before calling editor.action.clipboardPasteAction");
        this._pasteAsActionContext = { preferred };
        await this._commandService.executeCommand("editor.action.clipboardPasteAction");
      } finally {
        this._pasteAsActionContext = void 0;
      }
    }
    clearWidgets() {
      this._postPasteWidgetManager.clear();
    }
    isPasteAsEnabled() {
      return this._editor.getOption(
        97
        /* EditorOption.pasteAs */
      ).enabled;
    }
    async finishedPaste() {
      await this._currentPasteOperation;
    }
    handleCopy(e) {
      let id = null;
      if (e.clipboardData) {
        const [text2, metadata] = ClipboardEventUtils.getTextData(e.clipboardData);
        const storedMetadata = metadata || InMemoryClipboardMetadataManager.INSTANCE.get(text2);
        id = storedMetadata?.id || null;
        this._logService.trace("CopyPasteController#handleCopy for id : ", id, " with text.length : ", text2.length);
      } else {
        this._logService.trace("CopyPasteController#handleCopy");
      }
      if (!this._editor.hasTextFocus()) {
        return;
      }
      this._clipboardService.clearInternalState?.();
      if (!e.clipboardData || !this.isPasteAsEnabled()) {
        return;
      }
      const model = this._editor.getModel();
      const selections = this._editor.getSelections();
      if (!model || !selections?.length) {
        return;
      }
      const enableEmptySelectionClipboard = this._editor.getOption(
        45
        /* EditorOption.emptySelectionClipboard */
      );
      let ranges = selections;
      const wasFromEmptySelection = selections.length === 1 && selections[0].isEmpty();
      if (wasFromEmptySelection) {
        if (!enableEmptySelectionClipboard) {
          return;
        }
        ranges = [new Range$2(ranges[0].startLineNumber, 1, ranges[0].startLineNumber, 1 + model.getLineLength(ranges[0].startLineNumber))];
      }
      const toCopy = this._editor._getViewModel()?.getPlainTextToCopy(selections, enableEmptySelectionClipboard, isWindows);
      const multicursorText = Array.isArray(toCopy) ? toCopy : null;
      const defaultPastePayload = {
        multicursorText,
        pasteOnNewLine: wasFromEmptySelection,
        mode: null
      };
      const providers = this._languageFeaturesService.documentPasteEditProvider.ordered(model).filter((x) => !!x.prepareDocumentPaste);
      if (!providers.length) {
        this.setCopyMetadata(e.clipboardData, { defaultPastePayload });
        return;
      }
      const dataTransfer = toVSDataTransfer(e.clipboardData);
      const providerCopyMimeTypes = providers.flatMap((x) => x.copyMimeTypes ?? []);
      const handle = id ?? generateUuid();
      this.setCopyMetadata(e.clipboardData, {
        id: handle,
        providerCopyMimeTypes,
        defaultPastePayload
      });
      const operations = providers.map((provider) => {
        return {
          providerMimeTypes: provider.copyMimeTypes,
          operation: createCancelablePromise((token) => provider.prepareDocumentPaste(model, ranges, dataTransfer, token).catch((err) => {
            console.error(err);
            return void 0;
          }))
        };
      });
      CopyPasteController_1._currentCopyOperation?.operations.forEach((entry) => entry.operation.cancel());
      CopyPasteController_1._currentCopyOperation = { handle, operations };
    }
    async handlePaste(e) {
      if (e.clipboardData) {
        const [text2, metadata2] = ClipboardEventUtils.getTextData(e.clipboardData);
        const metadataComputed = metadata2 || InMemoryClipboardMetadataManager.INSTANCE.get(text2);
        this._logService.trace("CopyPasteController#handlePaste for id : ", metadataComputed?.id);
      } else {
        this._logService.trace("CopyPasteController#handlePaste");
      }
      if (!e.clipboardData || !this._editor.hasTextFocus()) {
        return;
      }
      MessageController.get(this._editor)?.closeMessage();
      this._currentPasteOperation?.cancel();
      this._currentPasteOperation = void 0;
      const model = this._editor.getModel();
      const selections = this._editor.getSelections();
      if (!selections?.length || !model) {
        return;
      }
      if (this._editor.getOption(
        104
        /* EditorOption.readOnly */
      ) || !this.isPasteAsEnabled() && !this._pasteAsActionContext) {
        return;
      }
      const metadata = this.fetchCopyMetadata(e);
      this._logService.trace("CopyPasteController#handlePaste with metadata : ", metadata?.id, " and text.length : ", e.clipboardData.getData("text/plain").length);
      const dataTransfer = toExternalVSDataTransfer(e.clipboardData);
      dataTransfer.delete(vscodeClipboardMime);
      const fileTypes = Array.from(e.clipboardData.files).map((file) => file.type);
      const allPotentialMimeTypes = [
        ...e.clipboardData.types,
        ...fileTypes,
        ...metadata?.providerCopyMimeTypes ?? [],
        // TODO: always adds `uri-list` because this get set if there are resources in the system clipboard.
        // However we can only check the system clipboard async. For this early check, just add it in.
        // We filter providers again once we have the final dataTransfer we will use.
        Mimes.uriList
      ];
      const allProviders = this._languageFeaturesService.documentPasteEditProvider.ordered(model).filter((provider) => {
        const preference = this._pasteAsActionContext?.preferred;
        if (preference) {
          if (!this.providerMatchesPreference(provider, preference)) {
            return false;
          }
        }
        return provider.pasteMimeTypes?.some((type) => matchesMimeType(type, allPotentialMimeTypes));
      });
      if (!allProviders.length) {
        if (this._pasteAsActionContext?.preferred) {
          this.showPasteAsNoEditMessage(selections, this._pasteAsActionContext.preferred);
          e.preventDefault();
          e.stopImmediatePropagation();
        }
        return;
      }
      e.preventDefault();
      e.stopImmediatePropagation();
      if (this._pasteAsActionContext) {
        this.showPasteAsPick(this._pasteAsActionContext.preferred, allProviders, selections, dataTransfer, metadata);
      } else {
        this.doPasteInline(allProviders, selections, dataTransfer, metadata, e);
      }
    }
    showPasteAsNoEditMessage(selections, preference) {
      const kindLabel = "only" in preference ? preference.only.value : "preferences" in preference ? preference.preferences.length ? preference.preferences.map((preference2) => preference2.value).join(", ") : localize(919, "empty") : preference.providerId;
      MessageController.get(this._editor)?.showMessage(localize(920, "No paste edits for '{0}' found", kindLabel), selections[0].getStartPosition());
    }
    doPasteInline(allProviders, selections, dataTransfer, metadata, clipboardEvent) {
      this._logService.trace("CopyPasteController#doPasteInline");
      const editor2 = this._editor;
      if (!editor2.hasModel()) {
        return;
      }
      const editorStateCts = new EditorStateCancellationTokenSource(editor2, 1 | 2, void 0);
      const p = createCancelablePromise(async (pToken) => {
        const editor3 = this._editor;
        if (!editor3.hasModel()) {
          return;
        }
        const model = editor3.getModel();
        const disposables = new DisposableStore();
        const cts = disposables.add(new CancellationTokenSource$1(pToken));
        disposables.add(editorStateCts.token.onCancellationRequested(() => cts.cancel()));
        const token = cts.token;
        try {
          await this.mergeInDataFromCopy(allProviders, dataTransfer, metadata, token);
          if (token.isCancellationRequested) {
            return;
          }
          const supportedProviders = allProviders.filter((provider) => this.isSupportedPasteProvider(provider, dataTransfer));
          if (!supportedProviders.length || supportedProviders.length === 1 && supportedProviders[0] instanceof DefaultTextPasteOrDropEditProvider) {
            return this.applyDefaultPasteHandler(dataTransfer, metadata, token, clipboardEvent);
          }
          const context = {
            triggerKind: DocumentPasteTriggerKind.Automatic
          };
          const editSession = await this.getPasteEdits(supportedProviders, dataTransfer, model, selections, context, token);
          disposables.add(editSession);
          if (token.isCancellationRequested) {
            return;
          }
          if (editSession.edits.length === 1 && editSession.edits[0].provider instanceof DefaultTextPasteOrDropEditProvider) {
            return this.applyDefaultPasteHandler(dataTransfer, metadata, token, clipboardEvent);
          }
          if (editSession.edits.length) {
            const canShowWidget = editor3.getOption(
              97
              /* EditorOption.pasteAs */
            ).showPasteSelector === "afterPaste";
            return this._postPasteWidgetManager.applyEditAndShowIfNeeded(selections, { activeEditIndex: this.getInitialActiveEditIndex(model, editSession.edits), allEdits: editSession.edits }, canShowWidget, async (edit2, resolveToken) => {
              if (!edit2.provider.resolveDocumentPasteEdit) {
                return edit2;
              }
              const resolveP = edit2.provider.resolveDocumentPasteEdit(edit2, resolveToken);
              const showP = new DeferredPromise();
              const resolved = await this._pasteProgressManager.showWhile(selections[0].getEndPosition(), localize(921, "Resolving paste edit for '{0}'. Click to cancel", edit2.title), raceCancellation(Promise.race([showP.p, resolveP]), resolveToken), {
                cancel: () => showP.cancel()
              }, 0);
              if (resolved) {
                edit2.insertText = resolved.insertText;
                edit2.additionalEdit = resolved.additionalEdit;
              }
              return edit2;
            }, token);
          }
          await this.applyDefaultPasteHandler(dataTransfer, metadata, token, clipboardEvent);
        } finally {
          disposables.dispose();
          if (this._currentPasteOperation === p) {
            this._currentPasteOperation = void 0;
          }
        }
      });
      this._pasteProgressManager.showWhile(selections[0].getEndPosition(), localize(922, "Running paste handlers. Click to cancel and do basic paste"), p, {
        cancel: async () => {
          p.cancel();
          if (editorStateCts.token.isCancellationRequested) {
            return;
          }
          await this.applyDefaultPasteHandler(dataTransfer, metadata, editorStateCts.token, clipboardEvent);
        }
      }).finally(() => {
        editorStateCts.dispose();
      });
      this._currentPasteOperation = p;
    }
    showPasteAsPick(preference, allProviders, selections, dataTransfer, metadata) {
      this._logService.trace("CopyPasteController#showPasteAsPick");
      const p = createCancelablePromise(async (token) => {
        const editor2 = this._editor;
        if (!editor2.hasModel()) {
          return;
        }
        const model = editor2.getModel();
        const disposables = new DisposableStore();
        const tokenSource = disposables.add(new EditorStateCancellationTokenSource(editor2, 1 | 2, void 0, token));
        try {
          await this.mergeInDataFromCopy(allProviders, dataTransfer, metadata, tokenSource.token);
          if (tokenSource.token.isCancellationRequested) {
            return;
          }
          let supportedProviders = allProviders.filter((provider) => this.isSupportedPasteProvider(provider, dataTransfer, preference));
          if (preference) {
            supportedProviders = supportedProviders.filter((provider) => this.providerMatchesPreference(provider, preference));
          }
          const context = {
            triggerKind: DocumentPasteTriggerKind.PasteAs,
            only: preference && "only" in preference ? preference.only : void 0
          };
          let editSession = disposables.add(await this.getPasteEdits(supportedProviders, dataTransfer, model, selections, context, tokenSource.token));
          if (tokenSource.token.isCancellationRequested) {
            return;
          }
          if (preference) {
            editSession = {
              edits: editSession.edits.filter((edit2) => {
                if ("only" in preference) {
                  return preference.only.contains(edit2.kind);
                } else if ("preferences" in preference) {
                  return preference.preferences.some((preference2) => preference2.contains(edit2.kind));
                } else {
                  return preference.providerId === edit2.provider.id;
                }
              }),
              dispose: editSession.dispose
            };
          }
          if (!editSession.edits.length) {
            if (preference) {
              this.showPasteAsNoEditMessage(selections, preference);
            }
            return;
          }
          let pickedEdit;
          if (preference) {
            pickedEdit = editSession.edits.at(0);
          } else {
            const configureDefaultItem = {
              id: "editor.pasteAs.default",
              label: localize(923, "Configure default paste action"),
              edit: void 0
            };
            const selected = await this._quickInputService.pick([
              ...editSession.edits.map((edit2) => ({
                label: edit2.title,
                description: edit2.kind?.value,
                edit: edit2
              })),
              ...CopyPasteController_1._configureDefaultAction ? [
                upcast({ type: "separator" }),
                {
                  label: CopyPasteController_1._configureDefaultAction.label,
                  edit: void 0
                }
              ] : []
            ], {
              placeHolder: localize(924, "Select Paste Action")
            });
            if (selected === configureDefaultItem) {
              CopyPasteController_1._configureDefaultAction?.run();
              return;
            }
            pickedEdit = selected?.edit;
          }
          if (!pickedEdit) {
            return;
          }
          const combinedWorkspaceEdit = createCombinedWorkspaceEdit(model.uri, selections, pickedEdit);
          await this._bulkEditService.apply(combinedWorkspaceEdit, { editor: this._editor });
        } finally {
          disposables.dispose();
          if (this._currentPasteOperation === p) {
            this._currentPasteOperation = void 0;
          }
        }
      });
      this._progressService.withProgress({
        location: 10,
        title: localize(925, "Running paste handlers")
      }, () => p);
    }
    setCopyMetadata(dataTransfer, metadata) {
      this._logService.trace("CopyPasteController#setCopyMetadata new id : ", metadata.id);
      dataTransfer.setData(vscodeClipboardMime, JSON.stringify(metadata));
    }
    fetchCopyMetadata(e) {
      this._logService.trace("CopyPasteController#fetchCopyMetadata");
      if (!e.clipboardData) {
        return;
      }
      const rawMetadata = e.clipboardData.getData(vscodeClipboardMime);
      if (rawMetadata) {
        try {
          return JSON.parse(rawMetadata);
        } catch {
          return void 0;
        }
      }
      const [_, metadata] = ClipboardEventUtils.getTextData(e.clipboardData);
      if (metadata) {
        return {
          defaultPastePayload: {
            mode: metadata.mode,
            multicursorText: metadata.multicursorText ?? null,
            pasteOnNewLine: !!metadata.isFromEmptySelection
          }
        };
      }
      return void 0;
    }
    async mergeInDataFromCopy(allProviders, dataTransfer, metadata, token) {
      this._logService.trace("CopyPasteController#mergeInDataFromCopy with metadata : ", metadata?.id);
      if (metadata?.id && CopyPasteController_1._currentCopyOperation?.handle === metadata.id) {
        const toResolve = CopyPasteController_1._currentCopyOperation.operations.filter((op) => allProviders.some((provider) => provider.pasteMimeTypes.some((type) => matchesMimeType(type, op.providerMimeTypes)))).map((op) => op.operation);
        const toMergeResults = await Promise.all(toResolve);
        if (token.isCancellationRequested) {
          return;
        }
        for (const toMergeData of toMergeResults.reverse()) {
          if (toMergeData) {
            for (const [key, value] of toMergeData) {
              dataTransfer.replace(key, value);
            }
          }
        }
      }
      if (!dataTransfer.has(Mimes.uriList)) {
        const resources = await this._clipboardService.readResources();
        if (token.isCancellationRequested) {
          return;
        }
        if (resources.length) {
          dataTransfer.append(Mimes.uriList, createStringDataTransferItem(UriList.create(resources)));
        }
      }
    }
    async getPasteEdits(providers, dataTransfer, model, selections, context, token) {
      const disposables = new DisposableStore();
      const results = await raceCancellation(Promise.all(providers.map(async (provider) => {
        try {
          const edits2 = await provider.provideDocumentPasteEdits?.(model, selections, dataTransfer, context, token);
          if (edits2) {
            disposables.add(edits2);
          }
          return edits2?.edits?.map((edit2) => ({ ...edit2, provider }));
        } catch (err) {
          if (!isCancellationError(err)) {
            console.error(err);
          }
          return void 0;
        }
      })), token);
      const edits = coalesce(results ?? []).flat().filter((edit2) => {
        return !context.only || context.only.contains(edit2.kind);
      });
      return {
        edits: sortEditsByYieldTo(edits),
        dispose: () => disposables.dispose()
      };
    }
    async applyDefaultPasteHandler(dataTransfer, metadata, token, clipboardEvent) {
      const textDataTransfer = dataTransfer.get(Mimes.text) ?? dataTransfer.get("text");
      const text2 = await textDataTransfer?.asString() ?? "";
      if (token.isCancellationRequested) {
        return;
      }
      const payload = {
        clipboardEvent,
        text: text2,
        pasteOnNewLine: metadata?.defaultPastePayload.pasteOnNewLine ?? false,
        multicursorText: metadata?.defaultPastePayload.multicursorText ?? null,
        mode: null
      };
      this._logService.trace("CopyPasteController#applyDefaultPasteHandler for id : ", metadata?.id);
      this._editor.trigger("keyboard", "paste", payload);
    }
    /**
     * Filter out providers if they:
     * - Don't handle any of the data transfer types we have
     * - Don't match the preferred paste kind
     */
    isSupportedPasteProvider(provider, dataTransfer, preference) {
      if (!provider.pasteMimeTypes?.some((type) => dataTransfer.matches(type))) {
        return false;
      }
      return !preference || this.providerMatchesPreference(provider, preference);
    }
    providerMatchesPreference(provider, preference) {
      if ("only" in preference) {
        return provider.providedPasteEditKinds.some((providedKind) => preference.only.contains(providedKind));
      } else if ("preferences" in preference) {
        return preference.preferences.some((providedKind) => preference.preferences.some((preferredKind) => preferredKind.contains(providedKind)));
      } else {
        return provider.id === preference.providerId;
      }
    }
    getInitialActiveEditIndex(model, edits) {
      const preferredProviders = this._configService.getValue(pasteAsPreferenceConfig, { resource: model.uri });
      for (const config of Array.isArray(preferredProviders) ? preferredProviders : []) {
        const desiredKind = new HierarchicalKind(config);
        const editIndex = edits.findIndex((edit2) => desiredKind.contains(edit2.kind));
        if (editIndex >= 0) {
          return editIndex;
        }
      }
      return 0;
    }
  }, CopyPasteController_1 = _s, _s.ID = "editor.contrib.copyPasteActionController", _s);
  CopyPasteController = CopyPasteController_1 = __decorate$2k([
    __param$2i(1, IInstantiationService),
    __param$2i(2, ILogService),
    __param$2i(3, IBulkEditService),
    __param$2i(4, IClipboardService),
    __param$2i(5, ICommandService),
    __param$2i(6, IConfigurationService),
    __param$2i(7, ILanguageFeaturesService),
    __param$2i(8, IQuickInputService),
    __param$2i(9, IProgressService)
  ], CopyPasteController);
  const CLIPBOARD_CONTEXT_MENU_GROUP = "9_cutcopypaste";
  const supportsCut = isNative || document.queryCommandSupported("cut");
  const supportsCopy = isNative || document.queryCommandSupported("copy");
  const supportsPaste = typeof navigator.clipboard === "undefined" || isFirefox$1 ? document.queryCommandSupported("paste") : true;
  function registerCommand$1(command) {
    command.register();
    return command;
  }
  const CutAction = supportsCut ? registerCommand$1(new MultiCommand({
    id: "editor.action.clipboardCutAction",
    precondition: void 0,
    kbOpts: (
      // Do not bind cut keybindings in the browser,
      // since browsers do that for us and it avoids security prompts
      isNative ? {
        primary: 2048 | 54,
        win: { primary: 2048 | 54, secondary: [
          1024 | 20
          /* KeyCode.Delete */
        ] },
        weight: 100
        /* KeybindingWeight.EditorContrib */
      } : void 0
    ),
    menuOpts: [{
      menuId: MenuId.MenubarEditMenu,
      group: "2_ccp",
      title: localize(813, "Cu&&t"),
      order: 1
    }, {
      menuId: MenuId.EditorContext,
      group: CLIPBOARD_CONTEXT_MENU_GROUP,
      title: localize(814, "Cut"),
      when: EditorContextKeys.writable,
      order: 1
    }, {
      menuId: MenuId.CommandPalette,
      group: "",
      title: localize(815, "Cut"),
      order: 1
    }, {
      menuId: MenuId.SimpleEditorContext,
      group: CLIPBOARD_CONTEXT_MENU_GROUP,
      title: localize(816, "Cut"),
      when: EditorContextKeys.writable,
      order: 1
    }]
  })) : void 0;
  const CopyAction = supportsCopy ? registerCommand$1(new MultiCommand({
    id: "editor.action.clipboardCopyAction",
    precondition: void 0,
    kbOpts: (
      // Do not bind copy keybindings in the browser,
      // since browsers do that for us and it avoids security prompts
      isNative ? {
        primary: 2048 | 33,
        win: { primary: 2048 | 33, secondary: [
          2048 | 19
          /* KeyCode.Insert */
        ] },
        weight: 100
        /* KeybindingWeight.EditorContrib */
      } : void 0
    ),
    menuOpts: [{
      menuId: MenuId.MenubarEditMenu,
      group: "2_ccp",
      title: localize(817, "&&Copy"),
      order: 2
    }, {
      menuId: MenuId.EditorContext,
      group: CLIPBOARD_CONTEXT_MENU_GROUP,
      title: localize(818, "Copy"),
      order: 2
    }, {
      menuId: MenuId.CommandPalette,
      group: "",
      title: localize(819, "Copy"),
      order: 1
    }, {
      menuId: MenuId.SimpleEditorContext,
      group: CLIPBOARD_CONTEXT_MENU_GROUP,
      title: localize(820, "Copy"),
      order: 2
    }]
  })) : void 0;
  MenuRegistry.appendMenuItem(MenuId.MenubarEditMenu, { submenu: MenuId.MenubarCopy, title: localize2(825, "Copy As"), group: "2_ccp", order: 3 });
  MenuRegistry.appendMenuItem(MenuId.EditorContext, { submenu: MenuId.EditorContextCopy, title: localize2(826, "Copy As"), group: CLIPBOARD_CONTEXT_MENU_GROUP, order: 3 });
  MenuRegistry.appendMenuItem(MenuId.EditorContext, { submenu: MenuId.EditorContextShare, title: localize2(827, "Share"), group: "11_share", order: -1, when: ContextKeyExpr.and(ContextKeyExpr.notEquals("resourceScheme", "output"), EditorContextKeys.editorTextFocus) });
  MenuRegistry.appendMenuItem(MenuId.ExplorerContext, { submenu: MenuId.ExplorerContextShare, title: localize2(828, "Share"), group: "11_share", order: -1 });
  const PasteAction = supportsPaste ? registerCommand$1(new MultiCommand({
    id: "editor.action.clipboardPasteAction",
    precondition: void 0,
    kbOpts: (
      // Do not bind paste keybindings in the browser,
      // since browsers do that for us and it avoids security prompts
      isNative ? {
        primary: 2048 | 52,
        win: { primary: 2048 | 52, secondary: [
          1024 | 19
          /* KeyCode.Insert */
        ] },
        linux: { primary: 2048 | 52, secondary: [
          1024 | 19
          /* KeyCode.Insert */
        ] },
        weight: 100
        /* KeybindingWeight.EditorContrib */
      } : void 0
    ),
    menuOpts: [{
      menuId: MenuId.MenubarEditMenu,
      group: "2_ccp",
      title: localize(821, "&&Paste"),
      order: 4
    }, {
      menuId: MenuId.EditorContext,
      group: CLIPBOARD_CONTEXT_MENU_GROUP,
      title: localize(822, "Paste"),
      when: EditorContextKeys.writable,
      order: 4
    }, {
      menuId: MenuId.CommandPalette,
      group: "",
      title: localize(823, "Paste"),
      order: 1
    }, {
      menuId: MenuId.SimpleEditorContext,
      group: CLIPBOARD_CONTEXT_MENU_GROUP,
      title: localize(824, "Paste"),
      when: EditorContextKeys.writable,
      order: 4
    }]
  })) : void 0;
  class ExecCommandCopyWithSyntaxHighlightingAction extends EditorAction {
    constructor() {
      super({
        id: "editor.action.clipboardCopyWithSyntaxHighlightingAction",
        label: localize2(829, "Copy with Syntax Highlighting"),
        precondition: void 0,
        kbOpts: {
          kbExpr: EditorContextKeys.textInputFocus,
          primary: 0,
          weight: 100
          /* KeybindingWeight.EditorContrib */
        }
      });
    }
    run(accessor, editor2) {
      const logService = accessor.get(ILogService);
      logService.trace("ExecCommandCopyWithSyntaxHighlightingAction#run");
      if (!editor2.hasModel()) {
        return;
      }
      const emptySelectionClipboard = editor2.getOption(
        45
        /* EditorOption.emptySelectionClipboard */
      );
      if (!emptySelectionClipboard && editor2.getSelection().isEmpty()) {
        return;
      }
      CopyOptions.forceCopyWithSyntaxHighlighting = true;
      editor2.focus();
      logService.trace("ExecCommandCopyWithSyntaxHighlightingAction (before execCommand copy)");
      editor2.getContainerDomNode().ownerDocument.execCommand("copy");
      logService.trace("ExecCommandCopyWithSyntaxHighlightingAction (after execCommand copy)");
      CopyOptions.forceCopyWithSyntaxHighlighting = false;
    }
  }
  function registerExecCommandImpl(target, browserCommand) {
    if (!target) {
      return;
    }
    target.addImplementation(1e4, "code-editor", (accessor, args) => {
      const logService = accessor.get(ILogService);
      logService.trace("registerExecCommandImpl (addImplementation code-editor for : ", browserCommand, ")");
      const focusedEditor = accessor.get(ICodeEditorService).getFocusedCodeEditor();
      if (focusedEditor && focusedEditor.hasTextFocus()) {
        const emptySelectionClipboard = focusedEditor.getOption(
          45
          /* EditorOption.emptySelectionClipboard */
        );
        const selection = focusedEditor.getSelection();
        if (selection && selection.isEmpty() && !emptySelectionClipboard) {
          return true;
        }
        if (focusedEditor.getOption(
          170
          /* EditorOption.effectiveEditContext */
        ) && browserCommand === "cut") {
          logCopyCommand(focusedEditor);
          logService.trace("registerExecCommandImpl (before execCommand copy)");
          focusedEditor.getContainerDomNode().ownerDocument.execCommand("copy");
          focusedEditor.trigger(void 0, "cut", void 0);
          logService.trace("registerExecCommandImpl (after execCommand copy)");
        } else {
          logCopyCommand(focusedEditor);
          logService.trace("registerExecCommandImpl (before execCommand " + browserCommand + ")");
          focusedEditor.getContainerDomNode().ownerDocument.execCommand(browserCommand);
          logService.trace("registerExecCommandImpl (after execCommand " + browserCommand + ")");
        }
        return true;
      }
      return false;
    });
    target.addImplementation(0, "generic-dom", (accessor, args) => {
      const logService = accessor.get(ILogService);
      logService.trace("registerExecCommandImpl (addImplementation generic-dom for : ", browserCommand, ")");
      logService.trace("registerExecCommandImpl (before execCommand " + browserCommand + ")");
      getActiveDocument().execCommand(browserCommand);
      logService.trace("registerExecCommandImpl (after execCommand " + browserCommand + ")");
      return true;
    });
  }
  function logCopyCommand(editor2) {
    const editContextEnabled = editor2.getOption(
      170
      /* EditorOption.effectiveEditContext */
    );
    if (editContextEnabled) {
      const nativeEditContext = NativeEditContextRegistry.get(editor2.getId());
      if (nativeEditContext) {
        nativeEditContext.onWillCopy();
      }
    }
  }
  registerExecCommandImpl(CutAction, "cut");
  registerExecCommandImpl(CopyAction, "copy");
  if (PasteAction) {
    PasteAction.addImplementation(1e4, "code-editor", (accessor, args) => {
      const logService = accessor.get(ILogService);
      logService.trace("registerExecCommandImpl (addImplementation code-editor for : paste)");
      const codeEditorService = accessor.get(ICodeEditorService);
      const clipboardService = accessor.get(IClipboardService);
      const telemetryService = accessor.get(ITelemetryService);
      const productService = accessor.get(IProductService);
      const focusedEditor = codeEditorService.getFocusedCodeEditor();
      if (focusedEditor && focusedEditor.hasModel() && focusedEditor.hasTextFocus()) {
        const editContextEnabled = focusedEditor.getOption(
          170
          /* EditorOption.effectiveEditContext */
        );
        if (editContextEnabled) {
          const nativeEditContext = NativeEditContextRegistry.get(focusedEditor.getId());
          if (nativeEditContext) {
            nativeEditContext.onWillPaste();
          }
        }
        const sw = StopWatch.create(true);
        logService.trace("registerExecCommandImpl (before triggerPaste)");
        const triggerPaste = clipboardService.triggerPaste(getActiveWindow().vscodeWindowId);
        if (triggerPaste) {
          logService.trace("registerExecCommandImpl (triggerPaste defined)");
          return triggerPaste.then(async () => {
            logService.trace("registerExecCommandImpl (after triggerPaste)");
            if (productService.quality !== "stable") {
              const duration = sw.elapsed();
              telemetryService.publicLog2("editorAsyncPaste", { duration });
            }
            return CopyPasteController.get(focusedEditor)?.finishedPaste() ?? Promise.resolve();
          });
        } else {
          logService.trace("registerExecCommandImpl (triggerPaste undefined)");
        }
        if (isWeb) {
          logService.trace("registerExecCommandImpl (Paste handling on web)");
          return (async () => {
            const clipboardText = await clipboardService.readText();
            if (clipboardText !== "") {
              const metadata = InMemoryClipboardMetadataManager.INSTANCE.get(clipboardText);
              let pasteOnNewLine = false;
              let multicursorText = null;
              let mode = null;
              if (metadata) {
                pasteOnNewLine = focusedEditor.getOption(
                  45
                  /* EditorOption.emptySelectionClipboard */
                ) && !!metadata.isFromEmptySelection;
                multicursorText = typeof metadata.multicursorText !== "undefined" ? metadata.multicursorText : null;
                mode = metadata.mode;
              }
              logService.trace("registerExecCommandImpl (clipboardText.length : ", clipboardText.length, " id : ", metadata?.id, ")");
              focusedEditor.trigger("keyboard", "paste", {
                text: clipboardText,
                pasteOnNewLine,
                multicursorText,
                mode
              });
            }
          })();
        }
        return true;
      }
      return false;
    });
    PasteAction.addImplementation(0, "generic-dom", (accessor, args) => {
      const logService = accessor.get(ILogService);
      logService.trace("registerExecCommandImpl (addImplementation generic-dom for : paste)");
      const triggerPaste = accessor.get(IClipboardService).triggerPaste(getActiveWindow().vscodeWindowId);
      return triggerPaste ?? false;
    });
  }
  if (supportsCopy) {
    registerEditorAction(ExecCommandCopyWithSyntaxHighlightingAction);
  }
  const editorConfigurationBaseNode = Object.freeze({
    id: "editor",
    order: 5,
    type: "object",
    title: localize(147, "Editor"),
    scope: 6
  });
  const editorConfiguration = {
    ...editorConfigurationBaseNode,
    properties: {
      "editor.tabSize": {
        type: "number",
        default: EDITOR_MODEL_DEFAULTS.tabSize,
        minimum: 1,
        maximum: 100,
        markdownDescription: localize(148, "The number of spaces a tab is equal to. This setting is overridden based on the file contents when {0} is on.", "`#editor.detectIndentation#`")
      },
      "editor.indentSize": {
        "anyOf": [
          {
            type: "string",
            enum: ["tabSize"]
          },
          {
            type: "number",
            minimum: 1
          }
        ],
        default: "tabSize",
        markdownDescription: localize(149, 'The number of spaces used for indentation or `"tabSize"` to use the value from `#editor.tabSize#`. This setting is overridden based on the file contents when `#editor.detectIndentation#` is on.')
      },
      "editor.insertSpaces": {
        type: "boolean",
        default: EDITOR_MODEL_DEFAULTS.insertSpaces,
        markdownDescription: localize(150, "Insert spaces when pressing `Tab`. This setting is overridden based on the file contents when {0} is on.", "`#editor.detectIndentation#`")
      },
      "editor.detectIndentation": {
        type: "boolean",
        default: EDITOR_MODEL_DEFAULTS.detectIndentation,
        markdownDescription: localize(151, "Controls whether {0} and {1} will be automatically detected when a file is opened based on the file contents.", "`#editor.tabSize#`", "`#editor.insertSpaces#`")
      },
      "editor.trimAutoWhitespace": {
        type: "boolean",
        default: EDITOR_MODEL_DEFAULTS.trimAutoWhitespace,
        description: localize(152, "Remove trailing auto inserted whitespace.")
      },
      "editor.largeFileOptimizations": {
        type: "boolean",
        default: EDITOR_MODEL_DEFAULTS.largeFileOptimizations,
        description: localize(153, "Special handling for large files to disable certain memory intensive features.")
      },
      "editor.wordBasedSuggestions": {
        enum: ["off", "currentDocument", "matchingDocuments", "allDocuments"],
        default: "matchingDocuments",
        enumDescriptions: [
          localize(154, "Turn off Word Based Suggestions."),
          localize(155, "Only suggest words from the active document."),
          localize(156, "Suggest words from all open documents of the same language."),
          localize(157, "Suggest words from all open documents.")
        ],
        description: localize(158, "Controls whether completions should be computed based on words in the document and from which documents they are computed.")
      },
      "editor.semanticHighlighting.enabled": {
        enum: [true, false, "configuredByTheme"],
        enumDescriptions: [
          localize(159, "Semantic highlighting enabled for all color themes."),
          localize(160, "Semantic highlighting disabled for all color themes."),
          localize(161, "Semantic highlighting is configured by the current color theme's `semanticHighlighting` setting.")
        ],
        default: "configuredByTheme",
        description: localize(162, "Controls whether the semanticHighlighting is shown for the languages that support it.")
      },
      "editor.stablePeek": {
        type: "boolean",
        default: false,
        markdownDescription: localize(163, "Keep peek editors open even when double-clicking their content or when hitting `Escape`.")
      },
      "editor.maxTokenizationLineLength": {
        type: "integer",
        default: 2e4,
        description: localize(164, "Lines above this length will not be tokenized for performance reasons")
      },
      "editor.experimental.asyncTokenization": {
        type: "boolean",
        default: true,
        description: localize(165, "Controls whether the tokenization should happen asynchronously on a web worker."),
        tags: ["experimental"]
      },
      "editor.experimental.asyncTokenizationLogging": {
        type: "boolean",
        default: false,
        description: localize(166, "Controls whether async tokenization should be logged. For debugging only.")
      },
      "editor.experimental.asyncTokenizationVerification": {
        type: "boolean",
        default: false,
        description: localize(167, "Controls whether async tokenization should be verified against legacy background tokenization. Might slow down tokenization. For debugging only."),
        tags: ["experimental"]
      },
      "editor.experimental.treeSitterTelemetry": {
        type: "boolean",
        default: false,
        markdownDescription: localize(168, "Controls whether tree sitter parsing should be turned on and telemetry collected. Setting `#editor.experimental.preferTreeSitter#` for specific languages will take precedence."),
        tags: ["experimental"],
        experiment: {
          mode: "auto"
        }
      },
      "editor.experimental.preferTreeSitter.css": {
        type: "boolean",
        default: false,
        markdownDescription: localize(169, "Controls whether tree sitter parsing should be turned on for css. This will take precedence over `#editor.experimental.treeSitterTelemetry#` for css."),
        tags: ["experimental"],
        experiment: {
          mode: "auto"
        }
      },
      "editor.experimental.preferTreeSitter.typescript": {
        type: "boolean",
        default: false,
        markdownDescription: localize(170, "Controls whether tree sitter parsing should be turned on for typescript. This will take precedence over `#editor.experimental.treeSitterTelemetry#` for typescript."),
        tags: ["experimental"],
        experiment: {
          mode: "auto"
        }
      },
      "editor.experimental.preferTreeSitter.ini": {
        type: "boolean",
        default: false,
        markdownDescription: localize(171, "Controls whether tree sitter parsing should be turned on for ini. This will take precedence over `#editor.experimental.treeSitterTelemetry#` for ini."),
        tags: ["experimental"],
        experiment: {
          mode: "auto"
        }
      },
      "editor.experimental.preferTreeSitter.regex": {
        type: "boolean",
        default: false,
        markdownDescription: localize(172, "Controls whether tree sitter parsing should be turned on for regex. This will take precedence over `#editor.experimental.treeSitterTelemetry#` for regex."),
        tags: ["experimental"],
        experiment: {
          mode: "auto"
        }
      },
      "editor.language.brackets": {
        type: ["array", "null"],
        default: null,
        // We want to distinguish the empty array from not configured.
        description: localize(173, "Defines the bracket symbols that increase or decrease the indentation."),
        items: {
          type: "array",
          items: [
            {
              type: "string",
              description: localize(174, "The opening bracket character or string sequence.")
            },
            {
              type: "string",
              description: localize(175, "The closing bracket character or string sequence.")
            }
          ]
        }
      },
      "editor.language.colorizedBracketPairs": {
        type: ["array", "null"],
        default: null,
        // We want to distinguish the empty array from not configured.
        description: localize(176, "Defines the bracket pairs that are colorized by their nesting level if bracket pair colorization is enabled."),
        items: {
          type: "array",
          items: [
            {
              type: "string",
              description: localize(177, "The opening bracket character or string sequence.")
            },
            {
              type: "string",
              description: localize(178, "The closing bracket character or string sequence.")
            }
          ]
        }
      },
      "diffEditor.maxComputationTime": {
        type: "number",
        default: diffEditorDefaultOptions.maxComputationTime,
        description: localize(179, "Timeout in milliseconds after which diff computation is cancelled. Use 0 for no timeout.")
      },
      "diffEditor.maxFileSize": {
        type: "number",
        default: diffEditorDefaultOptions.maxFileSize,
        description: localize(180, "Maximum file size in MB for which to compute diffs. Use 0 for no limit.")
      },
      "diffEditor.renderSideBySide": {
        type: "boolean",
        default: diffEditorDefaultOptions.renderSideBySide,
        description: localize(181, "Controls whether the diff editor shows the diff side by side or inline.")
      },
      "diffEditor.renderSideBySideInlineBreakpoint": {
        type: "number",
        default: diffEditorDefaultOptions.renderSideBySideInlineBreakpoint,
        description: localize(182, "If the diff editor width is smaller than this value, the inline view is used.")
      },
      "diffEditor.useInlineViewWhenSpaceIsLimited": {
        type: "boolean",
        default: diffEditorDefaultOptions.useInlineViewWhenSpaceIsLimited,
        description: localize(183, "If enabled and the editor width is too small, the inline view is used.")
      },
      "diffEditor.renderMarginRevertIcon": {
        type: "boolean",
        default: diffEditorDefaultOptions.renderMarginRevertIcon,
        description: localize(184, "When enabled, the diff editor shows arrows in its glyph margin to revert changes.")
      },
      "diffEditor.renderGutterMenu": {
        type: "boolean",
        default: diffEditorDefaultOptions.renderGutterMenu,
        description: localize(185, "When enabled, the diff editor shows a special gutter for revert and stage actions.")
      },
      "diffEditor.ignoreTrimWhitespace": {
        type: "boolean",
        default: diffEditorDefaultOptions.ignoreTrimWhitespace,
        description: localize(186, "When enabled, the diff editor ignores changes in leading or trailing whitespace.")
      },
      "diffEditor.renderIndicators": {
        type: "boolean",
        default: diffEditorDefaultOptions.renderIndicators,
        description: localize(187, "Controls whether the diff editor shows +/- indicators for added/removed changes.")
      },
      "diffEditor.codeLens": {
        type: "boolean",
        default: diffEditorDefaultOptions.diffCodeLens,
        description: localize(188, "Controls whether the editor shows CodeLens.")
      },
      "diffEditor.wordWrap": {
        type: "string",
        enum: ["off", "on", "inherit"],
        default: diffEditorDefaultOptions.diffWordWrap,
        markdownEnumDescriptions: [
          localize(189, "Lines will never wrap."),
          localize(190, "Lines will wrap at the viewport width."),
          localize(191, "Lines will wrap according to the {0} setting.", "`#editor.wordWrap#`")
        ]
      },
      "diffEditor.diffAlgorithm": {
        type: "string",
        enum: ["legacy", "advanced"],
        default: diffEditorDefaultOptions.diffAlgorithm,
        markdownEnumDescriptions: [
          localize(192, "Uses the legacy diffing algorithm."),
          localize(193, "Uses the advanced diffing algorithm.")
        ]
      },
      "diffEditor.hideUnchangedRegions.enabled": {
        type: "boolean",
        default: diffEditorDefaultOptions.hideUnchangedRegions.enabled,
        markdownDescription: localize(194, "Controls whether the diff editor shows unchanged regions.")
      },
      "diffEditor.hideUnchangedRegions.revealLineCount": {
        type: "integer",
        default: diffEditorDefaultOptions.hideUnchangedRegions.revealLineCount,
        markdownDescription: localize(195, "Controls how many lines are used for unchanged regions."),
        minimum: 1
      },
      "diffEditor.hideUnchangedRegions.minimumLineCount": {
        type: "integer",
        default: diffEditorDefaultOptions.hideUnchangedRegions.minimumLineCount,
        markdownDescription: localize(196, "Controls how many lines are used as a minimum for unchanged regions."),
        minimum: 1
      },
      "diffEditor.hideUnchangedRegions.contextLineCount": {
        type: "integer",
        default: diffEditorDefaultOptions.hideUnchangedRegions.contextLineCount,
        markdownDescription: localize(197, "Controls how many lines are used as context when comparing unchanged regions."),
        minimum: 1
      },
      "diffEditor.experimental.showMoves": {
        type: "boolean",
        default: diffEditorDefaultOptions.experimental.showMoves,
        markdownDescription: localize(198, "Controls whether the diff editor should show detected code moves.")
      },
      "diffEditor.experimental.showEmptyDecorations": {
        type: "boolean",
        default: diffEditorDefaultOptions.experimental.showEmptyDecorations,
        description: localize(199, "Controls whether the diff editor shows empty decorations to see where characters got inserted or deleted.")
      },
      "diffEditor.experimental.useTrueInlineView": {
        type: "boolean",
        default: diffEditorDefaultOptions.experimental.useTrueInlineView,
        description: localize(200, "If enabled and the editor uses the inline view, word changes are rendered inline.")
      }
    }
  };
  function isConfigurationPropertySchema(x) {
    return typeof x.type !== "undefined" || typeof x.anyOf !== "undefined";
  }
  for (const editorOption of editorOptionsRegistry) {
    const schema = editorOption.schema;
    if (typeof schema !== "undefined") {
      if (isConfigurationPropertySchema(schema)) {
        editorConfiguration.properties[`editor.${editorOption.name}`] = schema;
      } else {
        for (const key in schema) {
          if (Object.hasOwnProperty.call(schema, key)) {
            editorConfiguration.properties[key] = schema[key];
          }
        }
      }
    }
  }
  let cachedEditorConfigurationKeys = null;
  function getEditorConfigurationKeys() {
    if (cachedEditorConfigurationKeys === null) {
      cachedEditorConfigurationKeys = /* @__PURE__ */ Object.create(null);
      Object.keys(editorConfiguration.properties).forEach((prop) => {
        cachedEditorConfigurationKeys[prop] = true;
      });
    }
    return cachedEditorConfigurationKeys;
  }
  function isEditorConfigurationKey(key) {
    const editorConfigurationKeys = getEditorConfigurationKeys();
    return editorConfigurationKeys[`editor.${key}`] || false;
  }
  function isDiffEditorConfigurationKey(key) {
    const editorConfigurationKeys = getEditorConfigurationKeys();
    return editorConfigurationKeys[`diffEditor.${key}`] || false;
  }
  const configurationRegistry$1 = Registry.as(Extensions$6.Configuration);
  configurationRegistry$1.registerConfiguration(editorConfiguration);
  const CodeActionKind = new class {
    constructor() {
      this.QuickFix = new HierarchicalKind("quickfix");
      this.Refactor = new HierarchicalKind("refactor");
      this.RefactorExtract = this.Refactor.append("extract");
      this.RefactorInline = this.Refactor.append("inline");
      this.RefactorMove = this.Refactor.append("move");
      this.RefactorRewrite = this.Refactor.append("rewrite");
      this.Notebook = new HierarchicalKind("notebook");
      this.Source = new HierarchicalKind("source");
      this.SourceOrganizeImports = this.Source.append("organizeImports");
      this.SourceFixAll = this.Source.append("fixAll");
      this.SurroundWith = this.Refactor.append("surround");
    }
  }();
  var CodeActionTriggerSource;
  (function(CodeActionTriggerSource2) {
    CodeActionTriggerSource2["Refactor"] = "refactor";
    CodeActionTriggerSource2["RefactorPreview"] = "refactor preview";
    CodeActionTriggerSource2["Lightbulb"] = "lightbulb";
    CodeActionTriggerSource2["Default"] = "other (default)";
    CodeActionTriggerSource2["SourceAction"] = "source action";
    CodeActionTriggerSource2["QuickFix"] = "quick fix action";
    CodeActionTriggerSource2["FixAll"] = "fix all";
    CodeActionTriggerSource2["OrganizeImports"] = "organize imports";
    CodeActionTriggerSource2["AutoFix"] = "auto fix";
    CodeActionTriggerSource2["QuickFixHover"] = "quick fix hover window";
    CodeActionTriggerSource2["OnSave"] = "save participants";
    CodeActionTriggerSource2["ProblemsView"] = "problems view";
  })(CodeActionTriggerSource || (CodeActionTriggerSource = {}));
  function mayIncludeActionsOfKind(filter, providedKind) {
    if (filter.include && !filter.include.intersects(providedKind)) {
      return false;
    }
    if (filter.excludes) {
      if (filter.excludes.some((exclude) => excludesAction(providedKind, exclude, filter.include))) {
        return false;
      }
    }
    if (!filter.includeSourceActions && CodeActionKind.Source.contains(providedKind)) {
      return false;
    }
    return true;
  }
  function filtersAction(filter, action) {
    const actionKind = action.kind ? new HierarchicalKind(action.kind) : void 0;
    if (filter.include) {
      if (!actionKind || !filter.include.contains(actionKind)) {
        return false;
      }
    }
    if (filter.excludes) {
      if (actionKind && filter.excludes.some((exclude) => excludesAction(actionKind, exclude, filter.include))) {
        return false;
      }
    }
    if (!filter.includeSourceActions) {
      if (actionKind && CodeActionKind.Source.contains(actionKind)) {
        return false;
      }
    }
    if (filter.onlyIncludePreferredActions) {
      if (!action.isPreferred) {
        return false;
      }
    }
    return true;
  }
  function excludesAction(providedKind, exclude, include) {
    if (!exclude.contains(providedKind)) {
      return false;
    }
    if (include && exclude.contains(include)) {
      return false;
    }
    return true;
  }
  class CodeActionCommandArgs {
    static fromUser(arg, defaults) {
      if (!arg || typeof arg !== "object") {
        return new CodeActionCommandArgs(defaults.kind, defaults.apply, false);
      }
      return new CodeActionCommandArgs(CodeActionCommandArgs.getKindFromUser(arg, defaults.kind), CodeActionCommandArgs.getApplyFromUser(arg, defaults.apply), CodeActionCommandArgs.getPreferredUser(arg));
    }
    static getApplyFromUser(arg, defaultAutoApply) {
      switch (typeof arg.apply === "string" ? arg.apply.toLowerCase() : "") {
        case "first":
          return "first";
        case "never":
          return "never";
        case "ifsingle":
          return "ifSingle";
        default:
          return defaultAutoApply;
      }
    }
    static getKindFromUser(arg, defaultKind) {
      return typeof arg.kind === "string" ? new HierarchicalKind(arg.kind) : defaultKind;
    }
    static getPreferredUser(arg) {
      return typeof arg.preferred === "boolean" ? arg.preferred : false;
    }
    constructor(kind, apply2, preferred) {
      this.kind = kind;
      this.apply = apply2;
      this.preferred = preferred;
    }
  }
  class CodeActionItem {
    constructor(action, provider, highlightRange2) {
      this.action = action;
      this.provider = provider;
      this.highlightRange = highlightRange2;
    }
    async resolve(token) {
      if (this.provider?.resolveCodeAction && !this.action.edit) {
        let action;
        try {
          action = await this.provider.resolveCodeAction(this.action, token);
        } catch (err) {
          onUnexpectedExternalError(err);
        }
        if (action) {
          this.action.edit = action.edit;
        }
      }
      return this;
    }
  }
  const codeActionCommandId = "editor.action.codeAction";
  const quickFixCommandId = "editor.action.quickFix";
  const autoFixCommandId = "editor.action.autoFix";
  const refactorCommandId = "editor.action.refactor";
  const sourceActionCommandId = "editor.action.sourceAction";
  const organizeImportsCommandId = "editor.action.organizeImports";
  const fixAllCommandId = "editor.action.fixAll";
  const CODE_ACTION_SOUND_APPLIED_DURATION = 1e3;
  class ManagedCodeActionSet extends Disposable {
    static codeActionsPreferredComparator(a, b) {
      if (a.isPreferred && !b.isPreferred) {
        return -1;
      } else if (!a.isPreferred && b.isPreferred) {
        return 1;
      } else {
        return 0;
      }
    }
    static codeActionsComparator({ action: a }, { action: b }) {
      if (a.isAI && !b.isAI) {
        return 1;
      } else if (!a.isAI && b.isAI) {
        return -1;
      }
      if (isNonEmptyArray(a.diagnostics)) {
        return isNonEmptyArray(b.diagnostics) ? ManagedCodeActionSet.codeActionsPreferredComparator(a, b) : -1;
      } else if (isNonEmptyArray(b.diagnostics)) {
        return 1;
      } else {
        return ManagedCodeActionSet.codeActionsPreferredComparator(a, b);
      }
    }
    constructor(actions, documentation, disposables) {
      super();
      this.documentation = documentation;
      this._register(disposables);
      this.allActions = [...actions].sort(ManagedCodeActionSet.codeActionsComparator);
      this.validActions = this.allActions.filter(({ action }) => !action.disabled);
    }
    get hasAutoFix() {
      return this.validActions.some(({ action: fix }) => !!fix.kind && CodeActionKind.QuickFix.contains(new HierarchicalKind(fix.kind)) && !!fix.isPreferred);
    }
    get hasAIFix() {
      return this.validActions.some(({ action: fix }) => !!fix.isAI);
    }
    get allAIFixes() {
      return this.validActions.every(({ action: fix }) => !!fix.isAI);
    }
  }
  const emptyCodeActionsResponse = { actions: [], documentation: void 0 };
  async function getCodeActions(registry, model, rangeOrSelection, trigger, progress, token) {
    const filter = trigger.filter || {};
    const notebookFilter = {
      ...filter,
      excludes: [...filter.excludes || [], CodeActionKind.Notebook]
    };
    const codeActionContext = {
      only: filter.include?.value,
      trigger: trigger.type
    };
    const cts = new TextModelCancellationTokenSource(model, token);
    const excludeNotebookCodeActions = trigger.type === 2;
    const providers = getCodeActionProviders(registry, model, excludeNotebookCodeActions ? notebookFilter : filter);
    const disposables = new DisposableStore();
    const promises = providers.map(async (provider) => {
      const handle = setTimeout(() => progress.report(provider), 1250);
      try {
        const providedCodeActions = await provider.provideCodeActions(model, rangeOrSelection, codeActionContext, cts.token);
        if (cts.token.isCancellationRequested) {
          providedCodeActions?.dispose();
          return emptyCodeActionsResponse;
        }
        if (providedCodeActions) {
          disposables.add(providedCodeActions);
        }
        const filteredActions = (providedCodeActions?.actions || []).filter((action) => action && filtersAction(filter, action));
        const documentation = getDocumentationFromProvider(provider, filteredActions, filter.include);
        return {
          actions: filteredActions.map((action) => new CodeActionItem(action, provider)),
          documentation
        };
      } catch (err) {
        if (isCancellationError(err)) {
          throw err;
        }
        onUnexpectedExternalError(err);
        return emptyCodeActionsResponse;
      } finally {
        clearTimeout(handle);
      }
    });
    const listener = registry.onDidChange(() => {
      const newProviders = registry.all(model);
      if (!equals$1(newProviders, providers)) {
        cts.cancel();
      }
    });
    try {
      const actions = await Promise.all(promises);
      const allActions = actions.map((x) => x.actions).flat();
      const allDocumentation = [
        ...coalesce(actions.map((x) => x.documentation)),
        ...getAdditionalDocumentationForShowingActions(registry, model, trigger, allActions)
      ];
      const managedCodeActionSet = new ManagedCodeActionSet(allActions, allDocumentation, disposables);
      disposables.add(managedCodeActionSet);
      return managedCodeActionSet;
    } catch (err) {
      disposables.dispose();
      throw err;
    } finally {
      listener.dispose();
      cts.dispose();
    }
  }
  function getCodeActionProviders(registry, model, filter) {
    return registry.all(model).filter((provider) => {
      if (!provider.providedCodeActionKinds) {
        return true;
      }
      return provider.providedCodeActionKinds.some((kind) => mayIncludeActionsOfKind(filter, new HierarchicalKind(kind)));
    });
  }
  function* getAdditionalDocumentationForShowingActions(registry, model, trigger, actionsToShow) {
    if (model && actionsToShow.length) {
      for (const provider of registry.all(model)) {
        if (provider._getAdditionalMenuItems) {
          yield* provider._getAdditionalMenuItems?.({ trigger: trigger.type, only: trigger.filter?.include?.value }, actionsToShow.map((item) => item.action));
        }
      }
    }
  }
  function getDocumentationFromProvider(provider, providedCodeActions, only) {
    if (!provider.documentation) {
      return void 0;
    }
    const documentation = provider.documentation.map((entry) => ({ kind: new HierarchicalKind(entry.kind), command: entry.command }));
    if (only) {
      let currentBest;
      for (const entry of documentation) {
        if (entry.kind.contains(only)) {
          if (!currentBest) {
            currentBest = entry;
          } else {
            if (currentBest.kind.contains(entry.kind)) {
              currentBest = entry;
            }
          }
        }
      }
      if (currentBest) {
        return currentBest?.command;
      }
    }
    for (const action of providedCodeActions) {
      if (!action.kind) {
        continue;
      }
      for (const entry of documentation) {
        if (entry.kind.contains(new HierarchicalKind(action.kind))) {
          return entry.command;
        }
      }
    }
    return void 0;
  }
  var ApplyCodeActionReason;
  (function(ApplyCodeActionReason2) {
    ApplyCodeActionReason2["OnSave"] = "onSave";
    ApplyCodeActionReason2["FromProblemsView"] = "fromProblemsView";
    ApplyCodeActionReason2["FromCodeActions"] = "fromCodeActions";
    ApplyCodeActionReason2["FromAILightbulb"] = "fromAILightbulb";
    ApplyCodeActionReason2["FromProblemsHover"] = "fromProblemsHover";
  })(ApplyCodeActionReason || (ApplyCodeActionReason = {}));
  async function applyCodeAction(accessor, item, codeActionReason, options, token = CancellationToken.None) {
    const bulkEditService = accessor.get(IBulkEditService);
    const commandService = accessor.get(ICommandService);
    const telemetryService = accessor.get(ITelemetryService);
    const notificationService = accessor.get(INotificationService);
    const accessibilitySignalService = accessor.get(IAccessibilitySignalService);
    telemetryService.publicLog2("codeAction.applyCodeAction", {
      codeActionTitle: item.action.title,
      codeActionKind: item.action.kind,
      codeActionIsPreferred: !!item.action.isPreferred,
      reason: codeActionReason
    });
    accessibilitySignalService.playSignal(AccessibilitySignal.codeActionTriggered);
    await item.resolve(token);
    if (token.isCancellationRequested) {
      return;
    }
    if (item.action.edit?.edits.length) {
      const result = await bulkEditService.apply(item.action.edit, {
        editor: options?.editor,
        label: item.action.title,
        quotableLabel: item.action.title,
        code: "undoredo.codeAction",
        respectAutoSaveConfig: codeActionReason !== ApplyCodeActionReason.OnSave,
        showPreview: options?.preview,
        reason: EditSources.codeAction({ kind: item.action.kind, providerId: ProviderId.fromExtensionId(item.provider?.extensionId) })
      });
      if (!result.isApplied) {
        return;
      }
    }
    if (item.action.command) {
      try {
        await commandService.executeCommand(item.action.command.id, ...item.action.command.arguments || []);
      } catch (err) {
        const message = asMessage(err);
        notificationService.error(typeof message === "string" ? message : localize(830, "An unknown error occurred while applying the code action"));
      }
    }
    setTimeout(() => accessibilitySignalService.playSignal(AccessibilitySignal.codeActionApplied), CODE_ACTION_SOUND_APPLIED_DURATION);
  }
  function asMessage(err) {
    if (typeof err === "string") {
      return err;
    } else if (err instanceof Error && typeof err.message === "string") {
      return err.message;
    } else {
      return void 0;
    }
  }
  CommandsRegistry.registerCommand("_executeCodeActionProvider", async function(accessor, resource, rangeOrSelection, kind, itemResolveCount) {
    if (!(resource instanceof URI)) {
      throw illegalArgument();
    }
    const { codeActionProvider } = accessor.get(ILanguageFeaturesService);
    const model = accessor.get(IModelService).getModel(resource);
    if (!model) {
      throw illegalArgument();
    }
    const validatedRangeOrSelection = Selection$1.isISelection(rangeOrSelection) ? Selection$1.liftSelection(rangeOrSelection) : Range$2.isIRange(rangeOrSelection) ? model.validateRange(rangeOrSelection) : void 0;
    if (!validatedRangeOrSelection) {
      throw illegalArgument();
    }
    const include = typeof kind === "string" ? new HierarchicalKind(kind) : void 0;
    const codeActionSet = await getCodeActions(codeActionProvider, model, validatedRangeOrSelection, { type: 1, triggerAction: CodeActionTriggerSource.Default, filter: { includeSourceActions: true, include } }, Progress.None, CancellationToken.None);
    const resolving = [];
    const resolveCount = Math.min(codeActionSet.validActions.length, typeof itemResolveCount === "number" ? itemResolveCount : 0);
    for (let i2 = 0; i2 < resolveCount; i2++) {
      resolving.push(codeActionSet.validActions[i2].resolve(CancellationToken.None));
    }
    try {
      await Promise.all(resolving);
      return codeActionSet.validActions.map((item) => item.action);
    } finally {
      setTimeout(() => codeActionSet.dispose(), 100);
    }
  });
  var MarkerSeverity$2;
  (function(MarkerSeverity2) {
    MarkerSeverity2[MarkerSeverity2["Hint"] = 1] = "Hint";
    MarkerSeverity2[MarkerSeverity2["Info"] = 2] = "Info";
    MarkerSeverity2[MarkerSeverity2["Warning"] = 4] = "Warning";
    MarkerSeverity2[MarkerSeverity2["Error"] = 8] = "Error";
  })(MarkerSeverity$2 || (MarkerSeverity$2 = {}));
  (function(MarkerSeverity2) {
    function compare2(a, b) {
      return b - a;
    }
    MarkerSeverity2.compare = compare2;
    const _displayStrings = /* @__PURE__ */ Object.create(null);
    _displayStrings[MarkerSeverity2.Error] = localize(1732, "Error");
    _displayStrings[MarkerSeverity2.Warning] = localize(1733, "Warning");
    _displayStrings[MarkerSeverity2.Info] = localize(1734, "Info");
    function toString(a) {
      return _displayStrings[a] || "";
    }
    MarkerSeverity2.toString = toString;
    const _displayStringsPlural = /* @__PURE__ */ Object.create(null);
    _displayStringsPlural[MarkerSeverity2.Error] = localize(1735, "Errors");
    _displayStringsPlural[MarkerSeverity2.Warning] = localize(1736, "Warnings");
    _displayStringsPlural[MarkerSeverity2.Info] = localize(1737, "Infos");
    function toStringPlural(a) {
      return _displayStringsPlural[a] || "";
    }
    MarkerSeverity2.toStringPlural = toStringPlural;
    function fromSeverity(severity) {
      switch (severity) {
        case Severity$2.Error:
          return MarkerSeverity2.Error;
        case Severity$2.Warning:
          return MarkerSeverity2.Warning;
        case Severity$2.Info:
          return MarkerSeverity2.Info;
        case Severity$2.Ignore:
          return MarkerSeverity2.Hint;
      }
    }
    MarkerSeverity2.fromSeverity = fromSeverity;
    function toSeverity(severity) {
      switch (severity) {
        case MarkerSeverity2.Error:
          return Severity$2.Error;
        case MarkerSeverity2.Warning:
          return Severity$2.Warning;
        case MarkerSeverity2.Info:
          return Severity$2.Info;
        case MarkerSeverity2.Hint:
          return Severity$2.Ignore;
      }
    }
    MarkerSeverity2.toSeverity = toSeverity;
  })(MarkerSeverity$2 || (MarkerSeverity$2 = {}));
  var IMarkerData;
  (function(IMarkerData2) {
    const emptyString = "";
    function makeKey(markerData) {
      return makeKeyOptionalMessage(markerData, true);
    }
    IMarkerData2.makeKey = makeKey;
    function makeKeyOptionalMessage(markerData, useMessage) {
      const result = [emptyString];
      if (markerData.source) {
        result.push(markerData.source.replace("¦", "\\¦"));
      } else {
        result.push(emptyString);
      }
      if (markerData.code) {
        if (typeof markerData.code === "string") {
          result.push(markerData.code.replace("¦", "\\¦"));
        } else {
          result.push(markerData.code.value.replace("¦", "\\¦"));
        }
      } else {
        result.push(emptyString);
      }
      if (markerData.severity !== void 0 && markerData.severity !== null) {
        result.push(MarkerSeverity$2.toString(markerData.severity));
      } else {
        result.push(emptyString);
      }
      if (markerData.message && useMessage) {
        result.push(markerData.message.replace("¦", "\\¦"));
      } else {
        result.push(emptyString);
      }
      if (markerData.startLineNumber !== void 0 && markerData.startLineNumber !== null) {
        result.push(markerData.startLineNumber.toString());
      } else {
        result.push(emptyString);
      }
      if (markerData.startColumn !== void 0 && markerData.startColumn !== null) {
        result.push(markerData.startColumn.toString());
      } else {
        result.push(emptyString);
      }
      if (markerData.endLineNumber !== void 0 && markerData.endLineNumber !== null) {
        result.push(markerData.endLineNumber.toString());
      } else {
        result.push(emptyString);
      }
      if (markerData.endColumn !== void 0 && markerData.endColumn !== null) {
        result.push(markerData.endColumn.toString());
      } else {
        result.push(emptyString);
      }
      result.push(emptyString);
      return result.join("¦");
    }
    IMarkerData2.makeKeyOptionalMessage = makeKeyOptionalMessage;
  })(IMarkerData || (IMarkerData = {}));
  const IMarkerService = createDecorator("markerService");
  var __decorate$2j = 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$2h = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  var CodeActionKeybindingResolver_1;
  let CodeActionKeybindingResolver = (_t = class {
    constructor(keybindingService) {
      this.keybindingService = keybindingService;
    }
    getResolver() {
      const allCodeActionBindings = new Lazy(() => this.keybindingService.getKeybindings().filter((item) => CodeActionKeybindingResolver_1.codeActionCommands.indexOf(item.command) >= 0).filter((item) => item.resolvedKeybinding).map((item) => {
        let commandArgs = item.commandArgs;
        if (item.command === organizeImportsCommandId) {
          commandArgs = { kind: CodeActionKind.SourceOrganizeImports.value };
        } else if (item.command === fixAllCommandId) {
          commandArgs = { kind: CodeActionKind.SourceFixAll.value };
        }
        return {
          resolvedKeybinding: item.resolvedKeybinding,
          ...CodeActionCommandArgs.fromUser(commandArgs, {
            kind: HierarchicalKind.None,
            apply: "never"
            /* CodeActionAutoApply.Never */
          })
        };
      }));
      return (action) => {
        if (action.kind) {
          const binding = this.bestKeybindingForCodeAction(action, allCodeActionBindings.value);
          return binding?.resolvedKeybinding;
        }
        return void 0;
      };
    }
    bestKeybindingForCodeAction(action, candidates) {
      if (!action.kind) {
        return void 0;
      }
      const kind = new HierarchicalKind(action.kind);
      return candidates.filter((candidate) => candidate.kind.contains(kind)).filter((candidate) => {
        if (candidate.preferred) {
          return action.isPreferred;
        }
        return true;
      }).reduceRight((currentBest, candidate) => {
        if (!currentBest) {
          return candidate;
        }
        return currentBest.kind.contains(candidate.kind) ? candidate : currentBest;
      }, void 0);
    }
  }, CodeActionKeybindingResolver_1 = _t, _t.codeActionCommands = [
    refactorCommandId,
    codeActionCommandId,
    sourceActionCommandId,
    organizeImportsCommandId,
    fixAllCommandId
  ], _t);
  CodeActionKeybindingResolver = CodeActionKeybindingResolver_1 = __decorate$2j([
    __param$2h(0, IKeybindingService)
  ], CodeActionKeybindingResolver);
  registerColor("symbolIcon.arrayForeground", foreground, localize(1495, "The foreground color for array symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));
  registerColor("symbolIcon.booleanForeground", foreground, localize(1496, "The foreground color for boolean symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));
  registerColor("symbolIcon.classForeground", {
    dark: "#EE9D28",
    light: "#D67E00",
    hcDark: "#EE9D28",
    hcLight: "#D67E00"
  }, localize(1497, "The foreground color for class symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));
  registerColor("symbolIcon.colorForeground", foreground, localize(1498, "The foreground color for color symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));
  registerColor("symbolIcon.constantForeground", foreground, localize(1499, "The foreground color for constant symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));
  registerColor("symbolIcon.constructorForeground", {
    dark: "#B180D7",
    light: "#652D90",
    hcDark: "#B180D7",
    hcLight: "#652D90"
  }, localize(1500, "The foreground color for constructor symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));
  registerColor("symbolIcon.enumeratorForeground", {
    dark: "#EE9D28",
    light: "#D67E00",
    hcDark: "#EE9D28",
    hcLight: "#D67E00"
  }, localize(1501, "The foreground color for enumerator symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));
  registerColor("symbolIcon.enumeratorMemberForeground", {
    dark: "#75BEFF",
    light: "#007ACC",
    hcDark: "#75BEFF",
    hcLight: "#007ACC"
  }, localize(1502, "The foreground color for enumerator member symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));
  registerColor("symbolIcon.eventForeground", {
    dark: "#EE9D28",
    light: "#D67E00",
    hcDark: "#EE9D28",
    hcLight: "#D67E00"
  }, localize(1503, "The foreground color for event symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));
  registerColor("symbolIcon.fieldForeground", {
    dark: "#75BEFF",
    light: "#007ACC",
    hcDark: "#75BEFF",
    hcLight: "#007ACC"
  }, localize(1504, "The foreground color for field symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));
  registerColor("symbolIcon.fileForeground", foreground, localize(1505, "The foreground color for file symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));
  registerColor("symbolIcon.folderForeground", foreground, localize(1506, "The foreground color for folder symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));
  registerColor("symbolIcon.functionForeground", {
    dark: "#B180D7",
    light: "#652D90",
    hcDark: "#B180D7",
    hcLight: "#652D90"
  }, localize(1507, "The foreground color for function symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));
  registerColor("symbolIcon.interfaceForeground", {
    dark: "#75BEFF",
    light: "#007ACC",
    hcDark: "#75BEFF",
    hcLight: "#007ACC"
  }, localize(1508, "The foreground color for interface symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));
  registerColor("symbolIcon.keyForeground", foreground, localize(1509, "The foreground color for key symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));
  registerColor("symbolIcon.keywordForeground", foreground, localize(1510, "The foreground color for keyword symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));
  registerColor("symbolIcon.methodForeground", {
    dark: "#B180D7",
    light: "#652D90",
    hcDark: "#B180D7",
    hcLight: "#652D90"
  }, localize(1511, "The foreground color for method symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));
  registerColor("symbolIcon.moduleForeground", foreground, localize(1512, "The foreground color for module symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));
  registerColor("symbolIcon.namespaceForeground", foreground, localize(1513, "The foreground color for namespace symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));
  registerColor("symbolIcon.nullForeground", foreground, localize(1514, "The foreground color for null symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));
  registerColor("symbolIcon.numberForeground", foreground, localize(1515, "The foreground color for number symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));
  registerColor("symbolIcon.objectForeground", foreground, localize(1516, "The foreground color for object symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));
  registerColor("symbolIcon.operatorForeground", foreground, localize(1517, "The foreground color for operator symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));
  registerColor("symbolIcon.packageForeground", foreground, localize(1518, "The foreground color for package symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));
  registerColor("symbolIcon.propertyForeground", foreground, localize(1519, "The foreground color for property symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));
  registerColor("symbolIcon.referenceForeground", foreground, localize(1520, "The foreground color for reference symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));
  registerColor("symbolIcon.snippetForeground", foreground, localize(1521, "The foreground color for snippet symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));
  registerColor("symbolIcon.stringForeground", foreground, localize(1522, "The foreground color for string symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));
  registerColor("symbolIcon.structForeground", foreground, localize(1523, "The foreground color for struct symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));
  registerColor("symbolIcon.textForeground", foreground, localize(1524, "The foreground color for text symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));
  registerColor("symbolIcon.typeParameterForeground", foreground, localize(1525, "The foreground color for type parameter symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));
  registerColor("symbolIcon.unitForeground", foreground, localize(1526, "The foreground color for unit symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));
  registerColor("symbolIcon.variableForeground", {
    dark: "#75BEFF",
    light: "#007ACC",
    hcDark: "#75BEFF",
    hcLight: "#007ACC"
  }, localize(1527, "The foreground color for variable symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));
  const uncategorizedCodeActionGroup = Object.freeze({ kind: HierarchicalKind.Empty, title: localize(866, "More Actions...") });
  const codeActionGroups = Object.freeze([
    { kind: CodeActionKind.QuickFix, title: localize(867, "Quick Fix") },
    { kind: CodeActionKind.RefactorExtract, title: localize(868, "Extract"), icon: Codicon.wrench },
    { kind: CodeActionKind.RefactorInline, title: localize(869, "Inline"), icon: Codicon.wrench },
    { kind: CodeActionKind.RefactorRewrite, title: localize(870, "Rewrite"), icon: Codicon.wrench },
    { kind: CodeActionKind.RefactorMove, title: localize(871, "Move"), icon: Codicon.wrench },
    { kind: CodeActionKind.SurroundWith, title: localize(872, "Surround With"), icon: Codicon.surroundWith },
    { kind: CodeActionKind.Source, title: localize(873, "Source Action"), icon: Codicon.symbolFile },
    uncategorizedCodeActionGroup
  ]);
  function toMenuItems(inputCodeActions, showHeaders, keybindingResolver) {
    if (!showHeaders) {
      return inputCodeActions.map((action) => {
        return {
          kind: "action",
          item: action,
          group: uncategorizedCodeActionGroup,
          disabled: !!action.action.disabled,
          label: action.action.disabled || action.action.title,
          canPreview: !!action.action.edit?.edits.length
        };
      });
    }
    const menuEntries = codeActionGroups.map((group) => ({ group, actions: [] }));
    for (const action of inputCodeActions) {
      const kind = action.action.kind ? new HierarchicalKind(action.action.kind) : HierarchicalKind.None;
      for (const menuEntry of menuEntries) {
        if (menuEntry.group.kind.contains(kind)) {
          menuEntry.actions.push(action);
          break;
        }
      }
    }
    const allMenuItems = [];
    for (const menuEntry of menuEntries) {
      if (menuEntry.actions.length) {
        allMenuItems.push({ kind: "header", group: menuEntry.group });
        for (const action of menuEntry.actions) {
          const group = menuEntry.group;
          allMenuItems.push({
            kind: "action",
            item: action,
            group: action.action.isAI ? { title: group.title, kind: group.kind, icon: Codicon.sparkle } : group,
            label: action.action.title,
            disabled: !!action.action.disabled,
            keybinding: keybindingResolver(action.action)
          });
        }
      }
    }
    return allMenuItems;
  }
  const SUPPORTED_CODE_ACTIONS = new RawContextKey("supportedCodeAction", "");
  const APPLY_FIX_ALL_COMMAND_ID = "_typescript.applyFixAllCodeAction";
  class CodeActionOracle extends Disposable {
    constructor(_editor, _markerService, _signalChange, _delay = 250) {
      super();
      this._editor = _editor;
      this._markerService = _markerService;
      this._signalChange = _signalChange;
      this._delay = _delay;
      this._autoTriggerTimer = this._register(new TimeoutTimer());
      this._register(this._markerService.onMarkerChanged((e) => this._onMarkerChanges(e)));
      this._register(this._editor.onDidChangeCursorPosition(() => this._tryAutoTrigger()));
    }
    trigger(trigger) {
      const selection = this._getRangeOfSelectionUnlessWhitespaceEnclosed(trigger);
      this._signalChange(selection ? { trigger, selection } : void 0);
    }
    _onMarkerChanges(resources) {
      const model = this._editor.getModel();
      if (model && resources.some((resource) => isEqual(resource, model.uri))) {
        this._tryAutoTrigger();
      }
    }
    _tryAutoTrigger() {
      this._autoTriggerTimer.cancelAndSet(() => {
        this.trigger({ type: 2, triggerAction: CodeActionTriggerSource.Default });
      }, this._delay);
    }
    _getRangeOfSelectionUnlessWhitespaceEnclosed(trigger) {
      if (!this._editor.hasModel()) {
        return void 0;
      }
      const selection = this._editor.getSelection();
      if (trigger.type === 1) {
        return selection;
      }
      const enabled = this._editor.getOption(
        73
        /* EditorOption.lightbulb */
      ).enabled;
      if (enabled === ShowLightbulbIconMode$1.Off) {
        return void 0;
      } else if (enabled === ShowLightbulbIconMode$1.On) {
        return selection;
      } else if (enabled === ShowLightbulbIconMode$1.OnCode) {
        const isSelectionEmpty = selection.isEmpty();
        if (!isSelectionEmpty) {
          return selection;
        }
        const model = this._editor.getModel();
        const { lineNumber, column } = selection.getPosition();
        const line = model.getLineContent(lineNumber);
        if (line.length === 0) {
          return void 0;
        } else if (column === 1) {
          if (/\s/.test(line[0])) {
            return void 0;
          }
        } else if (column === model.getLineMaxColumn(lineNumber)) {
          if (/\s/.test(line[line.length - 1])) {
            return void 0;
          }
        } else {
          if (/\s/.test(line[column - 2]) && /\s/.test(line[column - 1])) {
            return void 0;
          }
        }
      }
      return selection;
    }
  }
  var CodeActionsState;
  (function(CodeActionsState2) {
    CodeActionsState2.Empty = {
      type: 0
      /* Type.Empty */
    };
    class Triggered {
      constructor(trigger, position, _cancellablePromise) {
        this.trigger = trigger;
        this.position = position;
        this._cancellablePromise = _cancellablePromise;
        this.type = 1;
        this.actions = _cancellablePromise.catch((e) => {
          if (isCancellationError(e)) {
            return emptyCodeActionSet;
          }
          throw e;
        });
      }
      cancel() {
        this._cancellablePromise.cancel();
      }
    }
    CodeActionsState2.Triggered = Triggered;
  })(CodeActionsState || (CodeActionsState = {}));
  const emptyCodeActionSet = Object.freeze({
    allActions: [],
    validActions: [],
    dispose: () => {
    },
    documentation: [],
    hasAutoFix: false,
    hasAIFix: false,
    allAIFixes: false
  });
  class CodeActionModel extends Disposable {
    constructor(_editor, _registry2, _markerService, contextKeyService, _progressService, _configurationService) {
      super();
      this._editor = _editor;
      this._registry = _registry2;
      this._markerService = _markerService;
      this._progressService = _progressService;
      this._configurationService = _configurationService;
      this._codeActionOracle = this._register(new MutableDisposable());
      this._state = CodeActionsState.Empty;
      this._onDidChangeState = this._register(new Emitter$1());
      this.onDidChangeState = this._onDidChangeState.event;
      this.codeActionsDisposable = this._register(new MutableDisposable());
      this._disposed = false;
      this._supportedCodeActions = SUPPORTED_CODE_ACTIONS.bindTo(contextKeyService);
      this._register(this._editor.onDidChangeModel(() => this._update()));
      this._register(this._editor.onDidChangeModelLanguage(() => this._update()));
      this._register(this._registry.onDidChange(() => this._update()));
      this._register(this._editor.onDidChangeConfiguration((e) => {
        if (e.hasChanged(
          73
          /* EditorOption.lightbulb */
        )) {
          this._update();
        }
      }));
      this._update();
    }
    dispose() {
      if (this._disposed) {
        return;
      }
      this._disposed = true;
      super.dispose();
      this.setState(CodeActionsState.Empty, true);
    }
    _settingEnabledNearbyQuickfixes() {
      const model = this._editor?.getModel();
      return this._configurationService ? this._configurationService.getValue("editor.codeActionWidget.includeNearbyQuickFixes", { resource: model?.uri }) : false;
    }
    _update() {
      if (this._disposed) {
        return;
      }
      this._codeActionOracle.value = void 0;
      this.setState(CodeActionsState.Empty);
      const model = this._editor.getModel();
      if (model && this._registry.has(model) && !this._editor.getOption(
        104
        /* EditorOption.readOnly */
      )) {
        const supportedActions = this._registry.all(model).flatMap((provider) => provider.providedCodeActionKinds ?? []);
        this._supportedCodeActions.set(supportedActions.join(" "));
        this._codeActionOracle.value = new CodeActionOracle(this._editor, this._markerService, (trigger) => {
          if (!trigger) {
            this.setState(CodeActionsState.Empty);
            return;
          }
          const startPosition = trigger.selection.getStartPosition();
          const actions = createCancelablePromise(async (token) => {
            if (this._settingEnabledNearbyQuickfixes() && trigger.trigger.type === 1 && (trigger.trigger.triggerAction === CodeActionTriggerSource.QuickFix || trigger.trigger.filter?.include?.contains(CodeActionKind.QuickFix))) {
              const codeActionSet2 = await getCodeActions(this._registry, model, trigger.selection, trigger.trigger, Progress.None, token);
              this.codeActionsDisposable.value = codeActionSet2;
              const allCodeActions = [...codeActionSet2.allActions];
              if (token.isCancellationRequested) {
                codeActionSet2.dispose();
                return emptyCodeActionSet;
              }
              const foundQuickfix = codeActionSet2.validActions?.some((action) => {
                return action.action.kind && CodeActionKind.QuickFix.contains(new HierarchicalKind(action.action.kind)) && !action.action.isAI;
              });
              const allMarkers = this._markerService.read({ resource: model.uri });
              if (foundQuickfix) {
                for (const action of codeActionSet2.validActions) {
                  if (action.action.command?.arguments?.some((arg) => typeof arg === "string" && arg.includes(APPLY_FIX_ALL_COMMAND_ID))) {
                    action.action.diagnostics = [...allMarkers.filter((marker) => marker.relatedInformation)];
                  }
                }
                return { validActions: codeActionSet2.validActions, allActions: allCodeActions, documentation: codeActionSet2.documentation, hasAutoFix: codeActionSet2.hasAutoFix, hasAIFix: codeActionSet2.hasAIFix, allAIFixes: codeActionSet2.allAIFixes, dispose: () => {
                  this.codeActionsDisposable.value = codeActionSet2;
                } };
              } else if (!foundQuickfix) {
                if (allMarkers.length > 0) {
                  const currPosition = trigger.selection.getPosition();
                  let trackedPosition = currPosition;
                  let distance = Number.MAX_VALUE;
                  const currentActions = [...codeActionSet2.validActions];
                  for (const marker of allMarkers) {
                    const col = marker.endColumn;
                    const row = marker.endLineNumber;
                    const startRow = marker.startLineNumber;
                    if (row === currPosition.lineNumber || startRow === currPosition.lineNumber) {
                      trackedPosition = new Position$1(row, col);
                      const newCodeActionTrigger = {
                        type: trigger.trigger.type,
                        triggerAction: trigger.trigger.triggerAction,
                        filter: { include: trigger.trigger.filter?.include ? trigger.trigger.filter?.include : CodeActionKind.QuickFix },
                        autoApply: trigger.trigger.autoApply,
                        context: { notAvailableMessage: trigger.trigger.context?.notAvailableMessage || "", position: trackedPosition }
                      };
                      const selectionAsPosition = new Selection$1(trackedPosition.lineNumber, trackedPosition.column, trackedPosition.lineNumber, trackedPosition.column);
                      const actionsAtMarker = await getCodeActions(this._registry, model, selectionAsPosition, newCodeActionTrigger, Progress.None, token);
                      if (token.isCancellationRequested) {
                        actionsAtMarker.dispose();
                        return emptyCodeActionSet;
                      }
                      if (actionsAtMarker.validActions.length !== 0) {
                        for (const action of actionsAtMarker.validActions) {
                          if (action.action.command?.arguments?.some((arg) => typeof arg === "string" && arg.includes(APPLY_FIX_ALL_COMMAND_ID))) {
                            action.action.diagnostics = [...allMarkers.filter((marker2) => marker2.relatedInformation)];
                          }
                        }
                        if (codeActionSet2.allActions.length === 0) {
                          allCodeActions.push(...actionsAtMarker.allActions);
                        }
                        if (Math.abs(currPosition.column - col) < distance) {
                          currentActions.unshift(...actionsAtMarker.validActions);
                        } else {
                          currentActions.push(...actionsAtMarker.validActions);
                        }
                      }
                      distance = Math.abs(currPosition.column - col);
                    }
                  }
                  const filteredActions = currentActions.filter((action, index, self2) => self2.findIndex((a) => a.action.title === action.action.title) === index);
                  filteredActions.sort((a, b) => {
                    if (a.action.isPreferred && !b.action.isPreferred) {
                      return -1;
                    } else if (!a.action.isPreferred && b.action.isPreferred) {
                      return 1;
                    } else if (a.action.isAI && !b.action.isAI) {
                      return 1;
                    } else if (!a.action.isAI && b.action.isAI) {
                      return -1;
                    } else {
                      return 0;
                    }
                  });
                  return { validActions: filteredActions, allActions: allCodeActions, documentation: codeActionSet2.documentation, hasAutoFix: codeActionSet2.hasAutoFix, hasAIFix: codeActionSet2.hasAIFix, allAIFixes: codeActionSet2.allAIFixes, dispose: () => {
                    this.codeActionsDisposable.value = codeActionSet2;
                  } };
                }
              }
            }
            if (trigger.trigger.type === 1) {
              const codeActions = await getCodeActions(this._registry, model, trigger.selection, trigger.trigger, Progress.None, token);
              this.codeActionsDisposable.value = codeActions;
              return codeActions;
            }
            const codeActionSet = await getCodeActions(this._registry, model, trigger.selection, trigger.trigger, Progress.None, token);
            this.codeActionsDisposable.value = codeActionSet;
            return codeActionSet;
          });
          if (trigger.trigger.type === 1) {
            this._progressService?.showWhile(actions, 250);
          }
          const newState = new CodeActionsState.Triggered(trigger.trigger, startPosition, actions);
          let isManualToAutoTransition = false;
          if (this._state.type === 1) {
            isManualToAutoTransition = this._state.trigger.type === 1 && newState.type === 1 && newState.trigger.type === 2 && this._state.position !== newState.position;
          }
          if (!isManualToAutoTransition) {
            this.setState(newState);
          } else {
            setTimeout(() => {
              this.setState(newState);
            }, 500);
          }
        }, void 0);
        this._codeActionOracle.value.trigger({ type: 2, triggerAction: CodeActionTriggerSource.Default });
      } else {
        this._supportedCodeActions.reset();
      }
    }
    trigger(trigger) {
      this._codeActionOracle.value?.trigger(trigger);
      this.codeActionsDisposable.dispose();
    }
    setState(newState, skipNotify) {
      if (newState === this._state) {
        return;
      }
      if (this._state.type === 1) {
        this._state.cancel();
      }
      this._state = newState;
      if (!skipNotify && !this._disposed) {
        this._onDidChangeState.fire(newState);
      }
    }
  }
  var __decorate$2i = 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$2g = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  var LightBulbWidget_1;
  const GUTTER_LIGHTBULB_ICON = registerIcon("gutter-lightbulb", Codicon.lightBulb, localize(874, "Icon which spawns code actions menu from the gutter when there is no space in the editor."));
  const GUTTER_LIGHTBULB_AUTO_FIX_ICON = registerIcon("gutter-lightbulb-auto-fix", Codicon.lightbulbAutofix, localize(875, "Icon which spawns code actions menu from the gutter when there is no space in the editor and a quick fix is available."));
  const GUTTER_LIGHTBULB_AIFIX_ICON = registerIcon("gutter-lightbulb-sparkle", Codicon.lightbulbSparkle, localize(876, "Icon which spawns code actions menu from the gutter when there is no space in the editor and an AI fix is available."));
  const GUTTER_LIGHTBULB_AIFIX_AUTO_FIX_ICON = registerIcon("gutter-lightbulb-aifix-auto-fix", Codicon.lightbulbSparkleAutofix, localize(877, "Icon which spawns code actions menu from the gutter when there is no space in the editor and an AI fix and a quick fix is available."));
  const GUTTER_SPARKLE_FILLED_ICON = registerIcon("gutter-lightbulb-sparkle-filled", Codicon.sparkleFilled, localize(878, "Icon which spawns code actions menu from the gutter when there is no space in the editor and an AI fix and a quick fix is available."));
  var LightBulbState;
  (function(LightBulbState2) {
    LightBulbState2.Hidden = {
      type: 0
      /* Type.Hidden */
    };
    class Showing {
      constructor(actions, trigger, editorPosition, widgetPosition) {
        this.actions = actions;
        this.trigger = trigger;
        this.editorPosition = editorPosition;
        this.widgetPosition = widgetPosition;
        this.type = 1;
      }
    }
    LightBulbState2.Showing = Showing;
  })(LightBulbState || (LightBulbState = {}));
  let LightBulbWidget = (_u = class extends Disposable {
    constructor(_editor, _keybindingService) {
      super();
      this._editor = _editor;
      this._keybindingService = _keybindingService;
      this._onClick = this._register(new Emitter$1());
      this.onClick = this._onClick.event;
      this._state = LightBulbState.Hidden;
      this._gutterState = LightBulbState.Hidden;
      this._iconClasses = [];
      this.lightbulbClasses = [
        "codicon-" + GUTTER_LIGHTBULB_ICON.id,
        "codicon-" + GUTTER_LIGHTBULB_AIFIX_AUTO_FIX_ICON.id,
        "codicon-" + GUTTER_LIGHTBULB_AUTO_FIX_ICON.id,
        "codicon-" + GUTTER_LIGHTBULB_AIFIX_ICON.id,
        "codicon-" + GUTTER_SPARKLE_FILLED_ICON.id
      ];
      this.gutterDecoration = LightBulbWidget_1.GUTTER_DECORATION;
      this._domNode = $$l("div.lightBulbWidget");
      this._domNode.role = "listbox";
      this._register(Gesture.ignoreTarget(this._domNode));
      this._editor.addContentWidget(this);
      this._register(this._editor.onDidChangeModelContent((_) => {
        const editorModel = this._editor.getModel();
        if (this.state.type !== 1 || !editorModel || this.state.editorPosition.lineNumber >= editorModel.getLineCount()) {
          this.hide();
        }
        if (this.gutterState.type !== 1 || !editorModel || this.gutterState.editorPosition.lineNumber >= editorModel.getLineCount()) {
          this.gutterHide();
        }
      }));
      this._register(addStandardDisposableGenericMouseDownListener(this._domNode, (e) => {
        if (this.state.type !== 1) {
          return;
        }
        this._editor.focus();
        e.preventDefault();
        const { top, height } = getDomNodePagePosition(this._domNode);
        const lineHeight = this._editor.getOption(
          75
          /* EditorOption.lineHeight */
        );
        let pad = Math.floor(lineHeight / 3);
        if (this.state.widgetPosition.position !== null && this.state.widgetPosition.position.lineNumber < this.state.editorPosition.lineNumber) {
          pad += lineHeight;
        }
        this._onClick.fire({
          x: e.posx,
          y: top + height + pad,
          actions: this.state.actions,
          trigger: this.state.trigger
        });
      }));
      this._register(addDisposableListener(this._domNode, "mouseenter", (e) => {
        if ((e.buttons & 1) !== 1) {
          return;
        }
        this.hide();
      }));
      this._register(Event.runAndSubscribe(this._keybindingService.onDidUpdateKeybindings, () => {
        this._preferredKbLabel = this._keybindingService.lookupKeybinding(autoFixCommandId)?.getLabel() ?? void 0;
        this._quickFixKbLabel = this._keybindingService.lookupKeybinding(quickFixCommandId)?.getLabel() ?? void 0;
        this._updateLightBulbTitleAndIcon();
      }));
      this._register(this._editor.onMouseDown(async (e) => {
        if (!e.target.element || !this.lightbulbClasses.some((cls) => e.target.element && e.target.element.classList.contains(cls))) {
          return;
        }
        if (this.gutterState.type !== 1) {
          return;
        }
        this._editor.focus();
        const { top, height } = getDomNodePagePosition(e.target.element);
        const lineHeight = this._editor.getOption(
          75
          /* EditorOption.lineHeight */
        );
        let pad = Math.floor(lineHeight / 3);
        if (this.gutterState.widgetPosition.position !== null && this.gutterState.widgetPosition.position.lineNumber < this.gutterState.editorPosition.lineNumber) {
          pad += lineHeight;
        }
        this._onClick.fire({
          x: e.event.posx,
          y: top + height + pad,
          actions: this.gutterState.actions,
          trigger: this.gutterState.trigger
        });
      }));
    }
    dispose() {
      super.dispose();
      this._editor.removeContentWidget(this);
      if (this._gutterDecorationID) {
        this._removeGutterDecoration(this._gutterDecorationID);
      }
    }
    getId() {
      return "LightBulbWidget";
    }
    getDomNode() {
      return this._domNode;
    }
    getPosition() {
      return this._state.type === 1 ? this._state.widgetPosition : null;
    }
    update(actions, trigger, atPosition) {
      if (actions.validActions.length <= 0) {
        this.gutterHide();
        return this.hide();
      }
      const hasTextFocus = this._editor.hasTextFocus();
      if (!hasTextFocus) {
        this.gutterHide();
        return this.hide();
      }
      const options = this._editor.getOptions();
      if (!options.get(
        73
        /* EditorOption.lightbulb */
      ).enabled) {
        this.gutterHide();
        return this.hide();
      }
      const model = this._editor.getModel();
      if (!model) {
        this.gutterHide();
        return this.hide();
      }
      const { lineNumber, column } = model.validatePosition(atPosition);
      const tabSize = model.getOptions().tabSize;
      const fontInfo = this._editor.getOptions().get(
        59
        /* EditorOption.fontInfo */
      );
      const lineContent = model.getLineContent(lineNumber);
      const indent = computeIndentLevel(lineContent, tabSize);
      const lineHasSpace = fontInfo.spaceWidth * indent > 22;
      const isFolded = (lineNumber2) => {
        return lineNumber2 > 2 && this._editor.getTopForLineNumber(lineNumber2) === this._editor.getTopForLineNumber(lineNumber2 - 1);
      };
      const currLineDecorations = this._editor.getLineDecorations(lineNumber);
      let hasDecoration = false;
      if (currLineDecorations) {
        for (const decoration2 of currLineDecorations) {
          const glyphClass = decoration2.options.glyphMarginClassName;
          if (glyphClass && !this.lightbulbClasses.some((className2) => glyphClass.includes(className2))) {
            hasDecoration = true;
            break;
          }
        }
      }
      let effectiveLineNumber = lineNumber;
      let effectiveColumnNumber = 1;
      if (!lineHasSpace) {
        const isLineEmptyOrIndented = (lineNumber2) => {
          const lineContent2 = model.getLineContent(lineNumber2);
          return /^\s*$|^\s+/.test(lineContent2) || lineContent2.length <= effectiveColumnNumber;
        };
        if (lineNumber > 1 && !isFolded(lineNumber - 1)) {
          const lineCount = model.getLineCount();
          const endLine = lineNumber === lineCount;
          const prevLineEmptyOrIndented = lineNumber > 1 && isLineEmptyOrIndented(lineNumber - 1);
          const nextLineEmptyOrIndented = !endLine && isLineEmptyOrIndented(lineNumber + 1);
          const currLineEmptyOrIndented = isLineEmptyOrIndented(lineNumber);
          const notEmpty = !nextLineEmptyOrIndented && !prevLineEmptyOrIndented;
          if (!nextLineEmptyOrIndented && !prevLineEmptyOrIndented && !hasDecoration) {
            this.gutterState = new LightBulbState.Showing(actions, trigger, atPosition, {
              position: { lineNumber: effectiveLineNumber, column: effectiveColumnNumber },
              preference: LightBulbWidget_1._posPref
            });
            this.renderGutterLightbub();
            return this.hide();
          } else if (prevLineEmptyOrIndented || endLine || prevLineEmptyOrIndented && !currLineEmptyOrIndented) {
            effectiveLineNumber -= 1;
          } else if (nextLineEmptyOrIndented || notEmpty && currLineEmptyOrIndented) {
            effectiveLineNumber += 1;
          }
        } else if (lineNumber === 1 && (lineNumber === model.getLineCount() || !isLineEmptyOrIndented(lineNumber + 1) && !isLineEmptyOrIndented(lineNumber))) {
          this.gutterState = new LightBulbState.Showing(actions, trigger, atPosition, {
            position: { lineNumber: effectiveLineNumber, column: effectiveColumnNumber },
            preference: LightBulbWidget_1._posPref
          });
          if (hasDecoration) {
            this.gutterHide();
          } else {
            this.renderGutterLightbub();
            return this.hide();
          }
        } else if (lineNumber < model.getLineCount() && !isFolded(lineNumber + 1)) {
          effectiveLineNumber += 1;
        } else if (column * fontInfo.spaceWidth < 22) {
          return this.hide();
        }
        effectiveColumnNumber = /^\S\s*$/.test(model.getLineContent(effectiveLineNumber)) ? 2 : 1;
      }
      this.state = new LightBulbState.Showing(actions, trigger, atPosition, {
        position: { lineNumber: effectiveLineNumber, column: effectiveColumnNumber },
        preference: LightBulbWidget_1._posPref
      });
      if (this._gutterDecorationID) {
        this._removeGutterDecoration(this._gutterDecorationID);
        this.gutterHide();
      }
      const validActions = actions.validActions;
      const actionKind = actions.validActions[0].action.kind;
      if (validActions.length !== 1 || !actionKind) {
        this._editor.layoutContentWidget(this);
        return;
      }
      this._editor.layoutContentWidget(this);
    }
    hide() {
      if (this.state === LightBulbState.Hidden) {
        return;
      }
      this.state = LightBulbState.Hidden;
      this._editor.layoutContentWidget(this);
    }
    gutterHide() {
      if (this.gutterState === LightBulbState.Hidden) {
        return;
      }
      if (this._gutterDecorationID) {
        this._removeGutterDecoration(this._gutterDecorationID);
      }
      this.gutterState = LightBulbState.Hidden;
    }
    get state() {
      return this._state;
    }
    set state(value) {
      this._state = value;
      this._updateLightBulbTitleAndIcon();
    }
    get gutterState() {
      return this._gutterState;
    }
    set gutterState(value) {
      this._gutterState = value;
      this._updateGutterLightBulbTitleAndIcon();
    }
    _updateLightBulbTitleAndIcon() {
      this._domNode.classList.remove(...this._iconClasses);
      this._iconClasses = [];
      if (this.state.type !== 1) {
        return;
      }
      let icon;
      let autoRun = false;
      if (this.state.actions.allAIFixes) {
        icon = Codicon.sparkleFilled;
        if (this.state.actions.validActions.length === 1) {
          autoRun = true;
        }
      } else if (this.state.actions.hasAutoFix) {
        if (this.state.actions.hasAIFix) {
          icon = Codicon.lightbulbSparkleAutofix;
        } else {
          icon = Codicon.lightbulbAutofix;
        }
      } else if (this.state.actions.hasAIFix) {
        icon = Codicon.lightbulbSparkle;
      } else {
        icon = Codicon.lightBulb;
      }
      this._updateLightbulbTitle(this.state.actions.hasAutoFix, autoRun);
      this._iconClasses = ThemeIcon.asClassNameArray(icon);
      this._domNode.classList.add(...this._iconClasses);
    }
    _updateGutterLightBulbTitleAndIcon() {
      if (this.gutterState.type !== 1) {
        return;
      }
      let icon;
      let autoRun = false;
      if (this.gutterState.actions.allAIFixes) {
        icon = GUTTER_SPARKLE_FILLED_ICON;
        if (this.gutterState.actions.validActions.length === 1) {
          autoRun = true;
        }
      } else if (this.gutterState.actions.hasAutoFix) {
        if (this.gutterState.actions.hasAIFix) {
          icon = GUTTER_LIGHTBULB_AIFIX_AUTO_FIX_ICON;
        } else {
          icon = GUTTER_LIGHTBULB_AUTO_FIX_ICON;
        }
      } else if (this.gutterState.actions.hasAIFix) {
        icon = GUTTER_LIGHTBULB_AIFIX_ICON;
      } else {
        icon = GUTTER_LIGHTBULB_ICON;
      }
      this._updateLightbulbTitle(this.gutterState.actions.hasAutoFix, autoRun);
      const GUTTER_DECORATION = ModelDecorationOptions.register({
        description: "codicon-gutter-lightbulb-decoration",
        glyphMarginClassName: ThemeIcon.asClassName(icon),
        glyphMargin: { position: GlyphMarginLane$1.Left },
        stickiness: 1
      });
      this.gutterDecoration = GUTTER_DECORATION;
    }
    /* Gutter Helper Functions */
    renderGutterLightbub() {
      const selection = this._editor.getSelection();
      if (!selection) {
        return;
      }
      if (this._gutterDecorationID === void 0) {
        this._addGutterDecoration(selection.startLineNumber);
      } else {
        this._updateGutterDecoration(this._gutterDecorationID, selection.startLineNumber);
      }
    }
    _addGutterDecoration(lineNumber) {
      this._editor.changeDecorations((accessor) => {
        this._gutterDecorationID = accessor.addDecoration(new Range$2(lineNumber, 0, lineNumber, 0), this.gutterDecoration);
      });
    }
    _removeGutterDecoration(decorationId) {
      this._editor.changeDecorations((accessor) => {
        accessor.removeDecoration(decorationId);
        this._gutterDecorationID = void 0;
      });
    }
    _updateGutterDecoration(decorationId, lineNumber) {
      this._editor.changeDecorations((accessor) => {
        accessor.changeDecoration(decorationId, new Range$2(lineNumber, 0, lineNumber, 0));
        accessor.changeDecorationOptions(decorationId, this.gutterDecoration);
      });
    }
    _updateLightbulbTitle(autoFix, autoRun) {
      if (this.state.type !== 1) {
        return;
      }
      if (autoRun) {
        this.title = localize(879, "Run: {0}", this.state.actions.validActions[0].action.title);
      } else if (autoFix && this._preferredKbLabel) {
        this.title = localize(880, "Show Code Actions. Preferred Quick Fix Available ({0})", this._preferredKbLabel);
      } else if (!autoFix && this._quickFixKbLabel) {
        this.title = localize(881, "Show Code Actions ({0})", this._quickFixKbLabel);
      } else if (!autoFix) {
        this.title = localize(882, "Show Code Actions");
      }
    }
    set title(value) {
      this._domNode.title = value;
    }
  }, LightBulbWidget_1 = _u, _u.GUTTER_DECORATION = ModelDecorationOptions.register({
    description: "codicon-gutter-lightbulb-decoration",
    glyphMarginClassName: ThemeIcon.asClassName(Codicon.lightBulb),
    glyphMargin: { position: GlyphMarginLane$1.Left },
    stickiness: 1
  }), _u.ID = "editor.contrib.lightbulbWidget", _u._posPref = [
    0
    /* ContentWidgetPositionPreference.EXACT */
  ], _u);
  LightBulbWidget = LightBulbWidget_1 = __decorate$2i([
    __param$2g(1, IKeybindingService)
  ], LightBulbWidget);
  var __decorate$2h = 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$2f = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  var CodeActionController_1;
  const DECORATION_CLASS_NAME$1 = "quickfix-edit-highlight";
  let CodeActionController = (_v = class extends Disposable {
    static get(editor2) {
      return editor2.getContribution(CodeActionController_1.ID);
    }
    constructor(editor2, markerService, contextKeyService, instantiationService, languageFeaturesService, progressService, _commandService, _configurationService, _actionWidgetService, _instantiationService, _progressService) {
      super();
      this._commandService = _commandService;
      this._configurationService = _configurationService;
      this._actionWidgetService = _actionWidgetService;
      this._instantiationService = _instantiationService;
      this._progressService = _progressService;
      this._activeCodeActions = this._register(new MutableDisposable());
      this._showDisabled = false;
      this._disposed = false;
      this._editor = editor2;
      this._model = this._register(new CodeActionModel(this._editor, languageFeaturesService.codeActionProvider, markerService, contextKeyService, progressService, _configurationService));
      this._register(this._model.onDidChangeState((newState) => this.update(newState)));
      this._lightBulbWidget = new Lazy(() => {
        const widget = this._editor.getContribution(LightBulbWidget.ID);
        if (widget) {
          this._register(widget.onClick((e) => this.showCodeActionsFromLightbulb(e.actions, e)));
        }
        return widget;
      });
      this._resolver = instantiationService.createInstance(CodeActionKeybindingResolver);
      this._register(this._editor.onDidLayoutChange(() => this._actionWidgetService.hide()));
    }
    dispose() {
      this._disposed = true;
      super.dispose();
    }
    async showCodeActionsFromLightbulb(actions, at) {
      if (actions.allAIFixes && actions.validActions.length === 1) {
        const actionItem = actions.validActions[0];
        const command = actionItem.action.command;
        if (command && command.id === "inlineChat.start") {
          if (command.arguments && command.arguments.length >= 1 && command.arguments[0]) {
            command.arguments[0] = { ...command.arguments[0], autoSend: false };
          }
        }
        await this.applyCodeAction(actionItem, false, false, ApplyCodeActionReason.FromAILightbulb);
        return;
      }
      await this.showCodeActionList(actions, at, { includeDisabledActions: false, fromLightbulb: true });
    }
    showCodeActions(_trigger, actions, at) {
      return this.showCodeActionList(actions, at, { includeDisabledActions: false, fromLightbulb: false });
    }
    manualTriggerAtCurrentPosition(notAvailableMessage, triggerAction, filter, autoApply) {
      if (!this._editor.hasModel()) {
        return;
      }
      MessageController.get(this._editor)?.closeMessage();
      const triggerPosition = this._editor.getPosition();
      this._trigger({ type: 1, triggerAction, filter, autoApply, context: { notAvailableMessage, position: triggerPosition } });
    }
    _trigger(trigger) {
      return this._model.trigger(trigger);
    }
    async applyCodeAction(action, retrigger, preview, actionReason) {
      const progress = this._progressService.show(true, 500);
      try {
        await this._instantiationService.invokeFunction(applyCodeAction, action, actionReason, { preview, editor: this._editor });
      } finally {
        if (retrigger) {
          this._trigger({ type: 2, triggerAction: CodeActionTriggerSource.QuickFix, filter: {} });
        }
        progress.done();
      }
    }
    hideLightBulbWidget() {
      this._lightBulbWidget.rawValue?.hide();
      this._lightBulbWidget.rawValue?.gutterHide();
    }
    async update(newState) {
      if (newState.type !== 1) {
        this.hideLightBulbWidget();
        return;
      }
      let actions;
      try {
        actions = await newState.actions;
      } catch (e) {
        onUnexpectedError(e);
        return;
      }
      if (this._disposed) {
        return;
      }
      const selection = this._editor.getSelection();
      if (selection?.startLineNumber !== newState.position.lineNumber) {
        return;
      }
      this._lightBulbWidget.value?.update(actions, newState.trigger, newState.position);
      if (newState.trigger.type === 1) {
        if (newState.trigger.filter?.include) {
          const validActionToApply = this.tryGetValidActionToApply(newState.trigger, actions);
          if (validActionToApply) {
            try {
              this.hideLightBulbWidget();
              await this.applyCodeAction(validActionToApply, false, false, ApplyCodeActionReason.FromCodeActions);
            } finally {
              actions.dispose();
            }
            return;
          }
          if (newState.trigger.context) {
            const invalidAction = this.getInvalidActionThatWouldHaveBeenApplied(newState.trigger, actions);
            if (invalidAction && invalidAction.action.disabled) {
              MessageController.get(this._editor)?.showMessage(invalidAction.action.disabled, newState.trigger.context.position);
              actions.dispose();
              return;
            }
          }
        }
        const includeDisabledActions = !!newState.trigger.filter?.include;
        if (newState.trigger.context) {
          if (!actions.allActions.length || !includeDisabledActions && !actions.validActions.length) {
            MessageController.get(this._editor)?.showMessage(newState.trigger.context.notAvailableMessage, newState.trigger.context.position);
            this._activeCodeActions.value = actions;
            actions.dispose();
            return;
          }
        }
        this._activeCodeActions.value = actions;
        this.showCodeActionList(actions, this.toCoords(newState.position), { includeDisabledActions, fromLightbulb: false });
      } else {
        if (this._actionWidgetService.isVisible) {
          actions.dispose();
        } else {
          this._activeCodeActions.value = actions;
        }
      }
    }
    getInvalidActionThatWouldHaveBeenApplied(trigger, actions) {
      if (!actions.allActions.length) {
        return void 0;
      }
      if (trigger.autoApply === "first" && actions.validActions.length === 0 || trigger.autoApply === "ifSingle" && actions.allActions.length === 1) {
        return actions.allActions.find(({ action }) => action.disabled);
      }
      return void 0;
    }
    tryGetValidActionToApply(trigger, actions) {
      if (!actions.validActions.length) {
        return void 0;
      }
      if (trigger.autoApply === "first" && actions.validActions.length > 0 || trigger.autoApply === "ifSingle" && actions.validActions.length === 1) {
        return actions.validActions[0];
      }
      return void 0;
    }
    async showCodeActionList(actions, at, options) {
      const currentDecorations = this._editor.createDecorationsCollection();
      const editorDom = this._editor.getDomNode();
      if (!editorDom) {
        return;
      }
      const actionsToShow = options.includeDisabledActions && (this._showDisabled || actions.validActions.length === 0) ? actions.allActions : actions.validActions;
      if (!actionsToShow.length) {
        return;
      }
      const anchor = Position$1.isIPosition(at) ? this.toCoords(at) : at;
      const delegate = {
        onSelect: async (action, preview) => {
          this.applyCodeAction(
            action,
            /* retrigger */
            true,
            !!preview,
            options.fromLightbulb ? ApplyCodeActionReason.FromAILightbulb : ApplyCodeActionReason.FromCodeActions
          );
          this._actionWidgetService.hide(false);
          currentDecorations.clear();
        },
        onHide: (didCancel) => {
          this._editor?.focus();
          currentDecorations.clear();
        },
        onHover: async (action, token) => {
          if (token.isCancellationRequested) {
            return;
          }
          let canPreview = false;
          const actionKind = action.action.kind;
          if (actionKind) {
            const hierarchicalKind = new HierarchicalKind(actionKind);
            const refactorKinds = [
              CodeActionKind.RefactorExtract,
              CodeActionKind.RefactorInline,
              CodeActionKind.RefactorRewrite,
              CodeActionKind.RefactorMove,
              CodeActionKind.Source
            ];
            canPreview = refactorKinds.some((refactorKind) => refactorKind.contains(hierarchicalKind));
          }
          return { canPreview: canPreview || !!action.action.edit?.edits.length };
        },
        onFocus: (action) => {
          if (action && action.action) {
            const ranges = action.action.ranges;
            const diagnostics = action.action.diagnostics;
            currentDecorations.clear();
            if (ranges && ranges.length > 0) {
              const decorations = diagnostics && diagnostics?.length > 1 ? diagnostics.map((diagnostic) => ({ range: diagnostic, options: CodeActionController_1.DECORATION })) : ranges.map((range2) => ({ range: range2, options: CodeActionController_1.DECORATION }));
              currentDecorations.set(decorations);
            } else if (diagnostics && diagnostics.length > 0) {
              const decorations = diagnostics.map((diagnostic2) => ({ range: diagnostic2, options: CodeActionController_1.DECORATION }));
              currentDecorations.set(decorations);
              const diagnostic = diagnostics[0];
              if (diagnostic.startLineNumber && diagnostic.startColumn) {
                const selectionText = this._editor.getModel()?.getWordAtPosition({ lineNumber: diagnostic.startLineNumber, column: diagnostic.startColumn })?.word;
                status(localize(863, "Context: {0} at line {1} and column {2}.", selectionText, diagnostic.startLineNumber, diagnostic.startColumn));
              }
            }
          } else {
            currentDecorations.clear();
          }
        }
      };
      this._actionWidgetService.show("codeActionWidget", true, toMenuItems(actionsToShow, this._shouldShowHeaders(), this._resolver.getResolver()), delegate, anchor, editorDom, this._getActionBarActions(actions, at, options));
    }
    toCoords(position) {
      if (!this._editor.hasModel()) {
        return { x: 0, y: 0 };
      }
      this._editor.revealPosition(
        position,
        1
        /* ScrollType.Immediate */
      );
      this._editor.render();
      const cursorCoords = this._editor.getScrolledVisiblePosition(position);
      const editorCoords = getDomNodePagePosition(this._editor.getDomNode());
      const x = editorCoords.left + cursorCoords.left;
      const y = editorCoords.top + cursorCoords.top + cursorCoords.height;
      return { x, y };
    }
    _shouldShowHeaders() {
      const model = this._editor?.getModel();
      return this._configurationService.getValue("editor.codeActionWidget.showHeaders", { resource: model?.uri });
    }
    _getActionBarActions(actions, at, options) {
      if (options.fromLightbulb) {
        return [];
      }
      const resultActions = actions.documentation.map((command) => ({
        id: command.id,
        label: command.title,
        tooltip: command.tooltip ?? "",
        class: void 0,
        enabled: true,
        run: () => this._commandService.executeCommand(command.id, ...command.arguments ?? [])
      }));
      if (options.includeDisabledActions && actions.validActions.length > 0 && actions.allActions.length !== actions.validActions.length) {
        resultActions.push(this._showDisabled ? {
          id: "hideMoreActions",
          label: localize(864, "Hide Disabled"),
          enabled: true,
          tooltip: "",
          class: void 0,
          run: () => {
            this._showDisabled = false;
            return this.showCodeActionList(actions, at, options);
          }
        } : {
          id: "showMoreActions",
          label: localize(865, "Show Disabled"),
          enabled: true,
          tooltip: "",
          class: void 0,
          run: () => {
            this._showDisabled = true;
            return this.showCodeActionList(actions, at, options);
          }
        });
      }
      return resultActions;
    }
  }, CodeActionController_1 = _v, _v.ID = "editor.contrib.codeActionController", _v.DECORATION = ModelDecorationOptions.register({
    description: "quickfix-highlight",
    className: DECORATION_CLASS_NAME$1
  }), _v);
  CodeActionController = CodeActionController_1 = __decorate$2h([
    __param$2f(1, IMarkerService),
    __param$2f(2, IContextKeyService),
    __param$2f(3, IInstantiationService),
    __param$2f(4, ILanguageFeaturesService),
    __param$2f(5, IEditorProgressService),
    __param$2f(6, ICommandService),
    __param$2f(7, IConfigurationService),
    __param$2f(8, IActionWidgetService),
    __param$2f(9, IInstantiationService),
    __param$2f(10, IEditorProgressService)
  ], CodeActionController);
  registerThemingParticipant((theme, collector) => {
    const addBackgroundColorRule = (selector, color) => {
      if (color) {
        collector.addRule(`.monaco-editor ${selector} { background-color: ${color}; }`);
      }
    };
    addBackgroundColorRule(".quickfix-edit-highlight", theme.getColor(editorFindMatchHighlight));
    const findMatchHighlightBorder = theme.getColor(editorFindMatchHighlightBorder);
    if (findMatchHighlightBorder) {
      collector.addRule(`.monaco-editor .quickfix-edit-highlight { border: 1px ${isHighContrast(theme.type) ? "dotted" : "solid"} ${findMatchHighlightBorder}; box-sizing: border-box; }`);
    }
  });
  function contextKeyForSupportedActions(kind) {
    return ContextKeyExpr.regex(SUPPORTED_CODE_ACTIONS.keys()[0], new RegExp("(\\s|^)" + escapeRegExpCharacters(kind.value) + "\\b"));
  }
  const argsSchema = {
    type: "object",
    defaultSnippets: [{ body: { kind: "" } }],
    properties: {
      "kind": {
        type: "string",
        description: localize(831, "Kind of the code action to run.")
      },
      "apply": {
        type: "string",
        description: localize(832, "Controls when the returned actions are applied."),
        default: "ifSingle",
        enum: [
          "first",
          "ifSingle",
          "never"
          /* CodeActionAutoApply.Never */
        ],
        enumDescriptions: [
          localize(833, "Always apply the first returned code action."),
          localize(834, "Apply the first returned code action if it is the only one."),
          localize(835, "Do not apply the returned code actions.")
        ]
      },
      "preferred": {
        type: "boolean",
        default: false,
        description: localize(836, "Controls if only preferred code actions should be returned.")
      }
    }
  };
  function triggerCodeActionsForEditorSelection(editor2, notAvailableMessage, filter, autoApply, triggerAction = CodeActionTriggerSource.Default) {
    if (editor2.hasModel()) {
      const controller = CodeActionController.get(editor2);
      controller?.manualTriggerAtCurrentPosition(notAvailableMessage, triggerAction, filter, autoApply);
    }
  }
  class QuickFixAction extends EditorAction {
    constructor() {
      super({
        id: quickFixCommandId,
        label: localize2(853, "Quick Fix..."),
        precondition: ContextKeyExpr.and(EditorContextKeys.writable, EditorContextKeys.hasCodeActionsProvider),
        kbOpts: {
          kbExpr: EditorContextKeys.textInputFocus,
          primary: 2048 | 89,
          weight: 100
          /* KeybindingWeight.EditorContrib */
        }
      });
    }
    run(_accessor, editor2) {
      return triggerCodeActionsForEditorSelection(editor2, localize(837, "No code actions available"), void 0, void 0, CodeActionTriggerSource.QuickFix);
    }
  }
  class CodeActionCommand extends EditorCommand {
    constructor() {
      super({
        id: codeActionCommandId,
        precondition: ContextKeyExpr.and(EditorContextKeys.writable, EditorContextKeys.hasCodeActionsProvider),
        metadata: {
          description: "Trigger a code action",
          args: [{ name: "args", schema: argsSchema }]
        }
      });
    }
    runEditorCommand(_accessor, editor2, userArgs) {
      const args = CodeActionCommandArgs.fromUser(userArgs, {
        kind: HierarchicalKind.Empty,
        apply: "ifSingle"
      });
      return triggerCodeActionsForEditorSelection(editor2, typeof userArgs?.kind === "string" ? args.preferred ? localize(838, "No preferred code actions for '{0}' available", userArgs.kind) : localize(839, "No code actions for '{0}' available", userArgs.kind) : args.preferred ? localize(840, "No preferred code actions available") : localize(841, "No code actions available"), {
        include: args.kind,
        includeSourceActions: true,
        onlyIncludePreferredActions: args.preferred
      }, args.apply);
    }
  }
  class RefactorAction extends EditorAction {
    constructor() {
      super({
        id: refactorCommandId,
        label: localize2(854, "Refactor..."),
        precondition: ContextKeyExpr.and(EditorContextKeys.writable, EditorContextKeys.hasCodeActionsProvider),
        kbOpts: {
          kbExpr: EditorContextKeys.textInputFocus,
          primary: 2048 | 1024 | 48,
          mac: {
            primary: 256 | 1024 | 48
            /* KeyCode.KeyR */
          },
          weight: 100
          /* KeybindingWeight.EditorContrib */
        },
        contextMenuOpts: {
          group: "1_modification",
          order: 2,
          when: ContextKeyExpr.and(EditorContextKeys.writable, contextKeyForSupportedActions(CodeActionKind.Refactor))
        },
        metadata: {
          description: "Refactor...",
          args: [{ name: "args", schema: argsSchema }]
        }
      });
    }
    run(_accessor, editor2, userArgs) {
      const args = CodeActionCommandArgs.fromUser(userArgs, {
        kind: CodeActionKind.Refactor,
        apply: "never"
        /* CodeActionAutoApply.Never */
      });
      return triggerCodeActionsForEditorSelection(editor2, typeof userArgs?.kind === "string" ? args.preferred ? localize(842, "No preferred refactorings for '{0}' available", userArgs.kind) : localize(843, "No refactorings for '{0}' available", userArgs.kind) : args.preferred ? localize(844, "No preferred refactorings available") : localize(845, "No refactorings available"), {
        include: CodeActionKind.Refactor.contains(args.kind) ? args.kind : HierarchicalKind.None,
        onlyIncludePreferredActions: args.preferred
      }, args.apply, CodeActionTriggerSource.Refactor);
    }
  }
  class SourceAction extends EditorAction {
    constructor() {
      super({
        id: sourceActionCommandId,
        label: localize2(855, "Source Action..."),
        precondition: ContextKeyExpr.and(EditorContextKeys.writable, EditorContextKeys.hasCodeActionsProvider),
        contextMenuOpts: {
          group: "1_modification",
          order: 2.1,
          when: ContextKeyExpr.and(EditorContextKeys.writable, contextKeyForSupportedActions(CodeActionKind.Source))
        },
        metadata: {
          description: "Source Action...",
          args: [{ name: "args", schema: argsSchema }]
        }
      });
    }
    run(_accessor, editor2, userArgs) {
      const args = CodeActionCommandArgs.fromUser(userArgs, {
        kind: CodeActionKind.Source,
        apply: "never"
        /* CodeActionAutoApply.Never */
      });
      return triggerCodeActionsForEditorSelection(editor2, typeof userArgs?.kind === "string" ? args.preferred ? localize(846, "No preferred source actions for '{0}' available", userArgs.kind) : localize(847, "No source actions for '{0}' available", userArgs.kind) : args.preferred ? localize(848, "No preferred source actions available") : localize(849, "No source actions available"), {
        include: CodeActionKind.Source.contains(args.kind) ? args.kind : HierarchicalKind.None,
        includeSourceActions: true,
        onlyIncludePreferredActions: args.preferred
      }, args.apply, CodeActionTriggerSource.SourceAction);
    }
  }
  class OrganizeImportsAction extends EditorAction {
    constructor() {
      super({
        id: organizeImportsCommandId,
        label: localize2(856, "Organize Imports"),
        precondition: ContextKeyExpr.and(EditorContextKeys.writable, contextKeyForSupportedActions(CodeActionKind.SourceOrganizeImports)),
        kbOpts: {
          kbExpr: EditorContextKeys.textInputFocus,
          primary: 1024 | 512 | 45,
          weight: 100
          /* KeybindingWeight.EditorContrib */
        },
        metadata: {
          description: localize2(857, "Organize imports in the current file. Also called 'Optimize Imports' by some tools")
        }
      });
    }
    run(_accessor, editor2) {
      return triggerCodeActionsForEditorSelection(editor2, localize(850, "No organize imports action available"), { include: CodeActionKind.SourceOrganizeImports, includeSourceActions: true }, "ifSingle", CodeActionTriggerSource.OrganizeImports);
    }
  }
  class FixAllAction extends EditorAction {
    constructor() {
      super({
        id: fixAllCommandId,
        label: localize2(858, "Fix All"),
        precondition: ContextKeyExpr.and(EditorContextKeys.writable, contextKeyForSupportedActions(CodeActionKind.SourceFixAll))
      });
    }
    run(_accessor, editor2) {
      return triggerCodeActionsForEditorSelection(editor2, localize(851, "No fix all action available"), { include: CodeActionKind.SourceFixAll, includeSourceActions: true }, "ifSingle", CodeActionTriggerSource.FixAll);
    }
  }
  class AutoFixAction extends EditorAction {
    constructor() {
      super({
        id: autoFixCommandId,
        label: localize2(859, "Auto Fix..."),
        precondition: ContextKeyExpr.and(EditorContextKeys.writable, contextKeyForSupportedActions(CodeActionKind.QuickFix)),
        kbOpts: {
          kbExpr: EditorContextKeys.textInputFocus,
          primary: 512 | 1024 | 89,
          mac: {
            primary: 2048 | 512 | 89
            /* KeyCode.Period */
          },
          weight: 100
          /* KeybindingWeight.EditorContrib */
        }
      });
    }
    run(_accessor, editor2) {
      return triggerCodeActionsForEditorSelection(editor2, localize(852, "No auto fixes available"), {
        include: CodeActionKind.QuickFix,
        onlyIncludePreferredActions: true
      }, "ifSingle", CodeActionTriggerSource.AutoFix);
    }
  }
  registerEditorContribution(
    CodeActionController.ID,
    CodeActionController,
    3
    /* EditorContributionInstantiation.Eventually */
  );
  registerEditorContribution(
    LightBulbWidget.ID,
    LightBulbWidget,
    4
    /* EditorContributionInstantiation.Lazy */
  );
  registerEditorAction(QuickFixAction);
  registerEditorAction(RefactorAction);
  registerEditorAction(SourceAction);
  registerEditorAction(OrganizeImportsAction);
  registerEditorAction(AutoFixAction);
  registerEditorAction(FixAllAction);
  registerEditorCommand(new CodeActionCommand());
  Registry.as(Extensions$6.Configuration).registerConfiguration({
    ...editorConfigurationBaseNode,
    properties: {
      "editor.codeActionWidget.showHeaders": {
        type: "boolean",
        scope: 6,
        description: localize(860, "Enable/disable showing group headers in the Code Action menu."),
        default: true
      }
    }
  });
  Registry.as(Extensions$6.Configuration).registerConfiguration({
    ...editorConfigurationBaseNode,
    properties: {
      "editor.codeActionWidget.includeNearbyQuickFixes": {
        type: "boolean",
        scope: 6,
        description: localize(861, "Enable/disable showing nearest Quick Fix within a line when not currently on a diagnostic."),
        default: true
      }
    }
  });
  Registry.as(Extensions$6.Configuration).registerConfiguration({
    ...editorConfigurationBaseNode,
    properties: {
      "editor.codeActions.triggerOnFocusChange": {
        type: "boolean",
        scope: 6,
        markdownDescription: localize(862, "Enable triggering {0} when {1} is set to {2}. Code Actions must be set to {3} to be triggered for window and focus changes.", "`#editor.codeActionsOnSave#`", "`#files.autoSave#`", "`afterDelay`", "`always`"),
        default: false
      }
    }
  });
  const _CodeLensModel = class _CodeLensModel {
    constructor() {
      this.lenses = [];
    }
    dispose() {
      this._store?.dispose();
    }
    get isDisposed() {
      return this._store?.isDisposed ?? false;
    }
    add(list2, provider) {
      if (isDisposable(list2)) {
        this._store ??= new DisposableStore();
        this._store.add(list2);
      }
      for (const symbol of list2.lenses) {
        this.lenses.push({ symbol, provider });
      }
    }
  };
  _CodeLensModel.Empty = new _CodeLensModel();
  let CodeLensModel = _CodeLensModel;
  async function getCodeLensModel(registry, model, token) {
    const provider = registry.ordered(model);
    const providerRanks = /* @__PURE__ */ new Map();
    const result = new CodeLensModel();
    const promises = provider.map(async (provider2, i2) => {
      providerRanks.set(provider2, i2);
      try {
        const list2 = await Promise.resolve(provider2.provideCodeLenses(model, token));
        if (list2) {
          result.add(list2, provider2);
        }
      } catch (err) {
        onUnexpectedExternalError(err);
      }
    });
    await Promise.all(promises);
    if (token.isCancellationRequested) {
      result.dispose();
      return CodeLensModel.Empty;
    }
    result.lenses = result.lenses.sort((a, b) => {
      if (a.symbol.range.startLineNumber < b.symbol.range.startLineNumber) {
        return -1;
      } else if (a.symbol.range.startLineNumber > b.symbol.range.startLineNumber) {
        return 1;
      } else if (providerRanks.get(a.provider) < providerRanks.get(b.provider)) {
        return -1;
      } else if (providerRanks.get(a.provider) > providerRanks.get(b.provider)) {
        return 1;
      } else if (a.symbol.range.startColumn < b.symbol.range.startColumn) {
        return -1;
      } else if (a.symbol.range.startColumn > b.symbol.range.startColumn) {
        return 1;
      } else {
        return 0;
      }
    });
    return result;
  }
  CommandsRegistry.registerCommand("_executeCodeLensProvider", function(accessor, ...args) {
    let [uri, itemResolveCount] = args;
    assertType(URI.isUri(uri));
    assertType(typeof itemResolveCount === "number" || !itemResolveCount);
    const { codeLensProvider } = accessor.get(ILanguageFeaturesService);
    const model = accessor.get(IModelService).getModel(uri);
    if (!model) {
      throw illegalArgument();
    }
    const result = [];
    const disposables = new DisposableStore();
    return getCodeLensModel(codeLensProvider, model, CancellationToken.None).then((value) => {
      disposables.add(value);
      const resolve2 = [];
      for (const item of value.lenses) {
        if (itemResolveCount === void 0 || itemResolveCount === null || Boolean(item.symbol.command)) {
          result.push(item.symbol);
        } else if (itemResolveCount-- > 0 && item.provider.resolveCodeLens) {
          resolve2.push(Promise.resolve(item.provider.resolveCodeLens(model, item.symbol, CancellationToken.None)).then((symbol) => result.push(symbol || item.symbol)));
        }
      }
      return Promise.all(resolve2);
    }).then(() => {
      return result;
    }).finally(() => {
      setTimeout(() => disposables.dispose(), 100);
    });
  });
  var __decorate$2g = 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$2e = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  const ICodeLensCache = createDecorator("ICodeLensCache");
  class CacheItem {
    constructor(lineCount, data) {
      this.lineCount = lineCount;
      this.data = data;
    }
  }
  let CodeLensCache = class CodeLensCache {
    constructor(storageService) {
      this._fakeProvider = new class {
        provideCodeLenses() {
          throw new Error("not supported");
        }
      }();
      this._cache = new LRUCache(20, 0.75);
      const oldkey = "codelens/cache";
      runWhenWindowIdle(mainWindow, () => storageService.remove(
        oldkey,
        1
        /* StorageScope.WORKSPACE */
      ));
      const key = "codelens/cache2";
      const raw = storageService.get(key, 1, "{}");
      this._deserialize(raw);
      const onWillSaveStateBecauseOfShutdown = Event.filter(storageService.onWillSaveState, (e) => e.reason === WillSaveStateReason.SHUTDOWN);
      Event.once(onWillSaveStateBecauseOfShutdown)((e) => {
        storageService.store(
          key,
          this._serialize(),
          1,
          1
          /* StorageTarget.MACHINE */
        );
      });
    }
    put(model, data) {
      const copyItems = data.lenses.map((item2) => {
        return {
          range: item2.symbol.range,
          command: item2.symbol.command && { id: "", title: item2.symbol.command?.title }
        };
      });
      const copyModel = new CodeLensModel();
      copyModel.add({ lenses: copyItems }, this._fakeProvider);
      const item = new CacheItem(model.getLineCount(), copyModel);
      this._cache.set(model.uri.toString(), item);
    }
    get(model) {
      const item = this._cache.get(model.uri.toString());
      return item && item.lineCount === model.getLineCount() ? item.data : void 0;
    }
    delete(model) {
      this._cache.delete(model.uri.toString());
    }
    // --- persistence
    _serialize() {
      const data = /* @__PURE__ */ Object.create(null);
      for (const [key, value] of this._cache) {
        const lines = /* @__PURE__ */ new Set();
        for (const d of value.data.lenses) {
          lines.add(d.symbol.range.startLineNumber);
        }
        data[key] = {
          lineCount: value.lineCount,
          lines: [...lines.values()]
        };
      }
      return JSON.stringify(data);
    }
    _deserialize(raw) {
      try {
        const data = JSON.parse(raw);
        for (const key in data) {
          const element = data[key];
          const lenses = [];
          for (const line of element.lines) {
            lenses.push({ range: new Range$2(line, 1, line, 11) });
          }
          const model = new CodeLensModel();
          model.add({ lenses }, this._fakeProvider);
          this._cache.set(key, new CacheItem(element.lineCount, model));
        }
      } catch {
      }
    }
  };
  CodeLensCache = __decorate$2g([
    __param$2e(0, IStorageService)
  ], CodeLensCache);
  registerSingleton(
    ICodeLensCache,
    CodeLensCache,
    1
    /* InstantiationType.Delayed */
  );
  class CodeLensViewZone {
    constructor(afterLineNumber, heightInPx, onHeight) {
      this.afterColumn = 1073741824;
      this.afterLineNumber = afterLineNumber;
      this.heightInPx = heightInPx;
      this._onHeight = onHeight;
      this.suppressMouseDown = true;
      this.domNode = document.createElement("div");
    }
    onComputedHeight(height) {
      if (this._lastHeight === void 0) {
        this._lastHeight = height;
      } else if (this._lastHeight !== height) {
        this._lastHeight = height;
        this._onHeight();
      }
    }
    isVisible() {
      return this._lastHeight !== 0 && this.domNode.hasAttribute("monaco-visible-view-zone");
    }
  }
  const _CodeLensContentWidget = class _CodeLensContentWidget {
    constructor(editor2, line) {
      this.allowEditorOverflow = false;
      this.suppressMouseDown = true;
      this._commands = /* @__PURE__ */ new Map();
      this._isEmpty = true;
      this._editor = editor2;
      this._id = `codelens.widget-${_CodeLensContentWidget._idPool++}`;
      this.updatePosition(line);
      this._domNode = document.createElement("span");
      this._domNode.className = `codelens-decoration`;
    }
    withCommands(lenses, animate2) {
      this._commands.clear();
      const children = [];
      let hasSymbol = false;
      for (let i2 = 0; i2 < lenses.length; i2++) {
        const lens = lenses[i2];
        if (!lens) {
          continue;
        }
        hasSymbol = true;
        if (lens.command) {
          const title = renderLabelWithIcons(lens.command.title.trim());
          if (lens.command.id) {
            const id = `c${_CodeLensContentWidget._idPool++}`;
            children.push($$l("a", { id, title: lens.command.tooltip, role: "button" }, ...title));
            this._commands.set(id, lens.command);
          } else {
            children.push($$l("span", { title: lens.command.tooltip }, ...title));
          }
          if (i2 + 1 < lenses.length) {
            children.push($$l("span", void 0, " | "));
          }
        }
      }
      if (!hasSymbol) {
        reset(this._domNode, $$l("span", void 0, "no commands"));
      } else {
        reset(this._domNode, ...children);
        if (this._isEmpty && animate2) {
          this._domNode.classList.add("fadein");
        }
        this._isEmpty = false;
      }
    }
    getCommand(link2) {
      return link2.parentElement === this._domNode ? this._commands.get(link2.id) : void 0;
    }
    getId() {
      return this._id;
    }
    getDomNode() {
      return this._domNode;
    }
    updatePosition(line) {
      const column = this._editor.getModel().getLineFirstNonWhitespaceColumn(line);
      this._widgetPosition = {
        position: { lineNumber: line, column },
        preference: [
          1
          /* ContentWidgetPositionPreference.ABOVE */
        ]
      };
    }
    getPosition() {
      return this._widgetPosition || null;
    }
  };
  _CodeLensContentWidget._idPool = 0;
  let CodeLensContentWidget = _CodeLensContentWidget;
  class CodeLensHelper {
    constructor() {
      this._removeDecorations = [];
      this._addDecorations = [];
      this._addDecorationsCallbacks = [];
    }
    addDecoration(decoration2, callback) {
      this._addDecorations.push(decoration2);
      this._addDecorationsCallbacks.push(callback);
    }
    removeDecoration(decorationId) {
      this._removeDecorations.push(decorationId);
    }
    commit(changeAccessor) {
      const resultingDecorations = changeAccessor.deltaDecorations(this._removeDecorations, this._addDecorations);
      for (let i2 = 0, len = resultingDecorations.length; i2 < len; i2++) {
        this._addDecorationsCallbacks[i2](resultingDecorations[i2]);
      }
    }
  }
  const codeLensDecorationOptions = ModelDecorationOptions.register({
    collapseOnReplaceEdit: true,
    description: "codelens"
  });
  class CodeLensWidget {
    constructor(data, editor2, helper, viewZoneChangeAccessor, heightInPx, updateCallback) {
      this._isDisposed = false;
      this._editor = editor2;
      this._data = data;
      this._decorationIds = [];
      let range2;
      const lenses = [];
      this._data.forEach((codeLensData, i2) => {
        if (codeLensData.symbol.command) {
          lenses.push(codeLensData.symbol);
        }
        helper.addDecoration({
          range: codeLensData.symbol.range,
          options: codeLensDecorationOptions
        }, (id) => this._decorationIds[i2] = id);
        if (!range2) {
          range2 = Range$2.lift(codeLensData.symbol.range);
        } else {
          range2 = Range$2.plusRange(range2, codeLensData.symbol.range);
        }
      });
      this._viewZone = new CodeLensViewZone(range2.startLineNumber - 1, heightInPx, updateCallback);
      this._viewZoneId = viewZoneChangeAccessor.addZone(this._viewZone);
      if (lenses.length > 0) {
        this._createContentWidgetIfNecessary();
        this._contentWidget.withCommands(lenses, false);
      }
    }
    _createContentWidgetIfNecessary() {
      if (!this._contentWidget) {
        this._contentWidget = new CodeLensContentWidget(this._editor, this._viewZone.afterLineNumber + 1);
        this._editor.addContentWidget(this._contentWidget);
      } else {
        this._editor.layoutContentWidget(this._contentWidget);
      }
    }
    dispose(helper, viewZoneChangeAccessor) {
      this._decorationIds.forEach(helper.removeDecoration, helper);
      this._decorationIds = [];
      viewZoneChangeAccessor?.removeZone(this._viewZoneId);
      if (this._contentWidget) {
        this._editor.removeContentWidget(this._contentWidget);
        this._contentWidget = void 0;
      }
      this._isDisposed = true;
    }
    isDisposed() {
      return this._isDisposed;
    }
    isValid() {
      return this._decorationIds.some((id, i2) => {
        const range2 = this._editor.getModel().getDecorationRange(id);
        const symbol = this._data[i2].symbol;
        return !!(range2 && Range$2.isEmpty(symbol.range) === range2.isEmpty());
      });
    }
    updateCodeLensSymbols(data, helper) {
      this._decorationIds.forEach(helper.removeDecoration, helper);
      this._decorationIds = [];
      this._data = data;
      this._data.forEach((codeLensData, i2) => {
        helper.addDecoration({
          range: codeLensData.symbol.range,
          options: codeLensDecorationOptions
        }, (id) => this._decorationIds[i2] = id);
      });
    }
    updateHeight(height, viewZoneChangeAccessor) {
      this._viewZone.heightInPx = height;
      viewZoneChangeAccessor.layoutZone(this._viewZoneId);
      if (this._contentWidget) {
        this._editor.layoutContentWidget(this._contentWidget);
      }
    }
    computeIfNecessary(model) {
      if (!this._viewZone.isVisible()) {
        return null;
      }
      for (let i2 = 0; i2 < this._decorationIds.length; i2++) {
        const range2 = model.getDecorationRange(this._decorationIds[i2]);
        if (range2) {
          this._data[i2].symbol.range = range2;
        }
      }
      return this._data;
    }
    updateCommands(symbols) {
      this._createContentWidgetIfNecessary();
      this._contentWidget.withCommands(symbols, true);
      for (let i2 = 0; i2 < this._data.length; i2++) {
        const resolved = symbols[i2];
        if (resolved) {
          const { symbol } = this._data[i2];
          symbol.command = resolved.command || symbol.command;
        }
      }
    }
    getCommand(link2) {
      return this._contentWidget?.getCommand(link2);
    }
    getLineNumber() {
      const range2 = this._editor.getModel().getDecorationRange(this._decorationIds[0]);
      if (range2) {
        return range2.startLineNumber;
      }
      return -1;
    }
    update(viewZoneChangeAccessor) {
      if (this.isValid()) {
        const range2 = this._editor.getModel().getDecorationRange(this._decorationIds[0]);
        if (range2) {
          this._viewZone.afterLineNumber = range2.startLineNumber - 1;
          viewZoneChangeAccessor.layoutZone(this._viewZoneId);
          if (this._contentWidget) {
            this._contentWidget.updatePosition(range2.startLineNumber);
            this._editor.layoutContentWidget(this._contentWidget);
          }
        }
      }
    }
  }
  const IEnvironmentService = createDecorator("environmentService");
  var __decorate$2f = 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$2d = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  const ILanguageFeatureDebounceService = createDecorator("ILanguageFeatureDebounceService");
  var IdentityHash;
  (function(IdentityHash2) {
    const _hashes = /* @__PURE__ */ new WeakMap();
    let pool = 0;
    function of(obj) {
      let value = _hashes.get(obj);
      if (value === void 0) {
        value = ++pool;
        _hashes.set(obj, value);
      }
      return value;
    }
    IdentityHash2.of = of;
  })(IdentityHash || (IdentityHash = {}));
  class NullDebounceInformation {
    constructor(_default) {
      this._default = _default;
    }
    get(_model) {
      return this._default;
    }
    update(_model, _value) {
      return this._default;
    }
    default() {
      return this._default;
    }
  }
  class FeatureDebounceInformation {
    constructor(_logService, _name, _registry2, _default, _min, _max) {
      this._logService = _logService;
      this._name = _name;
      this._registry = _registry2;
      this._default = _default;
      this._min = _min;
      this._max = _max;
      this._cache = new LRUCache(50, 0.7);
    }
    _key(model) {
      return model.id + this._registry.all(model).reduce((hashVal, obj) => doHash(IdentityHash.of(obj), hashVal), 0);
    }
    get(model) {
      const key = this._key(model);
      const avg = this._cache.get(key);
      return avg ? clamp(avg.value, this._min, this._max) : this.default();
    }
    update(model, value) {
      const key = this._key(model);
      let avg = this._cache.get(key);
      if (!avg) {
        avg = new SlidingWindowAverage(6);
        this._cache.set(key, avg);
      }
      const newValue = clamp(avg.update(value), this._min, this._max);
      if (!matchesScheme(model.uri, "output")) {
        this._logService.trace(`[DEBOUNCE: ${this._name}] for ${model.uri.toString()} is ${newValue}ms`);
      }
      return newValue;
    }
    _overall() {
      const result = new MovingAverage();
      for (const [, avg] of this._cache) {
        result.update(avg.value);
      }
      return result.value;
    }
    default() {
      const value = this._overall() | 0 || this._default;
      return clamp(value, this._min, this._max);
    }
  }
  let LanguageFeatureDebounceService = class LanguageFeatureDebounceService {
    constructor(_logService, envService) {
      this._logService = _logService;
      this._data = /* @__PURE__ */ new Map();
      this._isDev = envService.isExtensionDevelopment || !envService.isBuilt;
    }
    for(feature, name, config) {
      const min = config?.min ?? 50;
      const max = config?.max ?? min ** 2;
      const extra = config?.key ?? void 0;
      const key = `${IdentityHash.of(feature)},${min}${extra ? "," + extra : ""}`;
      let info = this._data.get(key);
      if (!info) {
        if (this._isDev) {
          this._logService.debug(`[DEBOUNCE: ${name}] is disabled in developed mode`);
          info = new NullDebounceInformation(min * 1.5);
        } else {
          info = new FeatureDebounceInformation(
            this._logService,
            name,
            feature,
            this._overallAverage() | 0 || min * 1.5,
            // default is overall default or derived from min-value
            min,
            max
          );
        }
        this._data.set(key, info);
      }
      return info;
    }
    _overallAverage() {
      const result = new MovingAverage();
      for (const info of this._data.values()) {
        result.update(info.default());
      }
      return result.value;
    }
  };
  LanguageFeatureDebounceService = __decorate$2f([
    __param$2d(0, ILogService),
    __param$2d(1, IEnvironmentService)
  ], LanguageFeatureDebounceService);
  registerSingleton(
    ILanguageFeatureDebounceService,
    LanguageFeatureDebounceService,
    1
    /* InstantiationType.Delayed */
  );
  var __decorate$2e = 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$2c = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  let CodeLensContribution = (_w = class {
    constructor(_editor, _languageFeaturesService, debounceService, _commandService, _notificationService, _codeLensCache) {
      this._editor = _editor;
      this._languageFeaturesService = _languageFeaturesService;
      this._commandService = _commandService;
      this._notificationService = _notificationService;
      this._codeLensCache = _codeLensCache;
      this._disposables = new DisposableStore();
      this._localToDispose = new DisposableStore();
      this._lenses = [];
      this._oldCodeLensModels = new DisposableStore();
      this._provideCodeLensDebounce = debounceService.for(_languageFeaturesService.codeLensProvider, "CodeLensProvide", { min: 250 });
      this._resolveCodeLensesDebounce = debounceService.for(_languageFeaturesService.codeLensProvider, "CodeLensResolve", { min: 250, salt: "resolve" });
      this._resolveCodeLensesScheduler = new RunOnceScheduler(() => this._resolveCodeLensesInViewport(), this._resolveCodeLensesDebounce.default());
      this._disposables.add(this._editor.onDidChangeModel(() => this._onModelChange()));
      this._disposables.add(this._editor.onDidChangeModelLanguage(() => this._onModelChange()));
      this._disposables.add(this._editor.onDidChangeConfiguration((e) => {
        if (e.hasChanged(
          59
          /* EditorOption.fontInfo */
        ) || e.hasChanged(
          25
          /* EditorOption.codeLensFontSize */
        ) || e.hasChanged(
          24
          /* EditorOption.codeLensFontFamily */
        )) {
          this._updateLensStyle();
        }
        if (e.hasChanged(
          23
          /* EditorOption.codeLens */
        )) {
          this._onModelChange();
        }
      }));
      this._disposables.add(_languageFeaturesService.codeLensProvider.onDidChange(this._onModelChange, this));
      this._onModelChange();
      this._updateLensStyle();
    }
    dispose() {
      this._localDispose();
      this._localToDispose.dispose();
      this._disposables.dispose();
      this._oldCodeLensModels.dispose();
      this._currentCodeLensModel?.dispose();
    }
    _getLayoutInfo() {
      const lineHeightFactor = Math.max(1.3, this._editor.getOption(
        75
        /* EditorOption.lineHeight */
      ) / this._editor.getOption(
        61
        /* EditorOption.fontSize */
      ));
      let fontSize = this._editor.getOption(
        25
        /* EditorOption.codeLensFontSize */
      );
      if (!fontSize || fontSize < 5) {
        fontSize = this._editor.getOption(
          61
          /* EditorOption.fontSize */
        ) * 0.9 | 0;
      }
      return {
        fontSize,
        codeLensHeight: fontSize * lineHeightFactor | 0
      };
    }
    _updateLensStyle() {
      const { codeLensHeight, fontSize } = this._getLayoutInfo();
      const fontFamily = this._editor.getOption(
        24
        /* EditorOption.codeLensFontFamily */
      );
      const editorFontInfo = this._editor.getOption(
        59
        /* EditorOption.fontInfo */
      );
      const { style } = this._editor.getContainerDomNode();
      style.setProperty("--vscode-editorCodeLens-lineHeight", `${codeLensHeight}px`);
      style.setProperty("--vscode-editorCodeLens-fontSize", `${fontSize}px`);
      style.setProperty("--vscode-editorCodeLens-fontFeatureSettings", editorFontInfo.fontFeatureSettings);
      if (fontFamily) {
        style.setProperty("--vscode-editorCodeLens-fontFamily", fontFamily);
        style.setProperty("--vscode-editorCodeLens-fontFamilyDefault", EDITOR_FONT_DEFAULTS.fontFamily);
      }
      this._editor.changeViewZones((accessor) => {
        for (const lens of this._lenses) {
          lens.updateHeight(codeLensHeight, accessor);
        }
      });
    }
    _localDispose() {
      this._getCodeLensModelPromise?.cancel();
      this._getCodeLensModelPromise = void 0;
      this._resolveCodeLensesPromise?.cancel();
      this._resolveCodeLensesPromise = void 0;
      this._localToDispose.clear();
      this._oldCodeLensModels.clear();
      this._currentCodeLensModel?.dispose();
    }
    _onModelChange() {
      this._localDispose();
      const model = this._editor.getModel();
      if (!model) {
        return;
      }
      if (!this._editor.getOption(
        23
        /* EditorOption.codeLens */
      ) || model.isTooLargeForTokenization()) {
        return;
      }
      const cachedLenses = this._codeLensCache.get(model);
      if (cachedLenses) {
        this._renderCodeLensSymbols(cachedLenses);
      }
      if (!this._languageFeaturesService.codeLensProvider.has(model)) {
        if (cachedLenses) {
          disposableTimeout(() => {
            const cachedLensesNow = this._codeLensCache.get(model);
            if (cachedLenses === cachedLensesNow) {
              this._codeLensCache.delete(model);
              this._onModelChange();
            }
          }, 30 * 1e3, this._localToDispose);
        }
        return;
      }
      for (const provider of this._languageFeaturesService.codeLensProvider.all(model)) {
        if (typeof provider.onDidChange === "function") {
          const registration = provider.onDidChange(() => scheduler.schedule());
          this._localToDispose.add(registration);
        }
      }
      const scheduler = new RunOnceScheduler(() => {
        const t1 = Date.now();
        this._getCodeLensModelPromise?.cancel();
        this._getCodeLensModelPromise = createCancelablePromise((token) => getCodeLensModel(this._languageFeaturesService.codeLensProvider, model, token));
        this._getCodeLensModelPromise.then((result) => {
          if (this._currentCodeLensModel) {
            this._oldCodeLensModels.add(this._currentCodeLensModel);
          }
          this._currentCodeLensModel = result;
          this._codeLensCache.put(model, result);
          const newDelay = this._provideCodeLensDebounce.update(model, Date.now() - t1);
          scheduler.delay = newDelay;
          this._renderCodeLensSymbols(result);
          this._resolveCodeLensesInViewportSoon();
        }, onUnexpectedError);
      }, this._provideCodeLensDebounce.get(model));
      this._localToDispose.add(scheduler);
      this._localToDispose.add(toDisposable(() => this._resolveCodeLensesScheduler.cancel()));
      this._localToDispose.add(this._editor.onDidChangeModelContent(() => {
        this._editor.changeDecorations((decorationsAccessor) => {
          this._editor.changeViewZones((viewZonesAccessor) => {
            const toDispose = [];
            let lastLensLineNumber = -1;
            this._lenses.forEach((lens) => {
              if (!lens.isValid() || lastLensLineNumber === lens.getLineNumber()) {
                toDispose.push(lens);
              } else {
                lens.update(viewZonesAccessor);
                lastLensLineNumber = lens.getLineNumber();
              }
            });
            const helper = new CodeLensHelper();
            toDispose.forEach((l) => {
              l.dispose(helper, viewZonesAccessor);
              this._lenses.splice(this._lenses.indexOf(l), 1);
            });
            helper.commit(decorationsAccessor);
          });
        });
        scheduler.schedule();
        this._resolveCodeLensesScheduler.cancel();
        this._resolveCodeLensesPromise?.cancel();
        this._resolveCodeLensesPromise = void 0;
      }));
      this._localToDispose.add(this._editor.onDidFocusEditorText(() => {
        scheduler.schedule();
      }));
      this._localToDispose.add(this._editor.onDidBlurEditorText(() => {
        scheduler.cancel();
      }));
      this._localToDispose.add(this._editor.onDidScrollChange((e) => {
        if (e.scrollTopChanged && this._lenses.length > 0) {
          this._resolveCodeLensesInViewportSoon();
        }
      }));
      this._localToDispose.add(this._editor.onDidLayoutChange(() => {
        this._resolveCodeLensesInViewportSoon();
      }));
      this._localToDispose.add(toDisposable(() => {
        if (this._editor.getModel()) {
          const scrollState = StableEditorScrollState.capture(this._editor);
          this._editor.changeDecorations((decorationsAccessor) => {
            this._editor.changeViewZones((viewZonesAccessor) => {
              this._disposeAllLenses(decorationsAccessor, viewZonesAccessor);
            });
          });
          scrollState.restore(this._editor);
        } else {
          this._disposeAllLenses(void 0, void 0);
        }
      }));
      this._localToDispose.add(this._editor.onMouseDown((e) => {
        if (e.target.type !== 9) {
          return;
        }
        let target = e.target.element;
        if (target?.tagName === "SPAN") {
          target = target.parentElement;
        }
        if (target?.tagName === "A") {
          for (const lens of this._lenses) {
            const command = lens.getCommand(target);
            if (command) {
              this._commandService.executeCommand(command.id, ...command.arguments || []).catch((err) => this._notificationService.error(err));
              break;
            }
          }
        }
      }));
      scheduler.schedule();
    }
    _disposeAllLenses(decChangeAccessor, viewZoneChangeAccessor) {
      const helper = new CodeLensHelper();
      for (const lens of this._lenses) {
        lens.dispose(helper, viewZoneChangeAccessor);
      }
      if (decChangeAccessor) {
        helper.commit(decChangeAccessor);
      }
      this._lenses.length = 0;
    }
    _renderCodeLensSymbols(symbols) {
      if (!this._editor.hasModel()) {
        return;
      }
      const maxLineNumber = this._editor.getModel().getLineCount();
      const groups = [];
      let lastGroup;
      for (const symbol of symbols.lenses) {
        const line = symbol.symbol.range.startLineNumber;
        if (line < 1 || line > maxLineNumber) {
          continue;
        } else if (lastGroup && lastGroup[lastGroup.length - 1].symbol.range.startLineNumber === line) {
          lastGroup.push(symbol);
        } else {
          lastGroup = [symbol];
          groups.push(lastGroup);
        }
      }
      if (!groups.length && !this._lenses.length) {
        return;
      }
      const scrollState = StableEditorScrollState.capture(this._editor);
      const layoutInfo = this._getLayoutInfo();
      this._editor.changeDecorations((decorationsAccessor) => {
        this._editor.changeViewZones((viewZoneAccessor) => {
          const helper = new CodeLensHelper();
          let codeLensIndex = 0;
          let groupsIndex = 0;
          while (groupsIndex < groups.length && codeLensIndex < this._lenses.length) {
            const symbolsLineNumber = groups[groupsIndex][0].symbol.range.startLineNumber;
            const codeLensLineNumber = this._lenses[codeLensIndex].getLineNumber();
            if (codeLensLineNumber < symbolsLineNumber) {
              this._lenses[codeLensIndex].dispose(helper, viewZoneAccessor);
              this._lenses.splice(codeLensIndex, 1);
            } else if (codeLensLineNumber === symbolsLineNumber) {
              this._lenses[codeLensIndex].updateCodeLensSymbols(groups[groupsIndex], helper);
              groupsIndex++;
              codeLensIndex++;
            } else {
              this._lenses.splice(codeLensIndex, 0, new CodeLensWidget(groups[groupsIndex], this._editor, helper, viewZoneAccessor, layoutInfo.codeLensHeight, () => this._resolveCodeLensesInViewportSoon()));
              codeLensIndex++;
              groupsIndex++;
            }
          }
          while (codeLensIndex < this._lenses.length) {
            this._lenses[codeLensIndex].dispose(helper, viewZoneAccessor);
            this._lenses.splice(codeLensIndex, 1);
          }
          while (groupsIndex < groups.length) {
            this._lenses.push(new CodeLensWidget(groups[groupsIndex], this._editor, helper, viewZoneAccessor, layoutInfo.codeLensHeight, () => this._resolveCodeLensesInViewportSoon()));
            groupsIndex++;
          }
          helper.commit(decorationsAccessor);
        });
      });
      scrollState.restore(this._editor);
    }
    _resolveCodeLensesInViewportSoon() {
      const model = this._editor.getModel();
      if (model) {
        this._resolveCodeLensesScheduler.schedule();
      }
    }
    _resolveCodeLensesInViewport() {
      this._resolveCodeLensesPromise?.cancel();
      this._resolveCodeLensesPromise = void 0;
      const model = this._editor.getModel();
      if (!model) {
        return;
      }
      const toResolve = [];
      const lenses = [];
      this._lenses.forEach((lens) => {
        const request = lens.computeIfNecessary(model);
        if (request) {
          toResolve.push(request);
          lenses.push(lens);
        }
      });
      if (toResolve.length === 0) {
        this._oldCodeLensModels.clear();
        return;
      }
      const t1 = Date.now();
      const resolvePromise = createCancelablePromise((token) => {
        const promises = toResolve.map((request, i2) => {
          const resolvedSymbols = new Array(request.length);
          const promises2 = request.map((request2, i3) => {
            if (!request2.symbol.command && typeof request2.provider.resolveCodeLens === "function") {
              return Promise.resolve(request2.provider.resolveCodeLens(model, request2.symbol, token)).then((symbol) => {
                resolvedSymbols[i3] = symbol;
              }, onUnexpectedExternalError);
            } else {
              resolvedSymbols[i3] = request2.symbol;
              return Promise.resolve(void 0);
            }
          });
          return Promise.all(promises2).then(() => {
            if (!token.isCancellationRequested && !lenses[i2].isDisposed()) {
              lenses[i2].updateCommands(resolvedSymbols);
            }
          });
        });
        return Promise.all(promises);
      });
      this._resolveCodeLensesPromise = resolvePromise;
      this._resolveCodeLensesPromise.then(() => {
        const newDelay = this._resolveCodeLensesDebounce.update(model, Date.now() - t1);
        this._resolveCodeLensesScheduler.delay = newDelay;
        if (this._currentCodeLensModel) {
          this._codeLensCache.put(model, this._currentCodeLensModel);
        }
        this._oldCodeLensModels.clear();
        if (resolvePromise === this._resolveCodeLensesPromise) {
          this._resolveCodeLensesPromise = void 0;
        }
      }, (err) => {
        onUnexpectedError(err);
        if (resolvePromise === this._resolveCodeLensesPromise) {
          this._resolveCodeLensesPromise = void 0;
        }
      });
    }
    async getModel() {
      await this._getCodeLensModelPromise;
      await this._resolveCodeLensesPromise;
      return !this._currentCodeLensModel?.isDisposed ? this._currentCodeLensModel : void 0;
    }
  }, _w.ID = "css.editor.codeLens", _w);
  CodeLensContribution = __decorate$2e([
    __param$2c(1, ILanguageFeaturesService),
    __param$2c(2, ILanguageFeatureDebounceService),
    __param$2c(3, ICommandService),
    __param$2c(4, INotificationService),
    __param$2c(5, ICodeLensCache)
  ], CodeLensContribution);
  registerEditorContribution(
    CodeLensContribution.ID,
    CodeLensContribution,
    1
    /* EditorContributionInstantiation.AfterFirstRender */
  );
  registerEditorAction(class ShowLensesInCurrentLine extends EditorAction {
    constructor() {
      super({
        id: "codelens.showLensesInCurrentLine",
        precondition: EditorContextKeys.hasCodeLensProvider,
        label: localize2(884, "Show CodeLens Commands for Current Line")
      });
    }
    async run(accessor, editor2) {
      if (!editor2.hasModel()) {
        return;
      }
      const quickInputService = accessor.get(IQuickInputService);
      const commandService = accessor.get(ICommandService);
      const notificationService = accessor.get(INotificationService);
      const lineNumber = editor2.getSelection().positionLineNumber;
      const codelensController = editor2.getContribution(CodeLensContribution.ID);
      if (!codelensController) {
        return;
      }
      const model = await codelensController.getModel();
      if (!model) {
        return;
      }
      const items = [];
      for (const lens of model.lenses) {
        if (lens.symbol.command && lens.symbol.range.startLineNumber === lineNumber) {
          items.push({
            label: lens.symbol.command.title,
            command: lens.symbol.command
          });
        }
      }
      if (items.length === 0) {
        return;
      }
      const item = await quickInputService.pick(items, {
        canPickMany: false,
        placeHolder: localize(883, "Select a command")
      });
      if (!item) {
        return;
      }
      let command = item.command;
      if (model.isDisposed) {
        const newModel = await codelensController.getModel();
        const newLens = newModel?.lenses.find((lens) => lens.symbol.range.startLineNumber === lineNumber && lens.symbol.command?.title === command.title);
        if (!newLens || !newLens.symbol.command) {
          return;
        }
        command = newLens.symbol.command;
      }
      try {
        await commandService.executeCommand(command.id, ...command.arguments || []);
      } catch (err) {
        notificationService.error(err);
      }
    }
  });
  const editorFeatures = [];
  function registerEditorFeature(ctor) {
    editorFeatures.push(ctor);
  }
  function getEditorFeatures() {
    return editorFeatures.slice(0);
  }
  class HoverRangeAnchor {
    constructor(priority, range2, initialMousePosX, initialMousePosY) {
      this.priority = priority;
      this.range = range2;
      this.initialMousePosX = initialMousePosX;
      this.initialMousePosY = initialMousePosY;
      this.type = 1;
    }
    equals(other) {
      return other.type === 1 && this.range.equalsRange(other.range);
    }
    canAdoptVisibleHover(lastAnchor, showAtPosition) {
      return lastAnchor.type === 1 && showAtPosition.lineNumber === this.range.startLineNumber;
    }
  }
  class HoverForeignElementAnchor {
    constructor(priority, owner, range2, initialMousePosX, initialMousePosY, supportsMarkerHover) {
      this.priority = priority;
      this.owner = owner;
      this.range = range2;
      this.initialMousePosX = initialMousePosX;
      this.initialMousePosY = initialMousePosY;
      this.supportsMarkerHover = supportsMarkerHover;
      this.type = 2;
    }
    equals(other) {
      return other.type === 2 && this.owner === other.owner;
    }
    canAdoptVisibleHover(lastAnchor, showAtPosition) {
      return lastAnchor.type === 2 && this.owner === lastAnchor.owner;
    }
  }
  class RenderedHoverParts {
    constructor(renderedHoverParts, disposables) {
      this.renderedHoverParts = renderedHoverParts;
      this.disposables = disposables;
    }
    dispose() {
      for (const part of this.renderedHoverParts) {
        part.dispose();
      }
      this.disposables?.dispose();
    }
  }
  const HoverParticipantRegistry = new class HoverParticipantRegistry {
    constructor() {
      this._participants = [];
    }
    register(ctor) {
      this._participants.push(ctor);
    }
    getAll() {
      return this._participants;
    }
  }();
  var __decorate$2d = 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$2b = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  let DefaultDocumentColorProvider = class DefaultDocumentColorProvider {
    constructor(_editorWorkerService) {
      this._editorWorkerService = _editorWorkerService;
    }
    async provideDocumentColors(model, _token) {
      return this._editorWorkerService.computeDefaultDocumentColors(model.uri);
    }
    provideColorPresentations(_model, colorInfo, _token) {
      const range2 = colorInfo.range;
      const colorFromInfo = colorInfo.color;
      const alpha = colorFromInfo.alpha;
      const color = new Color(new RGBA(Math.round(255 * colorFromInfo.red), Math.round(255 * colorFromInfo.green), Math.round(255 * colorFromInfo.blue), alpha));
      const rgb = alpha ? Color.Format.CSS.formatRGBA(color) : Color.Format.CSS.formatRGB(color);
      const hsl = alpha ? Color.Format.CSS.formatHSLA(color) : Color.Format.CSS.formatHSL(color);
      const hex = alpha ? Color.Format.CSS.formatHexA(color) : Color.Format.CSS.formatHex(color);
      const colorPresentations = [];
      colorPresentations.push({ label: rgb, textEdit: { range: range2, text: rgb } });
      colorPresentations.push({ label: hsl, textEdit: { range: range2, text: hsl } });
      colorPresentations.push({ label: hex, textEdit: { range: range2, text: hex } });
      return colorPresentations;
    }
  };
  DefaultDocumentColorProvider = __decorate$2d([
    __param$2b(0, IEditorWorkerService)
  ], DefaultDocumentColorProvider);
  let DefaultDocumentColorProviderFeature = class DefaultDocumentColorProviderFeature extends Disposable {
    constructor(_languageFeaturesService, editorWorkerService) {
      super();
      this._register(_languageFeaturesService.colorProvider.register("*", new DefaultDocumentColorProvider(editorWorkerService)));
    }
  };
  DefaultDocumentColorProviderFeature = __decorate$2d([
    __param$2b(0, ILanguageFeaturesService),
    __param$2b(1, IEditorWorkerService)
  ], DefaultDocumentColorProviderFeature);
  async function getColors(colorProviderRegistry, model, token, defaultColorDecoratorsEnablement = "auto") {
    return _findColorData(new ColorDataCollector(), colorProviderRegistry, model, token, defaultColorDecoratorsEnablement);
  }
  function getColorPresentations(model, colorInfo, provider, token) {
    return Promise.resolve(provider.provideColorPresentations(model, colorInfo, token));
  }
  class ColorDataCollector {
    constructor() {
    }
    async compute(provider, model, token, colors) {
      const documentColors = await provider.provideDocumentColors(model, token);
      if (Array.isArray(documentColors)) {
        for (const colorInfo of documentColors) {
          colors.push({ colorInfo, provider });
        }
      }
      return Array.isArray(documentColors);
    }
  }
  class ExtColorDataCollector {
    constructor() {
    }
    async compute(provider, model, token, colors) {
      const documentColors = await provider.provideDocumentColors(model, token);
      if (Array.isArray(documentColors)) {
        for (const colorInfo of documentColors) {
          colors.push({ range: colorInfo.range, color: [colorInfo.color.red, colorInfo.color.green, colorInfo.color.blue, colorInfo.color.alpha] });
        }
      }
      return Array.isArray(documentColors);
    }
  }
  class ColorPresentationsCollector {
    constructor(colorInfo) {
      this.colorInfo = colorInfo;
    }
    async compute(provider, model, _token, colors) {
      const documentColors = await provider.provideColorPresentations(model, this.colorInfo, CancellationToken.None);
      if (Array.isArray(documentColors)) {
        colors.push(...documentColors);
      }
      return Array.isArray(documentColors);
    }
  }
  async function _findColorData(collector, colorProviderRegistry, model, token, defaultColorDecoratorsEnablement) {
    let validDocumentColorProviderFound = false;
    let defaultProvider;
    const colorData = [];
    const documentColorProviders = colorProviderRegistry.ordered(model);
    for (let i2 = documentColorProviders.length - 1; i2 >= 0; i2--) {
      const provider = documentColorProviders[i2];
      if (defaultColorDecoratorsEnablement !== "always" && provider instanceof DefaultDocumentColorProvider) {
        defaultProvider = provider;
      } else {
        try {
          if (await collector.compute(provider, model, token, colorData)) {
            validDocumentColorProviderFound = true;
          }
        } catch (e) {
          onUnexpectedExternalError(e);
        }
      }
    }
    if (validDocumentColorProviderFound) {
      return colorData;
    }
    if (defaultProvider && defaultColorDecoratorsEnablement !== "never") {
      await collector.compute(defaultProvider, model, token, colorData);
      return colorData;
    }
    return [];
  }
  function _setupColorCommand(accessor, resource) {
    const { colorProvider: colorProviderRegistry } = accessor.get(ILanguageFeaturesService);
    const model = accessor.get(IModelService).getModel(resource);
    if (!model) {
      throw illegalArgument();
    }
    const defaultColorDecoratorsEnablement = accessor.get(IConfigurationService).getValue("editor.defaultColorDecorators", { resource });
    return { model, colorProviderRegistry, defaultColorDecoratorsEnablement };
  }
  var __decorate$2c = 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$2a = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  var ColorDetector_1;
  const ColorDecorationInjectedTextMarker = /* @__PURE__ */ Object.create({});
  let ColorDetector = (_x = class extends Disposable {
    // ms
    constructor(_editor, _configurationService, _languageFeaturesService, languageFeatureDebounceService) {
      super();
      this._editor = _editor;
      this._configurationService = _configurationService;
      this._languageFeaturesService = _languageFeaturesService;
      this._localToDispose = this._register(new DisposableStore());
      this._decorationsIds = [];
      this._colorDatas = /* @__PURE__ */ new Map();
      this._decoratorLimitReporter = this._register(new DecoratorLimitReporter());
      this._colorDecorationClassRefs = this._register(new DisposableStore());
      this._colorDecoratorIds = this._editor.createDecorationsCollection();
      this._ruleFactory = this._register(new DynamicCssRules(this._editor));
      this._debounceInformation = languageFeatureDebounceService.for(_languageFeaturesService.colorProvider, "Document Colors", { min: ColorDetector_1.RECOMPUTE_TIME });
      this._register(_editor.onDidChangeModel(() => {
        this._isColorDecoratorsEnabled = this.isEnabled();
        this.updateColors();
      }));
      this._register(_editor.onDidChangeModelLanguage(() => this.updateColors()));
      this._register(_languageFeaturesService.colorProvider.onDidChange(() => this.updateColors()));
      this._register(_editor.onDidChangeConfiguration((e) => {
        const prevIsEnabled = this._isColorDecoratorsEnabled;
        this._isColorDecoratorsEnabled = this.isEnabled();
        this._defaultColorDecoratorsEnablement = this._editor.getOption(
          167
          /* EditorOption.defaultColorDecorators */
        );
        const updatedColorDecoratorsSetting = prevIsEnabled !== this._isColorDecoratorsEnabled || e.hasChanged(
          27
          /* EditorOption.colorDecoratorsLimit */
        );
        const updatedDefaultColorDecoratorsSetting = e.hasChanged(
          167
          /* EditorOption.defaultColorDecorators */
        );
        if (updatedColorDecoratorsSetting || updatedDefaultColorDecoratorsSetting) {
          if (this._isColorDecoratorsEnabled) {
            this.updateColors();
          } else {
            this.removeAllDecorations();
          }
        }
      }));
      this._timeoutTimer = null;
      this._computePromise = null;
      this._isColorDecoratorsEnabled = this.isEnabled();
      this._defaultColorDecoratorsEnablement = this._editor.getOption(
        167
        /* EditorOption.defaultColorDecorators */
      );
      this.updateColors();
    }
    isEnabled() {
      const model = this._editor.getModel();
      if (!model) {
        return false;
      }
      const languageId = model.getLanguageId();
      const deprecatedConfig = this._configurationService.getValue(languageId);
      if (deprecatedConfig && typeof deprecatedConfig === "object") {
        const colorDecorators = deprecatedConfig["colorDecorators"];
        if (colorDecorators && colorDecorators["enable"] !== void 0 && !colorDecorators["enable"]) {
          return colorDecorators["enable"];
        }
      }
      return this._editor.getOption(
        26
        /* EditorOption.colorDecorators */
      );
    }
    static get(editor2) {
      return editor2.getContribution(this.ID);
    }
    dispose() {
      this.stop();
      this.removeAllDecorations();
      super.dispose();
    }
    updateColors() {
      this.stop();
      if (!this._isColorDecoratorsEnabled) {
        return;
      }
      const model = this._editor.getModel();
      if (!model || !this._languageFeaturesService.colorProvider.has(model)) {
        return;
      }
      this._localToDispose.add(this._editor.onDidChangeModelContent(() => {
        if (!this._timeoutTimer) {
          this._timeoutTimer = new TimeoutTimer();
          this._timeoutTimer.cancelAndSet(() => {
            this._timeoutTimer = null;
            this.beginCompute();
          }, this._debounceInformation.get(model));
        }
      }));
      this.beginCompute();
    }
    async beginCompute() {
      this._computePromise = createCancelablePromise(async (token) => {
        const model = this._editor.getModel();
        if (!model) {
          return [];
        }
        const sw = new StopWatch(false);
        const colors = await getColors(this._languageFeaturesService.colorProvider, model, token, this._defaultColorDecoratorsEnablement);
        this._debounceInformation.update(model, sw.elapsed());
        return colors;
      });
      try {
        const colors = await this._computePromise;
        this.updateDecorations(colors);
        this.updateColorDecorators(colors);
        this._computePromise = null;
      } catch (e) {
        onUnexpectedError(e);
      }
    }
    stop() {
      if (this._timeoutTimer) {
        this._timeoutTimer.cancel();
        this._timeoutTimer = null;
      }
      if (this._computePromise) {
        this._computePromise.cancel();
        this._computePromise = null;
      }
      this._localToDispose.clear();
    }
    updateDecorations(colorDatas) {
      const decorations = colorDatas.map((c) => ({
        range: {
          startLineNumber: c.colorInfo.range.startLineNumber,
          startColumn: c.colorInfo.range.startColumn,
          endLineNumber: c.colorInfo.range.endLineNumber,
          endColumn: c.colorInfo.range.endColumn
        },
        options: ModelDecorationOptions.EMPTY
      }));
      this._editor.changeDecorations((changeAccessor) => {
        this._decorationsIds = changeAccessor.deltaDecorations(this._decorationsIds, decorations);
        this._colorDatas = /* @__PURE__ */ new Map();
        this._decorationsIds.forEach((id, i2) => this._colorDatas.set(id, colorDatas[i2]));
      });
    }
    updateColorDecorators(colorData) {
      this._colorDecorationClassRefs.clear();
      const decorations = [];
      const limit = this._editor.getOption(
        27
        /* EditorOption.colorDecoratorsLimit */
      );
      for (let i2 = 0; i2 < colorData.length && decorations.length < limit; i2++) {
        const { red, green, blue, alpha } = colorData[i2].colorInfo.color;
        const rgba = new RGBA(Math.round(red * 255), Math.round(green * 255), Math.round(blue * 255), alpha);
        const color = `rgba(${rgba.r}, ${rgba.g}, ${rgba.b}, ${rgba.a})`;
        const ref = this._colorDecorationClassRefs.add(this._ruleFactory.createClassNameRef({
          backgroundColor: color
        }));
        decorations.push({
          range: {
            startLineNumber: colorData[i2].colorInfo.range.startLineNumber,
            startColumn: colorData[i2].colorInfo.range.startColumn,
            endLineNumber: colorData[i2].colorInfo.range.endLineNumber,
            endColumn: colorData[i2].colorInfo.range.endColumn
          },
          options: {
            description: "colorDetector",
            before: {
              content: noBreakWhitespace,
              inlineClassName: `${ref.className} colorpicker-color-decoration`,
              inlineClassNameAffectsLetterSpacing: true,
              attachedData: ColorDecorationInjectedTextMarker
            }
          }
        });
      }
      const limited = limit < colorData.length ? limit : false;
      this._decoratorLimitReporter.update(colorData.length, limited);
      this._colorDecoratorIds.set(decorations);
    }
    removeAllDecorations() {
      this._editor.removeDecorations(this._decorationsIds);
      this._decorationsIds = [];
      this._colorDecoratorIds.clear();
      this._colorDecorationClassRefs.clear();
    }
    getColorData(position) {
      const model = this._editor.getModel();
      if (!model) {
        return null;
      }
      const decorations = model.getDecorationsInRange(Range$2.fromPositions(position, position)).filter((d) => this._colorDatas.has(d.id));
      if (decorations.length === 0) {
        return null;
      }
      return this._colorDatas.get(decorations[0].id);
    }
    isColorDecoration(decoration2) {
      return this._colorDecoratorIds.has(decoration2);
    }
  }, ColorDetector_1 = _x, _x.ID = "editor.contrib.colorDetector", _x.RECOMPUTE_TIME = 1e3, _x);
  ColorDetector = ColorDetector_1 = __decorate$2c([
    __param$2a(1, IConfigurationService),
    __param$2a(2, ILanguageFeaturesService),
    __param$2a(3, ILanguageFeatureDebounceService)
  ], ColorDetector);
  class DecoratorLimitReporter extends Disposable {
    constructor() {
      super(...arguments);
      this._onDidChange = this._register(new Emitter$1());
      this._computed = 0;
      this._limited = false;
    }
    update(computed, limited) {
      if (computed !== this._computed || limited !== this._limited) {
        this._computed = computed;
        this._limited = limited;
        this._onDidChange.fire();
      }
    }
  }
  const SHOW_OR_FOCUS_HOVER_ACTION_ID = "editor.action.showHover";
  const SHOW_DEFINITION_PREVIEW_HOVER_ACTION_ID = "editor.action.showDefinitionPreviewHover";
  const HIDE_HOVER_ACTION_ID = "editor.action.hideHover";
  const SCROLL_UP_HOVER_ACTION_ID = "editor.action.scrollUpHover";
  const SCROLL_DOWN_HOVER_ACTION_ID = "editor.action.scrollDownHover";
  const SCROLL_LEFT_HOVER_ACTION_ID = "editor.action.scrollLeftHover";
  const SCROLL_RIGHT_HOVER_ACTION_ID = "editor.action.scrollRightHover";
  const PAGE_UP_HOVER_ACTION_ID = "editor.action.pageUpHover";
  const PAGE_DOWN_HOVER_ACTION_ID = "editor.action.pageDownHover";
  const GO_TO_TOP_HOVER_ACTION_ID = "editor.action.goToTopHover";
  const GO_TO_BOTTOM_HOVER_ACTION_ID = "editor.action.goToBottomHover";
  const INCREASE_HOVER_VERBOSITY_ACTION_ID = "editor.action.increaseHoverVerbosityLevel";
  const INCREASE_HOVER_VERBOSITY_ACTION_LABEL = localize(1102, "Increase Hover Verbosity Level");
  const DECREASE_HOVER_VERBOSITY_ACTION_ID = "editor.action.decreaseHoverVerbosityLevel";
  const DECREASE_HOVER_VERBOSITY_ACTION_LABEL = localize(1103, "Decrease Hover Verbosity Level");
  const inlineSuggestCommitId = "editor.action.inlineSuggest.commit";
  const showPreviousInlineSuggestionActionId = "editor.action.inlineSuggest.showPrevious";
  const showNextInlineSuggestionActionId = "editor.action.inlineSuggest.showNext";
  const jumpToNextInlineEditId = "editor.action.inlineSuggest.jump";
  const hideInlineCompletionId = "editor.action.inlineSuggest.hide";
  const toggleShowCollapsedId = "editor.action.inlineSuggest.toggleShowCollapsed";
  var __decorate$2b = 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$29 = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  var InlineSuggestionHintsContentWidget_1;
  let InlineCompletionsHintsWidget = class InlineCompletionsHintsWidget extends Disposable {
    constructor(editor2, model, instantiationService) {
      super();
      this.editor = editor2;
      this.model = model;
      this.instantiationService = instantiationService;
      this.alwaysShowToolbar = observableFromEvent(this, this.editor.onDidChangeConfiguration, () => this.editor.getOption(
        71
        /* EditorOption.inlineSuggest */
      ).showToolbar === "always");
      this.sessionPosition = void 0;
      this.position = derived(this, (reader) => {
        const ghostText = this.model.read(reader)?.primaryGhostText.read(reader);
        if (!this.alwaysShowToolbar.read(reader) || !ghostText || ghostText.parts.length === 0) {
          this.sessionPosition = void 0;
          return null;
        }
        const firstColumn = ghostText.parts[0].column;
        if (this.sessionPosition && this.sessionPosition.lineNumber !== ghostText.lineNumber) {
          this.sessionPosition = void 0;
        }
        const position = new Position$1(ghostText.lineNumber, Math.min(firstColumn, this.sessionPosition?.column ?? Number.MAX_SAFE_INTEGER));
        this.sessionPosition = position;
        return position;
      });
      this._register(autorunWithStore((reader, store) => {
        const model2 = this.model.read(reader);
        if (!model2 || !this.alwaysShowToolbar.read(reader)) {
          return;
        }
        const contentWidgetValue = derived((reader2) => {
          const contentWidget = reader2.store.add(this.instantiationService.createInstance(InlineSuggestionHintsContentWidget.hot.read(reader2), this.editor, true, this.position, model2.selectedInlineCompletionIndex, model2.inlineCompletionsCount, model2.activeCommands, model2.warning, () => {
          }));
          editor2.addContentWidget(contentWidget);
          reader2.store.add(toDisposable(() => editor2.removeContentWidget(contentWidget)));
          reader2.store.add(autorun((reader3) => {
            const position = this.position.read(reader3);
            if (!position) {
              return;
            }
            if (model2.lastTriggerKind.read(reader3) !== InlineCompletionTriggerKind$1.Explicit) {
              model2.triggerExplicitly();
            }
          }));
          return contentWidget;
        });
        const hadPosition = derivedObservableWithCache(this, (reader2, lastValue) => !!this.position.read(reader2) || !!lastValue);
        store.add(autorun((reader2) => {
          if (hadPosition.read(reader2)) {
            contentWidgetValue.read(reader2);
          }
        }));
      }));
    }
  };
  InlineCompletionsHintsWidget = __decorate$2b([
    __param$29(2, IInstantiationService)
  ], InlineCompletionsHintsWidget);
  const inlineSuggestionHintsNextIcon = registerIcon("inline-suggestion-hints-next", Codicon.chevronRight, localize(1207, "Icon for show next parameter hint."));
  const inlineSuggestionHintsPreviousIcon = registerIcon("inline-suggestion-hints-previous", Codicon.chevronLeft, localize(1208, "Icon for show previous parameter hint."));
  let InlineSuggestionHintsContentWidget = (_y = class extends Disposable {
    static get dropDownVisible() {
      return this._dropDownVisible;
    }
    createCommandAction(commandId, label, iconClassName) {
      const action = new Action(commandId, label, iconClassName, true, () => this._commandService.executeCommand(commandId));
      const kb = this.keybindingService.lookupKeybinding(commandId, this._contextKeyService);
      let tooltip = label;
      if (kb) {
        tooltip = localize(1209, "{0} ({1})", label, kb.getLabel());
      }
      action.tooltip = tooltip;
      return action;
    }
    constructor(editor2, withBorder, _position, _currentSuggestionIdx, _suggestionCount, _extraCommands, _warning, _relayout, _commandService, instantiationService, keybindingService, _contextKeyService, _menuService) {
      super();
      this.editor = editor2;
      this.withBorder = withBorder;
      this._position = _position;
      this._currentSuggestionIdx = _currentSuggestionIdx;
      this._suggestionCount = _suggestionCount;
      this._extraCommands = _extraCommands;
      this._warning = _warning;
      this._relayout = _relayout;
      this._commandService = _commandService;
      this.keybindingService = keybindingService;
      this._contextKeyService = _contextKeyService;
      this._menuService = _menuService;
      this.id = `InlineSuggestionHintsContentWidget${InlineSuggestionHintsContentWidget_1.id++}`;
      this.allowEditorOverflow = true;
      this.suppressMouseDown = false;
      this._warningMessageContentNode = derived((reader) => {
        const warning = this._warning.read(reader);
        if (!warning) {
          return void 0;
        }
        if (typeof warning.message === "string") {
          return warning.message;
        }
        const markdownElement = reader.store.add(renderMarkdown$1(warning.message));
        return markdownElement.element;
      });
      this._warningMessageNode = n.div({
        class: "warningMessage",
        style: {
          maxWidth: 400,
          margin: 4,
          marginBottom: 4,
          display: derived((reader) => this._warning.read(reader) ? "block" : "none")
        }
      }, [
        this._warningMessageContentNode
      ]).keepUpdated(this._store);
      this.nodes = h("div.inlineSuggestionsHints", { className: this.withBorder ? "monaco-hover monaco-hover-content" : "" }, [
        this._warningMessageNode.element,
        h("div@toolBar")
      ]);
      this.previousAction = this._register(this.createCommandAction(showPreviousInlineSuggestionActionId, localize(1210, "Previous"), ThemeIcon.asClassName(inlineSuggestionHintsPreviousIcon)));
      this.availableSuggestionCountAction = this._register(new Action("inlineSuggestionHints.availableSuggestionCount", "", void 0, false));
      this.nextAction = this._register(this.createCommandAction(showNextInlineSuggestionActionId, localize(1211, "Next"), ThemeIcon.asClassName(inlineSuggestionHintsNextIcon)));
      this.inlineCompletionsActionsMenus = this._register(this._menuService.createMenu(MenuId.InlineCompletionsActions, this._contextKeyService));
      this.clearAvailableSuggestionCountLabelDebounced = this._register(new RunOnceScheduler(() => {
        this.availableSuggestionCountAction.label = "";
      }, 100));
      this.disableButtonsDebounced = this._register(new RunOnceScheduler(() => {
        this.previousAction.enabled = this.nextAction.enabled = false;
      }, 100));
      this._register(autorun((reader) => {
        this._warningMessageContentNode.read(reader);
        this._warningMessageNode.readEffect(reader);
        this._relayout();
      }));
      this.toolBar = this._register(instantiationService.createInstance(CustomizedMenuWorkbenchToolBar, this.nodes.toolBar, MenuId.InlineSuggestionToolbar, {
        menuOptions: { renderShortTitle: true },
        toolbarOptions: { primaryGroup: (g) => g.startsWith("primary") },
        actionViewItemProvider: (action, options) => {
          if (action instanceof MenuItemAction) {
            return instantiationService.createInstance(StatusBarViewItem, action, void 0);
          }
          if (action === this.availableSuggestionCountAction) {
            const a = new ActionViewItemWithClassName(void 0, action, { label: true, icon: false });
            a.setClass("availableSuggestionCount");
            return a;
          }
          return void 0;
        },
        telemetrySource: "InlineSuggestionToolbar"
      }));
      this.toolBar.setPrependedPrimaryActions([
        this.previousAction,
        this.availableSuggestionCountAction,
        this.nextAction
      ]);
      this._register(this.toolBar.onDidChangeDropdownVisibility((e) => {
        InlineSuggestionHintsContentWidget_1._dropDownVisible = e;
      }));
      this._register(autorun((reader) => {
        this._position.read(reader);
        this.editor.layoutContentWidget(this);
      }));
      this._register(autorun((reader) => {
        const suggestionCount = this._suggestionCount.read(reader);
        const currentSuggestionIdx = this._currentSuggestionIdx.read(reader);
        if (suggestionCount !== void 0) {
          this.clearAvailableSuggestionCountLabelDebounced.cancel();
          this.availableSuggestionCountAction.label = `${currentSuggestionIdx + 1}/${suggestionCount}`;
        } else {
          this.clearAvailableSuggestionCountLabelDebounced.schedule();
        }
        if (suggestionCount !== void 0 && suggestionCount > 1) {
          this.disableButtonsDebounced.cancel();
          this.previousAction.enabled = this.nextAction.enabled = true;
        } else {
          this.disableButtonsDebounced.schedule();
        }
      }));
      this._register(autorun((reader) => {
        const extraCommands = this._extraCommands.read(reader);
        const extraActions = extraCommands.map((c) => ({
          class: void 0,
          id: c.command.id,
          enabled: true,
          tooltip: c.command.tooltip || "",
          label: c.command.title,
          run: (event) => {
            return this._commandService.executeCommand(c.command.id);
          }
        }));
        for (const [_, group] of this.inlineCompletionsActionsMenus.getActions()) {
          for (const action of group) {
            if (action instanceof MenuItemAction) {
              extraActions.push(action);
            }
          }
        }
        if (extraActions.length > 0) {
          extraActions.unshift(new Separator());
        }
        this.toolBar.setAdditionalSecondaryActions(extraActions);
      }));
    }
    getId() {
      return this.id;
    }
    getDomNode() {
      return this.nodes.root;
    }
    getPosition() {
      return {
        position: this._position.get(),
        preference: [
          1,
          2
          /* ContentWidgetPositionPreference.BELOW */
        ],
        positionAffinity: 3
      };
    }
  }, InlineSuggestionHintsContentWidget_1 = _y, _y.hot = createHotClass(_y), _y._dropDownVisible = false, _y.id = 0, _y);
  InlineSuggestionHintsContentWidget = InlineSuggestionHintsContentWidget_1 = __decorate$2b([
    __param$29(8, ICommandService),
    __param$29(9, IInstantiationService),
    __param$29(10, IKeybindingService),
    __param$29(11, IContextKeyService),
    __param$29(12, IMenuService)
  ], InlineSuggestionHintsContentWidget);
  class ActionViewItemWithClassName extends ActionViewItem {
    constructor() {
      super(...arguments);
      this._className = void 0;
    }
    setClass(className2) {
      this._className = className2;
    }
    render(container) {
      super.render(container);
      if (this._className) {
        container.classList.add(this._className);
      }
    }
    updateTooltip() {
    }
  }
  class StatusBarViewItem extends MenuEntryActionViewItem {
    updateLabel() {
      const kb = this._keybindingService.lookupKeybinding(this._action.id, this._contextKeyService, true);
      if (!kb) {
        return super.updateLabel();
      }
      if (this.label) {
        const div = h("div.keybinding").root;
        const k = this._register(new KeybindingLabel(div, OS, { disableTitle: true, ...unthemedKeybindingLabelOptions }));
        k.set(kb);
        this.label.textContent = this._action.label;
        this.label.appendChild(div);
        this.label.classList.add("inlineSuggestionStatusBarItemLabel");
      }
    }
    updateTooltip() {
    }
  }
  let CustomizedMenuWorkbenchToolBar = class CustomizedMenuWorkbenchToolBar extends WorkbenchToolBar {
    constructor(container, menuId, options2, menuService, contextKeyService, contextMenuService, keybindingService, commandService, telemetryService) {
      super(container, { resetMenu: menuId, ...options2 }, menuService, contextKeyService, contextMenuService, keybindingService, commandService, telemetryService);
      this.menuId = menuId;
      this.options2 = options2;
      this.menuService = menuService;
      this.contextKeyService = contextKeyService;
      this.menu = this._store.add(this.menuService.createMenu(this.menuId, this.contextKeyService, { emitEventsForSubmenuChanges: true }));
      this.additionalActions = [];
      this.prependedPrimaryActions = [];
      this.additionalPrimaryActions = [];
      this._store.add(this.menu.onDidChange(() => this.updateToolbar()));
      this.updateToolbar();
    }
    updateToolbar() {
      const { primary, secondary } = getActionBarActions(this.menu.getActions(this.options2?.menuOptions), this.options2?.toolbarOptions?.primaryGroup, this.options2?.toolbarOptions?.shouldInlineSubmenu, this.options2?.toolbarOptions?.useSeparatorsInPrimaryActions);
      secondary.push(...this.additionalActions);
      primary.unshift(...this.prependedPrimaryActions);
      primary.push(...this.additionalPrimaryActions);
      this.setActions(primary, secondary);
    }
    setPrependedPrimaryActions(actions) {
      if (equals$1(this.prependedPrimaryActions, actions, (a, b) => a === b)) {
        return;
      }
      this.prependedPrimaryActions = actions;
      this.updateToolbar();
    }
    setAdditionalSecondaryActions(actions) {
      if (equals$1(this.additionalActions, actions, (a, b) => a === b)) {
        return;
      }
      this.additionalActions = actions;
      this.updateToolbar();
    }
  };
  CustomizedMenuWorkbenchToolBar = __decorate$2b([
    __param$29(3, IMenuService),
    __param$29(4, IContextKeyService),
    __param$29(5, IContextMenuService),
    __param$29(6, IKeybindingService),
    __param$29(7, ICommandService),
    __param$29(8, ITelemetryService)
  ], CustomizedMenuWorkbenchToolBar);
  function isMousePositionWithinElement(element, posx, posy) {
    const elementRect = getDomNodePagePosition(element);
    if (posx < elementRect.left || posx > elementRect.left + elementRect.width || posy < elementRect.top || posy > elementRect.top + elementRect.height) {
      return false;
    }
    return true;
  }
  class HoverResult {
    constructor(value, isComplete, hasLoadingMessage, options) {
      this.value = value;
      this.isComplete = isComplete;
      this.hasLoadingMessage = hasLoadingMessage;
      this.options = options;
    }
  }
  class HoverOperation extends Disposable {
    constructor(_editor, _computer) {
      super();
      this._editor = _editor;
      this._computer = _computer;
      this._onResult = this._register(new Emitter$1());
      this.onResult = this._onResult.event;
      this._asyncComputationScheduler = this._register(new Debouncer((options) => this._triggerAsyncComputation(options), 0));
      this._syncComputationScheduler = this._register(new Debouncer((options) => this._triggerSyncComputation(options), 0));
      this._loadingMessageScheduler = this._register(new Debouncer((options) => this._triggerLoadingMessage(options), 0));
      this._state = 0;
      this._asyncIterable = null;
      this._asyncIterableDone = false;
      this._result = [];
    }
    dispose() {
      if (this._asyncIterable) {
        this._asyncIterable.cancel();
        this._asyncIterable = null;
      }
      this._options = void 0;
      super.dispose();
    }
    get _hoverTime() {
      return this._editor.getOption(
        69
        /* EditorOption.hover */
      ).delay;
    }
    get _firstWaitTime() {
      return this._hoverTime / 2;
    }
    get _secondWaitTime() {
      return this._hoverTime - this._firstWaitTime;
    }
    get _loadingMessageTime() {
      return 3 * this._hoverTime;
    }
    _setState(state, options) {
      this._options = options;
      this._state = state;
      this._fireResult(options);
    }
    _triggerAsyncComputation(options) {
      this._setState(2, options);
      this._syncComputationScheduler.schedule(options, this._secondWaitTime);
      if (this._computer.computeAsync) {
        this._asyncIterableDone = false;
        this._asyncIterable = createCancelableAsyncIterableProducer((token) => this._computer.computeAsync(options, token));
        (async () => {
          try {
            for await (const item of this._asyncIterable) {
              if (item) {
                this._result.push(item);
                this._fireResult(options);
              }
            }
            this._asyncIterableDone = true;
            if (this._state === 3 || this._state === 4) {
              this._setState(0, options);
            }
          } catch (e) {
            onUnexpectedError(e);
          }
        })();
      } else {
        this._asyncIterableDone = true;
      }
    }
    _triggerSyncComputation(options) {
      if (this._computer.computeSync) {
        this._result = this._result.concat(this._computer.computeSync(options));
      }
      this._setState(this._asyncIterableDone ? 0 : 3, options);
    }
    _triggerLoadingMessage(options) {
      if (this._state === 3) {
        this._setState(4, options);
      }
    }
    _fireResult(options) {
      if (this._state === 1 || this._state === 2) {
        return;
      }
      const isComplete = this._state === 0;
      const hasLoadingMessage = this._state === 4;
      this._onResult.fire(new HoverResult(this._result.slice(0), isComplete, hasLoadingMessage, options));
    }
    start(mode, options) {
      if (mode === 0) {
        if (this._state === 0) {
          this._setState(1, options);
          this._asyncComputationScheduler.schedule(options, this._firstWaitTime);
          this._loadingMessageScheduler.schedule(options, this._loadingMessageTime);
        }
      } else {
        switch (this._state) {
          case 0:
            this._triggerAsyncComputation(options);
            this._syncComputationScheduler.cancel();
            this._triggerSyncComputation(options);
            break;
          case 2:
            this._syncComputationScheduler.cancel();
            this._triggerSyncComputation(options);
            break;
        }
      }
    }
    cancel() {
      this._asyncComputationScheduler.cancel();
      this._syncComputationScheduler.cancel();
      this._loadingMessageScheduler.cancel();
      if (this._asyncIterable) {
        this._asyncIterable.cancel();
        this._asyncIterable = null;
      }
      this._result = [];
      this._options = void 0;
      this._state = 0;
    }
    get options() {
      return this._options;
    }
  }
  class Debouncer extends Disposable {
    constructor(runner, debounceTimeMs) {
      super();
      this._scheduler = this._register(new RunOnceScheduler(() => runner(this._options), debounceTimeMs));
    }
    schedule(options, debounceTimeMs) {
      this._options = options;
      this._scheduler.schedule(debounceTimeMs);
    }
    cancel() {
      this._scheduler.cancel();
    }
  }
  class ResizableHTMLElement {
    get onDidWillResize() {
      return this._onDidWillResize.event;
    }
    get onDidResize() {
      return this._onDidResize.event;
    }
    constructor() {
      this._onDidWillResize = new Emitter$1();
      this._onDidResize = new Emitter$1();
      this._sashListener = new DisposableStore();
      this._size = new Dimension(0, 0);
      this._minSize = new Dimension(0, 0);
      this._maxSize = new Dimension(Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER);
      this.domNode = document.createElement("div");
      this._eastSash = new Sash(this.domNode, { getVerticalSashLeft: () => this._size.width }, {
        orientation: 0
        /* Orientation.VERTICAL */
      });
      this._westSash = new Sash(this.domNode, { getVerticalSashLeft: () => 0 }, {
        orientation: 0
        /* Orientation.VERTICAL */
      });
      this._northSash = new Sash(this.domNode, { getHorizontalSashTop: () => 0 }, { orientation: 1, orthogonalEdge: OrthogonalEdge.North });
      this._southSash = new Sash(this.domNode, { getHorizontalSashTop: () => this._size.height }, { orientation: 1, orthogonalEdge: OrthogonalEdge.South });
      this._northSash.orthogonalStartSash = this._westSash;
      this._northSash.orthogonalEndSash = this._eastSash;
      this._southSash.orthogonalStartSash = this._westSash;
      this._southSash.orthogonalEndSash = this._eastSash;
      let currentSize;
      let deltaY = 0;
      let deltaX = 0;
      this._sashListener.add(Event.any(this._northSash.onDidStart, this._eastSash.onDidStart, this._southSash.onDidStart, this._westSash.onDidStart)(() => {
        if (currentSize === void 0) {
          this._onDidWillResize.fire();
          currentSize = this._size;
          deltaY = 0;
          deltaX = 0;
        }
      }));
      this._sashListener.add(Event.any(this._northSash.onDidEnd, this._eastSash.onDidEnd, this._southSash.onDidEnd, this._westSash.onDidEnd)(() => {
        if (currentSize !== void 0) {
          currentSize = void 0;
          deltaY = 0;
          deltaX = 0;
          this._onDidResize.fire({ dimension: this._size, done: true });
        }
      }));
      this._sashListener.add(this._eastSash.onDidChange((e) => {
        if (currentSize) {
          deltaX = e.currentX - e.startX;
          this.layout(currentSize.height + deltaY, currentSize.width + deltaX);
          this._onDidResize.fire({ dimension: this._size, done: false, east: true });
        }
      }));
      this._sashListener.add(this._westSash.onDidChange((e) => {
        if (currentSize) {
          deltaX = -(e.currentX - e.startX);
          this.layout(currentSize.height + deltaY, currentSize.width + deltaX);
          this._onDidResize.fire({ dimension: this._size, done: false, west: true });
        }
      }));
      this._sashListener.add(this._northSash.onDidChange((e) => {
        if (currentSize) {
          deltaY = -(e.currentY - e.startY);
          this.layout(currentSize.height + deltaY, currentSize.width + deltaX);
          this._onDidResize.fire({ dimension: this._size, done: false, north: true });
        }
      }));
      this._sashListener.add(this._southSash.onDidChange((e) => {
        if (currentSize) {
          deltaY = e.currentY - e.startY;
          this.layout(currentSize.height + deltaY, currentSize.width + deltaX);
          this._onDidResize.fire({ dimension: this._size, done: false, south: true });
        }
      }));
      this._sashListener.add(Event.any(this._eastSash.onDidReset, this._westSash.onDidReset)((e) => {
        if (this._preferredSize) {
          this.layout(this._size.height, this._preferredSize.width);
          this._onDidResize.fire({ dimension: this._size, done: true });
        }
      }));
      this._sashListener.add(Event.any(this._northSash.onDidReset, this._southSash.onDidReset)((e) => {
        if (this._preferredSize) {
          this.layout(this._preferredSize.height, this._size.width);
          this._onDidResize.fire({ dimension: this._size, done: true });
        }
      }));
    }
    dispose() {
      this._northSash.dispose();
      this._southSash.dispose();
      this._eastSash.dispose();
      this._westSash.dispose();
      this._sashListener.dispose();
      this._onDidResize.dispose();
      this._onDidWillResize.dispose();
      this.domNode.remove();
    }
    enableSashes(north, east, south, west) {
      this._northSash.state = north ? 3 : 0;
      this._eastSash.state = east ? 3 : 0;
      this._southSash.state = south ? 3 : 0;
      this._westSash.state = west ? 3 : 0;
    }
    layout(height = this.size.height, width2 = this.size.width) {
      const { height: minHeight, width: minWidth } = this._minSize;
      const { height: maxHeight, width: maxWidth } = this._maxSize;
      height = Math.max(minHeight, Math.min(maxHeight, height));
      width2 = Math.max(minWidth, Math.min(maxWidth, width2));
      const newSize = new Dimension(width2, height);
      if (!Dimension.equals(newSize, this._size)) {
        this.domNode.style.height = height + "px";
        this.domNode.style.width = width2 + "px";
        this._size = newSize;
        this._northSash.layout();
        this._eastSash.layout();
        this._southSash.layout();
        this._westSash.layout();
      }
    }
    clearSashHoverState() {
      this._eastSash.clearSashHoverState();
      this._westSash.clearSashHoverState();
      this._northSash.clearSashHoverState();
      this._southSash.clearSashHoverState();
    }
    get size() {
      return this._size;
    }
    set maxSize(value) {
      this._maxSize = value;
    }
    get maxSize() {
      return this._maxSize;
    }
    set minSize(value) {
      this._minSize = value;
    }
    get minSize() {
      return this._minSize;
    }
    set preferredSize(value) {
      this._preferredSize = value;
    }
    get preferredSize() {
      return this._preferredSize;
    }
  }
  const TOP_HEIGHT = 30;
  const BOTTOM_HEIGHT = 24;
  class ResizableContentWidget extends Disposable {
    constructor(_editor, minimumSize = new Dimension(10, 10)) {
      super();
      this._editor = _editor;
      this.allowEditorOverflow = true;
      this.suppressMouseDown = false;
      this._resizableNode = this._register(new ResizableHTMLElement());
      this._contentPosition = null;
      this._isResizing = false;
      this._resizableNode.domNode.style.position = "absolute";
      this._resizableNode.minSize = Dimension.lift(minimumSize);
      this._resizableNode.layout(minimumSize.height, minimumSize.width);
      this._resizableNode.enableSashes(true, true, true, true);
      this._register(this._resizableNode.onDidResize((e) => {
        this._resize(new Dimension(e.dimension.width, e.dimension.height));
        if (e.done) {
          this._isResizing = false;
        }
      }));
      this._register(this._resizableNode.onDidWillResize(() => {
        this._isResizing = true;
      }));
    }
    get isResizing() {
      return this._isResizing;
    }
    getDomNode() {
      return this._resizableNode.domNode;
    }
    getPosition() {
      return this._contentPosition;
    }
    get position() {
      return this._contentPosition?.position ? Position$1.lift(this._contentPosition.position) : void 0;
    }
    _availableVerticalSpaceAbove(position) {
      const editorDomNode = this._editor.getDomNode();
      const mouseBox = this._editor.getScrolledVisiblePosition(position);
      if (!editorDomNode || !mouseBox) {
        return;
      }
      const editorBox = getDomNodePagePosition(editorDomNode);
      return editorBox.top + mouseBox.top - TOP_HEIGHT;
    }
    _availableVerticalSpaceBelow(position) {
      const editorDomNode = this._editor.getDomNode();
      const mouseBox = this._editor.getScrolledVisiblePosition(position);
      if (!editorDomNode || !mouseBox) {
        return;
      }
      const editorBox = getDomNodePagePosition(editorDomNode);
      const bodyBox = getClientArea(editorDomNode.ownerDocument.body);
      const mouseBottom = editorBox.top + mouseBox.top + mouseBox.height;
      return bodyBox.height - mouseBottom - BOTTOM_HEIGHT;
    }
    _findPositionPreference(widgetHeight, showAtPosition) {
      const maxHeightBelow = Math.min(this._availableVerticalSpaceBelow(showAtPosition) ?? Infinity, widgetHeight);
      const maxHeightAbove = Math.min(this._availableVerticalSpaceAbove(showAtPosition) ?? Infinity, widgetHeight);
      const maxHeight = Math.min(Math.max(maxHeightAbove, maxHeightBelow), widgetHeight);
      const height = Math.min(widgetHeight, maxHeight);
      let renderingAbove;
      if (this._editor.getOption(
        69
        /* EditorOption.hover */
      ).above) {
        renderingAbove = height <= maxHeightAbove ? 1 : 2;
      } else {
        renderingAbove = height <= maxHeightBelow ? 2 : 1;
      }
      if (renderingAbove === 1) {
        this._resizableNode.enableSashes(true, true, false, false);
      } else {
        this._resizableNode.enableSashes(false, true, true, false);
      }
      return renderingAbove;
    }
    _resize(dimension) {
      this._resizableNode.layout(dimension.height, dimension.width);
    }
  }
  const $$i = $$l;
  let HoverWidget$1 = class HoverWidget extends Disposable {
    constructor(fadeIn) {
      super();
      this.containerDomNode = document.createElement("div");
      this.containerDomNode.className = "monaco-hover";
      this.containerDomNode.classList.toggle("fade-in", !!fadeIn);
      this.containerDomNode.tabIndex = 0;
      this.containerDomNode.setAttribute("role", "tooltip");
      this.contentsDomNode = document.createElement("div");
      this.contentsDomNode.className = "monaco-hover-content";
      this.scrollbar = this._register(new DomScrollableElement(this.contentsDomNode, {
        consumeMouseWheelIfScrollbarIsNeeded: true
      }));
      this.containerDomNode.appendChild(this.scrollbar.getDomNode());
    }
    onContentsChanged() {
      this.scrollbar.scanDomNode();
    }
  };
  class HoverAction extends Disposable {
    static render(parent, actionOptions, keybindingLabel) {
      return new HoverAction(parent, actionOptions, keybindingLabel);
    }
    constructor(parent, actionOptions, keybindingLabel) {
      super();
      this.actionLabel = actionOptions.label;
      this.actionKeybindingLabel = keybindingLabel;
      this.actionContainer = append$2(parent, $$i("div.action-container"));
      this.actionContainer.setAttribute("tabindex", "0");
      this.action = append$2(this.actionContainer, $$i("a.action"));
      this.action.setAttribute("role", "button");
      if (actionOptions.iconClass) {
        const iconElement = append$2(this.action, $$i(`span.icon`));
        iconElement.classList.add(...actionOptions.iconClass.split(" "));
      }
      this.actionRenderedLabel = keybindingLabel ? `${actionOptions.label} (${keybindingLabel})` : actionOptions.label;
      const label = append$2(this.action, $$i("span"));
      label.textContent = this.actionRenderedLabel;
      this._store.add(new ClickAction(this.actionContainer, actionOptions.run));
      this._store.add(new KeyDownAction(this.actionContainer, actionOptions.run, [
        3,
        10
        /* KeyCode.Space */
      ]));
      this.setEnabled(true);
    }
    setEnabled(enabled) {
      if (enabled) {
        this.actionContainer.classList.remove("disabled");
        this.actionContainer.removeAttribute("aria-disabled");
      } else {
        this.actionContainer.classList.add("disabled");
        this.actionContainer.setAttribute("aria-disabled", "true");
      }
    }
  }
  function getHoverAccessibleViewHint(shouldHaveHint, keybinding) {
    return shouldHaveHint && keybinding ? localize(7, "Inspect this in the accessible view with {0}.", keybinding) : shouldHaveHint ? localize(8, "Inspect this in the accessible view via the command Open Accessible View which is currently not triggerable via keybinding.") : "";
  }
  class ClickAction extends Disposable {
    constructor(container, run) {
      super();
      this._register(addDisposableListener(container, EventType$1.CLICK, (e) => {
        e.stopPropagation();
        e.preventDefault();
        run(container);
      }));
    }
  }
  class KeyDownAction extends Disposable {
    constructor(container, run, keyCodes) {
      super();
      this._register(addDisposableListener(container, EventType$1.KEY_DOWN, (e) => {
        const event = new StandardKeyboardEvent(e);
        if (keyCodes.some((keyCode) => event.equals(keyCode))) {
          e.stopPropagation();
          e.preventDefault();
          run(container);
        }
      }));
    }
  }
  var __decorate$2a = 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$28 = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  var ContentHoverWidget_1;
  const HORIZONTAL_SCROLLING_BY = 30;
  let ContentHoverWidget = (_z = class extends ResizableContentWidget {
    get isVisibleFromKeyboard() {
      return this._renderedHover?.source === 2;
    }
    get isVisible() {
      return this._hoverVisibleKey.get() ?? false;
    }
    get isFocused() {
      return this._hoverFocusedKey.get() ?? false;
    }
    constructor(editor2, contextKeyService, _configurationService, _accessibilityService, _keybindingService) {
      const minimumHeight = editor2.getOption(
        75
        /* EditorOption.lineHeight */
      ) + 8;
      const minimumWidth = 150;
      const minimumSize = new Dimension(minimumWidth, minimumHeight);
      super(editor2, minimumSize);
      this._configurationService = _configurationService;
      this._accessibilityService = _accessibilityService;
      this._keybindingService = _keybindingService;
      this._hover = this._register(new HoverWidget$1(true));
      this._onDidResize = this._register(new Emitter$1());
      this.onDidResize = this._onDidResize.event;
      this._onDidScroll = this._register(new Emitter$1());
      this.onDidScroll = this._onDidScroll.event;
      this._onContentsChanged = this._register(new Emitter$1());
      this.onContentsChanged = this._onContentsChanged.event;
      this._minimumSize = minimumSize;
      this._hoverVisibleKey = EditorContextKeys.hoverVisible.bindTo(contextKeyService);
      this._hoverFocusedKey = EditorContextKeys.hoverFocused.bindTo(contextKeyService);
      append$2(this._resizableNode.domNode, this._hover.containerDomNode);
      this._resizableNode.domNode.style.zIndex = "50";
      this._resizableNode.domNode.className = "monaco-resizable-hover";
      this._register(this._editor.onDidLayoutChange(() => {
        if (this.isVisible) {
          this._updateMaxDimensions();
        }
      }));
      this._register(this._editor.onDidChangeConfiguration((e) => {
        if (e.hasChanged(
          59
          /* EditorOption.fontInfo */
        )) {
          this._updateFont();
        }
      }));
      const focusTracker = this._register(trackFocus(this._resizableNode.domNode));
      this._register(focusTracker.onDidFocus(() => {
        this._hoverFocusedKey.set(true);
      }));
      this._register(focusTracker.onDidBlur(() => {
        this._hoverFocusedKey.set(false);
      }));
      this._register(this._hover.scrollbar.onScroll((e) => {
        this._onDidScroll.fire(e);
      }));
      this._setRenderedHover(void 0);
      this._editor.addContentWidget(this);
    }
    dispose() {
      super.dispose();
      this._renderedHover?.dispose();
      this._editor.removeContentWidget(this);
    }
    getId() {
      return ContentHoverWidget_1.ID;
    }
    static _applyDimensions(container, width2, height) {
      const transformedWidth = typeof width2 === "number" ? `${width2}px` : width2;
      const transformedHeight = typeof height === "number" ? `${height}px` : height;
      container.style.width = transformedWidth;
      container.style.height = transformedHeight;
    }
    _setContentsDomNodeDimensions(width2, height) {
      const contentsDomNode = this._hover.contentsDomNode;
      return ContentHoverWidget_1._applyDimensions(contentsDomNode, width2, height);
    }
    _setContainerDomNodeDimensions(width2, height) {
      const containerDomNode = this._hover.containerDomNode;
      return ContentHoverWidget_1._applyDimensions(containerDomNode, width2, height);
    }
    _setScrollableElementDimensions(width2, height) {
      const scrollbarDomElement = this._hover.scrollbar.getDomNode();
      return ContentHoverWidget_1._applyDimensions(scrollbarDomElement, width2, height);
    }
    _setHoverWidgetDimensions(width2, height) {
      this._setContainerDomNodeDimensions(width2, height);
      this._setScrollableElementDimensions(width2, height);
      this._setContentsDomNodeDimensions(width2, height);
      this._layoutContentWidget();
    }
    static _applyMaxDimensions(container, width2, height) {
      const transformedWidth = typeof width2 === "number" ? `${width2}px` : width2;
      const transformedHeight = typeof height === "number" ? `${height}px` : height;
      container.style.maxWidth = transformedWidth;
      container.style.maxHeight = transformedHeight;
    }
    _setHoverWidgetMaxDimensions(width2, height) {
      ContentHoverWidget_1._applyMaxDimensions(this._hover.contentsDomNode, width2, height);
      ContentHoverWidget_1._applyMaxDimensions(this._hover.scrollbar.getDomNode(), width2, height);
      ContentHoverWidget_1._applyMaxDimensions(this._hover.containerDomNode, width2, height);
      this._hover.containerDomNode.style.setProperty("--vscode-hover-maxWidth", typeof width2 === "number" ? `${width2}px` : width2);
      this._layoutContentWidget();
    }
    _setAdjustedHoverWidgetDimensions(size2) {
      this._setHoverWidgetMaxDimensions("none", "none");
      this._setHoverWidgetDimensions(size2.width, size2.height);
    }
    _updateResizableNodeMaxDimensions() {
      const maxRenderingWidth = this._findMaximumRenderingWidth() ?? Infinity;
      const maxRenderingHeight = this._findMaximumRenderingHeight() ?? Infinity;
      this._resizableNode.maxSize = new Dimension(maxRenderingWidth, maxRenderingHeight);
      this._setHoverWidgetMaxDimensions(maxRenderingWidth, maxRenderingHeight);
    }
    _resize(size2) {
      ContentHoverWidget_1._lastDimensions = new Dimension(size2.width, size2.height);
      this._setAdjustedHoverWidgetDimensions(size2);
      this._resizableNode.layout(size2.height, size2.width);
      this._updateResizableNodeMaxDimensions();
      this._hover.scrollbar.scanDomNode();
      this._editor.layoutContentWidget(this);
      this._onDidResize.fire();
    }
    _findAvailableSpaceVertically() {
      const position = this._renderedHover?.showAtPosition;
      if (!position) {
        return;
      }
      return this._positionPreference === 1 ? this._availableVerticalSpaceAbove(position) : this._availableVerticalSpaceBelow(position);
    }
    _findMaximumRenderingHeight() {
      const availableSpace = this._findAvailableSpaceVertically();
      if (!availableSpace) {
        return;
      }
      const children = this._hover.contentsDomNode.children;
      let maximumHeight = children.length - 1;
      Array.from(this._hover.contentsDomNode.children).forEach((hoverPart) => {
        maximumHeight += hoverPart.clientHeight;
      });
      return Math.min(availableSpace, maximumHeight);
    }
    _isHoverTextOverflowing() {
      this._hover.containerDomNode.style.setProperty("--vscode-hover-whiteSpace", "nowrap");
      this._hover.containerDomNode.style.setProperty("--vscode-hover-sourceWhiteSpace", "nowrap");
      const overflowing = Array.from(this._hover.contentsDomNode.children).some((hoverElement) => {
        return hoverElement.scrollWidth > hoverElement.clientWidth;
      });
      this._hover.containerDomNode.style.removeProperty("--vscode-hover-whiteSpace");
      this._hover.containerDomNode.style.removeProperty("--vscode-hover-sourceWhiteSpace");
      return overflowing;
    }
    _findMaximumRenderingWidth() {
      if (!this._editor || !this._editor.hasModel()) {
        return;
      }
      const overflowing = this._isHoverTextOverflowing();
      const initialWidth = typeof this._contentWidth === "undefined" ? 0 : this._contentWidth;
      if (overflowing || this._hover.containerDomNode.clientWidth < initialWidth) {
        const bodyBoxWidth = getClientArea(this._hover.containerDomNode.ownerDocument.body).width;
        const horizontalPadding = 14;
        return bodyBoxWidth - horizontalPadding;
      } else {
        return this._hover.containerDomNode.clientWidth;
      }
    }
    isMouseGettingCloser(posx, posy) {
      if (!this._renderedHover) {
        return false;
      }
      if (this._renderedHover.initialMousePosX === void 0 || this._renderedHover.initialMousePosY === void 0) {
        this._renderedHover.initialMousePosX = posx;
        this._renderedHover.initialMousePosY = posy;
        return false;
      }
      const widgetRect = getDomNodePagePosition(this.getDomNode());
      if (this._renderedHover.closestMouseDistance === void 0) {
        this._renderedHover.closestMouseDistance = computeDistanceFromPointToRectangle(this._renderedHover.initialMousePosX, this._renderedHover.initialMousePosY, widgetRect.left, widgetRect.top, widgetRect.width, widgetRect.height);
      }
      const distance = computeDistanceFromPointToRectangle(posx, posy, widgetRect.left, widgetRect.top, widgetRect.width, widgetRect.height);
      if (distance > this._renderedHover.closestMouseDistance + 4) {
        return false;
      }
      this._renderedHover.closestMouseDistance = Math.min(this._renderedHover.closestMouseDistance, distance);
      return true;
    }
    _setRenderedHover(renderedHover) {
      this._renderedHover?.dispose();
      this._renderedHover = renderedHover;
      this._hoverVisibleKey.set(!!renderedHover);
      this._hover.containerDomNode.classList.toggle("hidden", !renderedHover);
    }
    _updateFont() {
      const { fontSize, lineHeight } = this._editor.getOption(
        59
        /* EditorOption.fontInfo */
      );
      const contentsDomNode = this._hover.contentsDomNode;
      contentsDomNode.style.fontSize = `${fontSize}px`;
      contentsDomNode.style.lineHeight = `${lineHeight / fontSize}`;
      const codeClasses = Array.prototype.slice.call(this._hover.contentsDomNode.getElementsByClassName("code"));
      codeClasses.forEach((node) => this._editor.applyFontInfo(node));
    }
    _updateContent(node) {
      const contentsDomNode = this._hover.contentsDomNode;
      contentsDomNode.style.paddingBottom = "";
      contentsDomNode.textContent = "";
      contentsDomNode.appendChild(node);
    }
    _layoutContentWidget() {
      this._editor.layoutContentWidget(this);
      this._hover.onContentsChanged();
    }
    _updateMaxDimensions() {
      const height = Math.max(this._editor.getLayoutInfo().height / 4, 250, ContentHoverWidget_1._lastDimensions.height);
      const width2 = Math.max(this._editor.getLayoutInfo().width * 0.66, 750, ContentHoverWidget_1._lastDimensions.width);
      this._resizableNode.maxSize = new Dimension(width2, height);
      this._setHoverWidgetMaxDimensions(width2, height);
    }
    _render(renderedHover) {
      this._setRenderedHover(renderedHover);
      this._updateFont();
      this._updateContent(renderedHover.domNode);
      this.handleContentsChanged();
      this._editor.render();
    }
    getPosition() {
      if (!this._renderedHover) {
        return null;
      }
      return {
        position: this._renderedHover.showAtPosition,
        secondaryPosition: this._renderedHover.showAtSecondaryPosition,
        positionAffinity: this._renderedHover.shouldAppearBeforeContent ? 3 : void 0,
        preference: [
          this._positionPreference ?? 1
          /* ContentWidgetPositionPreference.ABOVE */
        ]
      };
    }
    show(renderedHover) {
      if (!this._editor || !this._editor.hasModel()) {
        return;
      }
      this._render(renderedHover);
      const widgetHeight = getTotalHeight(this._hover.containerDomNode);
      const widgetPosition = renderedHover.showAtPosition;
      this._positionPreference = this._findPositionPreference(widgetHeight, widgetPosition) ?? 1;
      this.handleContentsChanged();
      if (renderedHover.shouldFocus) {
        this._hover.containerDomNode.focus();
      }
      this._onDidResize.fire();
      const hoverFocused = this._hover.containerDomNode.ownerDocument.activeElement === this._hover.containerDomNode;
      const accessibleViewHint = hoverFocused && getHoverAccessibleViewHint(this._configurationService.getValue("accessibility.verbosity.hover") === true && this._accessibilityService.isScreenReaderOptimized(), this._keybindingService.lookupKeybinding("editor.action.accessibleView")?.getAriaLabel() ?? "");
      if (accessibleViewHint) {
        this._hover.contentsDomNode.ariaLabel = this._hover.contentsDomNode.textContent + ", " + accessibleViewHint;
      }
    }
    hide() {
      if (!this._renderedHover) {
        return;
      }
      const hoverStoleFocus = this._renderedHover.shouldFocus || this._hoverFocusedKey.get();
      this._setRenderedHover(void 0);
      this._resizableNode.maxSize = new Dimension(Infinity, Infinity);
      this._resizableNode.clearSashHoverState();
      this._hoverFocusedKey.set(false);
      this._editor.layoutContentWidget(this);
      if (hoverStoleFocus) {
        this._editor.focus();
      }
    }
    _removeConstraintsRenderNormally() {
      const layoutInfo = this._editor.getLayoutInfo();
      this._resizableNode.layout(layoutInfo.height, layoutInfo.width);
      this._setHoverWidgetDimensions("auto", "auto");
      this._updateMaxDimensions();
    }
    setMinimumDimensions(dimensions) {
      this._minimumSize = new Dimension(Math.max(this._minimumSize.width, dimensions.width), Math.max(this._minimumSize.height, dimensions.height));
      this._updateMinimumWidth();
    }
    _updateMinimumWidth() {
      const width2 = typeof this._contentWidth === "undefined" ? this._minimumSize.width : Math.min(this._contentWidth, this._minimumSize.width);
      this._resizableNode.minSize = new Dimension(width2, this._minimumSize.height);
    }
    handleContentsChanged() {
      this._removeConstraintsRenderNormally();
      const contentsDomNode = this._hover.contentsDomNode;
      let height = getTotalHeight(contentsDomNode);
      let width2 = getTotalWidth(contentsDomNode) + 2;
      this._resizableNode.layout(height, width2);
      this._setHoverWidgetDimensions(width2, height);
      height = getTotalHeight(contentsDomNode);
      width2 = getTotalWidth(contentsDomNode);
      this._contentWidth = width2;
      this._updateMinimumWidth();
      this._resizableNode.layout(height, width2);
      if (this._renderedHover?.showAtPosition) {
        const widgetHeight = getTotalHeight(this._hover.containerDomNode);
        this._positionPreference = this._findPositionPreference(widgetHeight, this._renderedHover.showAtPosition);
      }
      this._layoutContentWidget();
      this._onContentsChanged.fire();
    }
    focus() {
      this._hover.containerDomNode.focus();
    }
    scrollUp() {
      const scrollTop = this._hover.scrollbar.getScrollPosition().scrollTop;
      const fontInfo = this._editor.getOption(
        59
        /* EditorOption.fontInfo */
      );
      this._hover.scrollbar.setScrollPosition({ scrollTop: scrollTop - fontInfo.lineHeight });
    }
    scrollDown() {
      const scrollTop = this._hover.scrollbar.getScrollPosition().scrollTop;
      const fontInfo = this._editor.getOption(
        59
        /* EditorOption.fontInfo */
      );
      this._hover.scrollbar.setScrollPosition({ scrollTop: scrollTop + fontInfo.lineHeight });
    }
    scrollLeft() {
      const scrollLeft = this._hover.scrollbar.getScrollPosition().scrollLeft;
      this._hover.scrollbar.setScrollPosition({ scrollLeft: scrollLeft - HORIZONTAL_SCROLLING_BY });
    }
    scrollRight() {
      const scrollLeft = this._hover.scrollbar.getScrollPosition().scrollLeft;
      this._hover.scrollbar.setScrollPosition({ scrollLeft: scrollLeft + HORIZONTAL_SCROLLING_BY });
    }
    pageUp() {
      const scrollTop = this._hover.scrollbar.getScrollPosition().scrollTop;
      const scrollHeight = this._hover.scrollbar.getScrollDimensions().height;
      this._hover.scrollbar.setScrollPosition({ scrollTop: scrollTop - scrollHeight });
    }
    pageDown() {
      const scrollTop = this._hover.scrollbar.getScrollPosition().scrollTop;
      const scrollHeight = this._hover.scrollbar.getScrollDimensions().height;
      this._hover.scrollbar.setScrollPosition({ scrollTop: scrollTop + scrollHeight });
    }
    goToTop() {
      this._hover.scrollbar.setScrollPosition({ scrollTop: 0 });
    }
    goToBottom() {
      this._hover.scrollbar.setScrollPosition({ scrollTop: this._hover.scrollbar.getScrollDimensions().scrollHeight });
    }
  }, ContentHoverWidget_1 = _z, _z.ID = "editor.contrib.resizableContentHoverWidget", _z._lastDimensions = new Dimension(0, 0), _z);
  ContentHoverWidget = ContentHoverWidget_1 = __decorate$2a([
    __param$28(1, IContextKeyService),
    __param$28(2, IConfigurationService),
    __param$28(3, IAccessibilityService),
    __param$28(4, IKeybindingService)
  ], ContentHoverWidget);
  function computeDistanceFromPointToRectangle(pointX, pointY, left, top, width2, height) {
    const x = left + width2 / 2;
    const y = top + height / 2;
    const dx = Math.max(Math.abs(pointX - x) - width2 / 2, 0);
    const dy = Math.max(Math.abs(pointY - y) - height / 2, 0);
    return Math.sqrt(dx * dx + dy * dy);
  }
  class ContentHoverComputer {
    constructor(_editor, _participants) {
      this._editor = _editor;
      this._participants = _participants;
    }
    static _getLineDecorations(editor2, anchor) {
      if (anchor.type !== 1 && !anchor.supportsMarkerHover) {
        return [];
      }
      const model = editor2.getModel();
      const lineNumber = anchor.range.startLineNumber;
      if (lineNumber > model.getLineCount()) {
        return [];
      }
      const maxColumn = model.getLineMaxColumn(lineNumber);
      return editor2.getLineDecorations(lineNumber).filter((d) => {
        if (d.options.isWholeLine) {
          return true;
        }
        const startColumn = d.range.startLineNumber === lineNumber ? d.range.startColumn : 1;
        const endColumn = d.range.endLineNumber === lineNumber ? d.range.endColumn : maxColumn;
        if (d.options.showIfCollapsed) {
          if (startColumn > anchor.range.startColumn + 1 || anchor.range.endColumn - 1 > endColumn) {
            return false;
          }
        } else {
          if (startColumn > anchor.range.startColumn || anchor.range.endColumn > endColumn) {
            return false;
          }
        }
        return true;
      });
    }
    computeAsync(options, token) {
      const anchor = options.anchor;
      if (!this._editor.hasModel() || !anchor) {
        return AsyncIterableProducer.EMPTY;
      }
      const lineDecorations = ContentHoverComputer._getLineDecorations(this._editor, anchor);
      return AsyncIterableProducer.merge(this._participants.map((participant) => {
        if (!participant.computeAsync) {
          return AsyncIterableProducer.EMPTY;
        }
        return participant.computeAsync(anchor, lineDecorations, options.source, token);
      }));
    }
    computeSync(options) {
      if (!this._editor.hasModel()) {
        return [];
      }
      const anchor = options.anchor;
      const lineDecorations = ContentHoverComputer._getLineDecorations(this._editor, anchor);
      let result = [];
      for (const participant of this._participants) {
        result = result.concat(participant.computeSync(anchor, lineDecorations, options.source));
      }
      return coalesce(result);
    }
  }
  class ContentHoverResult {
    constructor(hoverParts, isComplete, options) {
      this.hoverParts = hoverParts;
      this.isComplete = isComplete;
      this.options = options;
    }
    filter(anchor) {
      const filteredHoverParts = this.hoverParts.filter((m) => m.isValidForHoverAnchor(anchor));
      if (filteredHoverParts.length === this.hoverParts.length) {
        return this;
      }
      return new FilteredContentHoverResult(this, filteredHoverParts, this.isComplete, this.options);
    }
  }
  class FilteredContentHoverResult extends ContentHoverResult {
    constructor(original, messages, isComplete, options) {
      super(messages, isComplete, options);
      this.original = original;
    }
    filter(anchor) {
      return this.original.filter(anchor);
    }
  }
  var __decorate$29 = 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$27 = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  const $$h = $$l;
  let EditorHoverStatusBar = class EditorHoverStatusBar extends Disposable {
    get hasContent() {
      return this._hasContent;
    }
    constructor(_keybindingService, _hoverService) {
      super();
      this._keybindingService = _keybindingService;
      this._hoverService = _hoverService;
      this.actions = [];
      this._hasContent = false;
      this.hoverElement = $$h("div.hover-row.status-bar");
      this.hoverElement.tabIndex = 0;
      this.actionsElement = append$2(this.hoverElement, $$h("div.actions"));
    }
    addAction(actionOptions) {
      const keybinding = this._keybindingService.lookupKeybinding(actionOptions.commandId);
      const keybindingLabel = keybinding ? keybinding.getLabel() : null;
      this._hasContent = true;
      const action = this._register(HoverAction.render(this.actionsElement, actionOptions, keybindingLabel));
      this._register(this._hoverService.setupManagedHover(getDefaultHoverDelegate("element"), action.actionContainer, action.actionRenderedLabel));
      this.actions.push(action);
      return action;
    }
    append(element) {
      const result = append$2(this.actionsElement, element);
      this._hasContent = true;
      return result;
    }
  };
  EditorHoverStatusBar = __decorate$29([
    __param$27(0, IKeybindingService),
    __param$27(1, IHoverService)
  ], EditorHoverStatusBar);
  const unthemedToggleStyles = {
    inputActiveOptionBorder: "#007ACC00",
    inputActiveOptionForeground: "#FFFFFF",
    inputActiveOptionBackground: "#0E639C50"
  };
  class Toggle extends Widget$1 {
    get onChange() {
      return this._onChange.event;
    }
    get onKeyDown() {
      return this._onKeyDown.event;
    }
    constructor(opts) {
      super();
      this._onChange = this._register(new Emitter$1());
      this._onKeyDown = this._register(new Emitter$1());
      this._opts = opts;
      this._title = this._opts.title;
      this._checked = this._opts.isChecked;
      const classes = ["monaco-custom-toggle"];
      if (this._opts.icon) {
        this._icon = this._opts.icon;
        classes.push(...ThemeIcon.asClassNameArray(this._icon));
      }
      if (this._opts.actionClassName) {
        classes.push(...this._opts.actionClassName.split(" "));
      }
      if (this._checked) {
        classes.push("checked");
      }
      this.domNode = document.createElement("div");
      this._register(getBaseLayerHoverDelegate().setupDelayedHover(this.domNode, () => ({
        content: this._title,
        style: 1
      }), this._opts.hoverLifecycleOptions));
      this.domNode.classList.add(...classes);
      if (!this._opts.notFocusable) {
        this.domNode.tabIndex = 0;
      }
      this.domNode.setAttribute("role", "checkbox");
      this.domNode.setAttribute("aria-checked", String(this._checked));
      this.setTitle(this._opts.title);
      this.applyStyles();
      this.onclick(this.domNode, (ev) => {
        if (this.enabled) {
          this.checked = !this._checked;
          this._onChange.fire(false);
          ev.preventDefault();
        }
      });
      this._register(this.ignoreGesture(this.domNode));
      this.onkeydown(this.domNode, (keyboardEvent) => {
        if (!this.enabled) {
          return;
        }
        if (keyboardEvent.keyCode === 10 || keyboardEvent.keyCode === 3) {
          this.checked = !this._checked;
          this._onChange.fire(true);
          keyboardEvent.preventDefault();
          keyboardEvent.stopPropagation();
          return;
        }
        this._onKeyDown.fire(keyboardEvent);
      });
    }
    get enabled() {
      return this.domNode.getAttribute("aria-disabled") !== "true";
    }
    focus() {
      this.domNode.focus();
    }
    get checked() {
      return this._checked;
    }
    set checked(newIsChecked) {
      this._checked = newIsChecked;
      this.domNode.setAttribute("aria-checked", String(this._checked));
      this.domNode.classList.toggle("checked", this._checked);
      this.applyStyles();
    }
    setIcon(icon) {
      if (this._icon) {
        this.domNode.classList.remove(...ThemeIcon.asClassNameArray(this._icon));
      }
      this._icon = icon;
      if (this._icon) {
        this.domNode.classList.add(...ThemeIcon.asClassNameArray(this._icon));
      }
    }
    width() {
      return 2 + 2 + 2 + 16;
    }
    applyStyles() {
      if (this.domNode) {
        this.domNode.style.borderColor = this._checked && this._opts.inputActiveOptionBorder || "";
        this.domNode.style.color = this._checked && this._opts.inputActiveOptionForeground || "inherit";
        this.domNode.style.backgroundColor = this._checked && this._opts.inputActiveOptionBackground || "";
      }
    }
    enable() {
      this.domNode.setAttribute("aria-disabled", String(false));
      this.domNode.classList.remove("disabled");
    }
    disable() {
      this.domNode.setAttribute("aria-disabled", String(true));
      this.domNode.classList.add("disabled");
    }
    setTitle(newTitle) {
      this._title = newTitle;
      this.domNode.setAttribute("aria-label", newTitle);
    }
    set visible(visible) {
      this.domNode.style.display = visible ? "" : "none";
    }
    get visible() {
      return this.domNode.style.display !== "none";
    }
  }
  const _BaseCheckbox = class _BaseCheckbox extends Widget$1 {
    constructor(checkbox, domNode, styles) {
      super();
      this.checkbox = checkbox;
      this.domNode = domNode;
      this.styles = styles;
      this._onChange = this._register(new Emitter$1());
      this.onChange = this._onChange.event;
      this.applyStyles();
    }
    get enabled() {
      return this.checkbox.enabled;
    }
    enable() {
      this.checkbox.enable();
      this.applyStyles(true);
    }
    disable() {
      this.checkbox.disable();
      this.applyStyles(false);
    }
    setTitle(newTitle) {
      this.checkbox.setTitle(newTitle);
    }
    applyStyles(enabled = this.enabled) {
      this.domNode.style.color = (enabled ? this.styles.checkboxForeground : this.styles.checkboxDisabledForeground) || "";
      this.domNode.style.backgroundColor = (enabled ? this.styles.checkboxBackground : this.styles.checkboxDisabledBackground) || "";
      this.domNode.style.borderColor = (enabled ? this.styles.checkboxBorder : this.styles.checkboxDisabledBackground) || "";
      const size2 = this.styles.size || 18;
      this.domNode.style.width = this.domNode.style.height = this.domNode.style.fontSize = `${size2}px`;
      this.domNode.style.fontSize = `${size2 - 2}px`;
    }
  };
  _BaseCheckbox.CLASS_NAME = "monaco-checkbox";
  let BaseCheckbox = _BaseCheckbox;
  class Checkbox extends BaseCheckbox {
    constructor(title, isChecked, styles) {
      const toggle = new Toggle({ title, isChecked, icon: Codicon.check, actionClassName: BaseCheckbox.CLASS_NAME, hoverLifecycleOptions: styles.hoverLifecycleOptions, ...unthemedToggleStyles });
      super(toggle, toggle.domNode, styles);
      this._register(toggle);
      this._register(this.checkbox.onChange((keyboard) => {
        this.applyStyles();
        this._onChange.fire(keyboard);
      }));
    }
    get checked() {
      return this.checkbox.checked;
    }
    set checked(newIsChecked) {
      this.checkbox.checked = newIsChecked;
      this.applyStyles();
    }
    applyStyles(enabled) {
      if (this.checkbox.checked) {
        this.checkbox.setIcon(Codicon.check);
      } else {
        this.checkbox.setIcon(void 0);
      }
      super.applyStyles(enabled);
    }
  }
  class TriStateCheckbox extends BaseCheckbox {
    constructor(title, _state, styles) {
      let icon;
      switch (_state) {
        case true:
          icon = Codicon.check;
          break;
        case "mixed":
          icon = Codicon.dash;
          break;
        case false:
          icon = void 0;
          break;
      }
      const checkbox = new Toggle({
        title,
        isChecked: _state === true,
        icon,
        actionClassName: Checkbox.CLASS_NAME,
        hoverLifecycleOptions: styles.hoverLifecycleOptions,
        ...unthemedToggleStyles
      });
      super(checkbox, checkbox.domNode, styles);
      this._state = _state;
      this._register(checkbox);
      this._register(this.checkbox.onChange((keyboard) => {
        this._state = this.checkbox.checked;
        this.applyStyles();
        this._onChange.fire(keyboard);
      }));
    }
    get checked() {
      return this._state;
    }
    set checked(newState) {
      if (this._state !== newState) {
        this._state = newState;
        this.checkbox.checked = newState === true;
        this.applyStyles();
      }
    }
    applyStyles(enabled) {
      switch (this._state) {
        case true:
          this.checkbox.setIcon(Codicon.check);
          break;
        case "mixed":
          this.checkbox.setIcon(Codicon.dash);
          break;
        case false:
          this.checkbox.setIcon(void 0);
          break;
      }
      super.applyStyles(enabled);
    }
  }
  const _FindDecorations = class _FindDecorations {
    constructor(editor2) {
      this._editor = editor2;
      this._decorations = [];
      this._overviewRulerApproximateDecorations = [];
      this._findScopeDecorationIds = [];
      this._rangeHighlightDecorationId = null;
      this._highlightedDecorationId = null;
      this._startPosition = this._editor.getPosition();
    }
    dispose() {
      this._editor.removeDecorations(this._allDecorations());
      this._decorations = [];
      this._overviewRulerApproximateDecorations = [];
      this._findScopeDecorationIds = [];
      this._rangeHighlightDecorationId = null;
      this._highlightedDecorationId = null;
    }
    reset() {
      this._decorations = [];
      this._overviewRulerApproximateDecorations = [];
      this._findScopeDecorationIds = [];
      this._rangeHighlightDecorationId = null;
      this._highlightedDecorationId = null;
    }
    getCount() {
      return this._decorations.length;
    }
    /** @deprecated use getFindScopes to support multiple selections */
    getFindScope() {
      if (this._findScopeDecorationIds[0]) {
        return this._editor.getModel().getDecorationRange(this._findScopeDecorationIds[0]);
      }
      return null;
    }
    getFindScopes() {
      if (this._findScopeDecorationIds.length) {
        const scopes = this._findScopeDecorationIds.map((findScopeDecorationId) => this._editor.getModel().getDecorationRange(findScopeDecorationId)).filter((element) => !!element);
        if (scopes.length) {
          return scopes;
        }
      }
      return null;
    }
    getStartPosition() {
      return this._startPosition;
    }
    setStartPosition(newStartPosition) {
      this._startPosition = newStartPosition;
      this.setCurrentFindMatch(null);
    }
    _getDecorationIndex(decorationId) {
      const index = this._decorations.indexOf(decorationId);
      if (index >= 0) {
        return index + 1;
      }
      return 1;
    }
    getDecorationRangeAt(index) {
      const decorationId = index < this._decorations.length ? this._decorations[index] : null;
      if (decorationId) {
        return this._editor.getModel().getDecorationRange(decorationId);
      }
      return null;
    }
    getCurrentMatchesPosition(desiredRange) {
      const candidates = this._editor.getModel().getDecorationsInRange(desiredRange);
      for (const candidate of candidates) {
        const candidateOpts = candidate.options;
        if (candidateOpts === _FindDecorations._FIND_MATCH_DECORATION || candidateOpts === _FindDecorations._CURRENT_FIND_MATCH_DECORATION) {
          return this._getDecorationIndex(candidate.id);
        }
      }
      return 0;
    }
    setCurrentFindMatch(nextMatch) {
      let newCurrentDecorationId = null;
      let matchPosition = 0;
      if (nextMatch) {
        for (let i2 = 0, len = this._decorations.length; i2 < len; i2++) {
          const range2 = this._editor.getModel().getDecorationRange(this._decorations[i2]);
          if (nextMatch.equalsRange(range2)) {
            newCurrentDecorationId = this._decorations[i2];
            matchPosition = i2 + 1;
            break;
          }
        }
      }
      if (this._highlightedDecorationId !== null || newCurrentDecorationId !== null) {
        this._editor.changeDecorations((changeAccessor) => {
          if (this._highlightedDecorationId !== null) {
            changeAccessor.changeDecorationOptions(this._highlightedDecorationId, _FindDecorations._FIND_MATCH_DECORATION);
            this._highlightedDecorationId = null;
          }
          if (newCurrentDecorationId !== null) {
            this._highlightedDecorationId = newCurrentDecorationId;
            changeAccessor.changeDecorationOptions(this._highlightedDecorationId, _FindDecorations._CURRENT_FIND_MATCH_DECORATION);
          }
          if (this._rangeHighlightDecorationId !== null) {
            changeAccessor.removeDecoration(this._rangeHighlightDecorationId);
            this._rangeHighlightDecorationId = null;
          }
          if (newCurrentDecorationId !== null) {
            let rng = this._editor.getModel().getDecorationRange(newCurrentDecorationId);
            if (rng.startLineNumber !== rng.endLineNumber && rng.endColumn === 1) {
              const lineBeforeEnd = rng.endLineNumber - 1;
              const lineBeforeEndMaxColumn = this._editor.getModel().getLineMaxColumn(lineBeforeEnd);
              rng = new Range$2(rng.startLineNumber, rng.startColumn, lineBeforeEnd, lineBeforeEndMaxColumn);
            }
            this._rangeHighlightDecorationId = changeAccessor.addDecoration(rng, _FindDecorations._RANGE_HIGHLIGHT_DECORATION);
          }
        });
      }
      return matchPosition;
    }
    set(findMatches, findScopes) {
      this._editor.changeDecorations((accessor) => {
        let findMatchesOptions = _FindDecorations._FIND_MATCH_DECORATION;
        const newOverviewRulerApproximateDecorations = [];
        if (findMatches.length > 1e3) {
          findMatchesOptions = _FindDecorations._FIND_MATCH_NO_OVERVIEW_DECORATION;
          const lineCount = this._editor.getModel().getLineCount();
          const height = this._editor.getLayoutInfo().height;
          const approxPixelsPerLine = height / lineCount;
          const mergeLinesDelta = Math.max(2, Math.ceil(3 / approxPixelsPerLine));
          let prevStartLineNumber = findMatches[0].range.startLineNumber;
          let prevEndLineNumber = findMatches[0].range.endLineNumber;
          for (let i2 = 1, len = findMatches.length; i2 < len; i2++) {
            const range2 = findMatches[i2].range;
            if (prevEndLineNumber + mergeLinesDelta >= range2.startLineNumber) {
              if (range2.endLineNumber > prevEndLineNumber) {
                prevEndLineNumber = range2.endLineNumber;
              }
            } else {
              newOverviewRulerApproximateDecorations.push({
                range: new Range$2(prevStartLineNumber, 1, prevEndLineNumber, 1),
                options: _FindDecorations._FIND_MATCH_ONLY_OVERVIEW_DECORATION
              });
              prevStartLineNumber = range2.startLineNumber;
              prevEndLineNumber = range2.endLineNumber;
            }
          }
          newOverviewRulerApproximateDecorations.push({
            range: new Range$2(prevStartLineNumber, 1, prevEndLineNumber, 1),
            options: _FindDecorations._FIND_MATCH_ONLY_OVERVIEW_DECORATION
          });
        }
        const newFindMatchesDecorations = new Array(findMatches.length);
        for (let i2 = 0, len = findMatches.length; i2 < len; i2++) {
          newFindMatchesDecorations[i2] = {
            range: findMatches[i2].range,
            options: findMatchesOptions
          };
        }
        this._decorations = accessor.deltaDecorations(this._decorations, newFindMatchesDecorations);
        this._overviewRulerApproximateDecorations = accessor.deltaDecorations(this._overviewRulerApproximateDecorations, newOverviewRulerApproximateDecorations);
        if (this._rangeHighlightDecorationId) {
          accessor.removeDecoration(this._rangeHighlightDecorationId);
          this._rangeHighlightDecorationId = null;
        }
        if (this._findScopeDecorationIds.length) {
          this._findScopeDecorationIds.forEach((findScopeDecorationId) => accessor.removeDecoration(findScopeDecorationId));
          this._findScopeDecorationIds = [];
        }
        if (findScopes?.length) {
          this._findScopeDecorationIds = findScopes.map((findScope) => accessor.addDecoration(findScope, _FindDecorations._FIND_SCOPE_DECORATION));
        }
      });
    }
    matchBeforePosition(position) {
      if (this._decorations.length === 0) {
        return null;
      }
      for (let i2 = this._decorations.length - 1; i2 >= 0; i2--) {
        const decorationId = this._decorations[i2];
        const r = this._editor.getModel().getDecorationRange(decorationId);
        if (!r || r.endLineNumber > position.lineNumber) {
          continue;
        }
        if (r.endLineNumber < position.lineNumber) {
          return r;
        }
        if (r.endColumn > position.column) {
          continue;
        }
        return r;
      }
      return this._editor.getModel().getDecorationRange(this._decorations[this._decorations.length - 1]);
    }
    matchAfterPosition(position) {
      if (this._decorations.length === 0) {
        return null;
      }
      for (let i2 = 0, len = this._decorations.length; i2 < len; i2++) {
        const decorationId = this._decorations[i2];
        const r = this._editor.getModel().getDecorationRange(decorationId);
        if (!r || r.startLineNumber < position.lineNumber) {
          continue;
        }
        if (r.startLineNumber > position.lineNumber) {
          return r;
        }
        if (r.startColumn < position.column) {
          continue;
        }
        return r;
      }
      return this._editor.getModel().getDecorationRange(this._decorations[0]);
    }
    _allDecorations() {
      let result = [];
      result = result.concat(this._decorations);
      result = result.concat(this._overviewRulerApproximateDecorations);
      if (this._findScopeDecorationIds.length) {
        result.push(...this._findScopeDecorationIds);
      }
      if (this._rangeHighlightDecorationId) {
        result.push(this._rangeHighlightDecorationId);
      }
      return result;
    }
  };
  _FindDecorations._CURRENT_FIND_MATCH_DECORATION = ModelDecorationOptions.register({
    description: "current-find-match",
    stickiness: 1,
    zIndex: 13,
    className: "currentFindMatch",
    inlineClassName: "currentFindMatchInline",
    showIfCollapsed: true,
    overviewRuler: {
      color: themeColorFromId(overviewRulerFindMatchForeground),
      position: OverviewRulerLane$1.Center
    },
    minimap: {
      color: themeColorFromId(minimapFindMatch),
      position: 1
      /* MinimapPosition.Inline */
    }
  });
  _FindDecorations._FIND_MATCH_DECORATION = ModelDecorationOptions.register({
    description: "find-match",
    stickiness: 1,
    zIndex: 10,
    className: "findMatch",
    inlineClassName: "findMatchInline",
    showIfCollapsed: true,
    overviewRuler: {
      color: themeColorFromId(overviewRulerFindMatchForeground),
      position: OverviewRulerLane$1.Center
    },
    minimap: {
      color: themeColorFromId(minimapFindMatch),
      position: 1
      /* MinimapPosition.Inline */
    }
  });
  _FindDecorations._FIND_MATCH_NO_OVERVIEW_DECORATION = ModelDecorationOptions.register({
    description: "find-match-no-overview",
    stickiness: 1,
    className: "findMatch",
    showIfCollapsed: true
  });
  _FindDecorations._FIND_MATCH_ONLY_OVERVIEW_DECORATION = ModelDecorationOptions.register({
    description: "find-match-only-overview",
    stickiness: 1,
    overviewRuler: {
      color: themeColorFromId(overviewRulerFindMatchForeground),
      position: OverviewRulerLane$1.Center
    }
  });
  _FindDecorations._RANGE_HIGHLIGHT_DECORATION = ModelDecorationOptions.register({
    description: "find-range-highlight",
    stickiness: 1,
    className: "rangeHighlight",
    isWholeLine: true
  });
  _FindDecorations._FIND_SCOPE_DECORATION = ModelDecorationOptions.register({
    description: "find-scope",
    className: "findScope",
    isWholeLine: true
  });
  let FindDecorations = _FindDecorations;
  class ReplaceAllCommand {
    constructor(editorSelection, ranges, replaceStrings) {
      this._editorSelection = editorSelection;
      this._ranges = ranges;
      this._replaceStrings = replaceStrings;
      this._trackedEditorSelectionId = null;
    }
    getEditOperations(model, builder) {
      if (this._ranges.length > 0) {
        const ops = [];
        for (let i2 = 0; i2 < this._ranges.length; i2++) {
          ops.push({
            range: this._ranges[i2],
            text: this._replaceStrings[i2]
          });
        }
        ops.sort((o1, o2) => {
          return Range$2.compareRangesUsingStarts(o1.range, o2.range);
        });
        const resultOps = [];
        let previousOp = ops[0];
        for (let i2 = 1; i2 < ops.length; i2++) {
          if (previousOp.range.endLineNumber === ops[i2].range.startLineNumber && previousOp.range.endColumn === ops[i2].range.startColumn) {
            previousOp.range = previousOp.range.plusRange(ops[i2].range);
            previousOp.text = previousOp.text + ops[i2].text;
          } else {
            resultOps.push(previousOp);
            previousOp = ops[i2];
          }
        }
        resultOps.push(previousOp);
        for (const op of resultOps) {
          builder.addEditOperation(op.range, op.text);
        }
      }
      this._trackedEditorSelectionId = builder.trackSelection(this._editorSelection);
    }
    computeCursorState(model, helper) {
      return helper.getTrackedSelection(this._trackedEditorSelectionId);
    }
  }
  function buildReplaceStringWithCasePreserved(matches, pattern) {
    if (matches && matches[0] !== "") {
      const containsHyphens = validateSpecificSpecialCharacter(matches, pattern, "-");
      const containsUnderscores = validateSpecificSpecialCharacter(matches, pattern, "_");
      if (containsHyphens && !containsUnderscores) {
        return buildReplaceStringForSpecificSpecialCharacter(matches, pattern, "-");
      } else if (!containsHyphens && containsUnderscores) {
        return buildReplaceStringForSpecificSpecialCharacter(matches, pattern, "_");
      }
      if (matches[0].toUpperCase() === matches[0]) {
        return pattern.toUpperCase();
      } else if (matches[0].toLowerCase() === matches[0]) {
        return pattern.toLowerCase();
      } else if (containsUppercaseCharacter(matches[0][0]) && pattern.length > 0) {
        return pattern[0].toUpperCase() + pattern.substr(1);
      } else if (matches[0][0].toUpperCase() !== matches[0][0] && pattern.length > 0) {
        return pattern[0].toLowerCase() + pattern.substr(1);
      } else {
        return pattern;
      }
    } else {
      return pattern;
    }
  }
  function validateSpecificSpecialCharacter(matches, pattern, specialCharacter) {
    const doesContainSpecialCharacter = matches[0].indexOf(specialCharacter) !== -1 && pattern.indexOf(specialCharacter) !== -1;
    return doesContainSpecialCharacter && matches[0].split(specialCharacter).length === pattern.split(specialCharacter).length;
  }
  function buildReplaceStringForSpecificSpecialCharacter(matches, pattern, specialCharacter) {
    const splitPatternAtSpecialCharacter = pattern.split(specialCharacter);
    const splitMatchAtSpecialCharacter = matches[0].split(specialCharacter);
    let replaceString = "";
    splitPatternAtSpecialCharacter.forEach((splitValue, index) => {
      replaceString += buildReplaceStringWithCasePreserved([splitMatchAtSpecialCharacter[index]], splitValue) + specialCharacter;
    });
    return replaceString.slice(0, -1);
  }
  class StaticValueReplacePattern {
    constructor(staticValue) {
      this.staticValue = staticValue;
      this.kind = 0;
    }
  }
  class DynamicPiecesReplacePattern {
    constructor(pieces) {
      this.pieces = pieces;
      this.kind = 1;
    }
  }
  class ReplacePattern {
    static fromStaticValue(value) {
      return new ReplacePattern([ReplacePiece.staticValue(value)]);
    }
    get hasReplacementPatterns() {
      return this._state.kind === 1;
    }
    constructor(pieces) {
      if (!pieces || pieces.length === 0) {
        this._state = new StaticValueReplacePattern("");
      } else if (pieces.length === 1 && pieces[0].staticValue !== null) {
        this._state = new StaticValueReplacePattern(pieces[0].staticValue);
      } else {
        this._state = new DynamicPiecesReplacePattern(pieces);
      }
    }
    buildReplaceString(matches, preserveCase) {
      if (this._state.kind === 0) {
        if (preserveCase) {
          return buildReplaceStringWithCasePreserved(matches, this._state.staticValue);
        } else {
          return this._state.staticValue;
        }
      }
      let result = "";
      for (let i2 = 0, len = this._state.pieces.length; i2 < len; i2++) {
        const piece = this._state.pieces[i2];
        if (piece.staticValue !== null) {
          result += piece.staticValue;
          continue;
        }
        let match2 = ReplacePattern._substitute(piece.matchIndex, matches);
        if (piece.caseOps !== null && piece.caseOps.length > 0) {
          const repl = [];
          const lenOps = piece.caseOps.length;
          let opIdx = 0;
          for (let idx = 0, len2 = match2.length; idx < len2; idx++) {
            if (opIdx >= lenOps) {
              repl.push(match2.slice(idx));
              break;
            }
            switch (piece.caseOps[opIdx]) {
              case "U":
                repl.push(match2[idx].toUpperCase());
                break;
              case "u":
                repl.push(match2[idx].toUpperCase());
                opIdx++;
                break;
              case "L":
                repl.push(match2[idx].toLowerCase());
                break;
              case "l":
                repl.push(match2[idx].toLowerCase());
                opIdx++;
                break;
              default:
                repl.push(match2[idx]);
            }
          }
          match2 = repl.join("");
        }
        result += match2;
      }
      return result;
    }
    static _substitute(matchIndex, matches) {
      if (matches === null) {
        return "";
      }
      if (matchIndex === 0) {
        return matches[0];
      }
      let remainder = "";
      while (matchIndex > 0) {
        if (matchIndex < matches.length) {
          const match2 = matches[matchIndex] || "";
          return match2 + remainder;
        }
        remainder = String(matchIndex % 10) + remainder;
        matchIndex = Math.floor(matchIndex / 10);
      }
      return "$" + remainder;
    }
  }
  class ReplacePiece {
    static staticValue(value) {
      return new ReplacePiece(value, -1, null);
    }
    static caseOps(index, caseOps) {
      return new ReplacePiece(null, index, caseOps);
    }
    constructor(staticValue, matchIndex, caseOps) {
      this.staticValue = staticValue;
      this.matchIndex = matchIndex;
      if (!caseOps || caseOps.length === 0) {
        this.caseOps = null;
      } else {
        this.caseOps = caseOps.slice(0);
      }
    }
  }
  class ReplacePieceBuilder {
    constructor(source) {
      this._source = source;
      this._lastCharIndex = 0;
      this._result = [];
      this._resultLen = 0;
      this._currentStaticPiece = "";
    }
    emitUnchanged(toCharIndex) {
      this._emitStatic(this._source.substring(this._lastCharIndex, toCharIndex));
      this._lastCharIndex = toCharIndex;
    }
    emitStatic(value, toCharIndex) {
      this._emitStatic(value);
      this._lastCharIndex = toCharIndex;
    }
    _emitStatic(value) {
      if (value.length === 0) {
        return;
      }
      this._currentStaticPiece += value;
    }
    emitMatchIndex(index, toCharIndex, caseOps) {
      if (this._currentStaticPiece.length !== 0) {
        this._result[this._resultLen++] = ReplacePiece.staticValue(this._currentStaticPiece);
        this._currentStaticPiece = "";
      }
      this._result[this._resultLen++] = ReplacePiece.caseOps(index, caseOps);
      this._lastCharIndex = toCharIndex;
    }
    finalize() {
      this.emitUnchanged(this._source.length);
      if (this._currentStaticPiece.length !== 0) {
        this._result[this._resultLen++] = ReplacePiece.staticValue(this._currentStaticPiece);
        this._currentStaticPiece = "";
      }
      return new ReplacePattern(this._result);
    }
  }
  function parseReplaceString(replaceString) {
    if (!replaceString || replaceString.length === 0) {
      return new ReplacePattern(null);
    }
    const caseOps = [];
    const result = new ReplacePieceBuilder(replaceString);
    for (let i2 = 0, len = replaceString.length; i2 < len; i2++) {
      const chCode = replaceString.charCodeAt(i2);
      if (chCode === 92) {
        i2++;
        if (i2 >= len) {
          break;
        }
        const nextChCode = replaceString.charCodeAt(i2);
        switch (nextChCode) {
          case 92:
            result.emitUnchanged(i2 - 1);
            result.emitStatic("\\", i2 + 1);
            break;
          case 110:
            result.emitUnchanged(i2 - 1);
            result.emitStatic("\n", i2 + 1);
            break;
          case 116:
            result.emitUnchanged(i2 - 1);
            result.emitStatic("	", i2 + 1);
            break;
          // Case modification of string replacements, patterned after Boost, but only applied
          // to the replacement text, not subsequent content.
          case 117:
          // \u => upper-cases one character.
          case 85:
          // \U => upper-cases ALL following characters.
          case 108:
          // \l => lower-cases one character.
          case 76:
            result.emitUnchanged(i2 - 1);
            result.emitStatic("", i2 + 1);
            caseOps.push(String.fromCharCode(nextChCode));
            break;
        }
        continue;
      }
      if (chCode === 36) {
        i2++;
        if (i2 >= len) {
          break;
        }
        const nextChCode = replaceString.charCodeAt(i2);
        if (nextChCode === 36) {
          result.emitUnchanged(i2 - 1);
          result.emitStatic("$", i2 + 1);
          continue;
        }
        if (nextChCode === 48 || nextChCode === 38) {
          result.emitUnchanged(i2 - 1);
          result.emitMatchIndex(0, i2 + 1, caseOps);
          caseOps.length = 0;
          continue;
        }
        if (49 <= nextChCode && nextChCode <= 57) {
          let matchIndex = nextChCode - 48;
          if (i2 + 1 < len) {
            const nextNextChCode = replaceString.charCodeAt(i2 + 1);
            if (48 <= nextNextChCode && nextNextChCode <= 57) {
              i2++;
              matchIndex = matchIndex * 10 + (nextNextChCode - 48);
              result.emitUnchanged(i2 - 2);
              result.emitMatchIndex(matchIndex, i2 + 1, caseOps);
              caseOps.length = 0;
              continue;
            }
          }
          result.emitUnchanged(i2 - 1);
          result.emitMatchIndex(matchIndex, i2 + 1, caseOps);
          caseOps.length = 0;
          continue;
        }
      }
    }
    return result.finalize();
  }
  const CONTEXT_FIND_WIDGET_VISIBLE = new RawContextKey("findWidgetVisible", false);
  CONTEXT_FIND_WIDGET_VISIBLE.toNegated();
  const CONTEXT_FIND_INPUT_FOCUSED = new RawContextKey("findInputFocussed", false);
  const CONTEXT_REPLACE_INPUT_FOCUSED = new RawContextKey("replaceInputFocussed", false);
  const ToggleCaseSensitiveKeybinding = {
    primary: 512 | 33,
    mac: {
      primary: 2048 | 512 | 33
      /* KeyCode.KeyC */
    }
  };
  const ToggleWholeWordKeybinding = {
    primary: 512 | 53,
    mac: {
      primary: 2048 | 512 | 53
      /* KeyCode.KeyW */
    }
  };
  const ToggleRegexKeybinding = {
    primary: 512 | 48,
    mac: {
      primary: 2048 | 512 | 48
      /* KeyCode.KeyR */
    }
  };
  const ToggleSearchScopeKeybinding = {
    primary: 512 | 42,
    mac: {
      primary: 2048 | 512 | 42
      /* KeyCode.KeyL */
    }
  };
  const TogglePreserveCaseKeybinding = {
    primary: 512 | 46,
    mac: {
      primary: 2048 | 512 | 46
      /* KeyCode.KeyP */
    }
  };
  const FIND_IDS = {
    StartFindAction: "actions.find",
    StartFindWithSelection: "actions.findWithSelection",
    StartFindWithArgs: "editor.actions.findWithArgs",
    NextMatchFindAction: "editor.action.nextMatchFindAction",
    PreviousMatchFindAction: "editor.action.previousMatchFindAction",
    GoToMatchFindAction: "editor.action.goToMatchFindAction",
    NextSelectionMatchFindAction: "editor.action.nextSelectionMatchFindAction",
    PreviousSelectionMatchFindAction: "editor.action.previousSelectionMatchFindAction",
    StartFindReplaceAction: "editor.action.startFindReplaceAction",
    CloseFindWidgetCommand: "closeFindWidget",
    ToggleCaseSensitiveCommand: "toggleFindCaseSensitive",
    ToggleWholeWordCommand: "toggleFindWholeWord",
    ToggleRegexCommand: "toggleFindRegex",
    ToggleSearchScopeCommand: "toggleFindInSelection",
    TogglePreserveCaseCommand: "togglePreserveCase",
    ReplaceOneAction: "editor.action.replaceOne",
    ReplaceAllAction: "editor.action.replaceAll",
    SelectAllMatchesAction: "editor.action.selectAllMatches"
  };
  const MATCHES_LIMIT = 19999;
  const RESEARCH_DELAY = 240;
  class FindModelBoundToEditorModel {
    constructor(editor2, state) {
      this._toDispose = new DisposableStore();
      this._editor = editor2;
      this._state = state;
      this._isDisposed = false;
      this._startSearchingTimer = new TimeoutTimer();
      this._decorations = new FindDecorations(editor2);
      this._toDispose.add(this._decorations);
      this._updateDecorationsScheduler = new RunOnceScheduler(() => {
        if (!this._editor.hasModel()) {
          return;
        }
        return this.research(false);
      }, 100);
      this._toDispose.add(this._updateDecorationsScheduler);
      this._toDispose.add(this._editor.onDidChangeCursorPosition((e) => {
        if (e.reason === 3 || e.reason === 5 || e.reason === 6) {
          this._decorations.setStartPosition(this._editor.getPosition());
        }
      }));
      this._ignoreModelContentChanged = false;
      this._toDispose.add(this._editor.onDidChangeModelContent((e) => {
        if (this._ignoreModelContentChanged) {
          return;
        }
        if (e.isFlush) {
          this._decorations.reset();
        }
        this._decorations.setStartPosition(this._editor.getPosition());
        this._updateDecorationsScheduler.schedule();
      }));
      this._toDispose.add(this._state.onFindReplaceStateChange((e) => this._onStateChanged(e)));
      this.research(false, this._state.searchScope);
    }
    dispose() {
      this._isDisposed = true;
      dispose(this._startSearchingTimer);
      this._toDispose.dispose();
    }
    _onStateChanged(e) {
      if (this._isDisposed) {
        return;
      }
      if (!this._editor.hasModel()) {
        return;
      }
      if (e.searchString || e.isReplaceRevealed || e.isRegex || e.wholeWord || e.matchCase || e.searchScope) {
        const model = this._editor.getModel();
        if (model.isTooLargeForSyncing()) {
          this._startSearchingTimer.cancel();
          this._startSearchingTimer.setIfNotSet(() => {
            if (e.searchScope) {
              this.research(e.moveCursor, this._state.searchScope);
            } else {
              this.research(e.moveCursor);
            }
          }, RESEARCH_DELAY);
        } else {
          if (e.searchScope) {
            this.research(e.moveCursor, this._state.searchScope);
          } else {
            this.research(e.moveCursor);
          }
        }
      }
    }
    static _getSearchRange(model, findScope) {
      if (findScope) {
        return findScope;
      }
      return model.getFullModelRange();
    }
    research(moveCursor, newFindScope) {
      let findScopes = null;
      if (typeof newFindScope !== "undefined") {
        if (newFindScope !== null) {
          if (!Array.isArray(newFindScope)) {
            findScopes = [newFindScope];
          } else {
            findScopes = newFindScope;
          }
        }
      } else {
        findScopes = this._decorations.getFindScopes();
      }
      if (findScopes !== null) {
        findScopes = findScopes.map((findScope) => {
          if (findScope.startLineNumber !== findScope.endLineNumber) {
            let endLineNumber = findScope.endLineNumber;
            if (findScope.endColumn === 1) {
              endLineNumber = endLineNumber - 1;
            }
            return new Range$2(findScope.startLineNumber, 1, endLineNumber, this._editor.getModel().getLineMaxColumn(endLineNumber));
          }
          return findScope;
        });
      }
      const findMatches = this._findMatches(findScopes, false, MATCHES_LIMIT);
      this._decorations.set(findMatches, findScopes);
      const editorSelection = this._editor.getSelection();
      let currentMatchesPosition = this._decorations.getCurrentMatchesPosition(editorSelection);
      if (currentMatchesPosition === 0 && findMatches.length > 0) {
        const matchAfterSelection = findFirstIdxMonotonousOrArrLen(findMatches.map((match2) => match2.range), (range2) => Range$2.compareRangesUsingStarts(range2, editorSelection) >= 0);
        currentMatchesPosition = matchAfterSelection > 0 ? matchAfterSelection - 1 + 1 : currentMatchesPosition;
      }
      this._state.changeMatchInfo(currentMatchesPosition, this._decorations.getCount(), void 0);
      if (moveCursor && this._editor.getOption(
        50
        /* EditorOption.find */
      ).cursorMoveOnType) {
        this._moveToNextMatch(this._decorations.getStartPosition());
      }
    }
    _hasMatches() {
      return this._state.matchesCount > 0;
    }
    _cannotFind() {
      if (!this._hasMatches()) {
        const findScope = this._decorations.getFindScope();
        if (findScope) {
          this._editor.revealRangeInCenterIfOutsideViewport(
            findScope,
            0
            /* ScrollType.Smooth */
          );
        }
        return true;
      }
      return false;
    }
    _setCurrentFindMatch(match2) {
      const matchesPosition = this._decorations.setCurrentFindMatch(match2);
      this._state.changeMatchInfo(matchesPosition, this._decorations.getCount(), match2);
      this._editor.setSelection(match2);
      this._editor.revealRangeInCenterIfOutsideViewport(
        match2,
        0
        /* ScrollType.Smooth */
      );
    }
    _prevSearchPosition(before) {
      const isUsingLineStops = this._state.isRegex && (this._state.searchString.indexOf("^") >= 0 || this._state.searchString.indexOf("$") >= 0);
      let { lineNumber, column } = before;
      const model = this._editor.getModel();
      if (isUsingLineStops || column === 1) {
        if (lineNumber === 1) {
          lineNumber = model.getLineCount();
        } else {
          lineNumber--;
        }
        column = model.getLineMaxColumn(lineNumber);
      } else {
        column--;
      }
      return new Position$1(lineNumber, column);
    }
    _moveToPrevMatch(before, isRecursed = false) {
      if (!this._state.canNavigateBack()) {
        const nextMatchRange = this._decorations.matchAfterPosition(before);
        if (nextMatchRange) {
          this._setCurrentFindMatch(nextMatchRange);
        }
        return;
      }
      if (this._decorations.getCount() < MATCHES_LIMIT) {
        let prevMatchRange = this._decorations.matchBeforePosition(before);
        if (prevMatchRange && prevMatchRange.isEmpty() && prevMatchRange.getStartPosition().equals(before)) {
          before = this._prevSearchPosition(before);
          prevMatchRange = this._decorations.matchBeforePosition(before);
        }
        if (prevMatchRange) {
          this._setCurrentFindMatch(prevMatchRange);
        }
        return;
      }
      if (this._cannotFind()) {
        return;
      }
      const findScope = this._decorations.getFindScope();
      const searchRange = FindModelBoundToEditorModel._getSearchRange(this._editor.getModel(), findScope);
      if (searchRange.getEndPosition().isBefore(before)) {
        before = searchRange.getEndPosition();
      }
      if (before.isBefore(searchRange.getStartPosition())) {
        before = searchRange.getEndPosition();
      }
      const { lineNumber, column } = before;
      const model = this._editor.getModel();
      let position = new Position$1(lineNumber, column);
      let prevMatch = model.findPreviousMatch(this._state.searchString, position, this._state.isRegex, this._state.matchCase, this._state.wholeWord ? this._editor.getOption(
        148
        /* EditorOption.wordSeparators */
      ) : null, false);
      if (prevMatch && prevMatch.range.isEmpty() && prevMatch.range.getStartPosition().equals(position)) {
        position = this._prevSearchPosition(position);
        prevMatch = model.findPreviousMatch(this._state.searchString, position, this._state.isRegex, this._state.matchCase, this._state.wholeWord ? this._editor.getOption(
          148
          /* EditorOption.wordSeparators */
        ) : null, false);
      }
      if (!prevMatch) {
        return;
      }
      if (!isRecursed && !searchRange.containsRange(prevMatch.range)) {
        return this._moveToPrevMatch(prevMatch.range.getStartPosition(), true);
      }
      this._setCurrentFindMatch(prevMatch.range);
    }
    moveToPrevMatch() {
      this._moveToPrevMatch(this._editor.getSelection().getStartPosition());
    }
    _nextSearchPosition(after2) {
      const isUsingLineStops = this._state.isRegex && (this._state.searchString.indexOf("^") >= 0 || this._state.searchString.indexOf("$") >= 0);
      let { lineNumber, column } = after2;
      const model = this._editor.getModel();
      if (isUsingLineStops || column === model.getLineMaxColumn(lineNumber)) {
        if (lineNumber === model.getLineCount()) {
          lineNumber = 1;
        } else {
          lineNumber++;
        }
        column = 1;
      } else {
        column++;
      }
      return new Position$1(lineNumber, column);
    }
    _moveToNextMatch(after2) {
      if (!this._state.canNavigateForward()) {
        const prevMatchRange = this._decorations.matchBeforePosition(after2);
        if (prevMatchRange) {
          this._setCurrentFindMatch(prevMatchRange);
        }
        return;
      }
      if (this._decorations.getCount() < MATCHES_LIMIT) {
        let nextMatchRange = this._decorations.matchAfterPosition(after2);
        if (nextMatchRange && nextMatchRange.isEmpty() && nextMatchRange.getStartPosition().equals(after2)) {
          after2 = this._nextSearchPosition(after2);
          nextMatchRange = this._decorations.matchAfterPosition(after2);
        }
        if (nextMatchRange) {
          this._setCurrentFindMatch(nextMatchRange);
        }
        return;
      }
      const nextMatch = this._getNextMatch(after2, false, true);
      if (nextMatch) {
        this._setCurrentFindMatch(nextMatch.range);
      }
    }
    _getNextMatch(after2, captureMatches, forceMove, isRecursed = false) {
      if (this._cannotFind()) {
        return null;
      }
      const findScope = this._decorations.getFindScope();
      const searchRange = FindModelBoundToEditorModel._getSearchRange(this._editor.getModel(), findScope);
      if (searchRange.getEndPosition().isBefore(after2)) {
        after2 = searchRange.getStartPosition();
      }
      if (after2.isBefore(searchRange.getStartPosition())) {
        after2 = searchRange.getStartPosition();
      }
      const { lineNumber, column } = after2;
      const model = this._editor.getModel();
      let position = new Position$1(lineNumber, column);
      let nextMatch = model.findNextMatch(this._state.searchString, position, this._state.isRegex, this._state.matchCase, this._state.wholeWord ? this._editor.getOption(
        148
        /* EditorOption.wordSeparators */
      ) : null, captureMatches);
      if (forceMove && nextMatch && nextMatch.range.isEmpty() && nextMatch.range.getStartPosition().equals(position)) {
        position = this._nextSearchPosition(position);
        nextMatch = model.findNextMatch(this._state.searchString, position, this._state.isRegex, this._state.matchCase, this._state.wholeWord ? this._editor.getOption(
          148
          /* EditorOption.wordSeparators */
        ) : null, captureMatches);
      }
      if (!nextMatch) {
        return null;
      }
      if (!isRecursed && !searchRange.containsRange(nextMatch.range)) {
        return this._getNextMatch(nextMatch.range.getEndPosition(), captureMatches, forceMove, true);
      }
      return nextMatch;
    }
    moveToNextMatch() {
      this._moveToNextMatch(this._editor.getSelection().getEndPosition());
    }
    _moveToMatch(index) {
      const decorationRange = this._decorations.getDecorationRangeAt(index);
      if (decorationRange) {
        this._setCurrentFindMatch(decorationRange);
      }
    }
    moveToMatch(index) {
      this._moveToMatch(index);
    }
    _getReplacePattern() {
      if (this._state.isRegex) {
        return parseReplaceString(this._state.replaceString);
      }
      return ReplacePattern.fromStaticValue(this._state.replaceString);
    }
    replace() {
      if (!this._hasMatches()) {
        return;
      }
      const replacePattern = this._getReplacePattern();
      const selection = this._editor.getSelection();
      const nextMatch = this._getNextMatch(selection.getStartPosition(), true, false);
      if (nextMatch) {
        if (selection.equalsRange(nextMatch.range)) {
          const replaceString = replacePattern.buildReplaceString(nextMatch.matches, this._state.preserveCase);
          const command = new ReplaceCommand(selection, replaceString);
          this._executeEditorCommand("replace", command);
          this._decorations.setStartPosition(new Position$1(selection.startLineNumber, selection.startColumn + replaceString.length));
          this.research(true);
        } else {
          this._decorations.setStartPosition(this._editor.getPosition());
          this._setCurrentFindMatch(nextMatch.range);
        }
      }
    }
    _findMatches(findScopes, captureMatches, limitResultCount) {
      const searchRanges = (findScopes || [null]).map((scope) => FindModelBoundToEditorModel._getSearchRange(this._editor.getModel(), scope));
      return this._editor.getModel().findMatches(this._state.searchString, searchRanges, this._state.isRegex, this._state.matchCase, this._state.wholeWord ? this._editor.getOption(
        148
        /* EditorOption.wordSeparators */
      ) : null, captureMatches, limitResultCount);
    }
    replaceAll() {
      if (!this._hasMatches()) {
        return;
      }
      const findScopes = this._decorations.getFindScopes();
      if (findScopes === null && this._state.matchesCount >= MATCHES_LIMIT) {
        this._largeReplaceAll();
      } else {
        this._regularReplaceAll(findScopes);
      }
      this.research(false);
    }
    _largeReplaceAll() {
      const searchParams = new SearchParams(this._state.searchString, this._state.isRegex, this._state.matchCase, this._state.wholeWord ? this._editor.getOption(
        148
        /* EditorOption.wordSeparators */
      ) : null);
      const searchData = searchParams.parseSearchRequest();
      if (!searchData) {
        return;
      }
      let searchRegex = searchData.regex;
      if (!searchRegex.multiline) {
        let mod = "mu";
        if (searchRegex.ignoreCase) {
          mod += "i";
        }
        if (searchRegex.global) {
          mod += "g";
        }
        searchRegex = new RegExp(searchRegex.source, mod);
      }
      const model = this._editor.getModel();
      const modelText = model.getValue(
        1
        /* EndOfLinePreference.LF */
      );
      const fullModelRange = model.getFullModelRange();
      const replacePattern = this._getReplacePattern();
      let resultText;
      const preserveCase = this._state.preserveCase;
      if (replacePattern.hasReplacementPatterns || preserveCase) {
        resultText = modelText.replace(searchRegex, function() {
          return replacePattern.buildReplaceString(arguments, preserveCase);
        });
      } else {
        resultText = modelText.replace(searchRegex, replacePattern.buildReplaceString(null, preserveCase));
      }
      const command = new ReplaceCommandThatPreservesSelection(fullModelRange, resultText, this._editor.getSelection());
      this._executeEditorCommand("replaceAll", command);
    }
    _regularReplaceAll(findScopes) {
      const replacePattern = this._getReplacePattern();
      const matches = this._findMatches(
        findScopes,
        replacePattern.hasReplacementPatterns || this._state.preserveCase,
        1073741824
        /* Constants.MAX_SAFE_SMALL_INTEGER */
      );
      const replaceStrings = [];
      for (let i2 = 0, len = matches.length; i2 < len; i2++) {
        replaceStrings[i2] = replacePattern.buildReplaceString(matches[i2].matches, this._state.preserveCase);
      }
      const command = new ReplaceAllCommand(this._editor.getSelection(), matches.map((m) => m.range), replaceStrings);
      this._executeEditorCommand("replaceAll", command);
    }
    selectAllMatches() {
      if (!this._hasMatches()) {
        return;
      }
      const findScopes = this._decorations.getFindScopes();
      const matches = this._findMatches(
        findScopes,
        false,
        1073741824
        /* Constants.MAX_SAFE_SMALL_INTEGER */
      );
      let selections = matches.map((m) => new Selection$1(m.range.startLineNumber, m.range.startColumn, m.range.endLineNumber, m.range.endColumn));
      const editorSelection = this._editor.getSelection();
      for (let i2 = 0, len = selections.length; i2 < len; i2++) {
        const sel = selections[i2];
        if (sel.equalsRange(editorSelection)) {
          selections = [editorSelection].concat(selections.slice(0, i2)).concat(selections.slice(i2 + 1));
          break;
        }
      }
      this._editor.setSelections(selections);
    }
    _executeEditorCommand(source, command) {
      try {
        this._ignoreModelContentChanged = true;
        this._editor.pushUndoStop();
        this._editor.executeCommand(source, command);
        this._editor.pushUndoStop();
      } finally {
        this._ignoreModelContentChanged = false;
      }
    }
  }
  const NLS_CASE_SENSITIVE_TOGGLE_LABEL = localize(2, "Match Case");
  const NLS_WHOLE_WORD_TOGGLE_LABEL = localize(3, "Match Whole Word");
  const NLS_REGEX_TOGGLE_LABEL = localize(4, "Use Regular Expression");
  class CaseSensitiveToggle extends Toggle {
    constructor(opts) {
      super({
        icon: Codicon.caseSensitive,
        title: NLS_CASE_SENSITIVE_TOGGLE_LABEL + opts.appendTitle,
        isChecked: opts.isChecked,
        hoverLifecycleOptions: opts.hoverLifecycleOptions,
        inputActiveOptionBorder: opts.inputActiveOptionBorder,
        inputActiveOptionForeground: opts.inputActiveOptionForeground,
        inputActiveOptionBackground: opts.inputActiveOptionBackground
      });
    }
  }
  class WholeWordsToggle extends Toggle {
    constructor(opts) {
      super({
        icon: Codicon.wholeWord,
        title: NLS_WHOLE_WORD_TOGGLE_LABEL + opts.appendTitle,
        isChecked: opts.isChecked,
        hoverLifecycleOptions: opts.hoverLifecycleOptions,
        inputActiveOptionBorder: opts.inputActiveOptionBorder,
        inputActiveOptionForeground: opts.inputActiveOptionForeground,
        inputActiveOptionBackground: opts.inputActiveOptionBackground
      });
    }
  }
  class RegexToggle extends Toggle {
    constructor(opts) {
      super({
        icon: Codicon.regex,
        title: NLS_REGEX_TOGGLE_LABEL + opts.appendTitle,
        isChecked: opts.isChecked,
        hoverLifecycleOptions: opts.hoverLifecycleOptions,
        inputActiveOptionBorder: opts.inputActiveOptionBorder,
        inputActiveOptionForeground: opts.inputActiveOptionForeground,
        inputActiveOptionBackground: opts.inputActiveOptionBackground
      });
    }
  }
  function renderText(text2, _options, target) {
    const element = target ?? document.createElement("div");
    element.textContent = text2;
    return element;
  }
  function renderFormattedText(formattedText, options, target) {
    const element = target ?? document.createElement("div");
    element.textContent = "";
    _renderFormattedText(element, parseFormattedText(formattedText), options?.actionHandler, options?.renderCodeSegments);
    return element;
  }
  class StringStream {
    constructor(source) {
      this.source = source;
      this.index = 0;
    }
    eos() {
      return this.index >= this.source.length;
    }
    next() {
      const next = this.peek();
      this.advance();
      return next;
    }
    peek() {
      return this.source[this.index];
    }
    advance() {
      this.index++;
    }
  }
  function _renderFormattedText(element, treeNode, actionHandler, renderCodeSegments) {
    let child;
    if (treeNode.type === 2) {
      child = document.createTextNode(treeNode.content || "");
    } else if (treeNode.type === 3) {
      child = document.createElement("b");
    } else if (treeNode.type === 4) {
      child = document.createElement("i");
    } else if (treeNode.type === 7 && renderCodeSegments) {
      child = document.createElement("code");
    } else if (treeNode.type === 5 && actionHandler) {
      const a = document.createElement("a");
      actionHandler.disposables.add(addStandardDisposableListener(a, "click", (event) => {
        actionHandler.callback(String(treeNode.index), event);
      }));
      child = a;
    } else if (treeNode.type === 8) {
      child = document.createElement("br");
    } else if (treeNode.type === 1) {
      child = element;
    }
    if (child && element !== child) {
      element.appendChild(child);
    }
    if (child && Array.isArray(treeNode.children)) {
      treeNode.children.forEach((nodeChild) => {
        _renderFormattedText(child, nodeChild, actionHandler, renderCodeSegments);
      });
    }
  }
  function parseFormattedText(content, parseCodeSegments) {
    const root = {
      type: 1,
      children: []
    };
    let actionViewItemIndex = 0;
    let current = root;
    const stack = [];
    const stream = new StringStream(content);
    while (!stream.eos()) {
      let next = stream.next();
      const isEscapedFormatType = next === "\\" && formatTagType(stream.peek()) !== 0;
      if (isEscapedFormatType) {
        next = stream.next();
      }
      if (!isEscapedFormatType && isFormatTag(next) && next === stream.peek()) {
        stream.advance();
        if (current.type === 2) {
          current = stack.pop();
        }
        const type = formatTagType(next);
        if (current.type === type || current.type === 5 && type === 6) {
          current = stack.pop();
        } else {
          const newCurrent = {
            type,
            children: []
          };
          if (type === 5) {
            newCurrent.index = actionViewItemIndex;
            actionViewItemIndex++;
          }
          current.children.push(newCurrent);
          stack.push(current);
          current = newCurrent;
        }
      } else if (next === "\n") {
        if (current.type === 2) {
          current = stack.pop();
        }
        current.children.push({
          type: 8
          /* FormatType.NewLine */
        });
      } else {
        if (current.type !== 2) {
          const textCurrent = {
            type: 2,
            content: next
          };
          current.children.push(textCurrent);
          stack.push(current);
          current = textCurrent;
        } else {
          current.content += next;
        }
      }
    }
    if (current.type === 2) {
      current = stack.pop();
    }
    return root;
  }
  function isFormatTag(char, supportCodeSegments) {
    return formatTagType(char) !== 0;
  }
  function formatTagType(char, supportCodeSegments) {
    switch (char) {
      case "*":
        return 3;
      case "_":
        return 4;
      case "[":
        return 5;
      case "]":
        return 6;
      case "`":
        return 0;
      default:
        return 0;
    }
  }
  class ArrayNavigator {
    constructor(items, start = 0, end = items.length, index = start - 1) {
      this.items = items;
      this.start = start;
      this.end = end;
      this.index = index;
    }
    current() {
      if (this.index === this.start - 1 || this.index === this.end) {
        return null;
      }
      return this.items[this.index];
    }
    next() {
      this.index = Math.min(this.index + 1, this.end);
      return this.current();
    }
    previous() {
      this.index = Math.max(this.index - 1, this.start - 1);
      return this.current();
    }
    first() {
      this.index = this.start;
      return this.current();
    }
    last() {
      this.index = this.end - 1;
      return this.current();
    }
  }
  class HistoryNavigator {
    constructor(_history = /* @__PURE__ */ new Set(), limit = 10) {
      this._history = _history;
      this._limit = limit;
      this._onChange();
      if (this._history.onDidChange) {
        this._disposable = this._history.onDidChange(() => this._onChange());
      }
    }
    getHistory() {
      return this._elements;
    }
    add(t) {
      this._history.delete(t);
      this._history.add(t);
      this._onChange();
    }
    next() {
      return this._navigator.next();
    }
    previous() {
      if (this._currentPosition() !== 0) {
        return this._navigator.previous();
      }
      return null;
    }
    current() {
      return this._navigator.current();
    }
    first() {
      return this._navigator.first();
    }
    last() {
      return this._navigator.last();
    }
    isLast() {
      return this._currentPosition() >= this._elements.length - 1;
    }
    isNowhere() {
      return this._navigator.current() === null;
    }
    has(t) {
      return this._history.has(t);
    }
    _onChange() {
      this._reduceToLimit();
      const elements = this._elements;
      this._navigator = new ArrayNavigator(elements, 0, elements.length, elements.length);
    }
    _reduceToLimit() {
      const data = this._elements;
      if (data.length > this._limit) {
        const replaceValue = data.slice(data.length - this._limit);
        if (this._history.replace) {
          this._history.replace(replaceValue);
        } else {
          this._history = new Set(replaceValue);
        }
      }
    }
    _currentPosition() {
      const currentElement = this._navigator.current();
      if (!currentElement) {
        return -1;
      }
      return this._elements.indexOf(currentElement);
    }
    get _elements() {
      const elements = [];
      this._history.forEach((e) => elements.push(e));
      return elements;
    }
    dispose() {
      if (this._disposable) {
        this._disposable.dispose();
        this._disposable = void 0;
      }
    }
  }
  const $$g = $$l;
  let InputBox$1 = class InputBox extends Widget$1 {
    get onDidChange() {
      return this._onDidChange.event;
    }
    get onDidHeightChange() {
      return this._onDidHeightChange.event;
    }
    constructor(container, contextViewProvider, options) {
      super();
      this.state = "idle";
      this.maxHeight = Number.POSITIVE_INFINITY;
      this.hover = this._register(new MutableDisposable());
      this._onDidChange = this._register(new Emitter$1());
      this._onDidHeightChange = this._register(new Emitter$1());
      this.contextViewProvider = contextViewProvider;
      this.options = options;
      this.message = null;
      this.placeholder = this.options.placeholder || "";
      this.tooltip = this.options.tooltip ?? (this.placeholder || "");
      this.ariaLabel = this.options.ariaLabel || "";
      if (this.options.validationOptions) {
        this.validation = this.options.validationOptions.validation;
      }
      this.element = append$2(container, $$g(".monaco-inputbox.idle"));
      const tagName = this.options.flexibleHeight ? "textarea" : "input";
      const wrapper = append$2(this.element, $$g(".ibwrapper"));
      this.input = append$2(wrapper, $$g(tagName + ".input.empty"));
      this.input.setAttribute("autocorrect", "off");
      this.input.setAttribute("autocapitalize", "off");
      this.input.setAttribute("spellcheck", "false");
      this.onfocus(this.input, () => this.element.classList.add("synthetic-focus"));
      this.onblur(this.input, () => this.element.classList.remove("synthetic-focus"));
      if (this.options.flexibleHeight) {
        this.maxHeight = typeof this.options.flexibleMaxHeight === "number" ? this.options.flexibleMaxHeight : Number.POSITIVE_INFINITY;
        this.mirror = append$2(wrapper, $$g("div.mirror"));
        this.mirror.innerText = " ";
        this.scrollableElement = new ScrollableElement(this.element, {
          vertical: 1
          /* ScrollbarVisibility.Auto */
        });
        if (this.options.flexibleWidth) {
          this.input.setAttribute("wrap", "off");
          this.mirror.style.whiteSpace = "pre";
          this.mirror.style.wordWrap = "initial";
        }
        append$2(container, this.scrollableElement.getDomNode());
        this._register(this.scrollableElement);
        this._register(this.scrollableElement.onScroll((e) => this.input.scrollTop = e.scrollTop));
        const onSelectionChange = this._register(new DomEmitter(container.ownerDocument, "selectionchange"));
        const onAnchoredSelectionChange = Event.filter(onSelectionChange.event, () => {
          const selection = container.ownerDocument.getSelection();
          return selection?.anchorNode === wrapper;
        });
        this._register(onAnchoredSelectionChange(this.updateScrollDimensions, this));
        this._register(this.onDidHeightChange(this.updateScrollDimensions, this));
      } else {
        this.input.type = this.options.type || "text";
        this.input.setAttribute("wrap", "off");
      }
      if (this.ariaLabel) {
        this.input.setAttribute("aria-label", this.ariaLabel);
      }
      if (this.placeholder && !this.options.showPlaceholderOnFocus) {
        this.setPlaceHolder(this.placeholder);
      }
      if (this.tooltip) {
        this.setTooltip(this.tooltip);
      }
      this.oninput(this.input, () => this.onValueChange());
      this.onblur(this.input, () => this.onBlur());
      this.onfocus(this.input, () => this.onFocus());
      this._register(this.ignoreGesture(this.input));
      setTimeout(() => this.updateMirror(), 0);
      if (this.options.actions) {
        this.actionbar = this._register(new ActionBar(this.element));
        this.actionbar.push(this.options.actions, { icon: true, label: false });
      }
      this.applyStyles();
    }
    onBlur() {
      this._hideMessage();
      if (this.options.showPlaceholderOnFocus) {
        this.input.setAttribute("placeholder", "");
      }
    }
    onFocus() {
      this._showMessage();
      if (this.options.showPlaceholderOnFocus) {
        this.input.setAttribute("placeholder", this.placeholder || "");
      }
    }
    setPlaceHolder(placeHolder) {
      this.placeholder = placeHolder;
      this.input.setAttribute("placeholder", placeHolder);
    }
    setTooltip(tooltip) {
      this.tooltip = tooltip;
      if (!this.hover.value) {
        this.hover.value = this._register(getBaseLayerHoverDelegate().setupDelayedHoverAtMouse(this.input, () => ({
          content: this.tooltip,
          appearance: {
            compact: true
          }
        })));
      }
    }
    get inputElement() {
      return this.input;
    }
    get value() {
      return this.input.value;
    }
    set value(newValue) {
      if (this.input.value !== newValue) {
        this.input.value = newValue;
        this.onValueChange();
      }
    }
    get height() {
      return typeof this.cachedHeight === "number" ? this.cachedHeight : getTotalHeight(this.element);
    }
    focus() {
      this.input.focus();
    }
    blur() {
      this.input.blur();
    }
    hasFocus() {
      return isActiveElement(this.input);
    }
    select(range2 = null) {
      this.input.select();
      if (range2) {
        this.input.setSelectionRange(range2.start, range2.end);
        if (range2.end === this.input.value.length) {
          this.input.scrollLeft = this.input.scrollWidth;
        }
      }
    }
    isSelectionAtEnd() {
      return this.input.selectionEnd === this.input.value.length && this.input.selectionStart === this.input.selectionEnd;
    }
    getSelection() {
      const selectionStart = this.input.selectionStart;
      if (selectionStart === null) {
        return null;
      }
      const selectionEnd = this.input.selectionEnd ?? selectionStart;
      return {
        start: selectionStart,
        end: selectionEnd
      };
    }
    enable() {
      this.input.removeAttribute("disabled");
    }
    disable() {
      this.blur();
      this.input.disabled = true;
      this._hideMessage();
    }
    set paddingRight(paddingRight) {
      this.input.style.width = `calc(100% - ${paddingRight}px)`;
      if (this.mirror) {
        this.mirror.style.paddingRight = paddingRight + "px";
      }
    }
    updateScrollDimensions() {
      if (typeof this.cachedContentHeight !== "number" || typeof this.cachedHeight !== "number" || !this.scrollableElement) {
        return;
      }
      const scrollHeight = this.cachedContentHeight;
      const height = this.cachedHeight;
      const scrollTop = this.input.scrollTop;
      this.scrollableElement.setScrollDimensions({ scrollHeight, height });
      this.scrollableElement.setScrollPosition({ scrollTop });
    }
    showMessage(message, force) {
      if (this.state === "open" && equals(this.message, message)) {
        return;
      }
      this.message = message;
      this.element.classList.remove("idle");
      this.element.classList.remove("info");
      this.element.classList.remove("warning");
      this.element.classList.remove("error");
      this.element.classList.add(this.classForType(message.type));
      const styles = this.stylesForType(this.message.type);
      this.element.style.border = `1px solid ${asCssValueWithDefault(styles.border, "transparent")}`;
      if (this.message.content && (this.hasFocus() || force)) {
        this._showMessage();
      }
    }
    hideMessage() {
      this.message = null;
      this.element.classList.remove("info");
      this.element.classList.remove("warning");
      this.element.classList.remove("error");
      this.element.classList.add("idle");
      this._hideMessage();
      this.applyStyles();
    }
    validate() {
      let errorMsg = null;
      if (this.validation) {
        errorMsg = this.validation(this.value);
        if (errorMsg) {
          this.inputElement.setAttribute("aria-invalid", "true");
          this.showMessage(errorMsg);
        } else if (this.inputElement.hasAttribute("aria-invalid")) {
          this.inputElement.removeAttribute("aria-invalid");
          this.hideMessage();
        }
      }
      return errorMsg?.type;
    }
    stylesForType(type) {
      const styles = this.options.inputBoxStyles;
      switch (type) {
        case 1:
          return { border: styles.inputValidationInfoBorder, background: styles.inputValidationInfoBackground, foreground: styles.inputValidationInfoForeground };
        case 2:
          return { border: styles.inputValidationWarningBorder, background: styles.inputValidationWarningBackground, foreground: styles.inputValidationWarningForeground };
        default:
          return { border: styles.inputValidationErrorBorder, background: styles.inputValidationErrorBackground, foreground: styles.inputValidationErrorForeground };
      }
    }
    classForType(type) {
      switch (type) {
        case 1:
          return "info";
        case 2:
          return "warning";
        default:
          return "error";
      }
    }
    _showMessage() {
      if (!this.contextViewProvider || !this.message) {
        return;
      }
      let div;
      const layout2 = () => div.style.width = getTotalWidth(this.element) + "px";
      this.contextViewProvider.showContextView({
        getAnchor: () => this.element,
        anchorAlignment: 1,
        render: (container) => {
          if (!this.message) {
            return null;
          }
          div = append$2(container, $$g(".monaco-inputbox-container"));
          layout2();
          const spanElement = $$g("span.monaco-inputbox-message");
          if (this.message.formatContent) {
            renderFormattedText(this.message.content, void 0, spanElement);
          } else {
            renderText(this.message.content, void 0, spanElement);
          }
          spanElement.classList.add(this.classForType(this.message.type));
          const styles = this.stylesForType(this.message.type);
          spanElement.style.backgroundColor = styles.background ?? "";
          spanElement.style.color = styles.foreground ?? "";
          spanElement.style.border = styles.border ? `1px solid ${styles.border}` : "";
          append$2(div, spanElement);
          return null;
        },
        onHide: () => {
          this.state = "closed";
        },
        layout: layout2
      });
      let alertText;
      if (this.message.type === 3) {
        alertText = localize(9, "Error: {0}", this.message.content);
      } else if (this.message.type === 2) {
        alertText = localize(10, "Warning: {0}", this.message.content);
      } else {
        alertText = localize(11, "Info: {0}", this.message.content);
      }
      alert(alertText);
      this.state = "open";
    }
    _hideMessage() {
      if (!this.contextViewProvider) {
        return;
      }
      if (this.state === "open") {
        this.contextViewProvider.hideContextView();
      }
      this.state = "idle";
    }
    onValueChange() {
      this._onDidChange.fire(this.value);
      this.validate();
      this.updateMirror();
      this.input.classList.toggle("empty", !this.value);
      if (this.state === "open" && this.contextViewProvider) {
        this.contextViewProvider.layout();
      }
    }
    updateMirror() {
      if (!this.mirror) {
        return;
      }
      const value = this.value;
      const lastCharCode = value.charCodeAt(value.length - 1);
      const suffix = lastCharCode === 10 ? " " : "";
      const mirrorTextContent = (value + suffix).replace(/\u000c/g, "");
      if (mirrorTextContent) {
        this.mirror.textContent = value + suffix;
      } else {
        this.mirror.innerText = " ";
      }
      this.layout();
    }
    applyStyles() {
      const styles = this.options.inputBoxStyles;
      const background = styles.inputBackground ?? "";
      const foreground2 = styles.inputForeground ?? "";
      const border = styles.inputBorder ?? "";
      this.element.style.backgroundColor = background;
      this.element.style.color = foreground2;
      this.input.style.backgroundColor = "inherit";
      this.input.style.color = foreground2;
      this.element.style.border = `1px solid ${asCssValueWithDefault(border, "transparent")}`;
    }
    layout() {
      if (!this.mirror) {
        return;
      }
      const previousHeight = this.cachedContentHeight;
      this.cachedContentHeight = getTotalHeight(this.mirror);
      if (previousHeight !== this.cachedContentHeight) {
        this.cachedHeight = Math.min(this.cachedContentHeight, this.maxHeight);
        this.input.style.height = this.cachedHeight + "px";
        this._onDidHeightChange.fire(this.cachedContentHeight);
      }
    }
    insertAtCursor(text2) {
      const inputElement = this.inputElement;
      const start = inputElement.selectionStart;
      const end = inputElement.selectionEnd;
      const content = inputElement.value;
      if (start !== null && end !== null) {
        this.value = content.substr(0, start) + text2 + content.substr(end);
        inputElement.setSelectionRange(start + 1, start + 1);
        this.layout();
      }
    }
    dispose() {
      this._hideMessage();
      this.message = null;
      this.actionbar?.dispose();
      super.dispose();
    }
  };
  class HistoryInputBox extends InputBox$1 {
    constructor(container, contextViewProvider, options) {
      const NLS_PLACEHOLDER_HISTORY_HINT_SUFFIX_NO_PARENS = localize(12, " or {0} for history", `⇅`);
      const NLS_PLACEHOLDER_HISTORY_HINT_SUFFIX_IN_PARENS = localize(13, " ({0} for history)", `⇅`);
      super(container, contextViewProvider, options);
      this._onDidFocus = this._register(new Emitter$1());
      this.onDidFocus = this._onDidFocus.event;
      this._onDidBlur = this._register(new Emitter$1());
      this.onDidBlur = this._onDidBlur.event;
      this.history = this._register(new HistoryNavigator(options.history, 100));
      const addSuffix = () => {
        if (options.showHistoryHint && options.showHistoryHint() && !this.placeholder.endsWith(NLS_PLACEHOLDER_HISTORY_HINT_SUFFIX_NO_PARENS) && !this.placeholder.endsWith(NLS_PLACEHOLDER_HISTORY_HINT_SUFFIX_IN_PARENS) && this.history.getHistory().length) {
          const suffix = this.placeholder.endsWith(")") ? NLS_PLACEHOLDER_HISTORY_HINT_SUFFIX_NO_PARENS : NLS_PLACEHOLDER_HISTORY_HINT_SUFFIX_IN_PARENS;
          const suffixedPlaceholder = this.placeholder + suffix;
          if (options.showPlaceholderOnFocus && !isActiveElement(this.input)) {
            this.placeholder = suffixedPlaceholder;
          } else {
            this.setPlaceHolder(suffixedPlaceholder);
          }
        }
      };
      this.observer = new MutationObserver((mutationList, observer) => {
        mutationList.forEach((mutation) => {
          if (!mutation.target.textContent) {
            addSuffix();
          }
        });
      });
      this.observer.observe(this.input, { attributeFilter: ["class"] });
      this.onfocus(this.input, () => addSuffix());
      this.onblur(this.input, () => {
        const resetPlaceholder = (historyHint) => {
          if (!this.placeholder.endsWith(historyHint)) {
            return false;
          } else {
            const revertedPlaceholder = this.placeholder.slice(0, this.placeholder.length - historyHint.length);
            if (options.showPlaceholderOnFocus) {
              this.placeholder = revertedPlaceholder;
            } else {
              this.setPlaceHolder(revertedPlaceholder);
            }
            return true;
          }
        };
        if (!resetPlaceholder(NLS_PLACEHOLDER_HISTORY_HINT_SUFFIX_IN_PARENS)) {
          resetPlaceholder(NLS_PLACEHOLDER_HISTORY_HINT_SUFFIX_NO_PARENS);
        }
      });
    }
    dispose() {
      super.dispose();
      if (this.observer) {
        this.observer.disconnect();
        this.observer = void 0;
      }
    }
    addToHistory(always) {
      if (this.value && (always || this.value !== this.getCurrentValue())) {
        this.history.add(this.value);
      }
    }
    isAtLastInHistory() {
      return this.history.isLast();
    }
    isNowhereInHistory() {
      return this.history.isNowhere();
    }
    showNextValue() {
      if (!this.history.has(this.value)) {
        this.addToHistory();
      }
      let next = this.getNextValue();
      if (next) {
        next = next === this.value ? this.getNextValue() : next;
      }
      this.value = next ?? "";
      status(this.value ? this.value : localize(14, "Cleared Input"));
    }
    showPreviousValue() {
      if (!this.history.has(this.value)) {
        this.addToHistory();
      }
      let previous = this.getPreviousValue();
      if (previous) {
        previous = previous === this.value ? this.getPreviousValue() : previous;
      }
      if (previous) {
        this.value = previous;
        status(this.value);
      }
    }
    setPlaceHolder(placeHolder) {
      super.setPlaceHolder(placeHolder);
      this.setTooltip(placeHolder);
    }
    onBlur() {
      super.onBlur();
      this._onDidBlur.fire();
    }
    onFocus() {
      super.onFocus();
      this._onDidFocus.fire();
    }
    getCurrentValue() {
      let currentValue = this.history.current();
      if (!currentValue) {
        currentValue = this.history.last();
        this.history.next();
      }
      return currentValue;
    }
    getPreviousValue() {
      return this.history.previous() || this.history.first();
    }
    getNextValue() {
      return this.history.next();
    }
  }
  const NLS_DEFAULT_LABEL$1 = localize(1, "input");
  class FindInput extends Widget$1 {
    get onDidOptionChange() {
      return this._onDidOptionChange.event;
    }
    get onKeyDown() {
      return this._onKeyDown.event;
    }
    get onMouseDown() {
      return this._onMouseDown.event;
    }
    get onCaseSensitiveKeyDown() {
      return this._onCaseSensitiveKeyDown.event;
    }
    get onRegexKeyDown() {
      return this._onRegexKeyDown.event;
    }
    constructor(parent, contextViewProvider, options) {
      super();
      this.fixFocusOnOptionClickEnabled = true;
      this.imeSessionInProgress = false;
      this.additionalTogglesDisposables = this._register(new MutableDisposable());
      this.additionalToggles = [];
      this._onDidOptionChange = this._register(new Emitter$1());
      this._onKeyDown = this._register(new Emitter$1());
      this._onMouseDown = this._register(new Emitter$1());
      this._onInput = this._register(new Emitter$1());
      this._onKeyUp = this._register(new Emitter$1());
      this._onCaseSensitiveKeyDown = this._register(new Emitter$1());
      this._onRegexKeyDown = this._register(new Emitter$1());
      this._lastHighlightFindOptions = 0;
      this.placeholder = options.placeholder || "";
      this.validation = options.validation;
      this.label = options.label || NLS_DEFAULT_LABEL$1;
      this.showCommonFindToggles = !!options.showCommonFindToggles;
      const appendCaseSensitiveLabel = options.appendCaseSensitiveLabel || "";
      const appendWholeWordsLabel = options.appendWholeWordsLabel || "";
      const appendRegexLabel = options.appendRegexLabel || "";
      const flexibleHeight = !!options.flexibleHeight;
      const flexibleWidth = !!options.flexibleWidth;
      const flexibleMaxHeight = options.flexibleMaxHeight;
      this.domNode = document.createElement("div");
      this.domNode.classList.add("monaco-findInput");
      this.inputBox = this._register(new HistoryInputBox(this.domNode, contextViewProvider, {
        placeholder: this.placeholder || "",
        ariaLabel: this.label || "",
        validationOptions: {
          validation: this.validation
        },
        showHistoryHint: options.showHistoryHint,
        flexibleHeight,
        flexibleWidth,
        flexibleMaxHeight,
        inputBoxStyles: options.inputBoxStyles,
        history: options.history
      }));
      if (this.showCommonFindToggles) {
        const hoverLifecycleOptions = options?.hoverLifecycleOptions || { groupId: "find-input" };
        this.regex = this._register(new RegexToggle({
          appendTitle: appendRegexLabel,
          isChecked: false,
          hoverLifecycleOptions,
          ...options.toggleStyles
        }));
        this._register(this.regex.onChange((viaKeyboard) => {
          this._onDidOptionChange.fire(viaKeyboard);
          if (!viaKeyboard && this.fixFocusOnOptionClickEnabled) {
            this.inputBox.focus();
          }
          this.validate();
        }));
        this._register(this.regex.onKeyDown((e) => {
          this._onRegexKeyDown.fire(e);
        }));
        this.wholeWords = this._register(new WholeWordsToggle({
          appendTitle: appendWholeWordsLabel,
          isChecked: false,
          hoverLifecycleOptions,
          ...options.toggleStyles
        }));
        this._register(this.wholeWords.onChange((viaKeyboard) => {
          this._onDidOptionChange.fire(viaKeyboard);
          if (!viaKeyboard && this.fixFocusOnOptionClickEnabled) {
            this.inputBox.focus();
          }
          this.validate();
        }));
        this.caseSensitive = this._register(new CaseSensitiveToggle({
          appendTitle: appendCaseSensitiveLabel,
          isChecked: false,
          hoverLifecycleOptions,
          ...options.toggleStyles
        }));
        this._register(this.caseSensitive.onChange((viaKeyboard) => {
          this._onDidOptionChange.fire(viaKeyboard);
          if (!viaKeyboard && this.fixFocusOnOptionClickEnabled) {
            this.inputBox.focus();
          }
          this.validate();
        }));
        this._register(this.caseSensitive.onKeyDown((e) => {
          this._onCaseSensitiveKeyDown.fire(e);
        }));
        const indexes = [this.caseSensitive.domNode, this.wholeWords.domNode, this.regex.domNode];
        this.onkeydown(this.domNode, (event) => {
          if (event.equals(
            15
            /* KeyCode.LeftArrow */
          ) || event.equals(
            17
            /* KeyCode.RightArrow */
          ) || event.equals(
            9
            /* KeyCode.Escape */
          )) {
            const index = indexes.indexOf(this.domNode.ownerDocument.activeElement);
            if (index >= 0) {
              let newIndex = -1;
              if (event.equals(
                17
                /* KeyCode.RightArrow */
              )) {
                newIndex = (index + 1) % indexes.length;
              } else if (event.equals(
                15
                /* KeyCode.LeftArrow */
              )) {
                if (index === 0) {
                  newIndex = indexes.length - 1;
                } else {
                  newIndex = index - 1;
                }
              }
              if (event.equals(
                9
                /* KeyCode.Escape */
              )) {
                indexes[index].blur();
                this.inputBox.focus();
              } else if (newIndex >= 0) {
                indexes[newIndex].focus();
              }
              EventHelper.stop(event, true);
            }
          }
        });
      }
      this.controls = document.createElement("div");
      this.controls.className = "controls";
      this.controls.style.display = this.showCommonFindToggles ? "" : "none";
      if (this.caseSensitive) {
        this.controls.append(this.caseSensitive.domNode);
      }
      if (this.wholeWords) {
        this.controls.appendChild(this.wholeWords.domNode);
      }
      if (this.regex) {
        this.controls.appendChild(this.regex.domNode);
      }
      this.setAdditionalToggles(options?.additionalToggles);
      if (this.controls) {
        this.domNode.appendChild(this.controls);
      }
      parent?.appendChild(this.domNode);
      this._register(addDisposableListener(this.inputBox.inputElement, "compositionstart", (e) => {
        this.imeSessionInProgress = true;
      }));
      this._register(addDisposableListener(this.inputBox.inputElement, "compositionend", (e) => {
        this.imeSessionInProgress = false;
        this._onInput.fire();
      }));
      this.onkeydown(this.inputBox.inputElement, (e) => this._onKeyDown.fire(e));
      this.onkeyup(this.inputBox.inputElement, (e) => this._onKeyUp.fire(e));
      this.oninput(this.inputBox.inputElement, (e) => this._onInput.fire());
      this.onmousedown(this.inputBox.inputElement, (e) => this._onMouseDown.fire(e));
    }
    get onDidChange() {
      return this.inputBox.onDidChange;
    }
    layout(style) {
      this.inputBox.layout();
      this.updateInputBoxPadding(style.collapsedFindWidget);
    }
    enable() {
      this.domNode.classList.remove("disabled");
      this.inputBox.enable();
      this.regex?.enable();
      this.wholeWords?.enable();
      this.caseSensitive?.enable();
      for (const toggle of this.additionalToggles) {
        toggle.enable();
      }
    }
    disable() {
      this.domNode.classList.add("disabled");
      this.inputBox.disable();
      this.regex?.disable();
      this.wholeWords?.disable();
      this.caseSensitive?.disable();
      for (const toggle of this.additionalToggles) {
        toggle.disable();
      }
    }
    setFocusInputOnOptionClick(value) {
      this.fixFocusOnOptionClickEnabled = value;
    }
    setEnabled(enabled) {
      if (enabled) {
        this.enable();
      } else {
        this.disable();
      }
    }
    setAdditionalToggles(toggles) {
      for (const currentToggle of this.additionalToggles) {
        currentToggle.domNode.remove();
      }
      this.additionalToggles = [];
      this.additionalTogglesDisposables.value = new DisposableStore();
      for (const toggle of toggles ?? []) {
        this.additionalTogglesDisposables.value.add(toggle);
        this.controls.appendChild(toggle.domNode);
        this.additionalTogglesDisposables.value.add(toggle.onChange((viaKeyboard) => {
          this._onDidOptionChange.fire(viaKeyboard);
          if (!viaKeyboard && this.fixFocusOnOptionClickEnabled) {
            this.inputBox.focus();
          }
        }));
        this.additionalToggles.push(toggle);
      }
      if (this.additionalToggles.length > 0) {
        this.controls.style.display = "";
      }
      this.updateInputBoxPadding();
    }
    updateInputBoxPadding(controlsHidden = false) {
      if (controlsHidden) {
        this.inputBox.paddingRight = 0;
      } else {
        this.inputBox.paddingRight = (this.caseSensitive?.width() ?? 0) + (this.wholeWords?.width() ?? 0) + (this.regex?.width() ?? 0) + this.additionalToggles.reduce((r, t) => r + t.width(), 0);
      }
    }
    getValue() {
      return this.inputBox.value;
    }
    setValue(value) {
      if (this.inputBox.value !== value) {
        this.inputBox.value = value;
      }
    }
    select() {
      this.inputBox.select();
    }
    focus() {
      this.inputBox.focus();
    }
    getCaseSensitive() {
      return this.caseSensitive?.checked ?? false;
    }
    setCaseSensitive(value) {
      if (this.caseSensitive) {
        this.caseSensitive.checked = value;
      }
    }
    getWholeWords() {
      return this.wholeWords?.checked ?? false;
    }
    setWholeWords(value) {
      if (this.wholeWords) {
        this.wholeWords.checked = value;
      }
    }
    getRegex() {
      return this.regex?.checked ?? false;
    }
    setRegex(value) {
      if (this.regex) {
        this.regex.checked = value;
        this.validate();
      }
    }
    focusOnCaseSensitive() {
      this.caseSensitive?.focus();
    }
    highlightFindOptions() {
      this.domNode.classList.remove("highlight-" + this._lastHighlightFindOptions);
      this._lastHighlightFindOptions = 1 - this._lastHighlightFindOptions;
      this.domNode.classList.add("highlight-" + this._lastHighlightFindOptions);
    }
    validate() {
      this.inputBox.validate();
    }
    showMessage(message) {
      this.inputBox.showMessage(message);
    }
    clearMessage() {
      this.inputBox.hideMessage();
    }
  }
  const NLS_DEFAULT_LABEL = localize(5, "input");
  const NLS_PRESERVE_CASE_LABEL = localize(6, "Preserve Case");
  class PreserveCaseToggle extends Toggle {
    constructor(opts) {
      super({
        // TODO: does this need its own icon?
        icon: Codicon.preserveCase,
        title: NLS_PRESERVE_CASE_LABEL + opts.appendTitle,
        isChecked: opts.isChecked,
        hoverLifecycleOptions: opts.hoverLifecycleOptions,
        inputActiveOptionBorder: opts.inputActiveOptionBorder,
        inputActiveOptionForeground: opts.inputActiveOptionForeground,
        inputActiveOptionBackground: opts.inputActiveOptionBackground
      });
    }
  }
  class ReplaceInput extends Widget$1 {
    get onDidOptionChange() {
      return this._onDidOptionChange.event;
    }
    get onKeyDown() {
      return this._onKeyDown.event;
    }
    get onPreserveCaseKeyDown() {
      return this._onPreserveCaseKeyDown.event;
    }
    constructor(parent, contextViewProvider, _showOptionButtons, options) {
      super();
      this._showOptionButtons = _showOptionButtons;
      this.fixFocusOnOptionClickEnabled = true;
      this.cachedOptionsWidth = 0;
      this._onDidOptionChange = this._register(new Emitter$1());
      this._onKeyDown = this._register(new Emitter$1());
      this._onMouseDown = this._register(new Emitter$1());
      this._onInput = this._register(new Emitter$1());
      this._onKeyUp = this._register(new Emitter$1());
      this._onPreserveCaseKeyDown = this._register(new Emitter$1());
      this.contextViewProvider = contextViewProvider;
      this.placeholder = options.placeholder || "";
      this.validation = options.validation;
      this.label = options.label || NLS_DEFAULT_LABEL;
      const appendPreserveCaseLabel = options.appendPreserveCaseLabel || "";
      const history = options.history || /* @__PURE__ */ new Set([]);
      const flexibleHeight = !!options.flexibleHeight;
      const flexibleWidth = !!options.flexibleWidth;
      const flexibleMaxHeight = options.flexibleMaxHeight;
      this.domNode = document.createElement("div");
      this.domNode.classList.add("monaco-findInput");
      this.inputBox = this._register(new HistoryInputBox(this.domNode, this.contextViewProvider, {
        ariaLabel: this.label || "",
        placeholder: this.placeholder || "",
        validationOptions: {
          validation: this.validation
        },
        history,
        showHistoryHint: options.showHistoryHint,
        flexibleHeight,
        flexibleWidth,
        flexibleMaxHeight,
        inputBoxStyles: options.inputBoxStyles
      }));
      this.preserveCase = this._register(new PreserveCaseToggle({
        appendTitle: appendPreserveCaseLabel,
        isChecked: false,
        hoverLifecycleOptions: options.hoverLifecycleOptions,
        ...options.toggleStyles
      }));
      this._register(this.preserveCase.onChange((viaKeyboard) => {
        this._onDidOptionChange.fire(viaKeyboard);
        if (!viaKeyboard && this.fixFocusOnOptionClickEnabled) {
          this.inputBox.focus();
        }
        this.validate();
      }));
      this._register(this.preserveCase.onKeyDown((e) => {
        this._onPreserveCaseKeyDown.fire(e);
      }));
      if (this._showOptionButtons) {
        this.cachedOptionsWidth = this.preserveCase.width();
      } else {
        this.cachedOptionsWidth = 0;
      }
      const indexes = [this.preserveCase.domNode];
      this.onkeydown(this.domNode, (event) => {
        if (event.equals(
          15
          /* KeyCode.LeftArrow */
        ) || event.equals(
          17
          /* KeyCode.RightArrow */
        ) || event.equals(
          9
          /* KeyCode.Escape */
        )) {
          const index = indexes.indexOf(this.domNode.ownerDocument.activeElement);
          if (index >= 0) {
            let newIndex = -1;
            if (event.equals(
              17
              /* KeyCode.RightArrow */
            )) {
              newIndex = (index + 1) % indexes.length;
            } else if (event.equals(
              15
              /* KeyCode.LeftArrow */
            )) {
              if (index === 0) {
                newIndex = indexes.length - 1;
              } else {
                newIndex = index - 1;
              }
            }
            if (event.equals(
              9
              /* KeyCode.Escape */
            )) {
              indexes[index].blur();
              this.inputBox.focus();
            } else if (newIndex >= 0) {
              indexes[newIndex].focus();
            }
            EventHelper.stop(event, true);
          }
        }
      });
      const controls = document.createElement("div");
      controls.className = "controls";
      controls.style.display = this._showOptionButtons ? "block" : "none";
      controls.appendChild(this.preserveCase.domNode);
      this.domNode.appendChild(controls);
      parent?.appendChild(this.domNode);
      this.onkeydown(this.inputBox.inputElement, (e) => this._onKeyDown.fire(e));
      this.onkeyup(this.inputBox.inputElement, (e) => this._onKeyUp.fire(e));
      this.oninput(this.inputBox.inputElement, (e) => this._onInput.fire());
      this.onmousedown(this.inputBox.inputElement, (e) => this._onMouseDown.fire(e));
    }
    enable() {
      this.domNode.classList.remove("disabled");
      this.inputBox.enable();
      this.preserveCase.enable();
    }
    disable() {
      this.domNode.classList.add("disabled");
      this.inputBox.disable();
      this.preserveCase.disable();
    }
    setEnabled(enabled) {
      if (enabled) {
        this.enable();
      } else {
        this.disable();
      }
    }
    select() {
      this.inputBox.select();
    }
    focus() {
      this.inputBox.focus();
    }
    getPreserveCase() {
      return this.preserveCase.checked;
    }
    setPreserveCase(value) {
      this.preserveCase.checked = value;
    }
    focusOnPreserve() {
      this.preserveCase.focus();
    }
    validate() {
      this.inputBox?.validate();
    }
    set width(newWidth) {
      this.inputBox.paddingRight = this.cachedOptionsWidth;
      this.domNode.style.width = newWidth + "px";
    }
    dispose() {
      super.dispose();
    }
  }
  var __decorate$28 = 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$26 = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  const historyNavigationVisible = new RawContextKey("suggestWidgetVisible", false, localize(1698, "Whether suggestion are visible"));
  const HistoryNavigationWidgetFocusContext = "historyNavigationWidgetFocus";
  const HistoryNavigationForwardsEnablementContext = "historyNavigationForwardsEnabled";
  const HistoryNavigationBackwardsEnablementContext = "historyNavigationBackwardsEnabled";
  let lastFocusedWidget = void 0;
  const widgets = [];
  function registerAndCreateHistoryNavigationContext(scopedContextKeyService, widget) {
    if (widgets.includes(widget)) {
      throw new Error("Cannot register the same widget multiple times");
    }
    widgets.push(widget);
    const disposableStore = new DisposableStore();
    const historyNavigationWidgetFocus = new RawContextKey(HistoryNavigationWidgetFocusContext, false).bindTo(scopedContextKeyService);
    const historyNavigationForwardsEnablement = new RawContextKey(HistoryNavigationForwardsEnablementContext, true).bindTo(scopedContextKeyService);
    const historyNavigationBackwardsEnablement = new RawContextKey(HistoryNavigationBackwardsEnablementContext, true).bindTo(scopedContextKeyService);
    const onDidFocus = () => {
      historyNavigationWidgetFocus.set(true);
      lastFocusedWidget = widget;
    };
    const onDidBlur = () => {
      historyNavigationWidgetFocus.set(false);
      if (lastFocusedWidget === widget) {
        lastFocusedWidget = void 0;
      }
    };
    if (isActiveElement(widget.element)) {
      onDidFocus();
    }
    disposableStore.add(widget.onDidFocus(() => onDidFocus()));
    disposableStore.add(widget.onDidBlur(() => onDidBlur()));
    disposableStore.add(toDisposable(() => {
      widgets.splice(widgets.indexOf(widget), 1);
      onDidBlur();
    }));
    return {
      historyNavigationForwardsEnablement,
      historyNavigationBackwardsEnablement,
      dispose() {
        disposableStore.dispose();
      }
    };
  }
  let ContextScopedFindInput = class ContextScopedFindInput extends FindInput {
    constructor(container, contextViewProvider, options, contextKeyService) {
      super(container, contextViewProvider, options);
      const scopedContextKeyService = this._register(contextKeyService.createScoped(this.inputBox.element));
      this._register(registerAndCreateHistoryNavigationContext(scopedContextKeyService, this.inputBox));
    }
  };
  ContextScopedFindInput = __decorate$28([
    __param$26(3, IContextKeyService)
  ], ContextScopedFindInput);
  let ContextScopedReplaceInput = class ContextScopedReplaceInput extends ReplaceInput {
    constructor(container, contextViewProvider, options, contextKeyService, showReplaceOptions = false) {
      super(container, contextViewProvider, showReplaceOptions, options);
      const scopedContextKeyService = this._register(contextKeyService.createScoped(this.inputBox.element));
      this._register(registerAndCreateHistoryNavigationContext(scopedContextKeyService, this.inputBox));
    }
  };
  ContextScopedReplaceInput = __decorate$28([
    __param$26(3, IContextKeyService)
  ], ContextScopedReplaceInput);
  KeybindingsRegistry.registerCommandAndKeybindingRule({
    id: "history.showPrevious",
    weight: 200,
    when: ContextKeyExpr.and(ContextKeyExpr.has(HistoryNavigationWidgetFocusContext), ContextKeyExpr.equals(HistoryNavigationBackwardsEnablementContext, true), ContextKeyExpr.not("isComposing"), historyNavigationVisible.isEqualTo(false)),
    primary: 16,
    secondary: [
      512 | 16
      /* KeyCode.UpArrow */
    ],
    handler: (accessor) => {
      lastFocusedWidget?.showPreviousValue();
    }
  });
  KeybindingsRegistry.registerCommandAndKeybindingRule({
    id: "history.showNext",
    weight: 200,
    when: ContextKeyExpr.and(ContextKeyExpr.has(HistoryNavigationWidgetFocusContext), ContextKeyExpr.equals(HistoryNavigationForwardsEnablementContext, true), ContextKeyExpr.not("isComposing"), historyNavigationVisible.isEqualTo(false)),
    primary: 18,
    secondary: [
      512 | 18
      /* KeyCode.DownArrow */
    ],
    handler: (accessor) => {
      lastFocusedWidget?.showNextValue();
    }
  });
  function showHistoryKeybindingHint(keybindingService) {
    return keybindingService.lookupKeybinding("history.showPrevious")?.getElectronAccelerator() === "Up" && keybindingService.lookupKeybinding("history.showNext")?.getElectronAccelerator() === "Down";
  }
  const findCollapsedIcon = registerIcon("find-collapsed", Codicon.chevronRight, localize(956, "Icon to indicate that the editor find widget is collapsed."));
  const findExpandedIcon = registerIcon("find-expanded", Codicon.chevronDown, localize(957, "Icon to indicate that the editor find widget is expanded."));
  const findSelectionIcon = registerIcon("find-selection", Codicon.selection, localize(958, "Icon for 'Find in Selection' in the editor find widget."));
  const findReplaceIcon = registerIcon("find-replace", Codicon.replace, localize(959, "Icon for 'Replace' in the editor find widget."));
  const findReplaceAllIcon = registerIcon("find-replace-all", Codicon.replaceAll, localize(960, "Icon for 'Replace All' in the editor find widget."));
  const findPreviousMatchIcon = registerIcon("find-previous-match", Codicon.arrowUp, localize(961, "Icon for 'Find Previous' in the editor find widget."));
  const findNextMatchIcon = registerIcon("find-next-match", Codicon.arrowDown, localize(962, "Icon for 'Find Next' in the editor find widget."));
  const NLS_FIND_DIALOG_LABEL = localize(963, "Find / Replace");
  const NLS_FIND_INPUT_LABEL = localize(964, "Find");
  const NLS_FIND_INPUT_PLACEHOLDER = localize(965, "Find");
  const NLS_PREVIOUS_MATCH_BTN_LABEL = localize(966, "Previous Match");
  const NLS_NEXT_MATCH_BTN_LABEL = localize(967, "Next Match");
  const NLS_TOGGLE_SELECTION_FIND_TITLE = localize(968, "Find in Selection");
  const NLS_CLOSE_BTN_LABEL = localize(969, "Close");
  const NLS_REPLACE_INPUT_LABEL = localize(970, "Replace");
  const NLS_REPLACE_INPUT_PLACEHOLDER = localize(971, "Replace");
  const NLS_REPLACE_BTN_LABEL = localize(972, "Replace");
  const NLS_REPLACE_ALL_BTN_LABEL = localize(973, "Replace All");
  const NLS_TOGGLE_REPLACE_MODE_BTN_LABEL = localize(974, "Toggle Replace");
  const NLS_MATCHES_COUNT_LIMIT_TITLE = localize(975, "Only the first {0} results are highlighted, but all find operations work on the entire text.", MATCHES_LIMIT);
  const NLS_MATCHES_LOCATION = localize(976, "{0} of {1}");
  const NLS_NO_RESULTS = localize(977, "No results");
  const FIND_WIDGET_INITIAL_WIDTH = 419;
  const PART_WIDTH = 275;
  const FIND_INPUT_AREA_WIDTH = PART_WIDTH - 54;
  let MAX_MATCHES_COUNT_WIDTH = 69;
  const FIND_INPUT_AREA_HEIGHT = 33;
  const ctrlKeyMod$1 = isMacintosh ? 256 : 2048;
  class FindWidgetViewZone {
    constructor(afterLineNumber) {
      this.afterLineNumber = afterLineNumber;
      this.heightInPx = FIND_INPUT_AREA_HEIGHT;
      this.suppressMouseDown = false;
      this.domNode = document.createElement("div");
      this.domNode.className = "dock-find-viewzone";
    }
  }
  function stopPropagationForMultiLineUpwards(event, value, textarea) {
    const isMultiline = !!value.match(/\n/);
    if (textarea && isMultiline && textarea.selectionStart > 0) {
      event.stopPropagation();
      return;
    }
  }
  function stopPropagationForMultiLineDownwards(event, value, textarea) {
    const isMultiline = !!value.match(/\n/);
    if (textarea && isMultiline && textarea.selectionEnd < textarea.value.length) {
      event.stopPropagation();
      return;
    }
  }
  const _FindWidget = class _FindWidget extends Widget$1 {
    constructor(codeEditor, controller, state, contextViewProvider, keybindingService, contextKeyService, _hoverService, _findWidgetSearchHistory, _replaceWidgetHistory) {
      super();
      this._hoverService = _hoverService;
      this._findWidgetSearchHistory = _findWidgetSearchHistory;
      this._replaceWidgetHistory = _replaceWidgetHistory;
      this._cachedHeight = null;
      this._revealTimeouts = [];
      this._codeEditor = codeEditor;
      this._controller = controller;
      this._state = state;
      this._contextViewProvider = contextViewProvider;
      this._keybindingService = keybindingService;
      this._contextKeyService = contextKeyService;
      this._isVisible = false;
      this._isReplaceVisible = false;
      this._ignoreChangeEvent = false;
      this._updateHistoryDelayer = new Delayer(500);
      this._register(toDisposable(() => this._updateHistoryDelayer.cancel()));
      this._register(this._state.onFindReplaceStateChange((e) => this._onStateChanged(e)));
      this._buildDomNode();
      this._updateButtons();
      this._tryUpdateWidgetWidth();
      this._findInput.inputBox.layout();
      this._register(this._codeEditor.onDidChangeConfiguration((e) => {
        if (e.hasChanged(
          104
          /* EditorOption.readOnly */
        )) {
          if (this._codeEditor.getOption(
            104
            /* EditorOption.readOnly */
          )) {
            this._state.change({ isReplaceRevealed: false }, false);
          }
          this._updateButtons();
        }
        if (e.hasChanged(
          165
          /* EditorOption.layoutInfo */
        )) {
          this._tryUpdateWidgetWidth();
        }
        if (e.hasChanged(
          2
          /* EditorOption.accessibilitySupport */
        )) {
          this.updateAccessibilitySupport();
        }
        if (e.hasChanged(
          50
          /* EditorOption.find */
        )) {
          const supportLoop = this._codeEditor.getOption(
            50
            /* EditorOption.find */
          ).loop;
          this._state.change({ loop: supportLoop }, false);
          const addExtraSpaceOnTop = this._codeEditor.getOption(
            50
            /* EditorOption.find */
          ).addExtraSpaceOnTop;
          if (addExtraSpaceOnTop && !this._viewZone) {
            this._viewZone = new FindWidgetViewZone(0);
            this._showViewZone();
          }
          if (!addExtraSpaceOnTop && this._viewZone) {
            this._removeViewZone();
          }
        }
      }));
      this.updateAccessibilitySupport();
      this._register(this._codeEditor.onDidChangeCursorSelection(() => {
        if (this._isVisible) {
          this._updateToggleSelectionFindButton();
        }
      }));
      this._register(this._codeEditor.onDidFocusEditorWidget(async () => {
        if (this._isVisible) {
          const globalBufferTerm = await this._controller.getGlobalBufferTerm();
          if (globalBufferTerm && globalBufferTerm !== this._state.searchString) {
            this._state.change({ searchString: globalBufferTerm }, false);
            this._findInput.select();
          }
        }
      }));
      this._findInputFocused = CONTEXT_FIND_INPUT_FOCUSED.bindTo(contextKeyService);
      this._findFocusTracker = this._register(trackFocus(this._findInput.inputBox.inputElement));
      this._register(this._findFocusTracker.onDidFocus(() => {
        this._findInputFocused.set(true);
        this._updateSearchScope();
      }));
      this._register(this._findFocusTracker.onDidBlur(() => {
        this._findInputFocused.set(false);
      }));
      this._replaceInputFocused = CONTEXT_REPLACE_INPUT_FOCUSED.bindTo(contextKeyService);
      this._replaceFocusTracker = this._register(trackFocus(this._replaceInput.inputBox.inputElement));
      this._register(this._replaceFocusTracker.onDidFocus(() => {
        this._replaceInputFocused.set(true);
        this._updateSearchScope();
      }));
      this._register(this._replaceFocusTracker.onDidBlur(() => {
        this._replaceInputFocused.set(false);
      }));
      this._codeEditor.addOverlayWidget(this);
      if (this._codeEditor.getOption(
        50
        /* EditorOption.find */
      ).addExtraSpaceOnTop) {
        this._viewZone = new FindWidgetViewZone(0);
      }
      this._register(this._codeEditor.onDidChangeModel(() => {
        if (!this._isVisible) {
          return;
        }
        this._viewZoneId = void 0;
      }));
      this._register(this._codeEditor.onDidScrollChange((e) => {
        if (e.scrollTopChanged) {
          this._layoutViewZone();
          return;
        }
        setTimeout(() => {
          this._layoutViewZone();
        }, 0);
      }));
    }
    // ----- IOverlayWidget API
    getId() {
      return _FindWidget.ID;
    }
    getDomNode() {
      return this._domNode;
    }
    getPosition() {
      if (this._isVisible) {
        return {
          preference: 0
          /* OverlayWidgetPositionPreference.TOP_RIGHT_CORNER */
        };
      }
      return null;
    }
    // ----- React to state changes
    _onStateChanged(e) {
      if (e.searchString) {
        try {
          this._ignoreChangeEvent = true;
          this._findInput.setValue(this._state.searchString);
        } finally {
          this._ignoreChangeEvent = false;
        }
        this._updateButtons();
      }
      if (e.replaceString) {
        this._replaceInput.inputBox.value = this._state.replaceString;
      }
      if (e.isRevealed) {
        if (this._state.isRevealed) {
          this._reveal();
        } else {
          this._hide(true);
        }
      }
      if (e.isReplaceRevealed) {
        if (this._state.isReplaceRevealed) {
          if (!this._codeEditor.getOption(
            104
            /* EditorOption.readOnly */
          ) && !this._isReplaceVisible) {
            this._isReplaceVisible = true;
            this._replaceInput.width = getTotalWidth(this._findInput.domNode);
            this._updateButtons();
            this._replaceInput.inputBox.layout();
          }
        } else {
          if (this._isReplaceVisible) {
            this._isReplaceVisible = false;
            this._updateButtons();
          }
        }
      }
      if ((e.isRevealed || e.isReplaceRevealed) && (this._state.isRevealed || this._state.isReplaceRevealed)) {
        if (this._tryUpdateHeight()) {
          this._showViewZone();
        }
      }
      if (e.isRegex) {
        this._findInput.setRegex(this._state.isRegex);
      }
      if (e.wholeWord) {
        this._findInput.setWholeWords(this._state.wholeWord);
      }
      if (e.matchCase) {
        this._findInput.setCaseSensitive(this._state.matchCase);
      }
      if (e.preserveCase) {
        this._replaceInput.setPreserveCase(this._state.preserveCase);
      }
      if (e.searchScope) {
        if (this._state.searchScope) {
          this._toggleSelectionFind.checked = true;
        } else {
          this._toggleSelectionFind.checked = false;
        }
        this._updateToggleSelectionFindButton();
      }
      if (e.searchString || e.matchesCount || e.matchesPosition) {
        const showRedOutline = this._state.searchString.length > 0 && this._state.matchesCount === 0;
        this._domNode.classList.toggle("no-results", showRedOutline);
        this._updateMatchesCount();
        this._updateButtons();
      }
      if (e.searchString || e.currentMatch) {
        this._layoutViewZone();
      }
      if (e.updateHistory) {
        this._delayedUpdateHistory();
      }
      if (e.loop) {
        this._updateButtons();
      }
    }
    _delayedUpdateHistory() {
      this._updateHistoryDelayer.trigger(this._updateHistory.bind(this)).then(void 0, onUnexpectedError);
    }
    _updateHistory() {
      if (this._state.searchString) {
        this._findInput.inputBox.addToHistory();
      }
      if (this._state.replaceString) {
        this._replaceInput.inputBox.addToHistory();
      }
    }
    _updateMatchesCount() {
      this._matchesCount.style.minWidth = MAX_MATCHES_COUNT_WIDTH + "px";
      if (this._state.matchesCount >= MATCHES_LIMIT) {
        this._matchesCount.title = NLS_MATCHES_COUNT_LIMIT_TITLE;
      } else {
        this._matchesCount.title = "";
      }
      this._matchesCount.firstChild?.remove();
      let label;
      if (this._state.matchesCount > 0) {
        let matchesCount = String(this._state.matchesCount);
        if (this._state.matchesCount >= MATCHES_LIMIT) {
          matchesCount += "+";
        }
        let matchesPosition = String(this._state.matchesPosition);
        if (matchesPosition === "0") {
          matchesPosition = "?";
        }
        label = format(NLS_MATCHES_LOCATION, matchesPosition, matchesCount);
      } else {
        label = NLS_NO_RESULTS;
      }
      this._matchesCount.appendChild(document.createTextNode(label));
      alert(this._getAriaLabel(label, this._state.currentMatch, this._state.searchString));
      MAX_MATCHES_COUNT_WIDTH = Math.max(MAX_MATCHES_COUNT_WIDTH, this._matchesCount.clientWidth);
    }
    // ----- actions
    _getAriaLabel(label, currentMatch, searchString) {
      if (label === NLS_NO_RESULTS) {
        return searchString === "" ? localize(978, "{0} found", label) : localize(979, "{0} found for '{1}'", label, searchString);
      }
      if (currentMatch) {
        const ariaLabel = localize(980, "{0} found for '{1}', at {2}", label, searchString, currentMatch.startLineNumber + ":" + currentMatch.startColumn);
        const model = this._codeEditor.getModel();
        if (model && currentMatch.startLineNumber <= model.getLineCount() && currentMatch.startLineNumber >= 1) {
          const lineContent = model.getLineContent(currentMatch.startLineNumber);
          return `${lineContent}, ${ariaLabel}`;
        }
        return ariaLabel;
      }
      return localize(981, "{0} found for '{1}'", label, searchString);
    }
    /**
     * If 'selection find' is ON we should not disable the button (its function is to cancel 'selection find').
     * If 'selection find' is OFF we enable the button only if there is a selection.
     */
    _updateToggleSelectionFindButton() {
      const selection = this._codeEditor.getSelection();
      const isSelection = selection ? selection.startLineNumber !== selection.endLineNumber || selection.startColumn !== selection.endColumn : false;
      const isChecked = this._toggleSelectionFind.checked;
      if (this._isVisible && (isChecked || isSelection)) {
        this._toggleSelectionFind.enable();
      } else {
        this._toggleSelectionFind.disable();
      }
    }
    _updateButtons() {
      this._findInput.setEnabled(this._isVisible);
      this._replaceInput.setEnabled(this._isVisible && this._isReplaceVisible);
      this._updateToggleSelectionFindButton();
      this._closeBtn.setEnabled(this._isVisible);
      const findInputIsNonEmpty = this._state.searchString.length > 0;
      const matchesCount = this._state.matchesCount ? true : false;
      this._prevBtn.setEnabled(this._isVisible && findInputIsNonEmpty && matchesCount && this._state.canNavigateBack());
      this._nextBtn.setEnabled(this._isVisible && findInputIsNonEmpty && matchesCount && this._state.canNavigateForward());
      this._replaceBtn.setEnabled(this._isVisible && this._isReplaceVisible && findInputIsNonEmpty);
      this._replaceAllBtn.setEnabled(this._isVisible && this._isReplaceVisible && findInputIsNonEmpty);
      this._domNode.classList.toggle("replaceToggled", this._isReplaceVisible);
      this._toggleReplaceBtn.setExpanded(this._isReplaceVisible);
      const canReplace = !this._codeEditor.getOption(
        104
        /* EditorOption.readOnly */
      );
      this._toggleReplaceBtn.setEnabled(this._isVisible && canReplace);
    }
    _reveal() {
      this._revealTimeouts.forEach((e) => {
        clearTimeout(e);
      });
      this._revealTimeouts = [];
      if (!this._isVisible) {
        this._isVisible = true;
        const selection = this._codeEditor.getSelection();
        switch (this._codeEditor.getOption(
          50
          /* EditorOption.find */
        ).autoFindInSelection) {
          case "always":
            this._toggleSelectionFind.checked = true;
            break;
          case "never":
            this._toggleSelectionFind.checked = false;
            break;
          case "multiline": {
            const isSelectionMultipleLine = !!selection && selection.startLineNumber !== selection.endLineNumber;
            this._toggleSelectionFind.checked = isSelectionMultipleLine;
            break;
          }
        }
        this._tryUpdateWidgetWidth();
        this._updateButtons();
        this._revealTimeouts.push(setTimeout(() => {
          this._domNode.classList.add("visible");
          this._domNode.setAttribute("aria-hidden", "false");
        }, 0));
        this._revealTimeouts.push(setTimeout(() => {
          this._findInput.validate();
        }, 200));
        this._codeEditor.layoutOverlayWidget(this);
        let adjustEditorScrollTop = true;
        if (this._codeEditor.getOption(
          50
          /* EditorOption.find */
        ).seedSearchStringFromSelection && selection) {
          const domNode = this._codeEditor.getDomNode();
          if (domNode) {
            const editorCoords = getDomNodePagePosition(domNode);
            const startCoords = this._codeEditor.getScrolledVisiblePosition(selection.getStartPosition());
            const startLeft = editorCoords.left + (startCoords ? startCoords.left : 0);
            const startTop = startCoords ? startCoords.top : 0;
            if (this._viewZone && startTop < this._viewZone.heightInPx) {
              if (selection.endLineNumber > selection.startLineNumber) {
                adjustEditorScrollTop = false;
              }
              const leftOfFindWidget = getTopLeftOffset(this._domNode).left;
              if (startLeft > leftOfFindWidget) {
                adjustEditorScrollTop = false;
              }
              const endCoords = this._codeEditor.getScrolledVisiblePosition(selection.getEndPosition());
              const endLeft = editorCoords.left + (endCoords ? endCoords.left : 0);
              if (endLeft > leftOfFindWidget) {
                adjustEditorScrollTop = false;
              }
            }
          }
        }
        this._showViewZone(adjustEditorScrollTop);
      }
    }
    _hide(focusTheEditor) {
      this._revealTimeouts.forEach((e) => {
        clearTimeout(e);
      });
      this._revealTimeouts = [];
      if (this._isVisible) {
        this._isVisible = false;
        this._updateButtons();
        this._domNode.classList.remove("visible");
        this._domNode.setAttribute("aria-hidden", "true");
        this._findInput.clearMessage();
        if (focusTheEditor) {
          this._codeEditor.focus();
        }
        this._codeEditor.layoutOverlayWidget(this);
        this._removeViewZone();
      }
    }
    _layoutViewZone(targetScrollTop) {
      const addExtraSpaceOnTop = this._codeEditor.getOption(
        50
        /* EditorOption.find */
      ).addExtraSpaceOnTop;
      if (!addExtraSpaceOnTop) {
        this._removeViewZone();
        return;
      }
      if (!this._isVisible) {
        return;
      }
      const viewZone = this._viewZone;
      if (this._viewZoneId !== void 0 || !viewZone) {
        return;
      }
      this._codeEditor.changeViewZones((accessor) => {
        viewZone.heightInPx = this._getHeight();
        this._viewZoneId = accessor.addZone(viewZone);
        this._codeEditor.setScrollTop(targetScrollTop || this._codeEditor.getScrollTop() + viewZone.heightInPx);
      });
    }
    _showViewZone(adjustScroll = true) {
      if (!this._isVisible) {
        return;
      }
      const addExtraSpaceOnTop = this._codeEditor.getOption(
        50
        /* EditorOption.find */
      ).addExtraSpaceOnTop;
      if (!addExtraSpaceOnTop) {
        return;
      }
      if (this._viewZone === void 0) {
        this._viewZone = new FindWidgetViewZone(0);
      }
      const viewZone = this._viewZone;
      this._codeEditor.changeViewZones((accessor) => {
        if (this._viewZoneId !== void 0) {
          const newHeight = this._getHeight();
          if (newHeight === viewZone.heightInPx) {
            return;
          }
          const scrollAdjustment = newHeight - viewZone.heightInPx;
          viewZone.heightInPx = newHeight;
          accessor.layoutZone(this._viewZoneId);
          if (adjustScroll) {
            this._codeEditor.setScrollTop(this._codeEditor.getScrollTop() + scrollAdjustment);
          }
          return;
        } else {
          let scrollAdjustment = this._getHeight();
          scrollAdjustment -= this._codeEditor.getOption(
            96
            /* EditorOption.padding */
          ).top;
          if (scrollAdjustment <= 0) {
            return;
          }
          viewZone.heightInPx = scrollAdjustment;
          this._viewZoneId = accessor.addZone(viewZone);
          if (adjustScroll) {
            this._codeEditor.setScrollTop(this._codeEditor.getScrollTop() + scrollAdjustment);
          }
        }
      });
    }
    _removeViewZone() {
      this._codeEditor.changeViewZones((accessor) => {
        if (this._viewZoneId !== void 0) {
          accessor.removeZone(this._viewZoneId);
          this._viewZoneId = void 0;
          if (this._viewZone) {
            this._codeEditor.setScrollTop(this._codeEditor.getScrollTop() - this._viewZone.heightInPx);
            this._viewZone = void 0;
          }
        }
      });
    }
    _tryUpdateWidgetWidth() {
      if (!this._isVisible) {
        return;
      }
      if (!this._domNode.isConnected) {
        return;
      }
      const layoutInfo = this._codeEditor.getLayoutInfo();
      const editorContentWidth = layoutInfo.contentWidth;
      if (editorContentWidth <= 0) {
        this._domNode.classList.add("hiddenEditor");
        return;
      } else if (this._domNode.classList.contains("hiddenEditor")) {
        this._domNode.classList.remove("hiddenEditor");
      }
      const editorWidth = layoutInfo.width;
      const minimapWidth = layoutInfo.minimap.minimapWidth;
      let collapsedFindWidget = false;
      let reducedFindWidget = false;
      let narrowFindWidget = false;
      if (this._resized) {
        const widgetWidth = getTotalWidth(this._domNode);
        if (widgetWidth > FIND_WIDGET_INITIAL_WIDTH) {
          this._domNode.style.maxWidth = `${editorWidth - 28 - minimapWidth - 15}px`;
          this._replaceInput.width = getTotalWidth(this._findInput.domNode);
          return;
        }
      }
      if (FIND_WIDGET_INITIAL_WIDTH + 28 + minimapWidth >= editorWidth) {
        reducedFindWidget = true;
      }
      if (FIND_WIDGET_INITIAL_WIDTH + 28 + minimapWidth - MAX_MATCHES_COUNT_WIDTH >= editorWidth) {
        narrowFindWidget = true;
      }
      if (FIND_WIDGET_INITIAL_WIDTH + 28 + minimapWidth - MAX_MATCHES_COUNT_WIDTH >= editorWidth + 50) {
        collapsedFindWidget = true;
      }
      this._domNode.classList.toggle("collapsed-find-widget", collapsedFindWidget);
      this._domNode.classList.toggle("narrow-find-widget", narrowFindWidget);
      this._domNode.classList.toggle("reduced-find-widget", reducedFindWidget);
      if (!narrowFindWidget && !collapsedFindWidget) {
        this._domNode.style.maxWidth = `${editorWidth - 28 - minimapWidth - 15}px`;
      }
      this._findInput.layout({ collapsedFindWidget, narrowFindWidget, reducedFindWidget });
      if (this._resized) {
        const findInputWidth = this._findInput.inputBox.element.clientWidth;
        if (findInputWidth > 0) {
          this._replaceInput.width = findInputWidth;
        }
      } else if (this._isReplaceVisible) {
        this._replaceInput.width = getTotalWidth(this._findInput.domNode);
      }
    }
    _getHeight() {
      let totalheight = 0;
      totalheight += 4;
      totalheight += this._findInput.inputBox.height + 2;
      if (this._isReplaceVisible) {
        totalheight += 4;
        totalheight += this._replaceInput.inputBox.height + 2;
      }
      totalheight += 4;
      return totalheight;
    }
    _tryUpdateHeight() {
      const totalHeight = this._getHeight();
      if (this._cachedHeight !== null && this._cachedHeight === totalHeight) {
        return false;
      }
      this._cachedHeight = totalHeight;
      this._domNode.style.height = `${totalHeight}px`;
      return true;
    }
    // ----- Public
    focusFindInput() {
      this._findInput.select();
      this._findInput.focus();
    }
    focusReplaceInput() {
      this._replaceInput.select();
      this._replaceInput.focus();
    }
    highlightFindOptions() {
      this._findInput.highlightFindOptions();
    }
    _updateSearchScope() {
      if (!this._codeEditor.hasModel()) {
        return;
      }
      if (this._toggleSelectionFind.checked) {
        const selections = this._codeEditor.getSelections();
        selections.map((selection) => {
          if (selection.endColumn === 1 && selection.endLineNumber > selection.startLineNumber) {
            selection = selection.setEndPosition(selection.endLineNumber - 1, this._codeEditor.getModel().getLineMaxColumn(selection.endLineNumber - 1));
          }
          const currentMatch = this._state.currentMatch;
          if (selection.startLineNumber !== selection.endLineNumber) {
            if (!Range$2.equalsRange(selection, currentMatch)) {
              return selection;
            }
          }
          return null;
        }).filter((element) => !!element);
        if (selections.length) {
          this._state.change({ searchScope: selections }, true);
        }
      }
    }
    _onFindInputMouseDown(e) {
      if (e.middleButton) {
        e.stopPropagation();
      }
    }
    _onFindInputKeyDown(e) {
      if (e.equals(
        ctrlKeyMod$1 | 3
        /* KeyCode.Enter */
      )) {
        if (this._keybindingService.dispatchEvent(e, e.target)) {
          e.preventDefault();
          return;
        } else {
          this._findInput.inputBox.insertAtCursor("\n");
          e.preventDefault();
          return;
        }
      }
      if (e.equals(
        2
        /* KeyCode.Tab */
      )) {
        if (this._isReplaceVisible) {
          this._replaceInput.focus();
        } else {
          this._findInput.focusOnCaseSensitive();
        }
        e.preventDefault();
        return;
      }
      if (e.equals(
        2048 | 18
        /* KeyCode.DownArrow */
      )) {
        this._codeEditor.focus();
        e.preventDefault();
        return;
      }
      if (e.equals(
        16
        /* KeyCode.UpArrow */
      )) {
        return stopPropagationForMultiLineUpwards(e, this._findInput.getValue(), this._findInput.domNode.querySelector("textarea"));
      }
      if (e.equals(
        18
        /* KeyCode.DownArrow */
      )) {
        return stopPropagationForMultiLineDownwards(e, this._findInput.getValue(), this._findInput.domNode.querySelector("textarea"));
      }
    }
    _onReplaceInputKeyDown(e) {
      if (e.equals(
        ctrlKeyMod$1 | 3
        /* KeyCode.Enter */
      )) {
        if (this._keybindingService.dispatchEvent(e, e.target)) {
          e.preventDefault();
          return;
        } else {
          this._replaceInput.inputBox.insertAtCursor("\n");
          e.preventDefault();
          return;
        }
      }
      if (e.equals(
        2
        /* KeyCode.Tab */
      )) {
        this._findInput.focusOnCaseSensitive();
        e.preventDefault();
        return;
      }
      if (e.equals(
        1024 | 2
        /* KeyCode.Tab */
      )) {
        this._findInput.focus();
        e.preventDefault();
        return;
      }
      if (e.equals(
        2048 | 18
        /* KeyCode.DownArrow */
      )) {
        this._codeEditor.focus();
        e.preventDefault();
        return;
      }
      if (e.equals(
        16
        /* KeyCode.UpArrow */
      )) {
        return stopPropagationForMultiLineUpwards(e, this._replaceInput.inputBox.value, this._replaceInput.inputBox.element.querySelector("textarea"));
      }
      if (e.equals(
        18
        /* KeyCode.DownArrow */
      )) {
        return stopPropagationForMultiLineDownwards(e, this._replaceInput.inputBox.value, this._replaceInput.inputBox.element.querySelector("textarea"));
      }
    }
    // ----- sash
    getVerticalSashLeft(_sash) {
      return 0;
    }
    // ----- initialization
    _keybindingLabelFor(actionId) {
      const kb = this._keybindingService.lookupKeybinding(actionId);
      if (!kb) {
        return "";
      }
      return ` (${kb.getLabel()})`;
    }
    _buildDomNode() {
      const flexibleHeight = true;
      const flexibleWidth = true;
      const findSearchHistoryConfig = this._codeEditor.getOption(
        50
        /* EditorOption.find */
      ).history;
      const replaceHistoryConfig = this._codeEditor.getOption(
        50
        /* EditorOption.find */
      ).replaceHistory;
      this._findInput = this._register(new ContextScopedFindInput(null, this._contextViewProvider, {
        width: FIND_INPUT_AREA_WIDTH,
        label: NLS_FIND_INPUT_LABEL,
        placeholder: NLS_FIND_INPUT_PLACEHOLDER,
        appendCaseSensitiveLabel: this._keybindingLabelFor(FIND_IDS.ToggleCaseSensitiveCommand),
        appendWholeWordsLabel: this._keybindingLabelFor(FIND_IDS.ToggleWholeWordCommand),
        appendRegexLabel: this._keybindingLabelFor(FIND_IDS.ToggleRegexCommand),
        validation: (value) => {
          if (value.length === 0 || !this._findInput.getRegex()) {
            return null;
          }
          try {
            new RegExp(value, "gu");
            return null;
          } catch (e) {
            return { content: e.message };
          }
        },
        flexibleHeight,
        flexibleWidth,
        flexibleMaxHeight: 118,
        showCommonFindToggles: true,
        showHistoryHint: () => showHistoryKeybindingHint(this._keybindingService),
        inputBoxStyles: defaultInputBoxStyles,
        toggleStyles: defaultToggleStyles,
        history: findSearchHistoryConfig === "workspace" ? this._findWidgetSearchHistory : /* @__PURE__ */ new Set([])
      }, this._contextKeyService));
      this._findInput.setRegex(!!this._state.isRegex);
      this._findInput.setCaseSensitive(!!this._state.matchCase);
      this._findInput.setWholeWords(!!this._state.wholeWord);
      this._register(this._findInput.onKeyDown((e) => {
        if (e.equals(
          3
          /* KeyCode.Enter */
        ) && !this._codeEditor.getOption(
          50
          /* EditorOption.find */
        ).findOnType) {
          this._state.change({ searchString: this._findInput.getValue() }, true);
        }
        this._onFindInputKeyDown(e);
      }));
      this._register(this._findInput.inputBox.onDidChange(() => {
        if (this._ignoreChangeEvent || !this._codeEditor.getOption(
          50
          /* EditorOption.find */
        ).findOnType) {
          return;
        }
        this._state.change({ searchString: this._findInput.getValue() }, true);
      }));
      this._register(this._findInput.onDidOptionChange(() => {
        this._state.change({
          isRegex: this._findInput.getRegex(),
          wholeWord: this._findInput.getWholeWords(),
          matchCase: this._findInput.getCaseSensitive()
        }, true);
      }));
      this._register(this._findInput.onCaseSensitiveKeyDown((e) => {
        if (e.equals(
          1024 | 2
          /* KeyCode.Tab */
        )) {
          if (this._isReplaceVisible) {
            this._replaceInput.focus();
            e.preventDefault();
          }
        }
      }));
      this._register(this._findInput.onRegexKeyDown((e) => {
        if (e.equals(
          2
          /* KeyCode.Tab */
        )) {
          if (this._isReplaceVisible) {
            this._replaceInput.focusOnPreserve();
            e.preventDefault();
          }
        }
      }));
      this._register(this._findInput.inputBox.onDidHeightChange((e) => {
        if (this._tryUpdateHeight()) {
          this._showViewZone();
        }
      }));
      if (isLinux) {
        this._register(this._findInput.onMouseDown((e) => this._onFindInputMouseDown(e)));
      }
      this._matchesCount = document.createElement("div");
      this._matchesCount.className = "matchesCount";
      this._updateMatchesCount();
      const hoverLifecycleOptions = { groupId: "find-widget" };
      this._prevBtn = this._register(new SimpleButton({
        label: NLS_PREVIOUS_MATCH_BTN_LABEL + this._keybindingLabelFor(FIND_IDS.PreviousMatchFindAction),
        icon: findPreviousMatchIcon,
        hoverLifecycleOptions,
        onTrigger: () => {
          assertReturnsDefined(this._codeEditor.getAction(FIND_IDS.PreviousMatchFindAction)).run().then(void 0, onUnexpectedError);
        }
      }, this._hoverService));
      this._nextBtn = this._register(new SimpleButton({
        label: NLS_NEXT_MATCH_BTN_LABEL + this._keybindingLabelFor(FIND_IDS.NextMatchFindAction),
        icon: findNextMatchIcon,
        hoverLifecycleOptions,
        onTrigger: () => {
          assertReturnsDefined(this._codeEditor.getAction(FIND_IDS.NextMatchFindAction)).run().then(void 0, onUnexpectedError);
        }
      }, this._hoverService));
      const findPart = document.createElement("div");
      findPart.className = "find-part";
      findPart.appendChild(this._findInput.domNode);
      const actionsContainer = document.createElement("div");
      actionsContainer.className = "find-actions";
      findPart.appendChild(actionsContainer);
      actionsContainer.appendChild(this._matchesCount);
      actionsContainer.appendChild(this._prevBtn.domNode);
      actionsContainer.appendChild(this._nextBtn.domNode);
      this._toggleSelectionFind = this._register(new Toggle({
        icon: findSelectionIcon,
        title: NLS_TOGGLE_SELECTION_FIND_TITLE + this._keybindingLabelFor(FIND_IDS.ToggleSearchScopeCommand),
        isChecked: false,
        hoverLifecycleOptions,
        inputActiveOptionBackground: asCssVariable(inputActiveOptionBackground),
        inputActiveOptionBorder: asCssVariable(inputActiveOptionBorder),
        inputActiveOptionForeground: asCssVariable(inputActiveOptionForeground)
      }));
      this._register(this._toggleSelectionFind.onChange(() => {
        if (this._toggleSelectionFind.checked) {
          if (this._codeEditor.hasModel()) {
            let selections = this._codeEditor.getSelections();
            selections = selections.map((selection) => {
              if (selection.endColumn === 1 && selection.endLineNumber > selection.startLineNumber) {
                selection = selection.setEndPosition(selection.endLineNumber - 1, this._codeEditor.getModel().getLineMaxColumn(selection.endLineNumber - 1));
              }
              if (!selection.isEmpty()) {
                return selection;
              }
              return null;
            }).filter((element) => !!element);
            if (selections.length) {
              this._state.change({ searchScope: selections }, true);
            }
          }
        } else {
          this._state.change({ searchScope: null }, true);
        }
      }));
      actionsContainer.appendChild(this._toggleSelectionFind.domNode);
      this._closeBtn = this._register(new SimpleButton({
        label: NLS_CLOSE_BTN_LABEL + this._keybindingLabelFor(FIND_IDS.CloseFindWidgetCommand),
        icon: widgetClose,
        hoverLifecycleOptions,
        onTrigger: () => {
          this._state.change({ isRevealed: false, searchScope: null }, false);
        },
        onKeyDown: (e) => {
          if (e.equals(
            2
            /* KeyCode.Tab */
          )) {
            if (this._isReplaceVisible) {
              if (this._replaceBtn.isEnabled()) {
                this._replaceBtn.focus();
              } else {
                this._codeEditor.focus();
              }
              e.preventDefault();
            }
          }
        }
      }, this._hoverService));
      this._replaceInput = this._register(new ContextScopedReplaceInput(null, void 0, {
        label: NLS_REPLACE_INPUT_LABEL,
        placeholder: NLS_REPLACE_INPUT_PLACEHOLDER,
        appendPreserveCaseLabel: this._keybindingLabelFor(FIND_IDS.TogglePreserveCaseCommand),
        history: replaceHistoryConfig === "workspace" ? this._replaceWidgetHistory : /* @__PURE__ */ new Set([]),
        flexibleHeight,
        flexibleWidth,
        flexibleMaxHeight: 118,
        showHistoryHint: () => showHistoryKeybindingHint(this._keybindingService),
        inputBoxStyles: defaultInputBoxStyles,
        toggleStyles: defaultToggleStyles,
        hoverLifecycleOptions
      }, this._contextKeyService, true));
      this._replaceInput.setPreserveCase(!!this._state.preserveCase);
      this._register(this._replaceInput.onKeyDown((e) => this._onReplaceInputKeyDown(e)));
      this._register(this._replaceInput.inputBox.onDidChange(() => {
        this._state.change({ replaceString: this._replaceInput.inputBox.value }, false);
      }));
      this._register(this._replaceInput.inputBox.onDidHeightChange((e) => {
        if (this._isReplaceVisible && this._tryUpdateHeight()) {
          this._showViewZone();
        }
      }));
      this._register(this._replaceInput.onDidOptionChange(() => {
        this._state.change({
          preserveCase: this._replaceInput.getPreserveCase()
        }, true);
      }));
      this._register(this._replaceInput.onPreserveCaseKeyDown((e) => {
        if (e.equals(
          2
          /* KeyCode.Tab */
        )) {
          if (this._prevBtn.isEnabled()) {
            this._prevBtn.focus();
          } else if (this._nextBtn.isEnabled()) {
            this._nextBtn.focus();
          } else if (this._toggleSelectionFind.enabled) {
            this._toggleSelectionFind.focus();
          } else if (this._closeBtn.isEnabled()) {
            this._closeBtn.focus();
          }
          e.preventDefault();
        }
      }));
      this._replaceBtn = this._register(new SimpleButton({
        label: NLS_REPLACE_BTN_LABEL + this._keybindingLabelFor(FIND_IDS.ReplaceOneAction),
        icon: findReplaceIcon,
        hoverLifecycleOptions,
        onTrigger: () => {
          this._controller.replace();
        },
        onKeyDown: (e) => {
          if (e.equals(
            1024 | 2
            /* KeyCode.Tab */
          )) {
            this._closeBtn.focus();
            e.preventDefault();
          }
        }
      }, this._hoverService));
      this._replaceAllBtn = this._register(new SimpleButton({
        label: NLS_REPLACE_ALL_BTN_LABEL + this._keybindingLabelFor(FIND_IDS.ReplaceAllAction),
        icon: findReplaceAllIcon,
        hoverLifecycleOptions,
        onTrigger: () => {
          this._controller.replaceAll();
        }
      }, this._hoverService));
      const replacePart = document.createElement("div");
      replacePart.className = "replace-part";
      replacePart.appendChild(this._replaceInput.domNode);
      const replaceActionsContainer = document.createElement("div");
      replaceActionsContainer.className = "replace-actions";
      replacePart.appendChild(replaceActionsContainer);
      replaceActionsContainer.appendChild(this._replaceBtn.domNode);
      replaceActionsContainer.appendChild(this._replaceAllBtn.domNode);
      this._toggleReplaceBtn = this._register(new SimpleButton({
        label: NLS_TOGGLE_REPLACE_MODE_BTN_LABEL,
        className: "codicon toggle left",
        onTrigger: () => {
          this._state.change({ isReplaceRevealed: !this._isReplaceVisible }, false);
          if (this._isReplaceVisible) {
            this._replaceInput.width = getTotalWidth(this._findInput.domNode);
            this._replaceInput.inputBox.layout();
          }
          this._showViewZone();
        }
      }, this._hoverService));
      this._toggleReplaceBtn.setExpanded(this._isReplaceVisible);
      this._domNode = document.createElement("div");
      this._domNode.className = "editor-widget find-widget";
      this._domNode.setAttribute("aria-hidden", "true");
      this._domNode.ariaLabel = NLS_FIND_DIALOG_LABEL;
      this._domNode.role = "dialog";
      this._domNode.style.width = `${FIND_WIDGET_INITIAL_WIDTH}px`;
      this._domNode.appendChild(this._toggleReplaceBtn.domNode);
      this._domNode.appendChild(findPart);
      this._domNode.appendChild(this._closeBtn.domNode);
      this._domNode.appendChild(replacePart);
      this._resizeSash = this._register(new Sash(this._domNode, this, { orientation: 0, size: 2 }));
      this._resized = false;
      let originalWidth = FIND_WIDGET_INITIAL_WIDTH;
      this._register(this._resizeSash.onDidStart(() => {
        originalWidth = getTotalWidth(this._domNode);
      }));
      this._register(this._resizeSash.onDidChange((evt) => {
        this._resized = true;
        const width2 = originalWidth + evt.startX - evt.currentX;
        if (width2 < FIND_WIDGET_INITIAL_WIDTH) {
          return;
        }
        const maxWidth = parseFloat(getComputedStyle(this._domNode).maxWidth) || 0;
        if (width2 > maxWidth) {
          return;
        }
        this._domNode.style.width = `${width2}px`;
        if (this._isReplaceVisible) {
          this._replaceInput.width = getTotalWidth(this._findInput.domNode);
        }
        this._findInput.inputBox.layout();
        this._tryUpdateHeight();
      }));
      this._register(this._resizeSash.onDidReset(() => {
        const currentWidth = getTotalWidth(this._domNode);
        if (currentWidth < FIND_WIDGET_INITIAL_WIDTH) {
          return;
        }
        let width2 = FIND_WIDGET_INITIAL_WIDTH;
        if (!this._resized || currentWidth === FIND_WIDGET_INITIAL_WIDTH) {
          const layoutInfo = this._codeEditor.getLayoutInfo();
          width2 = layoutInfo.width - 28 - layoutInfo.minimap.minimapWidth - 15;
          this._resized = true;
        }
        this._domNode.style.width = `${width2}px`;
        if (this._isReplaceVisible) {
          this._replaceInput.width = getTotalWidth(this._findInput.domNode);
        }
        this._findInput.inputBox.layout();
      }));
    }
    updateAccessibilitySupport() {
      const value = this._codeEditor.getOption(
        2
        /* EditorOption.accessibilitySupport */
      );
      this._findInput.setFocusInputOnOptionClick(
        value !== 2
        /* AccessibilitySupport.Enabled */
      );
    }
    getViewState() {
      let widgetViewZoneVisible = false;
      if (this._viewZone && this._viewZoneId) {
        widgetViewZoneVisible = this._viewZone.heightInPx > this._codeEditor.getScrollTop();
      }
      return {
        widgetViewZoneVisible,
        scrollTop: this._codeEditor.getScrollTop()
      };
    }
    setViewState(state) {
      if (!state) {
        return;
      }
      if (state.widgetViewZoneVisible) {
        this._layoutViewZone(state.scrollTop);
      }
    }
  };
  _FindWidget.ID = "editor.contrib.findWidget";
  let FindWidget = _FindWidget;
  class SimpleButton extends Widget$1 {
    constructor(opts, hoverService) {
      super();
      this._opts = opts;
      let className2 = "button";
      if (this._opts.className) {
        className2 = className2 + " " + this._opts.className;
      }
      if (this._opts.icon) {
        className2 = className2 + " " + ThemeIcon.asClassName(this._opts.icon);
      }
      this._domNode = document.createElement("div");
      this._domNode.tabIndex = 0;
      this._domNode.className = className2;
      this._domNode.setAttribute("role", "button");
      this._domNode.setAttribute("aria-label", this._opts.label);
      this._register(hoverService.setupDelayedHover(this._domNode, {
        content: this._opts.label,
        style: 1
      }, opts.hoverLifecycleOptions));
      this.onclick(this._domNode, (e) => {
        this._opts.onTrigger();
        e.preventDefault();
      });
      this.onkeydown(this._domNode, (e) => {
        if (e.equals(
          10
          /* KeyCode.Space */
        ) || e.equals(
          3
          /* KeyCode.Enter */
        )) {
          this._opts.onTrigger();
          e.preventDefault();
          return;
        }
        this._opts.onKeyDown?.(e);
      });
    }
    get domNode() {
      return this._domNode;
    }
    isEnabled() {
      return this._domNode.tabIndex >= 0;
    }
    focus() {
      this._domNode.focus();
    }
    setEnabled(enabled) {
      this._domNode.classList.toggle("disabled", !enabled);
      this._domNode.setAttribute("aria-disabled", String(!enabled));
      this._domNode.tabIndex = enabled ? 0 : -1;
    }
    setExpanded(expanded2) {
      this._domNode.setAttribute("aria-expanded", String(!!expanded2));
      if (expanded2) {
        this._domNode.classList.remove(...ThemeIcon.asClassNameArray(findCollapsedIcon));
        this._domNode.classList.add(...ThemeIcon.asClassNameArray(findExpandedIcon));
      } else {
        this._domNode.classList.remove(...ThemeIcon.asClassNameArray(findExpandedIcon));
        this._domNode.classList.add(...ThemeIcon.asClassNameArray(findCollapsedIcon));
      }
    }
  }
  registerThemingParticipant((theme, collector) => {
    const findMatchHighlightBorder = theme.getColor(editorFindMatchHighlightBorder);
    if (findMatchHighlightBorder) {
      collector.addRule(`.monaco-editor .findMatch { border: 1px ${isHighContrast(theme.type) ? "dotted" : "solid"} ${findMatchHighlightBorder}; box-sizing: border-box; }`);
    }
    const findRangeHighlightBorder = theme.getColor(editorFindRangeHighlightBorder);
    if (findRangeHighlightBorder) {
      collector.addRule(`.monaco-editor .findScope { border: 1px ${isHighContrast(theme.type) ? "dashed" : "solid"} ${findRangeHighlightBorder}; }`);
    }
    const hcBorder = theme.getColor(contrastBorder);
    if (hcBorder) {
      collector.addRule(`.monaco-editor .find-widget { border: 1px solid ${hcBorder}; }`);
    }
    const findMatchForeground = theme.getColor(editorFindMatchForeground);
    if (findMatchForeground) {
      collector.addRule(`.monaco-editor .findMatchInline { color: ${findMatchForeground}; }`);
    }
    const findMatchHighlightForeground = theme.getColor(editorFindMatchHighlightForeground);
    if (findMatchHighlightForeground) {
      collector.addRule(`.monaco-editor .currentFindMatchInline { color: ${findMatchHighlightForeground}; }`);
    }
  });
  var __decorate$27 = 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$25 = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  let HoverCopyButton = class HoverCopyButton extends Disposable {
    constructor(_container, _getContent, _clipboardService, _hoverService) {
      super();
      this._container = _container;
      this._getContent = _getContent;
      this._clipboardService = _clipboardService;
      this._hoverService = _hoverService;
      this._container.classList.add("hover-row-with-copy");
      this._button = this._register(new SimpleButton({
        label: localize(1128, "Copy"),
        icon: Codicon.copy,
        onTrigger: () => this._copyContent(),
        className: "hover-copy-button"
      }, this._hoverService));
      this._container.appendChild(this._button.domNode);
    }
    async _copyContent() {
      const content = this._getContent();
      if (content) {
        await this._clipboardService.writeText(content);
        status(localize(1129, "Copied to clipboard"));
      }
    }
  };
  HoverCopyButton = __decorate$27([
    __param$25(2, IClipboardService),
    __param$25(3, IHoverService)
  ], HoverCopyButton);
  class HoverProviderResult {
    constructor(provider, hover, ordinal) {
      this.provider = provider;
      this.hover = hover;
      this.ordinal = ordinal;
    }
  }
  async function executeProvider(provider, ordinal, model, position, token) {
    const result = await Promise.resolve(provider.provideHover(model, position, token)).catch(onUnexpectedExternalError);
    if (!result || !isValid(result)) {
      return void 0;
    }
    return new HoverProviderResult(provider, result, ordinal);
  }
  function getHoverProviderResultsAsAsyncIterable(registry, model, position, token, recursive = false) {
    const providers = registry.ordered(model, recursive);
    const promises = providers.map((provider, index) => executeProvider(provider, index, model, position, token));
    return AsyncIterableProducer.fromPromisesResolveOrder(promises).coalesce();
  }
  async function getHoversPromise(registry, model, position, token, recursive = false) {
    const out = [];
    for await (const item of getHoverProviderResultsAsAsyncIterable(registry, model, position, token, recursive)) {
      out.push(item.hover);
    }
    return out;
  }
  registerModelAndPositionCommand("_executeHoverProvider", (accessor, model, position) => {
    const languageFeaturesService = accessor.get(ILanguageFeaturesService);
    return getHoversPromise(languageFeaturesService.hoverProvider, model, position, CancellationToken.None);
  });
  registerModelAndPositionCommand("_executeHoverProvider_recursive", (accessor, model, position) => {
    const languageFeaturesService = accessor.get(ILanguageFeaturesService);
    return getHoversPromise(languageFeaturesService.hoverProvider, model, position, CancellationToken.None, true);
  });
  function isValid(result) {
    const hasRange = typeof result.range !== "undefined";
    const hasHtmlContent = typeof result.contents !== "undefined" && result.contents && result.contents.length > 0;
    return hasRange && hasHtmlContent;
  }
  var __decorate$26 = 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$24 = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  const $$f = $$l;
  const increaseHoverVerbosityIcon = registerIcon("hover-increase-verbosity", Codicon.add, localize(1130, "Icon for increaseing hover verbosity."));
  const decreaseHoverVerbosityIcon = registerIcon("hover-decrease-verbosity", Codicon.remove, localize(1131, "Icon for decreasing hover verbosity."));
  class MarkdownHover {
    constructor(owner, range2, contents, isBeforeContent, ordinal, source = void 0) {
      this.owner = owner;
      this.range = range2;
      this.contents = contents;
      this.isBeforeContent = isBeforeContent;
      this.ordinal = ordinal;
      this.source = source;
    }
    isValidForHoverAnchor(anchor) {
      return anchor.type === 1 && this.range.startColumn <= anchor.range.startColumn && this.range.endColumn >= anchor.range.endColumn;
    }
  }
  class HoverSource {
    constructor(hover, hoverProvider, hoverPosition) {
      this.hover = hover;
      this.hoverProvider = hoverProvider;
      this.hoverPosition = hoverPosition;
    }
    supportsVerbosityAction(hoverVerbosityAction) {
      switch (hoverVerbosityAction) {
        case HoverVerbosityAction$1.Increase:
          return this.hover.canIncreaseVerbosity ?? false;
        case HoverVerbosityAction$1.Decrease:
          return this.hover.canDecreaseVerbosity ?? false;
      }
    }
  }
  let MarkdownHoverParticipant = class MarkdownHoverParticipant {
    constructor(_editor, _markdownRendererService, _configurationService, _languageFeaturesService, _keybindingService, _hoverService, _commandService) {
      this._editor = _editor;
      this._markdownRendererService = _markdownRendererService;
      this._configurationService = _configurationService;
      this._languageFeaturesService = _languageFeaturesService;
      this._keybindingService = _keybindingService;
      this._hoverService = _hoverService;
      this._commandService = _commandService;
      this.hoverOrdinal = 3;
    }
    createLoadingMessage(anchor) {
      return new MarkdownHover(this, anchor.range, [new MarkdownString().appendText(localize(1132, "Loading..."))], false, 2e3);
    }
    computeSync(anchor, lineDecorations) {
      if (!this._editor.hasModel() || anchor.type !== 1) {
        return [];
      }
      const model = this._editor.getModel();
      const lineNumber = anchor.range.startLineNumber;
      const maxColumn = model.getLineMaxColumn(lineNumber);
      const result = [];
      let index = 1e3;
      const lineLength = model.getLineLength(lineNumber);
      const languageId = model.getLanguageIdAtPosition(anchor.range.startLineNumber, anchor.range.startColumn);
      const stopRenderingLineAfter = this._editor.getOption(
        133
        /* EditorOption.stopRenderingLineAfter */
      );
      const maxTokenizationLineLength = this._configurationService.getValue("editor.maxTokenizationLineLength", {
        overrideIdentifier: languageId
      });
      let stopRenderingMessage = false;
      if (stopRenderingLineAfter >= 0 && lineLength > stopRenderingLineAfter && anchor.range.startColumn >= stopRenderingLineAfter) {
        stopRenderingMessage = true;
        result.push(new MarkdownHover(this, anchor.range, [{
          value: localize(1133, "Rendering paused for long line for performance reasons. This can be configured via `editor.stopRenderingLineAfter`.")
        }], false, index++));
      }
      if (!stopRenderingMessage && typeof maxTokenizationLineLength === "number" && lineLength >= maxTokenizationLineLength) {
        result.push(new MarkdownHover(this, anchor.range, [{
          value: localize(1134, "Tokenization is skipped for long lines for performance reasons. This can be configured via `editor.maxTokenizationLineLength`.")
        }], false, index++));
      }
      let isBeforeContent = false;
      for (const d of lineDecorations) {
        const startColumn = d.range.startLineNumber === lineNumber ? d.range.startColumn : 1;
        const endColumn = d.range.endLineNumber === lineNumber ? d.range.endColumn : maxColumn;
        const hoverMessage = d.options.hoverMessage;
        if (!hoverMessage || isEmptyMarkdownString(hoverMessage)) {
          continue;
        }
        if (d.options.beforeContentClassName) {
          isBeforeContent = true;
        }
        const range2 = new Range$2(anchor.range.startLineNumber, startColumn, anchor.range.startLineNumber, endColumn);
        result.push(new MarkdownHover(this, range2, asArray(hoverMessage), isBeforeContent, index++));
      }
      return result;
    }
    computeAsync(anchor, lineDecorations, source, token) {
      if (!this._editor.hasModel() || anchor.type !== 1) {
        return AsyncIterableProducer.EMPTY;
      }
      const model = this._editor.getModel();
      const hoverProviderRegistry = this._languageFeaturesService.hoverProvider;
      if (!hoverProviderRegistry.has(model)) {
        return AsyncIterableProducer.EMPTY;
      }
      return this._getMarkdownHovers(hoverProviderRegistry, model, anchor, token);
    }
    async *_getMarkdownHovers(hoverProviderRegistry, model, anchor, token) {
      const position = anchor.range.getStartPosition();
      const hoverProviderResults = getHoverProviderResultsAsAsyncIterable(hoverProviderRegistry, model, position, token);
      for await (const item of hoverProviderResults) {
        if (!isEmptyMarkdownString(item.hover.contents)) {
          const range2 = item.hover.range ? Range$2.lift(item.hover.range) : anchor.range;
          const hoverSource = new HoverSource(item.hover, item.provider, position);
          yield new MarkdownHover(this, range2, item.hover.contents, false, item.ordinal, hoverSource);
        }
      }
    }
    renderHoverParts(context, hoverParts) {
      this._renderedHoverParts = new MarkdownRenderedHoverParts(hoverParts, context.fragment, this, this._editor, this._commandService, this._keybindingService, this._hoverService, this._configurationService, this._markdownRendererService, context.onContentsChanged);
      return this._renderedHoverParts;
    }
    handleScroll(e) {
      this._renderedHoverParts?.handleScroll(e);
    }
    getAccessibleContent(hoverPart) {
      return this._renderedHoverParts?.getAccessibleContent(hoverPart) ?? "";
    }
    updateMarkdownHoverVerbosityLevel(action, index) {
      return Promise.resolve(this._renderedHoverParts?.updateMarkdownHoverPartVerbosityLevel(action, index));
    }
  };
  MarkdownHoverParticipant = __decorate$26([
    __param$24(1, IMarkdownRendererService),
    __param$24(2, IConfigurationService),
    __param$24(3, ILanguageFeaturesService),
    __param$24(4, IKeybindingService),
    __param$24(5, IHoverService),
    __param$24(6, ICommandService)
  ], MarkdownHoverParticipant);
  class RenderedMarkdownHoverPart {
    constructor(hoverPart, hoverElement, disposables, actionsContainer) {
      this.hoverPart = hoverPart;
      this.hoverElement = hoverElement;
      this.disposables = disposables;
      this.actionsContainer = actionsContainer;
    }
    dispose() {
      this.disposables.dispose();
    }
  }
  class MarkdownRenderedHoverParts {
    constructor(hoverParts, hoverPartsContainer, _hoverParticipant, _editor, _commandService, _keybindingService, _hoverService, _configurationService, _markdownRendererService, _onFinishedRendering) {
      this._hoverParticipant = _hoverParticipant;
      this._editor = _editor;
      this._commandService = _commandService;
      this._keybindingService = _keybindingService;
      this._hoverService = _hoverService;
      this._configurationService = _configurationService;
      this._markdownRendererService = _markdownRendererService;
      this._onFinishedRendering = _onFinishedRendering;
      this._ongoingHoverOperations = /* @__PURE__ */ new Map();
      this._disposables = new DisposableStore();
      this.renderedHoverParts = this._renderHoverParts(hoverParts, hoverPartsContainer, this._onFinishedRendering);
      this._disposables.add(toDisposable(() => {
        this.renderedHoverParts.forEach((renderedHoverPart) => {
          renderedHoverPart.dispose();
        });
        this._ongoingHoverOperations.forEach((operation) => {
          operation.tokenSource.dispose(true);
        });
      }));
    }
    _renderHoverParts(hoverParts, hoverPartsContainer, onFinishedRendering) {
      hoverParts.sort(compareBy((hover) => hover.ordinal, numberComparator));
      return hoverParts.map((hoverPart) => {
        const renderedHoverPart = this._renderHoverPart(hoverPart, onFinishedRendering);
        hoverPartsContainer.appendChild(renderedHoverPart.hoverElement);
        return renderedHoverPart;
      });
    }
    _renderHoverPart(hoverPart, onFinishedRendering) {
      const renderedMarkdownPart = this._renderMarkdownHover(hoverPart, onFinishedRendering);
      const renderedMarkdownElement = renderedMarkdownPart.hoverElement;
      const hoverSource = hoverPart.source;
      const disposables = new DisposableStore();
      disposables.add(renderedMarkdownPart);
      if (!hoverSource) {
        return new RenderedMarkdownHoverPart(hoverPart, renderedMarkdownElement, disposables);
      }
      const canIncreaseVerbosity = hoverSource.supportsVerbosityAction(HoverVerbosityAction$1.Increase);
      const canDecreaseVerbosity = hoverSource.supportsVerbosityAction(HoverVerbosityAction$1.Decrease);
      if (!canIncreaseVerbosity && !canDecreaseVerbosity) {
        return new RenderedMarkdownHoverPart(hoverPart, renderedMarkdownElement, disposables);
      }
      const actionsContainer = $$f("div.verbosity-actions");
      renderedMarkdownElement.prepend(actionsContainer);
      const actionsContainerInner = $$f("div.verbosity-actions-inner");
      actionsContainer.append(actionsContainerInner);
      disposables.add(this._renderHoverExpansionAction(actionsContainerInner, HoverVerbosityAction$1.Increase, canIncreaseVerbosity));
      disposables.add(this._renderHoverExpansionAction(actionsContainerInner, HoverVerbosityAction$1.Decrease, canDecreaseVerbosity));
      return new RenderedMarkdownHoverPart(hoverPart, renderedMarkdownElement, disposables, actionsContainerInner);
    }
    _renderMarkdownHover(markdownHover, onFinishedRendering) {
      const renderedMarkdownHover = renderMarkdown(this._editor, markdownHover, this._markdownRendererService, onFinishedRendering);
      return renderedMarkdownHover;
    }
    _renderHoverExpansionAction(container, action, actionEnabled) {
      const store = new DisposableStore();
      const isActionIncrease = action === HoverVerbosityAction$1.Increase;
      const actionElement = append$2(container, $$f(ThemeIcon.asCSSSelector(isActionIncrease ? increaseHoverVerbosityIcon : decreaseHoverVerbosityIcon)));
      actionElement.tabIndex = 0;
      const hoverDelegate = new WorkbenchHoverDelegate("mouse", void 0, { target: container, position: {
        hoverPosition: 0
        /* HoverPosition.LEFT */
      } }, this._configurationService, this._hoverService);
      store.add(this._hoverService.setupManagedHover(hoverDelegate, actionElement, labelForHoverVerbosityAction(this._keybindingService, action)));
      if (!actionEnabled) {
        actionElement.classList.add("disabled");
        return store;
      }
      actionElement.classList.add("enabled");
      const actionFunction = () => this._commandService.executeCommand(action === HoverVerbosityAction$1.Increase ? INCREASE_HOVER_VERBOSITY_ACTION_ID : DECREASE_HOVER_VERBOSITY_ACTION_ID, { focus: true });
      store.add(new ClickAction(actionElement, actionFunction));
      store.add(new KeyDownAction(actionElement, actionFunction, [
        3,
        10
        /* KeyCode.Space */
      ]));
      return store;
    }
    handleScroll(e) {
      this.renderedHoverParts.forEach((renderedHoverPart) => {
        const actionsContainerInner = renderedHoverPart.actionsContainer;
        if (!actionsContainerInner) {
          return;
        }
        const hoverElement = renderedHoverPart.hoverElement;
        const topOfHoverScrollPosition = e.scrollTop;
        const bottomOfHoverScrollPosition = topOfHoverScrollPosition + e.height;
        const topOfRenderedPart = hoverElement.offsetTop;
        const hoverElementHeight = hoverElement.clientHeight;
        const bottomOfRenderedPart = topOfRenderedPart + hoverElementHeight;
        const iconsHeight = 22;
        let top;
        if (bottomOfRenderedPart <= bottomOfHoverScrollPosition || topOfRenderedPart >= bottomOfHoverScrollPosition) {
          top = hoverElementHeight - iconsHeight;
        } else {
          top = bottomOfHoverScrollPosition - topOfRenderedPart - iconsHeight;
        }
        actionsContainerInner.style.top = `${top}px`;
      });
    }
    async updateMarkdownHoverPartVerbosityLevel(action, index) {
      const model = this._editor.getModel();
      if (!model) {
        return void 0;
      }
      const hoverRenderedPart = this._getRenderedHoverPartAtIndex(index);
      const hoverSource = hoverRenderedPart?.hoverPart.source;
      if (!hoverRenderedPart || !hoverSource?.supportsVerbosityAction(action)) {
        return void 0;
      }
      const newHover = await this._fetchHover(hoverSource, model, action);
      if (!newHover) {
        return void 0;
      }
      const newHoverSource = new HoverSource(newHover, hoverSource.hoverProvider, hoverSource.hoverPosition);
      const initialHoverPart = hoverRenderedPart.hoverPart;
      const newHoverPart = new MarkdownHover(this._hoverParticipant, initialHoverPart.range, newHover.contents, initialHoverPart.isBeforeContent, initialHoverPart.ordinal, newHoverSource);
      const newHoverRenderedPart = this._updateRenderedHoverPart(index, newHoverPart);
      if (!newHoverRenderedPart) {
        return void 0;
      }
      return {
        hoverPart: newHoverPart,
        hoverElement: newHoverRenderedPart.hoverElement
      };
    }
    getAccessibleContent(hoverPart) {
      const renderedHoverPartIndex = this.renderedHoverParts.findIndex((renderedHoverPart2) => renderedHoverPart2.hoverPart === hoverPart);
      if (renderedHoverPartIndex === -1) {
        return void 0;
      }
      const renderedHoverPart = this._getRenderedHoverPartAtIndex(renderedHoverPartIndex);
      if (!renderedHoverPart) {
        return void 0;
      }
      const hoverElementInnerText = renderedHoverPart.hoverElement.innerText;
      const accessibleContent = hoverElementInnerText.replace(/[^\S\n\r]+/gu, " ");
      return accessibleContent;
    }
    async _fetchHover(hoverSource, model, action) {
      let verbosityDelta = action === HoverVerbosityAction$1.Increase ? 1 : -1;
      const provider = hoverSource.hoverProvider;
      const ongoingHoverOperation = this._ongoingHoverOperations.get(provider);
      if (ongoingHoverOperation) {
        ongoingHoverOperation.tokenSource.cancel();
        verbosityDelta += ongoingHoverOperation.verbosityDelta;
      }
      const tokenSource = new CancellationTokenSource$1();
      this._ongoingHoverOperations.set(provider, { verbosityDelta, tokenSource });
      const context = { verbosityRequest: { verbosityDelta, previousHover: hoverSource.hover } };
      let hover;
      try {
        hover = await Promise.resolve(provider.provideHover(model, hoverSource.hoverPosition, tokenSource.token, context));
      } catch (e) {
        onUnexpectedExternalError(e);
      }
      tokenSource.dispose();
      this._ongoingHoverOperations.delete(provider);
      return hover;
    }
    _updateRenderedHoverPart(index, hoverPart) {
      if (index >= this.renderedHoverParts.length || index < 0) {
        return void 0;
      }
      const renderedHoverPart = this._renderHoverPart(hoverPart, this._onFinishedRendering);
      const currentRenderedHoverPart = this.renderedHoverParts[index];
      const currentRenderedMarkdown = currentRenderedHoverPart.hoverElement;
      const renderedMarkdown = renderedHoverPart.hoverElement;
      const renderedChildrenElements = Array.from(renderedMarkdown.children);
      currentRenderedMarkdown.replaceChildren(...renderedChildrenElements);
      const newRenderedHoverPart = new RenderedMarkdownHoverPart(hoverPart, currentRenderedMarkdown, renderedHoverPart.disposables, renderedHoverPart.actionsContainer);
      currentRenderedHoverPart.dispose();
      this.renderedHoverParts[index] = newRenderedHoverPart;
      return newRenderedHoverPart;
    }
    _getRenderedHoverPartAtIndex(index) {
      return this.renderedHoverParts[index];
    }
    dispose() {
      this._disposables.dispose();
    }
  }
  function renderMarkdownHovers(context, markdownHovers, editor2, markdownRendererService) {
    markdownHovers.sort(compareBy((hover) => hover.ordinal, numberComparator));
    const renderedHoverParts = [];
    for (const markdownHover of markdownHovers) {
      const renderedHoverPart = renderMarkdown(editor2, markdownHover, markdownRendererService, context.onContentsChanged);
      context.fragment.appendChild(renderedHoverPart.hoverElement);
      renderedHoverParts.push(renderedHoverPart);
    }
    return new RenderedHoverParts(renderedHoverParts);
  }
  function renderMarkdown(editor2, markdownHover, markdownRendererService, onFinishedRendering) {
    const disposables = new DisposableStore();
    const renderedMarkdown = $$f("div.hover-row");
    const renderedMarkdownContents = $$f("div.hover-row-contents");
    renderedMarkdown.appendChild(renderedMarkdownContents);
    const markdownStrings = markdownHover.contents;
    for (const markdownString of markdownStrings) {
      if (isEmptyMarkdownString(markdownString)) {
        continue;
      }
      const markdownHoverElement = $$f("div.markdown-hover");
      const hoverContentsElement = append$2(markdownHoverElement, $$f("div.hover-contents"));
      const renderedContents = disposables.add(markdownRendererService.render(markdownString, {
        context: editor2,
        asyncRenderCallback: () => {
          hoverContentsElement.className = "hover-contents code-hover-contents";
          onFinishedRendering();
        }
      }));
      hoverContentsElement.appendChild(renderedContents.element);
      renderedMarkdownContents.appendChild(markdownHoverElement);
    }
    const renderedHoverPart = {
      hoverPart: markdownHover,
      hoverElement: renderedMarkdown,
      dispose() {
        disposables.dispose();
      }
    };
    return renderedHoverPart;
  }
  function labelForHoverVerbosityAction(keybindingService, action) {
    switch (action) {
      case HoverVerbosityAction$1.Increase: {
        const kb = keybindingService.lookupKeybinding(INCREASE_HOVER_VERBOSITY_ACTION_ID);
        return kb ? localize(1135, "Increase Hover Verbosity ({0})", kb.getLabel()) : localize(1136, "Increase Hover Verbosity");
      }
      case HoverVerbosityAction$1.Decrease: {
        const kb = keybindingService.lookupKeybinding(DECREASE_HOVER_VERBOSITY_ACTION_ID);
        return kb ? localize(1137, "Decrease Hover Verbosity ({0})", kb.getLabel()) : localize(1138, "Decrease Hover Verbosity");
      }
    }
  }
  const $$e = $$l;
  class SaturationBox extends Disposable {
    constructor(container, model, pixelRatio) {
      super();
      this.model = model;
      this.pixelRatio = pixelRatio;
      this._onDidChange = new Emitter$1();
      this.onDidChange = this._onDidChange.event;
      this._onColorFlushed = new Emitter$1();
      this.onColorFlushed = this._onColorFlushed.event;
      this._domNode = $$e(".saturation-wrap");
      append$2(container, this._domNode);
      this._canvas = document.createElement("canvas");
      this._canvas.className = "saturation-box";
      append$2(this._domNode, this._canvas);
      this.selection = $$e(".saturation-selection");
      append$2(this._domNode, this.selection);
      this.layout();
      this._register(addDisposableListener(this._domNode, EventType$1.POINTER_DOWN, (e) => this.onPointerDown(e)));
      this._register(this.model.onDidChangeColor(this.onDidChangeColor, this));
      this.monitor = null;
    }
    get domNode() {
      return this._domNode;
    }
    onPointerDown(e) {
      if (!e.target || !(e.target instanceof Element)) {
        return;
      }
      this.monitor = this._register(new GlobalPointerMoveMonitor());
      const origin = getDomNodePagePosition(this._domNode);
      if (e.target !== this.selection) {
        this.onDidChangePosition(e.offsetX, e.offsetY);
      }
      this.monitor.startMonitoring(e.target, e.pointerId, e.buttons, (event) => this.onDidChangePosition(event.pageX - origin.left, event.pageY - origin.top), () => null);
      const pointerUpListener = addDisposableListener(e.target.ownerDocument, EventType$1.POINTER_UP, () => {
        this._onColorFlushed.fire();
        pointerUpListener.dispose();
        if (this.monitor) {
          this.monitor.stopMonitoring(true);
          this.monitor = null;
        }
      }, true);
    }
    onDidChangePosition(left, top) {
      const s = Math.max(0, Math.min(1, left / this.width));
      const v = Math.max(0, Math.min(1, 1 - top / this.height));
      this.paintSelection(s, v);
      this._onDidChange.fire({ s, v });
    }
    layout() {
      this.width = this._domNode.offsetWidth;
      this.height = this._domNode.offsetHeight;
      this._canvas.width = this.width * this.pixelRatio;
      this._canvas.height = this.height * this.pixelRatio;
      this.paint();
      const hsva = this.model.color.hsva;
      this.paintSelection(hsva.s, hsva.v);
    }
    paint() {
      const hsva = this.model.color.hsva;
      const saturatedColor = new Color(new HSVA(hsva.h, 1, 1, 1));
      const ctx = this._canvas.getContext("2d");
      const whiteGradient = ctx.createLinearGradient(0, 0, this._canvas.width, 0);
      whiteGradient.addColorStop(0, "rgba(255, 255, 255, 1)");
      whiteGradient.addColorStop(0.5, "rgba(255, 255, 255, 0.5)");
      whiteGradient.addColorStop(1, "rgba(255, 255, 255, 0)");
      const blackGradient = ctx.createLinearGradient(0, 0, 0, this._canvas.height);
      blackGradient.addColorStop(0, "rgba(0, 0, 0, 0)");
      blackGradient.addColorStop(1, "rgba(0, 0, 0, 1)");
      ctx.rect(0, 0, this._canvas.width, this._canvas.height);
      ctx.fillStyle = Color.Format.CSS.format(saturatedColor);
      ctx.fill();
      ctx.fillStyle = whiteGradient;
      ctx.fill();
      ctx.fillStyle = blackGradient;
      ctx.fill();
    }
    paintSelection(s, v) {
      this.selection.style.left = `${s * this.width}px`;
      this.selection.style.top = `${this.height - v * this.height}px`;
    }
    onDidChangeColor(color) {
      if (this.monitor && this.monitor.isMonitoring()) {
        return;
      }
      this.paint();
      const hsva = color.hsva;
      this.paintSelection(hsva.s, hsva.v);
    }
  }
  class InsertButton extends Disposable {
    constructor(container) {
      super();
      this._onClicked = this._register(new Emitter$1());
      this.onClicked = this._onClicked.event;
      this._button = append$2(container, document.createElement("button"));
      this._button.classList.add("insert-button");
      this._button.textContent = "Insert";
      this._register(addDisposableListener(this._button, EventType$1.CLICK, () => {
        this._onClicked.fire();
      }));
    }
    get button() {
      return this._button;
    }
  }
  const $$d = $$l;
  class Strip extends Disposable {
    constructor(container, model, type) {
      super();
      this.model = model;
      this._onDidChange = new Emitter$1();
      this.onDidChange = this._onDidChange.event;
      this._onColorFlushed = new Emitter$1();
      this.onColorFlushed = this._onColorFlushed.event;
      if (type === "standalone") {
        this.domNode = append$2(container, $$d(".standalone-strip"));
        this.overlay = append$2(this.domNode, $$d(".standalone-overlay"));
      } else {
        this.domNode = append$2(container, $$d(".strip"));
        this.overlay = append$2(this.domNode, $$d(".overlay"));
      }
      this.slider = append$2(this.domNode, $$d(".slider"));
      this.slider.style.top = `0px`;
      this._register(addDisposableListener(this.domNode, EventType$1.POINTER_DOWN, (e) => this.onPointerDown(e)));
      this._register(model.onDidChangeColor(this.onDidChangeColor, this));
      this.layout();
    }
    layout() {
      this.height = this.domNode.offsetHeight - this.slider.offsetHeight;
      const value = this.getValue(this.model.color);
      this.updateSliderPosition(value);
    }
    onDidChangeColor(color) {
      const value = this.getValue(color);
      this.updateSliderPosition(value);
    }
    onPointerDown(e) {
      if (!e.target || !(e.target instanceof Element)) {
        return;
      }
      const monitor = this._register(new GlobalPointerMoveMonitor());
      const origin = getDomNodePagePosition(this.domNode);
      this.domNode.classList.add("grabbing");
      if (e.target !== this.slider) {
        this.onDidChangeTop(e.offsetY);
      }
      monitor.startMonitoring(e.target, e.pointerId, e.buttons, (event) => this.onDidChangeTop(event.pageY - origin.top), () => null);
      const pointerUpListener = addDisposableListener(e.target.ownerDocument, EventType$1.POINTER_UP, () => {
        this._onColorFlushed.fire();
        pointerUpListener.dispose();
        monitor.stopMonitoring(true);
        this.domNode.classList.remove("grabbing");
      }, true);
    }
    onDidChangeTop(top) {
      const value = Math.max(0, Math.min(1, 1 - top / this.height));
      this.updateSliderPosition(value);
      this._onDidChange.fire(value);
    }
    updateSliderPosition(value) {
      this.slider.style.top = `${(1 - value) * this.height}px`;
    }
  }
  class OpacityStrip extends Strip {
    constructor(container, model, type) {
      super(container, model, type);
      this.domNode.classList.add("opacity-strip");
      this.onDidChangeColor(this.model.color);
    }
    onDidChangeColor(color) {
      super.onDidChangeColor(color);
      const { r, g, b } = color.rgba;
      const opaque = new Color(new RGBA(r, g, b, 1));
      const transparent2 = new Color(new RGBA(r, g, b, 0));
      this.overlay.style.background = `linear-gradient(to bottom, ${opaque} 0%, ${transparent2} 100%)`;
    }
    getValue(color) {
      return color.hsva.a;
    }
  }
  class HueStrip extends Strip {
    constructor(container, model, type) {
      super(container, model, type);
      this.domNode.classList.add("hue-strip");
    }
    getValue(color) {
      return 1 - color.hsva.h / 360;
    }
  }
  const $$c = $$l;
  class ColorPickerBody extends Disposable {
    constructor(container, model, pixelRatio, type) {
      super();
      this.model = model;
      this.pixelRatio = pixelRatio;
      this._insertButton = null;
      this._domNode = $$c(".colorpicker-body");
      append$2(container, this._domNode);
      this._saturationBox = new SaturationBox(this._domNode, this.model, this.pixelRatio);
      this._register(this._saturationBox);
      this._register(this._saturationBox.onDidChange(this.onDidSaturationValueChange, this));
      this._register(this._saturationBox.onColorFlushed(this.flushColor, this));
      this._opacityStrip = new OpacityStrip(this._domNode, this.model, type);
      this._register(this._opacityStrip);
      this._register(this._opacityStrip.onDidChange(this.onDidOpacityChange, this));
      this._register(this._opacityStrip.onColorFlushed(this.flushColor, this));
      this._hueStrip = new HueStrip(this._domNode, this.model, type);
      this._register(this._hueStrip);
      this._register(this._hueStrip.onDidChange(this.onDidHueChange, this));
      this._register(this._hueStrip.onColorFlushed(this.flushColor, this));
      if (type === "standalone") {
        this._insertButton = this._register(new InsertButton(this._domNode));
        this._domNode.classList.add("standalone-colorpicker");
      }
    }
    flushColor() {
      this.model.flushColor();
    }
    onDidSaturationValueChange({ s, v }) {
      const hsva = this.model.color.hsva;
      this.model.color = new Color(new HSVA(hsva.h, s, v, hsva.a));
    }
    onDidOpacityChange(a) {
      const hsva = this.model.color.hsva;
      this.model.color = new Color(new HSVA(hsva.h, hsva.s, hsva.v, a));
    }
    onDidHueChange(value) {
      const hsva = this.model.color.hsva;
      const h2 = (1 - value) * 360;
      this.model.color = new Color(new HSVA(h2 === 360 ? 0 : h2, hsva.s, hsva.v, hsva.a));
    }
    get domNode() {
      return this._domNode;
    }
    get saturationBox() {
      return this._saturationBox;
    }
    get enterButton() {
      return this._insertButton;
    }
    layout() {
      this._saturationBox.layout();
      this._opacityStrip.layout();
      this._hueStrip.layout();
    }
  }
  const $$b = $$l;
  class CloseButton extends Disposable {
    constructor(container) {
      super();
      this._onClicked = this._register(new Emitter$1());
      this.onClicked = this._onClicked.event;
      this._button = document.createElement("div");
      this._button.classList.add("close-button");
      append$2(container, this._button);
      const innerDiv = document.createElement("div");
      innerDiv.classList.add("close-button-inner-div");
      append$2(this._button, innerDiv);
      const closeButton = append$2(innerDiv, $$b(".button" + ThemeIcon.asCSSSelector(registerIcon("color-picker-close", Codicon.close, localize(885, "Icon to close the color picker")))));
      closeButton.classList.add("close-icon");
      this._register(addDisposableListener(this._button, EventType$1.CLICK, () => {
        this._onClicked.fire();
      }));
    }
  }
  const $$a = $$l;
  class ColorPickerHeader extends Disposable {
    constructor(container, model, themeService, type) {
      super();
      this.model = model;
      this.type = type;
      this._closeButton = null;
      this._domNode = $$a(".colorpicker-header");
      append$2(container, this._domNode);
      this._pickedColorNode = append$2(this._domNode, $$a(".picked-color"));
      append$2(this._pickedColorNode, $$a("span.codicon.codicon-color-mode"));
      this._pickedColorPresentation = append$2(this._pickedColorNode, document.createElement("span"));
      this._pickedColorPresentation.classList.add("picked-color-presentation");
      const tooltip = localize(886, "Click to toggle color options (rgb/hsl/hex)");
      this._pickedColorNode.setAttribute("title", tooltip);
      this._originalColorNode = append$2(this._domNode, $$a(".original-color"));
      this._originalColorNode.style.backgroundColor = Color.Format.CSS.format(this.model.originalColor) || "";
      this.backgroundColor = themeService.getColorTheme().getColor(editorHoverBackground) || Color.white;
      this._register(themeService.onDidColorThemeChange((theme) => {
        this.backgroundColor = theme.getColor(editorHoverBackground) || Color.white;
      }));
      this._register(addDisposableListener(this._pickedColorNode, EventType$1.CLICK, () => this.model.selectNextColorPresentation()));
      this._register(addDisposableListener(this._originalColorNode, EventType$1.CLICK, () => {
        this.model.color = this.model.originalColor;
        this.model.flushColor();
      }));
      this._register(model.onDidChangeColor(this.onDidChangeColor, this));
      this._register(model.onDidChangePresentation(this.onDidChangePresentation, this));
      this._pickedColorNode.style.backgroundColor = Color.Format.CSS.format(model.color) || "";
      this._pickedColorNode.classList.toggle("light", model.color.rgba.a < 0.5 ? this.backgroundColor.isLighter() : model.color.isLighter());
      this.onDidChangeColor(this.model.color);
      if (this.type === "standalone") {
        this._domNode.classList.add("standalone-colorpicker");
        this._closeButton = this._register(new CloseButton(this._domNode));
      }
    }
    get closeButton() {
      return this._closeButton;
    }
    get pickedColorNode() {
      return this._pickedColorNode;
    }
    get originalColorNode() {
      return this._originalColorNode;
    }
    onDidChangeColor(color) {
      this._pickedColorNode.style.backgroundColor = Color.Format.CSS.format(color) || "";
      this._pickedColorNode.classList.toggle("light", color.rgba.a < 0.5 ? this.backgroundColor.isLighter() : color.isLighter());
      this.onDidChangePresentation();
    }
    onDidChangePresentation() {
      this._pickedColorPresentation.textContent = this.model.presentation ? this.model.presentation.label : "";
    }
  }
  const $$9 = $$l;
  class ColorPickerWidget extends Widget$1 {
    constructor(container, model, pixelRatio, themeService, type) {
      super();
      this.model = model;
      this.pixelRatio = pixelRatio;
      this._register(PixelRatio.getInstance(getWindow(container)).onDidChange(() => this.layout()));
      this._domNode = $$9(".colorpicker-widget");
      container.appendChild(this._domNode);
      this.header = this._register(new ColorPickerHeader(this._domNode, this.model, themeService, type));
      this.body = this._register(new ColorPickerBody(this._domNode, this.model, this.pixelRatio, type));
    }
    layout() {
      this.body.layout();
    }
    get domNode() {
      return this._domNode;
    }
  }
  class ColorPickerModel {
    get color() {
      return this._color;
    }
    set color(color) {
      if (this._color.equals(color)) {
        return;
      }
      this._color = color;
      this._onDidChangeColor.fire(color);
    }
    get presentation() {
      return this.colorPresentations[this.presentationIndex];
    }
    get colorPresentations() {
      return this._colorPresentations;
    }
    set colorPresentations(colorPresentations) {
      this._colorPresentations = colorPresentations;
      if (this.presentationIndex > colorPresentations.length - 1) {
        this.presentationIndex = 0;
      }
      this._onDidChangePresentation.fire(this.presentation);
    }
    constructor(color, availableColorPresentations, presentationIndex) {
      this.presentationIndex = presentationIndex;
      this._onColorFlushed = new Emitter$1();
      this.onColorFlushed = this._onColorFlushed.event;
      this._onDidChangeColor = new Emitter$1();
      this.onDidChangeColor = this._onDidChangeColor.event;
      this._onDidChangePresentation = new Emitter$1();
      this.onDidChangePresentation = this._onDidChangePresentation.event;
      this.originalColor = color;
      this._color = color;
      this._colorPresentations = availableColorPresentations;
    }
    selectNextColorPresentation() {
      this.presentationIndex = (this.presentationIndex + 1) % this.colorPresentations.length;
      this.flushColor();
      this._onDidChangePresentation.fire(this.presentation);
    }
    guessColorPresentation(color, originalText) {
      let presentationIndex = -1;
      for (let i2 = 0; i2 < this.colorPresentations.length; i2++) {
        if (originalText.toLowerCase() === this.colorPresentations[i2].label) {
          presentationIndex = i2;
          break;
        }
      }
      if (presentationIndex === -1) {
        const originalTextPrefix = originalText.split("(")[0].toLowerCase();
        for (let i2 = 0; i2 < this.colorPresentations.length; i2++) {
          if (this.colorPresentations[i2].label.toLowerCase().startsWith(originalTextPrefix)) {
            presentationIndex = i2;
            break;
          }
        }
      }
      if (presentationIndex !== -1 && presentationIndex !== this.presentationIndex) {
        this.presentationIndex = presentationIndex;
        this._onDidChangePresentation.fire(this.presentation);
      }
    }
    flushColor() {
      this._onColorFlushed.fire(this._color);
    }
  }
  async function createColorHover(editorModel, colorInfo, provider) {
    const originalText = editorModel.getValueInRange(colorInfo.range);
    const { red, green, blue, alpha } = colorInfo.color;
    const rgba = new RGBA(Math.round(red * 255), Math.round(green * 255), Math.round(blue * 255), alpha);
    const color = new Color(rgba);
    const colorPresentations = await getColorPresentations(editorModel, colorInfo, provider, CancellationToken.None);
    const model = new ColorPickerModel(color, [], 0);
    model.colorPresentations = colorPresentations || [];
    model.guessColorPresentation(color, originalText);
    return {
      range: Range$2.lift(colorInfo.range),
      model,
      provider
    };
  }
  function updateEditorModel(editor2, range2, model) {
    const textEdits = [];
    const edit2 = model.presentation.textEdit ?? { range: range2, text: model.presentation.label, forceMoveMarkers: false };
    textEdits.push(edit2);
    if (model.presentation.additionalTextEdits) {
      textEdits.push(...model.presentation.additionalTextEdits);
    }
    const replaceRange = Range$2.lift(edit2.range);
    const trackedRange = editor2.getModel()._setTrackedRange(
      null,
      replaceRange,
      3
      /* TrackedRangeStickiness.GrowsOnlyWhenTypingAfter */
    );
    editor2.executeEdits("colorpicker", textEdits);
    editor2.pushUndoStop();
    return editor2.getModel()._getTrackedRange(trackedRange) ?? replaceRange;
  }
  async function updateColorPresentations(editorModel, colorPickerModel, color, range2, colorHover) {
    const colorPresentations = await getColorPresentations(editorModel, {
      range: range2,
      color: {
        red: color.rgba.r / 255,
        green: color.rgba.g / 255,
        blue: color.rgba.b / 255,
        alpha: color.rgba.a
      }
    }, colorHover.provider, CancellationToken.None);
    colorPickerModel.colorPresentations = colorPresentations || [];
  }
  var __decorate$25 = 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$23 = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  class ColorHover {
    constructor(owner, range2, model, provider) {
      this.owner = owner;
      this.range = range2;
      this.model = model;
      this.provider = provider;
      this.forceShowAtRange = true;
    }
    isValidForHoverAnchor(anchor) {
      return anchor.type === 1 && this.range.startColumn <= anchor.range.startColumn && this.range.endColumn >= anchor.range.endColumn;
    }
    static fromBaseColor(owner, color) {
      return new ColorHover(owner, color.range, color.model, color.provider);
    }
  }
  let HoverColorPickerParticipant = class HoverColorPickerParticipant {
    constructor(_editor, _themeService) {
      this._editor = _editor;
      this._themeService = _themeService;
      this.hoverOrdinal = 2;
    }
    computeSync(_anchor, _lineDecorations, source) {
      return [];
    }
    computeAsync(anchor, lineDecorations, source, token) {
      return AsyncIterableProducer.fromPromise(this._computeAsync(anchor, lineDecorations, source));
    }
    async _computeAsync(_anchor, lineDecorations, source) {
      if (!this._editor.hasModel()) {
        return [];
      }
      if (!this._isValidRequest(source)) {
        return [];
      }
      const colorDetector = ColorDetector.get(this._editor);
      if (!colorDetector) {
        return [];
      }
      for (const d of lineDecorations) {
        if (!colorDetector.isColorDecoration(d)) {
          continue;
        }
        const colorData = colorDetector.getColorData(d.range.getStartPosition());
        if (colorData) {
          const colorHover = ColorHover.fromBaseColor(this, await createColorHover(this._editor.getModel(), colorData.colorInfo, colorData.provider));
          return [colorHover];
        }
      }
      return [];
    }
    _isValidRequest(source) {
      const decoratorActivatedOn = this._editor.getOption(
        168
        /* EditorOption.colorDecoratorsActivatedOn */
      );
      switch (source) {
        case 0:
          return decoratorActivatedOn === "hover" || decoratorActivatedOn === "clickAndHover";
        case 1:
          return decoratorActivatedOn === "click" || decoratorActivatedOn === "clickAndHover";
        case 2:
          return true;
      }
    }
    renderHoverParts(context, hoverParts) {
      const editor2 = this._editor;
      if (hoverParts.length === 0 || !editor2.hasModel()) {
        return new RenderedHoverParts([]);
      }
      const minimumHeight = editor2.getOption(
        75
        /* EditorOption.lineHeight */
      ) + 8;
      context.setMinimumDimensions(new Dimension(302, minimumHeight));
      const disposables = new DisposableStore();
      const colorHover = hoverParts[0];
      const editorModel = editor2.getModel();
      const model = colorHover.model;
      this._colorPicker = disposables.add(new ColorPickerWidget(
        context.fragment,
        model,
        editor2.getOption(
          163
          /* EditorOption.pixelRatio */
        ),
        this._themeService,
        "hover"
        /* ColorPickerWidgetType.Hover */
      ));
      let editorUpdatedByColorPicker = false;
      let range2 = new Range$2(colorHover.range.startLineNumber, colorHover.range.startColumn, colorHover.range.endLineNumber, colorHover.range.endColumn);
      disposables.add(model.onColorFlushed(async (color) => {
        await updateColorPresentations(editorModel, model, color, range2, colorHover);
        editorUpdatedByColorPicker = true;
        range2 = updateEditorModel(editor2, range2, model);
      }));
      disposables.add(model.onDidChangeColor((color) => {
        updateColorPresentations(editorModel, model, color, range2, colorHover);
      }));
      disposables.add(editor2.onDidChangeModelContent((e) => {
        if (editorUpdatedByColorPicker) {
          editorUpdatedByColorPicker = false;
        } else {
          context.hide();
          editor2.focus();
        }
      }));
      const renderedHoverPart = {
        hoverPart: ColorHover.fromBaseColor(this, colorHover),
        hoverElement: this._colorPicker.domNode,
        dispose() {
          disposables.dispose();
        }
      };
      return new RenderedHoverParts([renderedHoverPart]);
    }
    getAccessibleContent(hoverPart) {
      return localize(887, "There is a color picker here.");
    }
    handleResize() {
      this._colorPicker?.layout();
    }
    handleContentsChanged() {
      this._colorPicker?.layout();
    }
    handleHide() {
      this._colorPicker?.dispose();
      this._colorPicker = void 0;
    }
    isColorPickerVisible() {
      return !!this._colorPicker;
    }
  };
  HoverColorPickerParticipant = __decorate$25([
    __param$23(1, IThemeService)
  ], HoverColorPickerParticipant);
  class EditOperation {
    static insert(position, text2) {
      return {
        range: new Range$2(position.lineNumber, position.column, position.lineNumber, position.column),
        text: text2,
        forceMoveMarkers: true
      };
    }
    static delete(range2) {
      return {
        range: range2,
        text: null
      };
    }
    static replace(range2, text2) {
      return {
        range: range2,
        text: text2
      };
    }
    static replaceMove(range2, text2) {
      return {
        range: range2,
        text: text2,
        forceMoveMarkers: true
      };
    }
  }
  function hasModifier(e, modifier) {
    return !!e[modifier];
  }
  class ClickLinkMouseEvent {
    constructor(source, opts) {
      this.target = source.target;
      this.isLeftClick = source.event.leftButton;
      this.isMiddleClick = source.event.middleButton;
      this.isRightClick = source.event.rightButton;
      this.mouseMiddleClickAction = opts.mouseMiddleClickAction;
      this.hasTriggerModifier = hasModifier(source.event, opts.triggerModifier);
      if (this.isMiddleClick && opts.mouseMiddleClickAction === "ctrlLeftClick") {
        this.isMiddleClick = false;
        this.isLeftClick = true;
        this.hasTriggerModifier = true;
      }
      this.hasSideBySideModifier = hasModifier(source.event, opts.triggerSideBySideModifier);
      this.isNoneOrSingleMouseDown = source.event.detail <= 1;
    }
  }
  class ClickLinkKeyboardEvent {
    constructor(source, opts) {
      this.keyCodeIsTriggerKey = source.keyCode === opts.triggerKey;
      this.keyCodeIsSideBySideKey = source.keyCode === opts.triggerSideBySideKey;
      this.hasTriggerModifier = hasModifier(source, opts.triggerModifier);
    }
  }
  class ClickLinkOptions {
    constructor(triggerKey, triggerModifier, triggerSideBySideKey, triggerSideBySideModifier, mouseMiddleClickAction) {
      this.mouseMiddleClickAction = mouseMiddleClickAction;
      this.triggerKey = triggerKey;
      this.triggerModifier = triggerModifier;
      this.triggerSideBySideKey = triggerSideBySideKey;
      this.triggerSideBySideModifier = triggerSideBySideModifier;
    }
    equals(other) {
      return this.triggerKey === other.triggerKey && this.triggerModifier === other.triggerModifier && this.triggerSideBySideKey === other.triggerSideBySideKey && this.triggerSideBySideModifier === other.triggerSideBySideModifier && this.mouseMiddleClickAction === other.mouseMiddleClickAction;
    }
  }
  function createOptions(multiCursorModifier, mouseMiddleClickAction) {
    if (multiCursorModifier === "altKey") {
      if (isMacintosh) {
        return new ClickLinkOptions(57, "metaKey", 6, "altKey", mouseMiddleClickAction);
      }
      return new ClickLinkOptions(5, "ctrlKey", 6, "altKey", mouseMiddleClickAction);
    }
    if (isMacintosh) {
      return new ClickLinkOptions(6, "altKey", 57, "metaKey", mouseMiddleClickAction);
    }
    return new ClickLinkOptions(6, "altKey", 5, "ctrlKey", mouseMiddleClickAction);
  }
  class ClickLinkGesture extends Disposable {
    constructor(editor2, opts) {
      super();
      this._onMouseMoveOrRelevantKeyDown = this._register(new Emitter$1());
      this.onMouseMoveOrRelevantKeyDown = this._onMouseMoveOrRelevantKeyDown.event;
      this._onExecute = this._register(new Emitter$1());
      this.onExecute = this._onExecute.event;
      this._onCancel = this._register(new Emitter$1());
      this.onCancel = this._onCancel.event;
      this._editor = editor2;
      this._extractLineNumberFromMouseEvent = opts?.extractLineNumberFromMouseEvent ?? ((e) => e.target.position ? e.target.position.lineNumber : 0);
      this._opts = createOptions(this._editor.getOption(
        86
        /* EditorOption.multiCursorModifier */
      ), this._editor.getOption(
        87
        /* EditorOption.mouseMiddleClickAction */
      ));
      this._lastMouseMoveEvent = null;
      this._hasTriggerKeyOnMouseDown = false;
      this._lineNumberOnMouseDown = 0;
      this._register(this._editor.onDidChangeConfiguration((e) => {
        if (e.hasChanged(
          86
          /* EditorOption.multiCursorModifier */
        ) || e.hasChanged(
          87
          /* EditorOption.mouseMiddleClickAction */
        )) {
          const newOpts = createOptions(this._editor.getOption(
            86
            /* EditorOption.multiCursorModifier */
          ), this._editor.getOption(
            87
            /* EditorOption.mouseMiddleClickAction */
          ));
          if (this._opts.equals(newOpts)) {
            return;
          }
          this._opts = newOpts;
          this._lastMouseMoveEvent = null;
          this._hasTriggerKeyOnMouseDown = false;
          this._lineNumberOnMouseDown = 0;
          this._onCancel.fire();
        }
      }));
      this._register(this._editor.onMouseMove((e) => this._onEditorMouseMove(new ClickLinkMouseEvent(e, this._opts))));
      this._register(this._editor.onMouseDown((e) => this._onEditorMouseDown(new ClickLinkMouseEvent(e, this._opts))));
      this._register(this._editor.onMouseUp((e) => this._onEditorMouseUp(new ClickLinkMouseEvent(e, this._opts))));
      this._register(this._editor.onKeyDown((e) => this._onEditorKeyDown(new ClickLinkKeyboardEvent(e, this._opts))));
      this._register(this._editor.onKeyUp((e) => this._onEditorKeyUp(new ClickLinkKeyboardEvent(e, this._opts))));
      this._register(this._editor.onMouseDrag(() => this._resetHandler()));
      this._register(this._editor.onDidChangeCursorSelection((e) => this._onDidChangeCursorSelection(e)));
      this._register(this._editor.onDidChangeModel((e) => this._resetHandler()));
      this._register(this._editor.onDidChangeModelContent(() => this._resetHandler()));
      this._register(this._editor.onDidScrollChange((e) => {
        if (e.scrollTopChanged || e.scrollLeftChanged) {
          this._resetHandler();
        }
      }));
    }
    _onDidChangeCursorSelection(e) {
      if (e.selection && e.selection.startColumn !== e.selection.endColumn) {
        this._resetHandler();
      }
    }
    _onEditorMouseMove(mouseEvent) {
      this._lastMouseMoveEvent = mouseEvent;
      this._onMouseMoveOrRelevantKeyDown.fire([mouseEvent, null]);
    }
    _onEditorMouseDown(mouseEvent) {
      this._hasTriggerKeyOnMouseDown = mouseEvent.hasTriggerModifier;
      this._lineNumberOnMouseDown = this._extractLineNumberFromMouseEvent(mouseEvent);
    }
    _onEditorMouseUp(mouseEvent) {
      const currentLineNumber = this._extractLineNumberFromMouseEvent(mouseEvent);
      const lineNumbersCorrect = !!this._lineNumberOnMouseDown && this._lineNumberOnMouseDown === currentLineNumber;
      if (lineNumbersCorrect && (this._hasTriggerKeyOnMouseDown || mouseEvent.isMiddleClick && mouseEvent.mouseMiddleClickAction === "openLink")) {
        this._onExecute.fire(mouseEvent);
      }
    }
    _onEditorKeyDown(e) {
      if (this._lastMouseMoveEvent && (e.keyCodeIsTriggerKey || e.keyCodeIsSideBySideKey && e.hasTriggerModifier)) {
        this._onMouseMoveOrRelevantKeyDown.fire([this._lastMouseMoveEvent, e]);
      } else if (e.hasTriggerModifier) {
        this._onCancel.fire();
      }
    }
    _onEditorKeyUp(e) {
      if (e.keyCodeIsTriggerKey) {
        this._onCancel.fire();
      }
    }
    _resetHandler() {
      this._lastMouseMoveEvent = null;
      this._hasTriggerKeyOnMouseDown = false;
      this._onCancel.fire();
    }
  }
  class InlayHintAnchor {
    constructor(range2, direction) {
      this.range = range2;
      this.direction = direction;
    }
  }
  class InlayHintItem {
    constructor(hint, anchor, provider) {
      this.hint = hint;
      this.anchor = anchor;
      this.provider = provider;
      this._isResolved = false;
    }
    with(delta) {
      const result = new InlayHintItem(this.hint, delta.anchor, this.provider);
      result._isResolved = this._isResolved;
      result._currentResolve = this._currentResolve;
      return result;
    }
    async resolve(token) {
      if (typeof this.provider.resolveInlayHint !== "function") {
        return;
      }
      if (this._currentResolve) {
        await this._currentResolve;
        if (token.isCancellationRequested) {
          return;
        }
        return this.resolve(token);
      }
      if (!this._isResolved) {
        this._currentResolve = this._doResolve(token).finally(() => this._currentResolve = void 0);
      }
      await this._currentResolve;
    }
    async _doResolve(token) {
      try {
        const newHint = await Promise.resolve(this.provider.resolveInlayHint(this.hint, token));
        this.hint.tooltip = newHint?.tooltip ?? this.hint.tooltip;
        this.hint.label = newHint?.label ?? this.hint.label;
        this.hint.textEdits = newHint?.textEdits ?? this.hint.textEdits;
        this._isResolved = true;
      } catch (err) {
        onUnexpectedExternalError(err);
        this._isResolved = false;
      }
    }
  }
  const _InlayHintsFragments = class _InlayHintsFragments {
    static async create(registry, model, ranges, token) {
      const data = [];
      const promises = registry.ordered(model).reverse().map((provider) => ranges.map(async (range2) => {
        try {
          const result = await provider.provideInlayHints(model, range2, token);
          if (result?.hints.length || provider.onDidChangeInlayHints) {
            data.push([result ?? _InlayHintsFragments._emptyInlayHintList, provider]);
          }
        } catch (err) {
          onUnexpectedExternalError(err);
        }
      }));
      await Promise.all(promises.flat());
      if (token.isCancellationRequested || model.isDisposed()) {
        throw new CancellationError();
      }
      return new _InlayHintsFragments(ranges, data, model);
    }
    constructor(ranges, data, model) {
      this._disposables = new DisposableStore();
      this.ranges = ranges;
      this.provider = /* @__PURE__ */ new Set();
      const items = [];
      for (const [list2, provider] of data) {
        this._disposables.add(list2);
        this.provider.add(provider);
        for (const hint of list2.hints) {
          const position = model.validatePosition(hint.position);
          let direction = "before";
          const wordRange = _InlayHintsFragments._getRangeAtPosition(model, position);
          let range2;
          if (wordRange.getStartPosition().isBefore(position)) {
            range2 = Range$2.fromPositions(wordRange.getStartPosition(), position);
            direction = "after";
          } else {
            range2 = Range$2.fromPositions(position, wordRange.getEndPosition());
            direction = "before";
          }
          items.push(new InlayHintItem(hint, new InlayHintAnchor(range2, direction), provider));
        }
      }
      this.items = items.sort((a, b) => Position$1.compare(a.hint.position, b.hint.position));
    }
    dispose() {
      this._disposables.dispose();
    }
    static _getRangeAtPosition(model, position) {
      const line = position.lineNumber;
      const word = model.getWordAtPosition(position);
      if (word) {
        return new Range$2(line, word.startColumn, line, word.endColumn);
      }
      model.tokenization.tokenizeIfCheap(line);
      const tokens = model.tokenization.getLineTokens(line);
      const offset = position.column - 1;
      const idx = tokens.findTokenIndexAtOffset(offset);
      let start = tokens.getStartOffset(idx);
      let end = tokens.getEndOffset(idx);
      if (end - start === 1) {
        if (start === offset && idx > 1) {
          start = tokens.getStartOffset(idx - 1);
          end = tokens.getEndOffset(idx - 1);
        } else if (end === offset && idx < tokens.getCount() - 1) {
          start = tokens.getStartOffset(idx + 1);
          end = tokens.getEndOffset(idx + 1);
        }
      }
      return new Range$2(line, start + 1, line, end + 1);
    }
  };
  _InlayHintsFragments._emptyInlayHintList = Object.freeze({ dispose() {
  }, hints: [] });
  let InlayHintsFragments = _InlayHintsFragments;
  function asCommandLink(command) {
    return createCommandUri(command.id, ...command.arguments ?? []).toString();
  }
  function isCodeEditor(thing) {
    if (thing && typeof thing.getEditorType === "function") {
      return thing.getEditorType() === EditorType.ICodeEditor;
    } else {
      return false;
    }
  }
  function isDiffEditor(thing) {
    if (thing && typeof thing.getEditorType === "function") {
      return thing.getEditorType() === EditorType.IDiffEditor;
    } else {
      return false;
    }
  }
  function isCompositeEditor(thing) {
    return !!thing && typeof thing === "object" && typeof thing.onDidChangeActiveEditor === "function";
  }
  function getCodeEditor(thing) {
    if (isCodeEditor(thing)) {
      return thing;
    }
    if (isDiffEditor(thing)) {
      return thing.getModifiedEditor();
    }
    if (isCompositeEditor(thing) && isCodeEditor(thing.activeCodeEditor)) {
      return thing.activeCodeEditor;
    }
    return null;
  }
  var __decorate$24 = 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$22 = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  let EmbeddedCodeEditorWidget = class EmbeddedCodeEditorWidget extends CodeEditorWidget {
    constructor(domElement, options, codeEditorWidgetOptions, parentEditor, instantiationService, codeEditorService, commandService, contextKeyService, themeService, notificationService, accessibilityService, languageConfigurationService, languageFeaturesService) {
      super(domElement, { ...parentEditor.getRawOptions(), overflowWidgetsDomNode: parentEditor.getOverflowWidgetsDomNode() }, codeEditorWidgetOptions, instantiationService, codeEditorService, commandService, contextKeyService, themeService, notificationService, accessibilityService, languageConfigurationService, languageFeaturesService);
      this._parentEditor = parentEditor;
      this._overwriteOptions = options;
      super.updateOptions(this._overwriteOptions);
      this._register(parentEditor.onDidChangeConfiguration((e) => this._onParentConfigurationChanged(e)));
    }
    getParentEditor() {
      return this._parentEditor;
    }
    _onParentConfigurationChanged(e) {
      super.updateOptions(this._parentEditor.getRawOptions());
      super.updateOptions(this._overwriteOptions);
    }
    updateOptions(newOptions) {
      mixin(this._overwriteOptions, newOptions, true);
      super.updateOptions(this._overwriteOptions);
    }
  };
  EmbeddedCodeEditorWidget = __decorate$24([
    __param$22(4, IInstantiationService),
    __param$22(5, ICodeEditorService),
    __param$22(6, ICommandService),
    __param$22(7, IContextKeyService),
    __param$22(8, IThemeService),
    __param$22(9, INotificationService),
    __param$22(10, IAccessibilityService),
    __param$22(11, ILanguageConfigurationService),
    __param$22(12, ILanguageFeaturesService)
  ], EmbeddedCodeEditorWidget);
  function getOuterEditor(accessor) {
    const editor2 = accessor.get(ICodeEditorService).getFocusedCodeEditor();
    if (editor2 instanceof EmbeddedCodeEditorWidget) {
      return editor2.getParentEditor();
    }
    return editor2;
  }
  const defaultColor = new Color(new RGBA(0, 122, 204));
  const defaultOptions$1 = {
    showArrow: true,
    showFrame: true,
    className: "",
    frameColor: defaultColor,
    arrowColor: defaultColor,
    keepEditorSelection: false
  };
  const WIDGET_ID = "vs.editor.contrib.zoneWidget";
  class ViewZoneDelegate {
    constructor(domNode, afterLineNumber, afterColumn, heightInLines, onDomNodeTop, onComputedHeight, showInHiddenAreas, ordinal) {
      this.id = "";
      this.domNode = domNode;
      this.afterLineNumber = afterLineNumber;
      this.afterColumn = afterColumn;
      this.heightInLines = heightInLines;
      this.showInHiddenAreas = showInHiddenAreas;
      this.ordinal = ordinal;
      this._onDomNodeTop = onDomNodeTop;
      this._onComputedHeight = onComputedHeight;
    }
    onDomNodeTop(top) {
      this._onDomNodeTop(top);
    }
    onComputedHeight(height) {
      this._onComputedHeight(height);
    }
  }
  class OverlayWidgetDelegate {
    constructor(id, domNode) {
      this._id = id;
      this._domNode = domNode;
    }
    getId() {
      return this._id;
    }
    getDomNode() {
      return this._domNode;
    }
    getPosition() {
      return null;
    }
  }
  const _Arrow = class _Arrow {
    constructor(_editor) {
      this._editor = _editor;
      this._ruleName = _Arrow._IdGenerator.nextId();
      this._color = null;
      this._height = -1;
      this._decorations = this._editor.createDecorationsCollection();
    }
    dispose() {
      this.hide();
      removeCSSRulesContainingSelector(this._ruleName);
    }
    set color(value) {
      if (this._color !== value) {
        this._color = value;
        this._updateStyle();
      }
    }
    set height(value) {
      if (this._height !== value) {
        this._height = value;
        this._updateStyle();
      }
    }
    _updateStyle() {
      removeCSSRulesContainingSelector(this._ruleName);
      createCSSRule(`.monaco-editor ${this._ruleName}`, `border-style: solid; border-color: transparent; border-bottom-color: ${this._color}; border-width: ${this._height}px; bottom: -${this._height}px !important; margin-left: -${this._height}px; `);
    }
    show(where) {
      if (where.column === 1) {
        where = { lineNumber: where.lineNumber, column: 2 };
      }
      this._decorations.set([{
        range: Range$2.fromPositions(where),
        options: {
          description: "zone-widget-arrow",
          className: this._ruleName,
          stickiness: 1
          /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */
        }
      }]);
    }
    hide() {
      this._decorations.clear();
    }
  };
  _Arrow._IdGenerator = new IdGenerator(".arrow-decoration-");
  let Arrow = _Arrow;
  class ZoneWidget {
    constructor(editor2, options = {}) {
      this._arrow = null;
      this._overlayWidget = null;
      this._resizeSash = null;
      this._isSashResizeHeight = false;
      this._viewZone = null;
      this._disposables = new DisposableStore();
      this.container = null;
      this._isShowing = false;
      this.editor = editor2;
      this._positionMarkerId = this.editor.createDecorationsCollection();
      this.options = deepClone(options);
      mixin(this.options, defaultOptions$1, false);
      this.domNode = document.createElement("div");
      if (!this.options.isAccessible) {
        this.domNode.setAttribute("aria-hidden", "true");
        this.domNode.setAttribute("role", "presentation");
      }
      this._disposables.add(this.editor.onDidLayoutChange((info) => {
        const width2 = this._getWidth(info);
        this.domNode.style.width = width2 + "px";
        this.domNode.style.left = this._getLeft(info) + "px";
        this._onWidth(width2);
      }));
    }
    dispose() {
      if (this._overlayWidget) {
        this.editor.removeOverlayWidget(this._overlayWidget);
        this._overlayWidget = null;
      }
      if (this._viewZone) {
        this.editor.changeViewZones((accessor) => {
          if (this._viewZone) {
            accessor.removeZone(this._viewZone.id);
          }
          this._viewZone = null;
        });
      }
      this._positionMarkerId.clear();
      this._disposables.dispose();
    }
    create() {
      this.domNode.classList.add("zone-widget");
      if (this.options.className) {
        this.domNode.classList.add(this.options.className);
      }
      this.container = document.createElement("div");
      this.container.classList.add("zone-widget-container");
      this.domNode.appendChild(this.container);
      if (this.options.showArrow) {
        this._arrow = new Arrow(this.editor);
        this._disposables.add(this._arrow);
      }
      this._fillContainer(this.container);
      this._initSash();
      this._applyStyles();
    }
    style(styles) {
      if (styles.frameColor) {
        this.options.frameColor = styles.frameColor;
      }
      if (styles.arrowColor) {
        this.options.arrowColor = styles.arrowColor;
      }
      this._applyStyles();
    }
    _applyStyles() {
      if (this.container && this.options.frameColor) {
        const frameColor = this.options.frameColor.toString();
        this.container.style.borderTopColor = frameColor;
        this.container.style.borderBottomColor = frameColor;
      }
      if (this._arrow && this.options.arrowColor) {
        const arrowColor = this.options.arrowColor.toString();
        this._arrow.color = arrowColor;
      }
    }
    _getWidth(info) {
      return info.width - info.minimap.minimapWidth - info.verticalScrollbarWidth;
    }
    _getLeft(info) {
      if (info.minimap.minimapWidth > 0 && info.minimap.minimapLeft === 0) {
        return info.minimap.minimapWidth;
      }
      return 0;
    }
    _onViewZoneTop(top) {
      this.domNode.style.top = top + "px";
    }
    _onViewZoneHeight(height) {
      this.domNode.style.height = `${height}px`;
      if (this.container) {
        const containerHeight = height - this._decoratingElementsHeight();
        this.container.style.height = `${containerHeight}px`;
        const layoutInfo = this.editor.getLayoutInfo();
        this._doLayout(containerHeight, this._getWidth(layoutInfo));
      }
      this._resizeSash?.layout();
    }
    get position() {
      const range2 = this._positionMarkerId.getRange(0);
      if (!range2) {
        return void 0;
      }
      return range2.getStartPosition();
    }
    show(rangeOrPos, heightInLines) {
      const range2 = Range$2.isIRange(rangeOrPos) ? Range$2.lift(rangeOrPos) : Range$2.fromPositions(rangeOrPos);
      this._isShowing = true;
      this._showImpl(range2, heightInLines);
      this._isShowing = false;
      this._positionMarkerId.set([{ range: range2, options: ModelDecorationOptions.EMPTY }]);
    }
    hide() {
      if (this._viewZone) {
        this.editor.changeViewZones((accessor) => {
          if (this._viewZone) {
            accessor.removeZone(this._viewZone.id);
          }
        });
        this._viewZone = null;
      }
      if (this._overlayWidget) {
        this.editor.removeOverlayWidget(this._overlayWidget);
        this._overlayWidget = null;
      }
      this._arrow?.hide();
      this._positionMarkerId.clear();
      this._isSashResizeHeight = false;
    }
    _decoratingElementsHeight() {
      const lineHeight = this.editor.getOption(
        75
        /* EditorOption.lineHeight */
      );
      let result = 0;
      if (this.options.showArrow) {
        const arrowHeight = Math.round(lineHeight / 3);
        result += 2 * arrowHeight;
      }
      if (this.options.showFrame) {
        const frameThickness = this.options.frameWidth ?? Math.round(lineHeight / 9);
        result += 2 * frameThickness;
      }
      return result;
    }
    /** Gets the maximum widget height in lines. */
    _getMaximumHeightInLines() {
      return Math.max(12, this.editor.getLayoutInfo().height / this.editor.getOption(
        75
        /* EditorOption.lineHeight */
      ) * 0.8);
    }
    _showImpl(where, heightInLines) {
      const position = where.getStartPosition();
      const layoutInfo = this.editor.getLayoutInfo();
      const width2 = this._getWidth(layoutInfo);
      this.domNode.style.width = `${width2}px`;
      this.domNode.style.left = this._getLeft(layoutInfo) + "px";
      const viewZoneDomNode = document.createElement("div");
      viewZoneDomNode.style.overflow = "hidden";
      const lineHeight = this.editor.getOption(
        75
        /* EditorOption.lineHeight */
      );
      const maxHeightInLines = this._getMaximumHeightInLines();
      if (maxHeightInLines !== void 0) {
        heightInLines = Math.min(heightInLines, maxHeightInLines);
      }
      let arrowHeight = 0;
      let frameThickness = 0;
      if (this._arrow && this.options.showArrow) {
        arrowHeight = Math.round(lineHeight / 3);
        this._arrow.height = arrowHeight;
        this._arrow.show(position);
      }
      if (this.options.showFrame) {
        frameThickness = Math.round(lineHeight / 9);
      }
      this.editor.changeViewZones((accessor) => {
        if (this._viewZone) {
          accessor.removeZone(this._viewZone.id);
        }
        if (this._overlayWidget) {
          this.editor.removeOverlayWidget(this._overlayWidget);
          this._overlayWidget = null;
        }
        this.domNode.style.top = "-1000px";
        this._viewZone = new ViewZoneDelegate(viewZoneDomNode, position.lineNumber, position.column, heightInLines, (top) => this._onViewZoneTop(top), (height) => this._onViewZoneHeight(height), this.options.showInHiddenAreas, this.options.ordinal);
        this._viewZone.id = accessor.addZone(this._viewZone);
        this._overlayWidget = new OverlayWidgetDelegate(WIDGET_ID + this._viewZone.id, this.domNode);
        this.editor.addOverlayWidget(this._overlayWidget);
      });
      this._updateSashEnablement();
      if (this.container && this.options.showFrame) {
        const width3 = this.options.frameWidth ? this.options.frameWidth : frameThickness;
        this.container.style.borderTopWidth = width3 + "px";
        this.container.style.borderBottomWidth = width3 + "px";
      }
      const containerHeight = heightInLines * lineHeight - this._decoratingElementsHeight();
      if (this.container) {
        this.container.style.top = arrowHeight + "px";
        this.container.style.height = containerHeight + "px";
        this.container.style.overflow = "hidden";
      }
      this._doLayout(containerHeight, width2);
      if (!this.options.keepEditorSelection) {
        this.editor.setSelection(where);
      }
      const model = this.editor.getModel();
      if (model) {
        const range2 = model.validateRange(new Range$2(where.startLineNumber, 1, where.endLineNumber + 1, 1));
        this.revealRange(range2, range2.startLineNumber === model.getLineCount());
      }
    }
    revealRange(range2, isLastLine) {
      if (isLastLine) {
        this.editor.revealLineNearTop(
          range2.endLineNumber,
          0
          /* ScrollType.Smooth */
        );
      } else {
        this.editor.revealRange(
          range2,
          0
          /* ScrollType.Smooth */
        );
      }
    }
    setCssClass(className2, classToReplace) {
      if (!this.container) {
        return;
      }
      if (classToReplace) {
        this.container.classList.remove(classToReplace);
      }
      this.container.classList.add(className2);
    }
    _onWidth(widthInPixel) {
    }
    _doLayout(heightInPixel, widthInPixel) {
    }
    _relayout(_newHeightInLines, useMax) {
      const maxHeightInLines = this._getMaximumHeightInLines();
      const newHeightInLines = useMax && maxHeightInLines !== void 0 ? Math.min(maxHeightInLines, _newHeightInLines) : _newHeightInLines;
      if (this._viewZone && this._viewZone.heightInLines !== newHeightInLines) {
        this.editor.changeViewZones((accessor) => {
          if (this._viewZone) {
            this._viewZone.heightInLines = newHeightInLines;
            accessor.layoutZone(this._viewZone.id);
          }
        });
        this._updateSashEnablement();
      }
    }
    // --- sash
    _initSash() {
      if (this._resizeSash) {
        return;
      }
      this._resizeSash = this._disposables.add(new Sash(this.domNode, this, {
        orientation: 1
        /* Orientation.HORIZONTAL */
      }));
      if (!this.options.isResizeable) {
        this._resizeSash.state = 0;
      }
      let data;
      this._disposables.add(this._resizeSash.onDidStart((e) => {
        if (this._viewZone) {
          data = {
            startY: e.startY,
            heightInLines: this._viewZone.heightInLines,
            ...this._getResizeBounds()
          };
        }
      }));
      this._disposables.add(this._resizeSash.onDidEnd(() => {
        data = void 0;
      }));
      this._disposables.add(this._resizeSash.onDidChange((evt) => {
        if (data) {
          const lineDelta = (evt.currentY - data.startY) / this.editor.getOption(
            75
            /* EditorOption.lineHeight */
          );
          const roundedLineDelta = lineDelta < 0 ? Math.ceil(lineDelta) : Math.floor(lineDelta);
          const newHeightInLines = data.heightInLines + roundedLineDelta;
          if (newHeightInLines > data.minLines && newHeightInLines < data.maxLines) {
            this._isSashResizeHeight = true;
            this._relayout(newHeightInLines);
          }
        }
      }));
    }
    _updateSashEnablement() {
      if (this._resizeSash) {
        const { minLines, maxLines } = this._getResizeBounds();
        this._resizeSash.state = minLines === maxLines ? 0 : 3;
      }
    }
    _getResizeBounds() {
      return { minLines: 5, maxLines: 35 };
    }
    getHorizontalSashLeft() {
      return 0;
    }
    getHorizontalSashTop() {
      return (this.domNode.style.height === null ? 0 : parseInt(this.domNode.style.height)) - this._decoratingElementsHeight() / 2;
    }
    getHorizontalSashWidth() {
      const layoutInfo = this.editor.getLayoutInfo();
      return layoutInfo.width - layoutInfo.minimap.minimapWidth;
    }
  }
  var __decorate$23 = 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$21 = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  const IPeekViewService = createDecorator("IPeekViewService");
  registerSingleton(
    IPeekViewService,
    class {
      constructor() {
        this._widgets = /* @__PURE__ */ new Map();
      }
      addExclusiveWidget(editor2, widget) {
        const existing = this._widgets.get(editor2);
        if (existing) {
          existing.listener.dispose();
          existing.widget.dispose();
        }
        const remove = () => {
          const data = this._widgets.get(editor2);
          if (data && data.widget === widget) {
            data.listener.dispose();
            this._widgets.delete(editor2);
          }
        };
        this._widgets.set(editor2, { widget, listener: widget.onDidClose(remove) });
      }
    },
    1
    /* InstantiationType.Delayed */
  );
  var PeekContext;
  (function(PeekContext2) {
    PeekContext2.inPeekEditor = new RawContextKey("inReferenceSearchEditor", true, localize(1316, "Whether the current code editor is embedded inside peek"));
    PeekContext2.notInPeekEditor = PeekContext2.inPeekEditor.toNegated();
  })(PeekContext || (PeekContext = {}));
  let PeekContextController = (_A = class {
    constructor(editor2, contextKeyService) {
      if (editor2 instanceof EmbeddedCodeEditorWidget) {
        PeekContext.inPeekEditor.bindTo(contextKeyService);
      }
    }
    dispose() {
    }
  }, _A.ID = "editor.contrib.referenceController", _A);
  PeekContextController = __decorate$23([
    __param$21(1, IContextKeyService)
  ], PeekContextController);
  registerEditorContribution(
    PeekContextController.ID,
    PeekContextController,
    0
    /* EditorContributionInstantiation.Eager */
  );
  const defaultOptions = {
    headerBackgroundColor: Color.white,
    primaryHeadingColor: Color.fromHex("#333333"),
    secondaryHeadingColor: Color.fromHex("#6c6c6cb3")
  };
  let PeekViewWidget = class PeekViewWidget extends ZoneWidget {
    constructor(editor2, options, instantiationService) {
      super(editor2, options);
      this.instantiationService = instantiationService;
      this._onDidClose = new Emitter$1();
      this.onDidClose = this._onDidClose.event;
      mixin(this.options, defaultOptions, false);
      const e = observableCodeEditor(this.editor);
      e.openedPeekWidgets.set(e.openedPeekWidgets.get() + 1, void 0);
    }
    dispose() {
      if (!this.disposed) {
        this.disposed = true;
        super.dispose();
        this._onDidClose.fire(this);
        const e = observableCodeEditor(this.editor);
        e.openedPeekWidgets.set(e.openedPeekWidgets.get() - 1, void 0);
      }
    }
    style(styles) {
      const options = this.options;
      if (styles.headerBackgroundColor) {
        options.headerBackgroundColor = styles.headerBackgroundColor;
      }
      if (styles.primaryHeadingColor) {
        options.primaryHeadingColor = styles.primaryHeadingColor;
      }
      if (styles.secondaryHeadingColor) {
        options.secondaryHeadingColor = styles.secondaryHeadingColor;
      }
      super.style(styles);
    }
    _applyStyles() {
      super._applyStyles();
      const options = this.options;
      if (this._headElement && options.headerBackgroundColor) {
        this._headElement.style.backgroundColor = options.headerBackgroundColor.toString();
      }
      if (this._primaryHeading && options.primaryHeadingColor) {
        this._primaryHeading.style.color = options.primaryHeadingColor.toString();
      }
      if (this._secondaryHeading && options.secondaryHeadingColor) {
        this._secondaryHeading.style.color = options.secondaryHeadingColor.toString();
      }
      if (this._bodyElement && options.frameColor) {
        this._bodyElement.style.borderColor = options.frameColor.toString();
      }
    }
    _fillContainer(container) {
      this.setCssClass("peekview-widget");
      this._headElement = $$l(".head");
      this._bodyElement = $$l(".body");
      this._fillHead(this._headElement);
      this._fillBody(this._bodyElement);
      container.appendChild(this._headElement);
      container.appendChild(this._bodyElement);
    }
    _fillHead(container, noCloseAction) {
      this._titleElement = $$l(".peekview-title");
      if (this.options.supportOnTitleClick) {
        this._titleElement.classList.add("clickable");
        addStandardDisposableListener(this._titleElement, "click", (event) => this._onTitleClick(event));
      }
      append$2(this._headElement, this._titleElement);
      this._fillTitleIcon(this._titleElement);
      this._primaryHeading = $$l("span.filename");
      this._secondaryHeading = $$l("span.dirname");
      this._metaHeading = $$l("span.meta");
      append$2(this._titleElement, this._primaryHeading, this._secondaryHeading, this._metaHeading);
      const actionsContainer = $$l(".peekview-actions");
      append$2(this._headElement, actionsContainer);
      const actionBarOptions = this._getActionBarOptions();
      this._actionbarWidget = new ActionBar(actionsContainer, actionBarOptions);
      this._disposables.add(this._actionbarWidget);
      if (!noCloseAction) {
        this._actionbarWidget.push(this._disposables.add(new Action("peekview.close", localize(1317, "Close"), ThemeIcon.asClassName(Codicon.close), true, () => {
          this.dispose();
          return Promise.resolve();
        })), { label: false, icon: true });
      }
    }
    _fillTitleIcon(container) {
    }
    _getActionBarOptions() {
      return {
        actionViewItemProvider: createActionViewItem.bind(void 0, this.instantiationService),
        orientation: 0
        /* ActionsOrientation.HORIZONTAL */
      };
    }
    _onTitleClick(event) {
    }
    setTitle(primaryHeading, secondaryHeading) {
      if (this._primaryHeading && this._secondaryHeading) {
        this._primaryHeading.innerText = primaryHeading;
        this._primaryHeading.setAttribute("title", primaryHeading);
        if (secondaryHeading) {
          this._secondaryHeading.innerText = secondaryHeading;
        } else {
          clearNode(this._secondaryHeading);
        }
      }
    }
    setMetaTitle(value) {
      if (this._metaHeading) {
        if (value) {
          this._metaHeading.innerText = value;
          show(this._metaHeading);
        } else {
          hide(this._metaHeading);
        }
      }
    }
    _doLayout(heightInPixel, widthInPixel) {
      if (!this._isShowing && heightInPixel < 0) {
        this.dispose();
        return;
      }
      const headHeight = Math.ceil(this.editor.getOption(
        75
        /* EditorOption.lineHeight */
      ) * 1.2);
      const bodyHeight = Math.round(heightInPixel - (headHeight + 1));
      this._doLayoutHead(headHeight, widthInPixel);
      this._doLayoutBody(bodyHeight, widthInPixel);
    }
    _doLayoutHead(heightInPixel, widthInPixel) {
      if (this._headElement) {
        this._headElement.style.height = `${heightInPixel}px`;
        this._headElement.style.lineHeight = this._headElement.style.height;
      }
    }
    _doLayoutBody(heightInPixel, widthInPixel) {
      if (this._bodyElement) {
        this._bodyElement.style.height = `${heightInPixel}px`;
      }
    }
  };
  PeekViewWidget = __decorate$23([
    __param$21(2, IInstantiationService)
  ], PeekViewWidget);
  const peekViewTitleBackground = registerColor("peekViewTitle.background", { dark: "#252526", light: "#F3F3F3", hcDark: Color.black, hcLight: Color.white }, localize(1318, "Background color of the peek view title area."));
  const peekViewTitleForeground = registerColor("peekViewTitleLabel.foreground", { dark: Color.white, light: Color.black, hcDark: Color.white, hcLight: editorForeground }, localize(1319, "Color of the peek view title."));
  const peekViewTitleInfoForeground = registerColor("peekViewTitleDescription.foreground", { dark: "#ccccccb3", light: "#616161", hcDark: "#FFFFFF99", hcLight: "#292929" }, localize(1320, "Color of the peek view title info."));
  const peekViewBorder = registerColor("peekView.border", { dark: editorInfoForeground, light: editorInfoForeground, hcDark: contrastBorder, hcLight: contrastBorder }, localize(1321, "Color of the peek view borders and arrow."));
  const peekViewResultsBackground = registerColor("peekViewResult.background", { dark: "#252526", light: "#F3F3F3", hcDark: Color.black, hcLight: Color.white }, localize(1322, "Background color of the peek view result list."));
  registerColor("peekViewResult.lineForeground", { dark: "#bbbbbb", light: "#646465", hcDark: Color.white, hcLight: editorForeground }, localize(1323, "Foreground color for line nodes in the peek view result list."));
  registerColor("peekViewResult.fileForeground", { dark: Color.white, light: "#1E1E1E", hcDark: Color.white, hcLight: editorForeground }, localize(1324, "Foreground color for file nodes in the peek view result list."));
  registerColor("peekViewResult.selectionBackground", { dark: "#3399ff33", light: "#3399ff33", hcDark: null, hcLight: null }, localize(1325, "Background color of the selected entry in the peek view result list."));
  registerColor("peekViewResult.selectionForeground", { dark: Color.white, light: "#6C6C6C", hcDark: Color.white, hcLight: editorForeground }, localize(1326, "Foreground color of the selected entry in the peek view result list."));
  const peekViewEditorBackground = registerColor("peekViewEditor.background", { dark: "#001F33", light: "#F2F8FC", hcDark: Color.black, hcLight: Color.white }, localize(1327, "Background color of the peek view editor."));
  registerColor("peekViewEditorGutter.background", peekViewEditorBackground, localize(1328, "Background color of the gutter in the peek view editor."));
  registerColor("peekViewEditorStickyScroll.background", peekViewEditorBackground, localize(1329, "Background color of sticky scroll in the peek view editor."));
  registerColor("peekViewEditorStickyScrollGutter.background", peekViewEditorBackground, localize(1330, "Background color of the gutter part of sticky scroll in the peek view editor."));
  registerColor("peekViewResult.matchHighlightBackground", { dark: "#ea5c004d", light: "#ea5c004d", hcDark: null, hcLight: null }, localize(1331, "Match highlight color in the peek view result list."));
  registerColor("peekViewEditor.matchHighlightBackground", { dark: "#ff8f0099", light: "#f5d802de", hcDark: null, hcLight: null }, localize(1332, "Match highlight color in the peek view editor."));
  registerColor("peekViewEditor.matchHighlightBorder", { dark: null, light: null, hcDark: activeContrastBorder, hcLight: activeContrastBorder }, localize(1333, "Match highlight border in the peek view editor."));
  class PagedRenderer {
    get templateId() {
      return this.renderer.templateId;
    }
    constructor(renderer, modelProvider) {
      this.renderer = renderer;
      this.modelProvider = modelProvider;
    }
    renderTemplate(container) {
      const data = this.renderer.renderTemplate(container);
      return { data, disposable: Disposable.None };
    }
    renderElement(index, _, data, details) {
      data.disposable?.dispose();
      if (!data.data) {
        return;
      }
      const model = this.modelProvider();
      if (model.isResolved(index)) {
        return this.renderer.renderElement(model.get(index), index, data.data, details);
      }
      const cts = new CancellationTokenSource$1();
      const promise = model.resolve(index, cts.token);
      data.disposable = { dispose: () => cts.cancel() };
      this.renderer.renderPlaceholder(index, data.data);
      promise.then((entry) => this.renderer.renderElement(entry, index, data.data, details));
    }
    disposeTemplate(data) {
      if (data.disposable) {
        data.disposable.dispose();
        data.disposable = void 0;
      }
      if (data.data) {
        this.renderer.disposeTemplate(data.data);
        data.data = void 0;
      }
    }
  }
  class PagedAccessibilityProvider {
    constructor(modelProvider, accessibilityProvider) {
      this.modelProvider = modelProvider;
      this.accessibilityProvider = accessibilityProvider;
    }
    getWidgetAriaLabel() {
      return this.accessibilityProvider.getWidgetAriaLabel();
    }
    getAriaLabel(index) {
      const model = this.modelProvider();
      if (!model.isResolved(index)) {
        return null;
      }
      return this.accessibilityProvider.getAriaLabel(model.get(index));
    }
  }
  function fromPagedListOptions(modelProvider, options) {
    return {
      ...options,
      accessibilityProvider: options.accessibilityProvider && new PagedAccessibilityProvider(modelProvider, options.accessibilityProvider)
    };
  }
  class PagedList {
    constructor(user, container, virtualDelegate, renderers, options = {}) {
      this.modelDisposables = new DisposableStore();
      const modelProvider = () => this.model;
      const pagedRenderers = renderers.map((r) => new PagedRenderer(r, modelProvider));
      this.list = new List(user, container, virtualDelegate, pagedRenderers, fromPagedListOptions(modelProvider, options));
    }
    updateOptions(options) {
      this.list.updateOptions(options);
    }
    getHTMLElement() {
      return this.list.getHTMLElement();
    }
    get onDidFocus() {
      return this.list.onDidFocus;
    }
    get widget() {
      return this.list;
    }
    get onDidDispose() {
      return this.list.onDidDispose;
    }
    get onMouseDblClick() {
      return Event.map(this.list.onMouseDblClick, ({ element, index, browserEvent }) => ({ element: element === void 0 ? void 0 : this._model.get(element), index, browserEvent }));
    }
    get onPointer() {
      return Event.map(this.list.onPointer, ({ element, index, browserEvent }) => ({ element: element === void 0 ? void 0 : this._model.get(element), index, browserEvent }));
    }
    get onDidChangeSelection() {
      return Event.map(this.list.onDidChangeSelection, ({ elements, indexes, browserEvent }) => ({ elements: elements.map((e) => this._model.get(e)), indexes, browserEvent }));
    }
    get model() {
      return this._model;
    }
    set model(model) {
      this.modelDisposables.clear();
      this._model = model;
      this.list.splice(0, this.list.length, range(model.length));
      this.modelDisposables.add(model.onDidIncrementLength((newLength) => this.list.splice(this.list.length, 0, range(this.list.length, newLength))));
    }
    getFocus() {
      return this.list.getFocus();
    }
    getSelection() {
      return this.list.getSelection();
    }
    getSelectedElements() {
      return this.getSelection().map((i2) => this.model.get(i2));
    }
    style(styles) {
      this.list.style(styles);
    }
    dispose() {
      this.list.dispose();
      this.modelDisposables.dispose();
    }
  }
  const defaultStyles = {
    separatorBorder: Color.transparent
  };
  class ViewItem {
    set size(size2) {
      this._size = size2;
    }
    get size() {
      return this._size;
    }
    get visible() {
      return typeof this._cachedVisibleSize === "undefined";
    }
    setVisible(visible, size2) {
      if (visible === this.visible) {
        return;
      }
      if (visible) {
        this.size = clamp(this._cachedVisibleSize, this.viewMinimumSize, this.viewMaximumSize);
        this._cachedVisibleSize = void 0;
      } else {
        this._cachedVisibleSize = typeof size2 === "number" ? size2 : this.size;
        this.size = 0;
      }
      this.container.classList.toggle("visible", visible);
      try {
        this.view.setVisible?.(visible);
      } catch (e) {
        console.error("Splitview: Failed to set visible view");
        console.error(e);
      }
    }
    get minimumSize() {
      return this.visible ? this.view.minimumSize : 0;
    }
    get viewMinimumSize() {
      return this.view.minimumSize;
    }
    get maximumSize() {
      return this.visible ? this.view.maximumSize : 0;
    }
    get viewMaximumSize() {
      return this.view.maximumSize;
    }
    get priority() {
      return this.view.priority;
    }
    get proportionalLayout() {
      return this.view.proportionalLayout ?? true;
    }
    get snap() {
      return !!this.view.snap;
    }
    set enabled(enabled) {
      this.container.style.pointerEvents = enabled ? "" : "none";
    }
    constructor(container, view, size2, disposable) {
      this.container = container;
      this.view = view;
      this.disposable = disposable;
      this._cachedVisibleSize = void 0;
      if (typeof size2 === "number") {
        this._size = size2;
        this._cachedVisibleSize = void 0;
        container.classList.add("visible");
      } else {
        this._size = 0;
        this._cachedVisibleSize = size2.cachedVisibleSize;
      }
    }
    layout(offset, layoutContext) {
      this.layoutContainer(offset);
      try {
        this.view.layout(this.size, offset, layoutContext);
      } catch (e) {
        console.error("Splitview: Failed to layout view");
        console.error(e);
      }
    }
    dispose() {
      this.disposable.dispose();
    }
  }
  class VerticalViewItem extends ViewItem {
    layoutContainer(offset) {
      this.container.style.top = `${offset}px`;
      this.container.style.height = `${this.size}px`;
    }
  }
  class HorizontalViewItem extends ViewItem {
    layoutContainer(offset) {
      this.container.style.left = `${offset}px`;
      this.container.style.width = `${this.size}px`;
    }
  }
  var State;
  (function(State2) {
    State2[State2["Idle"] = 0] = "Idle";
    State2[State2["Busy"] = 1] = "Busy";
  })(State || (State = {}));
  var Sizing;
  (function(Sizing2) {
    Sizing2.Distribute = { type: "distribute" };
    function Split(index) {
      return { type: "split", index };
    }
    Sizing2.Split = Split;
    function Auto(index) {
      return { type: "auto", index };
    }
    Sizing2.Auto = Auto;
    function Invisible(cachedVisibleSize) {
      return { type: "invisible", cachedVisibleSize };
    }
    Sizing2.Invisible = Invisible;
  })(Sizing || (Sizing = {}));
  class SplitView extends Disposable {
    get orthogonalStartSash() {
      return this._orthogonalStartSash;
    }
    get orthogonalEndSash() {
      return this._orthogonalEndSash;
    }
    get startSnappingEnabled() {
      return this._startSnappingEnabled;
    }
    get endSnappingEnabled() {
      return this._endSnappingEnabled;
    }
    /**
     * A reference to a sash, perpendicular to all sashes in this {@link SplitView},
     * located at the left- or top-most side of the SplitView.
     * Corner sashes will be created automatically at the intersections.
     */
    set orthogonalStartSash(sash) {
      for (const sashItem of this.sashItems) {
        sashItem.sash.orthogonalStartSash = sash;
      }
      this._orthogonalStartSash = sash;
    }
    /**
     * A reference to a sash, perpendicular to all sashes in this {@link SplitView},
     * located at the right- or bottom-most side of the SplitView.
     * Corner sashes will be created automatically at the intersections.
     */
    set orthogonalEndSash(sash) {
      for (const sashItem of this.sashItems) {
        sashItem.sash.orthogonalEndSash = sash;
      }
      this._orthogonalEndSash = sash;
    }
    /**
     * Enable/disable snapping at the beginning of this {@link SplitView}.
     */
    set startSnappingEnabled(startSnappingEnabled) {
      if (this._startSnappingEnabled === startSnappingEnabled) {
        return;
      }
      this._startSnappingEnabled = startSnappingEnabled;
      this.updateSashEnablement();
    }
    /**
     * Enable/disable snapping at the end of this {@link SplitView}.
     */
    set endSnappingEnabled(endSnappingEnabled) {
      if (this._endSnappingEnabled === endSnappingEnabled) {
        return;
      }
      this._endSnappingEnabled = endSnappingEnabled;
      this.updateSashEnablement();
    }
    /**
     * Create a new {@link SplitView} instance.
     */
    constructor(container, options = {}) {
      super();
      this.size = 0;
      this._contentSize = 0;
      this.proportions = void 0;
      this.viewItems = [];
      this.sashItems = [];
      this.state = State.Idle;
      this._onDidSashChange = this._register(new Emitter$1());
      this._onDidSashReset = this._register(new Emitter$1());
      this._startSnappingEnabled = true;
      this._endSnappingEnabled = true;
      this.onDidSashChange = this._onDidSashChange.event;
      this.onDidSashReset = this._onDidSashReset.event;
      this.orientation = options.orientation ?? 0;
      this.inverseAltBehavior = options.inverseAltBehavior ?? false;
      this.proportionalLayout = options.proportionalLayout ?? true;
      this.getSashOrthogonalSize = options.getSashOrthogonalSize;
      this.el = document.createElement("div");
      this.el.classList.add("monaco-split-view2");
      this.el.classList.add(this.orientation === 0 ? "vertical" : "horizontal");
      container.appendChild(this.el);
      this.sashContainer = append$2(this.el, $$l(".sash-container"));
      this.viewContainer = $$l(".split-view-container");
      this.scrollable = this._register(new Scrollable({
        forceIntegerValues: true,
        smoothScrollDuration: 125,
        scheduleAtNextAnimationFrame: (callback) => scheduleAtNextAnimationFrame(getWindow(this.el), callback)
      }));
      this.scrollableElement = this._register(new SmoothScrollableElement(this.viewContainer, {
        vertical: this.orientation === 0 ? options.scrollbarVisibility ?? 1 : 2,
        horizontal: this.orientation === 1 ? options.scrollbarVisibility ?? 1 : 2
        /* ScrollbarVisibility.Hidden */
      }, this.scrollable));
      const onDidScrollViewContainer = this._register(new DomEmitter(this.viewContainer, "scroll")).event;
      this._register(onDidScrollViewContainer((_) => {
        const position = this.scrollableElement.getScrollPosition();
        const scrollLeft = Math.abs(this.viewContainer.scrollLeft - position.scrollLeft) <= 1 ? void 0 : this.viewContainer.scrollLeft;
        const scrollTop = Math.abs(this.viewContainer.scrollTop - position.scrollTop) <= 1 ? void 0 : this.viewContainer.scrollTop;
        if (scrollLeft !== void 0 || scrollTop !== void 0) {
          this.scrollableElement.setScrollPosition({ scrollLeft, scrollTop });
        }
      }));
      this.onDidScroll = this.scrollableElement.onScroll;
      this._register(this.onDidScroll((e) => {
        if (e.scrollTopChanged) {
          this.viewContainer.scrollTop = e.scrollTop;
        }
        if (e.scrollLeftChanged) {
          this.viewContainer.scrollLeft = e.scrollLeft;
        }
      }));
      append$2(this.el, this.scrollableElement.getDomNode());
      this.style(options.styles || defaultStyles);
      if (options.descriptor) {
        this.size = options.descriptor.size;
        options.descriptor.views.forEach((viewDescriptor, index) => {
          const sizing = isUndefined(viewDescriptor.visible) || viewDescriptor.visible ? viewDescriptor.size : { type: "invisible", cachedVisibleSize: viewDescriptor.size };
          const view = viewDescriptor.view;
          this.doAddView(view, sizing, index, true);
        });
        this._contentSize = this.viewItems.reduce((r, i2) => r + i2.size, 0);
        this.saveProportions();
      }
    }
    style(styles) {
      if (styles.separatorBorder.isTransparent()) {
        this.el.classList.remove("separator-border");
        this.el.style.removeProperty("--separator-border");
      } else {
        this.el.classList.add("separator-border");
        this.el.style.setProperty("--separator-border", styles.separatorBorder.toString());
      }
    }
    /**
     * Add a {@link IView view} to this {@link SplitView}.
     *
     * @param view The view to add.
     * @param size Either a fixed size, or a dynamic {@link Sizing} strategy.
     * @param index The index to insert the view on.
     * @param skipLayout Whether layout should be skipped.
     */
    addView(view, size2, index = this.viewItems.length, skipLayout) {
      this.doAddView(view, size2, index, skipLayout);
    }
    /**
     * Layout the {@link SplitView}.
     *
     * @param size The entire size of the {@link SplitView}.
     * @param layoutContext An optional layout context to pass along to {@link IView views}.
     */
    layout(size2, layoutContext) {
      const previousSize = Math.max(this.size, this._contentSize);
      this.size = size2;
      this.layoutContext = layoutContext;
      if (!this.proportions) {
        const indexes = range(this.viewItems.length);
        const lowPriorityIndexes = indexes.filter(
          (i2) => this.viewItems[i2].priority === 1
          /* LayoutPriority.Low */
        );
        const highPriorityIndexes = indexes.filter(
          (i2) => this.viewItems[i2].priority === 2
          /* LayoutPriority.High */
        );
        this.resize(this.viewItems.length - 1, size2 - previousSize, void 0, lowPriorityIndexes, highPriorityIndexes);
      } else {
        let total = 0;
        for (let i2 = 0; i2 < this.viewItems.length; i2++) {
          const item = this.viewItems[i2];
          const proportion = this.proportions[i2];
          if (typeof proportion === "number") {
            total += proportion;
          } else {
            size2 -= item.size;
          }
        }
        for (let i2 = 0; i2 < this.viewItems.length; i2++) {
          const item = this.viewItems[i2];
          const proportion = this.proportions[i2];
          if (typeof proportion === "number" && total > 0) {
            item.size = clamp(Math.round(proportion * size2 / total), item.minimumSize, item.maximumSize);
          }
        }
      }
      this.distributeEmptySpace();
      this.layoutViews();
    }
    saveProportions() {
      if (this.proportionalLayout && this._contentSize > 0) {
        this.proportions = this.viewItems.map((v) => v.proportionalLayout && v.visible ? v.size / this._contentSize : void 0);
      }
    }
    onSashStart({ sash, start, alt }) {
      for (const item of this.viewItems) {
        item.enabled = false;
      }
      const index = this.sashItems.findIndex((item) => item.sash === sash);
      const disposable = combinedDisposable(addDisposableListener(this.el.ownerDocument.body, "keydown", (e) => resetSashDragState(this.sashDragState.current, e.altKey)), addDisposableListener(this.el.ownerDocument.body, "keyup", () => resetSashDragState(this.sashDragState.current, false)));
      const resetSashDragState = (start2, alt2) => {
        const sizes = this.viewItems.map((i2) => i2.size);
        let minDelta = Number.NEGATIVE_INFINITY;
        let maxDelta = Number.POSITIVE_INFINITY;
        if (this.inverseAltBehavior) {
          alt2 = !alt2;
        }
        if (alt2) {
          const isLastSash = index === this.sashItems.length - 1;
          if (isLastSash) {
            const viewItem = this.viewItems[index];
            minDelta = (viewItem.minimumSize - viewItem.size) / 2;
            maxDelta = (viewItem.maximumSize - viewItem.size) / 2;
          } else {
            const viewItem = this.viewItems[index + 1];
            minDelta = (viewItem.size - viewItem.maximumSize) / 2;
            maxDelta = (viewItem.size - viewItem.minimumSize) / 2;
          }
        }
        let snapBefore;
        let snapAfter;
        if (!alt2) {
          const upIndexes = range(index, -1);
          const downIndexes = range(index + 1, this.viewItems.length);
          const minDeltaUp = upIndexes.reduce((r, i2) => r + (this.viewItems[i2].minimumSize - sizes[i2]), 0);
          const maxDeltaUp = upIndexes.reduce((r, i2) => r + (this.viewItems[i2].viewMaximumSize - sizes[i2]), 0);
          const maxDeltaDown = downIndexes.length === 0 ? Number.POSITIVE_INFINITY : downIndexes.reduce((r, i2) => r + (sizes[i2] - this.viewItems[i2].minimumSize), 0);
          const minDeltaDown = downIndexes.length === 0 ? Number.NEGATIVE_INFINITY : downIndexes.reduce((r, i2) => r + (sizes[i2] - this.viewItems[i2].viewMaximumSize), 0);
          const minDelta2 = Math.max(minDeltaUp, minDeltaDown);
          const maxDelta2 = Math.min(maxDeltaDown, maxDeltaUp);
          const snapBeforeIndex = this.findFirstSnapIndex(upIndexes);
          const snapAfterIndex = this.findFirstSnapIndex(downIndexes);
          if (typeof snapBeforeIndex === "number") {
            const viewItem = this.viewItems[snapBeforeIndex];
            const halfSize = Math.floor(viewItem.viewMinimumSize / 2);
            snapBefore = {
              index: snapBeforeIndex,
              limitDelta: viewItem.visible ? minDelta2 - halfSize : minDelta2 + halfSize,
              size: viewItem.size
            };
          }
          if (typeof snapAfterIndex === "number") {
            const viewItem = this.viewItems[snapAfterIndex];
            const halfSize = Math.floor(viewItem.viewMinimumSize / 2);
            snapAfter = {
              index: snapAfterIndex,
              limitDelta: viewItem.visible ? maxDelta2 + halfSize : maxDelta2 - halfSize,
              size: viewItem.size
            };
          }
        }
        this.sashDragState = { start: start2, current: start2, index, sizes, minDelta, maxDelta, alt: alt2, snapBefore, snapAfter, disposable };
      };
      resetSashDragState(start, alt);
    }
    onSashChange({ current }) {
      const { index, start, sizes, alt, minDelta, maxDelta, snapBefore, snapAfter } = this.sashDragState;
      this.sashDragState.current = current;
      const delta = current - start;
      const newDelta = this.resize(index, delta, sizes, void 0, void 0, minDelta, maxDelta, snapBefore, snapAfter);
      if (alt) {
        const isLastSash = index === this.sashItems.length - 1;
        const newSizes = this.viewItems.map((i2) => i2.size);
        const viewItemIndex = isLastSash ? index : index + 1;
        const viewItem = this.viewItems[viewItemIndex];
        const newMinDelta = viewItem.size - viewItem.maximumSize;
        const newMaxDelta = viewItem.size - viewItem.minimumSize;
        const resizeIndex = isLastSash ? index - 1 : index + 1;
        this.resize(resizeIndex, -newDelta, newSizes, void 0, void 0, newMinDelta, newMaxDelta);
      }
      this.distributeEmptySpace();
      this.layoutViews();
    }
    onSashEnd(index) {
      this._onDidSashChange.fire(index);
      this.sashDragState.disposable.dispose();
      this.saveProportions();
      for (const item of this.viewItems) {
        item.enabled = true;
      }
    }
    onViewChange(item, size2) {
      const index = this.viewItems.indexOf(item);
      if (index < 0 || index >= this.viewItems.length) {
        return;
      }
      size2 = typeof size2 === "number" ? size2 : item.size;
      size2 = clamp(size2, item.minimumSize, item.maximumSize);
      if (this.inverseAltBehavior && index > 0) {
        this.resize(index - 1, Math.floor((item.size - size2) / 2));
        this.distributeEmptySpace();
        this.layoutViews();
      } else {
        item.size = size2;
        this.relayout([index], void 0);
      }
    }
    /**
     * Resize a {@link IView view} within the {@link SplitView}.
     *
     * @param index The {@link IView view} index.
     * @param size The {@link IView view} size.
     */
    resizeView(index, size2) {
      if (index < 0 || index >= this.viewItems.length) {
        return;
      }
      if (this.state !== State.Idle) {
        throw new Error("Cant modify splitview");
      }
      this.state = State.Busy;
      try {
        const indexes = range(this.viewItems.length).filter((i2) => i2 !== index);
        const lowPriorityIndexes = [...indexes.filter(
          (i2) => this.viewItems[i2].priority === 1
          /* LayoutPriority.Low */
        ), index];
        const highPriorityIndexes = indexes.filter(
          (i2) => this.viewItems[i2].priority === 2
          /* LayoutPriority.High */
        );
        const item = this.viewItems[index];
        size2 = Math.round(size2);
        size2 = clamp(size2, item.minimumSize, Math.min(item.maximumSize, this.size));
        item.size = size2;
        this.relayout(lowPriorityIndexes, highPriorityIndexes);
      } finally {
        this.state = State.Idle;
      }
    }
    /**
     * Distribute the entire {@link SplitView} size among all {@link IView views}.
     */
    distributeViewSizes() {
      const flexibleViewItems = [];
      let flexibleSize = 0;
      for (const item of this.viewItems) {
        if (item.maximumSize - item.minimumSize > 0) {
          flexibleViewItems.push(item);
          flexibleSize += item.size;
        }
      }
      const size2 = Math.floor(flexibleSize / flexibleViewItems.length);
      for (const item of flexibleViewItems) {
        item.size = clamp(size2, item.minimumSize, item.maximumSize);
      }
      const indexes = range(this.viewItems.length);
      const lowPriorityIndexes = indexes.filter(
        (i2) => this.viewItems[i2].priority === 1
        /* LayoutPriority.Low */
      );
      const highPriorityIndexes = indexes.filter(
        (i2) => this.viewItems[i2].priority === 2
        /* LayoutPriority.High */
      );
      this.relayout(lowPriorityIndexes, highPriorityIndexes);
    }
    /**
     * Returns the size of a {@link IView view}.
     */
    getViewSize(index) {
      if (index < 0 || index >= this.viewItems.length) {
        return -1;
      }
      return this.viewItems[index].size;
    }
    doAddView(view, size2, index = this.viewItems.length, skipLayout) {
      if (this.state !== State.Idle) {
        throw new Error("Cant modify splitview");
      }
      this.state = State.Busy;
      try {
        const container = $$l(".split-view-view");
        if (index === this.viewItems.length) {
          this.viewContainer.appendChild(container);
        } else {
          this.viewContainer.insertBefore(container, this.viewContainer.children.item(index));
        }
        const onChangeDisposable = view.onDidChange((size3) => this.onViewChange(item, size3));
        const containerDisposable = toDisposable(() => container.remove());
        const disposable = combinedDisposable(onChangeDisposable, containerDisposable);
        let viewSize;
        if (typeof size2 === "number") {
          viewSize = size2;
        } else {
          if (size2.type === "auto") {
            if (this.areViewsDistributed()) {
              size2 = { type: "distribute" };
            } else {
              size2 = { type: "split", index: size2.index };
            }
          }
          if (size2.type === "split") {
            viewSize = this.getViewSize(size2.index) / 2;
          } else if (size2.type === "invisible") {
            viewSize = { cachedVisibleSize: size2.cachedVisibleSize };
          } else {
            viewSize = view.minimumSize;
          }
        }
        const item = this.orientation === 0 ? new VerticalViewItem(container, view, viewSize, disposable) : new HorizontalViewItem(container, view, viewSize, disposable);
        this.viewItems.splice(index, 0, item);
        if (this.viewItems.length > 1) {
          const opts = { orthogonalStartSash: this.orthogonalStartSash, orthogonalEndSash: this.orthogonalEndSash };
          const sash = this.orientation === 0 ? new Sash(this.sashContainer, { getHorizontalSashTop: (s) => this.getSashPosition(s), getHorizontalSashWidth: this.getSashOrthogonalSize }, {
            ...opts,
            orientation: 1
            /* Orientation.HORIZONTAL */
          }) : new Sash(this.sashContainer, { getVerticalSashLeft: (s) => this.getSashPosition(s), getVerticalSashHeight: this.getSashOrthogonalSize }, {
            ...opts,
            orientation: 0
            /* Orientation.VERTICAL */
          });
          const sashEventMapper = this.orientation === 0 ? (e) => ({ sash, start: e.startY, current: e.currentY, alt: e.altKey }) : (e) => ({ sash, start: e.startX, current: e.currentX, alt: e.altKey });
          const onStart = Event.map(sash.onDidStart, sashEventMapper);
          const onStartDisposable = onStart(this.onSashStart, this);
          const onChange = Event.map(sash.onDidChange, sashEventMapper);
          const onChangeDisposable2 = onChange(this.onSashChange, this);
          const onEnd = Event.map(sash.onDidEnd, () => this.sashItems.findIndex((item2) => item2.sash === sash));
          const onEndDisposable = onEnd(this.onSashEnd, this);
          const onDidResetDisposable = sash.onDidReset(() => {
            const index2 = this.sashItems.findIndex((item2) => item2.sash === sash);
            const upIndexes = range(index2, -1);
            const downIndexes = range(index2 + 1, this.viewItems.length);
            const snapBeforeIndex = this.findFirstSnapIndex(upIndexes);
            const snapAfterIndex = this.findFirstSnapIndex(downIndexes);
            if (typeof snapBeforeIndex === "number" && !this.viewItems[snapBeforeIndex].visible) {
              return;
            }
            if (typeof snapAfterIndex === "number" && !this.viewItems[snapAfterIndex].visible) {
              return;
            }
            this._onDidSashReset.fire(index2);
          });
          const disposable2 = combinedDisposable(onStartDisposable, onChangeDisposable2, onEndDisposable, onDidResetDisposable, sash);
          const sashItem = { sash, disposable: disposable2 };
          this.sashItems.splice(index - 1, 0, sashItem);
        }
        container.appendChild(view.element);
        let highPriorityIndexes;
        if (typeof size2 !== "number" && size2.type === "split") {
          highPriorityIndexes = [size2.index];
        }
        if (!skipLayout) {
          this.relayout([index], highPriorityIndexes);
        }
        if (!skipLayout && typeof size2 !== "number" && size2.type === "distribute") {
          this.distributeViewSizes();
        }
      } finally {
        this.state = State.Idle;
      }
    }
    relayout(lowPriorityIndexes, highPriorityIndexes) {
      const contentSize = this.viewItems.reduce((r, i2) => r + i2.size, 0);
      this.resize(this.viewItems.length - 1, this.size - contentSize, void 0, lowPriorityIndexes, highPriorityIndexes);
      this.distributeEmptySpace();
      this.layoutViews();
      this.saveProportions();
    }
    resize(index, delta, sizes = this.viewItems.map((i2) => i2.size), lowPriorityIndexes, highPriorityIndexes, overloadMinDelta = Number.NEGATIVE_INFINITY, overloadMaxDelta = Number.POSITIVE_INFINITY, snapBefore, snapAfter) {
      if (index < 0 || index >= this.viewItems.length) {
        return 0;
      }
      const upIndexes = range(index, -1);
      const downIndexes = range(index + 1, this.viewItems.length);
      if (highPriorityIndexes) {
        for (const index2 of highPriorityIndexes) {
          pushToStart(upIndexes, index2);
          pushToStart(downIndexes, index2);
        }
      }
      if (lowPriorityIndexes) {
        for (const index2 of lowPriorityIndexes) {
          pushToEnd(upIndexes, index2);
          pushToEnd(downIndexes, index2);
        }
      }
      const upItems = upIndexes.map((i2) => this.viewItems[i2]);
      const upSizes = upIndexes.map((i2) => sizes[i2]);
      const downItems = downIndexes.map((i2) => this.viewItems[i2]);
      const downSizes = downIndexes.map((i2) => sizes[i2]);
      const minDeltaUp = upIndexes.reduce((r, i2) => r + (this.viewItems[i2].minimumSize - sizes[i2]), 0);
      const maxDeltaUp = upIndexes.reduce((r, i2) => r + (this.viewItems[i2].maximumSize - sizes[i2]), 0);
      const maxDeltaDown = downIndexes.length === 0 ? Number.POSITIVE_INFINITY : downIndexes.reduce((r, i2) => r + (sizes[i2] - this.viewItems[i2].minimumSize), 0);
      const minDeltaDown = downIndexes.length === 0 ? Number.NEGATIVE_INFINITY : downIndexes.reduce((r, i2) => r + (sizes[i2] - this.viewItems[i2].maximumSize), 0);
      const minDelta = Math.max(minDeltaUp, minDeltaDown, overloadMinDelta);
      const maxDelta = Math.min(maxDeltaDown, maxDeltaUp, overloadMaxDelta);
      let snapped = false;
      if (snapBefore) {
        const snapView = this.viewItems[snapBefore.index];
        const visible = delta >= snapBefore.limitDelta;
        snapped = visible !== snapView.visible;
        snapView.setVisible(visible, snapBefore.size);
      }
      if (!snapped && snapAfter) {
        const snapView = this.viewItems[snapAfter.index];
        const visible = delta < snapAfter.limitDelta;
        snapped = visible !== snapView.visible;
        snapView.setVisible(visible, snapAfter.size);
      }
      if (snapped) {
        return this.resize(index, delta, sizes, lowPriorityIndexes, highPriorityIndexes, overloadMinDelta, overloadMaxDelta);
      }
      delta = clamp(delta, minDelta, maxDelta);
      for (let i2 = 0, deltaUp = delta; i2 < upItems.length; i2++) {
        const item = upItems[i2];
        const size2 = clamp(upSizes[i2] + deltaUp, item.minimumSize, item.maximumSize);
        const viewDelta = size2 - upSizes[i2];
        deltaUp -= viewDelta;
        item.size = size2;
      }
      for (let i2 = 0, deltaDown = delta; i2 < downItems.length; i2++) {
        const item = downItems[i2];
        const size2 = clamp(downSizes[i2] - deltaDown, item.minimumSize, item.maximumSize);
        const viewDelta = size2 - downSizes[i2];
        deltaDown += viewDelta;
        item.size = size2;
      }
      return delta;
    }
    distributeEmptySpace(lowPriorityIndex) {
      const contentSize = this.viewItems.reduce((r, i2) => r + i2.size, 0);
      let emptyDelta = this.size - contentSize;
      const indexes = range(this.viewItems.length - 1, -1);
      const lowPriorityIndexes = indexes.filter(
        (i2) => this.viewItems[i2].priority === 1
        /* LayoutPriority.Low */
      );
      const highPriorityIndexes = indexes.filter(
        (i2) => this.viewItems[i2].priority === 2
        /* LayoutPriority.High */
      );
      for (const index of highPriorityIndexes) {
        pushToStart(indexes, index);
      }
      for (const index of lowPriorityIndexes) {
        pushToEnd(indexes, index);
      }
      if (typeof lowPriorityIndex === "number") {
        pushToEnd(indexes, lowPriorityIndex);
      }
      for (let i2 = 0; emptyDelta !== 0 && i2 < indexes.length; i2++) {
        const item = this.viewItems[indexes[i2]];
        const size2 = clamp(item.size + emptyDelta, item.minimumSize, item.maximumSize);
        const viewDelta = size2 - item.size;
        emptyDelta -= viewDelta;
        item.size = size2;
      }
    }
    layoutViews() {
      this._contentSize = this.viewItems.reduce((r, i2) => r + i2.size, 0);
      let offset = 0;
      for (const viewItem of this.viewItems) {
        viewItem.layout(offset, this.layoutContext);
        offset += viewItem.size;
      }
      this.sashItems.forEach((item) => item.sash.layout());
      this.updateSashEnablement();
      this.updateScrollableElement();
    }
    updateScrollableElement() {
      if (this.orientation === 0) {
        this.scrollableElement.setScrollDimensions({
          height: this.size,
          scrollHeight: this._contentSize
        });
      } else {
        this.scrollableElement.setScrollDimensions({
          width: this.size,
          scrollWidth: this._contentSize
        });
      }
    }
    updateSashEnablement() {
      let previous = false;
      const collapsesDown = this.viewItems.map((i2) => previous = i2.size - i2.minimumSize > 0 || previous);
      previous = false;
      const expandsDown = this.viewItems.map((i2) => previous = i2.maximumSize - i2.size > 0 || previous);
      const reverseViews = [...this.viewItems].reverse();
      previous = false;
      const collapsesUp = reverseViews.map((i2) => previous = i2.size - i2.minimumSize > 0 || previous).reverse();
      previous = false;
      const expandsUp = reverseViews.map((i2) => previous = i2.maximumSize - i2.size > 0 || previous).reverse();
      let position = 0;
      for (let index = 0; index < this.sashItems.length; index++) {
        const { sash } = this.sashItems[index];
        const viewItem = this.viewItems[index];
        position += viewItem.size;
        const min = !(collapsesDown[index] && expandsUp[index + 1]);
        const max = !(expandsDown[index] && collapsesUp[index + 1]);
        if (min && max) {
          const upIndexes = range(index, -1);
          const downIndexes = range(index + 1, this.viewItems.length);
          const snapBeforeIndex = this.findFirstSnapIndex(upIndexes);
          const snapAfterIndex = this.findFirstSnapIndex(downIndexes);
          const snappedBefore = typeof snapBeforeIndex === "number" && !this.viewItems[snapBeforeIndex].visible;
          const snappedAfter = typeof snapAfterIndex === "number" && !this.viewItems[snapAfterIndex].visible;
          if (snappedBefore && collapsesUp[index] && (position > 0 || this.startSnappingEnabled)) {
            sash.state = 1;
          } else if (snappedAfter && collapsesDown[index] && (position < this._contentSize || this.endSnappingEnabled)) {
            sash.state = 2;
          } else {
            sash.state = 0;
          }
        } else if (min && !max) {
          sash.state = 1;
        } else if (!min && max) {
          sash.state = 2;
        } else {
          sash.state = 3;
        }
      }
    }
    getSashPosition(sash) {
      let position = 0;
      for (let i2 = 0; i2 < this.sashItems.length; i2++) {
        position += this.viewItems[i2].size;
        if (this.sashItems[i2].sash === sash) {
          return position;
        }
      }
      return 0;
    }
    findFirstSnapIndex(indexes) {
      for (const index of indexes) {
        const viewItem = this.viewItems[index];
        if (!viewItem.visible) {
          continue;
        }
        if (viewItem.snap) {
          return index;
        }
      }
      for (const index of indexes) {
        const viewItem = this.viewItems[index];
        if (viewItem.visible && viewItem.maximumSize - viewItem.minimumSize > 0) {
          return void 0;
        }
        if (!viewItem.visible && viewItem.snap) {
          return index;
        }
      }
      return void 0;
    }
    areViewsDistributed() {
      let min = void 0, max = void 0;
      for (const view of this.viewItems) {
        min = min === void 0 ? view.size : Math.min(min, view.size);
        max = max === void 0 ? view.size : Math.max(max, view.size);
        if (max - min > 2) {
          return false;
        }
      }
      return true;
    }
    dispose() {
      this.sashDragState?.disposable.dispose();
      dispose(this.viewItems);
      this.viewItems = [];
      this.sashItems.forEach((i2) => i2.disposable.dispose());
      this.sashItems = [];
      super.dispose();
    }
  }
  const _TableListRenderer = class _TableListRenderer {
    constructor(columns, renderers, getColumnSize) {
      this.columns = columns;
      this.getColumnSize = getColumnSize;
      this.templateId = _TableListRenderer.TemplateId;
      this.renderedTemplates = /* @__PURE__ */ new Set();
      const rendererMap = new Map(renderers.map((r) => [r.templateId, r]));
      this.renderers = [];
      for (const column of columns) {
        const renderer = rendererMap.get(column.templateId);
        if (!renderer) {
          throw new Error(`Table cell renderer for template id ${column.templateId} not found.`);
        }
        this.renderers.push(renderer);
      }
    }
    renderTemplate(container) {
      const rowContainer = append$2(container, $$l(".monaco-table-tr"));
      const cellContainers = [];
      const cellTemplateData = [];
      for (let i2 = 0; i2 < this.columns.length; i2++) {
        const renderer = this.renderers[i2];
        const cellContainer = append$2(rowContainer, $$l(".monaco-table-td", { "data-col-index": i2 }));
        cellContainer.style.width = `${this.getColumnSize(i2)}px`;
        cellContainers.push(cellContainer);
        cellTemplateData.push(renderer.renderTemplate(cellContainer));
      }
      const result = { container, cellContainers, cellTemplateData };
      this.renderedTemplates.add(result);
      return result;
    }
    renderElement(element, index, templateData, renderDetails) {
      for (let i2 = 0; i2 < this.columns.length; i2++) {
        const column = this.columns[i2];
        const cell = column.project(element);
        const renderer = this.renderers[i2];
        renderer.renderElement(cell, index, templateData.cellTemplateData[i2], renderDetails);
      }
    }
    disposeElement(element, index, templateData, renderDetails) {
      for (let i2 = 0; i2 < this.columns.length; i2++) {
        const renderer = this.renderers[i2];
        if (renderer.disposeElement) {
          const column = this.columns[i2];
          const cell = column.project(element);
          renderer.disposeElement(cell, index, templateData.cellTemplateData[i2], renderDetails);
        }
      }
    }
    disposeTemplate(templateData) {
      for (let i2 = 0; i2 < this.columns.length; i2++) {
        const renderer = this.renderers[i2];
        renderer.disposeTemplate(templateData.cellTemplateData[i2]);
      }
      clearNode(templateData.container);
      this.renderedTemplates.delete(templateData);
    }
    layoutColumn(index, size2) {
      for (const { cellContainers } of this.renderedTemplates) {
        cellContainers[index].style.width = `${size2}px`;
      }
    }
  };
  _TableListRenderer.TemplateId = "row";
  let TableListRenderer = _TableListRenderer;
  function asListVirtualDelegate(delegate) {
    return {
      getHeight(row) {
        return delegate.getHeight(row);
      },
      getTemplateId() {
        return TableListRenderer.TemplateId;
      }
    };
  }
  class ColumnHeader extends Disposable {
    get minimumSize() {
      return this.column.minimumWidth ?? 120;
    }
    get maximumSize() {
      return this.column.maximumWidth ?? Number.POSITIVE_INFINITY;
    }
    get onDidChange() {
      return this.column.onDidChangeWidthConstraints ?? Event.None;
    }
    constructor(column, index) {
      super();
      this.column = column;
      this.index = index;
      this._onDidLayout = new Emitter$1();
      this.onDidLayout = this._onDidLayout.event;
      this.element = $$l(".monaco-table-th", { "data-col-index": index }, column.label);
      if (column.tooltip) {
        this._register(getBaseLayerHoverDelegate().setupManagedHover(getDefaultHoverDelegate("mouse"), this.element, column.tooltip));
      }
    }
    layout(size2) {
      this._onDidLayout.fire([this.index, size2]);
    }
  }
  const _Table = class _Table {
    get onDidChangeFocus() {
      return this.list.onDidChangeFocus;
    }
    get onDidChangeSelection() {
      return this.list.onDidChangeSelection;
    }
    get onDidScroll() {
      return this.list.onDidScroll;
    }
    get onMouseDblClick() {
      return this.list.onMouseDblClick;
    }
    get onPointer() {
      return this.list.onPointer;
    }
    get onDidFocus() {
      return this.list.onDidFocus;
    }
    get scrollTop() {
      return this.list.scrollTop;
    }
    set scrollTop(scrollTop) {
      this.list.scrollTop = scrollTop;
    }
    get scrollHeight() {
      return this.list.scrollHeight;
    }
    get renderHeight() {
      return this.list.renderHeight;
    }
    get onDidDispose() {
      return this.list.onDidDispose;
    }
    constructor(user, container, virtualDelegate, columns, renderers, _options) {
      this.virtualDelegate = virtualDelegate;
      this.columns = columns;
      this.domId = `table_id_${++_Table.InstanceCount}`;
      this.disposables = new DisposableStore();
      this.cachedWidth = 0;
      this.cachedHeight = 0;
      this.domNode = append$2(container, $$l(`.monaco-table.${this.domId}`));
      const headers = columns.map((c, i2) => this.disposables.add(new ColumnHeader(c, i2)));
      const descriptor = {
        size: headers.reduce((a, b) => a + b.column.weight, 0),
        views: headers.map((view) => ({ size: view.column.weight, view }))
      };
      this.splitview = this.disposables.add(new SplitView(this.domNode, {
        orientation: 1,
        scrollbarVisibility: 2,
        getSashOrthogonalSize: () => this.cachedHeight,
        descriptor
      }));
      this.splitview.el.style.height = `${virtualDelegate.headerRowHeight}px`;
      this.splitview.el.style.lineHeight = `${virtualDelegate.headerRowHeight}px`;
      const renderer = new TableListRenderer(columns, renderers, (i2) => this.splitview.getViewSize(i2));
      this.list = this.disposables.add(new List(user, this.domNode, asListVirtualDelegate(virtualDelegate), [renderer], _options));
      Event.any(...headers.map((h2) => h2.onDidLayout))(([index, size2]) => renderer.layoutColumn(index, size2), null, this.disposables);
      this.splitview.onDidSashReset((index) => {
        const totalWeight = columns.reduce((r, c) => r + c.weight, 0);
        const size2 = columns[index].weight / totalWeight * this.cachedWidth;
        this.splitview.resizeView(index, size2);
      }, null, this.disposables);
      this.styleElement = createStyleSheet(this.domNode);
      this.style(unthemedListStyles);
    }
    updateOptions(options) {
      this.list.updateOptions(options);
    }
    splice(start, deleteCount, elements = []) {
      this.list.splice(start, deleteCount, elements);
    }
    getHTMLElement() {
      return this.domNode;
    }
    style(styles) {
      const content = [];
      content.push(`.monaco-table.${this.domId} > .monaco-split-view2 .monaco-sash.vertical::before {
			top: ${this.virtualDelegate.headerRowHeight + 1}px;
			height: calc(100% - ${this.virtualDelegate.headerRowHeight}px);
		}`);
      this.styleElement.textContent = content.join("\n");
      this.list.style(styles);
    }
    getSelectedElements() {
      return this.list.getSelectedElements();
    }
    getSelection() {
      return this.list.getSelection();
    }
    getFocus() {
      return this.list.getFocus();
    }
    dispose() {
      this.disposables.dispose();
    }
  };
  _Table.InstanceCount = 0;
  let Table = _Table;
  var ObjectTreeElementCollapseState;
  (function(ObjectTreeElementCollapseState2) {
    ObjectTreeElementCollapseState2[ObjectTreeElementCollapseState2["Expanded"] = 0] = "Expanded";
    ObjectTreeElementCollapseState2[ObjectTreeElementCollapseState2["Collapsed"] = 1] = "Collapsed";
    ObjectTreeElementCollapseState2[ObjectTreeElementCollapseState2["PreserveOrExpanded"] = 2] = "PreserveOrExpanded";
    ObjectTreeElementCollapseState2[ObjectTreeElementCollapseState2["PreserveOrCollapsed"] = 3] = "PreserveOrCollapsed";
  })(ObjectTreeElementCollapseState || (ObjectTreeElementCollapseState = {}));
  var TreeMouseEventTarget;
  (function(TreeMouseEventTarget2) {
    TreeMouseEventTarget2[TreeMouseEventTarget2["Unknown"] = 0] = "Unknown";
    TreeMouseEventTarget2[TreeMouseEventTarget2["Twistie"] = 1] = "Twistie";
    TreeMouseEventTarget2[TreeMouseEventTarget2["Element"] = 2] = "Element";
    TreeMouseEventTarget2[TreeMouseEventTarget2["Filter"] = 3] = "Filter";
  })(TreeMouseEventTarget || (TreeMouseEventTarget = {}));
  class TreeError extends Error {
    constructor(user, message) {
      super(`TreeError [${user}] ${message}`);
    }
  }
  class WeakMapper {
    constructor(fn) {
      this.fn = fn;
      this._map = /* @__PURE__ */ new WeakMap();
    }
    map(key) {
      let result = this._map.get(key);
      if (!result) {
        result = this.fn(key);
        this._map.set(key, result);
      }
      return result;
    }
  }
  class DiffChange {
    /**
     * Constructs a new DiffChange with the given sequence information
     * and content.
     */
    constructor(originalStart, originalLength, modifiedStart, modifiedLength) {
      this.originalStart = originalStart;
      this.originalLength = originalLength;
      this.modifiedStart = modifiedStart;
      this.modifiedLength = modifiedLength;
    }
    /**
     * The end point (exclusive) of the change in the original sequence.
     */
    getOriginalEnd() {
      return this.originalStart + this.originalLength;
    }
    /**
     * The end point (exclusive) of the change in the modified sequence.
     */
    getModifiedEnd() {
      return this.modifiedStart + this.modifiedLength;
    }
  }
  class StringDiffSequence {
    constructor(source) {
      this.source = source;
    }
    getElements() {
      const source = this.source;
      const characters = new Int32Array(source.length);
      for (let i2 = 0, len = source.length; i2 < len; i2++) {
        characters[i2] = source.charCodeAt(i2);
      }
      return characters;
    }
  }
  function stringDiff(original, modified, pretty) {
    return new LcsDiff(new StringDiffSequence(original), new StringDiffSequence(modified)).ComputeDiff(pretty).changes;
  }
  class Debug {
    static Assert(condition, message) {
      if (!condition) {
        throw new Error(message);
      }
    }
  }
  class MyArray {
    /**
     * Copies a range of elements from an Array starting at the specified source index and pastes
     * them to another Array starting at the specified destination index. The length and the indexes
     * are specified as 64-bit integers.
     * sourceArray:
     *		The Array that contains the data to copy.
     * sourceIndex:
     *		A 64-bit integer that represents the index in the sourceArray at which copying begins.
     * destinationArray:
     *		The Array that receives the data.
     * destinationIndex:
     *		A 64-bit integer that represents the index in the destinationArray at which storing begins.
     * length:
     *		A 64-bit integer that represents the number of elements to copy.
     */
    static Copy(sourceArray, sourceIndex, destinationArray, destinationIndex, length) {
      for (let i2 = 0; i2 < length; i2++) {
        destinationArray[destinationIndex + i2] = sourceArray[sourceIndex + i2];
      }
    }
    static Copy2(sourceArray, sourceIndex, destinationArray, destinationIndex, length) {
      for (let i2 = 0; i2 < length; i2++) {
        destinationArray[destinationIndex + i2] = sourceArray[sourceIndex + i2];
      }
    }
  }
  class DiffChangeHelper {
    /**
     * Constructs a new DiffChangeHelper for the given DiffSequences.
     */
    constructor() {
      this.m_changes = [];
      this.m_originalStart = 1073741824;
      this.m_modifiedStart = 1073741824;
      this.m_originalCount = 0;
      this.m_modifiedCount = 0;
    }
    /**
     * Marks the beginning of the next change in the set of differences.
     */
    MarkNextChange() {
      if (this.m_originalCount > 0 || this.m_modifiedCount > 0) {
        this.m_changes.push(new DiffChange(this.m_originalStart, this.m_originalCount, this.m_modifiedStart, this.m_modifiedCount));
      }
      this.m_originalCount = 0;
      this.m_modifiedCount = 0;
      this.m_originalStart = 1073741824;
      this.m_modifiedStart = 1073741824;
    }
    /**
     * Adds the original element at the given position to the elements
     * affected by the current change. The modified index gives context
     * to the change position with respect to the original sequence.
     * @param originalIndex The index of the original element to add.
     * @param modifiedIndex The index of the modified element that provides corresponding position in the modified sequence.
     */
    AddOriginalElement(originalIndex, modifiedIndex) {
      this.m_originalStart = Math.min(this.m_originalStart, originalIndex);
      this.m_modifiedStart = Math.min(this.m_modifiedStart, modifiedIndex);
      this.m_originalCount++;
    }
    /**
     * Adds the modified element at the given position to the elements
     * affected by the current change. The original index gives context
     * to the change position with respect to the modified sequence.
     * @param originalIndex The index of the original element that provides corresponding position in the original sequence.
     * @param modifiedIndex The index of the modified element to add.
     */
    AddModifiedElement(originalIndex, modifiedIndex) {
      this.m_originalStart = Math.min(this.m_originalStart, originalIndex);
      this.m_modifiedStart = Math.min(this.m_modifiedStart, modifiedIndex);
      this.m_modifiedCount++;
    }
    /**
     * Retrieves all of the changes marked by the class.
     */
    getChanges() {
      if (this.m_originalCount > 0 || this.m_modifiedCount > 0) {
        this.MarkNextChange();
      }
      return this.m_changes;
    }
    /**
     * Retrieves all of the changes marked by the class in the reverse order
     */
    getReverseChanges() {
      if (this.m_originalCount > 0 || this.m_modifiedCount > 0) {
        this.MarkNextChange();
      }
      this.m_changes.reverse();
      return this.m_changes;
    }
  }
  class LcsDiff {
    /**
     * Constructs the DiffFinder
     */
    constructor(originalSequence, modifiedSequence, continueProcessingPredicate = null) {
      this.ContinueProcessingPredicate = continueProcessingPredicate;
      this._originalSequence = originalSequence;
      this._modifiedSequence = modifiedSequence;
      const [originalStringElements, originalElementsOrHash, originalHasStrings] = LcsDiff._getElements(originalSequence);
      const [modifiedStringElements, modifiedElementsOrHash, modifiedHasStrings] = LcsDiff._getElements(modifiedSequence);
      this._hasStrings = originalHasStrings && modifiedHasStrings;
      this._originalStringElements = originalStringElements;
      this._originalElementsOrHash = originalElementsOrHash;
      this._modifiedStringElements = modifiedStringElements;
      this._modifiedElementsOrHash = modifiedElementsOrHash;
      this.m_forwardHistory = [];
      this.m_reverseHistory = [];
    }
    static _isStringArray(arr) {
      return arr.length > 0 && typeof arr[0] === "string";
    }
    static _getElements(sequence) {
      const elements = sequence.getElements();
      if (LcsDiff._isStringArray(elements)) {
        const hashes = new Int32Array(elements.length);
        for (let i2 = 0, len = elements.length; i2 < len; i2++) {
          hashes[i2] = stringHash(elements[i2], 0);
        }
        return [elements, hashes, true];
      }
      if (elements instanceof Int32Array) {
        return [[], elements, false];
      }
      return [[], new Int32Array(elements), false];
    }
    ElementsAreEqual(originalIndex, newIndex) {
      if (this._originalElementsOrHash[originalIndex] !== this._modifiedElementsOrHash[newIndex]) {
        return false;
      }
      return this._hasStrings ? this._originalStringElements[originalIndex] === this._modifiedStringElements[newIndex] : true;
    }
    ElementsAreStrictEqual(originalIndex, newIndex) {
      if (!this.ElementsAreEqual(originalIndex, newIndex)) {
        return false;
      }
      const originalElement = LcsDiff._getStrictElement(this._originalSequence, originalIndex);
      const modifiedElement = LcsDiff._getStrictElement(this._modifiedSequence, newIndex);
      return originalElement === modifiedElement;
    }
    static _getStrictElement(sequence, index) {
      if (typeof sequence.getStrictElement === "function") {
        return sequence.getStrictElement(index);
      }
      return null;
    }
    OriginalElementsAreEqual(index1, index2) {
      if (this._originalElementsOrHash[index1] !== this._originalElementsOrHash[index2]) {
        return false;
      }
      return this._hasStrings ? this._originalStringElements[index1] === this._originalStringElements[index2] : true;
    }
    ModifiedElementsAreEqual(index1, index2) {
      if (this._modifiedElementsOrHash[index1] !== this._modifiedElementsOrHash[index2]) {
        return false;
      }
      return this._hasStrings ? this._modifiedStringElements[index1] === this._modifiedStringElements[index2] : true;
    }
    ComputeDiff(pretty) {
      return this._ComputeDiff(0, this._originalElementsOrHash.length - 1, 0, this._modifiedElementsOrHash.length - 1, pretty);
    }
    /**
     * Computes the differences between the original and modified input
     * sequences on the bounded range.
     * @returns An array of the differences between the two input sequences.
     */
    _ComputeDiff(originalStart, originalEnd, modifiedStart, modifiedEnd, pretty) {
      const quitEarlyArr = [false];
      let changes = this.ComputeDiffRecursive(originalStart, originalEnd, modifiedStart, modifiedEnd, quitEarlyArr);
      if (pretty) {
        changes = this.PrettifyChanges(changes);
      }
      return {
        quitEarly: quitEarlyArr[0],
        changes
      };
    }
    /**
     * Private helper method which computes the differences on the bounded range
     * recursively.
     * @returns An array of the differences between the two input sequences.
     */
    ComputeDiffRecursive(originalStart, originalEnd, modifiedStart, modifiedEnd, quitEarlyArr) {
      quitEarlyArr[0] = false;
      while (originalStart <= originalEnd && modifiedStart <= modifiedEnd && this.ElementsAreEqual(originalStart, modifiedStart)) {
        originalStart++;
        modifiedStart++;
      }
      while (originalEnd >= originalStart && modifiedEnd >= modifiedStart && this.ElementsAreEqual(originalEnd, modifiedEnd)) {
        originalEnd--;
        modifiedEnd--;
      }
      if (originalStart > originalEnd || modifiedStart > modifiedEnd) {
        let changes;
        if (modifiedStart <= modifiedEnd) {
          Debug.Assert(originalStart === originalEnd + 1, "originalStart should only be one more than originalEnd");
          changes = [
            new DiffChange(originalStart, 0, modifiedStart, modifiedEnd - modifiedStart + 1)
          ];
        } else if (originalStart <= originalEnd) {
          Debug.Assert(modifiedStart === modifiedEnd + 1, "modifiedStart should only be one more than modifiedEnd");
          changes = [
            new DiffChange(originalStart, originalEnd - originalStart + 1, modifiedStart, 0)
          ];
        } else {
          Debug.Assert(originalStart === originalEnd + 1, "originalStart should only be one more than originalEnd");
          Debug.Assert(modifiedStart === modifiedEnd + 1, "modifiedStart should only be one more than modifiedEnd");
          changes = [];
        }
        return changes;
      }
      const midOriginalArr = [0];
      const midModifiedArr = [0];
      const result = this.ComputeRecursionPoint(originalStart, originalEnd, modifiedStart, modifiedEnd, midOriginalArr, midModifiedArr, quitEarlyArr);
      const midOriginal = midOriginalArr[0];
      const midModified = midModifiedArr[0];
      if (result !== null) {
        return result;
      } else if (!quitEarlyArr[0]) {
        const leftChanges = this.ComputeDiffRecursive(originalStart, midOriginal, modifiedStart, midModified, quitEarlyArr);
        let rightChanges = [];
        if (!quitEarlyArr[0]) {
          rightChanges = this.ComputeDiffRecursive(midOriginal + 1, originalEnd, midModified + 1, modifiedEnd, quitEarlyArr);
        } else {
          rightChanges = [
            new DiffChange(midOriginal + 1, originalEnd - (midOriginal + 1) + 1, midModified + 1, modifiedEnd - (midModified + 1) + 1)
          ];
        }
        return this.ConcatenateChanges(leftChanges, rightChanges);
      }
      return [
        new DiffChange(originalStart, originalEnd - originalStart + 1, modifiedStart, modifiedEnd - modifiedStart + 1)
      ];
    }
    WALKTRACE(diagonalForwardBase, diagonalForwardStart, diagonalForwardEnd, diagonalForwardOffset, diagonalReverseBase, diagonalReverseStart, diagonalReverseEnd, diagonalReverseOffset, forwardPoints, reversePoints, originalIndex, originalEnd, midOriginalArr, modifiedIndex, modifiedEnd, midModifiedArr, deltaIsEven, quitEarlyArr) {
      let forwardChanges = null;
      let reverseChanges = null;
      let changeHelper = new DiffChangeHelper();
      let diagonalMin = diagonalForwardStart;
      let diagonalMax = diagonalForwardEnd;
      let diagonalRelative = midOriginalArr[0] - midModifiedArr[0] - diagonalForwardOffset;
      let lastOriginalIndex = -1073741824;
      let historyIndex = this.m_forwardHistory.length - 1;
      do {
        const diagonal = diagonalRelative + diagonalForwardBase;
        if (diagonal === diagonalMin || diagonal < diagonalMax && forwardPoints[diagonal - 1] < forwardPoints[diagonal + 1]) {
          originalIndex = forwardPoints[diagonal + 1];
          modifiedIndex = originalIndex - diagonalRelative - diagonalForwardOffset;
          if (originalIndex < lastOriginalIndex) {
            changeHelper.MarkNextChange();
          }
          lastOriginalIndex = originalIndex;
          changeHelper.AddModifiedElement(originalIndex + 1, modifiedIndex);
          diagonalRelative = diagonal + 1 - diagonalForwardBase;
        } else {
          originalIndex = forwardPoints[diagonal - 1] + 1;
          modifiedIndex = originalIndex - diagonalRelative - diagonalForwardOffset;
          if (originalIndex < lastOriginalIndex) {
            changeHelper.MarkNextChange();
          }
          lastOriginalIndex = originalIndex - 1;
          changeHelper.AddOriginalElement(originalIndex, modifiedIndex + 1);
          diagonalRelative = diagonal - 1 - diagonalForwardBase;
        }
        if (historyIndex >= 0) {
          forwardPoints = this.m_forwardHistory[historyIndex];
          diagonalForwardBase = forwardPoints[0];
          diagonalMin = 1;
          diagonalMax = forwardPoints.length - 1;
        }
      } while (--historyIndex >= -1);
      forwardChanges = changeHelper.getReverseChanges();
      if (quitEarlyArr[0]) {
        let originalStartPoint = midOriginalArr[0] + 1;
        let modifiedStartPoint = midModifiedArr[0] + 1;
        if (forwardChanges !== null && forwardChanges.length > 0) {
          const lastForwardChange = forwardChanges[forwardChanges.length - 1];
          originalStartPoint = Math.max(originalStartPoint, lastForwardChange.getOriginalEnd());
          modifiedStartPoint = Math.max(modifiedStartPoint, lastForwardChange.getModifiedEnd());
        }
        reverseChanges = [
          new DiffChange(originalStartPoint, originalEnd - originalStartPoint + 1, modifiedStartPoint, modifiedEnd - modifiedStartPoint + 1)
        ];
      } else {
        changeHelper = new DiffChangeHelper();
        diagonalMin = diagonalReverseStart;
        diagonalMax = diagonalReverseEnd;
        diagonalRelative = midOriginalArr[0] - midModifiedArr[0] - diagonalReverseOffset;
        lastOriginalIndex = 1073741824;
        historyIndex = deltaIsEven ? this.m_reverseHistory.length - 1 : this.m_reverseHistory.length - 2;
        do {
          const diagonal = diagonalRelative + diagonalReverseBase;
          if (diagonal === diagonalMin || diagonal < diagonalMax && reversePoints[diagonal - 1] >= reversePoints[diagonal + 1]) {
            originalIndex = reversePoints[diagonal + 1] - 1;
            modifiedIndex = originalIndex - diagonalRelative - diagonalReverseOffset;
            if (originalIndex > lastOriginalIndex) {
              changeHelper.MarkNextChange();
            }
            lastOriginalIndex = originalIndex + 1;
            changeHelper.AddOriginalElement(originalIndex + 1, modifiedIndex + 1);
            diagonalRelative = diagonal + 1 - diagonalReverseBase;
          } else {
            originalIndex = reversePoints[diagonal - 1];
            modifiedIndex = originalIndex - diagonalRelative - diagonalReverseOffset;
            if (originalIndex > lastOriginalIndex) {
              changeHelper.MarkNextChange();
            }
            lastOriginalIndex = originalIndex;
            changeHelper.AddModifiedElement(originalIndex + 1, modifiedIndex + 1);
            diagonalRelative = diagonal - 1 - diagonalReverseBase;
          }
          if (historyIndex >= 0) {
            reversePoints = this.m_reverseHistory[historyIndex];
            diagonalReverseBase = reversePoints[0];
            diagonalMin = 1;
            diagonalMax = reversePoints.length - 1;
          }
        } while (--historyIndex >= -1);
        reverseChanges = changeHelper.getChanges();
      }
      return this.ConcatenateChanges(forwardChanges, reverseChanges);
    }
    /**
     * Given the range to compute the diff on, this method finds the point:
     * (midOriginal, midModified)
     * that exists in the middle of the LCS of the two sequences and
     * is the point at which the LCS problem may be broken down recursively.
     * This method will try to keep the LCS trace in memory. If the LCS recursion
     * point is calculated and the full trace is available in memory, then this method
     * will return the change list.
     * @param originalStart The start bound of the original sequence range
     * @param originalEnd The end bound of the original sequence range
     * @param modifiedStart The start bound of the modified sequence range
     * @param modifiedEnd The end bound of the modified sequence range
     * @param midOriginal The middle point of the original sequence range
     * @param midModified The middle point of the modified sequence range
     * @returns The diff changes, if available, otherwise null
     */
    ComputeRecursionPoint(originalStart, originalEnd, modifiedStart, modifiedEnd, midOriginalArr, midModifiedArr, quitEarlyArr) {
      let originalIndex = 0, modifiedIndex = 0;
      let diagonalForwardStart = 0, diagonalForwardEnd = 0;
      let diagonalReverseStart = 0, diagonalReverseEnd = 0;
      originalStart--;
      modifiedStart--;
      midOriginalArr[0] = 0;
      midModifiedArr[0] = 0;
      this.m_forwardHistory = [];
      this.m_reverseHistory = [];
      const maxDifferences = originalEnd - originalStart + (modifiedEnd - modifiedStart);
      const numDiagonals = maxDifferences + 1;
      const forwardPoints = new Int32Array(numDiagonals);
      const reversePoints = new Int32Array(numDiagonals);
      const diagonalForwardBase = modifiedEnd - modifiedStart;
      const diagonalReverseBase = originalEnd - originalStart;
      const diagonalForwardOffset = originalStart - modifiedStart;
      const diagonalReverseOffset = originalEnd - modifiedEnd;
      const delta = diagonalReverseBase - diagonalForwardBase;
      const deltaIsEven = delta % 2 === 0;
      forwardPoints[diagonalForwardBase] = originalStart;
      reversePoints[diagonalReverseBase] = originalEnd;
      quitEarlyArr[0] = false;
      for (let numDifferences = 1; numDifferences <= maxDifferences / 2 + 1; numDifferences++) {
        let furthestOriginalIndex = 0;
        let furthestModifiedIndex = 0;
        diagonalForwardStart = this.ClipDiagonalBound(diagonalForwardBase - numDifferences, numDifferences, diagonalForwardBase, numDiagonals);
        diagonalForwardEnd = this.ClipDiagonalBound(diagonalForwardBase + numDifferences, numDifferences, diagonalForwardBase, numDiagonals);
        for (let diagonal = diagonalForwardStart; diagonal <= diagonalForwardEnd; diagonal += 2) {
          if (diagonal === diagonalForwardStart || diagonal < diagonalForwardEnd && forwardPoints[diagonal - 1] < forwardPoints[diagonal + 1]) {
            originalIndex = forwardPoints[diagonal + 1];
          } else {
            originalIndex = forwardPoints[diagonal - 1] + 1;
          }
          modifiedIndex = originalIndex - (diagonal - diagonalForwardBase) - diagonalForwardOffset;
          const tempOriginalIndex = originalIndex;
          while (originalIndex < originalEnd && modifiedIndex < modifiedEnd && this.ElementsAreEqual(originalIndex + 1, modifiedIndex + 1)) {
            originalIndex++;
            modifiedIndex++;
          }
          forwardPoints[diagonal] = originalIndex;
          if (originalIndex + modifiedIndex > furthestOriginalIndex + furthestModifiedIndex) {
            furthestOriginalIndex = originalIndex;
            furthestModifiedIndex = modifiedIndex;
          }
          if (!deltaIsEven && Math.abs(diagonal - diagonalReverseBase) <= numDifferences - 1) {
            if (originalIndex >= reversePoints[diagonal]) {
              midOriginalArr[0] = originalIndex;
              midModifiedArr[0] = modifiedIndex;
              if (tempOriginalIndex <= reversePoints[diagonal] && 1447 > 0 && numDifferences <= 1447 + 1) {
                return this.WALKTRACE(diagonalForwardBase, diagonalForwardStart, diagonalForwardEnd, diagonalForwardOffset, diagonalReverseBase, diagonalReverseStart, diagonalReverseEnd, diagonalReverseOffset, forwardPoints, reversePoints, originalIndex, originalEnd, midOriginalArr, modifiedIndex, modifiedEnd, midModifiedArr, deltaIsEven, quitEarlyArr);
              } else {
                return null;
              }
            }
          }
        }
        const matchLengthOfLongest = (furthestOriginalIndex - originalStart + (furthestModifiedIndex - modifiedStart) - numDifferences) / 2;
        if (this.ContinueProcessingPredicate !== null && !this.ContinueProcessingPredicate(furthestOriginalIndex, matchLengthOfLongest)) {
          quitEarlyArr[0] = true;
          midOriginalArr[0] = furthestOriginalIndex;
          midModifiedArr[0] = furthestModifiedIndex;
          if (matchLengthOfLongest > 0 && 1447 > 0 && numDifferences <= 1447 + 1) {
            return this.WALKTRACE(diagonalForwardBase, diagonalForwardStart, diagonalForwardEnd, diagonalForwardOffset, diagonalReverseBase, diagonalReverseStart, diagonalReverseEnd, diagonalReverseOffset, forwardPoints, reversePoints, originalIndex, originalEnd, midOriginalArr, modifiedIndex, modifiedEnd, midModifiedArr, deltaIsEven, quitEarlyArr);
          } else {
            originalStart++;
            modifiedStart++;
            return [
              new DiffChange(originalStart, originalEnd - originalStart + 1, modifiedStart, modifiedEnd - modifiedStart + 1)
            ];
          }
        }
        diagonalReverseStart = this.ClipDiagonalBound(diagonalReverseBase - numDifferences, numDifferences, diagonalReverseBase, numDiagonals);
        diagonalReverseEnd = this.ClipDiagonalBound(diagonalReverseBase + numDifferences, numDifferences, diagonalReverseBase, numDiagonals);
        for (let diagonal = diagonalReverseStart; diagonal <= diagonalReverseEnd; diagonal += 2) {
          if (diagonal === diagonalReverseStart || diagonal < diagonalReverseEnd && reversePoints[diagonal - 1] >= reversePoints[diagonal + 1]) {
            originalIndex = reversePoints[diagonal + 1] - 1;
          } else {
            originalIndex = reversePoints[diagonal - 1];
          }
          modifiedIndex = originalIndex - (diagonal - diagonalReverseBase) - diagonalReverseOffset;
          const tempOriginalIndex = originalIndex;
          while (originalIndex > originalStart && modifiedIndex > modifiedStart && this.ElementsAreEqual(originalIndex, modifiedIndex)) {
            originalIndex--;
            modifiedIndex--;
          }
          reversePoints[diagonal] = originalIndex;
          if (deltaIsEven && Math.abs(diagonal - diagonalForwardBase) <= numDifferences) {
            if (originalIndex <= forwardPoints[diagonal]) {
              midOriginalArr[0] = originalIndex;
              midModifiedArr[0] = modifiedIndex;
              if (tempOriginalIndex >= forwardPoints[diagonal] && 1447 > 0 && numDifferences <= 1447 + 1) {
                return this.WALKTRACE(diagonalForwardBase, diagonalForwardStart, diagonalForwardEnd, diagonalForwardOffset, diagonalReverseBase, diagonalReverseStart, diagonalReverseEnd, diagonalReverseOffset, forwardPoints, reversePoints, originalIndex, originalEnd, midOriginalArr, modifiedIndex, modifiedEnd, midModifiedArr, deltaIsEven, quitEarlyArr);
              } else {
                return null;
              }
            }
          }
        }
        if (numDifferences <= 1447) {
          let temp = new Int32Array(diagonalForwardEnd - diagonalForwardStart + 2);
          temp[0] = diagonalForwardBase - diagonalForwardStart + 1;
          MyArray.Copy2(forwardPoints, diagonalForwardStart, temp, 1, diagonalForwardEnd - diagonalForwardStart + 1);
          this.m_forwardHistory.push(temp);
          temp = new Int32Array(diagonalReverseEnd - diagonalReverseStart + 2);
          temp[0] = diagonalReverseBase - diagonalReverseStart + 1;
          MyArray.Copy2(reversePoints, diagonalReverseStart, temp, 1, diagonalReverseEnd - diagonalReverseStart + 1);
          this.m_reverseHistory.push(temp);
        }
      }
      return this.WALKTRACE(diagonalForwardBase, diagonalForwardStart, diagonalForwardEnd, diagonalForwardOffset, diagonalReverseBase, diagonalReverseStart, diagonalReverseEnd, diagonalReverseOffset, forwardPoints, reversePoints, originalIndex, originalEnd, midOriginalArr, modifiedIndex, modifiedEnd, midModifiedArr, deltaIsEven, quitEarlyArr);
    }
    /**
     * Shifts the given changes to provide a more intuitive diff.
     * While the first element in a diff matches the first element after the diff,
     * we shift the diff down.
     *
     * @param changes The list of changes to shift
     * @returns The shifted changes
     */
    PrettifyChanges(changes) {
      for (let i2 = 0; i2 < changes.length; i2++) {
        const change = changes[i2];
        const originalStop = i2 < changes.length - 1 ? changes[i2 + 1].originalStart : this._originalElementsOrHash.length;
        const modifiedStop = i2 < changes.length - 1 ? changes[i2 + 1].modifiedStart : this._modifiedElementsOrHash.length;
        const checkOriginal = change.originalLength > 0;
        const checkModified = change.modifiedLength > 0;
        while (change.originalStart + change.originalLength < originalStop && change.modifiedStart + change.modifiedLength < modifiedStop && (!checkOriginal || this.OriginalElementsAreEqual(change.originalStart, change.originalStart + change.originalLength)) && (!checkModified || this.ModifiedElementsAreEqual(change.modifiedStart, change.modifiedStart + change.modifiedLength))) {
          const startStrictEqual = this.ElementsAreStrictEqual(change.originalStart, change.modifiedStart);
          const endStrictEqual = this.ElementsAreStrictEqual(change.originalStart + change.originalLength, change.modifiedStart + change.modifiedLength);
          if (endStrictEqual && !startStrictEqual) {
            break;
          }
          change.originalStart++;
          change.modifiedStart++;
        }
        const mergedChangeArr = [null];
        if (i2 < changes.length - 1 && this.ChangesOverlap(changes[i2], changes[i2 + 1], mergedChangeArr)) {
          changes[i2] = mergedChangeArr[0];
          changes.splice(i2 + 1, 1);
          i2--;
          continue;
        }
      }
      for (let i2 = changes.length - 1; i2 >= 0; i2--) {
        const change = changes[i2];
        let originalStop = 0;
        let modifiedStop = 0;
        if (i2 > 0) {
          const prevChange = changes[i2 - 1];
          originalStop = prevChange.originalStart + prevChange.originalLength;
          modifiedStop = prevChange.modifiedStart + prevChange.modifiedLength;
        }
        const checkOriginal = change.originalLength > 0;
        const checkModified = change.modifiedLength > 0;
        let bestDelta = 0;
        let bestScore = this._boundaryScore(change.originalStart, change.originalLength, change.modifiedStart, change.modifiedLength);
        for (let delta = 1; ; delta++) {
          const originalStart = change.originalStart - delta;
          const modifiedStart = change.modifiedStart - delta;
          if (originalStart < originalStop || modifiedStart < modifiedStop) {
            break;
          }
          if (checkOriginal && !this.OriginalElementsAreEqual(originalStart, originalStart + change.originalLength)) {
            break;
          }
          if (checkModified && !this.ModifiedElementsAreEqual(modifiedStart, modifiedStart + change.modifiedLength)) {
            break;
          }
          const touchingPreviousChange = originalStart === originalStop && modifiedStart === modifiedStop;
          const score2 = (touchingPreviousChange ? 5 : 0) + this._boundaryScore(originalStart, change.originalLength, modifiedStart, change.modifiedLength);
          if (score2 > bestScore) {
            bestScore = score2;
            bestDelta = delta;
          }
        }
        change.originalStart -= bestDelta;
        change.modifiedStart -= bestDelta;
        const mergedChangeArr = [null];
        if (i2 > 0 && this.ChangesOverlap(changes[i2 - 1], changes[i2], mergedChangeArr)) {
          changes[i2 - 1] = mergedChangeArr[0];
          changes.splice(i2, 1);
          i2++;
          continue;
        }
      }
      if (this._hasStrings) {
        for (let i2 = 1, len = changes.length; i2 < len; i2++) {
          const aChange = changes[i2 - 1];
          const bChange = changes[i2];
          const matchedLength = bChange.originalStart - aChange.originalStart - aChange.originalLength;
          const aOriginalStart = aChange.originalStart;
          const bOriginalEnd = bChange.originalStart + bChange.originalLength;
          const abOriginalLength = bOriginalEnd - aOriginalStart;
          const aModifiedStart = aChange.modifiedStart;
          const bModifiedEnd = bChange.modifiedStart + bChange.modifiedLength;
          const abModifiedLength = bModifiedEnd - aModifiedStart;
          if (matchedLength < 5 && abOriginalLength < 20 && abModifiedLength < 20) {
            const t = this._findBetterContiguousSequence(aOriginalStart, abOriginalLength, aModifiedStart, abModifiedLength, matchedLength);
            if (t) {
              const [originalMatchStart, modifiedMatchStart] = t;
              if (originalMatchStart !== aChange.originalStart + aChange.originalLength || modifiedMatchStart !== aChange.modifiedStart + aChange.modifiedLength) {
                aChange.originalLength = originalMatchStart - aChange.originalStart;
                aChange.modifiedLength = modifiedMatchStart - aChange.modifiedStart;
                bChange.originalStart = originalMatchStart + matchedLength;
                bChange.modifiedStart = modifiedMatchStart + matchedLength;
                bChange.originalLength = bOriginalEnd - bChange.originalStart;
                bChange.modifiedLength = bModifiedEnd - bChange.modifiedStart;
              }
            }
          }
        }
      }
      return changes;
    }
    _findBetterContiguousSequence(originalStart, originalLength, modifiedStart, modifiedLength, desiredLength) {
      if (originalLength < desiredLength || modifiedLength < desiredLength) {
        return null;
      }
      const originalMax = originalStart + originalLength - desiredLength + 1;
      const modifiedMax = modifiedStart + modifiedLength - desiredLength + 1;
      let bestScore = 0;
      let bestOriginalStart = 0;
      let bestModifiedStart = 0;
      for (let i2 = originalStart; i2 < originalMax; i2++) {
        for (let j = modifiedStart; j < modifiedMax; j++) {
          const score2 = this._contiguousSequenceScore(i2, j, desiredLength);
          if (score2 > 0 && score2 > bestScore) {
            bestScore = score2;
            bestOriginalStart = i2;
            bestModifiedStart = j;
          }
        }
      }
      if (bestScore > 0) {
        return [bestOriginalStart, bestModifiedStart];
      }
      return null;
    }
    _contiguousSequenceScore(originalStart, modifiedStart, length) {
      let score2 = 0;
      for (let l = 0; l < length; l++) {
        if (!this.ElementsAreEqual(originalStart + l, modifiedStart + l)) {
          return 0;
        }
        score2 += this._originalStringElements[originalStart + l].length;
      }
      return score2;
    }
    _OriginalIsBoundary(index) {
      if (index <= 0 || index >= this._originalElementsOrHash.length - 1) {
        return true;
      }
      return this._hasStrings && /^\s*$/.test(this._originalStringElements[index]);
    }
    _OriginalRegionIsBoundary(originalStart, originalLength) {
      if (this._OriginalIsBoundary(originalStart) || this._OriginalIsBoundary(originalStart - 1)) {
        return true;
      }
      if (originalLength > 0) {
        const originalEnd = originalStart + originalLength;
        if (this._OriginalIsBoundary(originalEnd - 1) || this._OriginalIsBoundary(originalEnd)) {
          return true;
        }
      }
      return false;
    }
    _ModifiedIsBoundary(index) {
      if (index <= 0 || index >= this._modifiedElementsOrHash.length - 1) {
        return true;
      }
      return this._hasStrings && /^\s*$/.test(this._modifiedStringElements[index]);
    }
    _ModifiedRegionIsBoundary(modifiedStart, modifiedLength) {
      if (this._ModifiedIsBoundary(modifiedStart) || this._ModifiedIsBoundary(modifiedStart - 1)) {
        return true;
      }
      if (modifiedLength > 0) {
        const modifiedEnd = modifiedStart + modifiedLength;
        if (this._ModifiedIsBoundary(modifiedEnd - 1) || this._ModifiedIsBoundary(modifiedEnd)) {
          return true;
        }
      }
      return false;
    }
    _boundaryScore(originalStart, originalLength, modifiedStart, modifiedLength) {
      const originalScore = this._OriginalRegionIsBoundary(originalStart, originalLength) ? 1 : 0;
      const modifiedScore = this._ModifiedRegionIsBoundary(modifiedStart, modifiedLength) ? 1 : 0;
      return originalScore + modifiedScore;
    }
    /**
     * Concatenates the two input DiffChange lists and returns the resulting
     * list.
     * @param The left changes
     * @param The right changes
     * @returns The concatenated list
     */
    ConcatenateChanges(left, right) {
      const mergedChangeArr = [];
      if (left.length === 0 || right.length === 0) {
        return right.length > 0 ? right : left;
      } else if (this.ChangesOverlap(left[left.length - 1], right[0], mergedChangeArr)) {
        const result = new Array(left.length + right.length - 1);
        MyArray.Copy(left, 0, result, 0, left.length - 1);
        result[left.length - 1] = mergedChangeArr[0];
        MyArray.Copy(right, 1, result, left.length, right.length - 1);
        return result;
      } else {
        const result = new Array(left.length + right.length);
        MyArray.Copy(left, 0, result, 0, left.length);
        MyArray.Copy(right, 0, result, left.length, right.length);
        return result;
      }
    }
    /**
     * Returns true if the two changes overlap and can be merged into a single
     * change
     * @param left The left change
     * @param right The right change
     * @param mergedChange The merged change if the two overlap, null otherwise
     * @returns True if the two changes overlap
     */
    ChangesOverlap(left, right, mergedChangeArr) {
      Debug.Assert(left.originalStart <= right.originalStart, "Left change is not less than or equal to right change");
      Debug.Assert(left.modifiedStart <= right.modifiedStart, "Left change is not less than or equal to right change");
      if (left.originalStart + left.originalLength >= right.originalStart || left.modifiedStart + left.modifiedLength >= right.modifiedStart) {
        const originalStart = left.originalStart;
        let originalLength = left.originalLength;
        const modifiedStart = left.modifiedStart;
        let modifiedLength = left.modifiedLength;
        if (left.originalStart + left.originalLength >= right.originalStart) {
          originalLength = right.originalStart + right.originalLength - left.originalStart;
        }
        if (left.modifiedStart + left.modifiedLength >= right.modifiedStart) {
          modifiedLength = right.modifiedStart + right.modifiedLength - left.modifiedStart;
        }
        mergedChangeArr[0] = new DiffChange(originalStart, originalLength, modifiedStart, modifiedLength);
        return true;
      } else {
        mergedChangeArr[0] = null;
        return false;
      }
    }
    /**
     * Helper method used to clip a diagonal index to the range of valid
     * diagonals. This also decides whether or not the diagonal index,
     * if it exceeds the boundary, should be clipped to the boundary or clipped
     * one inside the boundary depending on the Even/Odd status of the boundary
     * and numDifferences.
     * @param diagonal The index of the diagonal to clip.
     * @param numDifferences The current number of differences being iterated upon.
     * @param diagonalBaseIndex The base reference diagonal.
     * @param numDiagonals The total number of diagonals.
     * @returns The clipped diagonal index.
     */
    ClipDiagonalBound(diagonal, numDifferences, diagonalBaseIndex, numDiagonals) {
      if (diagonal >= 0 && diagonal < numDiagonals) {
        return diagonal;
      }
      const diagonalsBelow = diagonalBaseIndex;
      const diagonalsAbove = numDiagonals - diagonalBaseIndex - 1;
      const diffEven = numDifferences % 2 === 0;
      if (diagonal < 0) {
        const lowerBoundEven = diagonalsBelow % 2 === 0;
        return diffEven === lowerBoundEven ? 0 : 1;
      } else {
        const upperBoundEven = diagonalsAbove % 2 === 0;
        return diffEven === upperBoundEven ? numDiagonals - 1 : numDiagonals - 2;
      }
    }
  }
  function isFilterResult(obj) {
    return !!obj && obj.visibility !== void 0;
  }
  function getVisibleState(visibility) {
    switch (visibility) {
      case true:
        return 1;
      case false:
        return 0;
      default:
        return visibility;
    }
  }
  function isCollapsibleStateUpdate(update) {
    return "collapsible" in update;
  }
  class IndexTreeModel {
    constructor(user, rootElement, options = {}) {
      this.user = user;
      this.rootRef = [];
      this.eventBufferer = new EventBufferer();
      this._onDidSpliceModel = new Emitter$1();
      this.onDidSpliceModel = this._onDidSpliceModel.event;
      this._onDidSpliceRenderedNodes = new Emitter$1();
      this.onDidSpliceRenderedNodes = this._onDidSpliceRenderedNodes.event;
      this._onDidChangeCollapseState = new Emitter$1();
      this.onDidChangeCollapseState = this.eventBufferer.wrapEvent(this._onDidChangeCollapseState.event);
      this._onDidChangeRenderNodeCount = new Emitter$1();
      this.onDidChangeRenderNodeCount = this.eventBufferer.wrapEvent(this._onDidChangeRenderNodeCount.event);
      this.refilterDelayer = new Delayer(MicrotaskDelay);
      this.collapseByDefault = typeof options.collapseByDefault === "undefined" ? false : options.collapseByDefault;
      this.allowNonCollapsibleParents = options.allowNonCollapsibleParents ?? false;
      this.filter = options.filter;
      this.autoExpandSingleChildren = typeof options.autoExpandSingleChildren === "undefined" ? false : options.autoExpandSingleChildren;
      this.root = {
        parent: void 0,
        element: rootElement,
        children: [],
        depth: 0,
        visibleChildrenCount: 0,
        visibleChildIndex: -1,
        collapsible: false,
        collapsed: false,
        renderNodeCount: 0,
        visibility: 1,
        visible: true,
        filterData: void 0
      };
    }
    splice(location, deleteCount, toInsert = Iterable.empty(), options = {}) {
      if (location.length === 0) {
        throw new TreeError(this.user, "Invalid tree location");
      }
      if (options.diffIdentityProvider) {
        this.spliceSmart(options.diffIdentityProvider, location, deleteCount, toInsert, options);
      } else {
        this.spliceSimple(location, deleteCount, toInsert, options);
      }
    }
    spliceSmart(identity2, location, deleteCount, toInsertIterable = Iterable.empty(), options, recurseLevels = options.diffDepth ?? 0) {
      const { parentNode } = this.getParentNodeWithListIndex(location);
      if (!parentNode.lastDiffIds) {
        return this.spliceSimple(location, deleteCount, toInsertIterable, options);
      }
      const toInsert = [...toInsertIterable];
      const index = location[location.length - 1];
      const diff = new LcsDiff({ getElements: () => parentNode.lastDiffIds }, {
        getElements: () => [
          ...parentNode.children.slice(0, index),
          ...toInsert,
          ...parentNode.children.slice(index + deleteCount)
        ].map((e) => identity2.getId(e.element).toString())
      }).ComputeDiff(false);
      if (diff.quitEarly) {
        parentNode.lastDiffIds = void 0;
        return this.spliceSimple(location, deleteCount, toInsert, options);
      }
      const locationPrefix = location.slice(0, -1);
      const recurseSplice = (fromOriginal, fromModified, count) => {
        if (recurseLevels > 0) {
          for (let i2 = 0; i2 < count; i2++) {
            fromOriginal--;
            fromModified--;
            this.spliceSmart(identity2, [...locationPrefix, fromOriginal, 0], Number.MAX_SAFE_INTEGER, toInsert[fromModified].children, options, recurseLevels - 1);
          }
        }
      };
      let lastStartO = Math.min(parentNode.children.length, index + deleteCount);
      let lastStartM = toInsert.length;
      for (const change of diff.changes.sort((a, b) => b.originalStart - a.originalStart)) {
        recurseSplice(lastStartO, lastStartM, lastStartO - (change.originalStart + change.originalLength));
        lastStartO = change.originalStart;
        lastStartM = change.modifiedStart - index;
        this.spliceSimple([...locationPrefix, lastStartO], change.originalLength, Iterable.slice(toInsert, lastStartM, lastStartM + change.modifiedLength), options);
      }
      recurseSplice(lastStartO, lastStartM, lastStartO);
    }
    spliceSimple(location, deleteCount, toInsert = Iterable.empty(), { onDidCreateNode, onDidDeleteNode, diffIdentityProvider }) {
      const { parentNode, listIndex, revealed, visible } = this.getParentNodeWithListIndex(location);
      const treeListElementsToInsert = [];
      const nodesToInsertIterator = Iterable.map(toInsert, (el) => this.createTreeNode(el, parentNode, parentNode.visible ? 1 : 0, revealed, treeListElementsToInsert, onDidCreateNode));
      const lastIndex = location[location.length - 1];
      let visibleChildStartIndex = 0;
      for (let i2 = lastIndex; i2 >= 0 && i2 < parentNode.children.length; i2--) {
        const child = parentNode.children[i2];
        if (child.visible) {
          visibleChildStartIndex = child.visibleChildIndex;
          break;
        }
      }
      const nodesToInsert = [];
      let insertedVisibleChildrenCount = 0;
      let renderNodeCount = 0;
      for (const child of nodesToInsertIterator) {
        nodesToInsert.push(child);
        renderNodeCount += child.renderNodeCount;
        if (child.visible) {
          child.visibleChildIndex = visibleChildStartIndex + insertedVisibleChildrenCount++;
        }
      }
      const deletedNodes = splice$1(parentNode.children, lastIndex, deleteCount, nodesToInsert);
      if (!diffIdentityProvider) {
        parentNode.lastDiffIds = void 0;
      } else if (parentNode.lastDiffIds) {
        splice$1(parentNode.lastDiffIds, lastIndex, deleteCount, nodesToInsert.map((n2) => diffIdentityProvider.getId(n2.element).toString()));
      } else {
        parentNode.lastDiffIds = parentNode.children.map((n2) => diffIdentityProvider.getId(n2.element).toString());
      }
      let deletedVisibleChildrenCount = 0;
      for (const child of deletedNodes) {
        if (child.visible) {
          deletedVisibleChildrenCount++;
        }
      }
      if (deletedVisibleChildrenCount !== 0) {
        for (let i2 = lastIndex + nodesToInsert.length; i2 < parentNode.children.length; i2++) {
          const child = parentNode.children[i2];
          if (child.visible) {
            child.visibleChildIndex -= deletedVisibleChildrenCount;
          }
        }
      }
      parentNode.visibleChildrenCount += insertedVisibleChildrenCount - deletedVisibleChildrenCount;
      if (deletedNodes.length > 0 && onDidDeleteNode) {
        const visit = (node2) => {
          onDidDeleteNode(node2);
          node2.children.forEach(visit);
        };
        deletedNodes.forEach(visit);
      }
      if (revealed && visible) {
        const visibleDeleteCount = deletedNodes.reduce((r, node2) => r + (node2.visible ? node2.renderNodeCount : 0), 0);
        this._updateAncestorsRenderNodeCount(parentNode, renderNodeCount - visibleDeleteCount);
        this._onDidSpliceRenderedNodes.fire({ start: listIndex, deleteCount: visibleDeleteCount, elements: treeListElementsToInsert });
      }
      this._onDidSpliceModel.fire({ insertedNodes: nodesToInsert, deletedNodes });
      let node = parentNode;
      while (node) {
        if (node.visibility === 2) {
          this.refilterDelayer.trigger(() => this.refilter());
          break;
        }
        node = node.parent;
      }
    }
    rerender(location) {
      if (location.length === 0) {
        throw new TreeError(this.user, "Invalid tree location");
      }
      const { node, listIndex, revealed } = this.getTreeNodeWithListIndex(location);
      if (node.visible && revealed) {
        this._onDidSpliceRenderedNodes.fire({ start: listIndex, deleteCount: 1, elements: [node] });
      }
    }
    has(location) {
      return this.hasTreeNode(location);
    }
    getListIndex(location) {
      const { listIndex, visible, revealed } = this.getTreeNodeWithListIndex(location);
      return visible && revealed ? listIndex : -1;
    }
    getListRenderCount(location) {
      return this.getTreeNode(location).renderNodeCount;
    }
    isCollapsible(location) {
      return this.getTreeNode(location).collapsible;
    }
    setCollapsible(location, collapsible) {
      const node = this.getTreeNode(location);
      if (typeof collapsible === "undefined") {
        collapsible = !node.collapsible;
      }
      const update = { collapsible };
      return this.eventBufferer.bufferEvents(() => this._setCollapseState(location, update));
    }
    isCollapsed(location) {
      return this.getTreeNode(location).collapsed;
    }
    setCollapsed(location, collapsed2, recursive) {
      const node = this.getTreeNode(location);
      if (typeof collapsed2 === "undefined") {
        collapsed2 = !node.collapsed;
      }
      const update = { collapsed: collapsed2, recursive: recursive || false };
      return this.eventBufferer.bufferEvents(() => this._setCollapseState(location, update));
    }
    _setCollapseState(location, update) {
      const { node, listIndex, revealed } = this.getTreeNodeWithListIndex(location);
      const result = this._setListNodeCollapseState(node, listIndex, revealed, update);
      if (node !== this.root && this.autoExpandSingleChildren && result && !isCollapsibleStateUpdate(update) && node.collapsible && !node.collapsed && !update.recursive) {
        let onlyVisibleChildIndex = -1;
        for (let i2 = 0; i2 < node.children.length; i2++) {
          const child = node.children[i2];
          if (child.visible) {
            if (onlyVisibleChildIndex > -1) {
              onlyVisibleChildIndex = -1;
              break;
            } else {
              onlyVisibleChildIndex = i2;
            }
          }
        }
        if (onlyVisibleChildIndex > -1) {
          this._setCollapseState([...location, onlyVisibleChildIndex], update);
        }
      }
      return result;
    }
    _setListNodeCollapseState(node, listIndex, revealed, update) {
      const result = this._setNodeCollapseState(node, update, false);
      if (!revealed || !node.visible || !result) {
        return result;
      }
      const previousRenderNodeCount = node.renderNodeCount;
      const toInsert = this.updateNodeAfterCollapseChange(node);
      const deleteCount = previousRenderNodeCount - (listIndex === -1 ? 0 : 1);
      this._onDidSpliceRenderedNodes.fire({ start: listIndex + 1, deleteCount, elements: toInsert.slice(1) });
      return result;
    }
    _setNodeCollapseState(node, update, deep) {
      let result;
      if (node === this.root) {
        result = false;
      } else {
        if (isCollapsibleStateUpdate(update)) {
          result = node.collapsible !== update.collapsible;
          node.collapsible = update.collapsible;
        } else if (!node.collapsible) {
          result = false;
        } else {
          result = node.collapsed !== update.collapsed;
          node.collapsed = update.collapsed;
        }
        if (result) {
          this._onDidChangeCollapseState.fire({ node, deep });
        }
      }
      if (!isCollapsibleStateUpdate(update) && update.recursive) {
        for (const child of node.children) {
          result = this._setNodeCollapseState(child, update, true) || result;
        }
      }
      return result;
    }
    expandTo(location) {
      this.eventBufferer.bufferEvents(() => {
        let node = this.getTreeNode(location);
        while (node.parent) {
          node = node.parent;
          location = location.slice(0, location.length - 1);
          if (node.collapsed) {
            this._setCollapseState(location, { collapsed: false, recursive: false });
          }
        }
      });
    }
    refilter() {
      const previousRenderNodeCount = this.root.renderNodeCount;
      const toInsert = this.updateNodeAfterFilterChange(this.root);
      this._onDidSpliceRenderedNodes.fire({ start: 0, deleteCount: previousRenderNodeCount, elements: toInsert });
      this.refilterDelayer.cancel();
    }
    createTreeNode(treeElement, parent, parentVisibility, revealed, treeListElements, onDidCreateNode) {
      const node = {
        parent,
        element: treeElement.element,
        children: [],
        depth: parent.depth + 1,
        visibleChildrenCount: 0,
        visibleChildIndex: -1,
        collapsible: typeof treeElement.collapsible === "boolean" ? treeElement.collapsible : typeof treeElement.collapsed !== "undefined",
        collapsed: typeof treeElement.collapsed === "undefined" ? this.collapseByDefault : treeElement.collapsed,
        renderNodeCount: 1,
        visibility: 1,
        visible: true,
        filterData: void 0
      };
      const visibility = this._filterNode(node, parentVisibility);
      node.visibility = visibility;
      if (revealed) {
        treeListElements.push(node);
      }
      const childElements = treeElement.children || Iterable.empty();
      const childRevealed = revealed && visibility !== 0 && !node.collapsed;
      let visibleChildrenCount = 0;
      let renderNodeCount = 1;
      for (const el of childElements) {
        const child = this.createTreeNode(el, node, visibility, childRevealed, treeListElements, onDidCreateNode);
        node.children.push(child);
        renderNodeCount += child.renderNodeCount;
        if (child.visible) {
          child.visibleChildIndex = visibleChildrenCount++;
        }
      }
      if (!this.allowNonCollapsibleParents) {
        node.collapsible = node.collapsible || node.children.length > 0;
      }
      node.visibleChildrenCount = visibleChildrenCount;
      node.visible = visibility === 2 ? visibleChildrenCount > 0 : visibility === 1;
      if (!node.visible) {
        node.renderNodeCount = 0;
        if (revealed) {
          treeListElements.pop();
        }
      } else if (!node.collapsed) {
        node.renderNodeCount = renderNodeCount;
      }
      onDidCreateNode?.(node);
      return node;
    }
    updateNodeAfterCollapseChange(node) {
      const previousRenderNodeCount = node.renderNodeCount;
      const result = [];
      this._updateNodeAfterCollapseChange(node, result);
      this._updateAncestorsRenderNodeCount(node.parent, result.length - previousRenderNodeCount);
      return result;
    }
    _updateNodeAfterCollapseChange(node, result) {
      if (node.visible === false) {
        return 0;
      }
      result.push(node);
      node.renderNodeCount = 1;
      if (!node.collapsed) {
        for (const child of node.children) {
          node.renderNodeCount += this._updateNodeAfterCollapseChange(child, result);
        }
      }
      this._onDidChangeRenderNodeCount.fire(node);
      return node.renderNodeCount;
    }
    updateNodeAfterFilterChange(node) {
      const previousRenderNodeCount = node.renderNodeCount;
      const result = [];
      this._updateNodeAfterFilterChange(node, node.visible ? 1 : 0, result);
      this._updateAncestorsRenderNodeCount(node.parent, result.length - previousRenderNodeCount);
      return result;
    }
    _updateNodeAfterFilterChange(node, parentVisibility, result, revealed = true) {
      let visibility;
      if (node !== this.root) {
        visibility = this._filterNode(node, parentVisibility);
        if (visibility === 0) {
          node.visible = false;
          node.renderNodeCount = 0;
          return false;
        }
        if (revealed) {
          result.push(node);
        }
      }
      const resultStartLength = result.length;
      node.renderNodeCount = node === this.root ? 0 : 1;
      let hasVisibleDescendants = false;
      if (!node.collapsed || visibility !== 0) {
        let visibleChildIndex = 0;
        for (const child of node.children) {
          hasVisibleDescendants = this._updateNodeAfterFilterChange(child, visibility, result, revealed && !node.collapsed) || hasVisibleDescendants;
          if (child.visible) {
            child.visibleChildIndex = visibleChildIndex++;
          }
        }
        node.visibleChildrenCount = visibleChildIndex;
      } else {
        node.visibleChildrenCount = 0;
      }
      if (node !== this.root) {
        node.visible = visibility === 2 ? hasVisibleDescendants : visibility === 1;
        node.visibility = visibility;
      }
      if (!node.visible) {
        node.renderNodeCount = 0;
        if (revealed) {
          result.pop();
        }
      } else if (!node.collapsed) {
        node.renderNodeCount += result.length - resultStartLength;
      }
      this._onDidChangeRenderNodeCount.fire(node);
      return node.visible;
    }
    _updateAncestorsRenderNodeCount(node, diff) {
      if (diff === 0) {
        return;
      }
      while (node) {
        node.renderNodeCount += diff;
        this._onDidChangeRenderNodeCount.fire(node);
        node = node.parent;
      }
    }
    _filterNode(node, parentVisibility) {
      const result = this.filter ? this.filter.filter(node.element, parentVisibility) : 1;
      if (typeof result === "boolean") {
        node.filterData = void 0;
        return result ? 1 : 0;
      } else if (isFilterResult(result)) {
        node.filterData = result.data;
        return getVisibleState(result.visibility);
      } else {
        node.filterData = void 0;
        return getVisibleState(result);
      }
    }
    // cheap
    hasTreeNode(location, node = this.root) {
      if (!location || location.length === 0) {
        return true;
      }
      const [index, ...rest] = location;
      if (index < 0 || index > node.children.length) {
        return false;
      }
      return this.hasTreeNode(rest, node.children[index]);
    }
    // cheap
    getTreeNode(location, node = this.root) {
      if (!location || location.length === 0) {
        return node;
      }
      const [index, ...rest] = location;
      if (index < 0 || index > node.children.length) {
        throw new TreeError(this.user, "Invalid tree location");
      }
      return this.getTreeNode(rest, node.children[index]);
    }
    // expensive
    getTreeNodeWithListIndex(location) {
      if (location.length === 0) {
        return { node: this.root, listIndex: -1, revealed: true, visible: false };
      }
      const { parentNode, listIndex, revealed, visible } = this.getParentNodeWithListIndex(location);
      const index = location[location.length - 1];
      if (index < 0 || index > parentNode.children.length) {
        throw new TreeError(this.user, "Invalid tree location");
      }
      const node = parentNode.children[index];
      return { node, listIndex, revealed, visible: visible && node.visible };
    }
    getParentNodeWithListIndex(location, node = this.root, listIndex = 0, revealed = true, visible = true) {
      const [index, ...rest] = location;
      if (index < 0 || index > node.children.length) {
        throw new TreeError(this.user, "Invalid tree location");
      }
      for (let i2 = 0; i2 < index; i2++) {
        listIndex += node.children[i2].renderNodeCount;
      }
      revealed = revealed && !node.collapsed;
      visible = visible && node.visible;
      if (rest.length === 0) {
        return { parentNode: node, listIndex, revealed, visible };
      }
      return this.getParentNodeWithListIndex(rest, node.children[index], listIndex + 1, revealed, visible);
    }
    getNode(location = []) {
      return this.getTreeNode(location);
    }
    // TODO@joao perf!
    getNodeLocation(node) {
      const location = [];
      let indexTreeNode = node;
      while (indexTreeNode.parent) {
        location.push(indexTreeNode.parent.children.indexOf(indexTreeNode));
        indexTreeNode = indexTreeNode.parent;
      }
      return location.reverse();
    }
    getParentNodeLocation(location) {
      if (location.length === 0) {
        return void 0;
      } else if (location.length === 1) {
        return [];
      } else {
        return tail(location)[0];
      }
    }
    getFirstElementChild(location) {
      const node = this.getTreeNode(location);
      if (node.children.length === 0) {
        return void 0;
      }
      return node.children[0].element;
    }
  }
  class TreeElementsDragAndDropData extends ElementsDragAndDropData {
    constructor(data) {
      super(data.elements.map((node) => node.element));
      this.data = data;
    }
  }
  function asTreeDragAndDropData(data) {
    if (data instanceof ElementsDragAndDropData) {
      return new TreeElementsDragAndDropData(data);
    }
    return data;
  }
  class TreeNodeListDragAndDrop {
    constructor(modelProvider, dnd) {
      this.modelProvider = modelProvider;
      this.dnd = dnd;
      this.autoExpandDisposable = Disposable.None;
      this.disposables = new DisposableStore();
    }
    getDragURI(node) {
      return this.dnd.getDragURI(node.element);
    }
    getDragLabel(nodes, originalEvent) {
      if (this.dnd.getDragLabel) {
        return this.dnd.getDragLabel(nodes.map((node) => node.element), originalEvent);
      }
      return void 0;
    }
    onDragStart(data, originalEvent) {
      this.dnd.onDragStart?.(asTreeDragAndDropData(data), originalEvent);
    }
    onDragOver(data, targetNode, targetIndex, targetSector, originalEvent, raw = true) {
      const result = this.dnd.onDragOver(asTreeDragAndDropData(data), targetNode && targetNode.element, targetIndex, targetSector, originalEvent);
      const didChangeAutoExpandNode = this.autoExpandNode !== targetNode;
      if (didChangeAutoExpandNode) {
        this.autoExpandDisposable.dispose();
        this.autoExpandNode = targetNode;
      }
      if (typeof targetNode === "undefined") {
        return result;
      }
      if (didChangeAutoExpandNode && typeof result !== "boolean" && result.autoExpand) {
        this.autoExpandDisposable = disposableTimeout(() => {
          const model2 = this.modelProvider();
          const ref2 = model2.getNodeLocation(targetNode);
          if (model2.isCollapsed(ref2)) {
            model2.setCollapsed(ref2, false);
          }
          this.autoExpandNode = void 0;
        }, 500, this.disposables);
      }
      if (typeof result === "boolean" || !result.accept || typeof result.bubble === "undefined" || result.feedback) {
        if (!raw) {
          const accept = typeof result === "boolean" ? result : result.accept;
          const effect = typeof result === "boolean" ? void 0 : result.effect;
          return { accept, effect, feedback: [targetIndex] };
        }
        return result;
      }
      if (result.bubble === 1) {
        const model2 = this.modelProvider();
        const ref2 = model2.getNodeLocation(targetNode);
        const parentRef = model2.getParentNodeLocation(ref2);
        const parentNode = model2.getNode(parentRef);
        const parentIndex = parentRef && model2.getListIndex(parentRef);
        return this.onDragOver(data, parentNode, parentIndex, targetSector, originalEvent, false);
      }
      const model = this.modelProvider();
      const ref = model.getNodeLocation(targetNode);
      const start = model.getListIndex(ref);
      const length = model.getListRenderCount(ref);
      return { ...result, feedback: range(start, start + length) };
    }
    drop(data, targetNode, targetIndex, targetSector, originalEvent) {
      this.autoExpandDisposable.dispose();
      this.autoExpandNode = void 0;
      this.dnd.drop(asTreeDragAndDropData(data), targetNode && targetNode.element, targetIndex, targetSector, originalEvent);
    }
    onDragEnd(originalEvent) {
      this.dnd.onDragEnd?.(originalEvent);
    }
    dispose() {
      this.disposables.dispose();
      this.dnd.dispose();
    }
  }
  function asListOptions(modelProvider, disposableStore, options) {
    return options && {
      ...options,
      identityProvider: options.identityProvider && {
        getId(el) {
          return options.identityProvider.getId(el.element);
        }
      },
      dnd: options.dnd && disposableStore.add(new TreeNodeListDragAndDrop(modelProvider, options.dnd)),
      multipleSelectionController: options.multipleSelectionController && {
        isSelectionSingleChangeEvent(e) {
          return options.multipleSelectionController.isSelectionSingleChangeEvent({ ...e, element: e.element });
        },
        isSelectionRangeChangeEvent(e) {
          return options.multipleSelectionController.isSelectionRangeChangeEvent({ ...e, element: e.element });
        }
      },
      accessibilityProvider: options.accessibilityProvider && {
        ...options.accessibilityProvider,
        getSetSize(node) {
          const model = modelProvider();
          const ref = model.getNodeLocation(node);
          const parentRef = model.getParentNodeLocation(ref);
          const parentNode = model.getNode(parentRef);
          return parentNode.visibleChildrenCount;
        },
        getPosInSet(node) {
          return node.visibleChildIndex + 1;
        },
        isChecked: options.accessibilityProvider && options.accessibilityProvider.isChecked ? (node) => {
          return options.accessibilityProvider.isChecked(node.element);
        } : void 0,
        getRole: options.accessibilityProvider && options.accessibilityProvider.getRole ? (node) => {
          return options.accessibilityProvider.getRole(node.element);
        } : () => "treeitem",
        getAriaLabel(e) {
          return options.accessibilityProvider.getAriaLabel(e.element);
        },
        getWidgetAriaLabel() {
          return options.accessibilityProvider.getWidgetAriaLabel();
        },
        getWidgetRole: options.accessibilityProvider && options.accessibilityProvider.getWidgetRole ? () => options.accessibilityProvider.getWidgetRole() : () => "tree",
        getAriaLevel: options.accessibilityProvider && options.accessibilityProvider.getAriaLevel ? (node) => options.accessibilityProvider.getAriaLevel(node.element) : (node) => {
          return node.depth;
        },
        getActiveDescendantId: options.accessibilityProvider.getActiveDescendantId && ((node) => {
          return options.accessibilityProvider.getActiveDescendantId(node.element);
        })
      },
      keyboardNavigationLabelProvider: options.keyboardNavigationLabelProvider && {
        ...options.keyboardNavigationLabelProvider,
        getKeyboardNavigationLabel(node) {
          return options.keyboardNavigationLabelProvider.getKeyboardNavigationLabel(node.element);
        }
      }
    };
  }
  class ComposedTreeDelegate {
    constructor(delegate) {
      this.delegate = delegate;
    }
    getHeight(element) {
      return this.delegate.getHeight(element.element);
    }
    getTemplateId(element) {
      return this.delegate.getTemplateId(element.element);
    }
    hasDynamicHeight(element) {
      return !!this.delegate.hasDynamicHeight && this.delegate.hasDynamicHeight(element.element);
    }
    setDynamicHeight(element, height) {
      this.delegate.setDynamicHeight?.(element.element, height);
    }
  }
  var RenderIndentGuides;
  (function(RenderIndentGuides2) {
    RenderIndentGuides2["None"] = "none";
    RenderIndentGuides2["OnHover"] = "onHover";
    RenderIndentGuides2["Always"] = "always";
  })(RenderIndentGuides || (RenderIndentGuides = {}));
  class EventCollection {
    get elements() {
      return this._elements;
    }
    constructor(onDidChange, _elements = []) {
      this._elements = _elements;
      this.disposables = new DisposableStore();
      this.onDidChange = Event.forEach(onDidChange, (elements) => this._elements = elements, this.disposables);
    }
    dispose() {
      this.disposables.dispose();
    }
  }
  const _TreeRenderer = class _TreeRenderer {
    constructor(renderer, model, onDidChangeCollapseState, activeNodes, renderedIndentGuides, options = {}) {
      this.renderer = renderer;
      this.model = model;
      this.activeNodes = activeNodes;
      this.renderedIndentGuides = renderedIndentGuides;
      this.renderedElements = /* @__PURE__ */ new Map();
      this.renderedNodes = /* @__PURE__ */ new Map();
      this.indent = _TreeRenderer.DefaultIndent;
      this.hideTwistiesOfChildlessElements = false;
      this.shouldRenderIndentGuides = false;
      this.activeIndentNodes = /* @__PURE__ */ new Set();
      this.indentGuidesDisposable = Disposable.None;
      this.disposables = new DisposableStore();
      this.templateId = renderer.templateId;
      this.updateOptions(options);
      Event.map(onDidChangeCollapseState, (e) => e.node)(this.onDidChangeNodeTwistieState, this, this.disposables);
      renderer.onDidChangeTwistieState?.(this.onDidChangeTwistieState, this, this.disposables);
    }
    updateOptions(options = {}) {
      if (typeof options.indent !== "undefined") {
        const indent = clamp(options.indent, 0, 40);
        if (indent !== this.indent) {
          this.indent = indent;
          for (const [node, templateData] of this.renderedNodes) {
            templateData.indentSize = _TreeRenderer.DefaultIndent + (node.depth - 1) * this.indent;
            this.renderTreeElement(node, templateData);
          }
        }
      }
      if (typeof options.renderIndentGuides !== "undefined") {
        const shouldRenderIndentGuides = options.renderIndentGuides !== RenderIndentGuides.None;
        if (shouldRenderIndentGuides !== this.shouldRenderIndentGuides) {
          this.shouldRenderIndentGuides = shouldRenderIndentGuides;
          for (const [node, templateData] of this.renderedNodes) {
            this._renderIndentGuides(node, templateData);
          }
          this.indentGuidesDisposable.dispose();
          if (shouldRenderIndentGuides) {
            const disposables = new DisposableStore();
            this.activeNodes.onDidChange(this._onDidChangeActiveNodes, this, disposables);
            this.indentGuidesDisposable = disposables;
            this._onDidChangeActiveNodes(this.activeNodes.elements);
          }
        }
      }
      if (typeof options.hideTwistiesOfChildlessElements !== "undefined") {
        this.hideTwistiesOfChildlessElements = options.hideTwistiesOfChildlessElements;
      }
    }
    renderTemplate(container) {
      const el = append$2(container, $$l(".monaco-tl-row"));
      const indent = append$2(el, $$l(".monaco-tl-indent"));
      const twistie = append$2(el, $$l(".monaco-tl-twistie"));
      const contents = append$2(el, $$l(".monaco-tl-contents"));
      const templateData = this.renderer.renderTemplate(contents);
      return { container, indent, twistie, indentGuidesDisposable: Disposable.None, indentSize: 0, templateData };
    }
    renderElement(node, index, templateData, details) {
      templateData.indentSize = _TreeRenderer.DefaultIndent + (node.depth - 1) * this.indent;
      this.renderedNodes.set(node, templateData);
      this.renderedElements.set(node.element, node);
      this.renderTreeElement(node, templateData);
      this.renderer.renderElement(node, index, templateData.templateData, { ...details, indent: templateData.indentSize });
    }
    disposeElement(node, index, templateData, details) {
      templateData.indentGuidesDisposable.dispose();
      this.renderer.disposeElement?.(node, index, templateData.templateData, { ...details, indent: templateData.indentSize });
      if (typeof details?.height === "number") {
        this.renderedNodes.delete(node);
        this.renderedElements.delete(node.element);
      }
    }
    disposeTemplate(templateData) {
      this.renderer.disposeTemplate(templateData.templateData);
    }
    onDidChangeTwistieState(element) {
      const node = this.renderedElements.get(element);
      if (!node) {
        return;
      }
      this.onDidChangeNodeTwistieState(node);
    }
    onDidChangeNodeTwistieState(node) {
      const templateData = this.renderedNodes.get(node);
      if (!templateData) {
        return;
      }
      this._onDidChangeActiveNodes(this.activeNodes.elements);
      this.renderTreeElement(node, templateData);
    }
    renderTreeElement(node, templateData) {
      templateData.twistie.style.paddingLeft = `${templateData.indentSize}px`;
      templateData.indent.style.width = `${templateData.indentSize + this.indent - 16}px`;
      if (node.collapsible) {
        templateData.container.setAttribute("aria-expanded", String(!node.collapsed));
      } else {
        templateData.container.removeAttribute("aria-expanded");
      }
      templateData.twistie.classList.remove(...ThemeIcon.asClassNameArray(Codicon.treeItemExpanded));
      let twistieRendered = false;
      if (this.renderer.renderTwistie) {
        twistieRendered = this.renderer.renderTwistie(node.element, templateData.twistie);
      }
      if (node.collapsible && (!this.hideTwistiesOfChildlessElements || node.visibleChildrenCount > 0)) {
        if (!twistieRendered) {
          templateData.twistie.classList.add(...ThemeIcon.asClassNameArray(Codicon.treeItemExpanded));
        }
        templateData.twistie.classList.add("collapsible");
        templateData.twistie.classList.toggle("collapsed", node.collapsed);
      } else {
        templateData.twistie.classList.remove("collapsible", "collapsed");
      }
      this._renderIndentGuides(node, templateData);
    }
    _renderIndentGuides(node, templateData) {
      clearNode(templateData.indent);
      templateData.indentGuidesDisposable.dispose();
      if (!this.shouldRenderIndentGuides) {
        return;
      }
      const disposableStore = new DisposableStore();
      while (true) {
        const ref = this.model.getNodeLocation(node);
        const parentRef = this.model.getParentNodeLocation(ref);
        if (!parentRef) {
          break;
        }
        const parent = this.model.getNode(parentRef);
        const guide = $$l(".indent-guide", { style: `width: ${this.indent}px` });
        if (this.activeIndentNodes.has(parent)) {
          guide.classList.add("active");
        }
        if (templateData.indent.childElementCount === 0) {
          templateData.indent.appendChild(guide);
        } else {
          templateData.indent.insertBefore(guide, templateData.indent.firstElementChild);
        }
        this.renderedIndentGuides.add(parent, guide);
        disposableStore.add(toDisposable(() => this.renderedIndentGuides.delete(parent, guide)));
        node = parent;
      }
      templateData.indentGuidesDisposable = disposableStore;
    }
    _onDidChangeActiveNodes(nodes) {
      if (!this.shouldRenderIndentGuides) {
        return;
      }
      const set = /* @__PURE__ */ new Set();
      nodes.forEach((node) => {
        const ref = this.model.getNodeLocation(node);
        try {
          const parentRef = this.model.getParentNodeLocation(ref);
          if (node.collapsible && node.children.length > 0 && !node.collapsed) {
            set.add(node);
          } else if (parentRef) {
            set.add(this.model.getNode(parentRef));
          }
        } catch {
        }
      });
      this.activeIndentNodes.forEach((node) => {
        if (!set.has(node)) {
          this.renderedIndentGuides.forEach(node, (line) => line.classList.remove("active"));
        }
      });
      set.forEach((node) => {
        if (!this.activeIndentNodes.has(node)) {
          this.renderedIndentGuides.forEach(node, (line) => line.classList.add("active"));
        }
      });
      this.activeIndentNodes = set;
    }
    dispose() {
      this.renderedNodes.clear();
      this.renderedElements.clear();
      this.indentGuidesDisposable.dispose();
      dispose(this.disposables);
    }
  };
  _TreeRenderer.DefaultIndent = 8;
  let TreeRenderer = _TreeRenderer;
  function contiguousFuzzyScore(patternLower, wordLower) {
    const index = wordLower.toLowerCase().indexOf(patternLower);
    let score2;
    if (index > -1) {
      score2 = [Number.MAX_SAFE_INTEGER, 0];
      for (let i2 = patternLower.length; i2 > 0; i2--) {
        score2.push(index + i2 - 1);
      }
    }
    return score2;
  }
  class FindFilter {
    get totalCount() {
      return this._totalCount;
    }
    get matchCount() {
      return this._matchCount;
    }
    set findMatchType(type) {
      this._findMatchType = type;
    }
    get findMatchType() {
      return this._findMatchType;
    }
    set findMode(mode) {
      this._findMode = mode;
    }
    get findMode() {
      return this._findMode;
    }
    constructor(_keyboardNavigationLabelProvider, _filter, _defaultFindVisibility) {
      this._keyboardNavigationLabelProvider = _keyboardNavigationLabelProvider;
      this._filter = _filter;
      this._defaultFindVisibility = _defaultFindVisibility;
      this._totalCount = 0;
      this._matchCount = 0;
      this._findMatchType = TreeFindMatchType.Fuzzy;
      this._findMode = TreeFindMode.Highlight;
      this._pattern = "";
      this._lowercasePattern = "";
      this.disposables = new DisposableStore();
    }
    filter(element, parentVisibility) {
      let visibility = 1;
      if (this._filter) {
        const result = this._filter.filter(element, parentVisibility);
        if (typeof result === "boolean") {
          visibility = result ? 1 : 0;
        } else if (isFilterResult(result)) {
          visibility = getVisibleState(result.visibility);
        } else {
          visibility = result;
        }
        if (visibility === 0) {
          return false;
        }
      }
      this._totalCount++;
      if (!this._pattern) {
        this._matchCount++;
        return { data: FuzzyScore.Default, visibility };
      }
      const label = this._keyboardNavigationLabelProvider.getKeyboardNavigationLabel(element);
      const labels = Array.isArray(label) ? label : [label];
      for (const l of labels) {
        const labelStr = l && l.toString();
        if (typeof labelStr === "undefined") {
          return { data: FuzzyScore.Default, visibility };
        }
        let score2;
        if (this._findMatchType === TreeFindMatchType.Contiguous) {
          score2 = contiguousFuzzyScore(this._lowercasePattern, labelStr.toLowerCase());
        } else {
          score2 = fuzzyScore(this._pattern, this._lowercasePattern, 0, labelStr, labelStr.toLowerCase(), 0, { firstMatchCanBeWeak: true, boostFullMatch: true });
        }
        if (score2) {
          this._matchCount++;
          return labels.length === 1 ? { data: score2, visibility } : { data: { label: labelStr, score: score2 }, visibility };
        }
      }
      if (this._findMode === TreeFindMode.Filter) {
        if (typeof this._defaultFindVisibility === "number") {
          return this._defaultFindVisibility;
        } else if (this._defaultFindVisibility) {
          return this._defaultFindVisibility(element);
        } else {
          return 2;
        }
      } else {
        return { data: FuzzyScore.Default, visibility };
      }
    }
    reset() {
      this._totalCount = 0;
      this._matchCount = 0;
    }
    dispose() {
      dispose(this.disposables);
    }
  }
  class FindToggles {
    constructor(startStates) {
      this.stateMap = new Map(startStates.map((state) => [state.id, { ...state }]));
    }
    get(id) {
      const state = this.stateMap.get(id);
      if (state === void 0) {
        throw new Error(`No state found for toggle id ${id}`);
      }
      return state.isChecked;
    }
    set(id, value) {
      const state = this.stateMap.get(id);
      if (state === void 0) {
        throw new Error(`No state found for toggle id ${id}`);
      }
      if (state.isChecked === value) {
        return false;
      }
      state.isChecked = value;
      return true;
    }
  }
  var TreeFindMode;
  (function(TreeFindMode2) {
    TreeFindMode2[TreeFindMode2["Highlight"] = 0] = "Highlight";
    TreeFindMode2[TreeFindMode2["Filter"] = 1] = "Filter";
  })(TreeFindMode || (TreeFindMode = {}));
  var TreeFindMatchType;
  (function(TreeFindMatchType2) {
    TreeFindMatchType2[TreeFindMatchType2["Fuzzy"] = 0] = "Fuzzy";
    TreeFindMatchType2[TreeFindMatchType2["Contiguous"] = 1] = "Contiguous";
  })(TreeFindMatchType || (TreeFindMatchType = {}));
  var DefaultTreeToggles;
  (function(DefaultTreeToggles2) {
    DefaultTreeToggles2["Mode"] = "mode";
    DefaultTreeToggles2["MatchType"] = "matchType";
  })(DefaultTreeToggles || (DefaultTreeToggles = {}));
  class AbstractFindController {
    get pattern() {
      return this._pattern;
    }
    get placeholder() {
      return this._placeholder;
    }
    set placeholder(value) {
      this._placeholder = value;
      this.widget?.setPlaceHolder(value);
    }
    constructor(tree, filter, contextViewProvider, options = {}) {
      this.tree = tree;
      this.filter = filter;
      this.contextViewProvider = contextViewProvider;
      this.options = options;
      this._pattern = "";
      this._onDidChangePattern = new Emitter$1();
      this._onDidChangeOpenState = new Emitter$1();
      this.onDidChangeOpenState = this._onDidChangeOpenState.event;
      this.enabledDisposables = new DisposableStore();
      this.disposables = new DisposableStore();
      this.toggles = new FindToggles(options.toggles ?? []);
      this._placeholder = options.placeholder ?? localize(20, "Type to search");
    }
    isOpened() {
      return !!this.widget;
    }
    updateToggleState(id, checked) {
      this.toggles.set(id, checked);
      this.widget?.setToggleState(id, checked);
    }
    renderMessage(showNotFound, warningMessage) {
      if (showNotFound) {
        if (this.tree.options.showNotFoundMessage ?? true) {
          this.widget?.showMessage({ type: 2, content: warningMessage ?? localize(21, "No results found.") });
        } else {
          this.widget?.showMessage({
            type: 2
            /* MessageType.WARNING */
          });
        }
      } else {
        this.widget?.clearMessage();
      }
    }
    alertResults(results) {
      if (!results) {
        alert(localize(22, "No results"));
      } else {
        alert(localize(23, "{0} results", results));
      }
    }
    dispose() {
      this._history = void 0;
      this._onDidChangePattern.dispose();
      this.enabledDisposables.dispose();
      this.disposables.dispose();
    }
  }
  let FindController$1 = class FindController extends AbstractFindController {
    get mode() {
      return this.toggles.get(DefaultTreeToggles.Mode) ? TreeFindMode.Filter : TreeFindMode.Highlight;
    }
    set mode(mode) {
      if (mode === this.mode) {
        return;
      }
      const isFilterMode = mode === TreeFindMode.Filter;
      this.updateToggleState(DefaultTreeToggles.Mode, isFilterMode);
      this.placeholder = isFilterMode ? localize(24, "Type to filter") : localize(25, "Type to search");
      this.filter.findMode = mode;
      this.tree.refilter();
      this.render();
      this._onDidChangeMode.fire(mode);
    }
    get matchType() {
      return this.toggles.get(DefaultTreeToggles.MatchType) ? TreeFindMatchType.Fuzzy : TreeFindMatchType.Contiguous;
    }
    set matchType(matchType) {
      if (matchType === this.matchType) {
        return;
      }
      this.updateToggleState(DefaultTreeToggles.MatchType, matchType === TreeFindMatchType.Fuzzy);
      this.filter.findMatchType = matchType;
      this.tree.refilter();
      this.render();
      this._onDidChangeMatchType.fire(matchType);
    }
    constructor(tree, filter, contextViewProvider, options = {}) {
      const defaultFindMode = options.defaultFindMode ?? TreeFindMode.Highlight;
      const defaultFindMatchType = options.defaultFindMatchType ?? TreeFindMatchType.Fuzzy;
      const toggleContributions = [{
        id: DefaultTreeToggles.Mode,
        icon: Codicon.listFilter,
        title: localize(26, "Filter"),
        isChecked: defaultFindMode === TreeFindMode.Filter
      }, {
        id: DefaultTreeToggles.MatchType,
        icon: Codicon.searchFuzzy,
        title: localize(27, "Fuzzy Match"),
        isChecked: defaultFindMatchType === TreeFindMatchType.Fuzzy
      }];
      filter.findMatchType = defaultFindMatchType;
      filter.findMode = defaultFindMode;
      super(tree, filter, contextViewProvider, { ...options, toggles: toggleContributions });
      this.filter = filter;
      this._onDidChangeMode = new Emitter$1();
      this.onDidChangeMode = this._onDidChangeMode.event;
      this._onDidChangeMatchType = new Emitter$1();
      this.onDidChangeMatchType = this._onDidChangeMatchType.event;
      this.disposables.add(this.tree.onDidChangeModel(() => {
        if (!this.isOpened()) {
          return;
        }
        if (this.pattern.length !== 0) {
          this.tree.refilter();
        }
        this.render();
      }));
      this.disposables.add(this.tree.onWillRefilter(() => this.filter.reset()));
    }
    updateOptions(optionsUpdate = {}) {
      if (optionsUpdate.defaultFindMode !== void 0) {
        this.mode = optionsUpdate.defaultFindMode;
      }
      if (optionsUpdate.defaultFindMatchType !== void 0) {
        this.matchType = optionsUpdate.defaultFindMatchType;
      }
    }
    shouldAllowFocus(node) {
      if (!this.isOpened() || !this.pattern) {
        return true;
      }
      if (this.filter.totalCount > 0 && this.filter.matchCount <= 1) {
        return true;
      }
      return !FuzzyScore.isDefault(node.filterData);
    }
    render() {
      const noMatches = this.filter.matchCount === 0 && this.filter.totalCount > 0;
      const showNotFound = noMatches && this.pattern.length > 0;
      this.renderMessage(showNotFound);
      if (this.pattern.length) {
        this.alertResults(this.filter.matchCount);
      }
    }
  };
  function stickyScrollNodeStateEquals(node1, node2) {
    return node1.position === node2.position && stickyScrollNodeEquals(node1, node2);
  }
  function stickyScrollNodeEquals(node1, node2) {
    return node1.node.element === node2.node.element && node1.startIndex === node2.startIndex && node1.height === node2.height && node1.endIndex === node2.endIndex;
  }
  class StickyScrollState {
    constructor(stickyNodes = []) {
      this.stickyNodes = stickyNodes;
    }
    get count() {
      return this.stickyNodes.length;
    }
    equal(state) {
      return equals$1(this.stickyNodes, state.stickyNodes, stickyScrollNodeStateEquals);
    }
    contains(element) {
      return this.stickyNodes.some((node) => node.node.element === element.element);
    }
    lastNodePartiallyVisible() {
      if (this.count === 0) {
        return false;
      }
      const lastStickyNode = this.stickyNodes[this.count - 1];
      if (this.count === 1) {
        return lastStickyNode.position !== 0;
      }
      const secondLastStickyNode = this.stickyNodes[this.count - 2];
      return secondLastStickyNode.position + secondLastStickyNode.height !== lastStickyNode.position;
    }
    animationStateChanged(previousState) {
      if (!equals$1(this.stickyNodes, previousState.stickyNodes, stickyScrollNodeEquals)) {
        return false;
      }
      if (this.count === 0) {
        return false;
      }
      const lastStickyNode = this.stickyNodes[this.count - 1];
      const previousLastStickyNode = previousState.stickyNodes[previousState.count - 1];
      return lastStickyNode.position !== previousLastStickyNode.position;
    }
  }
  class DefaultStickyScrollDelegate {
    constrainStickyScrollNodes(stickyNodes, stickyScrollMaxItemCount, maxWidgetHeight) {
      for (let i2 = 0; i2 < stickyNodes.length; i2++) {
        const stickyNode = stickyNodes[i2];
        const stickyNodeBottom = stickyNode.position + stickyNode.height;
        if (stickyNodeBottom > maxWidgetHeight || i2 >= stickyScrollMaxItemCount) {
          return stickyNodes.slice(0, i2);
        }
      }
      return stickyNodes;
    }
  }
  let StickyScrollController$1 = class StickyScrollController extends Disposable {
    constructor(tree, model, view, renderers, treeDelegate, options = {}) {
      super();
      this.tree = tree;
      this.model = model;
      this.view = view;
      this.treeDelegate = treeDelegate;
      this.maxWidgetViewRatio = 0.4;
      const stickyScrollOptions = this.validateStickySettings(options);
      this.stickyScrollMaxItemCount = stickyScrollOptions.stickyScrollMaxItemCount;
      this.stickyScrollDelegate = options.stickyScrollDelegate ?? new DefaultStickyScrollDelegate();
      this.paddingTop = options.paddingTop ?? 0;
      this._widget = this._register(new StickyScrollWidget$1(view.getScrollableElement(), view, tree, renderers, treeDelegate, options.accessibilityProvider));
      this.onDidChangeHasFocus = this._widget.onDidChangeHasFocus;
      this.onContextMenu = this._widget.onContextMenu;
      this._register(view.onDidScroll(() => this.update()));
      this._register(view.onDidChangeContentHeight(() => this.update()));
      this._register(tree.onDidChangeCollapseState(() => this.update()));
      this._register(model.onDidSpliceRenderedNodes((e) => {
        const state = this._widget.state;
        if (!state) {
          return;
        }
        const hasRemovedStickyNode = e.deleteCount > 0 && state.stickyNodes.some((stickyNode) => !this.model.has(this.model.getNodeLocation(stickyNode.node)));
        if (hasRemovedStickyNode) {
          this.update();
          return;
        }
        const shouldRerenderStickyNodes = state.stickyNodes.some((stickyNode) => {
          const listIndex = this.model.getListIndex(this.model.getNodeLocation(stickyNode.node));
          return listIndex >= e.start && listIndex < e.start + e.deleteCount && state.contains(stickyNode.node);
        });
        if (shouldRerenderStickyNodes) {
          this._widget.rerender();
        }
      }));
      this.update();
    }
    get height() {
      return this._widget.height;
    }
    getNodeAtHeight(height) {
      let index;
      if (height === 0) {
        index = this.view.firstVisibleIndex;
      } else {
        index = this.view.indexAt(height + this.view.scrollTop);
      }
      if (index < 0 || index >= this.view.length) {
        return void 0;
      }
      return this.view.element(index);
    }
    update() {
      const firstVisibleNode = this.getNodeAtHeight(this.paddingTop);
      if (!firstVisibleNode || this.tree.scrollTop <= this.paddingTop) {
        this._widget.setState(void 0);
        return;
      }
      const stickyState = this.findStickyState(firstVisibleNode);
      this._widget.setState(stickyState);
    }
    findStickyState(firstVisibleNode) {
      const stickyNodes = [];
      let firstVisibleNodeUnderWidget = firstVisibleNode;
      let stickyNodesHeight = 0;
      let nextStickyNode = this.getNextStickyNode(firstVisibleNodeUnderWidget, void 0, stickyNodesHeight);
      while (nextStickyNode) {
        stickyNodes.push(nextStickyNode);
        stickyNodesHeight += nextStickyNode.height;
        if (stickyNodes.length <= this.stickyScrollMaxItemCount) {
          firstVisibleNodeUnderWidget = this.getNextVisibleNode(nextStickyNode);
          if (!firstVisibleNodeUnderWidget) {
            break;
          }
        }
        nextStickyNode = this.getNextStickyNode(firstVisibleNodeUnderWidget, nextStickyNode.node, stickyNodesHeight);
      }
      const contrainedStickyNodes = this.constrainStickyNodes(stickyNodes);
      return contrainedStickyNodes.length ? new StickyScrollState(contrainedStickyNodes) : void 0;
    }
    getNextVisibleNode(previousStickyNode) {
      return this.getNodeAtHeight(previousStickyNode.position + previousStickyNode.height);
    }
    getNextStickyNode(firstVisibleNodeUnderWidget, previousStickyNode, stickyNodesHeight) {
      const nextStickyNode = this.getAncestorUnderPrevious(firstVisibleNodeUnderWidget, previousStickyNode);
      if (!nextStickyNode) {
        return void 0;
      }
      if (nextStickyNode === firstVisibleNodeUnderWidget) {
        if (!this.nodeIsUncollapsedParent(firstVisibleNodeUnderWidget)) {
          return void 0;
        }
        if (this.nodeTopAlignsWithStickyNodesBottom(firstVisibleNodeUnderWidget, stickyNodesHeight)) {
          return void 0;
        }
      }
      return this.createStickyScrollNode(nextStickyNode, stickyNodesHeight);
    }
    nodeTopAlignsWithStickyNodesBottom(node, stickyNodesHeight) {
      const nodeIndex = this.getNodeIndex(node);
      const elementTop = this.view.getElementTop(nodeIndex);
      const stickyPosition = stickyNodesHeight;
      return this.view.scrollTop === elementTop - stickyPosition;
    }
    createStickyScrollNode(node, currentStickyNodesHeight) {
      const height = this.treeDelegate.getHeight(node);
      const { startIndex, endIndex } = this.getNodeRange(node);
      const position = this.calculateStickyNodePosition(endIndex, currentStickyNodesHeight, height);
      return { node, position, height, startIndex, endIndex };
    }
    getAncestorUnderPrevious(node, previousAncestor = void 0) {
      let currentAncestor = node;
      let parentOfcurrentAncestor = this.getParentNode(currentAncestor);
      while (parentOfcurrentAncestor) {
        if (parentOfcurrentAncestor === previousAncestor) {
          return currentAncestor;
        }
        currentAncestor = parentOfcurrentAncestor;
        parentOfcurrentAncestor = this.getParentNode(currentAncestor);
      }
      if (previousAncestor === void 0) {
        return currentAncestor;
      }
      return void 0;
    }
    calculateStickyNodePosition(lastDescendantIndex, stickyRowPositionTop, stickyNodeHeight) {
      let lastChildRelativeTop = this.view.getRelativeTop(lastDescendantIndex);
      if (lastChildRelativeTop === null && this.view.firstVisibleIndex === lastDescendantIndex && lastDescendantIndex + 1 < this.view.length) {
        const nodeHeight = this.treeDelegate.getHeight(this.view.element(lastDescendantIndex));
        const nextNodeRelativeTop = this.view.getRelativeTop(lastDescendantIndex + 1);
        lastChildRelativeTop = nextNodeRelativeTop ? nextNodeRelativeTop - nodeHeight / this.view.renderHeight : null;
      }
      if (lastChildRelativeTop === null) {
        return stickyRowPositionTop;
      }
      const lastChildNode = this.view.element(lastDescendantIndex);
      const lastChildHeight = this.treeDelegate.getHeight(lastChildNode);
      const topOfLastChild = lastChildRelativeTop * this.view.renderHeight;
      const bottomOfLastChild = topOfLastChild + lastChildHeight;
      if (stickyRowPositionTop + stickyNodeHeight > bottomOfLastChild && stickyRowPositionTop <= bottomOfLastChild) {
        return bottomOfLastChild - stickyNodeHeight;
      }
      return stickyRowPositionTop;
    }
    constrainStickyNodes(stickyNodes) {
      if (stickyNodes.length === 0) {
        return [];
      }
      const maximumStickyWidgetHeight = this.view.renderHeight * this.maxWidgetViewRatio;
      const lastStickyNode = stickyNodes[stickyNodes.length - 1];
      if (stickyNodes.length <= this.stickyScrollMaxItemCount && lastStickyNode.position + lastStickyNode.height <= maximumStickyWidgetHeight) {
        return stickyNodes;
      }
      const constrainedStickyNodes = this.stickyScrollDelegate.constrainStickyScrollNodes(stickyNodes, this.stickyScrollMaxItemCount, maximumStickyWidgetHeight);
      if (!constrainedStickyNodes.length) {
        return [];
      }
      const lastConstrainedStickyNode = constrainedStickyNodes[constrainedStickyNodes.length - 1];
      if (constrainedStickyNodes.length > this.stickyScrollMaxItemCount || lastConstrainedStickyNode.position + lastConstrainedStickyNode.height > maximumStickyWidgetHeight) {
        throw new Error("stickyScrollDelegate violates constraints");
      }
      return constrainedStickyNodes;
    }
    getParentNode(node) {
      const nodeLocation = this.model.getNodeLocation(node);
      const parentLocation = this.model.getParentNodeLocation(nodeLocation);
      return parentLocation ? this.model.getNode(parentLocation) : void 0;
    }
    nodeIsUncollapsedParent(node) {
      const nodeLocation = this.model.getNodeLocation(node);
      return this.model.getListRenderCount(nodeLocation) > 1;
    }
    getNodeIndex(node) {
      const nodeLocation = this.model.getNodeLocation(node);
      const nodeIndex = this.model.getListIndex(nodeLocation);
      return nodeIndex;
    }
    getNodeRange(node) {
      const nodeLocation = this.model.getNodeLocation(node);
      const startIndex = this.model.getListIndex(nodeLocation);
      if (startIndex < 0) {
        throw new Error("Node not found in tree");
      }
      const renderCount = this.model.getListRenderCount(nodeLocation);
      const endIndex = startIndex + renderCount - 1;
      return { startIndex, endIndex };
    }
    nodePositionTopBelowWidget(node) {
      const ancestors = [];
      let currentAncestor = this.getParentNode(node);
      while (currentAncestor) {
        ancestors.push(currentAncestor);
        currentAncestor = this.getParentNode(currentAncestor);
      }
      let widgetHeight = 0;
      for (let i2 = 0; i2 < ancestors.length && i2 < this.stickyScrollMaxItemCount; i2++) {
        widgetHeight += this.treeDelegate.getHeight(ancestors[i2]);
      }
      return widgetHeight;
    }
    domFocus() {
      this._widget.domFocus();
    }
    // Whether sticky scroll was the last focused part in the tree or not
    focusedLast() {
      return this._widget.focusedLast();
    }
    updateOptions(optionsUpdate = {}) {
      if (optionsUpdate.paddingTop !== void 0) {
        this.paddingTop = optionsUpdate.paddingTop;
      }
      if (optionsUpdate.stickyScrollMaxItemCount !== void 0) {
        const validatedOptions = this.validateStickySettings(optionsUpdate);
        if (this.stickyScrollMaxItemCount !== validatedOptions.stickyScrollMaxItemCount) {
          this.stickyScrollMaxItemCount = validatedOptions.stickyScrollMaxItemCount;
          this.update();
        }
      }
    }
    validateStickySettings(options) {
      let stickyScrollMaxItemCount = 7;
      if (typeof options.stickyScrollMaxItemCount === "number") {
        stickyScrollMaxItemCount = Math.max(options.stickyScrollMaxItemCount, 1);
      }
      return { stickyScrollMaxItemCount };
    }
  };
  let StickyScrollWidget$1 = class StickyScrollWidget {
    get state() {
      return this._previousState;
    }
    constructor(container, view, tree, treeRenderers, treeDelegate, accessibilityProvider) {
      this.view = view;
      this.tree = tree;
      this.treeRenderers = treeRenderers;
      this.treeDelegate = treeDelegate;
      this.accessibilityProvider = accessibilityProvider;
      this._previousElements = [];
      this._previousStateDisposables = new DisposableStore();
      this._rootDomNode = $$l(".monaco-tree-sticky-container.empty");
      container.appendChild(this._rootDomNode);
      const shadow = $$l(".monaco-tree-sticky-container-shadow");
      this._rootDomNode.appendChild(shadow);
      this.stickyScrollFocus = new StickyScrollFocus(this._rootDomNode, view);
      this.onDidChangeHasFocus = this.stickyScrollFocus.onDidChangeHasFocus;
      this.onContextMenu = this.stickyScrollFocus.onContextMenu;
    }
    get height() {
      if (!this._previousState) {
        return 0;
      }
      const lastElement = this._previousState.stickyNodes[this._previousState.count - 1];
      return lastElement.position + lastElement.height;
    }
    setState(state) {
      const wasVisible = !!this._previousState && this._previousState.count > 0;
      const isVisible = !!state && state.count > 0;
      if (!wasVisible && !isVisible || wasVisible && isVisible && this._previousState.equal(state)) {
        return;
      }
      if (wasVisible !== isVisible) {
        this.setVisible(isVisible);
      }
      if (!isVisible) {
        this._previousState = void 0;
        this._previousElements = [];
        this._previousStateDisposables.clear();
        return;
      }
      const lastStickyNode = state.stickyNodes[state.count - 1];
      if (this._previousState && state.animationStateChanged(this._previousState)) {
        this._previousElements[this._previousState.count - 1].style.top = `${lastStickyNode.position}px`;
      } else {
        this.renderState(state);
      }
      this._previousState = state;
      this._rootDomNode.style.height = `${lastStickyNode.position + lastStickyNode.height}px`;
    }
    renderState(state) {
      this._previousStateDisposables.clear();
      const elements = Array(state.count);
      for (let stickyIndex = state.count - 1; stickyIndex >= 0; stickyIndex--) {
        const stickyNode = state.stickyNodes[stickyIndex];
        const { element, disposable } = this.createElement(stickyNode, stickyIndex, state.count);
        elements[stickyIndex] = element;
        this._rootDomNode.appendChild(element);
        this._previousStateDisposables.add(disposable);
      }
      this.stickyScrollFocus.updateElements(elements, state);
      this._previousElements = elements;
    }
    rerender() {
      if (this._previousState) {
        this.renderState(this._previousState);
      }
    }
    createElement(stickyNode, stickyIndex, stickyNodesTotal) {
      const nodeIndex = stickyNode.startIndex;
      const stickyElement = document.createElement("div");
      stickyElement.style.top = `${stickyNode.position}px`;
      if (this.tree.options.setRowHeight !== false) {
        stickyElement.style.height = `${stickyNode.height}px`;
      }
      if (this.tree.options.setRowLineHeight !== false) {
        stickyElement.style.lineHeight = `${stickyNode.height}px`;
      }
      stickyElement.classList.add("monaco-tree-sticky-row");
      stickyElement.classList.add("monaco-list-row");
      stickyElement.setAttribute("data-index", `${nodeIndex}`);
      stickyElement.setAttribute("data-parity", nodeIndex % 2 === 0 ? "even" : "odd");
      stickyElement.setAttribute("id", this.view.getElementID(nodeIndex));
      const accessibilityDisposable = this.setAccessibilityAttributes(stickyElement, stickyNode.node.element, stickyIndex, stickyNodesTotal);
      const nodeTemplateId = this.treeDelegate.getTemplateId(stickyNode.node);
      const renderer = this.treeRenderers.find((renderer2) => renderer2.templateId === nodeTemplateId);
      if (!renderer) {
        throw new Error(`No renderer found for template id ${nodeTemplateId}`);
      }
      let nodeCopy = stickyNode.node;
      if (nodeCopy === this.tree.getNode(this.tree.getNodeLocation(stickyNode.node))) {
        nodeCopy = new Proxy(stickyNode.node, {});
      }
      const templateData = renderer.renderTemplate(stickyElement);
      renderer.renderElement(nodeCopy, stickyNode.startIndex, templateData, { height: stickyNode.height });
      const disposable = toDisposable(() => {
        accessibilityDisposable.dispose();
        renderer.disposeElement(nodeCopy, stickyNode.startIndex, templateData, { height: stickyNode.height });
        renderer.disposeTemplate(templateData);
        stickyElement.remove();
      });
      return { element: stickyElement, disposable };
    }
    setAccessibilityAttributes(container, element, stickyIndex, stickyNodesTotal) {
      if (!this.accessibilityProvider) {
        return Disposable.None;
      }
      if (this.accessibilityProvider.getSetSize) {
        container.setAttribute("aria-setsize", String(this.accessibilityProvider.getSetSize(element, stickyIndex, stickyNodesTotal)));
      }
      if (this.accessibilityProvider.getPosInSet) {
        container.setAttribute("aria-posinset", String(this.accessibilityProvider.getPosInSet(element, stickyIndex)));
      }
      if (this.accessibilityProvider.getRole) {
        container.setAttribute("role", this.accessibilityProvider.getRole(element) ?? "treeitem");
      }
      const ariaLabel = this.accessibilityProvider.getAriaLabel(element);
      const observable = ariaLabel && typeof ariaLabel !== "string" ? ariaLabel : constObservable(ariaLabel);
      const result = autorun((reader) => {
        const value = reader.readObservable(observable);
        if (value) {
          container.setAttribute("aria-label", value);
        } else {
          container.removeAttribute("aria-label");
        }
      });
      if (typeof ariaLabel === "string") ;
      else if (ariaLabel) {
        container.setAttribute("aria-label", ariaLabel.get());
      }
      const ariaLevel = this.accessibilityProvider.getAriaLevel && this.accessibilityProvider.getAriaLevel(element);
      if (typeof ariaLevel === "number") {
        container.setAttribute("aria-level", `${ariaLevel}`);
      }
      container.setAttribute("aria-selected", String(false));
      return result;
    }
    setVisible(visible) {
      this._rootDomNode.classList.toggle("empty", !visible);
      if (!visible) {
        this.stickyScrollFocus.updateElements([], void 0);
      }
    }
    domFocus() {
      this.stickyScrollFocus.domFocus();
    }
    focusedLast() {
      return this.stickyScrollFocus.focusedLast();
    }
    dispose() {
      this.stickyScrollFocus.dispose();
      this._previousStateDisposables.dispose();
      this._rootDomNode.remove();
    }
  };
  class StickyScrollFocus extends Disposable {
    get domHasFocus() {
      return this._domHasFocus;
    }
    set domHasFocus(hasFocus) {
      if (hasFocus !== this._domHasFocus) {
        this._onDidChangeHasFocus.fire(hasFocus);
        this._domHasFocus = hasFocus;
      }
    }
    constructor(container, view) {
      super();
      this.container = container;
      this.view = view;
      this.focusedIndex = -1;
      this.elements = [];
      this._onDidChangeHasFocus = new Emitter$1();
      this.onDidChangeHasFocus = this._onDidChangeHasFocus.event;
      this._onContextMenu = new Emitter$1();
      this.onContextMenu = this._onContextMenu.event;
      this._domHasFocus = false;
      this._register(addDisposableListener(this.container, "focus", () => this.onFocus()));
      this._register(addDisposableListener(this.container, "blur", () => this.onBlur()));
      this._register(this.view.onDidFocus(() => this.toggleStickyScrollFocused(false)));
      this._register(this.view.onKeyDown((e) => this.onKeyDown(e)));
      this._register(this.view.onMouseDown((e) => this.onMouseDown(e)));
      this._register(this.view.onContextMenu((e) => this.handleContextMenu(e)));
    }
    handleContextMenu(e) {
      const target = e.browserEvent.target;
      if (!isStickyScrollContainer(target) && !isStickyScrollElement(target)) {
        if (this.focusedLast()) {
          this.view.domFocus();
        }
        return;
      }
      if (!isKeyboardEvent(e.browserEvent)) {
        if (!this.state) {
          throw new Error("Context menu should not be triggered when state is undefined");
        }
        const stickyIndex = this.state.stickyNodes.findIndex((stickyNode2) => stickyNode2.node.element === e.element?.element);
        if (stickyIndex === -1) {
          throw new Error("Context menu should not be triggered when element is not in sticky scroll widget");
        }
        this.container.focus();
        this.setFocus(stickyIndex);
        return;
      }
      if (!this.state || this.focusedIndex < 0) {
        throw new Error("Context menu key should not be triggered when focus is not in sticky scroll widget");
      }
      const stickyNode = this.state.stickyNodes[this.focusedIndex];
      const element = stickyNode.node.element;
      const anchor = this.elements[this.focusedIndex];
      this._onContextMenu.fire({ element, anchor, browserEvent: e.browserEvent, isStickyScroll: true });
    }
    onKeyDown(e) {
      if (this.domHasFocus && this.state) {
        if (e.key === "ArrowUp") {
          this.setFocusedElement(Math.max(0, this.focusedIndex - 1));
          e.preventDefault();
          e.stopPropagation();
        } else if (e.key === "ArrowDown" || e.key === "ArrowRight") {
          if (this.focusedIndex >= this.state.count - 1) {
            const nodeIndexToFocus = this.state.stickyNodes[this.state.count - 1].startIndex + 1;
            this.view.domFocus();
            this.view.setFocus([nodeIndexToFocus]);
            this.scrollNodeUnderWidget(nodeIndexToFocus, this.state);
          } else {
            this.setFocusedElement(this.focusedIndex + 1);
          }
          e.preventDefault();
          e.stopPropagation();
        }
      }
    }
    onMouseDown(e) {
      const target = e.browserEvent.target;
      if (!isStickyScrollContainer(target) && !isStickyScrollElement(target)) {
        return;
      }
      e.browserEvent.preventDefault();
      e.browserEvent.stopPropagation();
    }
    updateElements(elements, state) {
      if (state && state.count === 0) {
        throw new Error("Sticky scroll state must be undefined when there are no sticky nodes");
      }
      if (state && state.count !== elements.length) {
        throw new Error("Sticky scroll focus received illigel state");
      }
      const previousIndex = this.focusedIndex;
      this.removeFocus();
      this.elements = elements;
      this.state = state;
      if (state) {
        const newFocusedIndex = clamp(previousIndex, 0, state.count - 1);
        this.setFocus(newFocusedIndex);
      } else {
        if (this.domHasFocus) {
          this.view.domFocus();
        }
      }
      this.container.tabIndex = state ? 0 : -1;
    }
    setFocusedElement(stickyIndex) {
      const state = this.state;
      if (!state) {
        throw new Error("Cannot set focus when state is undefined");
      }
      this.setFocus(stickyIndex);
      if (stickyIndex < state.count - 1) {
        return;
      }
      if (state.lastNodePartiallyVisible()) {
        const lastStickyNode = state.stickyNodes[stickyIndex];
        this.scrollNodeUnderWidget(lastStickyNode.endIndex + 1, state);
      }
    }
    scrollNodeUnderWidget(nodeIndex, state) {
      const lastStickyNode = state.stickyNodes[state.count - 1];
      const secondLastStickyNode = state.count > 1 ? state.stickyNodes[state.count - 2] : void 0;
      const elementScrollTop = this.view.getElementTop(nodeIndex);
      const elementTargetViewTop = secondLastStickyNode ? secondLastStickyNode.position + secondLastStickyNode.height + lastStickyNode.height : lastStickyNode.height;
      this.view.scrollTop = elementScrollTop - elementTargetViewTop;
    }
    domFocus() {
      if (!this.state) {
        throw new Error("Cannot focus when state is undefined");
      }
      this.container.focus();
    }
    focusedLast() {
      if (!this.state) {
        return false;
      }
      return this.view.getHTMLElement().classList.contains("sticky-scroll-focused");
    }
    removeFocus() {
      if (this.focusedIndex === -1) {
        return;
      }
      this.toggleElementFocus(this.elements[this.focusedIndex], false);
      this.focusedIndex = -1;
    }
    setFocus(newFocusIndex) {
      if (0 > newFocusIndex) {
        throw new Error("addFocus() can not remove focus");
      }
      if (!this.state && newFocusIndex >= 0) {
        throw new Error("Cannot set focus index when state is undefined");
      }
      if (this.state && newFocusIndex >= this.state.count) {
        throw new Error("Cannot set focus index to an index that does not exist");
      }
      const oldIndex = this.focusedIndex;
      if (oldIndex >= 0) {
        this.toggleElementFocus(this.elements[oldIndex], false);
      }
      if (newFocusIndex >= 0) {
        this.toggleElementFocus(this.elements[newFocusIndex], true);
      }
      this.focusedIndex = newFocusIndex;
    }
    toggleElementFocus(element, focused) {
      this.toggleElementActiveFocus(element, focused && this.domHasFocus);
      this.toggleElementPassiveFocus(element, focused);
    }
    toggleCurrentElementActiveFocus(focused) {
      if (this.focusedIndex === -1) {
        return;
      }
      this.toggleElementActiveFocus(this.elements[this.focusedIndex], focused);
    }
    toggleElementActiveFocus(element, focused) {
      element.classList.toggle("focused", focused);
    }
    toggleElementPassiveFocus(element, focused) {
      element.classList.toggle("passive-focused", focused);
    }
    toggleStickyScrollFocused(focused) {
      this.view.getHTMLElement().classList.toggle("sticky-scroll-focused", focused);
    }
    onFocus() {
      if (!this.state || this.elements.length === 0) {
        throw new Error("Cannot focus when state is undefined or elements are empty");
      }
      this.domHasFocus = true;
      this.toggleStickyScrollFocused(true);
      this.toggleCurrentElementActiveFocus(true);
      if (this.focusedIndex === -1) {
        this.setFocus(0);
      }
    }
    onBlur() {
      this.domHasFocus = false;
      this.toggleCurrentElementActiveFocus(false);
    }
    dispose() {
      this.toggleStickyScrollFocused(false);
      this._onDidChangeHasFocus.fire(false);
      super.dispose();
    }
  }
  function asTreeMouseEvent$1(event) {
    let target = TreeMouseEventTarget.Unknown;
    if (hasParentWithClass(event.browserEvent.target, "monaco-tl-twistie", "monaco-tl-row")) {
      target = TreeMouseEventTarget.Twistie;
    } else if (hasParentWithClass(event.browserEvent.target, "monaco-tl-contents", "monaco-tl-row")) {
      target = TreeMouseEventTarget.Element;
    } else if (hasParentWithClass(event.browserEvent.target, "monaco-tree-type-filter", "monaco-list")) {
      target = TreeMouseEventTarget.Filter;
    }
    return {
      browserEvent: event.browserEvent,
      element: event.element ? event.element.element : null,
      target
    };
  }
  function asTreeContextMenuEvent(event) {
    const isStickyScroll = isStickyScrollContainer(event.browserEvent.target);
    return {
      element: event.element ? event.element.element : null,
      browserEvent: event.browserEvent,
      anchor: event.anchor,
      isStickyScroll
    };
  }
  function dfs$1(node, fn) {
    fn(node);
    node.children.forEach((child) => dfs$1(child, fn));
  }
  class Trait {
    get nodeSet() {
      if (!this._nodeSet) {
        this._nodeSet = this.createNodeSet();
      }
      return this._nodeSet;
    }
    constructor(getFirstViewElementWithTrait, identityProvider) {
      this.getFirstViewElementWithTrait = getFirstViewElementWithTrait;
      this.identityProvider = identityProvider;
      this.nodes = [];
      this._onDidChange = new Emitter$1();
      this.onDidChange = this._onDidChange.event;
    }
    set(nodes, browserEvent) {
      const event = browserEvent;
      if (!event?.__forceEvent && equals$1(this.nodes, nodes)) {
        return;
      }
      this._set(nodes, false, browserEvent);
    }
    _set(nodes, silent, browserEvent) {
      this.nodes = [...nodes];
      this.elements = void 0;
      this._nodeSet = void 0;
      if (!silent) {
        const that = this;
        this._onDidChange.fire({ get elements() {
          return that.get();
        }, browserEvent });
      }
    }
    get() {
      if (!this.elements) {
        this.elements = this.nodes.map((node) => node.element);
      }
      return [...this.elements];
    }
    getNodes() {
      return this.nodes;
    }
    has(node) {
      return this.nodeSet.has(node);
    }
    onDidModelSplice({ insertedNodes, deletedNodes }) {
      if (!this.identityProvider) {
        const set = this.createNodeSet();
        const visit = (node) => set.delete(node);
        deletedNodes.forEach((node) => dfs$1(node, visit));
        this.set([...set.values()]);
        return;
      }
      const deletedNodesIdSet = /* @__PURE__ */ new Set();
      const deletedNodesVisitor = (node) => deletedNodesIdSet.add(this.identityProvider.getId(node.element).toString());
      deletedNodes.forEach((node) => dfs$1(node, deletedNodesVisitor));
      const insertedNodesMap = /* @__PURE__ */ new Map();
      const insertedNodesVisitor = (node) => insertedNodesMap.set(this.identityProvider.getId(node.element).toString(), node);
      insertedNodes.forEach((node) => dfs$1(node, insertedNodesVisitor));
      const nodes = [];
      for (const node of this.nodes) {
        const id = this.identityProvider.getId(node.element).toString();
        const wasDeleted = deletedNodesIdSet.has(id);
        if (!wasDeleted) {
          nodes.push(node);
        } else {
          const insertedNode = insertedNodesMap.get(id);
          if (insertedNode && insertedNode.visible) {
            nodes.push(insertedNode);
          }
        }
      }
      if (this.nodes.length > 0 && nodes.length === 0) {
        const node = this.getFirstViewElementWithTrait();
        if (node) {
          nodes.push(node);
        }
      }
      this._set(nodes, true);
    }
    createNodeSet() {
      const set = /* @__PURE__ */ new Set();
      for (const node of this.nodes) {
        set.add(node);
      }
      return set;
    }
  }
  class TreeNodeListMouseController extends MouseController {
    constructor(list2, tree, stickyScrollProvider) {
      super(list2);
      this.tree = tree;
      this.stickyScrollProvider = stickyScrollProvider;
    }
    onViewPointer(e) {
      if (isButton(e.browserEvent.target) || isEditableElement(e.browserEvent.target) || isMonacoEditor(e.browserEvent.target)) {
        return;
      }
      if (e.browserEvent.isHandledByList) {
        return;
      }
      const node = e.element;
      if (!node) {
        return super.onViewPointer(e);
      }
      if (this.isSelectionRangeChangeEvent(e) || this.isSelectionSingleChangeEvent(e)) {
        return super.onViewPointer(e);
      }
      const target = e.browserEvent.target;
      const onTwistie = target.classList.contains("monaco-tl-twistie") || target.classList.contains("monaco-icon-label") && target.classList.contains("folder-icon") && e.browserEvent.offsetX < 16;
      const isStickyElement = isStickyScrollElement(e.browserEvent.target);
      let expandOnlyOnTwistieClick = false;
      if (isStickyElement) {
        expandOnlyOnTwistieClick = true;
      } else if (typeof this.tree.expandOnlyOnTwistieClick === "function") {
        expandOnlyOnTwistieClick = this.tree.expandOnlyOnTwistieClick(node.element);
      } else {
        expandOnlyOnTwistieClick = !!this.tree.expandOnlyOnTwistieClick;
      }
      if (!isStickyElement) {
        if (expandOnlyOnTwistieClick && !onTwistie && e.browserEvent.detail !== 2) {
          return super.onViewPointer(e);
        }
        if (!this.tree.expandOnDoubleClick && e.browserEvent.detail === 2) {
          return super.onViewPointer(e);
        }
      } else {
        this.handleStickyScrollMouseEvent(e, node);
      }
      if (node.collapsible && (!isStickyElement || onTwistie)) {
        const location = this.tree.getNodeLocation(node);
        const recursive = e.browserEvent.altKey;
        this.tree.setFocus([location]);
        this.tree.toggleCollapsed(location, recursive);
        if (onTwistie) {
          e.browserEvent.isHandledByList = true;
          return;
        }
      }
      if (!isStickyElement) {
        super.onViewPointer(e);
      }
    }
    handleStickyScrollMouseEvent(e, node) {
      if (isMonacoCustomToggle(e.browserEvent.target) || isActionItem(e.browserEvent.target)) {
        return;
      }
      const stickyScrollController = this.stickyScrollProvider();
      if (!stickyScrollController) {
        throw new Error("Sticky scroll controller not found");
      }
      const nodeIndex = this.list.indexOf(node);
      const elementScrollTop = this.list.getElementTop(nodeIndex);
      const elementTargetViewTop = stickyScrollController.nodePositionTopBelowWidget(node);
      this.tree.scrollTop = elementScrollTop - elementTargetViewTop;
      this.list.domFocus();
      this.list.setFocus([nodeIndex]);
      this.list.setSelection([nodeIndex]);
    }
    onDoubleClick(e) {
      const onTwistie = e.browserEvent.target.classList.contains("monaco-tl-twistie");
      if (onTwistie || !this.tree.expandOnDoubleClick) {
        return;
      }
      if (e.browserEvent.isHandledByList) {
        return;
      }
      super.onDoubleClick(e);
    }
    // to make sure dom focus is not stolen (for example with context menu)
    onMouseDown(e) {
      const target = e.browserEvent.target;
      if (!isStickyScrollContainer(target) && !isStickyScrollElement(target)) {
        super.onMouseDown(e);
        return;
      }
    }
    onContextMenu(e) {
      const target = e.browserEvent.target;
      if (!isStickyScrollContainer(target) && !isStickyScrollElement(target)) {
        super.onContextMenu(e);
        return;
      }
    }
  }
  class TreeNodeList extends List {
    constructor(user, container, virtualDelegate, renderers, focusTrait, selectionTrait, anchorTrait, options) {
      super(user, container, virtualDelegate, renderers, options);
      this.focusTrait = focusTrait;
      this.selectionTrait = selectionTrait;
      this.anchorTrait = anchorTrait;
    }
    createMouseController(options) {
      return new TreeNodeListMouseController(this, options.tree, options.stickyScrollProvider);
    }
    splice(start, deleteCount, elements = []) {
      super.splice(start, deleteCount, elements);
      if (elements.length === 0) {
        return;
      }
      const additionalFocus = [];
      const additionalSelection = [];
      let anchor;
      elements.forEach((node, index) => {
        if (this.focusTrait.has(node)) {
          additionalFocus.push(start + index);
        }
        if (this.selectionTrait.has(node)) {
          additionalSelection.push(start + index);
        }
        if (this.anchorTrait.has(node)) {
          anchor = start + index;
        }
      });
      if (additionalFocus.length > 0) {
        super.setFocus(distinct([...super.getFocus(), ...additionalFocus]));
      }
      if (additionalSelection.length > 0) {
        super.setSelection(distinct([...super.getSelection(), ...additionalSelection]));
      }
      if (typeof anchor === "number") {
        super.setAnchor(anchor);
      }
    }
    setFocus(indexes, browserEvent, fromAPI = false) {
      super.setFocus(indexes, browserEvent);
      if (!fromAPI) {
        this.focusTrait.set(indexes.map((i2) => this.element(i2)), browserEvent);
      }
    }
    setSelection(indexes, browserEvent, fromAPI = false) {
      super.setSelection(indexes, browserEvent);
      if (!fromAPI) {
        this.selectionTrait.set(indexes.map((i2) => this.element(i2)), browserEvent);
      }
    }
    setAnchor(index, fromAPI = false) {
      super.setAnchor(index);
      if (!fromAPI) {
        if (typeof index === "undefined") {
          this.anchorTrait.set([]);
        } else {
          this.anchorTrait.set([this.element(index)]);
        }
      }
    }
  }
  class AbstractTree {
    get onDidScroll() {
      return this.view.onDidScroll;
    }
    get onDidChangeFocus() {
      return this.eventBufferer.wrapEvent(this.focus.onDidChange);
    }
    get onDidChangeSelection() {
      return this.eventBufferer.wrapEvent(this.selection.onDidChange);
    }
    get onMouseDblClick() {
      return Event.filter(Event.map(this.view.onMouseDblClick, asTreeMouseEvent$1), (e) => e.target !== TreeMouseEventTarget.Filter);
    }
    get onMouseOver() {
      return Event.map(this.view.onMouseOver, asTreeMouseEvent$1);
    }
    get onMouseOut() {
      return Event.map(this.view.onMouseOut, asTreeMouseEvent$1);
    }
    get onContextMenu() {
      return Event.any(Event.filter(Event.map(this.view.onContextMenu, asTreeContextMenuEvent), (e) => !e.isStickyScroll), this.stickyScrollController?.onContextMenu ?? Event.None);
    }
    get onPointer() {
      return Event.map(this.view.onPointer, asTreeMouseEvent$1);
    }
    get onKeyDown() {
      return this.view.onKeyDown;
    }
    get onDidFocus() {
      return this.view.onDidFocus;
    }
    get onDidChangeModel() {
      return Event.any(this.onDidChangeModelRelay.event, this.onDidSwapModel.event);
    }
    get onDidChangeCollapseState() {
      return this.onDidChangeCollapseStateRelay.event;
    }
    get expandOnDoubleClick() {
      return typeof this._options.expandOnDoubleClick === "undefined" ? true : this._options.expandOnDoubleClick;
    }
    get expandOnlyOnTwistieClick() {
      return typeof this._options.expandOnlyOnTwistieClick === "undefined" ? true : this._options.expandOnlyOnTwistieClick;
    }
    get onDidDispose() {
      return this.view.onDidDispose;
    }
    constructor(_user, container, delegate, renderers, _options = {}) {
      this._user = _user;
      this._options = _options;
      this.eventBufferer = new EventBufferer();
      this.onDidChangeFindOpenState = Event.None;
      this.onDidChangeStickyScrollFocused = Event.None;
      this.disposables = new DisposableStore();
      this.onDidSwapModel = this.disposables.add(new Emitter$1());
      this.onDidChangeModelRelay = this.disposables.add(new Relay());
      this.onDidSpliceModelRelay = this.disposables.add(new Relay());
      this.onDidChangeCollapseStateRelay = this.disposables.add(new Relay());
      this.onDidChangeRenderNodeCountRelay = this.disposables.add(new Relay());
      this.onDidChangeActiveNodesRelay = this.disposables.add(new Relay());
      this._onWillRefilter = new Emitter$1();
      this.onWillRefilter = this._onWillRefilter.event;
      this._onDidUpdateOptions = new Emitter$1();
      this.modelDisposables = new DisposableStore();
      if (_options.keyboardNavigationLabelProvider && (_options.findWidgetEnabled ?? true)) {
        this.findFilter = new FindFilter(_options.keyboardNavigationLabelProvider, _options.filter, _options.defaultFindVisibility);
        _options = { ..._options, filter: this.findFilter };
        this.disposables.add(this.findFilter);
      }
      this.model = this.createModel(_user, _options);
      this.treeDelegate = new ComposedTreeDelegate(delegate);
      const activeNodes = this.disposables.add(new EventCollection(this.onDidChangeActiveNodesRelay.event));
      const renderedIndentGuides = new SetMap();
      this.renderers = renderers.map((r) => new TreeRenderer(r, this.model, this.onDidChangeCollapseStateRelay.event, activeNodes, renderedIndentGuides, _options));
      for (const r of this.renderers) {
        this.disposables.add(r);
      }
      this.focus = new Trait(() => this.view.getFocusedElements()[0], _options.identityProvider);
      this.selection = new Trait(() => this.view.getSelectedElements()[0], _options.identityProvider);
      this.anchor = new Trait(() => this.view.getAnchorElement(), _options.identityProvider);
      this.view = new TreeNodeList(_user, container, this.treeDelegate, this.renderers, this.focus, this.selection, this.anchor, { ...asListOptions(() => this.model, this.disposables, _options), tree: this, stickyScrollProvider: () => this.stickyScrollController });
      this.setupModel(this.model);
      if (_options.keyboardSupport !== false) {
        const onKeyDown = Event.chain(this.view.onKeyDown, ($2) => $2.filter((e) => !isEditableElement(e.target)).map((e) => new StandardKeyboardEvent(e)));
        Event.chain(onKeyDown, ($2) => $2.filter(
          (e) => e.keyCode === 15
          /* KeyCode.LeftArrow */
        ))(this.onLeftArrow, this, this.disposables);
        Event.chain(onKeyDown, ($2) => $2.filter(
          (e) => e.keyCode === 17
          /* KeyCode.RightArrow */
        ))(this.onRightArrow, this, this.disposables);
        Event.chain(onKeyDown, ($2) => $2.filter(
          (e) => e.keyCode === 10
          /* KeyCode.Space */
        ))(this.onSpace, this, this.disposables);
      }
      if ((_options.findWidgetEnabled ?? true) && _options.keyboardNavigationLabelProvider && _options.contextViewProvider) {
        const findOptions = {
          styles: _options.findWidgetStyles,
          defaultFindMode: _options.defaultFindMode,
          defaultFindMatchType: _options.defaultFindMatchType,
          showNotFoundMessage: _options.showNotFoundMessage
        };
        this.findController = this.disposables.add(new FindController$1(this, this.findFilter, _options.contextViewProvider, findOptions));
        this.focusNavigationFilter = (node) => this.findController.shouldAllowFocus(node);
        this.onDidChangeFindOpenState = this.findController.onDidChangeOpenState;
        this.onDidChangeFindMode = this.findController.onDidChangeMode;
        this.onDidChangeFindMatchType = this.findController.onDidChangeMatchType;
      } else {
        this.onDidChangeFindMode = Event.None;
        this.onDidChangeFindMatchType = Event.None;
      }
      if (_options.enableStickyScroll) {
        this.stickyScrollController = new StickyScrollController$1(this, this.model, this.view, this.renderers, this.treeDelegate, _options);
        this.onDidChangeStickyScrollFocused = this.stickyScrollController.onDidChangeHasFocus;
      }
      this.styleElement = createStyleSheet(this.view.getHTMLElement());
      this.getHTMLElement().classList.toggle("always", this._options.renderIndentGuides === RenderIndentGuides.Always);
    }
    updateOptions(optionsUpdate = {}) {
      this._options = { ...this._options, ...optionsUpdate };
      for (const renderer of this.renderers) {
        renderer.updateOptions(optionsUpdate);
      }
      this.view.updateOptions(this._options);
      this.findController?.updateOptions(optionsUpdate);
      this.updateStickyScroll(optionsUpdate);
      this._onDidUpdateOptions.fire(this._options);
      this.getHTMLElement().classList.toggle("always", this._options.renderIndentGuides === RenderIndentGuides.Always);
    }
    get options() {
      return this._options;
    }
    updateStickyScroll(optionsUpdate) {
      if (!this.stickyScrollController && this._options.enableStickyScroll) {
        this.stickyScrollController = new StickyScrollController$1(this, this.model, this.view, this.renderers, this.treeDelegate, this._options);
        this.onDidChangeStickyScrollFocused = this.stickyScrollController.onDidChangeHasFocus;
      } else if (this.stickyScrollController && !this._options.enableStickyScroll) {
        this.onDidChangeStickyScrollFocused = Event.None;
        this.stickyScrollController.dispose();
        this.stickyScrollController = void 0;
      }
      this.stickyScrollController?.updateOptions(optionsUpdate);
    }
    // Widget
    getHTMLElement() {
      return this.view.getHTMLElement();
    }
    get onDidChangeContentHeight() {
      return this.view.onDidChangeContentHeight;
    }
    get scrollTop() {
      return this.view.scrollTop;
    }
    set scrollTop(scrollTop) {
      this.view.scrollTop = scrollTop;
    }
    get scrollHeight() {
      return this.view.scrollHeight;
    }
    get renderHeight() {
      return this.view.renderHeight;
    }
    get ariaLabel() {
      return this.view.ariaLabel;
    }
    set ariaLabel(value) {
      this.view.ariaLabel = value;
    }
    domFocus() {
      if (this.stickyScrollController?.focusedLast()) {
        this.stickyScrollController.domFocus();
      } else {
        this.view.domFocus();
      }
    }
    layout(height, width2) {
      this.view.layout(height, width2);
    }
    style(styles) {
      const suffix = `.${this.view.domId}`;
      const content = [];
      if (styles.treeIndentGuidesStroke) {
        content.push(`.monaco-list${suffix}:hover .monaco-tl-indent > .indent-guide, .monaco-list${suffix}.always .monaco-tl-indent > .indent-guide  { opacity: 1; border-color: ${styles.treeInactiveIndentGuidesStroke}; }`);
        content.push(`.monaco-list${suffix} .monaco-tl-indent > .indent-guide.active { opacity: 1; border-color: ${styles.treeIndentGuidesStroke}; }`);
      }
      const stickyScrollBackground = styles.treeStickyScrollBackground ?? styles.listBackground;
      if (stickyScrollBackground) {
        content.push(`.monaco-list${suffix} .monaco-scrollable-element .monaco-tree-sticky-container { background-color: ${stickyScrollBackground}; }`);
        content.push(`.monaco-list${suffix} .monaco-scrollable-element .monaco-tree-sticky-container .monaco-tree-sticky-row { background-color: ${stickyScrollBackground}; }`);
      }
      if (styles.treeStickyScrollBorder) {
        content.push(`.monaco-list${suffix} .monaco-scrollable-element .monaco-tree-sticky-container { border-bottom: 1px solid ${styles.treeStickyScrollBorder}; }`);
      }
      if (styles.treeStickyScrollShadow) {
        content.push(`.monaco-list${suffix} .monaco-scrollable-element .monaco-tree-sticky-container .monaco-tree-sticky-container-shadow { box-shadow: ${styles.treeStickyScrollShadow} 0 6px 6px -6px inset; height: 3px; }`);
      }
      if (styles.listFocusForeground) {
        content.push(`.monaco-list${suffix}.sticky-scroll-focused .monaco-scrollable-element .monaco-tree-sticky-container:focus .monaco-list-row.focused { color: ${styles.listFocusForeground}; }`);
        content.push(`.monaco-list${suffix}:not(.sticky-scroll-focused) .monaco-scrollable-element .monaco-tree-sticky-container .monaco-list-row.focused { color: inherit; }`);
      }
      const focusAndSelectionOutline = asCssValueWithDefault(styles.listFocusAndSelectionOutline, asCssValueWithDefault(styles.listSelectionOutline, styles.listFocusOutline ?? ""));
      if (focusAndSelectionOutline) {
        content.push(`.monaco-list${suffix}.sticky-scroll-focused .monaco-scrollable-element .monaco-tree-sticky-container:focus .monaco-list-row.focused.selected { outline: 1px solid ${focusAndSelectionOutline}; outline-offset: -1px;}`);
        content.push(`.monaco-list${suffix}:not(.sticky-scroll-focused) .monaco-scrollable-element .monaco-tree-sticky-container .monaco-list-row.focused.selected { outline: inherit;}`);
      }
      if (styles.listFocusOutline) {
        content.push(`.monaco-list${suffix}.sticky-scroll-focused .monaco-scrollable-element .monaco-tree-sticky-container:focus .monaco-list-row.focused { outline: 1px solid ${styles.listFocusOutline}; outline-offset: -1px; }`);
        content.push(`.monaco-list${suffix}:not(.sticky-scroll-focused) .monaco-scrollable-element .monaco-tree-sticky-container .monaco-list-row.focused { outline: inherit; }`);
        content.push(`.context-menu-visible .monaco-list${suffix}.last-focused.sticky-scroll-focused .monaco-scrollable-element .monaco-tree-sticky-container .monaco-list-row.passive-focused { outline: 1px solid ${styles.listFocusOutline}; outline-offset: -1px; }`);
        content.push(`.context-menu-visible .monaco-list${suffix}.last-focused.sticky-scroll-focused .monaco-list-rows .monaco-list-row.focused { outline: inherit; }`);
        content.push(`.context-menu-visible .monaco-list${suffix}.last-focused:not(.sticky-scroll-focused) .monaco-tree-sticky-container .monaco-list-rows .monaco-list-row.focused { outline: inherit; }`);
      }
      this.styleElement.textContent = content.join("\n");
      this.view.style(styles);
    }
    // Tree navigation
    getParentElement(location) {
      const parentRef = this.model.getParentNodeLocation(location);
      const parentNode = this.model.getNode(parentRef);
      return parentNode.element;
    }
    getFirstElementChild(location) {
      return this.model.getFirstElementChild(location);
    }
    // Tree
    getNode(location) {
      return this.model.getNode(location);
    }
    getNodeLocation(node) {
      return this.model.getNodeLocation(node);
    }
    collapse(location, recursive = false) {
      return this.model.setCollapsed(location, true, recursive);
    }
    expand(location, recursive = false) {
      return this.model.setCollapsed(location, false, recursive);
    }
    toggleCollapsed(location, recursive = false) {
      return this.model.setCollapsed(location, void 0, recursive);
    }
    isCollapsible(location) {
      return this.model.isCollapsible(location);
    }
    setCollapsible(location, collapsible) {
      return this.model.setCollapsible(location, collapsible);
    }
    isCollapsed(location) {
      return this.model.isCollapsed(location);
    }
    refilter() {
      this._onWillRefilter.fire(void 0);
      this.model.refilter();
    }
    setSelection(elements, browserEvent) {
      this.eventBufferer.bufferEvents(() => {
        const nodes = elements.map((e) => this.model.getNode(e));
        this.selection.set(nodes, browserEvent);
        const indexes = elements.map((e) => this.model.getListIndex(e)).filter((i2) => i2 > -1);
        this.view.setSelection(indexes, browserEvent, true);
      });
    }
    getSelection() {
      return this.selection.get();
    }
    setFocus(elements, browserEvent) {
      this.eventBufferer.bufferEvents(() => {
        const nodes = elements.map((e) => this.model.getNode(e));
        this.focus.set(nodes, browserEvent);
        const indexes = elements.map((e) => this.model.getListIndex(e)).filter((i2) => i2 > -1);
        this.view.setFocus(indexes, browserEvent, true);
      });
    }
    focusNext(n2 = 1, loop = false, browserEvent, filter = isKeyboardEvent(browserEvent) && browserEvent.altKey ? void 0 : this.focusNavigationFilter) {
      this.view.focusNext(n2, loop, browserEvent, filter);
    }
    focusPrevious(n2 = 1, loop = false, browserEvent, filter = isKeyboardEvent(browserEvent) && browserEvent.altKey ? void 0 : this.focusNavigationFilter) {
      this.view.focusPrevious(n2, loop, browserEvent, filter);
    }
    focusNextPage(browserEvent, filter = isKeyboardEvent(browserEvent) && browserEvent.altKey ? void 0 : this.focusNavigationFilter) {
      return this.view.focusNextPage(browserEvent, filter);
    }
    focusPreviousPage(browserEvent, filter = isKeyboardEvent(browserEvent) && browserEvent.altKey ? void 0 : this.focusNavigationFilter) {
      return this.view.focusPreviousPage(browserEvent, filter, () => this.stickyScrollController?.height ?? 0);
    }
    focusLast(browserEvent, filter = isKeyboardEvent(browserEvent) && browserEvent.altKey ? void 0 : this.focusNavigationFilter) {
      this.view.focusLast(browserEvent, filter);
    }
    focusFirst(browserEvent, filter = isKeyboardEvent(browserEvent) && browserEvent.altKey ? void 0 : this.focusNavigationFilter) {
      this.view.focusFirst(browserEvent, filter);
    }
    getFocus() {
      return this.focus.get();
    }
    reveal(location, relativeTop) {
      this.model.expandTo(location);
      const index = this.model.getListIndex(location);
      if (index === -1) {
        return;
      }
      if (!this.stickyScrollController) {
        this.view.reveal(index, relativeTop);
      } else {
        const paddingTop = this.stickyScrollController.nodePositionTopBelowWidget(this.getNode(location));
        this.view.reveal(index, relativeTop, paddingTop);
      }
    }
    // List
    onLeftArrow(e) {
      e.preventDefault();
      e.stopPropagation();
      const nodes = this.view.getFocusedElements();
      if (nodes.length === 0) {
        return;
      }
      const node = nodes[0];
      const location = this.model.getNodeLocation(node);
      const didChange = this.model.setCollapsed(location, true);
      if (!didChange) {
        const parentLocation = this.model.getParentNodeLocation(location);
        if (!parentLocation) {
          return;
        }
        const parentListIndex = this.model.getListIndex(parentLocation);
        this.view.reveal(parentListIndex);
        this.view.setFocus([parentListIndex]);
      }
    }
    onRightArrow(e) {
      e.preventDefault();
      e.stopPropagation();
      const nodes = this.view.getFocusedElements();
      if (nodes.length === 0) {
        return;
      }
      const node = nodes[0];
      const location = this.model.getNodeLocation(node);
      const didChange = this.model.setCollapsed(location, false);
      if (!didChange) {
        if (!node.children.some((child) => child.visible)) {
          return;
        }
        const [focusedIndex] = this.view.getFocus();
        const firstChildIndex = focusedIndex + 1;
        this.view.reveal(firstChildIndex);
        this.view.setFocus([firstChildIndex]);
      }
    }
    onSpace(e) {
      e.preventDefault();
      e.stopPropagation();
      const nodes = this.view.getFocusedElements();
      if (nodes.length === 0) {
        return;
      }
      const node = nodes[0];
      const location = this.model.getNodeLocation(node);
      const recursive = e.browserEvent.altKey;
      this.model.setCollapsed(location, void 0, recursive);
    }
    setupModel(model) {
      this.modelDisposables.clear();
      this.modelDisposables.add(model.onDidSpliceRenderedNodes(({ start, deleteCount, elements }) => this.view.splice(start, deleteCount, elements)));
      const onDidModelSplice = Event.forEach(model.onDidSpliceModel, (e) => {
        this.eventBufferer.bufferEvents(() => {
          this.focus.onDidModelSplice(e);
          this.selection.onDidModelSplice(e);
        });
      }, this.modelDisposables);
      onDidModelSplice(() => null, null, this.modelDisposables);
      const activeNodesEmitter = this.modelDisposables.add(new Emitter$1());
      const activeNodesDebounce = this.modelDisposables.add(new Delayer(0));
      this.modelDisposables.add(Event.any(onDidModelSplice, this.focus.onDidChange, this.selection.onDidChange)(() => {
        activeNodesDebounce.trigger(() => {
          const set = /* @__PURE__ */ new Set();
          for (const node of this.focus.getNodes()) {
            set.add(node);
          }
          for (const node of this.selection.getNodes()) {
            set.add(node);
          }
          activeNodesEmitter.fire([...set.values()]);
        });
      }));
      this.onDidChangeActiveNodesRelay.input = activeNodesEmitter.event;
      this.onDidChangeModelRelay.input = Event.signal(model.onDidSpliceModel);
      this.onDidChangeCollapseStateRelay.input = model.onDidChangeCollapseState;
      this.onDidChangeRenderNodeCountRelay.input = model.onDidChangeRenderNodeCount;
      this.onDidSpliceModelRelay.input = model.onDidSpliceModel;
    }
    dispose() {
      dispose(this.disposables);
      this.stickyScrollController?.dispose();
      this.view.dispose();
      this.modelDisposables.dispose();
    }
  }
  class ObjectTreeModel {
    constructor(user, options = {}) {
      this.user = user;
      this.rootRef = null;
      this.nodes = /* @__PURE__ */ new Map();
      this.nodesByIdentity = /* @__PURE__ */ new Map();
      this.model = new IndexTreeModel(user, null, options);
      this.onDidSpliceModel = this.model.onDidSpliceModel;
      this.onDidSpliceRenderedNodes = this.model.onDidSpliceRenderedNodes;
      this.onDidChangeCollapseState = this.model.onDidChangeCollapseState;
      this.onDidChangeRenderNodeCount = this.model.onDidChangeRenderNodeCount;
      if (options.sorter) {
        this.sorter = {
          compare(a, b) {
            return options.sorter.compare(a.element, b.element);
          }
        };
      }
      this.identityProvider = options.identityProvider;
    }
    setChildren(element, children = Iterable.empty(), options = {}) {
      const location = this.getElementLocation(element);
      this._setChildren(location, this.preserveCollapseState(children), options);
    }
    _setChildren(location, children = Iterable.empty(), options) {
      const insertedElements = /* @__PURE__ */ new Set();
      const insertedElementIds = /* @__PURE__ */ new Set();
      const onDidCreateNode = (node) => {
        if (node.element === null) {
          return;
        }
        const tnode = node;
        insertedElements.add(tnode.element);
        this.nodes.set(tnode.element, tnode);
        if (this.identityProvider) {
          const id = this.identityProvider.getId(tnode.element).toString();
          insertedElementIds.add(id);
          this.nodesByIdentity.set(id, tnode);
        }
        options.onDidCreateNode?.(tnode);
      };
      const onDidDeleteNode = (node) => {
        if (node.element === null) {
          return;
        }
        const tnode = node;
        if (!insertedElements.has(tnode.element)) {
          this.nodes.delete(tnode.element);
        }
        if (this.identityProvider) {
          const id = this.identityProvider.getId(tnode.element).toString();
          if (!insertedElementIds.has(id)) {
            this.nodesByIdentity.delete(id);
          }
        }
        options.onDidDeleteNode?.(tnode);
      };
      this.model.splice([...location, 0], Number.MAX_VALUE, children, { ...options, onDidCreateNode, onDidDeleteNode });
    }
    preserveCollapseState(elements = Iterable.empty()) {
      if (this.sorter) {
        elements = [...elements].sort(this.sorter.compare.bind(this.sorter));
      }
      return Iterable.map(elements, (treeElement) => {
        let node = this.nodes.get(treeElement.element);
        if (!node && this.identityProvider) {
          const id = this.identityProvider.getId(treeElement.element).toString();
          node = this.nodesByIdentity.get(id);
        }
        if (!node) {
          let collapsed3;
          if (typeof treeElement.collapsed === "undefined") {
            collapsed3 = void 0;
          } else if (treeElement.collapsed === ObjectTreeElementCollapseState.Collapsed || treeElement.collapsed === ObjectTreeElementCollapseState.PreserveOrCollapsed) {
            collapsed3 = true;
          } else if (treeElement.collapsed === ObjectTreeElementCollapseState.Expanded || treeElement.collapsed === ObjectTreeElementCollapseState.PreserveOrExpanded) {
            collapsed3 = false;
          } else {
            collapsed3 = Boolean(treeElement.collapsed);
          }
          return {
            ...treeElement,
            children: this.preserveCollapseState(treeElement.children),
            collapsed: collapsed3
          };
        }
        const collapsible = typeof treeElement.collapsible === "boolean" ? treeElement.collapsible : node.collapsible;
        let collapsed2;
        if (typeof treeElement.collapsed === "undefined" || treeElement.collapsed === ObjectTreeElementCollapseState.PreserveOrCollapsed || treeElement.collapsed === ObjectTreeElementCollapseState.PreserveOrExpanded) {
          collapsed2 = node.collapsed;
        } else if (treeElement.collapsed === ObjectTreeElementCollapseState.Collapsed) {
          collapsed2 = true;
        } else if (treeElement.collapsed === ObjectTreeElementCollapseState.Expanded) {
          collapsed2 = false;
        } else {
          collapsed2 = Boolean(treeElement.collapsed);
        }
        return {
          ...treeElement,
          collapsible,
          collapsed: collapsed2,
          children: this.preserveCollapseState(treeElement.children)
        };
      });
    }
    rerender(element) {
      const location = this.getElementLocation(element);
      this.model.rerender(location);
    }
    resort(element = null, recursive = true) {
      if (!this.sorter) {
        return;
      }
      const location = this.getElementLocation(element);
      const node = this.model.getNode(location);
      this._setChildren(location, this.resortChildren(node, recursive), {});
    }
    resortChildren(node, recursive, first2 = true) {
      let childrenNodes = [...node.children];
      if (recursive || first2) {
        childrenNodes = childrenNodes.sort(this.sorter.compare.bind(this.sorter));
      }
      return Iterable.map(childrenNodes, (node2) => ({
        element: node2.element,
        collapsible: node2.collapsible,
        collapsed: node2.collapsed,
        children: this.resortChildren(node2, recursive, false)
      }));
    }
    getFirstElementChild(ref = null) {
      const location = this.getElementLocation(ref);
      return this.model.getFirstElementChild(location);
    }
    has(element) {
      return this.nodes.has(element);
    }
    getListIndex(element) {
      const location = this.getElementLocation(element);
      return this.model.getListIndex(location);
    }
    getListRenderCount(element) {
      const location = this.getElementLocation(element);
      return this.model.getListRenderCount(location);
    }
    isCollapsible(element) {
      const location = this.getElementLocation(element);
      return this.model.isCollapsible(location);
    }
    setCollapsible(element, collapsible) {
      const location = this.getElementLocation(element);
      return this.model.setCollapsible(location, collapsible);
    }
    isCollapsed(element) {
      const location = this.getElementLocation(element);
      return this.model.isCollapsed(location);
    }
    setCollapsed(element, collapsed2, recursive) {
      const location = this.getElementLocation(element);
      return this.model.setCollapsed(location, collapsed2, recursive);
    }
    expandTo(element) {
      const location = this.getElementLocation(element);
      this.model.expandTo(location);
    }
    refilter() {
      this.model.refilter();
    }
    getNode(element = null) {
      if (element === null) {
        return this.model.getNode(this.model.rootRef);
      }
      const node = this.nodes.get(element);
      if (!node) {
        throw new TreeError(this.user, `Tree element not found: ${element}`);
      }
      return node;
    }
    getNodeLocation(node) {
      return node.element;
    }
    getParentNodeLocation(element) {
      if (element === null) {
        throw new TreeError(this.user, `Invalid getParentNodeLocation call`);
      }
      const node = this.nodes.get(element);
      if (!node) {
        throw new TreeError(this.user, `Tree element not found: ${element}`);
      }
      const location = this.model.getNodeLocation(node);
      const parentLocation = this.model.getParentNodeLocation(location);
      const parent = this.model.getNode(parentLocation);
      return parent.element;
    }
    getElementLocation(element) {
      if (element === null) {
        return [];
      }
      const node = this.nodes.get(element);
      if (!node) {
        throw new TreeError(this.user, `Tree element not found: ${element}`);
      }
      return this.model.getNodeLocation(node);
    }
  }
  function noCompress(element) {
    const elements = [element.element];
    const incompressible = element.incompressible || false;
    return {
      element: { elements, incompressible },
      children: Iterable.map(Iterable.from(element.children), noCompress),
      collapsible: element.collapsible,
      collapsed: element.collapsed
    };
  }
  function compress(element) {
    const elements = [element.element];
    const incompressible = element.incompressible || false;
    let childrenIterator;
    let children;
    while (true) {
      [children, childrenIterator] = Iterable.consume(Iterable.from(element.children), 2);
      if (children.length !== 1) {
        break;
      }
      if (children[0].incompressible) {
        break;
      }
      element = children[0];
      elements.push(element.element);
    }
    return {
      element: { elements, incompressible },
      children: Iterable.map(Iterable.concat(children, childrenIterator), compress),
      collapsible: element.collapsible,
      collapsed: element.collapsed
    };
  }
  function _decompress(element, index = 0) {
    let children;
    if (index < element.element.elements.length - 1) {
      children = [_decompress(element, index + 1)];
    } else {
      children = Iterable.map(Iterable.from(element.children), (el) => _decompress(el, 0));
    }
    if (index === 0 && element.element.incompressible) {
      return {
        element: element.element.elements[index],
        children,
        incompressible: true,
        collapsible: element.collapsible,
        collapsed: element.collapsed
      };
    }
    return {
      element: element.element.elements[index],
      children,
      collapsible: element.collapsible,
      collapsed: element.collapsed
    };
  }
  function decompress(element) {
    return _decompress(element, 0);
  }
  function splice(treeElement, element, children) {
    if (treeElement.element === element) {
      return { ...treeElement, children };
    }
    return { ...treeElement, children: Iterable.map(Iterable.from(treeElement.children), (e) => splice(e, element, children)) };
  }
  const wrapIdentityProvider = (base) => ({
    getId(node) {
      return node.elements.map((e) => base.getId(e).toString()).join("\0");
    }
  });
  class CompressedObjectTreeModel {
    get onDidSpliceRenderedNodes() {
      return this.model.onDidSpliceRenderedNodes;
    }
    get onDidSpliceModel() {
      return this.model.onDidSpliceModel;
    }
    get onDidChangeCollapseState() {
      return this.model.onDidChangeCollapseState;
    }
    get onDidChangeRenderNodeCount() {
      return this.model.onDidChangeRenderNodeCount;
    }
    constructor(user, options = {}) {
      this.user = user;
      this.rootRef = null;
      this.nodes = /* @__PURE__ */ new Map();
      this.model = new ObjectTreeModel(user, options);
      this.enabled = typeof options.compressionEnabled === "undefined" ? true : options.compressionEnabled;
      this.identityProvider = options.identityProvider;
    }
    setChildren(element, children = Iterable.empty(), options) {
      const diffIdentityProvider = options.diffIdentityProvider && wrapIdentityProvider(options.diffIdentityProvider);
      if (element === null) {
        const compressedChildren = Iterable.map(children, this.enabled ? compress : noCompress);
        this._setChildren(null, compressedChildren, { diffIdentityProvider, diffDepth: Infinity });
        return;
      }
      const compressedNode = this.nodes.get(element);
      if (!compressedNode) {
        throw new TreeError(this.user, "Unknown compressed tree node");
      }
      const node = this.model.getNode(compressedNode);
      const compressedParentNode = this.model.getParentNodeLocation(compressedNode);
      const parent = this.model.getNode(compressedParentNode);
      const decompressedElement = decompress(node);
      const splicedElement = splice(decompressedElement, element, children);
      const recompressedElement = (this.enabled ? compress : noCompress)(splicedElement);
      const elementComparator = options.diffIdentityProvider ? ((a, b) => options.diffIdentityProvider.getId(a) === options.diffIdentityProvider.getId(b)) : void 0;
      if (equals$1(recompressedElement.element.elements, node.element.elements, elementComparator)) {
        this._setChildren(compressedNode, recompressedElement.children || Iterable.empty(), { diffIdentityProvider, diffDepth: 1 });
        return;
      }
      const parentChildren = parent.children.map((child) => child === node ? recompressedElement : child);
      this._setChildren(parent.element, parentChildren, {
        diffIdentityProvider,
        diffDepth: node.depth - parent.depth
      });
    }
    isCompressionEnabled() {
      return this.enabled;
    }
    setCompressionEnabled(enabled) {
      if (enabled === this.enabled) {
        return;
      }
      this.enabled = enabled;
      const root = this.model.getNode();
      const rootChildren = root.children;
      const decompressedRootChildren = Iterable.map(rootChildren, decompress);
      const recompressedRootChildren = Iterable.map(decompressedRootChildren, enabled ? compress : noCompress);
      this._setChildren(null, recompressedRootChildren, {
        diffIdentityProvider: this.identityProvider,
        diffDepth: Infinity
      });
    }
    _setChildren(node, children, options) {
      const insertedElements = /* @__PURE__ */ new Set();
      const onDidCreateNode = (node2) => {
        for (const element of node2.element.elements) {
          insertedElements.add(element);
          this.nodes.set(element, node2.element);
        }
      };
      const onDidDeleteNode = (node2) => {
        for (const element of node2.element.elements) {
          if (!insertedElements.has(element)) {
            this.nodes.delete(element);
          }
        }
      };
      this.model.setChildren(node, children, { ...options, onDidCreateNode, onDidDeleteNode });
    }
    has(element) {
      return this.nodes.has(element);
    }
    getListIndex(location) {
      const node = this.getCompressedNode(location);
      return this.model.getListIndex(node);
    }
    getListRenderCount(location) {
      const node = this.getCompressedNode(location);
      return this.model.getListRenderCount(node);
    }
    getNode(location) {
      if (typeof location === "undefined") {
        return this.model.getNode();
      }
      const node = this.getCompressedNode(location);
      return this.model.getNode(node);
    }
    // TODO: review this
    getNodeLocation(node) {
      const compressedNode = this.model.getNodeLocation(node);
      if (compressedNode === null) {
        return null;
      }
      return compressedNode.elements[compressedNode.elements.length - 1];
    }
    // TODO: review this
    getParentNodeLocation(location) {
      const compressedNode = this.getCompressedNode(location);
      const parentNode = this.model.getParentNodeLocation(compressedNode);
      if (parentNode === null) {
        return null;
      }
      return parentNode.elements[parentNode.elements.length - 1];
    }
    getFirstElementChild(location) {
      const compressedNode = this.getCompressedNode(location);
      return this.model.getFirstElementChild(compressedNode);
    }
    isCollapsible(location) {
      const compressedNode = this.getCompressedNode(location);
      return this.model.isCollapsible(compressedNode);
    }
    setCollapsible(location, collapsible) {
      const compressedNode = this.getCompressedNode(location);
      return this.model.setCollapsible(compressedNode, collapsible);
    }
    isCollapsed(location) {
      const compressedNode = this.getCompressedNode(location);
      return this.model.isCollapsed(compressedNode);
    }
    setCollapsed(location, collapsed2, recursive) {
      const compressedNode = this.getCompressedNode(location);
      return this.model.setCollapsed(compressedNode, collapsed2, recursive);
    }
    expandTo(location) {
      const compressedNode = this.getCompressedNode(location);
      this.model.expandTo(compressedNode);
    }
    rerender(location) {
      const compressedNode = this.getCompressedNode(location);
      this.model.rerender(compressedNode);
    }
    refilter() {
      this.model.refilter();
    }
    resort(location = null, recursive = true) {
      const compressedNode = this.getCompressedNode(location);
      this.model.resort(compressedNode, recursive);
    }
    getCompressedNode(element) {
      if (element === null) {
        return null;
      }
      const node = this.nodes.get(element);
      if (!node) {
        throw new TreeError(this.user, `Tree element not found: ${element}`);
      }
      return node;
    }
  }
  const DefaultElementMapper = (elements) => elements[elements.length - 1];
  class CompressedTreeNodeWrapper {
    get element() {
      return this.node.element === null ? null : this.unwrapper(this.node.element);
    }
    get children() {
      return this.node.children.map((node) => new CompressedTreeNodeWrapper(this.unwrapper, node));
    }
    get depth() {
      return this.node.depth;
    }
    get visibleChildrenCount() {
      return this.node.visibleChildrenCount;
    }
    get visibleChildIndex() {
      return this.node.visibleChildIndex;
    }
    get collapsible() {
      return this.node.collapsible;
    }
    get collapsed() {
      return this.node.collapsed;
    }
    get visible() {
      return this.node.visible;
    }
    get filterData() {
      return this.node.filterData;
    }
    constructor(unwrapper, node) {
      this.unwrapper = unwrapper;
      this.node = node;
    }
  }
  function mapOptions(compressedNodeUnwrapper, options) {
    return {
      ...options,
      identityProvider: options.identityProvider && {
        getId(node) {
          return options.identityProvider.getId(compressedNodeUnwrapper(node));
        }
      },
      sorter: options.sorter && {
        compare(node, otherNode) {
          return options.sorter.compare(node.elements[0], otherNode.elements[0]);
        }
      },
      filter: options.filter && {
        filter(node, parentVisibility) {
          const elements = node.elements;
          for (let i2 = 0; i2 < elements.length - 1; i2++) {
            const result = options.filter.filter(elements[i2], parentVisibility);
            parentVisibility = getVisibleState(isFilterResult(result) ? result.visibility : result);
          }
          return options.filter.filter(elements[elements.length - 1], parentVisibility);
        }
      }
    };
  }
  class CompressibleObjectTreeModel {
    get onDidSpliceModel() {
      return Event.map(this.model.onDidSpliceModel, ({ insertedNodes, deletedNodes }) => ({
        insertedNodes: insertedNodes.map((node) => this.nodeMapper.map(node)),
        deletedNodes: deletedNodes.map((node) => this.nodeMapper.map(node))
      }));
    }
    get onDidSpliceRenderedNodes() {
      return Event.map(this.model.onDidSpliceRenderedNodes, ({ start, deleteCount, elements }) => ({
        start,
        deleteCount,
        elements: elements.map((node) => this.nodeMapper.map(node))
      }));
    }
    get onDidChangeCollapseState() {
      return Event.map(this.model.onDidChangeCollapseState, ({ node, deep }) => ({
        node: this.nodeMapper.map(node),
        deep
      }));
    }
    get onDidChangeRenderNodeCount() {
      return Event.map(this.model.onDidChangeRenderNodeCount, (node) => this.nodeMapper.map(node));
    }
    constructor(user, options = {}) {
      this.rootRef = null;
      this.elementMapper = options.elementMapper || DefaultElementMapper;
      const compressedNodeUnwrapper = (node) => this.elementMapper(node.elements);
      this.nodeMapper = new WeakMapper((node) => new CompressedTreeNodeWrapper(compressedNodeUnwrapper, node));
      this.model = new CompressedObjectTreeModel(user, mapOptions(compressedNodeUnwrapper, options));
    }
    setChildren(element, children = Iterable.empty(), options = {}) {
      this.model.setChildren(element, children, options);
    }
    isCompressionEnabled() {
      return this.model.isCompressionEnabled();
    }
    setCompressionEnabled(enabled) {
      this.model.setCompressionEnabled(enabled);
    }
    has(location) {
      return this.model.has(location);
    }
    getListIndex(location) {
      return this.model.getListIndex(location);
    }
    getListRenderCount(location) {
      return this.model.getListRenderCount(location);
    }
    getNode(location) {
      return this.nodeMapper.map(this.model.getNode(location));
    }
    getNodeLocation(node) {
      return node.element;
    }
    getParentNodeLocation(location) {
      return this.model.getParentNodeLocation(location);
    }
    getFirstElementChild(location) {
      const result = this.model.getFirstElementChild(location);
      if (result === null || typeof result === "undefined") {
        return result;
      }
      return this.elementMapper(result.elements);
    }
    isCollapsible(location) {
      return this.model.isCollapsible(location);
    }
    setCollapsible(location, collapsed2) {
      return this.model.setCollapsible(location, collapsed2);
    }
    isCollapsed(location) {
      return this.model.isCollapsed(location);
    }
    setCollapsed(location, collapsed2, recursive) {
      return this.model.setCollapsed(location, collapsed2, recursive);
    }
    expandTo(location) {
      return this.model.expandTo(location);
    }
    rerender(location) {
      return this.model.rerender(location);
    }
    refilter() {
      return this.model.refilter();
    }
    resort(element = null, recursive = true) {
      return this.model.resort(element, recursive);
    }
    getCompressedTreeNode(location = null) {
      return this.model.getNode(location);
    }
  }
  var __decorate$22 = 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;
  };
  class ObjectTree extends AbstractTree {
    get onDidChangeCollapseState() {
      return this.model.onDidChangeCollapseState;
    }
    constructor(user, container, delegate, renderers, options = {}) {
      super(user, container, delegate, renderers, options);
      this.user = user;
    }
    setChildren(element, children = Iterable.empty(), options) {
      this.model.setChildren(element, children, options);
    }
    rerender(element) {
      if (element === void 0) {
        this.view.rerender();
        return;
      }
      this.model.rerender(element);
    }
    resort(element, recursive = true) {
      this.model.resort(element, recursive);
    }
    hasElement(element) {
      return this.model.has(element);
    }
    createModel(user, options) {
      return new ObjectTreeModel(user, options);
    }
  }
  class CompressibleRenderer {
    get compressedTreeNodeProvider() {
      return this._compressedTreeNodeProvider();
    }
    constructor(_compressedTreeNodeProvider, stickyScrollDelegate, renderer) {
      this._compressedTreeNodeProvider = _compressedTreeNodeProvider;
      this.stickyScrollDelegate = stickyScrollDelegate;
      this.renderer = renderer;
      this.templateId = renderer.templateId;
      if (renderer.onDidChangeTwistieState) {
        this.onDidChangeTwistieState = renderer.onDidChangeTwistieState;
      }
    }
    renderTemplate(container) {
      const data = this.renderer.renderTemplate(container);
      return { compressedTreeNode: void 0, data };
    }
    renderElement(node, index, templateData, details) {
      let compressedTreeNode = this.stickyScrollDelegate.getCompressedNode(node);
      if (!compressedTreeNode) {
        compressedTreeNode = this.compressedTreeNodeProvider.getCompressedTreeNode(node.element);
      }
      if (compressedTreeNode.element.elements.length === 1) {
        templateData.compressedTreeNode = void 0;
        this.renderer.renderElement(node, index, templateData.data, details);
      } else {
        templateData.compressedTreeNode = compressedTreeNode;
        this.renderer.renderCompressedElements(compressedTreeNode, index, templateData.data, details);
      }
    }
    disposeElement(node, index, templateData, details) {
      if (templateData.compressedTreeNode) {
        this.renderer.disposeCompressedElements?.(templateData.compressedTreeNode, index, templateData.data, details);
      } else {
        this.renderer.disposeElement?.(node, index, templateData.data, details);
      }
    }
    disposeTemplate(templateData) {
      this.renderer.disposeTemplate(templateData.data);
    }
    renderTwistie(element, twistieElement) {
      return this.renderer.renderTwistie?.(element, twistieElement) ?? false;
    }
  }
  __decorate$22([
    memoize
  ], CompressibleRenderer.prototype, "compressedTreeNodeProvider", null);
  class CompressibleStickyScrollDelegate {
    constructor(modelProvider) {
      this.modelProvider = modelProvider;
      this.compressedStickyNodes = /* @__PURE__ */ new Map();
    }
    getCompressedNode(node) {
      return this.compressedStickyNodes.get(node);
    }
    constrainStickyScrollNodes(stickyNodes, stickyScrollMaxItemCount, maxWidgetHeight) {
      this.compressedStickyNodes.clear();
      if (stickyNodes.length === 0) {
        return [];
      }
      for (let i2 = 0; i2 < stickyNodes.length; i2++) {
        const stickyNode = stickyNodes[i2];
        const stickyNodeBottom = stickyNode.position + stickyNode.height;
        const followingReachesMaxHeight = i2 + 1 < stickyNodes.length && stickyNodeBottom + stickyNodes[i2 + 1].height > maxWidgetHeight;
        if (followingReachesMaxHeight || i2 >= stickyScrollMaxItemCount - 1 && stickyScrollMaxItemCount < stickyNodes.length) {
          const uncompressedStickyNodes = stickyNodes.slice(0, i2);
          const overflowingStickyNodes = stickyNodes.slice(i2);
          const compressedStickyNode = this.compressStickyNodes(overflowingStickyNodes);
          return [...uncompressedStickyNodes, compressedStickyNode];
        }
      }
      return stickyNodes;
    }
    compressStickyNodes(stickyNodes) {
      if (stickyNodes.length === 0) {
        throw new Error("Can't compress empty sticky nodes");
      }
      const compressionModel = this.modelProvider();
      if (!compressionModel.isCompressionEnabled()) {
        return stickyNodes[0];
      }
      const elements = [];
      for (let i2 = 0; i2 < stickyNodes.length; i2++) {
        const stickyNode = stickyNodes[i2];
        const compressedNode2 = compressionModel.getCompressedTreeNode(stickyNode.node.element);
        if (compressedNode2.element) {
          if (i2 !== 0 && compressedNode2.element.incompressible) {
            break;
          }
          elements.push(...compressedNode2.element.elements);
        }
      }
      if (elements.length < 2) {
        return stickyNodes[0];
      }
      const lastStickyNode = stickyNodes[stickyNodes.length - 1];
      const compressedElement = { elements, incompressible: false };
      const compressedNode = { ...lastStickyNode.node, children: [], element: compressedElement };
      const stickyTreeNode = new Proxy(stickyNodes[0].node, {});
      const compressedStickyNode = {
        node: stickyTreeNode,
        startIndex: stickyNodes[0].startIndex,
        endIndex: lastStickyNode.endIndex,
        position: stickyNodes[0].position,
        height: stickyNodes[0].height
      };
      this.compressedStickyNodes.set(stickyTreeNode, compressedNode);
      return compressedStickyNode;
    }
  }
  function asObjectTreeOptions$1(compressedTreeNodeProvider, options) {
    return options && {
      ...options,
      keyboardNavigationLabelProvider: options.keyboardNavigationLabelProvider && {
        getKeyboardNavigationLabel(e) {
          let compressedTreeNode;
          try {
            compressedTreeNode = compressedTreeNodeProvider().getCompressedTreeNode(e);
          } catch {
            return options.keyboardNavigationLabelProvider.getKeyboardNavigationLabel(e);
          }
          if (compressedTreeNode.element.elements.length === 1) {
            return options.keyboardNavigationLabelProvider.getKeyboardNavigationLabel(e);
          } else {
            return options.keyboardNavigationLabelProvider.getCompressedNodeKeyboardNavigationLabel(compressedTreeNode.element.elements);
          }
        }
      }
    };
  }
  class CompressibleObjectTree extends ObjectTree {
    constructor(user, container, delegate, renderers, options = {}) {
      const compressedTreeNodeProvider = () => this;
      const stickyScrollDelegate = new CompressibleStickyScrollDelegate(() => this.model);
      const compressibleRenderers = renderers.map((r) => new CompressibleRenderer(compressedTreeNodeProvider, stickyScrollDelegate, r));
      super(user, container, delegate, compressibleRenderers, { ...asObjectTreeOptions$1(compressedTreeNodeProvider, options), stickyScrollDelegate });
    }
    setChildren(element, children = Iterable.empty(), options) {
      this.model.setChildren(element, children, options);
    }
    createModel(user, options) {
      return new CompressibleObjectTreeModel(user, options);
    }
    updateOptions(optionsUpdate = {}) {
      super.updateOptions(optionsUpdate);
      if (typeof optionsUpdate.compressionEnabled !== "undefined") {
        this.model.setCompressionEnabled(optionsUpdate.compressionEnabled);
      }
    }
    getCompressedTreeNode(element = null) {
      return this.model.getCompressedTreeNode(element);
    }
  }
  function createAsyncDataTreeNode(props) {
    return {
      ...props,
      children: [],
      refreshPromise: void 0,
      stale: true,
      slow: false,
      forceExpanded: false
    };
  }
  function isAncestor(ancestor, descendant) {
    if (!descendant.parent) {
      return false;
    } else if (descendant.parent === ancestor) {
      return true;
    } else {
      return isAncestor(ancestor, descendant.parent);
    }
  }
  function intersects(node, other) {
    return node === other || isAncestor(node, other) || isAncestor(other, node);
  }
  class AsyncDataTreeNodeWrapper {
    get element() {
      return this.node.element.element;
    }
    get children() {
      return this.node.children.map((node) => new AsyncDataTreeNodeWrapper(node));
    }
    get depth() {
      return this.node.depth;
    }
    get visibleChildrenCount() {
      return this.node.visibleChildrenCount;
    }
    get visibleChildIndex() {
      return this.node.visibleChildIndex;
    }
    get collapsible() {
      return this.node.collapsible;
    }
    get collapsed() {
      return this.node.collapsed;
    }
    get visible() {
      return this.node.visible;
    }
    get filterData() {
      return this.node.filterData;
    }
    constructor(node) {
      this.node = node;
    }
  }
  class AsyncDataTreeRenderer {
    constructor(renderer, nodeMapper, onDidChangeTwistieState) {
      this.renderer = renderer;
      this.nodeMapper = nodeMapper;
      this.onDidChangeTwistieState = onDidChangeTwistieState;
      this.renderedNodes = /* @__PURE__ */ new Map();
      this.templateId = renderer.templateId;
    }
    renderTemplate(container) {
      const templateData = this.renderer.renderTemplate(container);
      return { templateData };
    }
    renderElement(node, index, templateData, details) {
      this.renderer.renderElement(this.nodeMapper.map(node), index, templateData.templateData, details);
    }
    renderTwistie(element, twistieElement) {
      if (element.slow) {
        twistieElement.classList.add(...ThemeIcon.asClassNameArray(Codicon.treeItemLoading));
        return true;
      } else {
        twistieElement.classList.remove(...ThemeIcon.asClassNameArray(Codicon.treeItemLoading));
        return false;
      }
    }
    disposeElement(node, index, templateData, details) {
      this.renderer.disposeElement?.(this.nodeMapper.map(node), index, templateData.templateData, details);
    }
    disposeTemplate(templateData) {
      this.renderer.disposeTemplate(templateData.templateData);
    }
    dispose() {
      this.renderedNodes.clear();
    }
  }
  function asTreeEvent(e) {
    return {
      browserEvent: e.browserEvent,
      elements: e.elements.map((e2) => e2.element)
    };
  }
  function asTreeMouseEvent(e) {
    return {
      browserEvent: e.browserEvent,
      element: e.element && e.element.element,
      target: e.target
    };
  }
  class AsyncDataTreeElementsDragAndDropData extends ElementsDragAndDropData {
    constructor(data) {
      super(data.elements.map((node) => node.element));
      this.data = data;
    }
  }
  function asAsyncDataTreeDragAndDropData(data) {
    if (data instanceof ElementsDragAndDropData) {
      return new AsyncDataTreeElementsDragAndDropData(data);
    }
    return data;
  }
  class AsyncDataTreeNodeListDragAndDrop {
    constructor(dnd) {
      this.dnd = dnd;
    }
    getDragURI(node) {
      return this.dnd.getDragURI(node.element);
    }
    getDragLabel(nodes, originalEvent) {
      if (this.dnd.getDragLabel) {
        return this.dnd.getDragLabel(nodes.map((node) => node.element), originalEvent);
      }
      return void 0;
    }
    onDragStart(data, originalEvent) {
      this.dnd.onDragStart?.(asAsyncDataTreeDragAndDropData(data), originalEvent);
    }
    onDragOver(data, targetNode, targetIndex, targetSector, originalEvent, raw = true) {
      return this.dnd.onDragOver(asAsyncDataTreeDragAndDropData(data), targetNode && targetNode.element, targetIndex, targetSector, originalEvent);
    }
    drop(data, targetNode, targetIndex, targetSector, originalEvent) {
      this.dnd.drop(asAsyncDataTreeDragAndDropData(data), targetNode && targetNode.element, targetIndex, targetSector, originalEvent);
    }
    onDragEnd(originalEvent) {
      this.dnd.onDragEnd?.(originalEvent);
    }
    dispose() {
      this.dnd.dispose();
    }
  }
  class AsyncFindFilter extends FindFilter {
    constructor(findProvider, keyboardNavigationLabelProvider, filter) {
      super(keyboardNavigationLabelProvider, filter);
      this.findProvider = findProvider;
      this.isFindSessionActive = false;
    }
    filter(element, parentVisibility) {
      const filterResult = super.filter(element, parentVisibility);
      if (!this.isFindSessionActive || this.findMode === TreeFindMode.Highlight || !this.findProvider.isVisible) {
        return filterResult;
      }
      const visibility = isFilterResult(filterResult) ? filterResult.visibility : filterResult;
      if (getVisibleState(visibility) === 0) {
        return 0;
      }
      return this.findProvider.isVisible(element) ? filterResult : 0;
    }
  }
  class AsyncFindController extends FindController$1 {
    constructor(tree, findProvider, filter, contextViewProvider, options) {
      super(tree, filter, contextViewProvider, options);
      this.findProvider = findProvider;
      this.filter = filter;
      this.activeSession = false;
      this.asyncWorkInProgress = false;
      this.disposables.add(toDisposable(async () => {
        if (this.activeSession) {
          await this.findProvider.endSession?.();
        }
      }));
    }
    render() {
      if (this.asyncWorkInProgress || !this.activeFindMetadata) {
        return;
      }
      const showNotFound = this.activeFindMetadata.matchCount === 0 && this.pattern.length > 0;
      this.renderMessage(showNotFound);
      if (this.pattern.length) {
        this.alertResults(this.activeFindMetadata.matchCount);
      }
    }
    shouldAllowFocus(node) {
      return this.shouldFocusWhenNavigating(node);
    }
    shouldFocusWhenNavigating(node) {
      if (!this.activeSession || !this.activeFindMetadata) {
        return true;
      }
      const element = node.element?.element;
      if (element && this.activeFindMetadata.isMatch(element)) {
        return true;
      }
      return !FuzzyScore.isDefault(node.filterData);
    }
  }
  function asObjectTreeOptions(options) {
    return options && {
      ...options,
      collapseByDefault: true,
      identityProvider: options.identityProvider && {
        getId(el) {
          return options.identityProvider.getId(el.element);
        }
      },
      dnd: options.dnd && new AsyncDataTreeNodeListDragAndDrop(options.dnd),
      multipleSelectionController: options.multipleSelectionController && {
        isSelectionSingleChangeEvent(e) {
          return options.multipleSelectionController.isSelectionSingleChangeEvent({ ...e, element: e.element });
        },
        isSelectionRangeChangeEvent(e) {
          return options.multipleSelectionController.isSelectionRangeChangeEvent({ ...e, element: e.element });
        }
      },
      accessibilityProvider: options.accessibilityProvider && {
        ...options.accessibilityProvider,
        getPosInSet: void 0,
        getSetSize: void 0,
        getRole: options.accessibilityProvider.getRole ? (el) => {
          return options.accessibilityProvider.getRole(el.element);
        } : () => "treeitem",
        isChecked: options.accessibilityProvider.isChecked ? (e) => {
          return !!options.accessibilityProvider?.isChecked(e.element);
        } : void 0,
        getAriaLabel(e) {
          return options.accessibilityProvider.getAriaLabel(e.element);
        },
        getWidgetAriaLabel() {
          return options.accessibilityProvider.getWidgetAriaLabel();
        },
        getWidgetRole: options.accessibilityProvider.getWidgetRole ? () => options.accessibilityProvider.getWidgetRole() : () => "tree",
        getAriaLevel: options.accessibilityProvider.getAriaLevel && ((node) => {
          return options.accessibilityProvider.getAriaLevel(node.element);
        }),
        getActiveDescendantId: options.accessibilityProvider.getActiveDescendantId && ((node) => {
          return options.accessibilityProvider.getActiveDescendantId(node.element);
        })
      },
      filter: options.filter && {
        filter(e, parentVisibility) {
          return options.filter.filter(e.element, parentVisibility);
        }
      },
      keyboardNavigationLabelProvider: options.keyboardNavigationLabelProvider && {
        ...options.keyboardNavigationLabelProvider,
        getKeyboardNavigationLabel(e) {
          return options.keyboardNavigationLabelProvider.getKeyboardNavigationLabel(e.element);
        }
      },
      sorter: void 0,
      expandOnlyOnTwistieClick: typeof options.expandOnlyOnTwistieClick === "undefined" ? void 0 : typeof options.expandOnlyOnTwistieClick !== "function" ? options.expandOnlyOnTwistieClick : ((e) => options.expandOnlyOnTwistieClick(e.element)),
      defaultFindVisibility: (e) => {
        if (e.hasChildren && e.stale) {
          return 1;
        } else if (typeof options.defaultFindVisibility === "number") {
          return options.defaultFindVisibility;
        } else if (typeof options.defaultFindVisibility === "undefined") {
          return 2;
        } else {
          return options.defaultFindVisibility(e.element);
        }
      },
      stickyScrollDelegate: options.stickyScrollDelegate
    };
  }
  function dfs(node, fn) {
    fn(node);
    node.children.forEach((child) => dfs(child, fn));
  }
  class AsyncDataTree {
    get onDidScroll() {
      return this.tree.onDidScroll;
    }
    get onDidChangeFocus() {
      return Event.map(this.tree.onDidChangeFocus, asTreeEvent);
    }
    get onDidChangeSelection() {
      return Event.map(this.tree.onDidChangeSelection, asTreeEvent);
    }
    get onMouseDblClick() {
      return Event.map(this.tree.onMouseDblClick, asTreeMouseEvent);
    }
    get onPointer() {
      return Event.map(this.tree.onPointer, asTreeMouseEvent);
    }
    get onDidFocus() {
      return this.tree.onDidFocus;
    }
    /**
     * To be used internally only!
     * @deprecated
     */
    get onDidChangeModel() {
      return this.tree.onDidChangeModel;
    }
    get onDidChangeCollapseState() {
      return this.tree.onDidChangeCollapseState;
    }
    get onDidChangeStickyScrollFocused() {
      return this.tree.onDidChangeStickyScrollFocused;
    }
    get onDidDispose() {
      return this.tree.onDidDispose;
    }
    constructor(user, container, delegate, renderers, dataSource, options = {}) {
      this.user = user;
      this.dataSource = dataSource;
      this.nodes = /* @__PURE__ */ new Map();
      this.subTreeRefreshPromises = /* @__PURE__ */ new Map();
      this.refreshPromises = /* @__PURE__ */ new Map();
      this._onDidRender = new Emitter$1();
      this._onDidChangeNodeSlowState = new Emitter$1();
      this.nodeMapper = new WeakMapper((node) => new AsyncDataTreeNodeWrapper(node));
      this.disposables = new DisposableStore();
      this.identityProvider = options.identityProvider;
      this.autoExpandSingleChildren = typeof options.autoExpandSingleChildren === "undefined" ? false : options.autoExpandSingleChildren;
      this.sorter = options.sorter;
      this.getDefaultCollapseState = (e) => options.collapseByDefault ? options.collapseByDefault(e) ? ObjectTreeElementCollapseState.PreserveOrCollapsed : ObjectTreeElementCollapseState.PreserveOrExpanded : void 0;
      let asyncFindEnabled = false;
      let findFilter;
      if (options.findProvider && (options.findWidgetEnabled ?? true) && options.keyboardNavigationLabelProvider && options.contextViewProvider) {
        asyncFindEnabled = true;
        findFilter = new AsyncFindFilter(options.findProvider, options.keyboardNavigationLabelProvider, options.filter);
      }
      this.tree = this.createTree(user, container, delegate, renderers, { ...options, findWidgetEnabled: !asyncFindEnabled, filter: findFilter ?? options.filter });
      this.root = createAsyncDataTreeNode({
        element: void 0,
        parent: null,
        hasChildren: true,
        defaultCollapseState: void 0
      });
      if (this.identityProvider) {
        this.root = {
          ...this.root,
          id: null
        };
      }
      this.nodes.set(null, this.root);
      this.tree.onDidChangeCollapseState(this._onDidChangeCollapseState, this, this.disposables);
      if (asyncFindEnabled) {
        const findOptions = {
          styles: options.findWidgetStyles,
          showNotFoundMessage: options.showNotFoundMessage,
          defaultFindMatchType: options.defaultFindMatchType,
          defaultFindMode: options.defaultFindMode
        };
        this.findController = this.disposables.add(new AsyncFindController(this.tree, options.findProvider, findFilter, this.tree.options.contextViewProvider, findOptions));
        this.focusNavigationFilter = (node) => this.findController.shouldFocusWhenNavigating(node);
        this.onDidChangeFindOpenState = this.findController.onDidChangeOpenState;
        this.onDidChangeFindMode = this.findController.onDidChangeMode;
        this.onDidChangeFindMatchType = this.findController.onDidChangeMatchType;
      } else {
        this.onDidChangeFindOpenState = this.tree.onDidChangeFindOpenState;
        this.onDidChangeFindMode = this.tree.onDidChangeFindMode;
        this.onDidChangeFindMatchType = this.tree.onDidChangeFindMatchType;
      }
    }
    createTree(user, container, delegate, renderers, options) {
      const objectTreeDelegate = new ComposedTreeDelegate(delegate);
      const objectTreeRenderers = renderers.map((r) => new AsyncDataTreeRenderer(r, this.nodeMapper, this._onDidChangeNodeSlowState.event));
      const objectTreeOptions = asObjectTreeOptions(options) || {};
      return new ObjectTree(user, container, objectTreeDelegate, objectTreeRenderers, objectTreeOptions);
    }
    updateOptions(optionsUpdate = {}) {
      if (this.findController) {
        if (optionsUpdate.defaultFindMode !== void 0) {
          this.findController.mode = optionsUpdate.defaultFindMode;
        }
        if (optionsUpdate.defaultFindMatchType !== void 0) {
          this.findController.matchType = optionsUpdate.defaultFindMatchType;
        }
      }
      this.tree.updateOptions(optionsUpdate);
    }
    // Widget
    getHTMLElement() {
      return this.tree.getHTMLElement();
    }
    get scrollTop() {
      return this.tree.scrollTop;
    }
    set scrollTop(scrollTop) {
      this.tree.scrollTop = scrollTop;
    }
    get scrollHeight() {
      return this.tree.scrollHeight;
    }
    get renderHeight() {
      return this.tree.renderHeight;
    }
    domFocus() {
      this.tree.domFocus();
    }
    layout(height, width2) {
      this.tree.layout(height, width2);
    }
    style(styles) {
      this.tree.style(styles);
    }
    // Model
    getInput() {
      return this.root.element;
    }
    async setInput(input, viewState) {
      this.cancelAllRefreshPromises();
      this.root.element = input;
      const viewStateContext = viewState && { viewState, focus: [], selection: [] };
      await this._updateChildren(input, true, false, viewStateContext);
      if (viewStateContext) {
        this.tree.setFocus(viewStateContext.focus);
        this.tree.setSelection(viewStateContext.selection);
      }
      if (viewState && typeof viewState.scrollTop === "number") {
        this.scrollTop = viewState.scrollTop;
      }
    }
    cancelAllRefreshPromises(includeSubTrees = false) {
      this.refreshPromises.forEach((promise) => promise.cancel());
      this.refreshPromises.clear();
      if (includeSubTrees) {
        this.subTreeRefreshPromises.forEach((promise) => promise.cancel());
        this.subTreeRefreshPromises.clear();
      }
    }
    async _updateChildren(element = this.root.element, recursive = true, rerender = false, viewStateContext, options) {
      if (typeof this.root.element === "undefined") {
        throw new TreeError(this.user, "Tree input not set");
      }
      if (this.root.refreshPromise) {
        await this.root.refreshPromise;
        await Event.toPromise(this._onDidRender.event);
      }
      const node = this.getDataNode(element);
      await this.refreshAndRenderNode(node, recursive, viewStateContext, options);
      if (rerender) {
        try {
          this.tree.rerender(node);
        } catch {
        }
      }
    }
    // View
    rerender(element) {
      if (element === void 0 || element === this.root.element) {
        this.tree.rerender();
        return;
      }
      const node = this.getDataNode(element);
      this.tree.rerender(node);
    }
    // Tree
    getNode(element = this.root.element) {
      const dataNode = this.getDataNode(element);
      const node = this.tree.getNode(dataNode === this.root ? null : dataNode);
      return this.nodeMapper.map(node);
    }
    collapse(element, recursive = false) {
      const node = this.getDataNode(element);
      return this.tree.collapse(node === this.root ? null : node, recursive);
    }
    async expand(element, recursive = false) {
      if (typeof this.root.element === "undefined") {
        throw new TreeError(this.user, "Tree input not set");
      }
      if (this.root.refreshPromise) {
        await this.root.refreshPromise;
        await Event.toPromise(this._onDidRender.event);
      }
      const node = this.getDataNode(element);
      if (this.tree.hasElement(node) && !this.tree.isCollapsible(node)) {
        return false;
      }
      if (node.refreshPromise) {
        await node.refreshPromise;
        await Event.toPromise(this._onDidRender.event);
      }
      if (node !== this.root && !node.refreshPromise && !this.tree.isCollapsed(node)) {
        return false;
      }
      const result = this.tree.expand(node === this.root ? null : node, recursive);
      if (node.refreshPromise) {
        await node.refreshPromise;
        await Event.toPromise(this._onDidRender.event);
      }
      return result;
    }
    setSelection(elements, browserEvent) {
      const nodes = elements.map((e) => this.getDataNode(e));
      this.tree.setSelection(nodes, browserEvent);
    }
    getSelection() {
      const nodes = this.tree.getSelection();
      return nodes.map((n2) => n2.element);
    }
    setFocus(elements, browserEvent) {
      const nodes = elements.map((e) => this.getDataNode(e));
      this.tree.setFocus(nodes, browserEvent);
    }
    getFocus() {
      const nodes = this.tree.getFocus();
      return nodes.map((n2) => n2.element);
    }
    reveal(element, relativeTop) {
      this.tree.reveal(this.getDataNode(element), relativeTop);
    }
    // Tree navigation
    getParentElement(element) {
      const node = this.tree.getParentElement(this.getDataNode(element));
      return node && node.element;
    }
    getFirstElementChild(element = this.root.element) {
      const dataNode = this.getDataNode(element);
      const node = this.tree.getFirstElementChild(dataNode === this.root ? null : dataNode);
      return node && node.element;
    }
    // Implementation
    getDataNode(element) {
      const node = this.nodes.get(element === this.root.element ? null : element);
      if (!node) {
        const nodeIdentity = this.identityProvider?.getId(element).toString();
        throw new TreeError(this.user, `Data tree node not found${nodeIdentity ? `: ${nodeIdentity}` : ""}`);
      }
      return node;
    }
    async refreshAndRenderNode(node, recursive, viewStateContext, options) {
      if (this.disposables.isDisposed) {
        return;
      }
      await this.refreshNode(node, recursive, viewStateContext);
      if (this.disposables.isDisposed) {
        return;
      }
      this.render(node, viewStateContext, options);
    }
    async refreshNode(node, recursive, viewStateContext) {
      let result;
      this.subTreeRefreshPromises.forEach((refreshPromise, refreshNode) => {
        if (!result && intersects(refreshNode, node)) {
          result = refreshPromise.then(() => this.refreshNode(node, recursive, viewStateContext));
        }
      });
      if (result) {
        return result;
      }
      if (node !== this.root) {
        const treeNode = this.tree.getNode(node);
        if (treeNode.collapsed) {
          node.hasChildren = !!this.dataSource.hasChildren(node.element);
          node.stale = true;
          this.setChildren(node, [], recursive, viewStateContext);
          return;
        }
      }
      return this.doRefreshSubTree(node, recursive, viewStateContext);
    }
    async doRefreshSubTree(node, recursive, viewStateContext) {
      const cancelablePromise = createCancelablePromise(async () => {
        const childrenToRefresh = await this.doRefreshNode(node, recursive, viewStateContext);
        node.stale = false;
        await Promises.settled(childrenToRefresh.map((child) => this.doRefreshSubTree(child, recursive, viewStateContext)));
      });
      node.refreshPromise = cancelablePromise;
      this.subTreeRefreshPromises.set(node, cancelablePromise);
      cancelablePromise.finally(() => {
        node.refreshPromise = void 0;
        this.subTreeRefreshPromises.delete(node);
      });
      return cancelablePromise;
    }
    async doRefreshNode(node, recursive, viewStateContext) {
      node.hasChildren = !!this.dataSource.hasChildren(node.element);
      let childrenPromise;
      if (!node.hasChildren) {
        childrenPromise = Promise.resolve(Iterable.empty());
      } else {
        const children = this.doGetChildren(node);
        if (isIterable(children)) {
          childrenPromise = Promise.resolve(children);
        } else {
          const slowTimeout = timeout(800);
          slowTimeout.then(() => {
            node.slow = true;
            this._onDidChangeNodeSlowState.fire(node);
          }, (_) => null);
          childrenPromise = children.finally(() => slowTimeout.cancel());
        }
      }
      try {
        const children = await childrenPromise;
        return this.setChildren(node, children, recursive, viewStateContext);
      } catch (err) {
        if (node !== this.root && this.tree.hasElement(node)) {
          this.tree.collapse(node);
        }
        if (isCancellationError(err)) {
          return [];
        }
        throw err;
      } finally {
        if (node.slow) {
          node.slow = false;
          this._onDidChangeNodeSlowState.fire(node);
        }
      }
    }
    doGetChildren(node) {
      let result = this.refreshPromises.get(node);
      if (result) {
        return result;
      }
      const children = this.dataSource.getChildren(node.element);
      if (isIterable(children)) {
        return this.processChildren(children);
      } else {
        result = createCancelablePromise(async () => this.processChildren(await children));
        this.refreshPromises.set(node, result);
        return result.finally(() => {
          this.refreshPromises.delete(node);
        });
      }
    }
    _onDidChangeCollapseState({ node, deep }) {
      if (node.element === null) {
        return;
      }
      if (!node.collapsed && node.element.stale) {
        if (deep) {
          this.collapse(node.element.element);
        } else {
          this.refreshAndRenderNode(node.element, false).catch(onUnexpectedError);
        }
      }
    }
    setChildren(node, childrenElementsIterable, recursive, viewStateContext) {
      const childrenElements = [...childrenElementsIterable];
      if (node.children.length === 0 && childrenElements.length === 0) {
        return [];
      }
      const nodesToForget = /* @__PURE__ */ new Map();
      const childrenTreeNodesById = /* @__PURE__ */ new Map();
      for (const child of node.children) {
        nodesToForget.set(child.element, child);
        if (this.identityProvider) {
          childrenTreeNodesById.set(child.id, { node: child, collapsed: this.tree.hasElement(child) && this.tree.isCollapsed(child) });
        }
      }
      const childrenToRefresh = [];
      const children = childrenElements.map((element) => {
        const hasChildren = !!this.dataSource.hasChildren(element);
        if (!this.identityProvider) {
          const asyncDataTreeNode = createAsyncDataTreeNode({ element, parent: node, hasChildren, defaultCollapseState: this.getDefaultCollapseState(element) });
          if (hasChildren && asyncDataTreeNode.defaultCollapseState === ObjectTreeElementCollapseState.PreserveOrExpanded) {
            childrenToRefresh.push(asyncDataTreeNode);
          }
          return asyncDataTreeNode;
        }
        const id = this.identityProvider.getId(element).toString();
        const result = childrenTreeNodesById.get(id);
        if (result) {
          const asyncDataTreeNode = result.node;
          nodesToForget.delete(asyncDataTreeNode.element);
          this.nodes.delete(asyncDataTreeNode.element);
          this.nodes.set(element, asyncDataTreeNode);
          asyncDataTreeNode.element = element;
          asyncDataTreeNode.hasChildren = hasChildren;
          if (recursive) {
            if (result.collapsed) {
              asyncDataTreeNode.children.forEach((node2) => dfs(node2, (node3) => this.nodes.delete(node3.element)));
              asyncDataTreeNode.children.splice(0, asyncDataTreeNode.children.length);
              asyncDataTreeNode.stale = true;
            } else {
              childrenToRefresh.push(asyncDataTreeNode);
            }
          } else if (hasChildren && !result.collapsed) {
            childrenToRefresh.push(asyncDataTreeNode);
          }
          return asyncDataTreeNode;
        }
        const childAsyncDataTreeNode = createAsyncDataTreeNode({ element, parent: node, id, hasChildren, defaultCollapseState: this.getDefaultCollapseState(element) });
        if (viewStateContext && viewStateContext.viewState.focus && viewStateContext.viewState.focus.indexOf(id) > -1) {
          viewStateContext.focus.push(childAsyncDataTreeNode);
        }
        if (viewStateContext && viewStateContext.viewState.selection && viewStateContext.viewState.selection.indexOf(id) > -1) {
          viewStateContext.selection.push(childAsyncDataTreeNode);
        }
        if (viewStateContext && viewStateContext.viewState.expanded && viewStateContext.viewState.expanded.indexOf(id) > -1) {
          childrenToRefresh.push(childAsyncDataTreeNode);
        } else if (hasChildren && childAsyncDataTreeNode.defaultCollapseState === ObjectTreeElementCollapseState.PreserveOrExpanded) {
          childrenToRefresh.push(childAsyncDataTreeNode);
        }
        return childAsyncDataTreeNode;
      });
      for (const node2 of nodesToForget.values()) {
        dfs(node2, (node3) => this.nodes.delete(node3.element));
      }
      for (const child of children) {
        this.nodes.set(child.element, child);
      }
      splice$1(node.children, 0, node.children.length, children);
      if (node !== this.root && this.autoExpandSingleChildren && children.length === 1 && childrenToRefresh.length === 0) {
        children[0].forceExpanded = true;
        childrenToRefresh.push(children[0]);
      }
      return childrenToRefresh;
    }
    render(node, viewStateContext, options) {
      const children = node.children.map((node2) => this.asTreeElement(node2, viewStateContext));
      const objectTreeOptions = options && {
        ...options,
        diffIdentityProvider: options.diffIdentityProvider && {
          getId(node2) {
            return options.diffIdentityProvider.getId(node2.element);
          }
        }
      };
      this.tree.setChildren(node === this.root ? null : node, children, objectTreeOptions);
      if (node !== this.root) {
        this.tree.setCollapsible(node, node.hasChildren);
      }
      this._onDidRender.fire();
    }
    asTreeElement(node, viewStateContext) {
      if (node.stale) {
        return {
          element: node,
          collapsible: node.hasChildren,
          collapsed: true
        };
      }
      let collapsed2;
      if (viewStateContext && viewStateContext.viewState.expanded && node.id && viewStateContext.viewState.expanded.indexOf(node.id) > -1) {
        collapsed2 = false;
      } else if (node.forceExpanded) {
        collapsed2 = false;
        node.forceExpanded = false;
      } else {
        collapsed2 = node.defaultCollapseState;
      }
      return {
        element: node,
        children: node.hasChildren ? Iterable.map(node.children, (child) => this.asTreeElement(child, viewStateContext)) : [],
        collapsible: node.hasChildren,
        collapsed: collapsed2
      };
    }
    processChildren(children) {
      if (this.sorter) {
        children = [...children].sort(this.sorter.compare.bind(this.sorter));
      }
      return children;
    }
    dispose() {
      this.disposables.dispose();
      this.tree.dispose();
    }
  }
  class CompressibleAsyncDataTreeNodeWrapper {
    get element() {
      return {
        elements: this.node.element.elements.map((e) => e.element),
        incompressible: this.node.element.incompressible
      };
    }
    get children() {
      return this.node.children.map((node) => new CompressibleAsyncDataTreeNodeWrapper(node));
    }
    get depth() {
      return this.node.depth;
    }
    get visibleChildrenCount() {
      return this.node.visibleChildrenCount;
    }
    get visibleChildIndex() {
      return this.node.visibleChildIndex;
    }
    get collapsible() {
      return this.node.collapsible;
    }
    get collapsed() {
      return this.node.collapsed;
    }
    get visible() {
      return this.node.visible;
    }
    get filterData() {
      return this.node.filterData;
    }
    constructor(node) {
      this.node = node;
    }
  }
  class CompressibleAsyncDataTreeRenderer {
    constructor(renderer, nodeMapper, compressibleNodeMapperProvider, onDidChangeTwistieState) {
      this.renderer = renderer;
      this.nodeMapper = nodeMapper;
      this.compressibleNodeMapperProvider = compressibleNodeMapperProvider;
      this.onDidChangeTwistieState = onDidChangeTwistieState;
      this.renderedNodes = /* @__PURE__ */ new Map();
      this.disposables = [];
      this.templateId = renderer.templateId;
    }
    renderTemplate(container) {
      const templateData = this.renderer.renderTemplate(container);
      return { templateData };
    }
    renderElement(node, index, templateData, details) {
      this.renderer.renderElement(this.nodeMapper.map(node), index, templateData.templateData, details);
    }
    renderCompressedElements(node, index, templateData, details) {
      this.renderer.renderCompressedElements(this.compressibleNodeMapperProvider().map(node), index, templateData.templateData, details);
    }
    renderTwistie(element, twistieElement) {
      if (element.slow) {
        twistieElement.classList.add(...ThemeIcon.asClassNameArray(Codicon.treeItemLoading));
        return true;
      } else {
        twistieElement.classList.remove(...ThemeIcon.asClassNameArray(Codicon.treeItemLoading));
        return false;
      }
    }
    disposeElement(node, index, templateData, details) {
      this.renderer.disposeElement?.(this.nodeMapper.map(node), index, templateData.templateData, details);
    }
    disposeCompressedElements(node, index, templateData, details) {
      this.renderer.disposeCompressedElements?.(this.compressibleNodeMapperProvider().map(node), index, templateData.templateData, details);
    }
    disposeTemplate(templateData) {
      this.renderer.disposeTemplate(templateData.templateData);
    }
    dispose() {
      this.renderedNodes.clear();
      this.disposables = dispose(this.disposables);
    }
  }
  function asCompressibleObjectTreeOptions(options) {
    const objectTreeOptions = options && asObjectTreeOptions(options);
    return objectTreeOptions && {
      ...objectTreeOptions,
      keyboardNavigationLabelProvider: objectTreeOptions.keyboardNavigationLabelProvider && {
        ...objectTreeOptions.keyboardNavigationLabelProvider,
        getCompressedNodeKeyboardNavigationLabel(els) {
          return options.keyboardNavigationLabelProvider.getCompressedNodeKeyboardNavigationLabel(els.map((e) => e.element));
        }
      },
      stickyScrollDelegate: objectTreeOptions.stickyScrollDelegate
    };
  }
  class CompressibleAsyncDataTree extends AsyncDataTree {
    constructor(user, container, virtualDelegate, compressionDelegate, renderers, dataSource, options = {}) {
      super(user, container, virtualDelegate, renderers, dataSource, options);
      this.compressionDelegate = compressionDelegate;
      this.compressibleNodeMapper = new WeakMapper((node) => new CompressibleAsyncDataTreeNodeWrapper(node));
      this.filter = options.filter;
    }
    createTree(user, container, delegate, renderers, options) {
      const objectTreeDelegate = new ComposedTreeDelegate(delegate);
      const objectTreeRenderers = renderers.map((r) => new CompressibleAsyncDataTreeRenderer(r, this.nodeMapper, () => this.compressibleNodeMapper, this._onDidChangeNodeSlowState.event));
      const objectTreeOptions = asCompressibleObjectTreeOptions(options) || {};
      return new CompressibleObjectTree(user, container, objectTreeDelegate, objectTreeRenderers, objectTreeOptions);
    }
    asTreeElement(node, viewStateContext) {
      return {
        incompressible: this.compressionDelegate.isIncompressible(node.element),
        ...super.asTreeElement(node, viewStateContext)
      };
    }
    render(node, viewStateContext, options) {
      if (!this.identityProvider) {
        return super.render(node, viewStateContext);
      }
      const getId = (element) => this.identityProvider.getId(element).toString();
      const getUncompressedIds = (nodes) => {
        const result = /* @__PURE__ */ new Set();
        for (const node2 of nodes) {
          const compressedNode = this.tree.getCompressedTreeNode(node2 === this.root ? null : node2);
          if (!compressedNode.element) {
            continue;
          }
          for (const node3 of compressedNode.element.elements) {
            result.add(getId(node3.element));
          }
        }
        return result;
      };
      const oldSelection = getUncompressedIds(this.tree.getSelection());
      const oldFocus = getUncompressedIds(this.tree.getFocus());
      super.render(node, viewStateContext, options);
      const selection = this.getSelection();
      let didChangeSelection = false;
      const focus = this.getFocus();
      let didChangeFocus = false;
      const visit = (node2) => {
        const compressedNode = node2.element;
        if (compressedNode) {
          for (let i2 = 0; i2 < compressedNode.elements.length; i2++) {
            const id = getId(compressedNode.elements[i2].element);
            const element = compressedNode.elements[compressedNode.elements.length - 1].element;
            if (oldSelection.has(id) && selection.indexOf(element) === -1) {
              selection.push(element);
              didChangeSelection = true;
            }
            if (oldFocus.has(id) && focus.indexOf(element) === -1) {
              focus.push(element);
              didChangeFocus = true;
            }
          }
        }
        node2.children.forEach(visit);
      };
      visit(this.tree.getCompressedTreeNode(node === this.root ? null : node));
      if (didChangeSelection) {
        this.setSelection(selection);
      }
      if (didChangeFocus) {
        this.setFocus(focus);
      }
    }
    // For compressed async data trees, `TreeVisibility.Recurse` doesn't currently work
    // and we have to filter everything beforehand
    // Related to #85193 and #85835
    processChildren(children) {
      if (this.filter) {
        children = Iterable.filter(children, (e) => {
          const result = this.filter.filter(
            e,
            1
            /* TreeVisibility.Visible */
          );
          const visibility = getVisibility(result);
          if (visibility === 2) {
            throw new Error("Recursive tree visibility not supported in async data compressed trees");
          }
          return visibility === 1;
        });
      }
      return super.processChildren(children);
    }
  }
  function getVisibility(filterResult) {
    if (typeof filterResult === "boolean") {
      return filterResult ? 1 : 0;
    } else if (isFilterResult(filterResult)) {
      return getVisibleState(filterResult.visibility);
    } else {
      return getVisibleState(filterResult);
    }
  }
  class DataTree extends AbstractTree {
    constructor(user, container, delegate, renderers, dataSource, options = {}) {
      super(user, container, delegate, renderers, options);
      this.user = user;
      this.dataSource = dataSource;
      this.identityProvider = options.identityProvider;
    }
    createModel(user, options) {
      return new ObjectTreeModel(user, options);
    }
  }
  new RawContextKey("isMac", isMacintosh, localize(1684, "Whether the operating system is macOS"));
  new RawContextKey("isLinux", isLinux, localize(1685, "Whether the operating system is Linux"));
  const IsWindowsContext = new RawContextKey("isWindows", isWindows, localize(1686, "Whether the operating system is Windows"));
  const IsWebContext = new RawContextKey("isWeb", isWeb, localize(1687, "Whether the platform is a web browser"));
  new RawContextKey("isMacNative", isMacintosh && !isWeb, localize(1688, "Whether the operating system is macOS on a non-browser platform"));
  new RawContextKey("isIOS", isIOS, localize(1689, "Whether the operating system is iOS"));
  new RawContextKey("isMobile", isMobile, localize(1690, "Whether the platform is a mobile web browser"));
  new RawContextKey("isDevelopment", false, true);
  new RawContextKey("productQualityType", "", localize(1691, "Quality type of VS Code"));
  const InputFocusedContextKey = "inputFocus";
  const InputFocusedContext = new RawContextKey(InputFocusedContextKey, false, localize(1692, "Whether keyboard focus is inside an input box"));
  var __decorate$21 = 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$20 = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  const IListService = createDecorator("listService");
  class ListService {
    get lastFocusedList() {
      return this._lastFocusedWidget;
    }
    constructor() {
      this.disposables = new DisposableStore();
      this.lists = [];
      this._lastFocusedWidget = void 0;
    }
    setLastFocusedList(widget) {
      if (widget === this._lastFocusedWidget) {
        return;
      }
      this._lastFocusedWidget?.getHTMLElement().classList.remove("last-focused");
      this._lastFocusedWidget = widget;
      this._lastFocusedWidget?.getHTMLElement().classList.add("last-focused");
    }
    register(widget, extraContextKeys) {
      if (this.lists.some((l) => l.widget === widget)) {
        throw new Error("Cannot register the same widget multiple times");
      }
      const registeredList = { widget, extraContextKeys };
      this.lists.push(registeredList);
      if (isActiveElement(widget.getHTMLElement())) {
        this.setLastFocusedList(widget);
      }
      return combinedDisposable(widget.onDidFocus(() => this.setLastFocusedList(widget)), toDisposable(() => this.lists.splice(this.lists.indexOf(registeredList), 1)), widget.onDidDispose(() => {
        this.lists = this.lists.filter((l) => l !== registeredList);
        if (this._lastFocusedWidget === widget) {
          this.setLastFocusedList(void 0);
        }
      }));
    }
    dispose() {
      this.disposables.dispose();
    }
  }
  const RawWorkbenchListScrollAtBoundaryContextKey = new RawContextKey("listScrollAtBoundary", "none");
  ContextKeyExpr.or(RawWorkbenchListScrollAtBoundaryContextKey.isEqualTo("top"), RawWorkbenchListScrollAtBoundaryContextKey.isEqualTo("both"));
  ContextKeyExpr.or(RawWorkbenchListScrollAtBoundaryContextKey.isEqualTo("bottom"), RawWorkbenchListScrollAtBoundaryContextKey.isEqualTo("both"));
  const RawWorkbenchListFocusContextKey = new RawContextKey("listFocus", true);
  const WorkbenchTreeStickyScrollFocused = new RawContextKey("treestickyScrollFocused", false);
  const WorkbenchListSupportsMultiSelectContextKey = new RawContextKey("listSupportsMultiselect", true);
  const WorkbenchListFocusContextKey = ContextKeyExpr.and(RawWorkbenchListFocusContextKey, ContextKeyExpr.not(InputFocusedContextKey), WorkbenchTreeStickyScrollFocused.negate());
  const WorkbenchListHasSelectionOrFocus = new RawContextKey("listHasSelectionOrFocus", false);
  const WorkbenchListDoubleSelection = new RawContextKey("listDoubleSelection", false);
  const WorkbenchListMultiSelection = new RawContextKey("listMultiSelection", false);
  const WorkbenchListSelectionNavigation = new RawContextKey("listSelectionNavigation", false);
  const WorkbenchListSupportsFind = new RawContextKey("listSupportsFind", true);
  const WorkbenchTreeElementCanCollapse = new RawContextKey("treeElementCanCollapse", false);
  const WorkbenchTreeElementHasParent = new RawContextKey("treeElementHasParent", false);
  const WorkbenchTreeElementCanExpand = new RawContextKey("treeElementCanExpand", false);
  const WorkbenchTreeElementHasChild = new RawContextKey("treeElementHasChild", false);
  const WorkbenchTreeFindOpen = new RawContextKey("treeFindOpen", false);
  const WorkbenchListTypeNavigationModeKey = "listTypeNavigationMode";
  const WorkbenchListAutomaticKeyboardNavigationLegacyKey = "listAutomaticKeyboardNavigation";
  function createScopedContextKeyService(contextKeyService, widget) {
    const result = contextKeyService.createScoped(widget.getHTMLElement());
    RawWorkbenchListFocusContextKey.bindTo(result);
    return result;
  }
  function createScrollObserver(contextKeyService, widget) {
    const listScrollAt = RawWorkbenchListScrollAtBoundaryContextKey.bindTo(contextKeyService);
    const update = () => {
      const atTop = widget.scrollTop === 0;
      const atBottom = widget.scrollHeight - widget.renderHeight - widget.scrollTop < 1;
      if (atTop && atBottom) {
        listScrollAt.set("both");
      } else if (atTop) {
        listScrollAt.set("top");
      } else if (atBottom) {
        listScrollAt.set("bottom");
      } else {
        listScrollAt.set("none");
      }
    };
    update();
    return widget.onDidScroll(update);
  }
  const multiSelectModifierSettingKey = "workbench.list.multiSelectModifier";
  const openModeSettingKey = "workbench.list.openMode";
  const horizontalScrollingKey = "workbench.list.horizontalScrolling";
  const defaultFindModeSettingKey = "workbench.list.defaultFindMode";
  const typeNavigationModeSettingKey = "workbench.list.typeNavigationMode";
  const keyboardNavigationSettingKey = "workbench.list.keyboardNavigation";
  const scrollByPageKey = "workbench.list.scrollByPage";
  const defaultFindMatchTypeSettingKey = "workbench.list.defaultFindMatchType";
  const treeIndentKey = "workbench.tree.indent";
  const treeRenderIndentGuidesKey = "workbench.tree.renderIndentGuides";
  const listSmoothScrolling = "workbench.list.smoothScrolling";
  const mouseWheelScrollSensitivityKey = "workbench.list.mouseWheelScrollSensitivity";
  const fastScrollSensitivityKey = "workbench.list.fastScrollSensitivity";
  const treeExpandMode = "workbench.tree.expandMode";
  const treeStickyScroll = "workbench.tree.enableStickyScroll";
  const treeStickyScrollMaxElements = "workbench.tree.stickyScrollMaxItemCount";
  function useAltAsMultipleSelectionModifier(configurationService) {
    return configurationService.getValue(multiSelectModifierSettingKey) === "alt";
  }
  class MultipleSelectionController extends Disposable {
    constructor(configurationService) {
      super();
      this.configurationService = configurationService;
      this.useAltAsMultipleSelectionModifier = useAltAsMultipleSelectionModifier(configurationService);
      this.registerListeners();
    }
    registerListeners() {
      this._register(this.configurationService.onDidChangeConfiguration((e) => {
        if (e.affectsConfiguration(multiSelectModifierSettingKey)) {
          this.useAltAsMultipleSelectionModifier = useAltAsMultipleSelectionModifier(this.configurationService);
        }
      }));
    }
    isSelectionSingleChangeEvent(event) {
      if (this.useAltAsMultipleSelectionModifier) {
        return event.browserEvent.altKey;
      }
      return isSelectionSingleChangeEvent(event);
    }
    isSelectionRangeChangeEvent(event) {
      return isSelectionRangeChangeEvent(event);
    }
  }
  function toWorkbenchListOptions(accessor, options) {
    const configurationService = accessor.get(IConfigurationService);
    const keybindingService = accessor.get(IKeybindingService);
    const disposables = new DisposableStore();
    const result = {
      ...options,
      keyboardNavigationDelegate: { mightProducePrintableCharacter(e) {
        return keybindingService.mightProducePrintableCharacter(e);
      } },
      smoothScrolling: Boolean(configurationService.getValue(listSmoothScrolling)),
      mouseWheelScrollSensitivity: configurationService.getValue(mouseWheelScrollSensitivityKey),
      fastScrollSensitivity: configurationService.getValue(fastScrollSensitivityKey),
      multipleSelectionController: options.multipleSelectionController ?? disposables.add(new MultipleSelectionController(configurationService)),
      keyboardNavigationEventFilter: createKeyboardNavigationEventFilter(keybindingService),
      scrollByPage: Boolean(configurationService.getValue(scrollByPageKey))
    };
    return [result, disposables];
  }
  let WorkbenchList = class WorkbenchList extends List {
    constructor(user, container, delegate, renderers, options, contextKeyService, listService, configurationService, instantiationService) {
      const horizontalScrolling = typeof options.horizontalScrolling !== "undefined" ? options.horizontalScrolling : Boolean(configurationService.getValue(horizontalScrollingKey));
      const [workbenchListOptions, workbenchListOptionsDisposable] = instantiationService.invokeFunction(toWorkbenchListOptions, options);
      super(user, container, delegate, renderers, {
        keyboardSupport: false,
        ...workbenchListOptions,
        horizontalScrolling
      });
      this.disposables.add(workbenchListOptionsDisposable);
      this.contextKeyService = createScopedContextKeyService(contextKeyService, this);
      this.disposables.add(createScrollObserver(this.contextKeyService, this));
      this.listSupportsMultiSelect = WorkbenchListSupportsMultiSelectContextKey.bindTo(this.contextKeyService);
      this.listSupportsMultiSelect.set(options.multipleSelectionSupport !== false);
      const listSelectionNavigation = WorkbenchListSelectionNavigation.bindTo(this.contextKeyService);
      listSelectionNavigation.set(Boolean(options.selectionNavigation));
      this.listHasSelectionOrFocus = WorkbenchListHasSelectionOrFocus.bindTo(this.contextKeyService);
      this.listDoubleSelection = WorkbenchListDoubleSelection.bindTo(this.contextKeyService);
      this.listMultiSelection = WorkbenchListMultiSelection.bindTo(this.contextKeyService);
      this.horizontalScrolling = options.horizontalScrolling;
      this._useAltAsMultipleSelectionModifier = useAltAsMultipleSelectionModifier(configurationService);
      this.disposables.add(this.contextKeyService);
      this.disposables.add(listService.register(this));
      this.updateStyles(options.overrideStyles);
      this.disposables.add(this.onDidChangeSelection(() => {
        const selection = this.getSelection();
        const focus = this.getFocus();
        this.contextKeyService.bufferChangeEvents(() => {
          this.listHasSelectionOrFocus.set(selection.length > 0 || focus.length > 0);
          this.listMultiSelection.set(selection.length > 1);
          this.listDoubleSelection.set(selection.length === 2);
        });
      }));
      this.disposables.add(this.onDidChangeFocus(() => {
        const selection = this.getSelection();
        const focus = this.getFocus();
        this.listHasSelectionOrFocus.set(selection.length > 0 || focus.length > 0);
      }));
      this.disposables.add(configurationService.onDidChangeConfiguration((e) => {
        if (e.affectsConfiguration(multiSelectModifierSettingKey)) {
          this._useAltAsMultipleSelectionModifier = useAltAsMultipleSelectionModifier(configurationService);
        }
        let options2 = {};
        if (e.affectsConfiguration(horizontalScrollingKey) && this.horizontalScrolling === void 0) {
          const horizontalScrolling2 = Boolean(configurationService.getValue(horizontalScrollingKey));
          options2 = { ...options2, horizontalScrolling: horizontalScrolling2 };
        }
        if (e.affectsConfiguration(scrollByPageKey)) {
          const scrollByPage = Boolean(configurationService.getValue(scrollByPageKey));
          options2 = { ...options2, scrollByPage };
        }
        if (e.affectsConfiguration(listSmoothScrolling)) {
          const smoothScrolling = Boolean(configurationService.getValue(listSmoothScrolling));
          options2 = { ...options2, smoothScrolling };
        }
        if (e.affectsConfiguration(mouseWheelScrollSensitivityKey)) {
          const mouseWheelScrollSensitivity = configurationService.getValue(mouseWheelScrollSensitivityKey);
          options2 = { ...options2, mouseWheelScrollSensitivity };
        }
        if (e.affectsConfiguration(fastScrollSensitivityKey)) {
          const fastScrollSensitivity = configurationService.getValue(fastScrollSensitivityKey);
          options2 = { ...options2, fastScrollSensitivity };
        }
        if (Object.keys(options2).length > 0) {
          this.updateOptions(options2);
        }
      }));
      this.navigator = new ListResourceNavigator(this, { configurationService, ...options });
      this.disposables.add(this.navigator);
    }
    updateOptions(options) {
      super.updateOptions(options);
      if (options.overrideStyles !== void 0) {
        this.updateStyles(options.overrideStyles);
      }
      if (options.multipleSelectionSupport !== void 0) {
        this.listSupportsMultiSelect.set(!!options.multipleSelectionSupport);
      }
    }
    updateStyles(styles) {
      this.style(styles ? getListStyles(styles) : defaultListStyles);
    }
  };
  WorkbenchList = __decorate$21([
    __param$20(5, IContextKeyService),
    __param$20(6, IListService),
    __param$20(7, IConfigurationService),
    __param$20(8, IInstantiationService)
  ], WorkbenchList);
  let WorkbenchPagedList = class WorkbenchPagedList extends PagedList {
    constructor(user, container, delegate, renderers, options, contextKeyService, listService, configurationService, instantiationService) {
      const horizontalScrolling = typeof options.horizontalScrolling !== "undefined" ? options.horizontalScrolling : Boolean(configurationService.getValue(horizontalScrollingKey));
      const [workbenchListOptions, workbenchListOptionsDisposable] = instantiationService.invokeFunction(toWorkbenchListOptions, options);
      super(user, container, delegate, renderers, {
        keyboardSupport: false,
        ...workbenchListOptions,
        horizontalScrolling
      });
      this.disposables = new DisposableStore();
      this.disposables.add(workbenchListOptionsDisposable);
      this.contextKeyService = createScopedContextKeyService(contextKeyService, this);
      this.disposables.add(createScrollObserver(this.contextKeyService, this.widget));
      this.horizontalScrolling = options.horizontalScrolling;
      this.listSupportsMultiSelect = WorkbenchListSupportsMultiSelectContextKey.bindTo(this.contextKeyService);
      this.listSupportsMultiSelect.set(options.multipleSelectionSupport !== false);
      const listSelectionNavigation = WorkbenchListSelectionNavigation.bindTo(this.contextKeyService);
      listSelectionNavigation.set(Boolean(options.selectionNavigation));
      this._useAltAsMultipleSelectionModifier = useAltAsMultipleSelectionModifier(configurationService);
      this.disposables.add(this.contextKeyService);
      this.disposables.add(listService.register(this));
      this.updateStyles(options.overrideStyles);
      this.disposables.add(configurationService.onDidChangeConfiguration((e) => {
        if (e.affectsConfiguration(multiSelectModifierSettingKey)) {
          this._useAltAsMultipleSelectionModifier = useAltAsMultipleSelectionModifier(configurationService);
        }
        let options2 = {};
        if (e.affectsConfiguration(horizontalScrollingKey) && this.horizontalScrolling === void 0) {
          const horizontalScrolling2 = Boolean(configurationService.getValue(horizontalScrollingKey));
          options2 = { ...options2, horizontalScrolling: horizontalScrolling2 };
        }
        if (e.affectsConfiguration(scrollByPageKey)) {
          const scrollByPage = Boolean(configurationService.getValue(scrollByPageKey));
          options2 = { ...options2, scrollByPage };
        }
        if (e.affectsConfiguration(listSmoothScrolling)) {
          const smoothScrolling = Boolean(configurationService.getValue(listSmoothScrolling));
          options2 = { ...options2, smoothScrolling };
        }
        if (e.affectsConfiguration(mouseWheelScrollSensitivityKey)) {
          const mouseWheelScrollSensitivity = configurationService.getValue(mouseWheelScrollSensitivityKey);
          options2 = { ...options2, mouseWheelScrollSensitivity };
        }
        if (e.affectsConfiguration(fastScrollSensitivityKey)) {
          const fastScrollSensitivity = configurationService.getValue(fastScrollSensitivityKey);
          options2 = { ...options2, fastScrollSensitivity };
        }
        if (Object.keys(options2).length > 0) {
          this.updateOptions(options2);
        }
      }));
      this.navigator = new ListResourceNavigator(this, { configurationService, ...options });
      this.disposables.add(this.navigator);
    }
    updateOptions(options) {
      super.updateOptions(options);
      if (options.overrideStyles !== void 0) {
        this.updateStyles(options.overrideStyles);
      }
      if (options.multipleSelectionSupport !== void 0) {
        this.listSupportsMultiSelect.set(!!options.multipleSelectionSupport);
      }
    }
    updateStyles(styles) {
      this.style(styles ? getListStyles(styles) : defaultListStyles);
    }
    dispose() {
      this.disposables.dispose();
      super.dispose();
    }
  };
  WorkbenchPagedList = __decorate$21([
    __param$20(5, IContextKeyService),
    __param$20(6, IListService),
    __param$20(7, IConfigurationService),
    __param$20(8, IInstantiationService)
  ], WorkbenchPagedList);
  let WorkbenchTable = class WorkbenchTable extends Table {
    constructor(user, container, delegate, columns, renderers, options, contextKeyService, listService, configurationService, instantiationService) {
      const horizontalScrolling = typeof options.horizontalScrolling !== "undefined" ? options.horizontalScrolling : Boolean(configurationService.getValue(horizontalScrollingKey));
      const [workbenchListOptions, workbenchListOptionsDisposable] = instantiationService.invokeFunction(toWorkbenchListOptions, options);
      super(user, container, delegate, columns, renderers, {
        keyboardSupport: false,
        ...workbenchListOptions,
        horizontalScrolling
      });
      this.disposables.add(workbenchListOptionsDisposable);
      this.contextKeyService = createScopedContextKeyService(contextKeyService, this);
      this.disposables.add(createScrollObserver(this.contextKeyService, this));
      this.listSupportsMultiSelect = WorkbenchListSupportsMultiSelectContextKey.bindTo(this.contextKeyService);
      this.listSupportsMultiSelect.set(options.multipleSelectionSupport !== false);
      const listSelectionNavigation = WorkbenchListSelectionNavigation.bindTo(this.contextKeyService);
      listSelectionNavigation.set(Boolean(options.selectionNavigation));
      this.listHasSelectionOrFocus = WorkbenchListHasSelectionOrFocus.bindTo(this.contextKeyService);
      this.listDoubleSelection = WorkbenchListDoubleSelection.bindTo(this.contextKeyService);
      this.listMultiSelection = WorkbenchListMultiSelection.bindTo(this.contextKeyService);
      this.horizontalScrolling = options.horizontalScrolling;
      this._useAltAsMultipleSelectionModifier = useAltAsMultipleSelectionModifier(configurationService);
      this.disposables.add(this.contextKeyService);
      this.disposables.add(listService.register(this));
      this.updateStyles(options.overrideStyles);
      this.disposables.add(this.onDidChangeSelection(() => {
        const selection = this.getSelection();
        const focus = this.getFocus();
        this.contextKeyService.bufferChangeEvents(() => {
          this.listHasSelectionOrFocus.set(selection.length > 0 || focus.length > 0);
          this.listMultiSelection.set(selection.length > 1);
          this.listDoubleSelection.set(selection.length === 2);
        });
      }));
      this.disposables.add(this.onDidChangeFocus(() => {
        const selection = this.getSelection();
        const focus = this.getFocus();
        this.listHasSelectionOrFocus.set(selection.length > 0 || focus.length > 0);
      }));
      this.disposables.add(configurationService.onDidChangeConfiguration((e) => {
        if (e.affectsConfiguration(multiSelectModifierSettingKey)) {
          this._useAltAsMultipleSelectionModifier = useAltAsMultipleSelectionModifier(configurationService);
        }
        let options2 = {};
        if (e.affectsConfiguration(horizontalScrollingKey) && this.horizontalScrolling === void 0) {
          const horizontalScrolling2 = Boolean(configurationService.getValue(horizontalScrollingKey));
          options2 = { ...options2, horizontalScrolling: horizontalScrolling2 };
        }
        if (e.affectsConfiguration(scrollByPageKey)) {
          const scrollByPage = Boolean(configurationService.getValue(scrollByPageKey));
          options2 = { ...options2, scrollByPage };
        }
        if (e.affectsConfiguration(listSmoothScrolling)) {
          const smoothScrolling = Boolean(configurationService.getValue(listSmoothScrolling));
          options2 = { ...options2, smoothScrolling };
        }
        if (e.affectsConfiguration(mouseWheelScrollSensitivityKey)) {
          const mouseWheelScrollSensitivity = configurationService.getValue(mouseWheelScrollSensitivityKey);
          options2 = { ...options2, mouseWheelScrollSensitivity };
        }
        if (e.affectsConfiguration(fastScrollSensitivityKey)) {
          const fastScrollSensitivity = configurationService.getValue(fastScrollSensitivityKey);
          options2 = { ...options2, fastScrollSensitivity };
        }
        if (Object.keys(options2).length > 0) {
          this.updateOptions(options2);
        }
      }));
      this.navigator = new TableResourceNavigator(this, { configurationService, ...options });
      this.disposables.add(this.navigator);
    }
    updateOptions(options) {
      super.updateOptions(options);
      if (options.overrideStyles !== void 0) {
        this.updateStyles(options.overrideStyles);
      }
      if (options.multipleSelectionSupport !== void 0) {
        this.listSupportsMultiSelect.set(!!options.multipleSelectionSupport);
      }
    }
    updateStyles(styles) {
      this.style(styles ? getListStyles(styles) : defaultListStyles);
    }
    dispose() {
      this.disposables.dispose();
      super.dispose();
    }
  };
  WorkbenchTable = __decorate$21([
    __param$20(6, IContextKeyService),
    __param$20(7, IListService),
    __param$20(8, IConfigurationService),
    __param$20(9, IInstantiationService)
  ], WorkbenchTable);
  class ResourceNavigator extends Disposable {
    constructor(widget, options) {
      super();
      this.widget = widget;
      this._onDidOpen = this._register(new Emitter$1());
      this.onDidOpen = this._onDidOpen.event;
      this._register(Event.filter(this.widget.onDidChangeSelection, (e) => isKeyboardEvent(e.browserEvent))((e) => this.onSelectionFromKeyboard(e)));
      this._register(this.widget.onPointer((e) => this.onPointer(e.element, e.browserEvent)));
      this._register(this.widget.onMouseDblClick((e) => this.onMouseDblClick(e.element, e.browserEvent)));
      if (typeof options?.openOnSingleClick !== "boolean" && options?.configurationService) {
        this.openOnSingleClick = options?.configurationService.getValue(openModeSettingKey) !== "doubleClick";
        this._register(options?.configurationService.onDidChangeConfiguration((e) => {
          if (e.affectsConfiguration(openModeSettingKey)) {
            this.openOnSingleClick = options?.configurationService.getValue(openModeSettingKey) !== "doubleClick";
          }
        }));
      } else {
        this.openOnSingleClick = options?.openOnSingleClick ?? true;
      }
    }
    onSelectionFromKeyboard(event) {
      if (event.elements.length !== 1) {
        return;
      }
      const selectionKeyboardEvent = event.browserEvent;
      const preserveFocus = typeof selectionKeyboardEvent.preserveFocus === "boolean" ? selectionKeyboardEvent.preserveFocus : true;
      const pinned = typeof selectionKeyboardEvent.pinned === "boolean" ? selectionKeyboardEvent.pinned : !preserveFocus;
      const sideBySide = false;
      this._open(this.getSelectedElement(), preserveFocus, pinned, sideBySide, event.browserEvent);
    }
    onPointer(element, browserEvent) {
      if (!this.openOnSingleClick) {
        return;
      }
      const isDoubleClick = browserEvent.detail === 2;
      if (isDoubleClick) {
        return;
      }
      const isMiddleClick = browserEvent.button === 1;
      const preserveFocus = true;
      const pinned = isMiddleClick;
      const sideBySide = browserEvent.ctrlKey || browserEvent.metaKey || browserEvent.altKey;
      this._open(element, preserveFocus, pinned, sideBySide, browserEvent);
    }
    onMouseDblClick(element, browserEvent) {
      if (!browserEvent) {
        return;
      }
      const target = browserEvent.target;
      const onTwistie = target.classList.contains("monaco-tl-twistie") || target.classList.contains("monaco-icon-label") && target.classList.contains("folder-icon") && browserEvent.offsetX < 16;
      if (onTwistie) {
        return;
      }
      const preserveFocus = false;
      const pinned = true;
      const sideBySide = browserEvent.ctrlKey || browserEvent.metaKey || browserEvent.altKey;
      this._open(element, preserveFocus, pinned, sideBySide, browserEvent);
    }
    _open(element, preserveFocus, pinned, sideBySide, browserEvent) {
      if (!element) {
        return;
      }
      this._onDidOpen.fire({
        editorOptions: {
          preserveFocus,
          pinned,
          revealIfVisible: true
        },
        sideBySide,
        element,
        browserEvent
      });
    }
  }
  class ListResourceNavigator extends ResourceNavigator {
    constructor(widget, options) {
      super(widget, options);
      this.widget = widget;
    }
    getSelectedElement() {
      return this.widget.getSelectedElements()[0];
    }
  }
  class TableResourceNavigator extends ResourceNavigator {
    constructor(widget, options) {
      super(widget, options);
    }
    getSelectedElement() {
      return this.widget.getSelectedElements()[0];
    }
  }
  class TreeResourceNavigator extends ResourceNavigator {
    constructor(widget, options) {
      super(widget, options);
    }
    getSelectedElement() {
      return this.widget.getSelection()[0] ?? void 0;
    }
  }
  function createKeyboardNavigationEventFilter(keybindingService) {
    let inMultiChord = false;
    return (event) => {
      if (event.toKeyCodeChord().isModifierKey()) {
        return false;
      }
      if (inMultiChord) {
        inMultiChord = false;
        return false;
      }
      const result = keybindingService.softDispatch(event, event.target);
      if (result.kind === 1) {
        inMultiChord = true;
        return false;
      }
      inMultiChord = false;
      return result.kind === 0;
    };
  }
  let WorkbenchObjectTree = class WorkbenchObjectTree extends ObjectTree {
    get onDidOpen() {
      return this.internals.onDidOpen;
    }
    constructor(user, container, delegate, renderers, options, instantiationService, contextKeyService, listService, configurationService) {
      const { options: treeOptions, getTypeNavigationMode, disposable } = instantiationService.invokeFunction(workbenchTreeDataPreamble, options);
      super(user, container, delegate, renderers, treeOptions);
      this.disposables.add(disposable);
      this.internals = new WorkbenchTreeInternals(this, options, getTypeNavigationMode, options.overrideStyles, contextKeyService, listService, configurationService);
      this.disposables.add(this.internals);
    }
    updateOptions(options) {
      super.updateOptions(options);
      this.internals.updateOptions(options);
    }
  };
  WorkbenchObjectTree = __decorate$21([
    __param$20(5, IInstantiationService),
    __param$20(6, IContextKeyService),
    __param$20(7, IListService),
    __param$20(8, IConfigurationService)
  ], WorkbenchObjectTree);
  let WorkbenchCompressibleObjectTree = class WorkbenchCompressibleObjectTree extends CompressibleObjectTree {
    constructor(user, container, delegate, renderers, options, instantiationService, contextKeyService, listService, configurationService) {
      const { options: treeOptions, getTypeNavigationMode, disposable } = instantiationService.invokeFunction(workbenchTreeDataPreamble, options);
      super(user, container, delegate, renderers, treeOptions);
      this.disposables.add(disposable);
      this.internals = new WorkbenchTreeInternals(this, options, getTypeNavigationMode, options.overrideStyles, contextKeyService, listService, configurationService);
      this.disposables.add(this.internals);
    }
    updateOptions(options = {}) {
      super.updateOptions(options);
      if (options.overrideStyles) {
        this.internals.updateStyleOverrides(options.overrideStyles);
      }
      this.internals.updateOptions(options);
    }
  };
  WorkbenchCompressibleObjectTree = __decorate$21([
    __param$20(5, IInstantiationService),
    __param$20(6, IContextKeyService),
    __param$20(7, IListService),
    __param$20(8, IConfigurationService)
  ], WorkbenchCompressibleObjectTree);
  let WorkbenchDataTree = class WorkbenchDataTree extends DataTree {
    constructor(user, container, delegate, renderers, dataSource, options, instantiationService, contextKeyService, listService, configurationService) {
      const { options: treeOptions, getTypeNavigationMode, disposable } = instantiationService.invokeFunction(workbenchTreeDataPreamble, options);
      super(user, container, delegate, renderers, dataSource, treeOptions);
      this.disposables.add(disposable);
      this.internals = new WorkbenchTreeInternals(this, options, getTypeNavigationMode, options.overrideStyles, contextKeyService, listService, configurationService);
      this.disposables.add(this.internals);
    }
    updateOptions(options = {}) {
      super.updateOptions(options);
      if (options.overrideStyles !== void 0) {
        this.internals.updateStyleOverrides(options.overrideStyles);
      }
      this.internals.updateOptions(options);
    }
  };
  WorkbenchDataTree = __decorate$21([
    __param$20(6, IInstantiationService),
    __param$20(7, IContextKeyService),
    __param$20(8, IListService),
    __param$20(9, IConfigurationService)
  ], WorkbenchDataTree);
  let WorkbenchAsyncDataTree = class WorkbenchAsyncDataTree extends AsyncDataTree {
    get onDidOpen() {
      return this.internals.onDidOpen;
    }
    constructor(user, container, delegate, renderers, dataSource, options, instantiationService, contextKeyService, listService, configurationService) {
      const { options: treeOptions, getTypeNavigationMode, disposable } = instantiationService.invokeFunction(workbenchTreeDataPreamble, options);
      super(user, container, delegate, renderers, dataSource, treeOptions);
      this.disposables.add(disposable);
      this.internals = new WorkbenchTreeInternals(this, options, getTypeNavigationMode, options.overrideStyles, contextKeyService, listService, configurationService);
      this.disposables.add(this.internals);
    }
    updateOptions(options = {}) {
      super.updateOptions(options);
      if (options.overrideStyles) {
        this.internals.updateStyleOverrides(options.overrideStyles);
      }
      this.internals.updateOptions(options);
    }
  };
  WorkbenchAsyncDataTree = __decorate$21([
    __param$20(6, IInstantiationService),
    __param$20(7, IContextKeyService),
    __param$20(8, IListService),
    __param$20(9, IConfigurationService)
  ], WorkbenchAsyncDataTree);
  let WorkbenchCompressibleAsyncDataTree = class WorkbenchCompressibleAsyncDataTree extends CompressibleAsyncDataTree {
    constructor(user, container, virtualDelegate, compressionDelegate, renderers, dataSource, options, instantiationService, contextKeyService, listService, configurationService) {
      const { options: treeOptions, getTypeNavigationMode, disposable } = instantiationService.invokeFunction(workbenchTreeDataPreamble, options);
      super(user, container, virtualDelegate, compressionDelegate, renderers, dataSource, treeOptions);
      this.disposables.add(disposable);
      this.internals = new WorkbenchTreeInternals(this, options, getTypeNavigationMode, options.overrideStyles, contextKeyService, listService, configurationService);
      this.disposables.add(this.internals);
    }
    updateOptions(options) {
      super.updateOptions(options);
      this.internals.updateOptions(options);
    }
  };
  WorkbenchCompressibleAsyncDataTree = __decorate$21([
    __param$20(7, IInstantiationService),
    __param$20(8, IContextKeyService),
    __param$20(9, IListService),
    __param$20(10, IConfigurationService)
  ], WorkbenchCompressibleAsyncDataTree);
  function getDefaultTreeFindMode(configurationService) {
    const value = configurationService.getValue(defaultFindModeSettingKey);
    if (value === "highlight") {
      return TreeFindMode.Highlight;
    } else if (value === "filter") {
      return TreeFindMode.Filter;
    }
    const deprecatedValue = configurationService.getValue(keyboardNavigationSettingKey);
    if (deprecatedValue === "simple" || deprecatedValue === "highlight") {
      return TreeFindMode.Highlight;
    } else if (deprecatedValue === "filter") {
      return TreeFindMode.Filter;
    }
    return void 0;
  }
  function getDefaultTreeFindMatchType(configurationService) {
    const value = configurationService.getValue(defaultFindMatchTypeSettingKey);
    if (value === "fuzzy") {
      return TreeFindMatchType.Fuzzy;
    } else if (value === "contiguous") {
      return TreeFindMatchType.Contiguous;
    }
    return void 0;
  }
  function workbenchTreeDataPreamble(accessor, options) {
    const configurationService = accessor.get(IConfigurationService);
    const contextViewService = accessor.get(IContextViewService);
    const contextKeyService = accessor.get(IContextKeyService);
    const instantiationService = accessor.get(IInstantiationService);
    const getTypeNavigationMode = () => {
      const modeString = contextKeyService.getContextKeyValue(WorkbenchListTypeNavigationModeKey);
      if (modeString === "automatic") {
        return TypeNavigationMode.Automatic;
      } else if (modeString === "trigger") {
        return TypeNavigationMode.Trigger;
      }
      const modeBoolean = contextKeyService.getContextKeyValue(WorkbenchListAutomaticKeyboardNavigationLegacyKey);
      if (modeBoolean === false) {
        return TypeNavigationMode.Trigger;
      }
      const configString = configurationService.getValue(typeNavigationModeSettingKey);
      if (configString === "automatic") {
        return TypeNavigationMode.Automatic;
      } else if (configString === "trigger") {
        return TypeNavigationMode.Trigger;
      }
      return void 0;
    };
    const horizontalScrolling = options.horizontalScrolling !== void 0 ? options.horizontalScrolling : Boolean(configurationService.getValue(horizontalScrollingKey));
    const [workbenchListOptions, disposable] = instantiationService.invokeFunction(toWorkbenchListOptions, options);
    const paddingBottom = options.paddingBottom;
    const renderIndentGuides = options.renderIndentGuides !== void 0 ? options.renderIndentGuides : configurationService.getValue(treeRenderIndentGuidesKey);
    return {
      getTypeNavigationMode,
      disposable,
      // eslint-disable-next-line local/code-no-dangerous-type-assertions
      options: {
        // ...options, // TODO@Joao why is this not splatted here?
        keyboardSupport: false,
        ...workbenchListOptions,
        indent: typeof configurationService.getValue(treeIndentKey) === "number" ? configurationService.getValue(treeIndentKey) : void 0,
        renderIndentGuides,
        smoothScrolling: Boolean(configurationService.getValue(listSmoothScrolling)),
        defaultFindMode: options.defaultFindMode ?? getDefaultTreeFindMode(configurationService),
        defaultFindMatchType: options.defaultFindMatchType ?? getDefaultTreeFindMatchType(configurationService),
        horizontalScrolling,
        scrollByPage: Boolean(configurationService.getValue(scrollByPageKey)),
        paddingBottom,
        hideTwistiesOfChildlessElements: options.hideTwistiesOfChildlessElements,
        expandOnlyOnTwistieClick: options.expandOnlyOnTwistieClick ?? configurationService.getValue(treeExpandMode) === "doubleClick",
        contextViewProvider: contextViewService,
        findWidgetStyles: defaultFindWidgetStyles,
        enableStickyScroll: Boolean(configurationService.getValue(treeStickyScroll)),
        stickyScrollMaxItemCount: Number(configurationService.getValue(treeStickyScrollMaxElements))
      }
    };
  }
  let WorkbenchTreeInternals = class WorkbenchTreeInternals {
    get onDidOpen() {
      return this.navigator.onDidOpen;
    }
    constructor(tree, options, getTypeNavigationMode, overrideStyles2, contextKeyService, listService, configurationService) {
      this.tree = tree;
      this.disposables = [];
      this.contextKeyService = createScopedContextKeyService(contextKeyService, tree);
      this.disposables.push(createScrollObserver(this.contextKeyService, tree));
      this.listSupportsMultiSelect = WorkbenchListSupportsMultiSelectContextKey.bindTo(this.contextKeyService);
      this.listSupportsMultiSelect.set(options.multipleSelectionSupport !== false);
      const listSelectionNavigation = WorkbenchListSelectionNavigation.bindTo(this.contextKeyService);
      listSelectionNavigation.set(Boolean(options.selectionNavigation));
      this.listSupportFindWidget = WorkbenchListSupportsFind.bindTo(this.contextKeyService);
      this.listSupportFindWidget.set(options.findWidgetEnabled ?? true);
      this.hasSelectionOrFocus = WorkbenchListHasSelectionOrFocus.bindTo(this.contextKeyService);
      this.hasDoubleSelection = WorkbenchListDoubleSelection.bindTo(this.contextKeyService);
      this.hasMultiSelection = WorkbenchListMultiSelection.bindTo(this.contextKeyService);
      this.treeElementCanCollapse = WorkbenchTreeElementCanCollapse.bindTo(this.contextKeyService);
      this.treeElementHasParent = WorkbenchTreeElementHasParent.bindTo(this.contextKeyService);
      this.treeElementCanExpand = WorkbenchTreeElementCanExpand.bindTo(this.contextKeyService);
      this.treeElementHasChild = WorkbenchTreeElementHasChild.bindTo(this.contextKeyService);
      this.treeFindOpen = WorkbenchTreeFindOpen.bindTo(this.contextKeyService);
      this.treeStickyScrollFocused = WorkbenchTreeStickyScrollFocused.bindTo(this.contextKeyService);
      this._useAltAsMultipleSelectionModifier = useAltAsMultipleSelectionModifier(configurationService);
      this.updateStyleOverrides(overrideStyles2);
      const updateCollapseContextKeys = () => {
        const focus = tree.getFocus()[0];
        if (!focus) {
          return;
        }
        const node = tree.getNode(focus);
        this.treeElementCanCollapse.set(node.collapsible && !node.collapsed);
        this.treeElementHasParent.set(!!tree.getParentElement(focus));
        this.treeElementCanExpand.set(node.collapsible && node.collapsed);
        this.treeElementHasChild.set(!!tree.getFirstElementChild(focus));
      };
      const interestingContextKeys = /* @__PURE__ */ new Set();
      interestingContextKeys.add(WorkbenchListTypeNavigationModeKey);
      interestingContextKeys.add(WorkbenchListAutomaticKeyboardNavigationLegacyKey);
      this.disposables.push(this.contextKeyService, listService.register(tree), tree.onDidChangeSelection(() => {
        const selection = tree.getSelection();
        const focus = tree.getFocus();
        this.contextKeyService.bufferChangeEvents(() => {
          this.hasSelectionOrFocus.set(selection.length > 0 || focus.length > 0);
          this.hasMultiSelection.set(selection.length > 1);
          this.hasDoubleSelection.set(selection.length === 2);
        });
      }), tree.onDidChangeFocus(() => {
        const selection = tree.getSelection();
        const focus = tree.getFocus();
        this.hasSelectionOrFocus.set(selection.length > 0 || focus.length > 0);
        updateCollapseContextKeys();
      }), tree.onDidChangeCollapseState(updateCollapseContextKeys), tree.onDidChangeModel(updateCollapseContextKeys), tree.onDidChangeFindOpenState((enabled) => this.treeFindOpen.set(enabled)), tree.onDidChangeStickyScrollFocused((focused) => this.treeStickyScrollFocused.set(focused)), configurationService.onDidChangeConfiguration((e) => {
        let newOptions = {};
        if (e.affectsConfiguration(multiSelectModifierSettingKey)) {
          this._useAltAsMultipleSelectionModifier = useAltAsMultipleSelectionModifier(configurationService);
        }
        if (e.affectsConfiguration(treeIndentKey)) {
          const indent = configurationService.getValue(treeIndentKey);
          newOptions = { ...newOptions, indent };
        }
        if (e.affectsConfiguration(treeRenderIndentGuidesKey) && options.renderIndentGuides === void 0) {
          const renderIndentGuides = configurationService.getValue(treeRenderIndentGuidesKey);
          newOptions = { ...newOptions, renderIndentGuides };
        }
        if (e.affectsConfiguration(listSmoothScrolling)) {
          const smoothScrolling = Boolean(configurationService.getValue(listSmoothScrolling));
          newOptions = { ...newOptions, smoothScrolling };
        }
        if (e.affectsConfiguration(defaultFindModeSettingKey) || e.affectsConfiguration(keyboardNavigationSettingKey)) {
          const defaultFindMode = getDefaultTreeFindMode(configurationService);
          newOptions = { ...newOptions, defaultFindMode };
        }
        if (e.affectsConfiguration(typeNavigationModeSettingKey) || e.affectsConfiguration(keyboardNavigationSettingKey)) {
          const typeNavigationMode = getTypeNavigationMode();
          newOptions = { ...newOptions, typeNavigationMode };
        }
        if (e.affectsConfiguration(defaultFindMatchTypeSettingKey)) {
          const defaultFindMatchType = getDefaultTreeFindMatchType(configurationService);
          newOptions = { ...newOptions, defaultFindMatchType };
        }
        if (e.affectsConfiguration(horizontalScrollingKey) && options.horizontalScrolling === void 0) {
          const horizontalScrolling = Boolean(configurationService.getValue(horizontalScrollingKey));
          newOptions = { ...newOptions, horizontalScrolling };
        }
        if (e.affectsConfiguration(scrollByPageKey)) {
          const scrollByPage = Boolean(configurationService.getValue(scrollByPageKey));
          newOptions = { ...newOptions, scrollByPage };
        }
        if (e.affectsConfiguration(treeExpandMode) && options.expandOnlyOnTwistieClick === void 0) {
          newOptions = { ...newOptions, expandOnlyOnTwistieClick: configurationService.getValue(treeExpandMode) === "doubleClick" };
        }
        if (e.affectsConfiguration(treeStickyScroll)) {
          const enableStickyScroll = configurationService.getValue(treeStickyScroll);
          newOptions = { ...newOptions, enableStickyScroll };
        }
        if (e.affectsConfiguration(treeStickyScrollMaxElements)) {
          const stickyScrollMaxItemCount = Math.max(1, configurationService.getValue(treeStickyScrollMaxElements));
          newOptions = { ...newOptions, stickyScrollMaxItemCount };
        }
        if (e.affectsConfiguration(mouseWheelScrollSensitivityKey)) {
          const mouseWheelScrollSensitivity = configurationService.getValue(mouseWheelScrollSensitivityKey);
          newOptions = { ...newOptions, mouseWheelScrollSensitivity };
        }
        if (e.affectsConfiguration(fastScrollSensitivityKey)) {
          const fastScrollSensitivity = configurationService.getValue(fastScrollSensitivityKey);
          newOptions = { ...newOptions, fastScrollSensitivity };
        }
        if (Object.keys(newOptions).length > 0) {
          tree.updateOptions(newOptions);
        }
      }), this.contextKeyService.onDidChangeContext((e) => {
        if (e.affectsSome(interestingContextKeys)) {
          tree.updateOptions({ typeNavigationMode: getTypeNavigationMode() });
        }
      }));
      this.navigator = new TreeResourceNavigator(tree, { configurationService, ...options });
      this.disposables.push(this.navigator);
    }
    updateOptions(options) {
      if (options.multipleSelectionSupport !== void 0) {
        this.listSupportsMultiSelect.set(!!options.multipleSelectionSupport);
      }
    }
    updateStyleOverrides(overrideStyles2) {
      this.tree.style(overrideStyles2 ? getListStyles(overrideStyles2) : defaultListStyles);
    }
    dispose() {
      this.disposables = dispose(this.disposables);
    }
  };
  WorkbenchTreeInternals = __decorate$21([
    __param$20(4, IContextKeyService),
    __param$20(5, IListService),
    __param$20(6, IConfigurationService)
  ], WorkbenchTreeInternals);
  const configurationRegistry = Registry.as(Extensions$6.Configuration);
  configurationRegistry.registerConfiguration({
    id: "workbench",
    order: 7,
    title: localize(1705, "Workbench"),
    type: "object",
    properties: {
      [multiSelectModifierSettingKey]: {
        type: "string",
        enum: ["ctrlCmd", "alt"],
        markdownEnumDescriptions: [
          localize(1706, "Maps to `Control` on Windows and Linux and to `Command` on macOS."),
          localize(1707, "Maps to `Alt` on Windows and Linux and to `Option` on macOS.")
        ],
        default: "ctrlCmd",
        description: localize(1708, "The modifier to be used to add an item in trees and lists to a multi-selection with the mouse (for example in the explorer, open editors and scm view). The 'Open to Side' mouse gestures - if supported - will adapt such that they do not conflict with the multiselect modifier.")
      },
      [openModeSettingKey]: {
        type: "string",
        enum: ["singleClick", "doubleClick"],
        default: "singleClick",
        description: localize(1709, "Controls how to open items in trees and lists using the mouse (if supported). Note that some trees and lists might choose to ignore this setting if it is not applicable.")
      },
      [horizontalScrollingKey]: {
        type: "boolean",
        default: false,
        description: localize(1710, "Controls whether lists and trees support horizontal scrolling in the workbench. Warning: turning on this setting has a performance implication.")
      },
      [scrollByPageKey]: {
        type: "boolean",
        default: false,
        description: localize(1711, "Controls whether clicks in the scrollbar scroll page by page.")
      },
      [treeIndentKey]: {
        type: "number",
        default: 8,
        minimum: 4,
        maximum: 40,
        description: localize(1712, "Controls tree indentation in pixels.")
      },
      [treeRenderIndentGuidesKey]: {
        type: "string",
        enum: ["none", "onHover", "always"],
        default: "onHover",
        description: localize(1713, "Controls whether the tree should render indent guides.")
      },
      [listSmoothScrolling]: {
        type: "boolean",
        default: false,
        description: localize(1714, "Controls whether lists and trees have smooth scrolling.")
      },
      [mouseWheelScrollSensitivityKey]: {
        type: "number",
        default: 1,
        markdownDescription: localize(1715, "A multiplier to be used on the `deltaX` and `deltaY` of mouse wheel scroll events.")
      },
      [fastScrollSensitivityKey]: {
        type: "number",
        default: 5,
        markdownDescription: localize(1716, "Scrolling speed multiplier when pressing `Alt`.")
      },
      [defaultFindModeSettingKey]: {
        type: "string",
        enum: ["highlight", "filter"],
        enumDescriptions: [
          localize(1717, "Highlight elements when searching. Further up and down navigation will traverse only the highlighted elements."),
          localize(1718, "Filter elements when searching.")
        ],
        default: "highlight",
        description: localize(1719, "Controls the default find mode for lists and trees in the workbench.")
      },
      [keyboardNavigationSettingKey]: {
        type: "string",
        enum: ["simple", "highlight", "filter"],
        enumDescriptions: [
          localize(1720, "Simple keyboard navigation focuses elements which match the keyboard input. Matching is done only on prefixes."),
          localize(1721, "Highlight keyboard navigation highlights elements which match the keyboard input. Further up and down navigation will traverse only the highlighted elements."),
          localize(1722, "Filter keyboard navigation will filter out and hide all the elements which do not match the keyboard input.")
        ],
        default: "highlight",
        description: localize(1723, "Controls the keyboard navigation style for lists and trees in the workbench. Can be simple, highlight and filter."),
        deprecated: true,
        deprecationMessage: localize(1724, "Please use 'workbench.list.defaultFindMode' and	'workbench.list.typeNavigationMode' instead.")
      },
      [defaultFindMatchTypeSettingKey]: {
        type: "string",
        enum: ["fuzzy", "contiguous"],
        enumDescriptions: [
          localize(1725, "Use fuzzy matching when searching."),
          localize(1726, "Use contiguous matching when searching.")
        ],
        default: "fuzzy",
        description: localize(1727, "Controls the type of matching used when searching lists and trees in the workbench.")
      },
      [treeExpandMode]: {
        type: "string",
        enum: ["singleClick", "doubleClick"],
        default: "singleClick",
        description: localize(1728, "Controls how tree folders are expanded when clicking the folder names. Note that some trees and lists might choose to ignore this setting if it is not applicable.")
      },
      [treeStickyScroll]: {
        type: "boolean",
        default: true,
        description: localize(1729, "Controls whether sticky scrolling is enabled in trees.")
      },
      [treeStickyScrollMaxElements]: {
        type: "number",
        minimum: 1,
        default: 7,
        markdownDescription: localize(1730, "Controls the number of sticky elements displayed in the tree when {0} is enabled.", "`#workbench.tree.enableStickyScroll#`")
      },
      [typeNavigationModeSettingKey]: {
        type: "string",
        enum: ["automatic", "trigger"],
        default: "automatic",
        markdownDescription: localize(1731, "Controls how type navigation works in lists and trees in the workbench. When set to `trigger`, type navigation begins once the `list.triggerTypeNavigation` command is run.")
      }
    }
  });
  class OneReference {
    constructor(isProviderFirst, parent, link2, _rangeCallback) {
      this.isProviderFirst = isProviderFirst;
      this.parent = parent;
      this.link = link2;
      this._rangeCallback = _rangeCallback;
      this.id = defaultGenerator.nextId();
    }
    get uri() {
      return this.link.uri;
    }
    get range() {
      return this._range ?? this.link.targetSelectionRange ?? this.link.range;
    }
    set range(value) {
      this._range = value;
      this._rangeCallback(this);
    }
    get ariaMessage() {
      const preview = this.parent.getPreview(this)?.preview(this.range);
      if (!preview) {
        return localize(1087, "in {0} on line {1} at column {2}", basename(this.uri), this.range.startLineNumber, this.range.startColumn);
      } else {
        return localize(1088, "{0} in {1} on line {2} at column {3}", preview.value, basename(this.uri), this.range.startLineNumber, this.range.startColumn);
      }
    }
  }
  class FilePreview {
    constructor(_modelReference) {
      this._modelReference = _modelReference;
    }
    dispose() {
      this._modelReference.dispose();
    }
    preview(range2, n2 = 8) {
      const model = this._modelReference.object.textEditorModel;
      if (!model) {
        return void 0;
      }
      const { startLineNumber, startColumn, endLineNumber, endColumn } = range2;
      const word = model.getWordUntilPosition({ lineNumber: startLineNumber, column: startColumn - n2 });
      const beforeRange = new Range$2(startLineNumber, word.startColumn, startLineNumber, startColumn);
      const afterRange = new Range$2(
        endLineNumber,
        endColumn,
        endLineNumber,
        1073741824
        /* Constants.MAX_SAFE_SMALL_INTEGER */
      );
      const before = model.getValueInRange(beforeRange).replace(/^\s+/, "");
      const inside = model.getValueInRange(range2);
      const after2 = model.getValueInRange(afterRange).replace(/\s+$/, "");
      return {
        value: before + inside + after2,
        highlight: { start: before.length, end: before.length + inside.length }
      };
    }
  }
  class FileReferences {
    constructor(parent, uri) {
      this.parent = parent;
      this.uri = uri;
      this.children = [];
      this._previews = new ResourceMap();
    }
    dispose() {
      dispose(this._previews.values());
      this._previews.clear();
    }
    getPreview(child) {
      return this._previews.get(child.uri);
    }
    get ariaMessage() {
      const len = this.children.length;
      if (len === 1) {
        return localize(1089, "1 symbol in {0}, full path {1}", basename(this.uri), this.uri.fsPath);
      } else {
        return localize(1090, "{0} symbols in {1}, full path {2}", len, basename(this.uri), this.uri.fsPath);
      }
    }
    async resolve(textModelResolverService) {
      if (this._previews.size !== 0) {
        return this;
      }
      for (const child of this.children) {
        if (this._previews.has(child.uri)) {
          continue;
        }
        try {
          const ref = await textModelResolverService.createModelReference(child.uri);
          this._previews.set(child.uri, new FilePreview(ref));
        } catch (err) {
          onUnexpectedError(err);
        }
      }
      return this;
    }
  }
  class ReferencesModel {
    constructor(links, title) {
      this.groups = [];
      this.references = [];
      this._onDidChangeReferenceRange = new Emitter$1();
      this.onDidChangeReferenceRange = this._onDidChangeReferenceRange.event;
      this._links = links;
      this._title = title;
      const [providersFirst] = links;
      links.sort(ReferencesModel._compareReferences);
      let current;
      for (const link2 of links) {
        if (!current || !extUri.isEqual(current.uri, link2.uri, true)) {
          current = new FileReferences(this, link2.uri);
          this.groups.push(current);
        }
        if (current.children.length === 0 || ReferencesModel._compareReferences(link2, current.children[current.children.length - 1]) !== 0) {
          const oneRef = new OneReference(providersFirst === link2, current, link2, (ref) => this._onDidChangeReferenceRange.fire(ref));
          this.references.push(oneRef);
          current.children.push(oneRef);
        }
      }
    }
    dispose() {
      dispose(this.groups);
      this._onDidChangeReferenceRange.dispose();
      this.groups.length = 0;
    }
    clone() {
      return new ReferencesModel(this._links, this._title);
    }
    get title() {
      return this._title;
    }
    get isEmpty() {
      return this.groups.length === 0;
    }
    get ariaMessage() {
      if (this.isEmpty) {
        return localize(1091, "No results found");
      } else if (this.references.length === 1) {
        return localize(1092, "Found 1 symbol in {0}", this.references[0].uri.fsPath);
      } else if (this.groups.length === 1) {
        return localize(1093, "Found {0} symbols in {1}", this.references.length, this.groups[0].uri.fsPath);
      } else {
        return localize(1094, "Found {0} symbols in {1} files", this.references.length, this.groups.length);
      }
    }
    nextOrPreviousReference(reference, next) {
      const { parent } = reference;
      let idx = parent.children.indexOf(reference);
      const childCount = parent.children.length;
      const groupCount = parent.parent.groups.length;
      if (groupCount === 1 || next && idx + 1 < childCount || !next && idx > 0) {
        if (next) {
          idx = (idx + 1) % childCount;
        } else {
          idx = (idx + childCount - 1) % childCount;
        }
        return parent.children[idx];
      }
      idx = parent.parent.groups.indexOf(parent);
      if (next) {
        idx = (idx + 1) % groupCount;
        return parent.parent.groups[idx].children[0];
      } else {
        idx = (idx + groupCount - 1) % groupCount;
        return parent.parent.groups[idx].children[parent.parent.groups[idx].children.length - 1];
      }
    }
    nearestReference(resource, position) {
      const nearest = this.references.map((ref, idx) => {
        return {
          idx,
          prefixLen: commonPrefixLength(ref.uri.toString(), resource.toString()),
          offsetDist: Math.abs(ref.range.startLineNumber - position.lineNumber) * 100 + Math.abs(ref.range.startColumn - position.column)
        };
      }).sort((a, b) => {
        if (a.prefixLen > b.prefixLen) {
          return -1;
        } else if (a.prefixLen < b.prefixLen) {
          return 1;
        } else if (a.offsetDist < b.offsetDist) {
          return -1;
        } else if (a.offsetDist > b.offsetDist) {
          return 1;
        } else {
          return 0;
        }
      })[0];
      if (nearest) {
        return this.references[nearest.idx];
      }
      return void 0;
    }
    referenceAt(resource, position) {
      for (const ref of this.references) {
        if (ref.uri.toString() === resource.toString()) {
          if (Range$2.containsPosition(ref.range, position)) {
            return ref;
          }
        }
      }
      return void 0;
    }
    firstReference() {
      for (const ref of this.references) {
        if (ref.isProviderFirst) {
          return ref;
        }
      }
      return this.references[0];
    }
    static _compareReferences(a, b) {
      return extUri.compare(a.uri, b.uri) || Range$2.compareRangesUsingStarts(a.range, b.range);
    }
  }
  class CountBadge extends Disposable {
    constructor(container, options, styles) {
      super();
      this.options = options;
      this.styles = styles;
      this.count = 0;
      this.hover = this._register(new MutableDisposable());
      this.element = append$2(container, $$l(".monaco-count-badge"));
      this._register(toDisposable(() => container.removeChild(this.element)));
      this.countFormat = this.options.countFormat || "{0}";
      this.titleFormat = this.options.titleFormat || "";
      this.setCount(this.options.count || 0);
      this.updateHover();
    }
    setCount(count) {
      this.count = count;
      this.render();
    }
    setTitleFormat(titleFormat) {
      this.titleFormat = titleFormat;
      this.updateHover();
      this.render();
    }
    updateHover() {
      if (this.titleFormat !== "" && !this.hover.value) {
        this.hover.value = getBaseLayerHoverDelegate().setupDelayedHoverAtMouse(this.element, () => ({ content: format(this.titleFormat, this.count), appearance: { compact: true } }));
      } else if (this.titleFormat === "" && this.hover.value) {
        this.hover.value = void 0;
      }
    }
    render() {
      this.element.textContent = format(this.countFormat, this.count);
      this.element.style.backgroundColor = this.styles.badgeBackground ?? "";
      this.element.style.color = this.styles.badgeForeground ?? "";
      if (this.styles.badgeBorder) {
        this.element.style.border = `1px solid ${this.styles.badgeBorder}`;
      }
    }
  }
  class HighlightedLabel extends Disposable {
    /**
     * Create a new {@link HighlightedLabel}.
     *
     * @param container The parent container to append to.
     */
    constructor(container, options) {
      super();
      this.options = options;
      this.text = "";
      this.title = "";
      this.highlights = [];
      this.didEverRender = false;
      this.domNode = append$2(container, $$l("span.monaco-highlighted-label"));
    }
    /**
     * The label's DOM node.
     */
    get element() {
      return this.domNode;
    }
    /**
     * Set the label and highlights.
     *
     * @param text The label to display.
     * @param highlights The ranges to highlight.
     * @param title An optional title for the hover tooltip.
     * @param escapeNewLines Whether to escape new lines.
     * @returns
     */
    set(text2, highlights = [], title = "", escapeNewLines, supportIcons) {
      if (!text2) {
        text2 = "";
      }
      if (escapeNewLines) {
        text2 = HighlightedLabel.escapeNewLines(text2, highlights);
      }
      if (this.didEverRender && this.text === text2 && this.title === title && equals(this.highlights, highlights)) {
        return;
      }
      this.text = text2;
      this.title = title;
      this.highlights = highlights;
      this.render(supportIcons);
    }
    render(supportIcons) {
      const children = [];
      let pos = 0;
      for (const highlight of this.highlights) {
        if (highlight.end === highlight.start) {
          continue;
        }
        if (pos < highlight.start) {
          const substring2 = this.text.substring(pos, highlight.start);
          if (supportIcons) {
            children.push(...renderLabelWithIcons(substring2));
          } else {
            children.push(substring2);
          }
          pos = highlight.start;
        }
        const substring = this.text.substring(pos, highlight.end);
        const element = $$l("span.highlight", void 0, ...supportIcons ? renderLabelWithIcons(substring) : [substring]);
        if (highlight.extraClasses) {
          element.classList.add(...highlight.extraClasses);
        }
        children.push(element);
        pos = highlight.end;
      }
      if (pos < this.text.length) {
        const substring = this.text.substring(pos);
        if (supportIcons) {
          children.push(...renderLabelWithIcons(substring));
        } else {
          children.push(substring);
        }
      }
      reset(this.domNode, ...children);
      if (!this.customHover && this.title !== "") {
        const hoverDelegate = this.options?.hoverDelegate ?? getDefaultHoverDelegate("mouse");
        this.customHover = this._register(getBaseLayerHoverDelegate().setupManagedHover(hoverDelegate, this.domNode, this.title));
      } else if (this.customHover) {
        this.customHover.update(this.title);
      }
      this.didEverRender = true;
    }
    static escapeNewLines(text2, highlights) {
      let total = 0;
      let extra = 0;
      return text2.replace(/\r\n|\r|\n/g, (match2, offset) => {
        extra = match2 === "\r\n" ? -1 : 0;
        offset += total;
        for (const highlight of highlights) {
          if (highlight.end <= offset) {
            continue;
          }
          if (highlight.start >= offset) {
            highlight.start += extra;
          }
          if (highlight.end >= offset) {
            highlight.end += extra;
          }
        }
        total += extra;
        return "⏎";
      });
    }
  }
  class FastLabelNode {
    constructor(_element) {
      this._element = _element;
    }
    get element() {
      return this._element;
    }
    set textContent(content) {
      if (this.disposed || content === this._textContent) {
        return;
      }
      this._textContent = content;
      this._element.textContent = content;
    }
    set classNames(classNames2) {
      if (this.disposed || equals(classNames2, this._classNames)) {
        return;
      }
      this._classNames = classNames2;
      this._element.classList.value = "";
      this._element.classList.add(...classNames2);
    }
    set empty(empty2) {
      if (this.disposed || empty2 === this._empty) {
        return;
      }
      this._empty = empty2;
      this._element.style.marginLeft = empty2 ? "0" : "";
    }
    dispose() {
      this.disposed = true;
    }
  }
  class IconLabel extends Disposable {
    constructor(container, options) {
      super();
      this.customHovers = /* @__PURE__ */ new Map();
      this.creationOptions = options;
      this.domNode = this._register(new FastLabelNode(append$2(container, $$l(".monaco-icon-label"))));
      this.labelContainer = append$2(this.domNode.element, $$l(".monaco-icon-label-container"));
      this.nameContainer = append$2(this.labelContainer, $$l("span.monaco-icon-name-container"));
      if (options?.supportHighlights || options?.supportIcons) {
        this.nameNode = this._register(new LabelWithHighlights(this.nameContainer, !!options.supportIcons));
      } else {
        this.nameNode = new Label(this.nameContainer);
      }
      this.hoverDelegate = options?.hoverDelegate ?? getDefaultHoverDelegate("mouse");
    }
    get element() {
      return this.domNode.element;
    }
    setLabel(label, description, options) {
      const labelClasses = ["monaco-icon-label"];
      const containerClasses = ["monaco-icon-label-container"];
      let ariaLabel = "";
      if (options) {
        if (options.extraClasses) {
          labelClasses.push(...options.extraClasses);
        }
        if (options.bold) {
          labelClasses.push("bold");
        }
        if (options.italic) {
          labelClasses.push("italic");
        }
        if (options.strikethrough) {
          labelClasses.push("strikethrough");
        }
        if (options.disabledCommand) {
          containerClasses.push("disabled");
        }
        if (options.title) {
          if (typeof options.title === "string") {
            ariaLabel += options.title;
          } else {
            ariaLabel += label;
          }
        }
      }
      const existingIconNode = this.domNode.element.querySelector(".monaco-icon-label-iconpath");
      if (options?.iconPath) {
        let iconNode;
        if (!existingIconNode || !isHTMLElement(existingIconNode)) {
          iconNode = $$l(".monaco-icon-label-iconpath");
          this.domNode.element.prepend(iconNode);
        } else {
          iconNode = existingIconNode;
        }
        if (ThemeIcon.isThemeIcon(options.iconPath)) {
          const iconClass = ThemeIcon.asClassName(options.iconPath);
          iconNode.className = `monaco-icon-label-iconpath ${iconClass}`;
          iconNode.style.backgroundImage = "";
        } else {
          iconNode.style.backgroundImage = asCSSUrl(options?.iconPath);
        }
        iconNode.style.backgroundRepeat = "no-repeat";
        iconNode.style.backgroundPosition = "center";
        iconNode.style.backgroundSize = "contain";
      } else if (existingIconNode) {
        existingIconNode.remove();
      }
      this.domNode.classNames = labelClasses;
      this.domNode.element.setAttribute("aria-label", ariaLabel);
      this.labelContainer.classList.value = "";
      this.labelContainer.classList.add(...containerClasses);
      this.setupHover(options?.descriptionTitle ? this.labelContainer : this.element, options?.title);
      this.nameNode.setLabel(label, options);
      if (description || this.descriptionNode) {
        const descriptionNode = this.getOrCreateDescriptionNode();
        if (descriptionNode instanceof HighlightedLabel) {
          const supportIcons = options?.supportIcons ?? this.creationOptions?.supportIcons;
          descriptionNode.set(description || "", options ? options.descriptionMatches : void 0, void 0, options?.labelEscapeNewLines, supportIcons);
          this.setupHover(descriptionNode.element, options?.descriptionTitle);
        } else {
          descriptionNode.textContent = description && options?.labelEscapeNewLines ? HighlightedLabel.escapeNewLines(description, []) : description || "";
          this.setupHover(descriptionNode.element, options?.descriptionTitle || "");
          descriptionNode.empty = !description;
        }
      }
      if (options?.suffix || this.suffixNode) {
        const suffixNode = this.getOrCreateSuffixNode();
        suffixNode.textContent = options?.suffix ?? "";
      }
    }
    setupHover(htmlElement, tooltip) {
      const previousCustomHover = this.customHovers.get(htmlElement);
      if (previousCustomHover) {
        previousCustomHover.dispose();
        this.customHovers.delete(htmlElement);
      }
      if (!tooltip) {
        htmlElement.removeAttribute("title");
        return;
      }
      let hoverTarget = htmlElement;
      if (this.creationOptions?.hoverTargetOverride) {
        if (!isAncestor$1(htmlElement, this.creationOptions.hoverTargetOverride)) {
          throw new Error("hoverTargetOverrride must be an ancestor of the htmlElement");
        }
        hoverTarget = this.creationOptions.hoverTargetOverride;
      }
      const hoverDisposable = getBaseLayerHoverDelegate().setupManagedHover(this.hoverDelegate, hoverTarget, tooltip);
      if (hoverDisposable) {
        this.customHovers.set(htmlElement, hoverDisposable);
      }
    }
    dispose() {
      super.dispose();
      for (const disposable of this.customHovers.values()) {
        disposable.dispose();
      }
      this.customHovers.clear();
    }
    getOrCreateSuffixNode() {
      if (!this.suffixNode) {
        const suffixContainer = this._register(new FastLabelNode(after(this.nameContainer, $$l("span.monaco-icon-suffix-container"))));
        this.suffixNode = this._register(new FastLabelNode(append$2(suffixContainer.element, $$l("span.label-suffix"))));
      }
      return this.suffixNode;
    }
    getOrCreateDescriptionNode() {
      if (!this.descriptionNode) {
        const descriptionContainer = this._register(new FastLabelNode(append$2(this.labelContainer, $$l("span.monaco-icon-description-container"))));
        if (this.creationOptions?.supportDescriptionHighlights) {
          this.descriptionNode = this._register(new HighlightedLabel(append$2(descriptionContainer.element, $$l("span.label-description"))));
        } else {
          this.descriptionNode = this._register(new FastLabelNode(append$2(descriptionContainer.element, $$l("span.label-description"))));
        }
      }
      return this.descriptionNode;
    }
  }
  class Label {
    constructor(container) {
      this.container = container;
      this.label = void 0;
      this.singleLabel = void 0;
    }
    setLabel(label, options) {
      if (this.label === label && equals(this.options, options)) {
        return;
      }
      this.label = label;
      this.options = options;
      if (typeof label === "string") {
        if (!this.singleLabel) {
          this.container.textContent = "";
          this.container.classList.remove("multiple");
          this.singleLabel = append$2(this.container, $$l("a.label-name", { id: options?.domId }));
        }
        this.singleLabel.textContent = label;
      } else {
        this.container.textContent = "";
        this.container.classList.add("multiple");
        this.singleLabel = void 0;
        for (let i2 = 0; i2 < label.length; i2++) {
          const l = label[i2];
          const id = options?.domId && `${options?.domId}_${i2}`;
          append$2(this.container, $$l("a.label-name", { id, "data-icon-label-count": label.length, "data-icon-label-index": i2, "role": "treeitem" }, l));
          if (i2 < label.length - 1) {
            append$2(this.container, $$l("span.label-separator", void 0, options?.separator || "/"));
          }
        }
      }
    }
  }
  function splitMatches(labels, separator2, matches) {
    if (!matches) {
      return void 0;
    }
    let labelStart = 0;
    return labels.map((label) => {
      const labelRange = { start: labelStart, end: labelStart + label.length };
      const result = matches.map((match2) => Range$1.intersect(labelRange, match2)).filter((range2) => !Range$1.isEmpty(range2)).map(({ start, end }) => ({ start: start - labelStart, end: end - labelStart }));
      labelStart = labelRange.end + separator2.length;
      return result;
    });
  }
  class LabelWithHighlights extends Disposable {
    constructor(container, supportIcons) {
      super();
      this.container = container;
      this.supportIcons = supportIcons;
      this.label = void 0;
      this.singleLabel = void 0;
    }
    setLabel(label, options) {
      if (this.label === label && equals(this.options, options)) {
        return;
      }
      this.label = label;
      this.options = options;
      const supportIcons = options?.supportIcons ?? this.supportIcons;
      if (typeof label === "string") {
        if (!this.singleLabel) {
          this.container.textContent = "";
          this.container.classList.remove("multiple");
          this.singleLabel = this._register(new HighlightedLabel(append$2(this.container, $$l("a.label-name", { id: options?.domId }))));
        }
        this.singleLabel.set(label, options?.matches, void 0, options?.labelEscapeNewLines, supportIcons);
      } else {
        this.container.textContent = "";
        this.container.classList.add("multiple");
        this.singleLabel = void 0;
        const separator2 = options?.separator || "/";
        const matches = splitMatches(label, separator2, options?.matches);
        for (let i2 = 0; i2 < label.length; i2++) {
          const l = label[i2];
          const m = matches ? matches[i2] : void 0;
          const id = options?.domId && `${options?.domId}_${i2}`;
          const name = $$l("a.label-name", { id, "data-icon-label-count": label.length, "data-icon-label-index": i2, "role": "treeitem" });
          const highlightedLabel = this._register(new HighlightedLabel(append$2(this.container, name)));
          highlightedLabel.set(l, m, void 0, options?.labelEscapeNewLines, supportIcons);
          if (i2 < label.length - 1) {
            append$2(name, $$l("span.label-separator", void 0, separator2));
          }
        }
      }
    }
  }
  const ILabelService = createDecorator("labelService");
  var __decorate$20 = 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$1$ = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  var FileReferencesRenderer_1;
  let DataSource = class DataSource {
    constructor(_resolverService) {
      this._resolverService = _resolverService;
    }
    hasChildren(element) {
      if (element instanceof ReferencesModel) {
        return true;
      }
      if (element instanceof FileReferences) {
        return true;
      }
      return false;
    }
    getChildren(element) {
      if (element instanceof ReferencesModel) {
        return element.groups;
      }
      if (element instanceof FileReferences) {
        return element.resolve(this._resolverService).then((val) => {
          return val.children;
        });
      }
      throw new Error("bad tree");
    }
  };
  DataSource = __decorate$20([
    __param$1$(0, ITextModelService)
  ], DataSource);
  class Delegate {
    getHeight() {
      return 23;
    }
    getTemplateId(element) {
      if (element instanceof FileReferences) {
        return FileReferencesRenderer.id;
      } else {
        return OneReferenceRenderer.id;
      }
    }
  }
  let StringRepresentationProvider = class StringRepresentationProvider {
    constructor(_keybindingService) {
      this._keybindingService = _keybindingService;
    }
    getKeyboardNavigationLabel(element) {
      if (element instanceof OneReference) {
        const parts = element.parent.getPreview(element)?.preview(element.range);
        if (parts) {
          return parts.value;
        }
      }
      return basename(element.uri);
    }
  };
  StringRepresentationProvider = __decorate$20([
    __param$1$(0, IKeybindingService)
  ], StringRepresentationProvider);
  class IdentityProvider {
    getId(element) {
      return element instanceof OneReference ? element.id : element.uri;
    }
  }
  let FileReferencesTemplate = class FileReferencesTemplate extends Disposable {
    constructor(container, _labelService) {
      super();
      this._labelService = _labelService;
      const parent = document.createElement("div");
      parent.classList.add("reference-file");
      this.file = this._register(new IconLabel(parent, { supportHighlights: true }));
      this.badge = this._register(new CountBadge(append$2(parent, $$l(".count")), {}, defaultCountBadgeStyles));
      container.appendChild(parent);
    }
    set(element, matches) {
      const parent = dirname(element.uri);
      this.file.setLabel(this._labelService.getUriBasenameLabel(element.uri), this._labelService.getUriLabel(parent, { relative: true }), { title: this._labelService.getUriLabel(element.uri), matches });
      const len = element.children.length;
      this.badge.setCount(len);
      if (len > 1) {
        this.badge.setTitleFormat(localize(1081, "{0} references", len));
      } else {
        this.badge.setTitleFormat(localize(1082, "{0} reference", len));
      }
    }
  };
  FileReferencesTemplate = __decorate$20([
    __param$1$(1, ILabelService)
  ], FileReferencesTemplate);
  let FileReferencesRenderer = (_B = class {
    constructor(_instantiationService) {
      this._instantiationService = _instantiationService;
      this.templateId = FileReferencesRenderer_1.id;
    }
    renderTemplate(container) {
      return this._instantiationService.createInstance(FileReferencesTemplate, container);
    }
    renderElement(node, index, template) {
      template.set(node.element, createMatches(node.filterData));
    }
    disposeTemplate(templateData) {
      templateData.dispose();
    }
  }, FileReferencesRenderer_1 = _B, _B.id = "FileReferencesRenderer", _B);
  FileReferencesRenderer = FileReferencesRenderer_1 = __decorate$20([
    __param$1$(0, IInstantiationService)
  ], FileReferencesRenderer);
  class OneReferenceTemplate extends Disposable {
    constructor(container) {
      super();
      this.label = this._register(new HighlightedLabel(container));
    }
    set(element, score2) {
      const preview = element.parent.getPreview(element)?.preview(element.range);
      if (!preview || !preview.value) {
        this.label.set(`${basename(element.uri)}:${element.range.startLineNumber + 1}:${element.range.startColumn + 1}`);
      } else {
        const { value, highlight } = preview;
        if (score2 && !FuzzyScore.isDefault(score2)) {
          this.label.element.classList.toggle("referenceMatch", false);
          this.label.set(value, createMatches(score2));
        } else {
          this.label.element.classList.toggle("referenceMatch", true);
          this.label.set(value, [highlight]);
        }
      }
    }
  }
  const _OneReferenceRenderer = class _OneReferenceRenderer {
    constructor() {
      this.templateId = _OneReferenceRenderer.id;
    }
    renderTemplate(container) {
      return new OneReferenceTemplate(container);
    }
    renderElement(node, index, templateData) {
      templateData.set(node.element, node.filterData);
    }
    disposeTemplate(templateData) {
      templateData.dispose();
    }
  };
  _OneReferenceRenderer.id = "OneReferenceRenderer";
  let OneReferenceRenderer = _OneReferenceRenderer;
  class AccessibilityProvider {
    getWidgetAriaLabel() {
      return localize(1083, "References");
    }
    getAriaLabel(element) {
      return element.ariaMessage;
    }
  }
  var __decorate$1$ = 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$1_ = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  const _DecorationsManager = class _DecorationsManager {
    constructor(_editor, _model) {
      this._editor = _editor;
      this._model = _model;
      this._decorations = /* @__PURE__ */ new Map();
      this._decorationIgnoreSet = /* @__PURE__ */ new Set();
      this._callOnDispose = new DisposableStore();
      this._callOnModelChange = new DisposableStore();
      this._callOnDispose.add(this._editor.onDidChangeModel(() => this._onModelChanged()));
      this._onModelChanged();
    }
    dispose() {
      this._callOnModelChange.dispose();
      this._callOnDispose.dispose();
      this.removeDecorations();
    }
    _onModelChanged() {
      this._callOnModelChange.clear();
      const model = this._editor.getModel();
      if (!model) {
        return;
      }
      for (const ref of this._model.references) {
        if (ref.uri.toString() === model.uri.toString()) {
          this._addDecorations(ref.parent);
          return;
        }
      }
    }
    _addDecorations(reference) {
      if (!this._editor.hasModel()) {
        return;
      }
      this._callOnModelChange.add(this._editor.getModel().onDidChangeDecorations(() => this._onDecorationChanged()));
      const newDecorations = [];
      const newDecorationsActualIndex = [];
      for (let i2 = 0, len = reference.children.length; i2 < len; i2++) {
        const oneReference = reference.children[i2];
        if (this._decorationIgnoreSet.has(oneReference.id)) {
          continue;
        }
        if (oneReference.uri.toString() !== this._editor.getModel().uri.toString()) {
          continue;
        }
        newDecorations.push({
          range: oneReference.range,
          options: _DecorationsManager.DecorationOptions
        });
        newDecorationsActualIndex.push(i2);
      }
      this._editor.changeDecorations((changeAccessor) => {
        const decorations = changeAccessor.deltaDecorations([], newDecorations);
        for (let i2 = 0; i2 < decorations.length; i2++) {
          this._decorations.set(decorations[i2], reference.children[newDecorationsActualIndex[i2]]);
        }
      });
    }
    _onDecorationChanged() {
      const toRemove = [];
      const model = this._editor.getModel();
      if (!model) {
        return;
      }
      for (const [decorationId, reference] of this._decorations) {
        const newRange = model.getDecorationRange(decorationId);
        if (!newRange) {
          continue;
        }
        let ignore = false;
        if (Range$2.equalsRange(newRange, reference.range)) {
          continue;
        }
        if (Range$2.spansMultipleLines(newRange)) {
          ignore = true;
        } else {
          const lineLength = reference.range.endColumn - reference.range.startColumn;
          const newLineLength = newRange.endColumn - newRange.startColumn;
          if (lineLength !== newLineLength) {
            ignore = true;
          }
        }
        if (ignore) {
          this._decorationIgnoreSet.add(reference.id);
          toRemove.push(decorationId);
        } else {
          reference.range = newRange;
        }
      }
      for (let i2 = 0, len = toRemove.length; i2 < len; i2++) {
        this._decorations.delete(toRemove[i2]);
      }
      this._editor.removeDecorations(toRemove);
    }
    removeDecorations() {
      this._editor.removeDecorations([...this._decorations.keys()]);
      this._decorations.clear();
    }
  };
  _DecorationsManager.DecorationOptions = ModelDecorationOptions.register({
    description: "reference-decoration",
    stickiness: 1,
    className: "reference-decoration"
  });
  let DecorationsManager = _DecorationsManager;
  class LayoutData {
    constructor() {
      this.ratio = 0.7;
      this.heightInLines = 18;
    }
    static fromJSON(raw) {
      let ratio;
      let heightInLines;
      try {
        const data = JSON.parse(raw);
        ratio = data.ratio;
        heightInLines = data.heightInLines;
      } catch {
      }
      return {
        ratio: ratio || 0.7,
        heightInLines: heightInLines || 18
      };
    }
  }
  class ReferencesTree extends WorkbenchAsyncDataTree {
  }
  let ReferencesDragAndDrop = class ReferencesDragAndDrop {
    constructor(labelService) {
      this.labelService = labelService;
      this.disposables = new DisposableStore();
    }
    getDragURI(element) {
      if (element instanceof FileReferences) {
        return element.uri.toString();
      } else if (element instanceof OneReference) {
        return withSelection(element.uri, element.range).toString();
      }
      return null;
    }
    getDragLabel(elements) {
      if (elements.length === 0) {
        return void 0;
      }
      const labels = elements.map((e) => this.labelService.getUriBasenameLabel(e.uri));
      return labels.join(", ");
    }
    onDragStart(data, originalEvent) {
      if (!originalEvent.dataTransfer) {
        return;
      }
      const elements = data.elements;
      const resources = elements.map((e) => this.getDragURI(e)).filter(Boolean);
      if (resources.length) {
        originalEvent.dataTransfer.setData(DataTransfers.RESOURCES, JSON.stringify(resources));
        originalEvent.dataTransfer.setData(DataTransfers.TEXT, resources.join("\n"));
      }
    }
    onDragOver() {
      return false;
    }
    drop() {
    }
    dispose() {
      this.disposables.dispose();
    }
  };
  ReferencesDragAndDrop = __decorate$1$([
    __param$1_(0, ILabelService)
  ], ReferencesDragAndDrop);
  let ReferenceWidget = class ReferenceWidget extends PeekViewWidget {
    constructor(editor2, _defaultTreeKeyboardSupport, layoutData, themeService, _textModelResolverService, _instantiationService, _peekViewService, _uriLabel, _keybindingService) {
      super(editor2, { showFrame: false, showArrow: true, isResizeable: true, isAccessible: true, supportOnTitleClick: true }, _instantiationService);
      this._defaultTreeKeyboardSupport = _defaultTreeKeyboardSupport;
      this.layoutData = layoutData;
      this._textModelResolverService = _textModelResolverService;
      this._instantiationService = _instantiationService;
      this._peekViewService = _peekViewService;
      this._uriLabel = _uriLabel;
      this._keybindingService = _keybindingService;
      this._disposeOnNewModel = new DisposableStore();
      this._callOnDispose = new DisposableStore();
      this._onDidSelectReference = new Emitter$1();
      this.onDidSelectReference = this._onDidSelectReference.event;
      this._dim = new Dimension(0, 0);
      this._isClosing = false;
      this._applyTheme(themeService.getColorTheme());
      this._callOnDispose.add(themeService.onDidColorThemeChange(this._applyTheme.bind(this)));
      this._peekViewService.addExclusiveWidget(editor2, this);
      this.create();
    }
    get isClosing() {
      return this._isClosing;
    }
    dispose() {
      this._isClosing = true;
      this.setModel(void 0);
      this._callOnDispose.dispose();
      this._disposeOnNewModel.dispose();
      dispose(this._preview);
      dispose(this._previewNotAvailableMessage);
      dispose(this._tree);
      dispose(this._previewModelReference);
      this._splitView.dispose();
      super.dispose();
    }
    _applyTheme(theme) {
      const borderColor = theme.getColor(peekViewBorder) || Color.transparent;
      this.style({
        arrowColor: borderColor,
        frameColor: borderColor,
        headerBackgroundColor: theme.getColor(peekViewTitleBackground) || Color.transparent,
        primaryHeadingColor: theme.getColor(peekViewTitleForeground),
        secondaryHeadingColor: theme.getColor(peekViewTitleInfoForeground)
      });
    }
    show(where) {
      super.show(where, this.layoutData.heightInLines || 18);
    }
    focusOnReferenceTree() {
      this._tree.domFocus();
    }
    focusOnPreviewEditor() {
      this._preview.focus();
    }
    isPreviewEditorFocused() {
      return this._preview.hasTextFocus();
    }
    _onTitleClick(e) {
      if (this._preview && this._preview.getModel()) {
        this._onDidSelectReference.fire({
          element: this._getFocusedReference(),
          kind: e.ctrlKey || e.metaKey || e.altKey ? "side" : "open",
          source: "title"
        });
      }
    }
    _fillBody(containerElement) {
      this.setCssClass("reference-zone-widget");
      this._messageContainer = append$2(containerElement, $$l("div.messages"));
      hide(this._messageContainer);
      this._splitView = new SplitView(containerElement, {
        orientation: 1
        /* Orientation.HORIZONTAL */
      });
      this._previewContainer = append$2(containerElement, $$l("div.preview.inline"));
      const options = {
        scrollBeyondLastLine: false,
        scrollbar: {
          verticalScrollbarSize: 14,
          horizontal: "auto",
          useShadows: true,
          verticalHasArrows: false,
          horizontalHasArrows: false,
          alwaysConsumeMouseWheel: true
        },
        overviewRulerLanes: 2,
        fixedOverflowWidgets: true,
        minimap: {
          enabled: false
        }
      };
      this._preview = this._instantiationService.createInstance(EmbeddedCodeEditorWidget, this._previewContainer, options, {}, this.editor);
      hide(this._previewContainer);
      this._previewNotAvailableMessage = this._instantiationService.createInstance(TextModel, localize(1084, "no preview available"), PLAINTEXT_LANGUAGE_ID, TextModel.DEFAULT_CREATION_OPTIONS, null);
      this._treeContainer = append$2(containerElement, $$l("div.ref-tree.inline"));
      const treeOptions = {
        keyboardSupport: this._defaultTreeKeyboardSupport,
        accessibilityProvider: new AccessibilityProvider(),
        keyboardNavigationLabelProvider: this._instantiationService.createInstance(StringRepresentationProvider),
        identityProvider: new IdentityProvider(),
        openOnSingleClick: true,
        selectionNavigation: true,
        overrideStyles: {
          listBackground: peekViewResultsBackground
        },
        dnd: this._instantiationService.createInstance(ReferencesDragAndDrop)
      };
      if (this._defaultTreeKeyboardSupport) {
        this._callOnDispose.add(addStandardDisposableListener(this._treeContainer, "keydown", (e) => {
          if (e.equals(
            9
            /* KeyCode.Escape */
          )) {
            this._keybindingService.dispatchEvent(e, e.target);
            e.stopPropagation();
          }
        }, true));
      }
      this._tree = this._instantiationService.createInstance(ReferencesTree, "ReferencesWidget", this._treeContainer, new Delegate(), [
        this._instantiationService.createInstance(FileReferencesRenderer),
        this._instantiationService.createInstance(OneReferenceRenderer)
      ], this._instantiationService.createInstance(DataSource), treeOptions);
      this._splitView.addView({
        onDidChange: Event.None,
        element: this._previewContainer,
        minimumSize: 200,
        maximumSize: Number.MAX_VALUE,
        layout: (width2) => {
          this._preview.layout({ height: this._dim.height, width: width2 });
        }
      }, Sizing.Distribute);
      this._splitView.addView({
        onDidChange: Event.None,
        element: this._treeContainer,
        minimumSize: 100,
        maximumSize: Number.MAX_VALUE,
        layout: (width2) => {
          this._treeContainer.style.height = `${this._dim.height}px`;
          this._treeContainer.style.width = `${width2}px`;
          this._tree.layout(this._dim.height, width2);
        }
      }, Sizing.Distribute);
      this._disposables.add(this._splitView.onDidSashChange(() => {
        if (this._dim.width) {
          this.layoutData.ratio = this._splitView.getViewSize(0) / this._dim.width;
        }
      }, void 0));
      const onEvent = (element, kind) => {
        if (element instanceof OneReference) {
          if (kind === "show") {
            this._revealReference(element, false);
          }
          this._onDidSelectReference.fire({ element, kind, source: "tree" });
        }
      };
      this._disposables.add(this._tree.onDidOpen((e) => {
        if (e.sideBySide) {
          onEvent(e.element, "side");
        } else if (e.editorOptions.pinned) {
          onEvent(e.element, "goto");
        } else {
          onEvent(e.element, "show");
        }
      }));
      hide(this._treeContainer);
    }
    _onWidth(width2) {
      if (this._dim) {
        this._doLayoutBody(this._dim.height, width2);
      }
    }
    _doLayoutBody(heightInPixel, widthInPixel) {
      super._doLayoutBody(heightInPixel, widthInPixel);
      this._dim = new Dimension(widthInPixel, heightInPixel);
      this.layoutData.heightInLines = this._viewZone ? this._viewZone.heightInLines : this.layoutData.heightInLines;
      this._splitView.layout(widthInPixel);
      this._splitView.resizeView(0, widthInPixel * this.layoutData.ratio);
    }
    setSelection(selection) {
      return this._revealReference(selection, true).then(() => {
        if (!this._model) {
          return;
        }
        this._tree.setSelection([selection]);
        this._tree.setFocus([selection]);
      });
    }
    setModel(newModel) {
      this._disposeOnNewModel.clear();
      this._model = newModel;
      if (this._model) {
        return this._onNewModel();
      }
      return Promise.resolve();
    }
    _onNewModel() {
      if (!this._model) {
        return Promise.resolve(void 0);
      }
      if (this._model.isEmpty) {
        this.setTitle("");
        this._messageContainer.innerText = localize(1085, "No results");
        show(this._messageContainer);
        return Promise.resolve(void 0);
      }
      hide(this._messageContainer);
      this._decorationsManager = new DecorationsManager(this._preview, this._model);
      this._disposeOnNewModel.add(this._decorationsManager);
      this._disposeOnNewModel.add(this._model.onDidChangeReferenceRange((reference) => this._tree.rerender(reference)));
      this._disposeOnNewModel.add(this._preview.onMouseDown((e) => {
        const { event, target } = e;
        if (event.detail !== 2) {
          return;
        }
        const element = this._getFocusedReference();
        if (!element) {
          return;
        }
        this._onDidSelectReference.fire({
          element: { uri: element.uri, range: target.range },
          kind: event.ctrlKey || event.metaKey || event.altKey ? "side" : "open",
          source: "editor"
        });
      }));
      this.container.classList.add("results-loaded");
      show(this._treeContainer);
      show(this._previewContainer);
      this._splitView.layout(this._dim.width);
      this.focusOnReferenceTree();
      return this._tree.setInput(this._model.groups.length === 1 ? this._model.groups[0] : this._model);
    }
    _getFocusedReference() {
      const [element] = this._tree.getFocus();
      if (element instanceof OneReference) {
        return element;
      } else if (element instanceof FileReferences) {
        if (element.children.length > 0) {
          return element.children[0];
        }
      }
      return void 0;
    }
    async revealReference(reference) {
      await this._revealReference(reference, false);
      this._onDidSelectReference.fire({ element: reference, kind: "goto", source: "tree" });
    }
    async _revealReference(reference, revealParent) {
      if (this._revealedReference === reference) {
        return;
      }
      this._revealedReference = reference;
      if (reference.uri.scheme !== Schemas.inMemory) {
        this.setTitle(basenameOrAuthority(reference.uri), this._uriLabel.getUriLabel(dirname(reference.uri)));
      } else {
        this.setTitle(localize(1086, "References"));
      }
      const promise = this._textModelResolverService.createModelReference(reference.uri);
      if (this._tree.getInput() === reference.parent) {
        this._tree.reveal(reference);
      } else {
        if (revealParent) {
          this._tree.reveal(reference.parent);
        }
        await this._tree.expand(reference.parent);
        this._tree.reveal(reference);
      }
      const ref = await promise;
      if (!this._model) {
        ref.dispose();
        return;
      }
      dispose(this._previewModelReference);
      const model = ref.object;
      if (model) {
        const scrollType = this._preview.getModel() === model.textEditorModel ? 0 : 1;
        const sel = Range$2.lift(reference.range).collapseToStart();
        this._previewModelReference = ref;
        this._preview.setModel(model.textEditorModel);
        this._preview.setSelection(sel);
        this._preview.revealRangeInCenter(sel, scrollType);
      } else {
        this._preview.setModel(this._previewNotAvailableMessage);
        ref.dispose();
      }
    }
  };
  ReferenceWidget = __decorate$1$([
    __param$1_(3, IThemeService),
    __param$1_(4, ITextModelService),
    __param$1_(5, IInstantiationService),
    __param$1_(6, IPeekViewService),
    __param$1_(7, ILabelService),
    __param$1_(8, IKeybindingService)
  ], ReferenceWidget);
  var __decorate$1_ = 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$1Z = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  var ReferencesController_1;
  const ctxReferenceSearchVisible = new RawContextKey("referenceSearchVisible", false, localize(1078, "Whether reference peek is visible, like 'Peek References' or 'Peek Definition'"));
  let ReferencesController = (_C = class {
    static get(editor2) {
      return editor2.getContribution(ReferencesController_1.ID);
    }
    constructor(_defaultTreeKeyboardSupport, _editor, contextKeyService, _editorService, _notificationService, _instantiationService, _storageService, _configurationService) {
      this._defaultTreeKeyboardSupport = _defaultTreeKeyboardSupport;
      this._editor = _editor;
      this._editorService = _editorService;
      this._notificationService = _notificationService;
      this._instantiationService = _instantiationService;
      this._storageService = _storageService;
      this._configurationService = _configurationService;
      this._disposables = new DisposableStore();
      this._requestIdPool = 0;
      this._ignoreModelChangeEvent = false;
      this._referenceSearchVisible = ctxReferenceSearchVisible.bindTo(contextKeyService);
    }
    dispose() {
      this._referenceSearchVisible.reset();
      this._disposables.dispose();
      this._widget?.dispose();
      this._model?.dispose();
      this._widget = void 0;
      this._model = void 0;
    }
    toggleWidget(range2, modelPromise, peekMode) {
      let widgetPosition;
      if (this._widget) {
        widgetPosition = this._widget.position;
      }
      this.closeWidget();
      if (!!widgetPosition && range2.containsPosition(widgetPosition)) {
        return;
      }
      this._peekMode = peekMode;
      this._referenceSearchVisible.set(true);
      this._disposables.add(this._editor.onDidChangeModelLanguage(() => {
        this.closeWidget();
      }));
      this._disposables.add(this._editor.onDidChangeModel(() => {
        if (!this._ignoreModelChangeEvent) {
          this.closeWidget();
        }
      }));
      const storageKey = "peekViewLayout";
      const data = LayoutData.fromJSON(this._storageService.get(storageKey, 0, "{}"));
      this._widget = this._instantiationService.createInstance(ReferenceWidget, this._editor, this._defaultTreeKeyboardSupport, data);
      this._widget.setTitle(localize(1079, "Loading..."));
      this._widget.show(range2);
      this._disposables.add(this._widget.onDidClose(() => {
        modelPromise.cancel();
        if (this._widget) {
          this._storageService.store(
            storageKey,
            JSON.stringify(this._widget.layoutData),
            0,
            1
            /* StorageTarget.MACHINE */
          );
          if (!this._widget.isClosing) {
            this.closeWidget();
          }
          this._widget = void 0;
        } else {
          this.closeWidget();
        }
      }));
      this._disposables.add(this._widget.onDidSelectReference((event) => {
        const { element, kind } = event;
        if (!element) {
          return;
        }
        switch (kind) {
          case "open":
            if (event.source !== "editor" || !this._configurationService.getValue("editor.stablePeek")) {
              this.openReference(element, false, false);
            }
            break;
          case "side":
            this.openReference(element, true, false);
            break;
          case "goto":
            if (peekMode) {
              this._gotoReference(element, true);
            } else {
              this.openReference(element, false, true);
            }
            break;
        }
      }));
      const requestId = ++this._requestIdPool;
      modelPromise.then((model) => {
        if (requestId !== this._requestIdPool || !this._widget) {
          model.dispose();
          return void 0;
        }
        this._model?.dispose();
        this._model = model;
        return this._widget.setModel(this._model).then(() => {
          if (this._widget && this._model && this._editor.hasModel()) {
            if (!this._model.isEmpty) {
              this._widget.setMetaTitle(localize(1080, "{0} ({1})", this._model.title, this._model.references.length));
            } else {
              this._widget.setMetaTitle("");
            }
            const uri = this._editor.getModel().uri;
            const pos = new Position$1(range2.startLineNumber, range2.startColumn);
            const selection = this._model.nearestReference(uri, pos);
            if (selection) {
              return this._widget.setSelection(selection).then(() => {
                if (this._widget && this._editor.getOption(
                  99
                  /* EditorOption.peekWidgetDefaultFocus */
                ) === "editor") {
                  this._widget.focusOnPreviewEditor();
                }
              });
            }
          }
          return void 0;
        });
      }, (error) => {
        this._notificationService.error(error);
      });
    }
    changeFocusBetweenPreviewAndReferences() {
      if (!this._widget) {
        return;
      }
      if (this._widget.isPreviewEditorFocused()) {
        this._widget.focusOnReferenceTree();
      } else {
        this._widget.focusOnPreviewEditor();
      }
    }
    async goToNextOrPreviousReference(fwd) {
      if (!this._editor.hasModel() || !this._model || !this._widget) {
        return;
      }
      const currentPosition = this._widget.position;
      if (!currentPosition) {
        return;
      }
      const source = this._model.nearestReference(this._editor.getModel().uri, currentPosition);
      if (!source) {
        return;
      }
      const target = this._model.nextOrPreviousReference(source, fwd);
      const editorFocus = this._editor.hasTextFocus();
      const previewEditorFocus = this._widget.isPreviewEditorFocused();
      await this._widget.setSelection(target);
      await this._gotoReference(target, false);
      if (editorFocus) {
        this._editor.focus();
      } else if (this._widget && previewEditorFocus) {
        this._widget.focusOnPreviewEditor();
      }
    }
    async revealReference(reference) {
      if (!this._editor.hasModel() || !this._model || !this._widget) {
        return;
      }
      await this._widget.revealReference(reference);
    }
    closeWidget(focusEditor = true) {
      this._widget?.dispose();
      this._model?.dispose();
      this._referenceSearchVisible.reset();
      this._disposables.clear();
      this._widget = void 0;
      this._model = void 0;
      if (focusEditor) {
        this._editor.focus();
      }
      this._requestIdPool += 1;
    }
    _gotoReference(ref, pinned) {
      this._widget?.hide();
      this._ignoreModelChangeEvent = true;
      const range2 = Range$2.lift(ref.range).collapseToStart();
      return this._editorService.openCodeEditor({
        resource: ref.uri,
        options: { selection: range2, selectionSource: "code.jump", pinned }
      }, this._editor).then((openedEditor) => {
        this._ignoreModelChangeEvent = false;
        if (!openedEditor || !this._widget) {
          this.closeWidget();
          return;
        }
        if (this._editor === openedEditor) {
          this._widget.show(range2);
          this._widget.focusOnReferenceTree();
        } else {
          const other = ReferencesController_1.get(openedEditor);
          const model = this._model.clone();
          this.closeWidget();
          openedEditor.focus();
          other?.toggleWidget(range2, createCancelablePromise((_) => Promise.resolve(model)), this._peekMode ?? false);
        }
      }, (err) => {
        this._ignoreModelChangeEvent = false;
        onUnexpectedError(err);
      });
    }
    openReference(ref, sideBySide, pinned) {
      if (!sideBySide) {
        this.closeWidget();
      }
      const { uri, range: range2 } = ref;
      this._editorService.openCodeEditor({
        resource: uri,
        options: { selection: range2, selectionSource: "code.jump", pinned }
      }, this._editor, sideBySide);
    }
  }, ReferencesController_1 = _C, _C.ID = "editor.contrib.referencesController", _C);
  ReferencesController = ReferencesController_1 = __decorate$1_([
    __param$1Z(2, IContextKeyService),
    __param$1Z(3, ICodeEditorService),
    __param$1Z(4, INotificationService),
    __param$1Z(5, IInstantiationService),
    __param$1Z(6, IStorageService),
    __param$1Z(7, IConfigurationService)
  ], ReferencesController);
  function withController(accessor, fn) {
    const outerEditor = getOuterEditor(accessor);
    if (!outerEditor) {
      return;
    }
    const controller = ReferencesController.get(outerEditor);
    if (controller) {
      fn(controller);
    }
  }
  KeybindingsRegistry.registerCommandAndKeybindingRule({
    id: "togglePeekWidgetFocus",
    weight: 100,
    primary: KeyChord(
      2048 | 41,
      60
      /* KeyCode.F2 */
    ),
    when: ContextKeyExpr.or(ctxReferenceSearchVisible, PeekContext.inPeekEditor),
    handler(accessor) {
      withController(accessor, (controller) => {
        controller.changeFocusBetweenPreviewAndReferences();
      });
    }
  });
  KeybindingsRegistry.registerCommandAndKeybindingRule({
    id: "goToNextReference",
    weight: 100 - 10,
    primary: 62,
    secondary: [
      70
      /* KeyCode.F12 */
    ],
    when: ContextKeyExpr.or(ctxReferenceSearchVisible, PeekContext.inPeekEditor),
    handler(accessor) {
      withController(accessor, (controller) => {
        controller.goToNextOrPreviousReference(true);
      });
    }
  });
  KeybindingsRegistry.registerCommandAndKeybindingRule({
    id: "goToPreviousReference",
    weight: 100 - 10,
    primary: 1024 | 62,
    secondary: [
      1024 | 70
      /* KeyCode.F12 */
    ],
    when: ContextKeyExpr.or(ctxReferenceSearchVisible, PeekContext.inPeekEditor),
    handler(accessor) {
      withController(accessor, (controller) => {
        controller.goToNextOrPreviousReference(false);
      });
    }
  });
  CommandsRegistry.registerCommandAlias("goToNextReferenceFromEmbeddedEditor", "goToNextReference");
  CommandsRegistry.registerCommandAlias("goToPreviousReferenceFromEmbeddedEditor", "goToPreviousReference");
  CommandsRegistry.registerCommandAlias("closeReferenceSearchEditor", "closeReferenceSearch");
  CommandsRegistry.registerCommand("closeReferenceSearch", (accessor) => withController(accessor, (controller) => controller.closeWidget()));
  KeybindingsRegistry.registerKeybindingRule({
    id: "closeReferenceSearch",
    weight: 100 - 101,
    primary: 9,
    secondary: [
      1024 | 9
      /* KeyCode.Escape */
    ],
    when: ContextKeyExpr.and(PeekContext.inPeekEditor, ContextKeyExpr.not("config.editor.stablePeek"))
  });
  KeybindingsRegistry.registerKeybindingRule({
    id: "closeReferenceSearch",
    weight: 200 + 50,
    primary: 9,
    secondary: [
      1024 | 9
      /* KeyCode.Escape */
    ],
    when: ContextKeyExpr.and(ctxReferenceSearchVisible, ContextKeyExpr.not("config.editor.stablePeek"), ContextKeyExpr.or(EditorContextKeys.editorTextFocus, InputFocusedContext.negate()))
  });
  KeybindingsRegistry.registerCommandAndKeybindingRule({
    id: "revealReference",
    weight: 200,
    primary: 3,
    mac: {
      primary: 3,
      secondary: [
        2048 | 18
        /* KeyCode.DownArrow */
      ]
    },
    when: ContextKeyExpr.and(ctxReferenceSearchVisible, WorkbenchListFocusContextKey, WorkbenchTreeElementCanCollapse.negate(), WorkbenchTreeElementCanExpand.negate()),
    handler(accessor) {
      const listService = accessor.get(IListService);
      const focus = listService.lastFocusedList?.getFocus();
      if (Array.isArray(focus) && focus[0] instanceof OneReference) {
        withController(accessor, (controller) => controller.revealReference(focus[0]));
      }
    }
  });
  KeybindingsRegistry.registerCommandAndKeybindingRule({
    id: "openReferenceToSide",
    weight: 100,
    primary: 2048 | 3,
    mac: {
      primary: 256 | 3
      /* KeyCode.Enter */
    },
    when: ContextKeyExpr.and(ctxReferenceSearchVisible, WorkbenchListFocusContextKey, WorkbenchTreeElementCanCollapse.negate(), WorkbenchTreeElementCanExpand.negate()),
    handler(accessor) {
      const listService = accessor.get(IListService);
      const focus = listService.lastFocusedList?.getFocus();
      if (Array.isArray(focus) && focus[0] instanceof OneReference) {
        withController(accessor, (controller) => controller.openReference(focus[0], true, true));
      }
    }
  });
  CommandsRegistry.registerCommand("openReference", (accessor) => {
    const listService = accessor.get(IListService);
    const focus = listService.lastFocusedList?.getFocus();
    if (Array.isArray(focus) && focus[0] instanceof OneReference) {
      withController(accessor, (controller) => controller.openReference(focus[0], false, true));
    }
  });
  var __decorate$1Z = 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$1Y = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  const ctxHasSymbols = new RawContextKey("hasSymbols", false, localize(1095, "Whether there are symbol locations that can be navigated via keyboard-only."));
  const ISymbolNavigationService = createDecorator("ISymbolNavigationService");
  let SymbolNavigationService = class SymbolNavigationService {
    constructor(contextKeyService, _editorService, _notificationService, _keybindingService) {
      this._editorService = _editorService;
      this._notificationService = _notificationService;
      this._keybindingService = _keybindingService;
      this._currentModel = void 0;
      this._currentIdx = -1;
      this._ignoreEditorChange = false;
      this._ctxHasSymbols = ctxHasSymbols.bindTo(contextKeyService);
    }
    reset() {
      this._ctxHasSymbols.reset();
      this._currentState?.dispose();
      this._currentMessage?.close();
      this._currentModel = void 0;
      this._currentIdx = -1;
    }
    put(anchor) {
      const refModel = anchor.parent.parent;
      if (refModel.references.length <= 1) {
        this.reset();
        return;
      }
      this._currentModel = refModel;
      this._currentIdx = refModel.references.indexOf(anchor);
      this._ctxHasSymbols.set(true);
      this._showMessage();
      const editorState = new EditorState(this._editorService);
      const listener = editorState.onDidChange((_) => {
        if (this._ignoreEditorChange) {
          return;
        }
        const editor2 = this._editorService.getActiveCodeEditor();
        if (!editor2) {
          return;
        }
        const model = editor2.getModel();
        const position = editor2.getPosition();
        if (!model || !position) {
          return;
        }
        let seenUri = false;
        let seenPosition = false;
        for (const reference of refModel.references) {
          if (isEqual(reference.uri, model.uri)) {
            seenUri = true;
            seenPosition = seenPosition || Range$2.containsPosition(reference.range, position);
          } else if (seenUri) {
            break;
          }
        }
        if (!seenUri || !seenPosition) {
          this.reset();
        }
      });
      this._currentState = combinedDisposable(editorState, listener);
    }
    revealNext(source) {
      if (!this._currentModel) {
        return Promise.resolve();
      }
      this._currentIdx += 1;
      this._currentIdx %= this._currentModel.references.length;
      const reference = this._currentModel.references[this._currentIdx];
      this._showMessage();
      this._ignoreEditorChange = true;
      return this._editorService.openCodeEditor({
        resource: reference.uri,
        options: {
          selection: Range$2.collapseToStart(reference.range),
          selectionRevealType: 3
          /* TextEditorSelectionRevealType.NearTopIfOutsideViewport */
        }
      }, source).finally(() => {
        this._ignoreEditorChange = false;
      });
    }
    _showMessage() {
      this._currentMessage?.close();
      const kb = this._keybindingService.lookupKeybinding("editor.gotoNextSymbolFromResult");
      const message = kb ? localize(1096, "Symbol {0} of {1}, {2} for next", this._currentIdx + 1, this._currentModel.references.length, kb.getLabel()) : localize(1097, "Symbol {0} of {1}", this._currentIdx + 1, this._currentModel.references.length);
      this._currentMessage = this._notificationService.status(message);
    }
  };
  SymbolNavigationService = __decorate$1Z([
    __param$1Y(0, IContextKeyService),
    __param$1Y(1, ICodeEditorService),
    __param$1Y(2, INotificationService),
    __param$1Y(3, IKeybindingService)
  ], SymbolNavigationService);
  registerSingleton(
    ISymbolNavigationService,
    SymbolNavigationService,
    1
    /* InstantiationType.Delayed */
  );
  registerEditorCommand(new class extends EditorCommand {
    constructor() {
      super({
        id: "editor.gotoNextSymbolFromResult",
        precondition: ctxHasSymbols,
        kbOpts: {
          weight: 100,
          primary: 70
          /* KeyCode.F12 */
        }
      });
    }
    runEditorCommand(accessor, editor2) {
      return accessor.get(ISymbolNavigationService).revealNext(editor2);
    }
  }());
  KeybindingsRegistry.registerCommandAndKeybindingRule({
    id: "editor.gotoNextSymbolFromResult.cancel",
    weight: 100,
    when: ctxHasSymbols,
    primary: 9,
    handler(accessor) {
      accessor.get(ISymbolNavigationService).reset();
    }
  });
  let EditorState = class EditorState {
    constructor(editorService) {
      this._listener = /* @__PURE__ */ new Map();
      this._disposables = new DisposableStore();
      this._onDidChange = new Emitter$1();
      this.onDidChange = this._onDidChange.event;
      this._disposables.add(editorService.onCodeEditorRemove(this._onDidRemoveEditor, this));
      this._disposables.add(editorService.onCodeEditorAdd(this._onDidAddEditor, this));
      editorService.listCodeEditors().forEach(this._onDidAddEditor, this);
    }
    dispose() {
      this._disposables.dispose();
      this._onDidChange.dispose();
      dispose(this._listener.values());
    }
    _onDidAddEditor(editor2) {
      this._listener.set(editor2, combinedDisposable(editor2.onDidChangeCursorPosition((_) => this._onDidChange.fire({ editor: editor2 })), editor2.onDidChangeModelContent((_) => this._onDidChange.fire({ editor: editor2 }))));
    }
    _onDidRemoveEditor(editor2) {
      this._listener.get(editor2)?.dispose();
      this._listener.delete(editor2);
    }
  };
  EditorState = __decorate$1Z([
    __param$1Y(0, ICodeEditorService)
  ], EditorState);
  function shouldIncludeLocationLink(sourceModel, loc) {
    if (loc.uri.scheme === sourceModel.uri.scheme) {
      return true;
    }
    if (matchesSomeScheme(loc.uri, Schemas.walkThroughSnippet, Schemas.vscodeChatCodeBlock, Schemas.vscodeChatCodeCompareBlock)) {
      return false;
    }
    return true;
  }
  async function getLocationLinks(model, position, registry, recursive, provide) {
    const provider = registry.ordered(model, recursive);
    const promises = provider.map((provider2) => {
      return Promise.resolve(provide(provider2, model, position)).then(void 0, (err) => {
        onUnexpectedExternalError(err);
        return void 0;
      });
    });
    const values = await Promise.all(promises);
    return coalesce(values.flat()).filter((loc) => shouldIncludeLocationLink(model, loc));
  }
  function getDefinitionsAtPosition(registry, model, position, recursive, token) {
    return getLocationLinks(model, position, registry, recursive, (provider, model2, position2) => {
      return provider.provideDefinition(model2, position2, token);
    });
  }
  function getDeclarationsAtPosition(registry, model, position, recursive, token) {
    return getLocationLinks(model, position, registry, recursive, (provider, model2, position2) => {
      return provider.provideDeclaration(model2, position2, token);
    });
  }
  function getImplementationsAtPosition(registry, model, position, recursive, token) {
    return getLocationLinks(model, position, registry, recursive, (provider, model2, position2) => {
      return provider.provideImplementation(model2, position2, token);
    });
  }
  function getTypeDefinitionsAtPosition(registry, model, position, recursive, token) {
    return getLocationLinks(model, position, registry, recursive, (provider, model2, position2) => {
      return provider.provideTypeDefinition(model2, position2, token);
    });
  }
  function getReferencesAtPosition(registry, model, position, compact, recursive, token) {
    return getLocationLinks(model, position, registry, recursive, async (provider, model2, position2) => {
      const result = (await provider.provideReferences(model2, position2, { includeDeclaration: true }, token))?.filter((ref) => shouldIncludeLocationLink(model2, ref));
      if (!compact || !result || result.length !== 2) {
        return result;
      }
      const resultWithoutDeclaration = (await provider.provideReferences(model2, position2, { includeDeclaration: false }, token))?.filter((ref) => shouldIncludeLocationLink(model2, ref));
      if (resultWithoutDeclaration && resultWithoutDeclaration.length === 1) {
        return resultWithoutDeclaration;
      }
      return result;
    });
  }
  async function _sortedAndDeduped(callback) {
    const rawLinks = await callback();
    const model = new ReferencesModel(rawLinks, "");
    const modelLinks = model.references.map((ref) => ref.link);
    model.dispose();
    return modelLinks;
  }
  registerModelAndPositionCommand("_executeDefinitionProvider", (accessor, model, position) => {
    const languageFeaturesService = accessor.get(ILanguageFeaturesService);
    const promise = getDefinitionsAtPosition(languageFeaturesService.definitionProvider, model, position, false, CancellationToken.None);
    return _sortedAndDeduped(() => promise);
  });
  registerModelAndPositionCommand("_executeDefinitionProvider_recursive", (accessor, model, position) => {
    const languageFeaturesService = accessor.get(ILanguageFeaturesService);
    const promise = getDefinitionsAtPosition(languageFeaturesService.definitionProvider, model, position, true, CancellationToken.None);
    return _sortedAndDeduped(() => promise);
  });
  registerModelAndPositionCommand("_executeTypeDefinitionProvider", (accessor, model, position) => {
    const languageFeaturesService = accessor.get(ILanguageFeaturesService);
    const promise = getTypeDefinitionsAtPosition(languageFeaturesService.typeDefinitionProvider, model, position, false, CancellationToken.None);
    return _sortedAndDeduped(() => promise);
  });
  registerModelAndPositionCommand("_executeTypeDefinitionProvider_recursive", (accessor, model, position) => {
    const languageFeaturesService = accessor.get(ILanguageFeaturesService);
    const promise = getTypeDefinitionsAtPosition(languageFeaturesService.typeDefinitionProvider, model, position, true, CancellationToken.None);
    return _sortedAndDeduped(() => promise);
  });
  registerModelAndPositionCommand("_executeDeclarationProvider", (accessor, model, position) => {
    const languageFeaturesService = accessor.get(ILanguageFeaturesService);
    const promise = getDeclarationsAtPosition(languageFeaturesService.declarationProvider, model, position, false, CancellationToken.None);
    return _sortedAndDeduped(() => promise);
  });
  registerModelAndPositionCommand("_executeDeclarationProvider_recursive", (accessor, model, position) => {
    const languageFeaturesService = accessor.get(ILanguageFeaturesService);
    const promise = getDeclarationsAtPosition(languageFeaturesService.declarationProvider, model, position, true, CancellationToken.None);
    return _sortedAndDeduped(() => promise);
  });
  registerModelAndPositionCommand("_executeReferenceProvider", (accessor, model, position) => {
    const languageFeaturesService = accessor.get(ILanguageFeaturesService);
    const promise = getReferencesAtPosition(languageFeaturesService.referenceProvider, model, position, false, false, CancellationToken.None);
    return _sortedAndDeduped(() => promise);
  });
  registerModelAndPositionCommand("_executeReferenceProvider_recursive", (accessor, model, position) => {
    const languageFeaturesService = accessor.get(ILanguageFeaturesService);
    const promise = getReferencesAtPosition(languageFeaturesService.referenceProvider, model, position, false, true, CancellationToken.None);
    return _sortedAndDeduped(() => promise);
  });
  registerModelAndPositionCommand("_executeImplementationProvider", (accessor, model, position) => {
    const languageFeaturesService = accessor.get(ILanguageFeaturesService);
    const promise = getImplementationsAtPosition(languageFeaturesService.implementationProvider, model, position, false, CancellationToken.None);
    return _sortedAndDeduped(() => promise);
  });
  registerModelAndPositionCommand("_executeImplementationProvider_recursive", (accessor, model, position) => {
    const languageFeaturesService = accessor.get(ILanguageFeaturesService);
    const promise = getImplementationsAtPosition(languageFeaturesService.implementationProvider, model, position, true, CancellationToken.None);
    return _sortedAndDeduped(() => promise);
  });
  MenuRegistry.appendMenuItem(MenuId.EditorContext, {
    submenu: MenuId.EditorContextPeek,
    title: localize(1038, "Peek"),
    group: "navigation",
    order: 100
  });
  class SymbolNavigationAnchor {
    static is(thing) {
      if (!thing || typeof thing !== "object") {
        return false;
      }
      if (thing instanceof SymbolNavigationAnchor) {
        return true;
      }
      if (Position$1.isIPosition(thing.position) && thing.model) {
        return true;
      }
      return false;
    }
    constructor(model, position) {
      this.model = model;
      this.position = position;
    }
  }
  const _SymbolNavigationAction = class _SymbolNavigationAction extends EditorAction2 {
    static all() {
      return _SymbolNavigationAction._allSymbolNavigationCommands.values();
    }
    static _patchConfig(opts) {
      const result = { ...opts, f1: true };
      if (result.menu) {
        for (const item of Iterable.wrap(result.menu)) {
          if (item.id === MenuId.EditorContext || item.id === MenuId.EditorContextPeek) {
            item.when = ContextKeyExpr.and(opts.precondition, item.when);
          }
        }
      }
      return result;
    }
    constructor(configuration, opts) {
      super(_SymbolNavigationAction._patchConfig(opts));
      this.configuration = configuration;
      _SymbolNavigationAction._allSymbolNavigationCommands.set(opts.id, this);
    }
    runEditorCommand(accessor, editor2, arg, range2) {
      if (!editor2.hasModel()) {
        return Promise.resolve(void 0);
      }
      const notificationService = accessor.get(INotificationService);
      const editorService = accessor.get(ICodeEditorService);
      const progressService = accessor.get(IEditorProgressService);
      const symbolNavService = accessor.get(ISymbolNavigationService);
      const languageFeaturesService = accessor.get(ILanguageFeaturesService);
      const instaService = accessor.get(IInstantiationService);
      const model = editor2.getModel();
      const position = editor2.getPosition();
      const anchor = SymbolNavigationAnchor.is(arg) ? arg : new SymbolNavigationAnchor(model, position);
      const cts = new EditorStateCancellationTokenSource(
        editor2,
        1 | 4
        /* CodeEditorStateFlag.Position */
      );
      const promise = raceCancellation(this._getLocationModel(languageFeaturesService, anchor.model, anchor.position, cts.token), cts.token).then(async (references) => {
        if (!references || cts.token.isCancellationRequested) {
          return;
        }
        alert(references.ariaMessage);
        let altAction;
        if (references.referenceAt(model.uri, position)) {
          const altActionId = this._getAlternativeCommand(editor2);
          if (altActionId !== void 0 && !_SymbolNavigationAction._activeAlternativeCommands.has(altActionId) && _SymbolNavigationAction._allSymbolNavigationCommands.has(altActionId)) {
            altAction = _SymbolNavigationAction._allSymbolNavigationCommands.get(altActionId);
          }
        }
        const referenceCount = references.references.length;
        if (referenceCount === 0) {
          if (!this.configuration.muteMessage) {
            const info = model.getWordAtPosition(position);
            MessageController.get(editor2)?.showMessage(this._getNoResultFoundMessage(info), position);
          }
        } else if (referenceCount === 1 && altAction) {
          _SymbolNavigationAction._activeAlternativeCommands.add(this.desc.id);
          instaService.invokeFunction((accessor2) => altAction.runEditorCommand(accessor2, editor2, arg, range2).finally(() => {
            _SymbolNavigationAction._activeAlternativeCommands.delete(this.desc.id);
          }));
        } else {
          return this._onResult(editorService, symbolNavService, editor2, references, range2);
        }
      }, (err) => {
        notificationService.error(err);
      }).finally(() => {
        cts.dispose();
      });
      progressService.showWhile(promise, 250);
      return promise;
    }
    async _onResult(editorService, symbolNavService, editor2, model, range2) {
      const gotoLocation = this._getGoToPreference(editor2);
      if (!(editor2 instanceof EmbeddedCodeEditorWidget) && (this.configuration.openInPeek || gotoLocation === "peek" && model.references.length > 1)) {
        this._openInPeek(editor2, model, range2);
      } else {
        const next = model.firstReference();
        const peek = model.references.length > 1 && gotoLocation === "gotoAndPeek";
        const targetEditor = await this._openReference(editor2, editorService, next, this.configuration.openToSide, !peek);
        if (peek && targetEditor) {
          this._openInPeek(targetEditor, model, range2);
        } else {
          model.dispose();
        }
        if (gotoLocation === "goto") {
          symbolNavService.put(next);
        }
      }
    }
    async _openReference(editor2, editorService, reference, sideBySide, highlight) {
      let range2 = void 0;
      if (isLocationLink(reference)) {
        range2 = reference.targetSelectionRange;
      }
      if (!range2) {
        range2 = reference.range;
      }
      if (!range2) {
        return void 0;
      }
      const targetEditor = await editorService.openCodeEditor({
        resource: reference.uri,
        options: {
          selection: Range$2.collapseToStart(range2),
          selectionRevealType: 3,
          selectionSource: "code.jump"
          /* TextEditorSelectionSource.JUMP */
        }
      }, editor2, sideBySide);
      if (!targetEditor) {
        return void 0;
      }
      if (highlight) {
        const modelNow = targetEditor.getModel();
        const decorations = targetEditor.createDecorationsCollection([{ range: range2, options: { description: "symbol-navigate-action-highlight", className: "symbolHighlight" } }]);
        setTimeout(() => {
          if (targetEditor.getModel() === modelNow) {
            decorations.clear();
          }
        }, 350);
      }
      return targetEditor;
    }
    _openInPeek(target, model, range2) {
      const controller = ReferencesController.get(target);
      if (controller && target.hasModel()) {
        controller.toggleWidget(range2 ?? target.getSelection(), createCancelablePromise((_) => Promise.resolve(model)), this.configuration.openInPeek);
      } else {
        model.dispose();
      }
    }
  };
  _SymbolNavigationAction._allSymbolNavigationCommands = /* @__PURE__ */ new Map();
  _SymbolNavigationAction._activeAlternativeCommands = /* @__PURE__ */ new Set();
  let SymbolNavigationAction = _SymbolNavigationAction;
  class DefinitionAction extends SymbolNavigationAction {
    async _getLocationModel(languageFeaturesService, model, position, token) {
      return new ReferencesModel(await getDefinitionsAtPosition(languageFeaturesService.definitionProvider, model, position, false, token), localize(1039, "Definitions"));
    }
    _getNoResultFoundMessage(info) {
      return info && info.word ? localize(1040, "No definition found for '{0}'", info.word) : localize(1041, "No definition found");
    }
    _getAlternativeCommand(editor2) {
      return editor2.getOption(
        67
        /* EditorOption.gotoLocation */
      ).alternativeDefinitionCommand;
    }
    _getGoToPreference(editor2) {
      return editor2.getOption(
        67
        /* EditorOption.gotoLocation */
      ).multipleDefinitions;
    }
  }
  registerAction2((_D = class extends DefinitionAction {
    constructor() {
      super({
        openToSide: false,
        openInPeek: false,
        muteMessage: false
      }, {
        id: _D.id,
        title: {
          ...localize2(1065, "Go to Definition"),
          mnemonicTitle: localize(1042, "Go to &&Definition")
        },
        precondition: EditorContextKeys.hasDefinitionProvider,
        keybinding: [{
          when: EditorContextKeys.editorTextFocus,
          primary: 70,
          weight: 100
          /* KeybindingWeight.EditorContrib */
        }, {
          when: ContextKeyExpr.and(EditorContextKeys.editorTextFocus, IsWebContext),
          primary: 2048 | 70,
          weight: 100
          /* KeybindingWeight.EditorContrib */
        }],
        menu: [{
          id: MenuId.EditorContext,
          group: "navigation",
          order: 1.1
        }, {
          id: MenuId.MenubarGoMenu,
          precondition: null,
          group: "4_symbol_nav",
          order: 2
        }]
      });
      CommandsRegistry.registerCommandAlias("editor.action.goToDeclaration", _D.id);
    }
  }, _D.id = "editor.action.revealDefinition", _D));
  registerAction2((_E = class extends DefinitionAction {
    constructor() {
      super({
        openToSide: true,
        openInPeek: false,
        muteMessage: false
      }, {
        id: _E.id,
        title: localize2(1066, "Open Definition to the Side"),
        precondition: ContextKeyExpr.and(EditorContextKeys.hasDefinitionProvider, EditorContextKeys.isInEmbeddedEditor.toNegated()),
        keybinding: [{
          when: EditorContextKeys.editorTextFocus,
          primary: KeyChord(
            2048 | 41,
            70
            /* KeyCode.F12 */
          ),
          weight: 100
          /* KeybindingWeight.EditorContrib */
        }, {
          when: ContextKeyExpr.and(EditorContextKeys.editorTextFocus, IsWebContext),
          primary: KeyChord(
            2048 | 41,
            2048 | 70
            /* KeyCode.F12 */
          ),
          weight: 100
          /* KeybindingWeight.EditorContrib */
        }]
      });
      CommandsRegistry.registerCommandAlias("editor.action.openDeclarationToTheSide", _E.id);
    }
  }, _E.id = "editor.action.revealDefinitionAside", _E));
  registerAction2((_F = class extends DefinitionAction {
    constructor() {
      super({
        openToSide: false,
        openInPeek: true,
        muteMessage: false
      }, {
        id: _F.id,
        title: localize2(1067, "Peek Definition"),
        precondition: ContextKeyExpr.and(EditorContextKeys.hasDefinitionProvider, PeekContext.notInPeekEditor, EditorContextKeys.isInEmbeddedEditor.toNegated()),
        keybinding: {
          when: EditorContextKeys.editorTextFocus,
          primary: 512 | 70,
          linux: {
            primary: 2048 | 1024 | 68
            /* KeyCode.F10 */
          },
          weight: 100
          /* KeybindingWeight.EditorContrib */
        },
        menu: {
          id: MenuId.EditorContextPeek,
          group: "peek",
          order: 2
        }
      });
      CommandsRegistry.registerCommandAlias("editor.action.previewDeclaration", _F.id);
    }
  }, _F.id = "editor.action.peekDefinition", _F));
  class DeclarationAction extends SymbolNavigationAction {
    async _getLocationModel(languageFeaturesService, model, position, token) {
      return new ReferencesModel(await getDeclarationsAtPosition(languageFeaturesService.declarationProvider, model, position, false, token), localize(1043, "Declarations"));
    }
    _getNoResultFoundMessage(info) {
      return info && info.word ? localize(1044, "No declaration found for '{0}'", info.word) : localize(1045, "No declaration found");
    }
    _getAlternativeCommand(editor2) {
      return editor2.getOption(
        67
        /* EditorOption.gotoLocation */
      ).alternativeDeclarationCommand;
    }
    _getGoToPreference(editor2) {
      return editor2.getOption(
        67
        /* EditorOption.gotoLocation */
      ).multipleDeclarations;
    }
  }
  registerAction2((_G = class extends DeclarationAction {
    constructor() {
      super({
        openToSide: false,
        openInPeek: false,
        muteMessage: false
      }, {
        id: _G.id,
        title: {
          ...localize2(1068, "Go to Declaration"),
          mnemonicTitle: localize(1046, "Go to &&Declaration")
        },
        precondition: ContextKeyExpr.and(EditorContextKeys.hasDeclarationProvider, EditorContextKeys.isInEmbeddedEditor.toNegated()),
        menu: [{
          id: MenuId.EditorContext,
          group: "navigation",
          order: 1.3
        }, {
          id: MenuId.MenubarGoMenu,
          precondition: null,
          group: "4_symbol_nav",
          order: 3
        }]
      });
    }
    _getNoResultFoundMessage(info) {
      return info && info.word ? localize(1047, "No declaration found for '{0}'", info.word) : localize(1048, "No declaration found");
    }
  }, _G.id = "editor.action.revealDeclaration", _G));
  registerAction2(class PeekDeclarationAction extends DeclarationAction {
    constructor() {
      super({
        openToSide: false,
        openInPeek: true,
        muteMessage: false
      }, {
        id: "editor.action.peekDeclaration",
        title: localize2(1069, "Peek Declaration"),
        precondition: ContextKeyExpr.and(EditorContextKeys.hasDeclarationProvider, PeekContext.notInPeekEditor, EditorContextKeys.isInEmbeddedEditor.toNegated()),
        menu: {
          id: MenuId.EditorContextPeek,
          group: "peek",
          order: 3
        }
      });
    }
  });
  class TypeDefinitionAction extends SymbolNavigationAction {
    async _getLocationModel(languageFeaturesService, model, position, token) {
      return new ReferencesModel(await getTypeDefinitionsAtPosition(languageFeaturesService.typeDefinitionProvider, model, position, false, token), localize(1049, "Type Definitions"));
    }
    _getNoResultFoundMessage(info) {
      return info && info.word ? localize(1050, "No type definition found for '{0}'", info.word) : localize(1051, "No type definition found");
    }
    _getAlternativeCommand(editor2) {
      return editor2.getOption(
        67
        /* EditorOption.gotoLocation */
      ).alternativeTypeDefinitionCommand;
    }
    _getGoToPreference(editor2) {
      return editor2.getOption(
        67
        /* EditorOption.gotoLocation */
      ).multipleTypeDefinitions;
    }
  }
  registerAction2((_H = class extends TypeDefinitionAction {
    constructor() {
      super({
        openToSide: false,
        openInPeek: false,
        muteMessage: false
      }, {
        id: _H.ID,
        title: {
          ...localize2(1070, "Go to Type Definition"),
          mnemonicTitle: localize(1052, "Go to &&Type Definition")
        },
        precondition: EditorContextKeys.hasTypeDefinitionProvider,
        keybinding: {
          when: EditorContextKeys.editorTextFocus,
          primary: 0,
          weight: 100
          /* KeybindingWeight.EditorContrib */
        },
        menu: [{
          id: MenuId.EditorContext,
          group: "navigation",
          order: 1.4
        }, {
          id: MenuId.MenubarGoMenu,
          precondition: null,
          group: "4_symbol_nav",
          order: 3
        }]
      });
    }
  }, _H.ID = "editor.action.goToTypeDefinition", _H));
  registerAction2((_I = class extends TypeDefinitionAction {
    constructor() {
      super({
        openToSide: false,
        openInPeek: true,
        muteMessage: false
      }, {
        id: _I.ID,
        title: localize2(1071, "Peek Type Definition"),
        precondition: ContextKeyExpr.and(EditorContextKeys.hasTypeDefinitionProvider, PeekContext.notInPeekEditor, EditorContextKeys.isInEmbeddedEditor.toNegated()),
        menu: {
          id: MenuId.EditorContextPeek,
          group: "peek",
          order: 4
        }
      });
    }
  }, _I.ID = "editor.action.peekTypeDefinition", _I));
  class ImplementationAction extends SymbolNavigationAction {
    async _getLocationModel(languageFeaturesService, model, position, token) {
      return new ReferencesModel(await getImplementationsAtPosition(languageFeaturesService.implementationProvider, model, position, false, token), localize(1053, "Implementations"));
    }
    _getNoResultFoundMessage(info) {
      return info && info.word ? localize(1054, "No implementation found for '{0}'", info.word) : localize(1055, "No implementation found");
    }
    _getAlternativeCommand(editor2) {
      return editor2.getOption(
        67
        /* EditorOption.gotoLocation */
      ).alternativeImplementationCommand;
    }
    _getGoToPreference(editor2) {
      return editor2.getOption(
        67
        /* EditorOption.gotoLocation */
      ).multipleImplementations;
    }
  }
  registerAction2((_J = class extends ImplementationAction {
    constructor() {
      super({
        openToSide: false,
        openInPeek: false,
        muteMessage: false
      }, {
        id: _J.ID,
        title: {
          ...localize2(1072, "Go to Implementations"),
          mnemonicTitle: localize(1056, "Go to &&Implementations")
        },
        precondition: EditorContextKeys.hasImplementationProvider,
        keybinding: {
          when: EditorContextKeys.editorTextFocus,
          primary: 2048 | 70,
          weight: 100
          /* KeybindingWeight.EditorContrib */
        },
        menu: [{
          id: MenuId.EditorContext,
          group: "navigation",
          order: 1.45
        }, {
          id: MenuId.MenubarGoMenu,
          precondition: null,
          group: "4_symbol_nav",
          order: 4
        }]
      });
    }
  }, _J.ID = "editor.action.goToImplementation", _J));
  registerAction2((_K = class extends ImplementationAction {
    constructor() {
      super({
        openToSide: false,
        openInPeek: true,
        muteMessage: false
      }, {
        id: _K.ID,
        title: localize2(1073, "Peek Implementations"),
        precondition: ContextKeyExpr.and(EditorContextKeys.hasImplementationProvider, PeekContext.notInPeekEditor, EditorContextKeys.isInEmbeddedEditor.toNegated()),
        keybinding: {
          when: EditorContextKeys.editorTextFocus,
          primary: 2048 | 1024 | 70,
          weight: 100
          /* KeybindingWeight.EditorContrib */
        },
        menu: {
          id: MenuId.EditorContextPeek,
          group: "peek",
          order: 5
        }
      });
    }
  }, _K.ID = "editor.action.peekImplementation", _K));
  class ReferencesAction extends SymbolNavigationAction {
    _getNoResultFoundMessage(info) {
      return info ? localize(1057, "No references found for '{0}'", info.word) : localize(1058, "No references found");
    }
    _getAlternativeCommand(editor2) {
      return editor2.getOption(
        67
        /* EditorOption.gotoLocation */
      ).alternativeReferenceCommand;
    }
    _getGoToPreference(editor2) {
      return editor2.getOption(
        67
        /* EditorOption.gotoLocation */
      ).multipleReferences;
    }
  }
  registerAction2(class GoToReferencesAction extends ReferencesAction {
    constructor() {
      super({
        openToSide: false,
        openInPeek: false,
        muteMessage: false
      }, {
        id: "editor.action.goToReferences",
        title: {
          ...localize2(1074, "Go to References"),
          mnemonicTitle: localize(1059, "Go to &&References")
        },
        precondition: ContextKeyExpr.and(EditorContextKeys.hasReferenceProvider, PeekContext.notInPeekEditor, EditorContextKeys.isInEmbeddedEditor.toNegated()),
        keybinding: {
          when: EditorContextKeys.editorTextFocus,
          primary: 1024 | 70,
          weight: 100
          /* KeybindingWeight.EditorContrib */
        },
        menu: [{
          id: MenuId.EditorContext,
          group: "navigation",
          order: 1.45
        }, {
          id: MenuId.MenubarGoMenu,
          precondition: null,
          group: "4_symbol_nav",
          order: 5
        }]
      });
    }
    async _getLocationModel(languageFeaturesService, model, position, token) {
      return new ReferencesModel(await getReferencesAtPosition(languageFeaturesService.referenceProvider, model, position, true, false, token), localize(1060, "References"));
    }
  });
  registerAction2(class PeekReferencesAction extends ReferencesAction {
    constructor() {
      super({
        openToSide: false,
        openInPeek: true,
        muteMessage: false
      }, {
        id: "editor.action.referenceSearch.trigger",
        title: localize2(1075, "Peek References"),
        precondition: ContextKeyExpr.and(EditorContextKeys.hasReferenceProvider, PeekContext.notInPeekEditor, EditorContextKeys.isInEmbeddedEditor.toNegated()),
        menu: {
          id: MenuId.EditorContextPeek,
          group: "peek",
          order: 6
        }
      });
    }
    async _getLocationModel(languageFeaturesService, model, position, token) {
      return new ReferencesModel(await getReferencesAtPosition(languageFeaturesService.referenceProvider, model, position, false, false, token), localize(1061, "References"));
    }
  });
  class GenericGoToLocationAction extends SymbolNavigationAction {
    constructor(config, _references, _gotoMultipleBehaviour) {
      super(config, {
        id: "editor.action.goToLocation",
        title: localize2(1076, "Go to Any Symbol"),
        precondition: ContextKeyExpr.and(PeekContext.notInPeekEditor, EditorContextKeys.isInEmbeddedEditor.toNegated())
      });
      this._references = _references;
      this._gotoMultipleBehaviour = _gotoMultipleBehaviour;
    }
    async _getLocationModel(languageFeaturesService, _model, _position, _token) {
      return new ReferencesModel(this._references, localize(1062, "Locations"));
    }
    _getNoResultFoundMessage(info) {
      return info && localize(1063, "No results for '{0}'", info.word) || "";
    }
    _getGoToPreference(editor2) {
      return this._gotoMultipleBehaviour ?? editor2.getOption(
        67
        /* EditorOption.gotoLocation */
      ).multipleReferences;
    }
    _getAlternativeCommand() {
      return void 0;
    }
  }
  CommandsRegistry.registerCommand({
    id: "editor.action.goToLocations",
    metadata: {
      description: "Go to locations from a position in a file",
      args: [
        { name: "uri", description: "The text document in which to start", constraint: URI },
        { name: "position", description: "The position at which to start", constraint: Position$1.isIPosition },
        { name: "locations", description: "An array of locations.", constraint: Array },
        { name: "multiple", description: "Define what to do when having multiple results, either `peek`, `gotoAndPeek`, or `goto`" },
        { name: "noResultsMessage", description: "Human readable message that shows when locations is empty." }
      ]
    },
    handler: async (accessor, resource, position, references, multiple, noResultsMessage, openInPeek) => {
      assertType(URI.isUri(resource));
      assertType(Position$1.isIPosition(position));
      assertType(Array.isArray(references));
      assertType(typeof multiple === "undefined" || typeof multiple === "string");
      assertType(typeof openInPeek === "undefined" || typeof openInPeek === "boolean");
      const editorService = accessor.get(ICodeEditorService);
      const editor2 = await editorService.openCodeEditor({ resource }, editorService.getFocusedCodeEditor());
      if (isCodeEditor(editor2)) {
        editor2.setPosition(position);
        editor2.revealPositionInCenterIfOutsideViewport(
          position,
          0
          /* ScrollType.Smooth */
        );
        return editor2.invokeWithinContext((accessor2) => {
          const command = new class extends GenericGoToLocationAction {
            _getNoResultFoundMessage(info) {
              return noResultsMessage || super._getNoResultFoundMessage(info);
            }
          }({
            muteMessage: !Boolean(noResultsMessage),
            openInPeek: Boolean(openInPeek),
            openToSide: false
          }, references, multiple);
          accessor2.get(IInstantiationService).invokeFunction(command.run.bind(command), editor2);
        });
      }
    }
  });
  CommandsRegistry.registerCommand({
    id: "editor.action.peekLocations",
    metadata: {
      description: "Peek locations from a position in a file",
      args: [
        { name: "uri", description: "The text document in which to start", constraint: URI },
        { name: "position", description: "The position at which to start", constraint: Position$1.isIPosition },
        { name: "locations", description: "An array of locations.", constraint: Array },
        { name: "multiple", description: "Define what to do when having multiple results, either `peek`, `gotoAndPeek`, or `goto`" }
      ]
    },
    handler: async (accessor, resource, position, references, multiple) => {
      accessor.get(ICommandService).executeCommand("editor.action.goToLocations", resource, position, references, multiple, void 0, true);
    }
  });
  CommandsRegistry.registerCommand({
    id: "editor.action.findReferences",
    handler: (accessor, resource, position) => {
      assertType(URI.isUri(resource));
      assertType(Position$1.isIPosition(position));
      const languageFeaturesService = accessor.get(ILanguageFeaturesService);
      const codeEditorService = accessor.get(ICodeEditorService);
      return codeEditorService.openCodeEditor({ resource }, codeEditorService.getFocusedCodeEditor()).then((control) => {
        if (!isCodeEditor(control) || !control.hasModel()) {
          return void 0;
        }
        const controller = ReferencesController.get(control);
        if (!controller) {
          return void 0;
        }
        const references = createCancelablePromise((token) => getReferencesAtPosition(languageFeaturesService.referenceProvider, control.getModel(), Position$1.lift(position), false, false, token).then((references2) => new ReferencesModel(references2, localize(1064, "References"))));
        const range2 = new Range$2(position.lineNumber, position.column, position.lineNumber, position.column);
        return Promise.resolve(controller.toggleWidget(range2, references, false));
      });
    }
  });
  CommandsRegistry.registerCommandAlias("editor.action.showReferences", "editor.action.peekLocations");
  async function showGoToContextMenu(accessor, editor2, anchor, part) {
    const resolverService = accessor.get(ITextModelService);
    const contextMenuService = accessor.get(IContextMenuService);
    const commandService = accessor.get(ICommandService);
    const instaService = accessor.get(IInstantiationService);
    const notificationService = accessor.get(INotificationService);
    await part.item.resolve(CancellationToken.None);
    if (!part.part.location) {
      return;
    }
    const location = part.part.location;
    const menuActions = [];
    const filter = new Set(MenuRegistry.getMenuItems(MenuId.EditorContext).map((item) => isIMenuItem(item) ? item.command.id : generateUuid()));
    for (const delegate of SymbolNavigationAction.all()) {
      if (filter.has(delegate.desc.id)) {
        menuActions.push(new Action(delegate.desc.id, MenuItemAction.label(delegate.desc, { renderShortTitle: true }), void 0, true, async () => {
          const ref = await resolverService.createModelReference(location.uri);
          try {
            const symbolAnchor = new SymbolNavigationAnchor(ref.object.textEditorModel, Range$2.getStartPosition(location.range));
            const range2 = part.item.anchor.range;
            await instaService.invokeFunction(delegate.runEditorCommand.bind(delegate), editor2, symbolAnchor, range2);
          } finally {
            ref.dispose();
          }
        }));
      }
    }
    if (part.part.command) {
      const { command } = part.part;
      menuActions.push(new Separator());
      menuActions.push(new Action(command.id, command.title, void 0, true, async () => {
        try {
          await commandService.executeCommand(command.id, ...command.arguments ?? []);
        } catch (err) {
          notificationService.notify({
            severity: Severity.Error,
            source: part.item.provider.displayName,
            message: err
          });
        }
      }));
    }
    const useShadowDOM = editor2.getOption(
      144
      /* EditorOption.useShadowDOM */
    );
    contextMenuService.showContextMenu({
      domForShadowRoot: useShadowDOM ? editor2.getDomNode() ?? void 0 : void 0,
      getAnchor: () => {
        const box = getDomNodePagePosition(anchor);
        return { x: box.left, y: box.top + box.height + 8 };
      },
      getActions: () => menuActions,
      onHide: () => {
        editor2.focus();
      },
      autoSelectFirstItem: true
    });
  }
  async function goToDefinitionWithLocation(accessor, event, editor2, location) {
    const resolverService = accessor.get(ITextModelService);
    const ref = await resolverService.createModelReference(location.uri);
    await editor2.invokeWithinContext(async (accessor2) => {
      const openToSide = event.hasSideBySideModifier;
      const contextKeyService = accessor2.get(IContextKeyService);
      const isInPeek = PeekContext.inPeekEditor.getValue(contextKeyService);
      const canPeek = !openToSide && editor2.getOption(
        101
        /* EditorOption.definitionLinkOpensInPeek */
      ) && !isInPeek;
      const action = new DefinitionAction({ openToSide, openInPeek: canPeek, muteMessage: true }, { title: { value: "", original: "" }, id: "", precondition: void 0 });
      return action.run(accessor2, new SymbolNavigationAnchor(ref.object.textEditorModel, Range$2.getStartPosition(location.range)), Range$2.lift(location.range));
    });
    ref.dispose();
  }
  var __decorate$1Y = 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$1X = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  var InlayHintsController_1;
  class InlayHintsCache {
    constructor() {
      this._entries = new LRUCache(50);
    }
    get(model) {
      const key = InlayHintsCache._key(model);
      return this._entries.get(key);
    }
    set(model, value) {
      const key = InlayHintsCache._key(model);
      this._entries.set(key, value);
    }
    static _key(model) {
      return `${model.uri.toString()}/${model.getVersionId()}`;
    }
  }
  const IInlayHintsCache = createDecorator("IInlayHintsCache");
  registerSingleton(
    IInlayHintsCache,
    InlayHintsCache,
    1
    /* InstantiationType.Delayed */
  );
  class RenderedInlayHintLabelPart {
    constructor(item, index) {
      this.item = item;
      this.index = index;
    }
    get part() {
      const label = this.item.hint.label;
      if (typeof label === "string") {
        return { label };
      } else {
        return label[this.index];
      }
    }
  }
  class ActiveInlayHintInfo {
    constructor(part, hasTriggerModifier2) {
      this.part = part;
      this.hasTriggerModifier = hasTriggerModifier2;
    }
  }
  class CancellationStore {
    constructor() {
      this._store = new MutableDisposable();
      this._tokenSource = new CancellationTokenSource$1();
    }
    dispose() {
      this._store.dispose();
      this._tokenSource.dispose(true);
    }
    reset() {
      this._tokenSource.dispose(true);
      this._tokenSource = new CancellationTokenSource$1();
      this._store.value = new DisposableStore();
      return {
        store: this._store.value,
        token: this._tokenSource.token
      };
    }
  }
  let InlayHintsController = (_L = class {
    static get(editor2) {
      return editor2.getContribution(InlayHintsController_1.ID) ?? void 0;
    }
    constructor(_editor, _languageFeaturesService, _featureDebounce, _inlayHintsCache, _commandService, _notificationService, _instaService) {
      this._editor = _editor;
      this._languageFeaturesService = _languageFeaturesService;
      this._inlayHintsCache = _inlayHintsCache;
      this._commandService = _commandService;
      this._notificationService = _notificationService;
      this._instaService = _instaService;
      this._disposables = new DisposableStore();
      this._sessionDisposables = new DisposableStore();
      this._decorationsMetadata = /* @__PURE__ */ new Map();
      this._activeRenderMode = 0;
      this._ruleFactory = this._disposables.add(new DynamicCssRules(this._editor));
      this._debounceInfo = _featureDebounce.for(_languageFeaturesService.inlayHintsProvider, "InlayHint", { min: 25 });
      this._disposables.add(_languageFeaturesService.inlayHintsProvider.onDidChange(() => this._update()));
      this._disposables.add(_editor.onDidChangeModel(() => this._update()));
      this._disposables.add(_editor.onDidChangeModelLanguage(() => this._update()));
      this._disposables.add(_editor.onDidChangeConfiguration((e) => {
        if (e.hasChanged(
          159
          /* EditorOption.inlayHints */
        )) {
          this._update();
        }
      }));
      this._update();
    }
    dispose() {
      this._sessionDisposables.dispose();
      this._removeAllDecorations();
      this._disposables.dispose();
    }
    _update() {
      this._sessionDisposables.clear();
      this._removeAllDecorations();
      const options = this._editor.getOption(
        159
        /* EditorOption.inlayHints */
      );
      if (options.enabled === "off") {
        return;
      }
      const model = this._editor.getModel();
      if (!model || !this._languageFeaturesService.inlayHintsProvider.has(model)) {
        return;
      }
      if (options.enabled === "on") {
        this._activeRenderMode = 0;
      } else {
        let defaultMode;
        let altMode;
        if (options.enabled === "onUnlessPressed") {
          defaultMode = 0;
          altMode = 1;
        } else {
          defaultMode = 1;
          altMode = 0;
        }
        this._activeRenderMode = defaultMode;
        this._sessionDisposables.add(ModifierKeyEmitter.getInstance().event((e) => {
          if (!this._editor.hasModel()) {
            return;
          }
          const newRenderMode = e.altKey && e.ctrlKey && !(e.shiftKey || e.metaKey) ? altMode : defaultMode;
          if (newRenderMode !== this._activeRenderMode) {
            this._activeRenderMode = newRenderMode;
            const model2 = this._editor.getModel();
            const copies = this._copyInlayHintsWithCurrentAnchor(model2);
            this._updateHintsDecorators([model2.getFullModelRange()], copies);
            scheduler.schedule(0);
          }
        }));
      }
      const cached = this._inlayHintsCache.get(model);
      if (cached) {
        this._updateHintsDecorators([model.getFullModelRange()], cached);
      }
      this._sessionDisposables.add(toDisposable(() => {
        if (!model.isDisposed()) {
          this._cacheHintsForFastRestore(model);
        }
      }));
      let cts;
      const watchedProviders = /* @__PURE__ */ new Set();
      this._sessionDisposables.add(model.onWillDispose(() => cts?.cancel()));
      const cancellationStore = this._sessionDisposables.add(new CancellationStore());
      const scheduler = new RunOnceScheduler(async () => {
        const t1 = Date.now();
        const { store, token } = cancellationStore.reset();
        try {
          const inlayHints = await InlayHintsFragments.create(this._languageFeaturesService.inlayHintsProvider, model, this._getHintsRanges(), token);
          scheduler.delay = this._debounceInfo.update(model, Date.now() - t1);
          if (token.isCancellationRequested) {
            inlayHints.dispose();
            return;
          }
          for (const provider of inlayHints.provider) {
            if (typeof provider.onDidChangeInlayHints === "function" && !watchedProviders.has(provider)) {
              watchedProviders.add(provider);
              store.add(provider.onDidChangeInlayHints(() => {
                if (!scheduler.isScheduled()) {
                  scheduler.schedule();
                }
              }));
            }
          }
          store.add(inlayHints);
          this._updateHintsDecorators(inlayHints.ranges, inlayHints.items);
          this._cacheHintsForFastRestore(model);
        } catch (err) {
          onUnexpectedError(err);
        }
      }, this._debounceInfo.get(model));
      this._sessionDisposables.add(scheduler);
      scheduler.schedule(0);
      this._sessionDisposables.add(this._editor.onDidScrollChange((e) => {
        if (e.scrollTopChanged || !scheduler.isScheduled()) {
          scheduler.schedule();
        }
      }));
      const cursor = this._sessionDisposables.add(new MutableDisposable());
      this._sessionDisposables.add(this._editor.onDidChangeModelContent((e) => {
        const delay = Math.max(scheduler.delay, 800);
        this._cursorInfo = { position: this._editor.getPosition(), notEarlierThan: Date.now() + delay };
        cursor.value = disposableTimeout(() => scheduler.schedule(0), delay);
        scheduler.schedule();
      }));
      this._sessionDisposables.add(this._editor.onDidChangeConfiguration((e) => {
        if (e.hasChanged(
          159
          /* EditorOption.inlayHints */
        )) {
          scheduler.schedule();
        }
      }));
      this._sessionDisposables.add(this._installDblClickGesture(() => scheduler.schedule(0)));
      this._sessionDisposables.add(this._installLinkGesture());
      this._sessionDisposables.add(this._installContextMenu());
    }
    _installLinkGesture() {
      const store = new DisposableStore();
      const gesture = store.add(new ClickLinkGesture(this._editor));
      const sessionStore = new DisposableStore();
      store.add(sessionStore);
      store.add(gesture.onMouseMoveOrRelevantKeyDown((e) => {
        const [mouseEvent] = e;
        const labelPart = this._getInlayHintLabelPart(mouseEvent);
        const model = this._editor.getModel();
        if (!labelPart || !model) {
          sessionStore.clear();
          return;
        }
        const cts = new CancellationTokenSource$1();
        sessionStore.add(toDisposable(() => cts.dispose(true)));
        labelPart.item.resolve(cts.token);
        this._activeInlayHintPart = labelPart.part.command || labelPart.part.location ? new ActiveInlayHintInfo(labelPart, mouseEvent.hasTriggerModifier) : void 0;
        const lineNumber = model.validatePosition(labelPart.item.hint.position).lineNumber;
        const range2 = new Range$2(lineNumber, 1, lineNumber, model.getLineMaxColumn(lineNumber));
        const lineHints = this._getInlineHintsForRange(range2);
        this._updateHintsDecorators([range2], lineHints);
        sessionStore.add(toDisposable(() => {
          this._activeInlayHintPart = void 0;
          this._updateHintsDecorators([range2], lineHints);
        }));
      }));
      store.add(gesture.onCancel(() => sessionStore.clear()));
      store.add(gesture.onExecute(async (e) => {
        const label = this._getInlayHintLabelPart(e);
        if (label) {
          const part = label.part;
          if (part.location) {
            this._instaService.invokeFunction(goToDefinitionWithLocation, e, this._editor, part.location);
          } else if (Command.is(part.command)) {
            await this._invokeCommand(part.command, label.item);
          }
        }
      }));
      return store;
    }
    _getInlineHintsForRange(range2) {
      const lineHints = /* @__PURE__ */ new Set();
      for (const data of this._decorationsMetadata.values()) {
        if (range2.containsRange(data.item.anchor.range)) {
          lineHints.add(data.item);
        }
      }
      return Array.from(lineHints);
    }
    _installDblClickGesture(updateInlayHints) {
      return this._editor.onMouseUp(async (e) => {
        if (e.event.detail !== 2) {
          return;
        }
        const part = this._getInlayHintLabelPart(e);
        if (!part) {
          return;
        }
        e.event.preventDefault();
        await part.item.resolve(CancellationToken.None);
        if (isNonEmptyArray(part.item.hint.textEdits)) {
          const edits = part.item.hint.textEdits.map((edit2) => EditOperation.replace(Range$2.lift(edit2.range), edit2.text));
          this._editor.executeEdits("inlayHint.default", edits);
          updateInlayHints();
        }
      });
    }
    _installContextMenu() {
      return this._editor.onContextMenu(async (e) => {
        if (!isHTMLElement(e.event.target)) {
          return;
        }
        const part = this._getInlayHintLabelPart(e);
        if (part) {
          await this._instaService.invokeFunction(showGoToContextMenu, this._editor, e.event.target, part);
        }
      });
    }
    _getInlayHintLabelPart(e) {
      if (e.target.type !== 6) {
        return void 0;
      }
      const options = e.target.detail.injectedText?.options;
      if (options instanceof ModelDecorationInjectedTextOptions && options?.attachedData instanceof RenderedInlayHintLabelPart) {
        return options.attachedData;
      }
      return void 0;
    }
    async _invokeCommand(command, item) {
      try {
        await this._commandService.executeCommand(command.id, ...command.arguments ?? []);
      } catch (err) {
        this._notificationService.notify({
          severity: Severity.Error,
          source: item.provider.displayName,
          message: err
        });
      }
    }
    _cacheHintsForFastRestore(model) {
      const hints = this._copyInlayHintsWithCurrentAnchor(model);
      this._inlayHintsCache.set(model, hints);
    }
    // return inlay hints but with an anchor that reflects "updates"
    // that happened after receiving them, e.g adding new lines before a hint
    _copyInlayHintsWithCurrentAnchor(model) {
      const items = /* @__PURE__ */ new Map();
      for (const [id, obj] of this._decorationsMetadata) {
        if (items.has(obj.item)) {
          continue;
        }
        const range2 = model.getDecorationRange(id);
        if (range2) {
          const anchor = new InlayHintAnchor(range2, obj.item.anchor.direction);
          const copy = obj.item.with({ anchor });
          items.set(obj.item, copy);
        }
      }
      return Array.from(items.values());
    }
    _getHintsRanges() {
      const extra = 30;
      const model = this._editor.getModel();
      const visibleRanges = this._editor.getVisibleRangesPlusViewportAboveBelow();
      const result = [];
      for (const range2 of visibleRanges.sort(Range$2.compareRangesUsingStarts)) {
        const extendedRange = model.validateRange(new Range$2(range2.startLineNumber - extra, range2.startColumn, range2.endLineNumber + extra, range2.endColumn));
        if (result.length === 0 || !Range$2.areIntersectingOrTouching(result[result.length - 1], extendedRange)) {
          result.push(extendedRange);
        } else {
          result[result.length - 1] = Range$2.plusRange(result[result.length - 1], extendedRange);
        }
      }
      return result;
    }
    _updateHintsDecorators(ranges, items) {
      const itemFixedLengths = /* @__PURE__ */ new Map();
      if (this._cursorInfo && this._cursorInfo.notEarlierThan > Date.now() && ranges.some((range2) => range2.containsPosition(this._cursorInfo.position))) {
        const { position } = this._cursorInfo;
        this._cursorInfo = void 0;
        const lengths = /* @__PURE__ */ new Map();
        for (const deco of this._editor.getLineDecorations(position.lineNumber) ?? []) {
          const data = this._decorationsMetadata.get(deco.id);
          if (deco.range.startColumn > position.column) {
            continue;
          }
          const opts = data?.decoration.options[data.item.anchor.direction];
          if (opts && opts.attachedData !== InlayHintsController_1._whitespaceData) {
            const len = lengths.get(data.item) ?? 0;
            lengths.set(data.item, len + opts.content.length);
          }
        }
        const newItemsWithFixedLength = items.filter((item) => item.anchor.range.startLineNumber === position.lineNumber && item.anchor.range.endColumn <= position.column);
        const fixedLengths = Array.from(lengths.values());
        let lastItem;
        while (true) {
          const targetItem = newItemsWithFixedLength.shift();
          const fixedLength = fixedLengths.shift();
          if (!fixedLength && !targetItem) {
            break;
          }
          if (targetItem) {
            itemFixedLengths.set(targetItem, fixedLength ?? 0);
            lastItem = targetItem;
          } else if (lastItem && fixedLength) {
            let len = itemFixedLengths.get(lastItem);
            len += fixedLength;
            len += fixedLengths.reduce((p, c) => p + c, 0);
            fixedLengths.length = 0;
            break;
          }
        }
      }
      const newDecorationsData = [];
      const addInjectedText = (item, ref, content, cursorStops, attachedData) => {
        const opts = {
          content,
          inlineClassNameAffectsLetterSpacing: true,
          inlineClassName: ref.className,
          cursorStops,
          attachedData
        };
        newDecorationsData.push({
          item,
          classNameRef: ref,
          decoration: {
            range: item.anchor.range,
            options: {
              // className: "rangeHighlight", // DEBUG highlight to see to what range a hint is attached
              description: "InlayHint",
              showIfCollapsed: item.anchor.range.isEmpty(),
              // "original" range is empty
              collapseOnReplaceEdit: !item.anchor.range.isEmpty(),
              stickiness: 0,
              [item.anchor.direction]: this._activeRenderMode === 0 ? opts : void 0
            }
          }
        });
      };
      const addInjectedWhitespace = (item, isLast) => {
        const marginRule = this._ruleFactory.createClassNameRef({
          width: `${fontSize / 3 | 0}px`,
          display: "inline-block"
        });
        addInjectedText(item, marginRule, " ", isLast ? InjectedTextCursorStops$1.Right : InjectedTextCursorStops$1.None, InlayHintsController_1._whitespaceData);
      };
      const { fontSize, fontFamily, padding, isUniform } = this._getLayoutInfo();
      const maxLength = this._editor.getOption(
        159
        /* EditorOption.inlayHints */
      ).maximumLength;
      const fontFamilyVar = "--code-editorInlayHintsFontFamily";
      this._editor.getContainerDomNode().style.setProperty(fontFamilyVar, fontFamily);
      let currentLineInfo = { line: 0, totalLen: 0 };
      for (let i2 = 0; i2 < items.length; i2++) {
        const item = items[i2];
        if (currentLineInfo.line !== item.anchor.range.startLineNumber) {
          currentLineInfo = { line: item.anchor.range.startLineNumber, totalLen: 0 };
        }
        if (maxLength && currentLineInfo.totalLen > maxLength) {
          continue;
        }
        if (item.hint.paddingLeft) {
          addInjectedWhitespace(item, false);
        }
        const parts = typeof item.hint.label === "string" ? [{ label: item.hint.label }] : item.hint.label;
        const itemFixedLength = itemFixedLengths.get(item);
        let itemActualLength = 0;
        for (let i3 = 0; i3 < parts.length; i3++) {
          const part = parts[i3];
          const isFirst = i3 === 0;
          const isLast = i3 === parts.length - 1;
          const cssProperties = {
            fontSize: `${fontSize}px`,
            fontFamily: `var(${fontFamilyVar}), ${EDITOR_FONT_DEFAULTS.fontFamily}`,
            verticalAlign: isUniform ? "baseline" : "middle",
            unicodeBidi: "isolate"
          };
          if (isNonEmptyArray(item.hint.textEdits)) {
            cssProperties.cursor = "default";
          }
          this._fillInColors(cssProperties, item.hint);
          if ((part.command || part.location) && this._activeInlayHintPart?.part.item === item && this._activeInlayHintPart.part.index === i3) {
            cssProperties.textDecoration = "underline";
            if (this._activeInlayHintPart.hasTriggerModifier) {
              cssProperties.color = themeColorFromId(editorActiveLinkForeground);
              cssProperties.cursor = "pointer";
            }
          }
          let textlabel = part.label;
          currentLineInfo.totalLen += textlabel.length;
          let tooLong = false;
          const over = maxLength !== 0 ? currentLineInfo.totalLen - maxLength : 0;
          if (over > 0) {
            textlabel = textlabel.slice(0, -over) + "…";
            tooLong = true;
          }
          itemActualLength += textlabel.length;
          if (itemFixedLength !== void 0) {
            const overFixedLength = itemActualLength - itemFixedLength;
            if (overFixedLength >= 0) {
              itemActualLength -= overFixedLength;
              textlabel = textlabel.slice(0, -(1 + overFixedLength)) + "…";
              tooLong = true;
            }
          }
          if (padding) {
            if (isFirst && (isLast || tooLong)) {
              cssProperties.padding = `1px ${Math.max(1, fontSize / 4) | 0}px`;
              cssProperties.borderRadius = `${fontSize / 4 | 0}px`;
            } else if (isFirst) {
              cssProperties.padding = `1px 0 1px ${Math.max(1, fontSize / 4) | 0}px`;
              cssProperties.borderRadius = `${fontSize / 4 | 0}px 0 0 ${fontSize / 4 | 0}px`;
            } else if (isLast || tooLong) {
              cssProperties.padding = `1px ${Math.max(1, fontSize / 4) | 0}px 1px 0`;
              cssProperties.borderRadius = `0 ${fontSize / 4 | 0}px ${fontSize / 4 | 0}px 0`;
            } else {
              cssProperties.padding = `1px 0 1px 0`;
            }
          }
          addInjectedText(item, this._ruleFactory.createClassNameRef(cssProperties), fixSpace(textlabel), isLast && !item.hint.paddingRight ? InjectedTextCursorStops$1.Right : InjectedTextCursorStops$1.None, new RenderedInlayHintLabelPart(item, i3));
          if (tooLong) {
            break;
          }
        }
        if (itemFixedLength !== void 0 && itemActualLength < itemFixedLength) {
          const pad = itemFixedLength - itemActualLength;
          addInjectedText(item, this._ruleFactory.createClassNameRef({}), " ".repeat(pad), InjectedTextCursorStops$1.None);
        }
        if (item.hint.paddingRight) {
          addInjectedWhitespace(item, true);
        }
        if (newDecorationsData.length > InlayHintsController_1._MAX_DECORATORS) {
          break;
        }
      }
      const decorationIdsToReplace = [];
      for (const [id, metadata] of this._decorationsMetadata) {
        const range2 = this._editor.getModel()?.getDecorationRange(id);
        if (range2 && ranges.some((r) => r.containsRange(range2))) {
          decorationIdsToReplace.push(id);
          metadata.classNameRef.dispose();
          this._decorationsMetadata.delete(id);
        }
      }
      const scrollState = StableEditorScrollState.capture(this._editor);
      this._editor.changeDecorations((accessor) => {
        const newDecorationIds = accessor.deltaDecorations(decorationIdsToReplace, newDecorationsData.map((d) => d.decoration));
        for (let i2 = 0; i2 < newDecorationIds.length; i2++) {
          const data = newDecorationsData[i2];
          this._decorationsMetadata.set(newDecorationIds[i2], data);
        }
      });
      scrollState.restore(this._editor);
    }
    _fillInColors(props, hint) {
      if (hint.kind === InlayHintKind$1.Parameter) {
        props.backgroundColor = themeColorFromId(editorInlayHintParameterBackground);
        props.color = themeColorFromId(editorInlayHintParameterForeground);
      } else if (hint.kind === InlayHintKind$1.Type) {
        props.backgroundColor = themeColorFromId(editorInlayHintTypeBackground);
        props.color = themeColorFromId(editorInlayHintTypeForeground);
      } else {
        props.backgroundColor = themeColorFromId(editorInlayHintBackground);
        props.color = themeColorFromId(editorInlayHintForeground);
      }
    }
    _getLayoutInfo() {
      const options = this._editor.getOption(
        159
        /* EditorOption.inlayHints */
      );
      const padding = options.padding;
      const editorFontSize = this._editor.getOption(
        61
        /* EditorOption.fontSize */
      );
      const editorFontFamily = this._editor.getOption(
        58
        /* EditorOption.fontFamily */
      );
      let fontSize = options.fontSize;
      if (!fontSize || fontSize < 5 || fontSize > editorFontSize) {
        fontSize = editorFontSize;
      }
      const fontFamily = options.fontFamily || editorFontFamily;
      const isUniform = !padding && fontFamily === editorFontFamily && fontSize === editorFontSize;
      return { fontSize, fontFamily, padding, isUniform };
    }
    _removeAllDecorations() {
      this._editor.removeDecorations(Array.from(this._decorationsMetadata.keys()));
      for (const obj of this._decorationsMetadata.values()) {
        obj.classNameRef.dispose();
      }
      this._decorationsMetadata.clear();
    }
  }, InlayHintsController_1 = _L, _L.ID = "editor.contrib.InlayHints", _L._MAX_DECORATORS = 1500, _L._whitespaceData = {}, _L);
  InlayHintsController = InlayHintsController_1 = __decorate$1Y([
    __param$1X(1, ILanguageFeaturesService),
    __param$1X(2, ILanguageFeatureDebounceService),
    __param$1X(3, IInlayHintsCache),
    __param$1X(4, ICommandService),
    __param$1X(5, INotificationService),
    __param$1X(6, IInstantiationService)
  ], InlayHintsController);
  function fixSpace(str) {
    const noBreakWhitespace2 = " ";
    return str.replace(/[ \t]/g, noBreakWhitespace2);
  }
  CommandsRegistry.registerCommand("_executeInlayHintProvider", async (accessor, ...args) => {
    const [uri, range2] = args;
    assertType(URI.isUri(uri));
    assertType(Range$2.isIRange(range2));
    const { inlayHintsProvider } = accessor.get(ILanguageFeaturesService);
    const ref = await accessor.get(ITextModelService).createModelReference(uri);
    try {
      const model = await InlayHintsFragments.create(inlayHintsProvider, ref.object.textEditorModel, [Range$2.lift(range2)], CancellationToken.None);
      const result = model.items.map((i2) => i2.hint);
      setTimeout(() => model.dispose(), 0);
      return result;
    } finally {
      ref.dispose();
    }
  });
  var __decorate$1X = 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$1W = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  class InlayHintsHoverAnchor extends HoverForeignElementAnchor {
    constructor(part, owner, initialMousePosX, initialMousePosY) {
      super(10, owner, part.item.anchor.range, initialMousePosX, initialMousePosY, true);
      this.part = part;
    }
  }
  let InlayHintsHover = class InlayHintsHover extends MarkdownHoverParticipant {
    constructor(editor2, markdownRendererService, keybindingService, hoverService, configurationService, _resolverService, languageFeaturesService, commandService) {
      super(editor2, markdownRendererService, configurationService, languageFeaturesService, keybindingService, hoverService, commandService);
      this._resolverService = _resolverService;
      this.hoverOrdinal = 6;
    }
    suggestHoverAnchor(mouseEvent) {
      const controller = InlayHintsController.get(this._editor);
      if (!controller) {
        return null;
      }
      if (mouseEvent.target.type !== 6) {
        return null;
      }
      const options = mouseEvent.target.detail.injectedText?.options;
      if (!(options instanceof ModelDecorationInjectedTextOptions && options.attachedData instanceof RenderedInlayHintLabelPart)) {
        return null;
      }
      return new InlayHintsHoverAnchor(options.attachedData, this, mouseEvent.event.posx, mouseEvent.event.posy);
    }
    computeSync() {
      return [];
    }
    computeAsync(anchor, _lineDecorations, source, token) {
      if (!(anchor instanceof InlayHintsHoverAnchor)) {
        return AsyncIterableProducer.EMPTY;
      }
      return new AsyncIterableProducer(async (executor) => {
        const { part } = anchor;
        await part.item.resolve(token);
        if (token.isCancellationRequested) {
          return;
        }
        let itemTooltip;
        if (typeof part.item.hint.tooltip === "string") {
          itemTooltip = new MarkdownString().appendText(part.item.hint.tooltip);
        } else if (part.item.hint.tooltip) {
          itemTooltip = part.item.hint.tooltip;
        }
        if (itemTooltip) {
          executor.emitOne(new MarkdownHover(this, anchor.range, [itemTooltip], false, 0));
        }
        if (isNonEmptyArray(part.item.hint.textEdits)) {
          executor.emitOne(new MarkdownHover(this, anchor.range, [new MarkdownString().appendText(localize(1164, "Double-click to insert"))], false, 10001));
        }
        let partTooltip;
        if (typeof part.part.tooltip === "string") {
          partTooltip = new MarkdownString().appendText(part.part.tooltip);
        } else if (part.part.tooltip) {
          partTooltip = part.part.tooltip;
        }
        if (partTooltip) {
          executor.emitOne(new MarkdownHover(this, anchor.range, [partTooltip], false, 1));
        }
        if (part.part.location || part.part.command) {
          let linkHint;
          const useMetaKey = this._editor.getOption(
            86
            /* EditorOption.multiCursorModifier */
          ) === "altKey";
          const kb = useMetaKey ? isMacintosh ? localize(1165, "cmd + click") : localize(1166, "ctrl + click") : isMacintosh ? localize(1167, "option + click") : localize(1168, "alt + click");
          if (part.part.location && part.part.command) {
            linkHint = new MarkdownString().appendText(localize(1169, "Go to Definition ({0}), right click for more", kb));
          } else if (part.part.location) {
            linkHint = new MarkdownString().appendText(localize(1170, "Go to Definition ({0})", kb));
          } else if (part.part.command) {
            linkHint = new MarkdownString(`[${localize(1171, "Execute Command")}](${asCommandLink(part.part.command)} "${part.part.command.title}") (${kb})`, { isTrusted: true });
          }
          if (linkHint) {
            executor.emitOne(new MarkdownHover(this, anchor.range, [linkHint], false, 1e4));
          }
        }
        const iterable = this._resolveInlayHintLabelPartHover(part, token);
        for await (const item of iterable) {
          executor.emitOne(item);
        }
      });
    }
    async *_resolveInlayHintLabelPartHover(part, token) {
      if (!part.part.location) {
        return;
      }
      const { uri, range: range2 } = part.part.location;
      const ref = await this._resolverService.createModelReference(uri);
      try {
        const model = ref.object.textEditorModel;
        if (!this._languageFeaturesService.hoverProvider.has(model)) {
          return;
        }
        for await (const item of getHoverProviderResultsAsAsyncIterable(this._languageFeaturesService.hoverProvider, model, new Position$1(range2.startLineNumber, range2.startColumn), token)) {
          if (!isEmptyMarkdownString(item.hover.contents)) {
            yield new MarkdownHover(this, part.item.anchor.range, item.hover.contents, false, 2 + item.ordinal);
          }
        }
      } finally {
        ref.dispose();
      }
    }
  };
  InlayHintsHover = __decorate$1X([
    __param$1W(1, IMarkdownRendererService),
    __param$1W(2, IKeybindingService),
    __param$1W(3, IHoverService),
    __param$1W(4, IConfigurationService),
    __param$1W(5, ITextModelService),
    __param$1W(6, ILanguageFeaturesService),
    __param$1W(7, ICommandService)
  ], InlayHintsHover);
  var __decorate$1W = 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$1V = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  class MarkerCoordinate {
    constructor(marker, index, total) {
      this.marker = marker;
      this.index = index;
      this.total = total;
    }
  }
  let MarkerList = class MarkerList {
    constructor(resourceFilter, _markerService, _configService) {
      this._markerService = _markerService;
      this._configService = _configService;
      this._onDidChange = new Emitter$1();
      this.onDidChange = this._onDidChange.event;
      this._dispoables = new DisposableStore();
      this._markers = [];
      this._nextIdx = -1;
      if (URI.isUri(resourceFilter)) {
        this._resourceFilter = (uri) => uri.toString() === resourceFilter.toString();
      } else if (resourceFilter) {
        this._resourceFilter = resourceFilter;
      }
      const compareOrder = this._configService.getValue("problems.sortOrder");
      const compareMarker = (a, b) => {
        let res = compare(a.resource.toString(), b.resource.toString());
        if (res === 0) {
          if (compareOrder === "position") {
            res = Range$2.compareRangesUsingStarts(a, b) || MarkerSeverity$2.compare(a.severity, b.severity);
          } else {
            res = MarkerSeverity$2.compare(a.severity, b.severity) || Range$2.compareRangesUsingStarts(a, b);
          }
        }
        return res;
      };
      const updateMarker = () => {
        let newMarkers = this._markerService.read({
          resource: URI.isUri(resourceFilter) ? resourceFilter : void 0,
          severities: MarkerSeverity$2.Error | MarkerSeverity$2.Warning | MarkerSeverity$2.Info
        });
        if (typeof resourceFilter === "function") {
          newMarkers = newMarkers.filter((m) => this._resourceFilter(m.resource));
        }
        newMarkers.sort(compareMarker);
        if (equals$1(newMarkers, this._markers, (a, b) => a.resource.toString() === b.resource.toString() && a.startLineNumber === b.startLineNumber && a.startColumn === b.startColumn && a.endLineNumber === b.endLineNumber && a.endColumn === b.endColumn && a.severity === b.severity && a.message === b.message)) {
          return false;
        }
        this._markers = newMarkers;
        return true;
      };
      updateMarker();
      this._dispoables.add(_markerService.onMarkerChanged((uris) => {
        if (!this._resourceFilter || uris.some((uri) => this._resourceFilter(uri))) {
          if (updateMarker()) {
            this._nextIdx = -1;
            this._onDidChange.fire();
          }
        }
      }));
    }
    dispose() {
      this._dispoables.dispose();
      this._onDidChange.dispose();
    }
    matches(uri) {
      if (!this._resourceFilter && !uri) {
        return true;
      }
      if (!this._resourceFilter || !uri) {
        return false;
      }
      return this._resourceFilter(uri);
    }
    get selected() {
      const marker = this._markers[this._nextIdx];
      return marker && new MarkerCoordinate(marker, this._nextIdx + 1, this._markers.length);
    }
    _initIdx(model, position, fwd) {
      let idx = this._markers.findIndex((marker) => isEqual(marker.resource, model.uri));
      if (idx < 0) {
        idx = binarySearch2(this._markers.length, (idx2) => compare(this._markers[idx2].resource.toString(), model.uri.toString()));
        if (idx < 0) {
          idx = ~idx;
        }
        if (fwd) {
          this._nextIdx = idx;
        } else {
          this._nextIdx = (this._markers.length + idx - 1) % this._markers.length;
        }
      } else {
        let found = false;
        let wentPast = false;
        for (let i2 = idx; i2 < this._markers.length; i2++) {
          let range2 = Range$2.lift(this._markers[i2]);
          if (range2.isEmpty()) {
            const word = model.getWordAtPosition(range2.getStartPosition());
            if (word) {
              range2 = new Range$2(range2.startLineNumber, word.startColumn, range2.startLineNumber, word.endColumn);
            }
          }
          if (position && (range2.containsPosition(position) || position.isBeforeOrEqual(range2.getStartPosition()))) {
            this._nextIdx = i2;
            found = true;
            wentPast = !range2.containsPosition(position);
            break;
          }
          if (this._markers[i2].resource.toString() !== model.uri.toString()) {
            break;
          }
        }
        if (!found) {
          this._nextIdx = fwd ? 0 : this._markers.length - 1;
        } else if (wentPast && !fwd) {
          this._nextIdx -= 1;
        }
      }
      if (this._nextIdx < 0) {
        this._nextIdx = this._markers.length - 1;
      }
    }
    resetIndex() {
      this._nextIdx = -1;
    }
    move(fwd, model, position) {
      if (this._markers.length === 0) {
        return false;
      }
      const oldIdx = this._nextIdx;
      if (this._nextIdx === -1) {
        this._initIdx(model, position, fwd);
      } else if (fwd) {
        this._nextIdx = (this._nextIdx + 1) % this._markers.length;
      } else if (!fwd) {
        this._nextIdx = (this._nextIdx - 1 + this._markers.length) % this._markers.length;
      }
      if (oldIdx !== this._nextIdx) {
        return true;
      }
      return false;
    }
    find(uri, position) {
      let idx = this._markers.findIndex((marker) => marker.resource.toString() === uri.toString());
      if (idx < 0) {
        return void 0;
      }
      for (; idx < this._markers.length; idx++) {
        if (Range$2.containsPosition(this._markers[idx], position)) {
          return new MarkerCoordinate(this._markers[idx], idx + 1, this._markers.length);
        }
      }
      return void 0;
    }
  };
  MarkerList = __decorate$1W([
    __param$1V(1, IMarkerService),
    __param$1V(2, IConfigurationService)
  ], MarkerList);
  const IMarkerNavigationService = createDecorator("IMarkerNavigationService");
  let MarkerNavigationService = class MarkerNavigationService {
    constructor(_markerService, _configService) {
      this._markerService = _markerService;
      this._configService = _configService;
      this._provider = new LinkedList();
    }
    getMarkerList(resource) {
      for (const provider of this._provider) {
        const result = provider.getMarkerList(resource);
        if (result) {
          return result;
        }
      }
      return new MarkerList(resource, this._markerService, this._configService);
    }
  };
  MarkerNavigationService = __decorate$1W([
    __param$1V(0, IMarkerService),
    __param$1V(1, IConfigurationService)
  ], MarkerNavigationService);
  registerSingleton(
    IMarkerNavigationService,
    MarkerNavigationService,
    1
    /* InstantiationType.Delayed */
  );
  var SeverityIcon;
  (function(SeverityIcon2) {
    function className2(severity) {
      switch (severity) {
        case Severity$2.Ignore:
          return "severity-ignore " + ThemeIcon.asClassName(Codicon.info);
        case Severity$2.Info:
          return ThemeIcon.asClassName(Codicon.info);
        case Severity$2.Warning:
          return ThemeIcon.asClassName(Codicon.warning);
        case Severity$2.Error:
          return ThemeIcon.asClassName(Codicon.error);
        default:
          return "";
      }
    }
    SeverityIcon2.className = className2;
  })(SeverityIcon || (SeverityIcon = {}));
  var __decorate$1V = 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$1U = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  var MarkerNavigationWidget_1;
  class MessageWidget {
    constructor(parent, editor2, onRelatedInformation, _openerService, _labelService) {
      this._openerService = _openerService;
      this._labelService = _labelService;
      this._lines = 0;
      this._longestLineLength = 0;
      this._relatedDiagnostics = /* @__PURE__ */ new WeakMap();
      this._disposables = new DisposableStore();
      this._editor = editor2;
      const domNode = document.createElement("div");
      domNode.className = "descriptioncontainer";
      this._messageBlock = document.createElement("div");
      this._messageBlock.classList.add("message");
      this._messageBlock.setAttribute("aria-live", "assertive");
      this._messageBlock.setAttribute("role", "alert");
      domNode.appendChild(this._messageBlock);
      this._relatedBlock = document.createElement("div");
      domNode.appendChild(this._relatedBlock);
      this._disposables.add(addStandardDisposableListener(this._relatedBlock, "click", (event) => {
        event.preventDefault();
        const related = this._relatedDiagnostics.get(event.target);
        if (related) {
          onRelatedInformation(related);
        }
      }));
      this._scrollable = new ScrollableElement(domNode, {
        horizontal: 1,
        vertical: 1,
        useShadows: false,
        horizontalScrollbarSize: 6,
        verticalScrollbarSize: 6
      });
      parent.appendChild(this._scrollable.getDomNode());
      this._disposables.add(this._scrollable.onScroll((e) => {
        domNode.style.left = `-${e.scrollLeft}px`;
        domNode.style.top = `-${e.scrollTop}px`;
      }));
      this._disposables.add(this._scrollable);
    }
    dispose() {
      dispose(this._disposables);
    }
    update(marker) {
      const { source, message, relatedInformation, code } = marker;
      let sourceAndCodeLength = (source?.length || 0) + "()".length;
      if (code) {
        if (typeof code === "string") {
          sourceAndCodeLength += code.length;
        } else {
          sourceAndCodeLength += code.value.length;
        }
      }
      const lines = splitLines(message);
      this._lines = lines.length;
      this._longestLineLength = 0;
      for (const line of lines) {
        this._longestLineLength = Math.max(line.length + sourceAndCodeLength, this._longestLineLength);
      }
      clearNode(this._messageBlock);
      this._messageBlock.setAttribute("aria-label", this.getAriaLabel(marker));
      this._editor.applyFontInfo(this._messageBlock);
      let lastLineElement = this._messageBlock;
      for (const line of lines) {
        lastLineElement = document.createElement("div");
        lastLineElement.innerText = line;
        if (line === "") {
          lastLineElement.style.height = this._messageBlock.style.lineHeight;
        }
        this._messageBlock.appendChild(lastLineElement);
      }
      if (source || code) {
        const detailsElement = document.createElement("span");
        detailsElement.classList.add("details");
        lastLineElement.appendChild(detailsElement);
        if (source) {
          const sourceElement = document.createElement("span");
          sourceElement.innerText = source;
          sourceElement.classList.add("source");
          detailsElement.appendChild(sourceElement);
        }
        if (code) {
          if (typeof code === "string") {
            const codeElement = document.createElement("span");
            codeElement.innerText = `(${code})`;
            codeElement.classList.add("code");
            detailsElement.appendChild(codeElement);
          } else {
            this._codeLink = $$l("a.code-link");
            this._codeLink.setAttribute("href", `${code.target.toString()}`);
            this._codeLink.onclick = (e) => {
              this._openerService.open(code.target, { allowCommands: true });
              e.preventDefault();
              e.stopPropagation();
            };
            const codeElement = append$2(this._codeLink, $$l("span"));
            codeElement.innerText = code.value;
            detailsElement.appendChild(this._codeLink);
          }
        }
      }
      clearNode(this._relatedBlock);
      this._editor.applyFontInfo(this._relatedBlock);
      if (isNonEmptyArray(relatedInformation)) {
        const relatedInformationNode = this._relatedBlock.appendChild(document.createElement("div"));
        relatedInformationNode.style.paddingTop = `${Math.floor(this._editor.getOption(
          75
          /* EditorOption.lineHeight */
        ) * 0.66)}px`;
        this._lines += 1;
        for (const related of relatedInformation) {
          const container = document.createElement("div");
          const relatedResource = document.createElement("a");
          relatedResource.classList.add("filename");
          relatedResource.innerText = `${this._labelService.getUriBasenameLabel(related.resource)}(${related.startLineNumber}, ${related.startColumn}): `;
          relatedResource.title = this._labelService.getUriLabel(related.resource);
          this._relatedDiagnostics.set(relatedResource, related);
          const relatedMessage = document.createElement("span");
          relatedMessage.innerText = related.message;
          container.appendChild(relatedResource);
          container.appendChild(relatedMessage);
          this._lines += 1;
          relatedInformationNode.appendChild(container);
        }
      }
      const fontInfo = this._editor.getOption(
        59
        /* EditorOption.fontInfo */
      );
      const scrollWidth = Math.ceil(fontInfo.typicalFullwidthCharacterWidth * this._longestLineLength * 0.75);
      const scrollHeight = fontInfo.lineHeight * this._lines;
      this._scrollable.setScrollDimensions({ scrollWidth, scrollHeight });
    }
    layout(height, width2) {
      this._scrollable.getDomNode().style.height = `${height}px`;
      this._scrollable.getDomNode().style.width = `${width2}px`;
      this._scrollable.setScrollDimensions({ width: width2, height });
    }
    getHeightInLines() {
      return Math.min(17, this._lines);
    }
    getAriaLabel(marker) {
      let severityLabel = "";
      switch (marker.severity) {
        case MarkerSeverity$2.Error:
          severityLabel = localize(1024, "Error");
          break;
        case MarkerSeverity$2.Warning:
          severityLabel = localize(1025, "Warning");
          break;
        case MarkerSeverity$2.Info:
          severityLabel = localize(1026, "Info");
          break;
        case MarkerSeverity$2.Hint:
          severityLabel = localize(1027, "Hint");
          break;
      }
      let ariaLabel = localize(1028, "{0} at {1}. ", severityLabel, marker.startLineNumber + ":" + marker.startColumn);
      const model = this._editor.getModel();
      if (model && marker.startLineNumber <= model.getLineCount() && marker.startLineNumber >= 1) {
        const lineContent = model.getLineContent(marker.startLineNumber);
        ariaLabel = `${lineContent}, ${ariaLabel}`;
      }
      return ariaLabel;
    }
  }
  let MarkerNavigationWidget = (_M = class extends PeekViewWidget {
    constructor(editor2, _themeService, _openerService, _menuService, instantiationService, _contextKeyService, _labelService) {
      super(editor2, { showArrow: true, showFrame: true, isAccessible: true, frameWidth: 1 }, instantiationService);
      this._themeService = _themeService;
      this._openerService = _openerService;
      this._menuService = _menuService;
      this._contextKeyService = _contextKeyService;
      this._labelService = _labelService;
      this._callOnDispose = new DisposableStore();
      this._onDidSelectRelatedInformation = new Emitter$1();
      this.onDidSelectRelatedInformation = this._onDidSelectRelatedInformation.event;
      this._severity = MarkerSeverity$2.Warning;
      this._backgroundColor = Color.white;
      this._applyTheme(_themeService.getColorTheme());
      this._callOnDispose.add(_themeService.onDidColorThemeChange(this._applyTheme.bind(this)));
      this.create();
    }
    _applyTheme(theme) {
      this._backgroundColor = theme.getColor(editorMarkerNavigationBackground);
      let colorId = editorMarkerNavigationError;
      let headerBackground = editorMarkerNavigationErrorHeader;
      if (this._severity === MarkerSeverity$2.Warning) {
        colorId = editorMarkerNavigationWarning;
        headerBackground = editorMarkerNavigationWarningHeader;
      } else if (this._severity === MarkerSeverity$2.Info) {
        colorId = editorMarkerNavigationInfo;
        headerBackground = editorMarkerNavigationInfoHeader;
      }
      const frameColor = theme.getColor(colorId);
      const headerBg = theme.getColor(headerBackground);
      this.style({
        arrowColor: frameColor,
        frameColor,
        headerBackgroundColor: headerBg,
        primaryHeadingColor: theme.getColor(peekViewTitleForeground),
        secondaryHeadingColor: theme.getColor(peekViewTitleInfoForeground)
      });
    }
    _applyStyles() {
      if (this._parentContainer) {
        this._parentContainer.style.backgroundColor = this._backgroundColor ? this._backgroundColor.toString() : "";
      }
      super._applyStyles();
    }
    dispose() {
      this._callOnDispose.dispose();
      super.dispose();
    }
    _fillHead(container) {
      super._fillHead(container);
      this._disposables.add(this._actionbarWidget.actionRunner.onWillRun((e) => this.editor.focus()));
      const menu = this._menuService.getMenuActions(MarkerNavigationWidget_1.TitleMenu, this._contextKeyService);
      const actions = getFlatActionBarActions(menu);
      this._actionbarWidget.push(actions, { label: false, icon: true, index: 0 });
    }
    _fillTitleIcon(container) {
      this._icon = append$2(container, $$l(""));
    }
    _fillBody(container) {
      this._parentContainer = container;
      container.classList.add("marker-widget");
      this._parentContainer.tabIndex = 0;
      this._parentContainer.setAttribute("role", "tooltip");
      this._container = document.createElement("div");
      container.appendChild(this._container);
      this._message = new MessageWidget(this._container, this.editor, (related) => this._onDidSelectRelatedInformation.fire(related), this._openerService, this._labelService);
      this._disposables.add(this._message);
    }
    show() {
      throw new Error("call showAtMarker");
    }
    showAtMarker(marker, markerIdx, markerCount) {
      this._container.classList.remove("stale");
      this._message.update(marker);
      this._severity = marker.severity;
      this._applyTheme(this._themeService.getColorTheme());
      const range2 = Range$2.lift(marker);
      const editorPosition = this.editor.getPosition();
      const position = editorPosition && range2.containsPosition(editorPosition) ? editorPosition : range2.getStartPosition();
      super.show(position, this.computeRequiredHeight());
      const model = this.editor.getModel();
      if (model) {
        const detail = markerCount > 1 ? localize(1029, "{0} of {1} problems", markerIdx, markerCount) : localize(1030, "{0} of {1} problem", markerIdx, markerCount);
        this.setTitle(basename(model.uri), detail);
      }
      this._icon.className = `codicon ${SeverityIcon.className(MarkerSeverity$2.toSeverity(this._severity))}`;
      this.editor.revealPositionNearTop(
        position,
        0
        /* ScrollType.Smooth */
      );
      this.editor.focus();
    }
    updateMarker(marker) {
      this._container.classList.remove("stale");
      this._message.update(marker);
    }
    showStale() {
      this._container.classList.add("stale");
      this._relayout();
    }
    _doLayoutBody(heightInPixel, widthInPixel) {
      super._doLayoutBody(heightInPixel, widthInPixel);
      this._heightInPixel = heightInPixel;
      this._message.layout(heightInPixel, widthInPixel);
      this._container.style.height = `${heightInPixel}px`;
    }
    _onWidth(widthInPixel) {
      this._message.layout(this._heightInPixel, widthInPixel);
    }
    _relayout() {
      super._relayout(this.computeRequiredHeight());
    }
    computeRequiredHeight() {
      return 3 + this._message.getHeightInLines();
    }
  }, MarkerNavigationWidget_1 = _M, _M.TitleMenu = new MenuId("gotoErrorTitleMenu"), _M);
  MarkerNavigationWidget = MarkerNavigationWidget_1 = __decorate$1V([
    __param$1U(1, IThemeService),
    __param$1U(2, IOpenerService),
    __param$1U(3, IMenuService),
    __param$1U(4, IInstantiationService),
    __param$1U(5, IContextKeyService),
    __param$1U(6, ILabelService)
  ], MarkerNavigationWidget);
  const errorDefault = oneOf(editorErrorForeground, editorErrorBorder);
  const warningDefault = oneOf(editorWarningForeground, editorWarningBorder);
  const infoDefault = oneOf(editorInfoForeground, editorInfoBorder);
  const editorMarkerNavigationError = registerColor("editorMarkerNavigationError.background", { dark: errorDefault, light: errorDefault, hcDark: contrastBorder, hcLight: contrastBorder }, localize(1031, "Editor marker navigation widget error color."));
  const editorMarkerNavigationErrorHeader = registerColor("editorMarkerNavigationError.headerBackground", { dark: transparent(editorMarkerNavigationError, 0.1), light: transparent(editorMarkerNavigationError, 0.1), hcDark: null, hcLight: null }, localize(1032, "Editor marker navigation widget error heading background."));
  const editorMarkerNavigationWarning = registerColor("editorMarkerNavigationWarning.background", { dark: warningDefault, light: warningDefault, hcDark: contrastBorder, hcLight: contrastBorder }, localize(1033, "Editor marker navigation widget warning color."));
  const editorMarkerNavigationWarningHeader = registerColor("editorMarkerNavigationWarning.headerBackground", { dark: transparent(editorMarkerNavigationWarning, 0.1), light: transparent(editorMarkerNavigationWarning, 0.1), hcDark: "#0C141F", hcLight: transparent(editorMarkerNavigationWarning, 0.2) }, localize(1034, "Editor marker navigation widget warning heading background."));
  const editorMarkerNavigationInfo = registerColor("editorMarkerNavigationInfo.background", { dark: infoDefault, light: infoDefault, hcDark: contrastBorder, hcLight: contrastBorder }, localize(1035, "Editor marker navigation widget info color."));
  const editorMarkerNavigationInfoHeader = registerColor("editorMarkerNavigationInfo.headerBackground", { dark: transparent(editorMarkerNavigationInfo, 0.1), light: transparent(editorMarkerNavigationInfo, 0.1), hcDark: null, hcLight: null }, localize(1036, "Editor marker navigation widget info heading background."));
  const editorMarkerNavigationBackground = registerColor("editorMarkerNavigation.background", editorBackground, localize(1037, "Editor marker navigation widget background."));
  var __decorate$1U = 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$1T = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  var MarkerController_1;
  let MarkerController = (_N = class {
    static get(editor2) {
      return editor2.getContribution(MarkerController_1.ID);
    }
    constructor(editor2, _markerNavigationService, _contextKeyService, _editorService, _instantiationService) {
      this._markerNavigationService = _markerNavigationService;
      this._contextKeyService = _contextKeyService;
      this._editorService = _editorService;
      this._instantiationService = _instantiationService;
      this._sessionDispoables = new DisposableStore();
      this._editor = editor2;
      this._widgetVisible = CONTEXT_MARKERS_NAVIGATION_VISIBLE.bindTo(this._contextKeyService);
    }
    dispose() {
      this._cleanUp();
      this._sessionDispoables.dispose();
    }
    _cleanUp() {
      this._widgetVisible.reset();
      this._sessionDispoables.clear();
      this._widget = void 0;
      this._model = void 0;
    }
    _getOrCreateModel(uri) {
      if (this._model && this._model.matches(uri)) {
        return this._model;
      }
      let reusePosition = false;
      if (this._model) {
        reusePosition = true;
        this._cleanUp();
      }
      this._model = this._markerNavigationService.getMarkerList(uri);
      if (reusePosition) {
        this._model.move(true, this._editor.getModel(), this._editor.getPosition());
      }
      this._widget = this._instantiationService.createInstance(MarkerNavigationWidget, this._editor);
      this._widget.onDidClose(() => this.close(), this, this._sessionDispoables);
      this._widgetVisible.set(true);
      this._sessionDispoables.add(this._model);
      this._sessionDispoables.add(this._widget);
      this._sessionDispoables.add(this._editor.onDidChangeCursorPosition((e) => {
        if (!this._model?.selected || !Range$2.containsPosition(this._model?.selected.marker, e.position)) {
          this._model?.resetIndex();
        }
      }));
      this._sessionDispoables.add(this._model.onDidChange(() => {
        if (!this._widget || !this._widget.position || !this._model) {
          return;
        }
        const info = this._model.find(this._editor.getModel().uri, this._widget.position);
        if (info) {
          this._widget.updateMarker(info.marker);
        } else {
          this._widget.showStale();
        }
      }));
      this._sessionDispoables.add(this._widget.onDidSelectRelatedInformation((related) => {
        this._editorService.openCodeEditor({
          resource: related.resource,
          options: { pinned: true, revealIfOpened: true, selection: Range$2.lift(related).collapseToStart() }
        }, this._editor);
        this.close(false);
      }));
      this._sessionDispoables.add(this._editor.onDidChangeModel(() => this._cleanUp()));
      return this._model;
    }
    close(focusEditor = true) {
      this._cleanUp();
      if (focusEditor) {
        this._editor.focus();
      }
    }
    showAtMarker(marker) {
      if (!this._editor.hasModel()) {
        return;
      }
      const textModel = this._editor.getModel();
      const model = this._getOrCreateModel(textModel.uri);
      model.resetIndex();
      model.move(true, textModel, new Position$1(marker.startLineNumber, marker.startColumn));
      if (model.selected) {
        this._widget.showAtMarker(model.selected.marker, model.selected.index, model.selected.total);
      }
    }
    async navigate(next, multiFile) {
      if (!this._editor.hasModel()) {
        return;
      }
      const textModel = this._editor.getModel();
      const model = this._getOrCreateModel(multiFile ? void 0 : textModel.uri);
      model.move(next, textModel, this._editor.getPosition());
      if (!model.selected) {
        return;
      }
      if (model.selected.marker.resource.toString() !== textModel.uri.toString()) {
        this._cleanUp();
        const otherEditor = await this._editorService.openCodeEditor({
          resource: model.selected.marker.resource,
          options: { pinned: false, revealIfOpened: true, selectionRevealType: 2, selection: model.selected.marker }
        }, this._editor);
        if (otherEditor) {
          MarkerController_1.get(otherEditor)?.close();
          MarkerController_1.get(otherEditor)?.navigate(next, multiFile);
        }
      } else {
        this._widget.showAtMarker(model.selected.marker, model.selected.index, model.selected.total);
      }
    }
  }, MarkerController_1 = _N, _N.ID = "editor.contrib.markerController", _N);
  MarkerController = MarkerController_1 = __decorate$1U([
    __param$1T(1, IMarkerNavigationService),
    __param$1T(2, IContextKeyService),
    __param$1T(3, ICodeEditorService),
    __param$1T(4, IInstantiationService)
  ], MarkerController);
  class MarkerNavigationAction extends EditorAction {
    constructor(_next, _multiFile, opts) {
      super(opts);
      this._next = _next;
      this._multiFile = _multiFile;
    }
    async run(_accessor, editor2) {
      if (editor2.hasModel()) {
        await MarkerController.get(editor2)?.navigate(this._next, this._multiFile);
      }
    }
  }
  const _NextMarkerAction = class _NextMarkerAction extends MarkerNavigationAction {
    constructor() {
      super(true, false, {
        id: _NextMarkerAction.ID,
        label: _NextMarkerAction.LABEL,
        precondition: void 0,
        kbOpts: {
          kbExpr: EditorContextKeys.focus,
          primary: 512 | 66,
          weight: 100
          /* KeybindingWeight.EditorContrib */
        },
        menuOpts: {
          menuId: MarkerNavigationWidget.TitleMenu,
          title: _NextMarkerAction.LABEL.value,
          icon: registerIcon("marker-navigation-next", Codicon.arrowDown, localize(1016, "Icon for goto next marker.")),
          group: "navigation",
          order: 1
        }
      });
    }
  };
  _NextMarkerAction.ID = "editor.action.marker.next";
  _NextMarkerAction.LABEL = localize2(1020, "Go to Next Problem (Error, Warning, Info)");
  let NextMarkerAction = _NextMarkerAction;
  const _PrevMarkerAction = class _PrevMarkerAction extends MarkerNavigationAction {
    constructor() {
      super(false, false, {
        id: _PrevMarkerAction.ID,
        label: _PrevMarkerAction.LABEL,
        precondition: void 0,
        kbOpts: {
          kbExpr: EditorContextKeys.focus,
          primary: 1024 | 512 | 66,
          weight: 100
          /* KeybindingWeight.EditorContrib */
        },
        menuOpts: {
          menuId: MarkerNavigationWidget.TitleMenu,
          title: _PrevMarkerAction.LABEL.value,
          icon: registerIcon("marker-navigation-previous", Codicon.arrowUp, localize(1017, "Icon for goto previous marker.")),
          group: "navigation",
          order: 2
        }
      });
    }
  };
  _PrevMarkerAction.ID = "editor.action.marker.prev";
  _PrevMarkerAction.LABEL = localize2(1021, "Go to Previous Problem (Error, Warning, Info)");
  let PrevMarkerAction = _PrevMarkerAction;
  class NextMarkerInFilesAction extends MarkerNavigationAction {
    constructor() {
      super(true, true, {
        id: "editor.action.marker.nextInFiles",
        label: localize2(1022, "Go to Next Problem in Files (Error, Warning, Info)"),
        precondition: void 0,
        kbOpts: {
          kbExpr: EditorContextKeys.focus,
          primary: 66,
          weight: 100
          /* KeybindingWeight.EditorContrib */
        },
        menuOpts: {
          menuId: MenuId.MenubarGoMenu,
          title: localize(1018, "Next &&Problem"),
          group: "6_problem_nav",
          order: 1
        }
      });
    }
  }
  class PrevMarkerInFilesAction extends MarkerNavigationAction {
    constructor() {
      super(false, true, {
        id: "editor.action.marker.prevInFiles",
        label: localize2(1023, "Go to Previous Problem in Files (Error, Warning, Info)"),
        precondition: void 0,
        kbOpts: {
          kbExpr: EditorContextKeys.focus,
          primary: 1024 | 66,
          weight: 100
          /* KeybindingWeight.EditorContrib */
        },
        menuOpts: {
          menuId: MenuId.MenubarGoMenu,
          title: localize(1019, "Previous &&Problem"),
          group: "6_problem_nav",
          order: 2
        }
      });
    }
  }
  registerEditorContribution(
    MarkerController.ID,
    MarkerController,
    4
    /* EditorContributionInstantiation.Lazy */
  );
  registerEditorAction(NextMarkerAction);
  registerEditorAction(PrevMarkerAction);
  registerEditorAction(NextMarkerInFilesAction);
  registerEditorAction(PrevMarkerInFilesAction);
  const CONTEXT_MARKERS_NAVIGATION_VISIBLE = new RawContextKey("markersNavigationVisible", false);
  const MarkerCommand = EditorCommand.bindToContribution(MarkerController.get);
  registerEditorCommand(new MarkerCommand({
    id: "closeMarkersNavigation",
    precondition: CONTEXT_MARKERS_NAVIGATION_VISIBLE,
    handler: (x) => x.close(),
    kbOpts: {
      weight: 100 + 50,
      kbExpr: EditorContextKeys.focus,
      primary: 9,
      secondary: [
        1024 | 9
        /* KeyCode.Escape */
      ]
    }
  }));
  var __decorate$1T = 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$1S = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  const $$8 = $$l;
  class MarkerHover {
    constructor(owner, range2, marker) {
      this.owner = owner;
      this.range = range2;
      this.marker = marker;
    }
    isValidForHoverAnchor(anchor) {
      return anchor.type === 1 && this.range.startColumn <= anchor.range.startColumn && this.range.endColumn >= anchor.range.endColumn;
    }
  }
  const markerCodeActionTrigger = {
    type: 1,
    filter: { include: CodeActionKind.QuickFix },
    triggerAction: CodeActionTriggerSource.QuickFixHover
  };
  let MarkerHoverParticipant = class MarkerHoverParticipant {
    constructor(_editor, _markerDecorationsService, _openerService, _languageFeaturesService) {
      this._editor = _editor;
      this._markerDecorationsService = _markerDecorationsService;
      this._openerService = _openerService;
      this._languageFeaturesService = _languageFeaturesService;
      this.hoverOrdinal = 1;
      this.recentMarkerCodeActionsInfo = void 0;
    }
    computeSync(anchor, lineDecorations) {
      if (!this._editor.hasModel() || anchor.type !== 1 && !anchor.supportsMarkerHover) {
        return [];
      }
      const model = this._editor.getModel();
      const anchorRange = anchor.range;
      if (!model.isValidRange(anchor.range)) {
        return [];
      }
      const lineNumber = anchorRange.startLineNumber;
      const maxColumn = model.getLineMaxColumn(lineNumber);
      const result = [];
      for (const d of lineDecorations) {
        const startColumn = d.range.startLineNumber === lineNumber ? d.range.startColumn : 1;
        const endColumn = d.range.endLineNumber === lineNumber ? d.range.endColumn : maxColumn;
        const marker = this._markerDecorationsService.getMarker(model.uri, d);
        if (!marker) {
          continue;
        }
        const range2 = new Range$2(anchor.range.startLineNumber, startColumn, anchor.range.startLineNumber, endColumn);
        result.push(new MarkerHover(this, range2, marker));
      }
      return result;
    }
    renderHoverParts(context, hoverParts) {
      if (!hoverParts.length) {
        return new RenderedHoverParts([]);
      }
      const renderedHoverParts = [];
      hoverParts.forEach((hoverPart) => {
        const renderedMarkerHover = this._renderMarkerHover(hoverPart);
        context.fragment.appendChild(renderedMarkerHover.hoverElement);
        renderedHoverParts.push(renderedMarkerHover);
      });
      const markerHoverForStatusbar = hoverParts.length === 1 ? hoverParts[0] : hoverParts.sort((a, b) => MarkerSeverity$2.compare(a.marker.severity, b.marker.severity))[0];
      const disposables = this._renderMarkerStatusbar(context, markerHoverForStatusbar);
      return new RenderedHoverParts(renderedHoverParts, disposables);
    }
    getAccessibleContent(hoverPart) {
      return hoverPart.marker.message;
    }
    _renderMarkerHover(markerHover) {
      const disposables = new DisposableStore();
      const hoverElement = $$8("div.hover-row");
      const markerElement = append$2(hoverElement, $$8("div.marker.hover-contents"));
      const { source, message, code, relatedInformation } = markerHover.marker;
      this._editor.applyFontInfo(markerElement);
      const messageElement = append$2(markerElement, $$8("span"));
      messageElement.style.whiteSpace = "pre-wrap";
      messageElement.innerText = message;
      if (source || code) {
        if (code && typeof code !== "string") {
          const sourceAndCodeElement = $$8("span");
          if (source) {
            const sourceElement = append$2(sourceAndCodeElement, $$8("span"));
            sourceElement.innerText = source;
          }
          const codeLink = append$2(sourceAndCodeElement, $$8("a.code-link"));
          codeLink.setAttribute("href", code.target.toString(true));
          disposables.add(addDisposableListener(codeLink, "click", (e) => {
            this._openerService.open(code.target, { allowCommands: true });
            e.preventDefault();
            e.stopPropagation();
          }));
          const codeElement = append$2(codeLink, $$8("span"));
          codeElement.innerText = code.value;
          const detailsElement = append$2(markerElement, sourceAndCodeElement);
          detailsElement.style.opacity = "0.6";
          detailsElement.style.paddingLeft = "6px";
        } else {
          const detailsElement = append$2(markerElement, $$8("span"));
          detailsElement.style.opacity = "0.6";
          detailsElement.style.paddingLeft = "6px";
          detailsElement.innerText = source && code ? `${source}(${code})` : source ? source : `(${code})`;
        }
      }
      if (isNonEmptyArray(relatedInformation)) {
        for (const { message: message2, resource, startLineNumber, startColumn } of relatedInformation) {
          const relatedInfoContainer = append$2(markerElement, $$8("div"));
          relatedInfoContainer.style.marginTop = "8px";
          const a = append$2(relatedInfoContainer, $$8("a"));
          a.innerText = `${basename(resource)}(${startLineNumber}, ${startColumn}): `;
          a.style.cursor = "pointer";
          disposables.add(addDisposableListener(a, "click", (e) => {
            e.stopPropagation();
            e.preventDefault();
            if (this._openerService) {
              const editorOptions = { selection: { startLineNumber, startColumn } };
              this._openerService.open(resource, {
                fromUserGesture: true,
                editorOptions
              }).catch(onUnexpectedError);
            }
          }));
          const messageElement2 = append$2(relatedInfoContainer, $$8("span"));
          messageElement2.innerText = message2;
          this._editor.applyFontInfo(messageElement2);
        }
      }
      const renderedHoverPart = {
        hoverPart: markerHover,
        hoverElement,
        dispose: () => disposables.dispose()
      };
      return renderedHoverPart;
    }
    _renderMarkerStatusbar(context, markerHover) {
      const disposables = new DisposableStore();
      if (markerHover.marker.severity === MarkerSeverity$2.Error || markerHover.marker.severity === MarkerSeverity$2.Warning || markerHover.marker.severity === MarkerSeverity$2.Info) {
        const markerController = MarkerController.get(this._editor);
        if (markerController) {
          context.statusBar.addAction({
            label: localize(1139, "View Problem"),
            commandId: NextMarkerAction.ID,
            run: () => {
              context.hide();
              markerController.showAtMarker(markerHover.marker);
              this._editor.focus();
            }
          });
        }
      }
      if (!this._editor.getOption(
        104
        /* EditorOption.readOnly */
      )) {
        const quickfixPlaceholderElement = context.statusBar.append($$8("div"));
        if (this.recentMarkerCodeActionsInfo) {
          if (IMarkerData.makeKey(this.recentMarkerCodeActionsInfo.marker) === IMarkerData.makeKey(markerHover.marker)) {
            if (!this.recentMarkerCodeActionsInfo.hasCodeActions) {
              quickfixPlaceholderElement.textContent = localize(1140, "No quick fixes available");
            }
          } else {
            this.recentMarkerCodeActionsInfo = void 0;
          }
        }
        const updatePlaceholderDisposable = this.recentMarkerCodeActionsInfo && !this.recentMarkerCodeActionsInfo.hasCodeActions ? Disposable.None : disposableTimeout(() => quickfixPlaceholderElement.textContent = localize(1141, "Checking for quick fixes..."), 200, disposables);
        if (!quickfixPlaceholderElement.textContent) {
          quickfixPlaceholderElement.textContent = String.fromCharCode(160);
        }
        const codeActionsPromise = this.getCodeActions(markerHover.marker);
        disposables.add(toDisposable(() => codeActionsPromise.cancel()));
        codeActionsPromise.then((actions) => {
          updatePlaceholderDisposable.dispose();
          this.recentMarkerCodeActionsInfo = { marker: markerHover.marker, hasCodeActions: actions.validActions.length > 0 };
          if (!this.recentMarkerCodeActionsInfo.hasCodeActions) {
            actions.dispose();
            quickfixPlaceholderElement.textContent = localize(1142, "No quick fixes available");
            return;
          }
          quickfixPlaceholderElement.style.display = "none";
          let showing = false;
          disposables.add(toDisposable(() => {
            if (!showing) {
              actions.dispose();
            }
          }));
          context.statusBar.addAction({
            label: localize(1143, "Quick Fix..."),
            commandId: quickFixCommandId,
            run: (target) => {
              showing = true;
              const controller = CodeActionController.get(this._editor);
              const elementPosition = getDomNodePagePosition(target);
              context.hide();
              controller?.showCodeActions(markerCodeActionTrigger, actions, {
                x: elementPosition.left,
                y: elementPosition.top,
                width: elementPosition.width,
                height: elementPosition.height
              });
            }
          });
          const aiCodeAction = actions.validActions.find((action) => action.action.isAI);
          if (aiCodeAction) {
            context.statusBar.addAction({
              label: aiCodeAction.action.title,
              commandId: aiCodeAction.action.command?.id ?? "",
              iconClass: ThemeIcon.asClassName(Codicon.sparkle),
              run: () => {
                const controller = CodeActionController.get(this._editor);
                controller?.applyCodeAction(aiCodeAction, false, false, ApplyCodeActionReason.FromProblemsHover);
              }
            });
          }
          context.onContentsChanged();
        }, onUnexpectedError);
      }
      return disposables;
    }
    getCodeActions(marker) {
      return createCancelablePromise((cancellationToken) => {
        return getCodeActions(this._languageFeaturesService.codeActionProvider, this._editor.getModel(), new Range$2(marker.startLineNumber, marker.startColumn, marker.endLineNumber, marker.endColumn), markerCodeActionTrigger, Progress.None, cancellationToken);
      });
    }
  };
  MarkerHoverParticipant = __decorate$1T([
    __param$1S(1, IMarkerDecorationsService),
    __param$1S(2, IOpenerService),
    __param$1S(3, ILanguageFeaturesService)
  ], MarkerHoverParticipant);
  var __decorate$1S = 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$1R = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  var RenderedContentHover_1, RenderedContentHoverParts_1;
  let RenderedContentHover = RenderedContentHover_1 = class RenderedContentHover extends Disposable {
    constructor(editor2, hoverResult, participants, context, keybindingService, hoverService, clipboardService) {
      super();
      const parts = hoverResult.hoverParts;
      this._renderedHoverParts = this._register(new RenderedContentHoverParts(editor2, participants, parts, context, keybindingService, hoverService, clipboardService));
      const contentHoverComputerOptions = hoverResult.options;
      const anchor = contentHoverComputerOptions.anchor;
      const { showAtPosition, showAtSecondaryPosition } = RenderedContentHover_1.computeHoverPositions(editor2, anchor.range, parts);
      this.shouldAppearBeforeContent = parts.some((m) => m.isBeforeContent);
      this.showAtPosition = showAtPosition;
      this.showAtSecondaryPosition = showAtSecondaryPosition;
      this.initialMousePosX = anchor.initialMousePosX;
      this.initialMousePosY = anchor.initialMousePosY;
      this.shouldFocus = contentHoverComputerOptions.shouldFocus;
      this.source = contentHoverComputerOptions.source;
    }
    get domNode() {
      return this._renderedHoverParts.domNode;
    }
    get domNodeHasChildren() {
      return this._renderedHoverParts.domNodeHasChildren;
    }
    get focusedHoverPartIndex() {
      return this._renderedHoverParts.focusedHoverPartIndex;
    }
    get hoverPartsCount() {
      return this._renderedHoverParts.hoverPartsCount;
    }
    focusHoverPartWithIndex(index) {
      this._renderedHoverParts.focusHoverPartWithIndex(index);
    }
    async updateHoverVerbosityLevel(action, index, focus) {
      this._renderedHoverParts.updateHoverVerbosityLevel(action, index, focus);
    }
    isColorPickerVisible() {
      return this._renderedHoverParts.isColorPickerVisible();
    }
    static computeHoverPositions(editor2, anchorRange, hoverParts) {
      let startColumnBoundary = 1;
      if (editor2.hasModel()) {
        const viewModel = editor2._getViewModel();
        const coordinatesConverter = viewModel.coordinatesConverter;
        const anchorViewRange = coordinatesConverter.convertModelRangeToViewRange(anchorRange);
        const anchorViewMinColumn = viewModel.getLineMinColumn(anchorViewRange.startLineNumber);
        const anchorViewRangeStart = new Position$1(anchorViewRange.startLineNumber, anchorViewMinColumn);
        startColumnBoundary = coordinatesConverter.convertViewPositionToModelPosition(anchorViewRangeStart).column;
      }
      const anchorStartLineNumber = anchorRange.startLineNumber;
      let secondaryPositionColumn = anchorRange.startColumn;
      let forceShowAtRange;
      for (const hoverPart of hoverParts) {
        const hoverPartRange = hoverPart.range;
        const hoverPartRangeOnAnchorStartLine = hoverPartRange.startLineNumber === anchorStartLineNumber;
        const hoverPartRangeOnAnchorEndLine = hoverPartRange.endLineNumber === anchorStartLineNumber;
        const hoverPartRangeIsOnAnchorLine = hoverPartRangeOnAnchorStartLine && hoverPartRangeOnAnchorEndLine;
        if (hoverPartRangeIsOnAnchorLine) {
          const hoverPartStartColumn = hoverPartRange.startColumn;
          const minSecondaryPositionColumn = Math.min(secondaryPositionColumn, hoverPartStartColumn);
          secondaryPositionColumn = Math.max(minSecondaryPositionColumn, startColumnBoundary);
        }
        if (hoverPart.forceShowAtRange) {
          forceShowAtRange = hoverPartRange;
        }
      }
      let showAtPosition;
      let showAtSecondaryPosition;
      if (forceShowAtRange) {
        const forceShowAtPosition = forceShowAtRange.getStartPosition();
        showAtPosition = forceShowAtPosition;
        showAtSecondaryPosition = forceShowAtPosition;
      } else {
        showAtPosition = anchorRange.getStartPosition();
        showAtSecondaryPosition = new Position$1(anchorStartLineNumber, secondaryPositionColumn);
      }
      return {
        showAtPosition,
        showAtSecondaryPosition
      };
    }
  };
  RenderedContentHover = RenderedContentHover_1 = __decorate$1S([
    __param$1R(4, IKeybindingService),
    __param$1R(5, IHoverService),
    __param$1R(6, IClipboardService)
  ], RenderedContentHover);
  class RenderedStatusBar {
    constructor(fragment, _statusBar) {
      this._statusBar = _statusBar;
      fragment.appendChild(this._statusBar.hoverElement);
    }
    get hoverElement() {
      return this._statusBar.hoverElement;
    }
    get actions() {
      return this._statusBar.actions;
    }
    dispose() {
      this._statusBar.dispose();
    }
  }
  let RenderedContentHoverParts = (_O = class extends Disposable {
    constructor(editor2, participants, hoverParts, context, keybindingService, _hoverService, _clipboardService) {
      super();
      this._hoverService = _hoverService;
      this._clipboardService = _clipboardService;
      this._renderedParts = [];
      this._focusedHoverPartIndex = -1;
      this._context = context;
      this._fragment = document.createDocumentFragment();
      this._register(this._renderParts(participants, hoverParts, context, keybindingService, this._hoverService));
      this._register(this._registerListenersOnRenderedParts());
      this._register(this._createEditorDecorations(editor2, hoverParts));
      this._updateMarkdownAndColorParticipantInfo(participants);
    }
    _createEditorDecorations(editor2, hoverParts) {
      if (hoverParts.length === 0) {
        return Disposable.None;
      }
      let highlightRange2 = hoverParts[0].range;
      for (const hoverPart of hoverParts) {
        const hoverPartRange = hoverPart.range;
        highlightRange2 = Range$2.plusRange(highlightRange2, hoverPartRange);
      }
      const highlightDecoration = editor2.createDecorationsCollection();
      highlightDecoration.set([{
        range: highlightRange2,
        options: RenderedContentHoverParts_1._DECORATION_OPTIONS
      }]);
      return toDisposable(() => {
        highlightDecoration.clear();
      });
    }
    _renderParts(participants, hoverParts, hoverContext, keybindingService, hoverService) {
      const statusBar = new EditorHoverStatusBar(keybindingService, hoverService);
      const hoverRenderingContext = {
        fragment: this._fragment,
        statusBar,
        ...hoverContext
      };
      const disposables = new DisposableStore();
      disposables.add(statusBar);
      for (const participant of participants) {
        const renderedHoverParts = this._renderHoverPartsForParticipant(hoverParts, participant, hoverRenderingContext);
        disposables.add(renderedHoverParts);
        for (const renderedHoverPart of renderedHoverParts.renderedHoverParts) {
          this._renderedParts.push({
            type: "hoverPart",
            participant,
            hoverPart: renderedHoverPart.hoverPart,
            hoverElement: renderedHoverPart.hoverElement
          });
        }
      }
      const renderedStatusBar = this._renderStatusBar(this._fragment, statusBar);
      if (renderedStatusBar) {
        disposables.add(renderedStatusBar);
        this._renderedParts.push({
          type: "statusBar",
          hoverElement: renderedStatusBar.hoverElement,
          actions: renderedStatusBar.actions
        });
      }
      return disposables;
    }
    _renderHoverPartsForParticipant(hoverParts, participant, hoverRenderingContext) {
      const hoverPartsForParticipant = hoverParts.filter((hoverPart) => hoverPart.owner === participant);
      const hasHoverPartsForParticipant = hoverPartsForParticipant.length > 0;
      if (!hasHoverPartsForParticipant) {
        return new RenderedHoverParts([]);
      }
      return participant.renderHoverParts(hoverRenderingContext, hoverPartsForParticipant);
    }
    _renderStatusBar(fragment, statusBar) {
      if (!statusBar.hasContent) {
        return void 0;
      }
      return new RenderedStatusBar(fragment, statusBar);
    }
    _registerListenersOnRenderedParts() {
      const disposables = new DisposableStore();
      this._renderedParts.forEach((renderedPart, index) => {
        const element = renderedPart.hoverElement;
        element.tabIndex = 0;
        disposables.add(addDisposableListener(element, EventType$1.FOCUS_IN, (event) => {
          event.stopPropagation();
          this._focusedHoverPartIndex = index;
        }));
        disposables.add(addDisposableListener(element, EventType$1.FOCUS_OUT, (event) => {
          event.stopPropagation();
          this._focusedHoverPartIndex = -1;
        }));
        if (renderedPart.type === "hoverPart" && renderedPart.hoverPart instanceof MarkerHover) {
          disposables.add(new HoverCopyButton(element, () => renderedPart.participant.getAccessibleContent(renderedPart.hoverPart), this._clipboardService, this._hoverService));
        }
      });
      return disposables;
    }
    _updateMarkdownAndColorParticipantInfo(participants) {
      const markdownHoverParticipant = participants.find((p) => {
        return p instanceof MarkdownHoverParticipant && !(p instanceof InlayHintsHover);
      });
      if (markdownHoverParticipant) {
        this._markdownHoverParticipant = markdownHoverParticipant;
      }
      this._colorHoverParticipant = participants.find((p) => p instanceof HoverColorPickerParticipant);
    }
    focusHoverPartWithIndex(index) {
      if (index < 0 || index >= this._renderedParts.length) {
        return;
      }
      this._renderedParts[index].hoverElement.focus();
    }
    async updateHoverVerbosityLevel(action, index, focus) {
      if (!this._markdownHoverParticipant) {
        return;
      }
      let rangeOfIndicesToUpdate;
      if (index >= 0) {
        rangeOfIndicesToUpdate = { start: index, endExclusive: index + 1 };
      } else {
        rangeOfIndicesToUpdate = this._findRangeOfMarkdownHoverParts(this._markdownHoverParticipant);
      }
      for (let i2 = rangeOfIndicesToUpdate.start; i2 < rangeOfIndicesToUpdate.endExclusive; i2++) {
        const normalizedMarkdownHoverIndex = this._normalizedIndexToMarkdownHoverIndexRange(this._markdownHoverParticipant, i2);
        if (normalizedMarkdownHoverIndex === void 0) {
          continue;
        }
        const renderedPart = await this._markdownHoverParticipant.updateMarkdownHoverVerbosityLevel(action, normalizedMarkdownHoverIndex);
        if (!renderedPart) {
          continue;
        }
        this._renderedParts[i2] = {
          type: "hoverPart",
          participant: this._markdownHoverParticipant,
          hoverPart: renderedPart.hoverPart,
          hoverElement: renderedPart.hoverElement
        };
      }
      if (focus) {
        if (index >= 0) {
          this.focusHoverPartWithIndex(index);
        } else {
          this._context.focus();
        }
      }
      this._context.onContentsChanged();
    }
    isColorPickerVisible() {
      return this._colorHoverParticipant?.isColorPickerVisible() ?? false;
    }
    _normalizedIndexToMarkdownHoverIndexRange(markdownHoverParticipant, index) {
      const renderedPart = this._renderedParts[index];
      if (!renderedPart || renderedPart.type !== "hoverPart") {
        return void 0;
      }
      const isHoverPartMarkdownHover = renderedPart.participant === markdownHoverParticipant;
      if (!isHoverPartMarkdownHover) {
        return void 0;
      }
      const firstIndexOfMarkdownHovers = this._renderedParts.findIndex((renderedPart2) => renderedPart2.type === "hoverPart" && renderedPart2.participant === markdownHoverParticipant);
      if (firstIndexOfMarkdownHovers === -1) {
        throw new BugIndicatingError();
      }
      return index - firstIndexOfMarkdownHovers;
    }
    _findRangeOfMarkdownHoverParts(markdownHoverParticipant) {
      const copiedRenderedParts = this._renderedParts.slice();
      const firstIndexOfMarkdownHovers = copiedRenderedParts.findIndex((renderedPart) => renderedPart.type === "hoverPart" && renderedPart.participant === markdownHoverParticipant);
      const inversedLastIndexOfMarkdownHovers = copiedRenderedParts.reverse().findIndex((renderedPart) => renderedPart.type === "hoverPart" && renderedPart.participant === markdownHoverParticipant);
      const lastIndexOfMarkdownHovers = inversedLastIndexOfMarkdownHovers >= 0 ? copiedRenderedParts.length - inversedLastIndexOfMarkdownHovers : inversedLastIndexOfMarkdownHovers;
      return { start: firstIndexOfMarkdownHovers, endExclusive: lastIndexOfMarkdownHovers + 1 };
    }
    get domNode() {
      return this._fragment;
    }
    get domNodeHasChildren() {
      return this._fragment.hasChildNodes();
    }
    get focusedHoverPartIndex() {
      return this._focusedHoverPartIndex;
    }
    get hoverPartsCount() {
      return this._renderedParts.length;
    }
  }, RenderedContentHoverParts_1 = _O, _O._DECORATION_OPTIONS = ModelDecorationOptions.register({
    description: "content-hover-highlight",
    className: "hoverHighlight"
  }), _O);
  RenderedContentHoverParts = RenderedContentHoverParts_1 = __decorate$1S([
    __param$1R(4, IKeybindingService),
    __param$1R(5, IHoverService),
    __param$1R(6, IClipboardService)
  ], RenderedContentHoverParts);
  var __decorate$1R = 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$1Q = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  let ContentHoverWidgetWrapper = class ContentHoverWidgetWrapper extends Disposable {
    constructor(_editor, _instantiationService, _keybindingService, _hoverService, _clipboardService) {
      super();
      this._editor = _editor;
      this._instantiationService = _instantiationService;
      this._keybindingService = _keybindingService;
      this._hoverService = _hoverService;
      this._clipboardService = _clipboardService;
      this._currentResult = null;
      this._renderedContentHover = this._register(new MutableDisposable());
      this._onContentsChanged = this._register(new Emitter$1());
      this.onContentsChanged = this._onContentsChanged.event;
      this._contentHoverWidget = this._register(this._instantiationService.createInstance(ContentHoverWidget, this._editor));
      this._participants = this._initializeHoverParticipants();
      this._hoverOperation = this._register(new HoverOperation(this._editor, new ContentHoverComputer(this._editor, this._participants)));
      this._registerListeners();
    }
    _initializeHoverParticipants() {
      const participants = [];
      for (const participant of HoverParticipantRegistry.getAll()) {
        const participantInstance = this._instantiationService.createInstance(participant, this._editor);
        participants.push(participantInstance);
      }
      participants.sort((p1, p2) => p1.hoverOrdinal - p2.hoverOrdinal);
      this._register(this._contentHoverWidget.onDidResize(() => {
        this._participants.forEach((participant) => participant.handleResize?.());
      }));
      this._register(this._contentHoverWidget.onDidScroll((e) => {
        this._participants.forEach((participant) => participant.handleScroll?.(e));
      }));
      this._register(this._contentHoverWidget.onContentsChanged(() => {
        this._participants.forEach((participant) => participant.handleContentsChanged?.());
      }));
      return participants;
    }
    _registerListeners() {
      this._register(this._hoverOperation.onResult((result) => {
        const messages = result.hasLoadingMessage ? this._addLoadingMessage(result) : result.value;
        this._withResult(new ContentHoverResult(messages, result.isComplete, result.options));
      }));
      const contentHoverWidgetNode = this._contentHoverWidget.getDomNode();
      this._register(addStandardDisposableListener(contentHoverWidgetNode, "keydown", (e) => {
        if (e.equals(
          9
          /* KeyCode.Escape */
        )) {
          this.hide();
        }
      }));
      this._register(addStandardDisposableListener(contentHoverWidgetNode, "mouseleave", (e) => {
        this._onMouseLeave(e);
      }));
      this._register(TokenizationRegistry.onDidChange(() => {
        if (this._contentHoverWidget.position && this._currentResult) {
          this._setCurrentResult(this._currentResult);
        }
      }));
      this._register(this._contentHoverWidget.onContentsChanged(() => {
        this._onContentsChanged.fire();
      }));
    }
    /**
     * Returns true if the hover shows now or will show.
     */
    _startShowingOrUpdateHover(anchor, mode, source, focus, mouseEvent) {
      const contentHoverIsVisible = this._contentHoverWidget.position && this._currentResult;
      if (!contentHoverIsVisible) {
        if (anchor) {
          this._startHoverOperationIfNecessary(anchor, mode, source, focus, false);
          return true;
        }
        return false;
      }
      const isHoverSticky = this._editor.getOption(
        69
        /* EditorOption.hover */
      ).sticky;
      const isMouseGettingCloser = mouseEvent && this._contentHoverWidget.isMouseGettingCloser(mouseEvent.event.posx, mouseEvent.event.posy);
      const isHoverStickyAndIsMouseGettingCloser = isHoverSticky && isMouseGettingCloser;
      if (isHoverStickyAndIsMouseGettingCloser) {
        if (anchor) {
          this._startHoverOperationIfNecessary(anchor, mode, source, focus, true);
        }
        return true;
      }
      if (!anchor) {
        this._setCurrentResult(null);
        return false;
      }
      const currentAnchorEqualsPreviousAnchor = this._currentResult && this._currentResult.options.anchor.equals(anchor);
      if (currentAnchorEqualsPreviousAnchor) {
        return true;
      }
      const currentAnchorCompatibleWithPreviousAnchor = this._currentResult && anchor.canAdoptVisibleHover(this._currentResult.options.anchor, this._contentHoverWidget.position);
      if (!currentAnchorCompatibleWithPreviousAnchor) {
        this._setCurrentResult(null);
        this._startHoverOperationIfNecessary(anchor, mode, source, focus, false);
        return true;
      }
      if (this._currentResult) {
        this._setCurrentResult(this._currentResult.filter(anchor));
      }
      this._startHoverOperationIfNecessary(anchor, mode, source, focus, false);
      return true;
    }
    _startHoverOperationIfNecessary(anchor, mode, source, shouldFocus, insistOnKeepingHoverVisible) {
      const currentAnchorEqualToPreviousHover = this._hoverOperation.options && this._hoverOperation.options.anchor.equals(anchor);
      if (currentAnchorEqualToPreviousHover) {
        return;
      }
      this._hoverOperation.cancel();
      const contentHoverComputerOptions = {
        anchor,
        source,
        shouldFocus,
        insistOnKeepingHoverVisible
      };
      this._hoverOperation.start(mode, contentHoverComputerOptions);
    }
    _setCurrentResult(hoverResult) {
      let currentHoverResult = hoverResult;
      const currentResultEqualToPreviousResult = this._currentResult === currentHoverResult;
      if (currentResultEqualToPreviousResult) {
        return;
      }
      const currentHoverResultIsEmpty = currentHoverResult && currentHoverResult.hoverParts.length === 0;
      if (currentHoverResultIsEmpty) {
        currentHoverResult = null;
      }
      this._currentResult = currentHoverResult;
      if (this._currentResult) {
        this._showHover(this._currentResult);
      } else {
        this._hideHover();
      }
    }
    _addLoadingMessage(hoverResult) {
      for (const participant of this._participants) {
        if (!participant.createLoadingMessage) {
          continue;
        }
        const loadingMessage = participant.createLoadingMessage(hoverResult.options.anchor);
        if (!loadingMessage) {
          continue;
        }
        return hoverResult.value.slice(0).concat([loadingMessage]);
      }
      return hoverResult.value;
    }
    _withResult(hoverResult) {
      const previousHoverIsVisibleWithCompleteResult = this._contentHoverWidget.position && this._currentResult && this._currentResult.isComplete;
      if (!previousHoverIsVisibleWithCompleteResult) {
        this._setCurrentResult(hoverResult);
      }
      const isCurrentHoverResultComplete = hoverResult.isComplete;
      if (!isCurrentHoverResultComplete) {
        return;
      }
      const currentHoverResultIsEmpty = hoverResult.hoverParts.length === 0;
      const insistOnKeepingPreviousHoverVisible = hoverResult.options.insistOnKeepingHoverVisible;
      const shouldKeepPreviousHoverVisible = currentHoverResultIsEmpty && insistOnKeepingPreviousHoverVisible;
      if (shouldKeepPreviousHoverVisible) {
        return;
      }
      this._setCurrentResult(hoverResult);
    }
    _showHover(hoverResult) {
      const context = this._getHoverContext();
      this._renderedContentHover.value = new RenderedContentHover(this._editor, hoverResult, this._participants, context, this._keybindingService, this._hoverService, this._clipboardService);
      if (this._renderedContentHover.value.domNodeHasChildren) {
        this._contentHoverWidget.show(this._renderedContentHover.value);
      } else {
        this._renderedContentHover.clear();
      }
    }
    _hideHover() {
      this._contentHoverWidget.hide();
      this._participants.forEach((participant) => participant.handleHide?.());
    }
    _getHoverContext() {
      const hide2 = () => {
        this.hide();
      };
      const onContentsChanged = () => {
        this._contentHoverWidget.handleContentsChanged();
      };
      const setMinimumDimensions = (dimensions) => {
        this._contentHoverWidget.setMinimumDimensions(dimensions);
      };
      const focus = () => this.focus();
      return { hide: hide2, onContentsChanged, setMinimumDimensions, focus };
    }
    showsOrWillShow(mouseEvent) {
      const isContentWidgetResizing = this._contentHoverWidget.isResizing;
      if (isContentWidgetResizing) {
        return true;
      }
      const anchorCandidates = this._findHoverAnchorCandidates(mouseEvent);
      const anchorCandidatesExist = anchorCandidates.length > 0;
      if (!anchorCandidatesExist) {
        return this._startShowingOrUpdateHover(null, 0, 0, false, mouseEvent);
      }
      const anchor = anchorCandidates[0];
      return this._startShowingOrUpdateHover(anchor, 0, 0, false, mouseEvent);
    }
    _findHoverAnchorCandidates(mouseEvent) {
      const anchorCandidates = [];
      for (const participant of this._participants) {
        if (!participant.suggestHoverAnchor) {
          continue;
        }
        const anchor = participant.suggestHoverAnchor(mouseEvent);
        if (!anchor) {
          continue;
        }
        anchorCandidates.push(anchor);
      }
      const target = mouseEvent.target;
      switch (target.type) {
        case 6: {
          anchorCandidates.push(new HoverRangeAnchor(0, target.range, mouseEvent.event.posx, mouseEvent.event.posy));
          break;
        }
        case 7: {
          const epsilon = this._editor.getOption(
            59
            /* EditorOption.fontInfo */
          ).typicalHalfwidthCharacterWidth / 2;
          const mouseIsWithinLinesAndCloseToHover = !target.detail.isAfterLines && typeof target.detail.horizontalDistanceToText === "number" && target.detail.horizontalDistanceToText < epsilon;
          if (!mouseIsWithinLinesAndCloseToHover) {
            break;
          }
          anchorCandidates.push(new HoverRangeAnchor(0, target.range, mouseEvent.event.posx, mouseEvent.event.posy));
          break;
        }
      }
      anchorCandidates.sort((a, b) => b.priority - a.priority);
      return anchorCandidates;
    }
    _onMouseLeave(e) {
      const editorDomNode = this._editor.getDomNode();
      const isMousePositionOutsideOfEditor = !editorDomNode || !isMousePositionWithinElement(editorDomNode, e.x, e.y);
      if (isMousePositionOutsideOfEditor) {
        this.hide();
      }
    }
    startShowingAtRange(range2, mode, source, focus) {
      this._startShowingOrUpdateHover(new HoverRangeAnchor(0, range2, void 0, void 0), mode, source, focus, null);
    }
    async updateHoverVerbosityLevel(action, index, focus) {
      this._renderedContentHover.value?.updateHoverVerbosityLevel(action, index, focus);
    }
    focusedHoverPartIndex() {
      return this._renderedContentHover.value?.focusedHoverPartIndex ?? -1;
    }
    containsNode(node) {
      return node ? this._contentHoverWidget.getDomNode().contains(node) : false;
    }
    focus() {
      const hoverPartsCount = this._renderedContentHover.value?.hoverPartsCount;
      if (hoverPartsCount === 1) {
        this.focusHoverPartWithIndex(0);
        return;
      }
      this._contentHoverWidget.focus();
    }
    focusHoverPartWithIndex(index) {
      this._renderedContentHover.value?.focusHoverPartWithIndex(index);
    }
    scrollUp() {
      this._contentHoverWidget.scrollUp();
    }
    scrollDown() {
      this._contentHoverWidget.scrollDown();
    }
    scrollLeft() {
      this._contentHoverWidget.scrollLeft();
    }
    scrollRight() {
      this._contentHoverWidget.scrollRight();
    }
    pageUp() {
      this._contentHoverWidget.pageUp();
    }
    pageDown() {
      this._contentHoverWidget.pageDown();
    }
    goToTop() {
      this._contentHoverWidget.goToTop();
    }
    goToBottom() {
      this._contentHoverWidget.goToBottom();
    }
    hide() {
      this._hoverOperation.cancel();
      this._setCurrentResult(null);
    }
    getDomNode() {
      return this._contentHoverWidget.getDomNode();
    }
    get isColorPickerVisible() {
      return this._renderedContentHover.value?.isColorPickerVisible() ?? false;
    }
    get isVisibleFromKeyboard() {
      return this._contentHoverWidget.isVisibleFromKeyboard;
    }
    get isVisible() {
      return this._contentHoverWidget.isVisible;
    }
    get isFocused() {
      return this._contentHoverWidget.isFocused;
    }
    get isResizing() {
      return this._contentHoverWidget.isResizing;
    }
    get widget() {
      return this._contentHoverWidget;
    }
  };
  ContentHoverWidgetWrapper = __decorate$1R([
    __param$1Q(1, IInstantiationService),
    __param$1Q(2, IKeybindingService),
    __param$1Q(3, IHoverService),
    __param$1Q(4, IClipboardService)
  ], ContentHoverWidgetWrapper);
  function isOnColorDecorator(mouseEvent) {
    const target = mouseEvent.target;
    return !!target && target.type === 6 && target.detail.injectedText?.options.attachedData === ColorDecorationInjectedTextMarker;
  }
  var __decorate$1Q = 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$1P = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  var ContentHoverController_1;
  let ContentHoverController = (_P = class extends Disposable {
    constructor(_editor, _contextMenuService, _instantiationService, _keybindingService) {
      super();
      this._editor = _editor;
      this._instantiationService = _instantiationService;
      this._keybindingService = _keybindingService;
      this._onHoverContentsChanged = this._register(new Emitter$1());
      this.shouldKeepOpenOnEditorMouseMoveOrLeave = false;
      this._listenersStore = new DisposableStore();
      this._isMouseDown = false;
      this._ignoreMouseEvents = false;
      this._reactToEditorMouseMoveRunner = this._register(new RunOnceScheduler(() => {
        if (this._mouseMoveEvent) {
          this._reactToEditorMouseMove(this._mouseMoveEvent);
        }
      }, 0));
      this._register(_contextMenuService.onDidShowContextMenu(() => {
        this.hideContentHover();
        this._ignoreMouseEvents = true;
      }));
      this._register(_contextMenuService.onDidHideContextMenu(() => {
        this._ignoreMouseEvents = false;
      }));
      this._hookListeners();
      this._register(this._editor.onDidChangeConfiguration((e) => {
        if (e.hasChanged(
          69
          /* EditorOption.hover */
        )) {
          this._unhookListeners();
          this._hookListeners();
        }
      }));
    }
    static get(editor2) {
      return editor2.getContribution(ContentHoverController_1.ID);
    }
    _hookListeners() {
      const hoverOpts = this._editor.getOption(
        69
        /* EditorOption.hover */
      );
      this._hoverSettings = {
        enabled: hoverOpts.enabled,
        sticky: hoverOpts.sticky,
        hidingDelay: hoverOpts.hidingDelay
      };
      if (!hoverOpts.enabled) {
        this._cancelSchedulerAndHide();
      }
      this._listenersStore.add(this._editor.onMouseDown((e) => this._onEditorMouseDown(e)));
      this._listenersStore.add(this._editor.onMouseUp(() => this._onEditorMouseUp()));
      this._listenersStore.add(this._editor.onMouseMove((e) => this._onEditorMouseMove(e)));
      this._listenersStore.add(this._editor.onKeyDown((e) => this._onKeyDown(e)));
      this._listenersStore.add(this._editor.onMouseLeave((e) => this._onEditorMouseLeave(e)));
      this._listenersStore.add(this._editor.onDidChangeModel(() => this._cancelSchedulerAndHide()));
      this._listenersStore.add(this._editor.onDidChangeModelContent(() => this._cancelScheduler()));
      this._listenersStore.add(this._editor.onDidScrollChange((e) => this._onEditorScrollChanged(e)));
    }
    _unhookListeners() {
      this._listenersStore.clear();
    }
    _cancelSchedulerAndHide() {
      this._cancelScheduler();
      this.hideContentHover();
    }
    _cancelScheduler() {
      this._mouseMoveEvent = void 0;
      this._reactToEditorMouseMoveRunner.cancel();
    }
    _onEditorScrollChanged(e) {
      if (this._ignoreMouseEvents) {
        return;
      }
      if (e.scrollTopChanged || e.scrollLeftChanged) {
        this.hideContentHover();
      }
    }
    _onEditorMouseDown(mouseEvent) {
      if (this._ignoreMouseEvents) {
        return;
      }
      this._isMouseDown = true;
      const shouldKeepHoverWidgetVisible = this._shouldKeepHoverWidgetVisible(mouseEvent);
      if (shouldKeepHoverWidgetVisible) {
        return;
      }
      this.hideContentHover();
    }
    _shouldKeepHoverWidgetVisible(mouseEvent) {
      return this._isMouseOnContentHoverWidget(mouseEvent) || this._isContentWidgetResizing() || isOnColorDecorator(mouseEvent);
    }
    _isMouseOnContentHoverWidget(mouseEvent) {
      if (!this._contentWidget) {
        return false;
      }
      return isMousePositionWithinElement(this._contentWidget.getDomNode(), mouseEvent.event.posx, mouseEvent.event.posy);
    }
    _onEditorMouseUp() {
      if (this._ignoreMouseEvents) {
        return;
      }
      this._isMouseDown = false;
    }
    _onEditorMouseLeave(mouseEvent) {
      if (this._ignoreMouseEvents) {
        return;
      }
      if (this.shouldKeepOpenOnEditorMouseMoveOrLeave) {
        return;
      }
      this._cancelScheduler();
      const shouldKeepHoverWidgetVisible = this._shouldKeepHoverWidgetVisible(mouseEvent);
      if (shouldKeepHoverWidgetVisible) {
        return;
      }
      this.hideContentHover();
    }
    _shouldKeepCurrentHover(mouseEvent) {
      const contentWidget = this._contentWidget;
      if (!contentWidget) {
        return false;
      }
      const isHoverSticky = this._hoverSettings.sticky;
      const isMouseOnStickyContentHoverWidget = (mouseEvent2, isHoverSticky2) => {
        const isMouseOnContentHoverWidget = this._isMouseOnContentHoverWidget(mouseEvent2);
        return isHoverSticky2 && isMouseOnContentHoverWidget;
      };
      const isMouseOnColorPickerOrChoosingColor = (mouseEvent2) => {
        const isColorPickerVisible = contentWidget.isColorPickerVisible;
        const isMouseOnContentHoverWidget = this._isMouseOnContentHoverWidget(mouseEvent2);
        const isMouseOnHoverWithColorPicker = isColorPickerVisible && isMouseOnContentHoverWidget;
        const isMaybeChoosingColor = isColorPickerVisible && this._isMouseDown;
        return isMouseOnHoverWithColorPicker || isMaybeChoosingColor;
      };
      const isTextSelectedWithinContentHoverWidget = (mouseEvent2, sticky) => {
        const view = mouseEvent2.event.browserEvent.view;
        if (!view) {
          return false;
        }
        return sticky && contentWidget.containsNode(view.document.activeElement) && !view.getSelection()?.isCollapsed;
      };
      const isFocused = contentWidget.isFocused;
      const isResizing = contentWidget.isResizing;
      const isStickyAndVisibleFromKeyboard = this._hoverSettings.sticky && contentWidget.isVisibleFromKeyboard;
      return this.shouldKeepOpenOnEditorMouseMoveOrLeave || isFocused || isResizing || isStickyAndVisibleFromKeyboard || isMouseOnStickyContentHoverWidget(mouseEvent, isHoverSticky) || isMouseOnColorPickerOrChoosingColor(mouseEvent) || isTextSelectedWithinContentHoverWidget(mouseEvent, isHoverSticky);
    }
    _onEditorMouseMove(mouseEvent) {
      if (this._ignoreMouseEvents) {
        return;
      }
      this._mouseMoveEvent = mouseEvent;
      const shouldKeepCurrentHover = this._shouldKeepCurrentHover(mouseEvent);
      if (shouldKeepCurrentHover) {
        this._reactToEditorMouseMoveRunner.cancel();
        return;
      }
      const shouldRescheduleHoverComputation = this._shouldRescheduleHoverComputation();
      if (shouldRescheduleHoverComputation) {
        if (!this._reactToEditorMouseMoveRunner.isScheduled()) {
          this._reactToEditorMouseMoveRunner.schedule(this._hoverSettings.hidingDelay);
        }
        return;
      }
      this._reactToEditorMouseMove(mouseEvent);
    }
    _shouldRescheduleHoverComputation() {
      const hidingDelay = this._hoverSettings.hidingDelay;
      const isContentHoverWidgetVisible = this._contentWidget?.isVisible ?? false;
      return isContentHoverWidgetVisible && this._hoverSettings.sticky && hidingDelay > 0;
    }
    _reactToEditorMouseMove(mouseEvent) {
      if (this._hoverSettings.enabled) {
        const contentWidget = this._getOrCreateContentWidget();
        if (contentWidget.showsOrWillShow(mouseEvent)) {
          return;
        }
      }
      this.hideContentHover();
    }
    _onKeyDown(e) {
      if (this._ignoreMouseEvents) {
        return;
      }
      if (!this._contentWidget) {
        return;
      }
      const isPotentialKeyboardShortcut = this._isPotentialKeyboardShortcut(e);
      const isModifierKeyPressed = this._isModifierKeyPressed(e);
      if (isPotentialKeyboardShortcut || isModifierKeyPressed) {
        return;
      }
      if (this._contentWidget.isFocused && e.keyCode === 2) {
        return;
      }
      this.hideContentHover();
    }
    _isPotentialKeyboardShortcut(e) {
      if (!this._editor.hasModel() || !this._contentWidget) {
        return false;
      }
      const resolvedKeyboardEvent = this._keybindingService.softDispatch(e, this._editor.getDomNode());
      const moreChordsAreNeeded = resolvedKeyboardEvent.kind === 1;
      const isHoverAction = resolvedKeyboardEvent.kind === 2 && (resolvedKeyboardEvent.commandId === SHOW_OR_FOCUS_HOVER_ACTION_ID || resolvedKeyboardEvent.commandId === INCREASE_HOVER_VERBOSITY_ACTION_ID || resolvedKeyboardEvent.commandId === DECREASE_HOVER_VERBOSITY_ACTION_ID) && this._contentWidget.isVisible;
      return moreChordsAreNeeded || isHoverAction;
    }
    _isModifierKeyPressed(e) {
      return e.keyCode === 5 || e.keyCode === 6 || e.keyCode === 57 || e.keyCode === 4;
    }
    hideContentHover() {
      if (InlineSuggestionHintsContentWidget.dropDownVisible) {
        return;
      }
      this._contentWidget?.hide();
    }
    _getOrCreateContentWidget() {
      if (!this._contentWidget) {
        this._contentWidget = this._instantiationService.createInstance(ContentHoverWidgetWrapper, this._editor);
        this._listenersStore.add(this._contentWidget.onContentsChanged(() => this._onHoverContentsChanged.fire()));
      }
      return this._contentWidget;
    }
    showContentHover(range2, mode, source, focus) {
      this._getOrCreateContentWidget().startShowingAtRange(range2, mode, source, focus);
    }
    _isContentWidgetResizing() {
      return this._contentWidget?.widget.isResizing || false;
    }
    focusedHoverPartIndex() {
      return this._getOrCreateContentWidget().focusedHoverPartIndex();
    }
    updateHoverVerbosityLevel(action, index, focus) {
      this._getOrCreateContentWidget().updateHoverVerbosityLevel(action, index, focus);
    }
    focus() {
      this._contentWidget?.focus();
    }
    scrollUp() {
      this._contentWidget?.scrollUp();
    }
    scrollDown() {
      this._contentWidget?.scrollDown();
    }
    scrollLeft() {
      this._contentWidget?.scrollLeft();
    }
    scrollRight() {
      this._contentWidget?.scrollRight();
    }
    pageUp() {
      this._contentWidget?.pageUp();
    }
    pageDown() {
      this._contentWidget?.pageDown();
    }
    goToTop() {
      this._contentWidget?.goToTop();
    }
    goToBottom() {
      this._contentWidget?.goToBottom();
    }
    get isColorPickerVisible() {
      return this._contentWidget?.isColorPickerVisible;
    }
    get isHoverVisible() {
      return this._contentWidget?.isVisible;
    }
    dispose() {
      super.dispose();
      this._unhookListeners();
      this._listenersStore.dispose();
      this._contentWidget?.dispose();
    }
  }, ContentHoverController_1 = _P, _P.ID = "editor.contrib.contentHover", _P);
  ContentHoverController = ContentHoverController_1 = __decorate$1Q([
    __param$1P(1, IContextMenuService),
    __param$1P(2, IInstantiationService),
    __param$1P(3, IKeybindingService)
  ], ContentHoverController);
  const _HoverColorPickerContribution = class _HoverColorPickerContribution extends Disposable {
    // ms
    constructor(_editor) {
      super();
      this._editor = _editor;
      this._register(_editor.onMouseDown((e) => this.onMouseDown(e)));
    }
    dispose() {
      super.dispose();
    }
    onMouseDown(mouseEvent) {
      const colorDecoratorsActivatedOn = this._editor.getOption(
        168
        /* EditorOption.colorDecoratorsActivatedOn */
      );
      if (colorDecoratorsActivatedOn !== "click" && colorDecoratorsActivatedOn !== "clickAndHover") {
        return;
      }
      if (!isOnColorDecorator(mouseEvent)) {
        return;
      }
      const hoverController = this._editor.getContribution(ContentHoverController.ID);
      if (!hoverController) {
        return;
      }
      if (hoverController.isColorPickerVisible) {
        return;
      }
      const targetRange = mouseEvent.target.range;
      if (!targetRange) {
        return;
      }
      const range2 = new Range$2(targetRange.startLineNumber, targetRange.startColumn + 1, targetRange.endLineNumber, targetRange.endColumn + 1);
      hoverController.showContentHover(range2, 1, 1, false);
    }
  };
  _HoverColorPickerContribution.ID = "editor.contrib.colorContribution";
  let HoverColorPickerContribution = _HoverColorPickerContribution;
  var __decorate$1P = 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$1O = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  class StandaloneColorPickerHover {
    constructor(owner, range2, model, provider) {
      this.owner = owner;
      this.range = range2;
      this.model = model;
      this.provider = provider;
    }
    static fromBaseColor(owner, color) {
      return new StandaloneColorPickerHover(owner, color.range, color.model, color.provider);
    }
  }
  class StandaloneColorPickerRenderedParts extends Disposable {
    constructor(editor2, context, colorHover, themeService) {
      super();
      const editorModel = editor2.getModel();
      const colorPickerModel = colorHover.model;
      this.color = colorHover.model.color;
      this.colorPicker = this._register(new ColorPickerWidget(
        context.fragment,
        colorPickerModel,
        editor2.getOption(
          163
          /* EditorOption.pixelRatio */
        ),
        themeService,
        "standalone"
        /* ColorPickerWidgetType.Standalone */
      ));
      this._register(colorPickerModel.onColorFlushed((color) => {
        this.color = color;
      }));
      this._register(colorPickerModel.onDidChangeColor((color) => {
        updateColorPresentations(editorModel, colorPickerModel, color, colorHover.range, colorHover);
      }));
      this._register(editor2.onDidChangeModelContent((e) => {
        {
          context.hide();
          editor2.focus();
        }
      }));
      updateColorPresentations(editorModel, colorPickerModel, this.color, colorHover.range, colorHover);
    }
  }
  let StandaloneColorPickerParticipant = class StandaloneColorPickerParticipant {
    constructor(_editor, _themeService) {
      this._editor = _editor;
      this._themeService = _themeService;
    }
    async createColorHover(defaultColorInfo, defaultColorProvider, colorProviderRegistry) {
      if (!this._editor.hasModel()) {
        return null;
      }
      const colorDetector = ColorDetector.get(this._editor);
      if (!colorDetector) {
        return null;
      }
      const colors = await getColors(colorProviderRegistry, this._editor.getModel(), CancellationToken.None);
      let foundColorInfo = null;
      let foundColorProvider = null;
      for (const colorData of colors) {
        const colorInfo2 = colorData.colorInfo;
        if (Range$2.containsRange(colorInfo2.range, defaultColorInfo.range)) {
          foundColorInfo = colorInfo2;
          foundColorProvider = colorData.provider;
        }
      }
      const colorInfo = foundColorInfo ?? defaultColorInfo;
      const colorProvider = foundColorProvider ?? defaultColorProvider;
      const foundInEditor = !!foundColorInfo;
      const colorHover = StandaloneColorPickerHover.fromBaseColor(this, await createColorHover(this._editor.getModel(), colorInfo, colorProvider));
      return { colorHover, foundInEditor };
    }
    async updateEditorModel(colorHoverData) {
      if (!this._editor.hasModel()) {
        return;
      }
      const colorPickerModel = colorHoverData.model;
      let range2 = new Range$2(colorHoverData.range.startLineNumber, colorHoverData.range.startColumn, colorHoverData.range.endLineNumber, colorHoverData.range.endColumn);
      if (this._color) {
        await updateColorPresentations(this._editor.getModel(), colorPickerModel, this._color, range2, colorHoverData);
        range2 = updateEditorModel(this._editor, range2, colorPickerModel);
      }
    }
    renderHoverParts(context, hoverParts) {
      if (hoverParts.length === 0 || !this._editor.hasModel()) {
        return void 0;
      }
      this._setMinimumDimensions(context);
      this._renderedParts = new StandaloneColorPickerRenderedParts(this._editor, context, hoverParts[0], this._themeService);
      return this._renderedParts;
    }
    _setMinimumDimensions(context) {
      const minimumHeight = this._editor.getOption(
        75
        /* EditorOption.lineHeight */
      ) + 8;
      context.setMinimumDimensions(new Dimension(302, minimumHeight));
    }
    get _color() {
      return this._renderedParts?.color;
    }
  };
  StandaloneColorPickerParticipant = __decorate$1P([
    __param$1O(1, IThemeService)
  ], StandaloneColorPickerParticipant);
  var __decorate$1O = 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$1N = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  var StandaloneColorPickerWidget_1;
  class StandaloneColorPickerResult {
    // The color picker result consists of: an array of color results and a boolean indicating if the color was found in the editor
    constructor(value, foundInEditor) {
      this.value = value;
      this.foundInEditor = foundInEditor;
    }
  }
  const PADDING = 8;
  const CLOSE_BUTTON_WIDTH = 22;
  let StandaloneColorPickerWidget = (_Q = class extends Disposable {
    constructor(_editor, _standaloneColorPickerVisible, _standaloneColorPickerFocused, _instantiationService, _keybindingService, _languageFeaturesService, _editorWorkerService, _hoverService) {
      super();
      this._editor = _editor;
      this._standaloneColorPickerVisible = _standaloneColorPickerVisible;
      this._standaloneColorPickerFocused = _standaloneColorPickerFocused;
      this._keybindingService = _keybindingService;
      this._languageFeaturesService = _languageFeaturesService;
      this._editorWorkerService = _editorWorkerService;
      this._hoverService = _hoverService;
      this.allowEditorOverflow = true;
      this._position = void 0;
      this._body = document.createElement("div");
      this._colorHover = null;
      this._selectionSetInEditor = false;
      this._onResult = this._register(new Emitter$1());
      this.onResult = this._onResult.event;
      this._renderedHoverParts = this._register(new MutableDisposable());
      this._renderedStatusBar = this._register(new MutableDisposable());
      this._standaloneColorPickerVisible.set(true);
      this._standaloneColorPickerParticipant = _instantiationService.createInstance(StandaloneColorPickerParticipant, this._editor);
      this._position = this._editor._getViewModel()?.getPrimaryCursorState().modelState.position;
      const editorSelection = this._editor.getSelection();
      const selection = editorSelection ? {
        startLineNumber: editorSelection.startLineNumber,
        startColumn: editorSelection.startColumn,
        endLineNumber: editorSelection.endLineNumber,
        endColumn: editorSelection.endColumn
      } : { startLineNumber: 0, endLineNumber: 0, endColumn: 0, startColumn: 0 };
      const focusTracker = this._register(trackFocus(this._body));
      this._register(focusTracker.onDidBlur((_) => {
        this.hide();
      }));
      this._register(focusTracker.onDidFocus((_) => {
        this.focus();
      }));
      this._register(this._editor.onDidChangeCursorPosition(() => {
        if (!this._selectionSetInEditor) {
          this.hide();
        } else {
          this._selectionSetInEditor = false;
        }
      }));
      this._register(this._editor.onMouseMove((e) => {
        const classList = e.target.element?.classList;
        if (classList && classList.contains("colorpicker-color-decoration")) {
          this.hide();
        }
      }));
      this._register(this.onResult((result) => {
        this._render(result.value, result.foundInEditor);
      }));
      this._start(selection);
      this._body.style.zIndex = "50";
      this._editor.addContentWidget(this);
    }
    updateEditor() {
      if (this._colorHover) {
        this._standaloneColorPickerParticipant.updateEditorModel(this._colorHover);
      }
    }
    getId() {
      return StandaloneColorPickerWidget_1.ID;
    }
    getDomNode() {
      return this._body;
    }
    getPosition() {
      if (!this._position) {
        return null;
      }
      const positionPreference = this._editor.getOption(
        69
        /* EditorOption.hover */
      ).above;
      return {
        position: this._position,
        secondaryPosition: this._position,
        preference: positionPreference ? [
          1,
          2
          /* ContentWidgetPositionPreference.BELOW */
        ] : [
          2,
          1
          /* ContentWidgetPositionPreference.ABOVE */
        ],
        positionAffinity: 2
        /* PositionAffinity.None */
      };
    }
    hide() {
      this.dispose();
      this._standaloneColorPickerVisible.set(false);
      this._standaloneColorPickerFocused.set(false);
      this._editor.removeContentWidget(this);
      this._editor.focus();
    }
    focus() {
      this._standaloneColorPickerFocused.set(true);
      this._body.focus();
    }
    async _start(selection) {
      const computeAsyncResult = await this._computeAsync(selection);
      if (!computeAsyncResult) {
        return;
      }
      this._onResult.fire(new StandaloneColorPickerResult(computeAsyncResult.result, computeAsyncResult.foundInEditor));
    }
    async _computeAsync(range2) {
      if (!this._editor.hasModel()) {
        return null;
      }
      const colorInfo = {
        range: range2,
        color: { red: 0, green: 0, blue: 0, alpha: 1 }
      };
      const colorHoverResult = await this._standaloneColorPickerParticipant.createColorHover(colorInfo, new DefaultDocumentColorProvider(this._editorWorkerService), this._languageFeaturesService.colorProvider);
      if (!colorHoverResult) {
        return null;
      }
      return { result: colorHoverResult.colorHover, foundInEditor: colorHoverResult.foundInEditor };
    }
    _render(colorHover, foundInEditor) {
      const fragment = document.createDocumentFragment();
      this._renderedStatusBar.value = this._register(new EditorHoverStatusBar(this._keybindingService, this._hoverService));
      const context = {
        fragment,
        statusBar: this._renderedStatusBar.value,
        onContentsChanged: () => {
        },
        setMinimumDimensions: () => {
        },
        hide: () => this.hide(),
        focus: () => this.focus()
      };
      this._colorHover = colorHover;
      this._renderedHoverParts.value = this._standaloneColorPickerParticipant.renderHoverParts(context, [colorHover]);
      if (!this._renderedHoverParts.value) {
        this._renderedStatusBar.clear();
        this._renderedHoverParts.clear();
        return;
      }
      const colorPicker = this._renderedHoverParts.value.colorPicker;
      this._body.classList.add("standalone-colorpicker-body");
      this._body.style.maxHeight = Math.max(this._editor.getLayoutInfo().height / 4, 250) + "px";
      this._body.style.maxWidth = Math.max(this._editor.getLayoutInfo().width * 0.66, 500) + "px";
      this._body.tabIndex = 0;
      this._body.appendChild(fragment);
      colorPicker.layout();
      const colorPickerBody = colorPicker.body;
      const saturationBoxWidth = colorPickerBody.saturationBox.domNode.clientWidth;
      const widthOfOriginalColorBox = colorPickerBody.domNode.clientWidth - saturationBoxWidth - CLOSE_BUTTON_WIDTH - PADDING;
      const enterButton = colorPicker.body.enterButton;
      enterButton?.onClicked(() => {
        this.updateEditor();
        this.hide();
      });
      const colorPickerHeader = colorPicker.header;
      const pickedColorNode = colorPickerHeader.pickedColorNode;
      pickedColorNode.style.width = saturationBoxWidth + PADDING + "px";
      const originalColorNode = colorPickerHeader.originalColorNode;
      originalColorNode.style.width = widthOfOriginalColorBox + "px";
      const closeButton = colorPicker.header.closeButton;
      closeButton?.onClicked(() => {
        this.hide();
      });
      if (foundInEditor) {
        if (enterButton) {
          enterButton.button.textContent = "Replace";
        }
        this._selectionSetInEditor = true;
        this._editor.setSelection(colorHover.range);
      }
      this._editor.layoutContentWidget(this);
    }
  }, StandaloneColorPickerWidget_1 = _Q, _Q.ID = "editor.contrib.standaloneColorPickerWidget", _Q);
  StandaloneColorPickerWidget = StandaloneColorPickerWidget_1 = __decorate$1O([
    __param$1N(3, IInstantiationService),
    __param$1N(4, IKeybindingService),
    __param$1N(5, ILanguageFeaturesService),
    __param$1N(6, IEditorWorkerService),
    __param$1N(7, IHoverService)
  ], StandaloneColorPickerWidget);
  var __decorate$1N = 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$1M = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  var StandaloneColorPickerController_1;
  let StandaloneColorPickerController = (_R = class extends Disposable {
    constructor(_editor, _contextKeyService, _instantiationService) {
      super();
      this._editor = _editor;
      this._instantiationService = _instantiationService;
      this._standaloneColorPickerWidget = null;
      this._standaloneColorPickerVisible = EditorContextKeys.standaloneColorPickerVisible.bindTo(_contextKeyService);
      this._standaloneColorPickerFocused = EditorContextKeys.standaloneColorPickerFocused.bindTo(_contextKeyService);
    }
    showOrFocus() {
      if (!this._editor.hasModel()) {
        return;
      }
      if (!this._standaloneColorPickerVisible.get()) {
        this._standaloneColorPickerWidget = this._instantiationService.createInstance(StandaloneColorPickerWidget, this._editor, this._standaloneColorPickerVisible, this._standaloneColorPickerFocused);
      } else if (!this._standaloneColorPickerFocused.get()) {
        this._standaloneColorPickerWidget?.focus();
      }
    }
    hide() {
      this._standaloneColorPickerFocused.set(false);
      this._standaloneColorPickerVisible.set(false);
      this._standaloneColorPickerWidget?.hide();
      this._editor.focus();
    }
    insertColor() {
      this._standaloneColorPickerWidget?.updateEditor();
      this.hide();
    }
    static get(editor2) {
      return editor2.getContribution(StandaloneColorPickerController_1.ID);
    }
  }, StandaloneColorPickerController_1 = _R, _R.ID = "editor.contrib.standaloneColorPickerController", _R);
  StandaloneColorPickerController = StandaloneColorPickerController_1 = __decorate$1N([
    __param$1M(1, IContextKeyService),
    __param$1M(2, IInstantiationService)
  ], StandaloneColorPickerController);
  class ShowOrFocusStandaloneColorPicker extends EditorAction2 {
    constructor() {
      super({
        id: "editor.action.showOrFocusStandaloneColorPicker",
        title: {
          ...localize2(889, "Show or Focus Standalone Color Picker"),
          mnemonicTitle: localize(888, "&&Show or Focus Standalone Color Picker")
        },
        precondition: void 0,
        menu: [
          { id: MenuId.CommandPalette }
        ],
        metadata: {
          description: localize2(890, "Show or focus a standalone color picker which uses the default color provider. It displays hex/rgb/hsl colors.")
        }
      });
    }
    runEditorCommand(_accessor, editor2) {
      StandaloneColorPickerController.get(editor2)?.showOrFocus();
    }
  }
  class HideStandaloneColorPicker extends EditorAction {
    constructor() {
      super({
        id: "editor.action.hideColorPicker",
        label: localize2(891, "Hide the Color Picker"),
        precondition: EditorContextKeys.standaloneColorPickerVisible.isEqualTo(true),
        kbOpts: {
          primary: 9,
          weight: 100
          /* KeybindingWeight.EditorContrib */
        },
        metadata: {
          description: localize2(892, "Hide the standalone color picker.")
        }
      });
    }
    run(_accessor, editor2) {
      StandaloneColorPickerController.get(editor2)?.hide();
    }
  }
  class InsertColorWithStandaloneColorPicker extends EditorAction {
    constructor() {
      super({
        id: "editor.action.insertColorWithStandaloneColorPicker",
        label: localize2(893, "Insert Color with Standalone Color Picker"),
        precondition: EditorContextKeys.standaloneColorPickerFocused.isEqualTo(true),
        kbOpts: {
          primary: 3,
          weight: 100
          /* KeybindingWeight.EditorContrib */
        },
        metadata: {
          description: localize2(894, "Insert hex/rgb/hsl colors with the focused standalone color picker.")
        }
      });
    }
    run(_accessor, editor2) {
      StandaloneColorPickerController.get(editor2)?.insertColor();
    }
  }
  registerEditorAction(HideStandaloneColorPicker);
  registerEditorAction(InsertColorWithStandaloneColorPicker);
  registerAction2(ShowOrFocusStandaloneColorPicker);
  registerEditorContribution(
    HoverColorPickerContribution.ID,
    HoverColorPickerContribution,
    2
    /* EditorContributionInstantiation.BeforeFirstInteraction */
  );
  registerEditorContribution(
    StandaloneColorPickerController.ID,
    StandaloneColorPickerController,
    1
    /* EditorContributionInstantiation.AfterFirstRender */
  );
  registerEditorContribution(
    ColorDetector.ID,
    ColorDetector,
    1
    /* EditorContributionInstantiation.AfterFirstRender */
  );
  registerEditorFeature(DefaultDocumentColorProviderFeature);
  HoverParticipantRegistry.register(HoverColorPickerParticipant);
  CommandsRegistry.registerCommand("_executeDocumentColorProvider", function(accessor, ...args) {
    const [resource] = args;
    if (!(resource instanceof URI)) {
      throw illegalArgument();
    }
    const { model, colorProviderRegistry, defaultColorDecoratorsEnablement } = _setupColorCommand(accessor, resource);
    return _findColorData(new ExtColorDataCollector(), colorProviderRegistry, model, CancellationToken.None, defaultColorDecoratorsEnablement);
  });
  CommandsRegistry.registerCommand("_executeColorPresentationProvider", function(accessor, ...args) {
    const [color, context] = args;
    if (!context) {
      return;
    }
    const { uri, range: range2 } = context;
    if (!(uri instanceof URI) || !Array.isArray(color) || color.length !== 4 || !Range$2.isIRange(range2)) {
      throw illegalArgument();
    }
    const { model, colorProviderRegistry, defaultColorDecoratorsEnablement } = _setupColorCommand(accessor, uri);
    const [red, green, blue, alpha] = color;
    return _findColorData(new ColorPresentationsCollector({ range: range2, color: { red, green, blue, alpha } }), colorProviderRegistry, model, CancellationToken.None, defaultColorDecoratorsEnablement);
  });
  class BlockCommentCommand {
    constructor(selection, insertSpace, languageConfigurationService) {
      this.languageConfigurationService = languageConfigurationService;
      this._selection = selection;
      this._insertSpace = insertSpace;
      this._usedEndToken = null;
    }
    static _haystackHasNeedleAtOffset(haystack, needle, offset) {
      if (offset < 0) {
        return false;
      }
      const needleLength = needle.length;
      const haystackLength = haystack.length;
      if (offset + needleLength > haystackLength) {
        return false;
      }
      for (let i2 = 0; i2 < needleLength; i2++) {
        const codeA = haystack.charCodeAt(offset + i2);
        const codeB = needle.charCodeAt(i2);
        if (codeA === codeB) {
          continue;
        }
        if (codeA >= 65 && codeA <= 90 && codeA + 32 === codeB) {
          continue;
        }
        if (codeB >= 65 && codeB <= 90 && codeB + 32 === codeA) {
          continue;
        }
        return false;
      }
      return true;
    }
    _createOperationsForBlockComment(selection, startToken, endToken, insertSpace, model, builder) {
      const startLineNumber = selection.startLineNumber;
      const startColumn = selection.startColumn;
      const endLineNumber = selection.endLineNumber;
      const endColumn = selection.endColumn;
      const startLineText = model.getLineContent(startLineNumber);
      const endLineText = model.getLineContent(endLineNumber);
      let startTokenIndex = startLineText.lastIndexOf(startToken, startColumn - 1 + startToken.length);
      let endTokenIndex = endLineText.indexOf(endToken, endColumn - 1 - endToken.length);
      if (startTokenIndex !== -1 && endTokenIndex !== -1) {
        if (startLineNumber === endLineNumber) {
          const lineBetweenTokens = startLineText.substring(startTokenIndex + startToken.length, endTokenIndex);
          if (lineBetweenTokens.indexOf(endToken) >= 0) {
            startTokenIndex = -1;
            endTokenIndex = -1;
          }
        } else {
          const startLineAfterStartToken = startLineText.substring(startTokenIndex + startToken.length);
          const endLineBeforeEndToken = endLineText.substring(0, endTokenIndex);
          if (startLineAfterStartToken.indexOf(endToken) >= 0 || endLineBeforeEndToken.indexOf(endToken) >= 0) {
            startTokenIndex = -1;
            endTokenIndex = -1;
          }
        }
      }
      let ops;
      if (startTokenIndex !== -1 && endTokenIndex !== -1) {
        if (insertSpace && startTokenIndex + startToken.length < startLineText.length && startLineText.charCodeAt(startTokenIndex + startToken.length) === 32) {
          startToken = startToken + " ";
        }
        if (insertSpace && endTokenIndex > 0 && endLineText.charCodeAt(endTokenIndex - 1) === 32) {
          endToken = " " + endToken;
          endTokenIndex -= 1;
        }
        ops = BlockCommentCommand._createRemoveBlockCommentOperations(new Range$2(startLineNumber, startTokenIndex + startToken.length + 1, endLineNumber, endTokenIndex + 1), startToken, endToken);
      } else {
        ops = BlockCommentCommand._createAddBlockCommentOperations(selection, startToken, endToken, this._insertSpace);
        this._usedEndToken = ops.length === 1 ? endToken : null;
      }
      for (const op of ops) {
        builder.addTrackedEditOperation(op.range, op.text);
      }
    }
    static _createRemoveBlockCommentOperations(r, startToken, endToken) {
      const res = [];
      if (!Range$2.isEmpty(r)) {
        res.push(EditOperation.delete(new Range$2(r.startLineNumber, r.startColumn - startToken.length, r.startLineNumber, r.startColumn)));
        res.push(EditOperation.delete(new Range$2(r.endLineNumber, r.endColumn, r.endLineNumber, r.endColumn + endToken.length)));
      } else {
        res.push(EditOperation.delete(new Range$2(r.startLineNumber, r.startColumn - startToken.length, r.endLineNumber, r.endColumn + endToken.length)));
      }
      return res;
    }
    static _createAddBlockCommentOperations(r, startToken, endToken, insertSpace) {
      const res = [];
      if (!Range$2.isEmpty(r)) {
        res.push(EditOperation.insert(new Position$1(r.startLineNumber, r.startColumn), startToken + (insertSpace ? " " : "")));
        res.push(EditOperation.insert(new Position$1(r.endLineNumber, r.endColumn), (insertSpace ? " " : "") + endToken));
      } else {
        res.push(EditOperation.replace(new Range$2(r.startLineNumber, r.startColumn, r.endLineNumber, r.endColumn), startToken + "  " + endToken));
      }
      return res;
    }
    getEditOperations(model, builder) {
      const startLineNumber = this._selection.startLineNumber;
      const startColumn = this._selection.startColumn;
      model.tokenization.tokenizeIfCheap(startLineNumber);
      const languageId = model.getLanguageIdAtPosition(startLineNumber, startColumn);
      const config = this.languageConfigurationService.getLanguageConfiguration(languageId).comments;
      if (!config || !config.blockCommentStartToken || !config.blockCommentEndToken) {
        return;
      }
      this._createOperationsForBlockComment(this._selection, config.blockCommentStartToken, config.blockCommentEndToken, this._insertSpace, model, builder);
    }
    computeCursorState(model, helper) {
      const inverseEditOperations = helper.getInverseEditOperations();
      if (inverseEditOperations.length === 2) {
        const startTokenEditOperation = inverseEditOperations[0];
        const endTokenEditOperation = inverseEditOperations[1];
        return new Selection$1(startTokenEditOperation.range.endLineNumber, startTokenEditOperation.range.endColumn, endTokenEditOperation.range.startLineNumber, endTokenEditOperation.range.startColumn);
      } else {
        const srcRange = inverseEditOperations[0].range;
        const deltaColumn = this._usedEndToken ? -this._usedEndToken.length - 1 : 0;
        return new Selection$1(srcRange.endLineNumber, srcRange.endColumn + deltaColumn, srcRange.endLineNumber, srcRange.endColumn + deltaColumn);
      }
    }
  }
  class LineCommentCommand {
    constructor(languageConfigurationService, selection, indentSize, type, insertSpace, ignoreEmptyLines, ignoreFirstLine) {
      this.languageConfigurationService = languageConfigurationService;
      this._selection = selection;
      this._indentSize = indentSize;
      this._type = type;
      this._insertSpace = insertSpace;
      this._selectionId = null;
      this._deltaColumn = 0;
      this._moveEndPositionDown = false;
      this._ignoreEmptyLines = ignoreEmptyLines;
      this._ignoreFirstLine = ignoreFirstLine || false;
    }
    /**
     * Do an initial pass over the lines and gather info about the line comment string.
     * Returns null if any of the lines doesn't support a line comment string.
     */
    static _gatherPreflightCommentStrings(model, startLineNumber, endLineNumber, languageConfigurationService) {
      model.tokenization.tokenizeIfCheap(startLineNumber);
      const languageId = model.getLanguageIdAtPosition(startLineNumber, 1);
      const config = languageConfigurationService.getLanguageConfiguration(languageId).comments;
      const commentStr = config ? config.lineCommentToken : null;
      if (!commentStr) {
        return null;
      }
      const lines = [];
      for (let i2 = 0, lineCount = endLineNumber - startLineNumber + 1; i2 < lineCount; i2++) {
        lines[i2] = {
          ignore: false,
          commentStr,
          commentStrOffset: 0,
          commentStrLength: commentStr.length
        };
      }
      return lines;
    }
    /**
     * Analyze lines and decide which lines are relevant and what the toggle should do.
     * Also, build up several offsets and lengths useful in the generation of editor operations.
     */
    static _analyzeLines(type, insertSpace, model, lines, startLineNumber, ignoreEmptyLines, ignoreFirstLine, languageConfigurationService, languageId) {
      let onlyWhitespaceLines = true;
      const config = languageConfigurationService.getLanguageConfiguration(languageId).comments;
      const lineCommentNoIndent = config?.lineCommentNoIndent ?? false;
      let shouldRemoveComments;
      if (type === 0) {
        shouldRemoveComments = true;
      } else if (type === 1) {
        shouldRemoveComments = false;
      } else {
        shouldRemoveComments = true;
      }
      for (let i2 = 0, lineCount = lines.length; i2 < lineCount; i2++) {
        const lineData = lines[i2];
        const lineNumber = startLineNumber + i2;
        if (lineNumber === startLineNumber && ignoreFirstLine) {
          lineData.ignore = true;
          continue;
        }
        const lineContent = model.getLineContent(lineNumber);
        const lineContentStartOffset = firstNonWhitespaceIndex(lineContent);
        if (lineContentStartOffset === -1) {
          lineData.ignore = ignoreEmptyLines;
          lineData.commentStrOffset = lineCommentNoIndent ? 0 : lineContent.length;
          continue;
        }
        onlyWhitespaceLines = false;
        const offset = lineCommentNoIndent ? 0 : lineContentStartOffset;
        lineData.ignore = false;
        lineData.commentStrOffset = offset;
        if (shouldRemoveComments && !BlockCommentCommand._haystackHasNeedleAtOffset(lineContent, lineData.commentStr, offset)) {
          if (type === 0) {
            shouldRemoveComments = false;
          } else if (type === 1) ;
          else {
            lineData.ignore = true;
          }
        }
        if (shouldRemoveComments && insertSpace) {
          const commentStrEndOffset = lineContentStartOffset + lineData.commentStrLength;
          if (commentStrEndOffset < lineContent.length && lineContent.charCodeAt(commentStrEndOffset) === 32) {
            lineData.commentStrLength += 1;
          }
        }
      }
      if (type === 0 && onlyWhitespaceLines) {
        shouldRemoveComments = false;
        for (let i2 = 0, lineCount = lines.length; i2 < lineCount; i2++) {
          lines[i2].ignore = false;
        }
      }
      return {
        supported: true,
        shouldRemoveComments,
        lines
      };
    }
    /**
     * Analyze all lines and decide exactly what to do => not supported | insert line comments | remove line comments
     */
    static _gatherPreflightData(type, insertSpace, model, startLineNumber, endLineNumber, ignoreEmptyLines, ignoreFirstLine, languageConfigurationService) {
      const lines = LineCommentCommand._gatherPreflightCommentStrings(model, startLineNumber, endLineNumber, languageConfigurationService);
      const languageId = model.getLanguageIdAtPosition(startLineNumber, 1);
      if (lines === null) {
        return {
          supported: false
        };
      }
      return LineCommentCommand._analyzeLines(type, insertSpace, model, lines, startLineNumber, ignoreEmptyLines, ignoreFirstLine, languageConfigurationService, languageId);
    }
    /**
     * Given a successful analysis, execute either insert line comments, either remove line comments
     */
    _executeLineComments(model, builder, data, s) {
      let ops;
      if (data.shouldRemoveComments) {
        ops = LineCommentCommand._createRemoveLineCommentsOperations(data.lines, s.startLineNumber);
      } else {
        LineCommentCommand._normalizeInsertionPoint(model, data.lines, s.startLineNumber, this._indentSize);
        ops = this._createAddLineCommentsOperations(data.lines, s.startLineNumber);
      }
      const cursorPosition = new Position$1(s.positionLineNumber, s.positionColumn);
      for (let i2 = 0, len = ops.length; i2 < len; i2++) {
        builder.addEditOperation(ops[i2].range, ops[i2].text);
        if (Range$2.isEmpty(ops[i2].range) && Range$2.getStartPosition(ops[i2].range).equals(cursorPosition)) {
          const lineContent = model.getLineContent(cursorPosition.lineNumber);
          if (lineContent.length + 1 === cursorPosition.column) {
            this._deltaColumn = (ops[i2].text || "").length;
          }
        }
      }
      this._selectionId = builder.trackSelection(s);
    }
    _attemptRemoveBlockComment(model, s, startToken, endToken) {
      let startLineNumber = s.startLineNumber;
      let endLineNumber = s.endLineNumber;
      const startTokenAllowedBeforeColumn = endToken.length + Math.max(model.getLineFirstNonWhitespaceColumn(s.startLineNumber), s.startColumn);
      let startTokenIndex = model.getLineContent(startLineNumber).lastIndexOf(startToken, startTokenAllowedBeforeColumn - 1);
      let endTokenIndex = model.getLineContent(endLineNumber).indexOf(endToken, s.endColumn - 1 - startToken.length);
      if (startTokenIndex !== -1 && endTokenIndex === -1) {
        endTokenIndex = model.getLineContent(startLineNumber).indexOf(endToken, startTokenIndex + startToken.length);
        endLineNumber = startLineNumber;
      }
      if (startTokenIndex === -1 && endTokenIndex !== -1) {
        startTokenIndex = model.getLineContent(endLineNumber).lastIndexOf(startToken, endTokenIndex);
        startLineNumber = endLineNumber;
      }
      if (s.isEmpty() && (startTokenIndex === -1 || endTokenIndex === -1)) {
        startTokenIndex = model.getLineContent(startLineNumber).indexOf(startToken);
        if (startTokenIndex !== -1) {
          endTokenIndex = model.getLineContent(startLineNumber).indexOf(endToken, startTokenIndex + startToken.length);
        }
      }
      if (startTokenIndex !== -1 && model.getLineContent(startLineNumber).charCodeAt(startTokenIndex + startToken.length) === 32) {
        startToken += " ";
      }
      if (endTokenIndex !== -1 && model.getLineContent(endLineNumber).charCodeAt(endTokenIndex - 1) === 32) {
        endToken = " " + endToken;
        endTokenIndex -= 1;
      }
      if (startTokenIndex !== -1 && endTokenIndex !== -1) {
        return BlockCommentCommand._createRemoveBlockCommentOperations(new Range$2(startLineNumber, startTokenIndex + startToken.length + 1, endLineNumber, endTokenIndex + 1), startToken, endToken);
      }
      return null;
    }
    /**
     * Given an unsuccessful analysis, delegate to the block comment command
     */
    _executeBlockComment(model, builder, s) {
      model.tokenization.tokenizeIfCheap(s.startLineNumber);
      const languageId = model.getLanguageIdAtPosition(s.startLineNumber, 1);
      const config = this.languageConfigurationService.getLanguageConfiguration(languageId).comments;
      if (!config || !config.blockCommentStartToken || !config.blockCommentEndToken) {
        return;
      }
      const startToken = config.blockCommentStartToken;
      const endToken = config.blockCommentEndToken;
      let ops = this._attemptRemoveBlockComment(model, s, startToken, endToken);
      if (!ops) {
        if (s.isEmpty()) {
          const lineContent = model.getLineContent(s.startLineNumber);
          let firstNonWhitespaceIndex$1 = firstNonWhitespaceIndex(lineContent);
          if (firstNonWhitespaceIndex$1 === -1) {
            firstNonWhitespaceIndex$1 = lineContent.length;
          }
          ops = BlockCommentCommand._createAddBlockCommentOperations(new Range$2(s.startLineNumber, firstNonWhitespaceIndex$1 + 1, s.startLineNumber, lineContent.length + 1), startToken, endToken, this._insertSpace);
        } else {
          ops = BlockCommentCommand._createAddBlockCommentOperations(new Range$2(s.startLineNumber, model.getLineFirstNonWhitespaceColumn(s.startLineNumber), s.endLineNumber, model.getLineMaxColumn(s.endLineNumber)), startToken, endToken, this._insertSpace);
        }
        if (ops.length === 1) {
          this._deltaColumn = startToken.length + 1;
        }
      }
      this._selectionId = builder.trackSelection(s);
      for (const op of ops) {
        builder.addEditOperation(op.range, op.text);
      }
    }
    getEditOperations(model, builder) {
      let s = this._selection;
      this._moveEndPositionDown = false;
      if (s.startLineNumber === s.endLineNumber && this._ignoreFirstLine) {
        builder.addEditOperation(new Range$2(s.startLineNumber, model.getLineMaxColumn(s.startLineNumber), s.startLineNumber + 1, 1), s.startLineNumber === model.getLineCount() ? "" : "\n");
        this._selectionId = builder.trackSelection(s);
        return;
      }
      if (s.startLineNumber < s.endLineNumber && s.endColumn === 1) {
        this._moveEndPositionDown = true;
        s = s.setEndPosition(s.endLineNumber - 1, model.getLineMaxColumn(s.endLineNumber - 1));
      }
      const data = LineCommentCommand._gatherPreflightData(this._type, this._insertSpace, model, s.startLineNumber, s.endLineNumber, this._ignoreEmptyLines, this._ignoreFirstLine, this.languageConfigurationService);
      if (data.supported) {
        return this._executeLineComments(model, builder, data, s);
      }
      return this._executeBlockComment(model, builder, s);
    }
    computeCursorState(model, helper) {
      let result = helper.getTrackedSelection(this._selectionId);
      if (this._moveEndPositionDown) {
        result = result.setEndPosition(result.endLineNumber + 1, 1);
      }
      return new Selection$1(result.selectionStartLineNumber, result.selectionStartColumn + this._deltaColumn, result.positionLineNumber, result.positionColumn + this._deltaColumn);
    }
    /**
     * Generate edit operations in the remove line comment case
     */
    static _createRemoveLineCommentsOperations(lines, startLineNumber) {
      const res = [];
      for (let i2 = 0, len = lines.length; i2 < len; i2++) {
        const lineData = lines[i2];
        if (lineData.ignore) {
          continue;
        }
        res.push(EditOperation.delete(new Range$2(startLineNumber + i2, lineData.commentStrOffset + 1, startLineNumber + i2, lineData.commentStrOffset + lineData.commentStrLength + 1)));
      }
      return res;
    }
    /**
     * Generate edit operations in the add line comment case
     */
    _createAddLineCommentsOperations(lines, startLineNumber) {
      const res = [];
      const afterCommentStr = this._insertSpace ? " " : "";
      for (let i2 = 0, len = lines.length; i2 < len; i2++) {
        const lineData = lines[i2];
        if (lineData.ignore) {
          continue;
        }
        res.push(EditOperation.insert(new Position$1(startLineNumber + i2, lineData.commentStrOffset + 1), lineData.commentStr + afterCommentStr));
      }
      return res;
    }
    static nextVisibleColumn(currentVisibleColumn, indentSize, isTab, columnSize) {
      if (isTab) {
        return currentVisibleColumn + (indentSize - currentVisibleColumn % indentSize);
      }
      return currentVisibleColumn + columnSize;
    }
    /**
     * Adjust insertion points to have them vertically aligned in the add line comment case
     */
    static _normalizeInsertionPoint(model, lines, startLineNumber, indentSize) {
      let minVisibleColumn = 1073741824;
      let j;
      let lenJ;
      for (let i2 = 0, len = lines.length; i2 < len; i2++) {
        if (lines[i2].ignore) {
          continue;
        }
        const lineContent = model.getLineContent(startLineNumber + i2);
        let currentVisibleColumn = 0;
        for (let j2 = 0, lenJ2 = lines[i2].commentStrOffset; currentVisibleColumn < minVisibleColumn && j2 < lenJ2; j2++) {
          currentVisibleColumn = LineCommentCommand.nextVisibleColumn(currentVisibleColumn, indentSize, lineContent.charCodeAt(j2) === 9, 1);
        }
        if (currentVisibleColumn < minVisibleColumn) {
          minVisibleColumn = currentVisibleColumn;
        }
      }
      minVisibleColumn = Math.floor(minVisibleColumn / indentSize) * indentSize;
      for (let i2 = 0, len = lines.length; i2 < len; i2++) {
        if (lines[i2].ignore) {
          continue;
        }
        const lineContent = model.getLineContent(startLineNumber + i2);
        let currentVisibleColumn = 0;
        for (j = 0, lenJ = lines[i2].commentStrOffset; currentVisibleColumn < minVisibleColumn && j < lenJ; j++) {
          currentVisibleColumn = LineCommentCommand.nextVisibleColumn(currentVisibleColumn, indentSize, lineContent.charCodeAt(j) === 9, 1);
        }
        if (currentVisibleColumn > minVisibleColumn) {
          lines[i2].commentStrOffset = j - 1;
        } else {
          lines[i2].commentStrOffset = j;
        }
      }
    }
  }
  class CommentLineAction extends EditorAction {
    constructor(type, opts) {
      super(opts);
      this._type = type;
    }
    run(accessor, editor2) {
      const languageConfigurationService = accessor.get(ILanguageConfigurationService);
      if (!editor2.hasModel()) {
        return;
      }
      const model = editor2.getModel();
      const commands = [];
      const modelOptions = model.getOptions();
      const commentsOptions = editor2.getOption(
        29
        /* EditorOption.comments */
      );
      const selections = editor2.getSelections().map((selection, index) => ({ selection, index, ignoreFirstLine: false }));
      selections.sort((a, b) => Range$2.compareRangesUsingStarts(a.selection, b.selection));
      let prev = selections[0];
      for (let i2 = 1; i2 < selections.length; i2++) {
        const curr = selections[i2];
        if (prev.selection.endLineNumber === curr.selection.startLineNumber) {
          if (prev.index < curr.index) {
            curr.ignoreFirstLine = true;
          } else {
            prev.ignoreFirstLine = true;
            prev = curr;
          }
        }
      }
      for (const selection of selections) {
        commands.push(new LineCommentCommand(languageConfigurationService, selection.selection, modelOptions.indentSize, this._type, commentsOptions.insertSpace, commentsOptions.ignoreEmptyLines, selection.ignoreFirstLine));
      }
      editor2.pushUndoStop();
      editor2.executeCommands(this.id, commands);
      editor2.pushUndoStop();
    }
  }
  class ToggleCommentLineAction extends CommentLineAction {
    constructor() {
      super(0, {
        id: "editor.action.commentLine",
        label: localize2(897, "Toggle Line Comment"),
        precondition: EditorContextKeys.writable,
        kbOpts: {
          kbExpr: EditorContextKeys.editorTextFocus,
          primary: 2048 | 90,
          weight: 100
          /* KeybindingWeight.EditorContrib */
        },
        menuOpts: {
          menuId: MenuId.MenubarEditMenu,
          group: "5_insert",
          title: localize(895, "&&Toggle Line Comment"),
          order: 1
        },
        canTriggerInlineEdits: true
      });
    }
  }
  class AddLineCommentAction extends CommentLineAction {
    constructor() {
      super(1, {
        id: "editor.action.addCommentLine",
        label: localize2(898, "Add Line Comment"),
        precondition: EditorContextKeys.writable,
        kbOpts: {
          kbExpr: EditorContextKeys.editorTextFocus,
          primary: KeyChord(
            2048 | 41,
            2048 | 33
            /* KeyCode.KeyC */
          ),
          weight: 100
          /* KeybindingWeight.EditorContrib */
        },
        canTriggerInlineEdits: true
      });
    }
  }
  class RemoveLineCommentAction extends CommentLineAction {
    constructor() {
      super(2, {
        id: "editor.action.removeCommentLine",
        label: localize2(899, "Remove Line Comment"),
        precondition: EditorContextKeys.writable,
        kbOpts: {
          kbExpr: EditorContextKeys.editorTextFocus,
          primary: KeyChord(
            2048 | 41,
            2048 | 51
            /* KeyCode.KeyU */
          ),
          weight: 100
          /* KeybindingWeight.EditorContrib */
        },
        canTriggerInlineEdits: true
      });
    }
  }
  class BlockCommentAction extends EditorAction {
    constructor() {
      super({
        id: "editor.action.blockComment",
        label: localize2(900, "Toggle Block Comment"),
        precondition: EditorContextKeys.writable,
        kbOpts: {
          kbExpr: EditorContextKeys.editorTextFocus,
          primary: 1024 | 512 | 31,
          linux: {
            primary: 2048 | 1024 | 31
            /* KeyCode.KeyA */
          },
          weight: 100
          /* KeybindingWeight.EditorContrib */
        },
        menuOpts: {
          menuId: MenuId.MenubarEditMenu,
          group: "5_insert",
          title: localize(896, "Toggle &&Block Comment"),
          order: 2
        },
        canTriggerInlineEdits: true
      });
    }
    run(accessor, editor2) {
      const languageConfigurationService = accessor.get(ILanguageConfigurationService);
      if (!editor2.hasModel()) {
        return;
      }
      const commentsOptions = editor2.getOption(
        29
        /* EditorOption.comments */
      );
      const commands = [];
      const selections = editor2.getSelections();
      for (const selection of selections) {
        commands.push(new BlockCommentCommand(selection, commentsOptions.insertSpace, languageConfigurationService));
      }
      editor2.pushUndoStop();
      editor2.executeCommands(this.id, commands);
      editor2.pushUndoStop();
    }
  }
  registerEditorAction(ToggleCommentLineAction);
  registerEditorAction(AddLineCommentAction);
  registerEditorAction(RemoveLineCommentAction);
  registerEditorAction(BlockCommentAction);
  var __decorate$1M = 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$1L = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  var ContextMenuController_1;
  let ContextMenuController = (_S = class {
    static get(editor2) {
      return editor2.getContribution(ContextMenuController_1.ID);
    }
    constructor(editor2, _contextMenuService, _contextViewService, _contextKeyService, _keybindingService, _menuService, _configurationService, _workspaceContextService) {
      this._contextMenuService = _contextMenuService;
      this._contextViewService = _contextViewService;
      this._contextKeyService = _contextKeyService;
      this._keybindingService = _keybindingService;
      this._menuService = _menuService;
      this._configurationService = _configurationService;
      this._workspaceContextService = _workspaceContextService;
      this._toDispose = new DisposableStore();
      this._contextMenuIsBeingShownCount = 0;
      this._editor = editor2;
      this._toDispose.add(this._editor.onContextMenu((e) => this._onContextMenu(e)));
      this._toDispose.add(this._editor.onMouseWheel((e) => {
        if (this._contextMenuIsBeingShownCount > 0) {
          const view = this._contextViewService.getContextViewElement();
          const target = e.srcElement;
          if (!(target.shadowRoot && getShadowRoot(view) === target.shadowRoot)) {
            this._contextViewService.hideContextView();
          }
        }
      }));
      this._toDispose.add(this._editor.onKeyDown((e) => {
        if (!this._editor.getOption(
          30
          /* EditorOption.contextmenu */
        )) {
          return;
        }
        if (e.keyCode === 58) {
          e.preventDefault();
          e.stopPropagation();
          this.showContextMenu();
        }
      }));
    }
    _onContextMenu(e) {
      if (!this._editor.hasModel()) {
        return;
      }
      if (!this._editor.getOption(
        30
        /* EditorOption.contextmenu */
      )) {
        this._editor.focus();
        if (e.target.position && !this._editor.getSelection().containsPosition(e.target.position)) {
          this._editor.setPosition(e.target.position);
        }
        return;
      }
      if (e.target.type === 12) {
        return;
      }
      if (e.target.type === 6 && e.target.detail.injectedText) {
        return;
      }
      e.event.preventDefault();
      e.event.stopPropagation();
      if (e.target.type === 11) {
        return this._showScrollbarContextMenu(e.event);
      }
      if (e.target.type !== 6 && e.target.type !== 7 && e.target.type !== 1) {
        return;
      }
      this._editor.focus();
      if (e.target.position) {
        let hasSelectionAtPosition = false;
        for (const selection of this._editor.getSelections()) {
          if (selection.containsPosition(e.target.position)) {
            hasSelectionAtPosition = true;
            break;
          }
        }
        if (!hasSelectionAtPosition) {
          this._editor.setPosition(e.target.position);
        }
      }
      let anchor = null;
      if (e.target.type !== 1) {
        anchor = e.event;
      }
      this.showContextMenu(anchor);
    }
    showContextMenu(anchor) {
      if (!this._editor.getOption(
        30
        /* EditorOption.contextmenu */
      )) {
        return;
      }
      if (!this._editor.hasModel()) {
        return;
      }
      const menuActions = this._getMenuActions(this._editor.getModel(), this._editor.contextMenuId);
      if (menuActions.length > 0) {
        this._doShowContextMenu(menuActions, anchor);
      }
    }
    _getMenuActions(model, menuId) {
      const result = [];
      const groups = this._menuService.getMenuActions(menuId, this._contextKeyService, { arg: model.uri });
      for (const group of groups) {
        const [, actions] = group;
        let addedItems = 0;
        for (const action of actions) {
          if (action instanceof SubmenuItemAction) {
            const subActions = this._getMenuActions(model, action.item.submenu);
            if (subActions.length > 0) {
              result.push(new SubmenuAction(action.id, action.label, subActions));
              addedItems++;
            }
          } else {
            result.push(action);
            addedItems++;
          }
        }
        if (addedItems) {
          result.push(new Separator());
        }
      }
      if (result.length) {
        result.pop();
      }
      return result;
    }
    _doShowContextMenu(actions, event = null) {
      if (!this._editor.hasModel()) {
        return;
      }
      let anchor = event;
      if (!anchor) {
        this._editor.revealPosition(
          this._editor.getPosition(),
          1
          /* ScrollType.Immediate */
        );
        this._editor.render();
        const cursorCoords = this._editor.getScrolledVisiblePosition(this._editor.getPosition());
        const editorCoords = getDomNodePagePosition(this._editor.getDomNode());
        const posx = editorCoords.left + cursorCoords.left;
        const posy = editorCoords.top + cursorCoords.top + cursorCoords.height;
        anchor = { x: posx, y: posy };
      }
      const useShadowDOM = this._editor.getOption(
        144
        /* EditorOption.useShadowDOM */
      ) && !isIOS;
      this._contextMenuIsBeingShownCount++;
      this._contextMenuService.showContextMenu({
        domForShadowRoot: useShadowDOM ? this._editor.getOverflowWidgetsDomNode() ?? this._editor.getDomNode() : void 0,
        getAnchor: () => anchor,
        getActions: () => actions,
        getActionViewItem: (action) => {
          const keybinding = this._keybindingFor(action);
          if (keybinding) {
            return new ActionViewItem(action, action, { label: true, keybinding: keybinding.getLabel(), isMenu: true });
          }
          const customAction = action;
          if (typeof customAction.getActionViewItem === "function") {
            return customAction.getActionViewItem();
          }
          return new ActionViewItem(action, action, { icon: true, label: true, isMenu: true });
        },
        getKeyBinding: (action) => {
          return this._keybindingFor(action);
        },
        onHide: (wasCancelled) => {
          this._contextMenuIsBeingShownCount--;
        }
      });
    }
    _showScrollbarContextMenu(anchor) {
      if (!this._editor.hasModel()) {
        return;
      }
      if (isStandaloneEditorWorkspace(this._workspaceContextService.getWorkspace())) {
        return;
      }
      const minimapOptions = this._editor.getOption(
        81
        /* EditorOption.minimap */
      );
      let lastId = 0;
      const createAction = (opts) => {
        return {
          id: `menu-action-${++lastId}`,
          label: opts.label,
          tooltip: "",
          class: void 0,
          enabled: typeof opts.enabled === "undefined" ? true : opts.enabled,
          checked: opts.checked,
          run: opts.run
        };
      };
      const createSubmenuAction = (label, actions2) => {
        return new SubmenuAction(`menu-action-${++lastId}`, label, actions2, void 0);
      };
      const createEnumAction = (label, enabled, configName, configuredValue, options) => {
        if (!enabled) {
          return createAction({ label, enabled, run: () => {
          } });
        }
        const createRunner = (value) => {
          return () => {
            this._configurationService.updateValue(configName, value);
          };
        };
        const actions2 = [];
        for (const option2 of options) {
          actions2.push(createAction({
            label: option2.label,
            checked: configuredValue === option2.value,
            run: createRunner(option2.value)
          }));
        }
        return createSubmenuAction(label, actions2);
      };
      const actions = [];
      actions.push(createAction({
        label: localize(901, "Minimap"),
        checked: minimapOptions.enabled,
        run: () => {
          this._configurationService.updateValue(`editor.minimap.enabled`, !minimapOptions.enabled);
        }
      }));
      actions.push(new Separator());
      actions.push(createAction({
        label: localize(902, "Render Characters"),
        enabled: minimapOptions.enabled,
        checked: minimapOptions.renderCharacters,
        run: () => {
          this._configurationService.updateValue(`editor.minimap.renderCharacters`, !minimapOptions.renderCharacters);
        }
      }));
      actions.push(createEnumAction(localize(903, "Vertical size"), minimapOptions.enabled, "editor.minimap.size", minimapOptions.size, [{
        label: localize(904, "Proportional"),
        value: "proportional"
      }, {
        label: localize(905, "Fill"),
        value: "fill"
      }, {
        label: localize(906, "Fit"),
        value: "fit"
      }]));
      actions.push(createEnumAction(localize(907, "Slider"), minimapOptions.enabled, "editor.minimap.showSlider", minimapOptions.showSlider, [{
        label: localize(908, "Mouse Over"),
        value: "mouseover"
      }, {
        label: localize(909, "Always"),
        value: "always"
      }]));
      const useShadowDOM = this._editor.getOption(
        144
        /* EditorOption.useShadowDOM */
      ) && !isIOS;
      this._contextMenuIsBeingShownCount++;
      this._contextMenuService.showContextMenu({
        domForShadowRoot: useShadowDOM ? this._editor.getDomNode() : void 0,
        getAnchor: () => anchor,
        getActions: () => actions,
        onHide: (wasCancelled) => {
          this._contextMenuIsBeingShownCount--;
          this._editor.focus();
        }
      });
    }
    _keybindingFor(action) {
      return this._keybindingService.lookupKeybinding(action.id);
    }
    dispose() {
      if (this._contextMenuIsBeingShownCount > 0) {
        this._contextViewService.hideContextView();
      }
      this._toDispose.dispose();
    }
  }, ContextMenuController_1 = _S, _S.ID = "editor.contrib.contextmenu", _S);
  ContextMenuController = ContextMenuController_1 = __decorate$1M([
    __param$1L(1, IContextMenuService),
    __param$1L(2, IContextViewService),
    __param$1L(3, IContextKeyService),
    __param$1L(4, IKeybindingService),
    __param$1L(5, IMenuService),
    __param$1L(6, IConfigurationService),
    __param$1L(7, IWorkspaceContextService)
  ], ContextMenuController);
  class ShowContextMenu extends EditorAction {
    constructor() {
      super({
        id: "editor.action.showContextMenu",
        label: localize2(910, "Show Editor Context Menu"),
        precondition: void 0,
        kbOpts: {
          kbExpr: EditorContextKeys.textInputFocus,
          primary: 1024 | 68,
          weight: 100
          /* KeybindingWeight.EditorContrib */
        }
      });
    }
    run(accessor, editor2) {
      ContextMenuController.get(editor2)?.showContextMenu();
    }
  }
  registerEditorContribution(
    ContextMenuController.ID,
    ContextMenuController,
    2
    /* EditorContributionInstantiation.BeforeFirstInteraction */
  );
  registerEditorAction(ShowContextMenu);
  class CursorState {
    constructor(selections) {
      this.selections = selections;
    }
    equals(other) {
      const thisLen = this.selections.length;
      const otherLen = other.selections.length;
      if (thisLen !== otherLen) {
        return false;
      }
      for (let i2 = 0; i2 < thisLen; i2++) {
        if (!this.selections[i2].equalsSelection(other.selections[i2])) {
          return false;
        }
      }
      return true;
    }
  }
  class StackElement {
    constructor(cursorState, scrollTop, scrollLeft) {
      this.cursorState = cursorState;
      this.scrollTop = scrollTop;
      this.scrollLeft = scrollLeft;
    }
  }
  const _CursorUndoRedoController = class _CursorUndoRedoController extends Disposable {
    static get(editor2) {
      return editor2.getContribution(_CursorUndoRedoController.ID);
    }
    constructor(editor2) {
      super();
      this._editor = editor2;
      this._isCursorUndoRedo = false;
      this._undoStack = [];
      this._redoStack = [];
      this._register(editor2.onDidChangeModel((e) => {
        this._undoStack = [];
        this._redoStack = [];
      }));
      this._register(editor2.onDidChangeModelContent((e) => {
        this._undoStack = [];
        this._redoStack = [];
      }));
      this._register(editor2.onDidChangeCursorSelection((e) => {
        if (this._isCursorUndoRedo) {
          return;
        }
        if (!e.oldSelections) {
          return;
        }
        if (e.oldModelVersionId !== e.modelVersionId) {
          return;
        }
        const prevState = new CursorState(e.oldSelections);
        const isEqualToLastUndoStack = this._undoStack.length > 0 && this._undoStack[this._undoStack.length - 1].cursorState.equals(prevState);
        if (!isEqualToLastUndoStack) {
          this._undoStack.push(new StackElement(prevState, editor2.getScrollTop(), editor2.getScrollLeft()));
          this._redoStack = [];
          if (this._undoStack.length > 50) {
            this._undoStack.shift();
          }
        }
      }));
    }
    cursorUndo() {
      if (!this._editor.hasModel() || this._undoStack.length === 0) {
        return;
      }
      this._redoStack.push(new StackElement(new CursorState(this._editor.getSelections()), this._editor.getScrollTop(), this._editor.getScrollLeft()));
      this._applyState(this._undoStack.pop());
    }
    cursorRedo() {
      if (!this._editor.hasModel() || this._redoStack.length === 0) {
        return;
      }
      this._undoStack.push(new StackElement(new CursorState(this._editor.getSelections()), this._editor.getScrollTop(), this._editor.getScrollLeft()));
      this._applyState(this._redoStack.pop());
    }
    _applyState(stackElement) {
      this._isCursorUndoRedo = true;
      this._editor.setSelections(stackElement.cursorState.selections);
      this._editor.setScrollPosition({
        scrollTop: stackElement.scrollTop,
        scrollLeft: stackElement.scrollLeft
      });
      this._isCursorUndoRedo = false;
    }
  };
  _CursorUndoRedoController.ID = "editor.contrib.cursorUndoRedoController";
  let CursorUndoRedoController = _CursorUndoRedoController;
  class CursorUndo extends EditorAction {
    constructor() {
      super({
        id: "cursorUndo",
        label: localize2(911, "Cursor Undo"),
        precondition: void 0,
        kbOpts: {
          kbExpr: EditorContextKeys.textInputFocus,
          primary: 2048 | 51,
          weight: 100
          /* KeybindingWeight.EditorContrib */
        }
      });
    }
    run(accessor, editor2, args) {
      CursorUndoRedoController.get(editor2)?.cursorUndo();
    }
  }
  class CursorRedo extends EditorAction {
    constructor() {
      super({
        id: "cursorRedo",
        label: localize2(912, "Cursor Redo"),
        precondition: void 0
      });
    }
    run(accessor, editor2, args) {
      CursorUndoRedoController.get(editor2)?.cursorRedo();
    }
  }
  registerEditorContribution(
    CursorUndoRedoController.ID,
    CursorUndoRedoController,
    0
    /* EditorContributionInstantiation.Eager */
  );
  registerEditorAction(CursorUndo);
  registerEditorAction(CursorRedo);
  class DragAndDropCommand {
    constructor(selection, targetPosition, copy) {
      this.selection = selection;
      this.targetPosition = targetPosition;
      this.copy = copy;
      this.targetSelection = null;
    }
    getEditOperations(model, builder) {
      const text2 = model.getValueInRange(this.selection);
      if (!this.copy) {
        builder.addEditOperation(this.selection, null);
      }
      builder.addEditOperation(new Range$2(this.targetPosition.lineNumber, this.targetPosition.column, this.targetPosition.lineNumber, this.targetPosition.column), text2);
      if (this.selection.containsPosition(this.targetPosition) && !(this.copy && (this.selection.getEndPosition().equals(this.targetPosition) || this.selection.getStartPosition().equals(this.targetPosition)))) {
        this.targetSelection = this.selection;
        return;
      }
      if (this.copy) {
        this.targetSelection = new Selection$1(this.targetPosition.lineNumber, this.targetPosition.column, this.selection.endLineNumber - this.selection.startLineNumber + this.targetPosition.lineNumber, this.selection.startLineNumber === this.selection.endLineNumber ? this.targetPosition.column + this.selection.endColumn - this.selection.startColumn : this.selection.endColumn);
        return;
      }
      if (this.targetPosition.lineNumber > this.selection.endLineNumber) {
        this.targetSelection = new Selection$1(this.targetPosition.lineNumber - this.selection.endLineNumber + this.selection.startLineNumber, this.targetPosition.column, this.targetPosition.lineNumber, this.selection.startLineNumber === this.selection.endLineNumber ? this.targetPosition.column + this.selection.endColumn - this.selection.startColumn : this.selection.endColumn);
        return;
      }
      if (this.targetPosition.lineNumber < this.selection.endLineNumber) {
        this.targetSelection = new Selection$1(this.targetPosition.lineNumber, this.targetPosition.column, this.targetPosition.lineNumber + this.selection.endLineNumber - this.selection.startLineNumber, this.selection.startLineNumber === this.selection.endLineNumber ? this.targetPosition.column + this.selection.endColumn - this.selection.startColumn : this.selection.endColumn);
        return;
      }
      if (this.selection.endColumn <= this.targetPosition.column) {
        this.targetSelection = new Selection$1(this.targetPosition.lineNumber - this.selection.endLineNumber + this.selection.startLineNumber, this.selection.startLineNumber === this.selection.endLineNumber ? this.targetPosition.column - this.selection.endColumn + this.selection.startColumn : this.targetPosition.column - this.selection.endColumn + this.selection.startColumn, this.targetPosition.lineNumber, this.selection.startLineNumber === this.selection.endLineNumber ? this.targetPosition.column : this.selection.endColumn);
      } else {
        this.targetSelection = new Selection$1(this.targetPosition.lineNumber - this.selection.endLineNumber + this.selection.startLineNumber, this.targetPosition.column, this.targetPosition.lineNumber, this.targetPosition.column + this.selection.endColumn - this.selection.startColumn);
      }
    }
    computeCursorState(model, helper) {
      return this.targetSelection;
    }
  }
  function hasTriggerModifier(e) {
    if (isMacintosh) {
      return e.altKey;
    } else {
      return e.ctrlKey;
    }
  }
  const _DragAndDropController = class _DragAndDropController extends Disposable {
    constructor(editor2) {
      super();
      this._editor = editor2;
      this._dndDecorationIds = this._editor.createDecorationsCollection();
      this._register(this._editor.onMouseDown((e) => this._onEditorMouseDown(e)));
      this._register(this._editor.onMouseUp((e) => this._onEditorMouseUp(e)));
      this._register(this._editor.onMouseDrag((e) => this._onEditorMouseDrag(e)));
      this._register(this._editor.onMouseDrop((e) => this._onEditorMouseDrop(e)));
      this._register(this._editor.onMouseDropCanceled(() => this._onEditorMouseDropCanceled()));
      this._register(this._editor.onKeyDown((e) => this.onEditorKeyDown(e)));
      this._register(this._editor.onKeyUp((e) => this.onEditorKeyUp(e)));
      this._register(this._editor.onDidBlurEditorWidget(() => this.onEditorBlur()));
      this._register(this._editor.onDidBlurEditorText(() => this.onEditorBlur()));
      this._mouseDown = false;
      this._modifierPressed = false;
      this._dragSelection = null;
    }
    onEditorBlur() {
      this._removeDecoration();
      this._dragSelection = null;
      this._mouseDown = false;
      this._modifierPressed = false;
    }
    onEditorKeyDown(e) {
      if (!this._editor.getOption(
        42
        /* EditorOption.dragAndDrop */
      ) || this._editor.getOption(
        28
        /* EditorOption.columnSelection */
      )) {
        return;
      }
      if (hasTriggerModifier(e)) {
        this._modifierPressed = true;
      }
      if (this._mouseDown && hasTriggerModifier(e)) {
        this._editor.updateOptions({
          mouseStyle: "copy"
        });
      }
    }
    onEditorKeyUp(e) {
      if (!this._editor.getOption(
        42
        /* EditorOption.dragAndDrop */
      ) || this._editor.getOption(
        28
        /* EditorOption.columnSelection */
      )) {
        return;
      }
      if (hasTriggerModifier(e)) {
        this._modifierPressed = false;
      }
      if (this._mouseDown && e.keyCode === _DragAndDropController.TRIGGER_KEY_VALUE) {
        this._editor.updateOptions({
          mouseStyle: "default"
        });
      }
    }
    _onEditorMouseDown(mouseEvent) {
      this._mouseDown = true;
    }
    _onEditorMouseUp(mouseEvent) {
      this._mouseDown = false;
      this._editor.updateOptions({
        mouseStyle: "text"
      });
    }
    _onEditorMouseDrag(mouseEvent) {
      const target = mouseEvent.target;
      if (this._dragSelection === null) {
        const selections = this._editor.getSelections() || [];
        const possibleSelections = selections.filter((selection) => target.position && selection.containsPosition(target.position));
        if (possibleSelections.length === 1) {
          this._dragSelection = possibleSelections[0];
        } else {
          return;
        }
      }
      if (hasTriggerModifier(mouseEvent.event)) {
        this._editor.updateOptions({
          mouseStyle: "copy"
        });
      } else {
        this._editor.updateOptions({
          mouseStyle: "default"
        });
      }
      if (target.position) {
        if (this._dragSelection.containsPosition(target.position)) {
          this._removeDecoration();
        } else {
          this.showAt(target.position);
        }
      }
    }
    _onEditorMouseDropCanceled() {
      this._editor.updateOptions({
        mouseStyle: "text"
      });
      this._removeDecoration();
      this._dragSelection = null;
      this._mouseDown = false;
    }
    _onEditorMouseDrop(mouseEvent) {
      if (mouseEvent.target && (this._hitContent(mouseEvent.target) || this._hitMargin(mouseEvent.target)) && mouseEvent.target.position) {
        const newCursorPosition = new Position$1(mouseEvent.target.position.lineNumber, mouseEvent.target.position.column);
        if (this._dragSelection === null) {
          let newSelections = null;
          if (mouseEvent.event.shiftKey) {
            const primarySelection = this._editor.getSelection();
            if (primarySelection) {
              const { selectionStartLineNumber, selectionStartColumn } = primarySelection;
              newSelections = [new Selection$1(selectionStartLineNumber, selectionStartColumn, newCursorPosition.lineNumber, newCursorPosition.column)];
            }
          } else {
            newSelections = (this._editor.getSelections() || []).map((selection) => {
              if (selection.containsPosition(newCursorPosition)) {
                return new Selection$1(newCursorPosition.lineNumber, newCursorPosition.column, newCursorPosition.lineNumber, newCursorPosition.column);
              } else {
                return selection;
              }
            });
          }
          this._editor.setSelections(
            newSelections || [],
            "mouse",
            3
            /* CursorChangeReason.Explicit */
          );
        } else if (!this._dragSelection.containsPosition(newCursorPosition) || (hasTriggerModifier(mouseEvent.event) || this._modifierPressed) && (this._dragSelection.getEndPosition().equals(newCursorPosition) || this._dragSelection.getStartPosition().equals(newCursorPosition))) {
          this._editor.pushUndoStop();
          this._editor.executeCommand(_DragAndDropController.ID, new DragAndDropCommand(this._dragSelection, newCursorPosition, hasTriggerModifier(mouseEvent.event) || this._modifierPressed));
          this._editor.pushUndoStop();
        }
      }
      this._editor.updateOptions({
        mouseStyle: "text"
      });
      this._removeDecoration();
      this._dragSelection = null;
      this._mouseDown = false;
    }
    showAt(position) {
      this._dndDecorationIds.set([{
        range: new Range$2(position.lineNumber, position.column, position.lineNumber, position.column),
        options: _DragAndDropController._DECORATION_OPTIONS
      }]);
      this._editor.revealPosition(
        position,
        1
        /* ScrollType.Immediate */
      );
    }
    _removeDecoration() {
      this._dndDecorationIds.clear();
    }
    _hitContent(target) {
      return target.type === 6 || target.type === 7;
    }
    _hitMargin(target) {
      return target.type === 2 || target.type === 3 || target.type === 4;
    }
    dispose() {
      this._removeDecoration();
      this._dragSelection = null;
      this._mouseDown = false;
      this._modifierPressed = false;
      super.dispose();
    }
  };
  _DragAndDropController.ID = "editor.contrib.dragAndDrop";
  _DragAndDropController.TRIGGER_KEY_VALUE = isMacintosh ? 6 : 5;
  _DragAndDropController._DECORATION_OPTIONS = ModelDecorationOptions.register({
    description: "dnd-target",
    className: "dnd-target"
  });
  let DragAndDropController = _DragAndDropController;
  registerEditorContribution(
    DragAndDropController.ID,
    DragAndDropController,
    2
    /* EditorContributionInstantiation.BeforeFirstInteraction */
  );
  const pasteAsCommandId = "editor.action.pasteAs";
  registerEditorContribution(
    CopyPasteController.ID,
    CopyPasteController,
    0
    /* EditorContributionInstantiation.Eager */
  );
  registerEditorFeature(DefaultPasteProvidersFeature);
  registerEditorCommand(new class extends EditorCommand {
    constructor() {
      super({
        id: changePasteTypeCommandId,
        precondition: pasteWidgetVisibleCtx,
        kbOpts: {
          weight: 100,
          primary: 2048 | 89
        }
      });
    }
    runEditorCommand(_accessor, editor2) {
      return CopyPasteController.get(editor2)?.changePasteType();
    }
  }());
  registerEditorCommand(new class extends EditorCommand {
    constructor() {
      super({
        id: "editor.hidePasteWidget",
        precondition: pasteWidgetVisibleCtx,
        kbOpts: {
          weight: 100,
          primary: 9
        }
      });
    }
    runEditorCommand(_accessor, editor2) {
      CopyPasteController.get(editor2)?.clearWidgets();
    }
  }());
  registerEditorAction((_T = class extends EditorAction {
    constructor() {
      super({
        id: pasteAsCommandId,
        label: localize2(915, "Paste As..."),
        precondition: EditorContextKeys.writable,
        metadata: {
          description: "Paste as",
          args: [{
            name: "args",
            schema: _T.argsSchema
          }]
        },
        canTriggerInlineEdits: true
      });
    }
    run(_accessor, editor2, args) {
      let preference;
      if (args) {
        if ("kind" in args) {
          preference = { only: new HierarchicalKind(args.kind) };
        } else if ("preferences" in args) {
          preference = { preferences: args.preferences.map((kind) => new HierarchicalKind(kind)) };
        }
      }
      return CopyPasteController.get(editor2)?.pasteAs(preference);
    }
  }, _T.argsSchema = {
    oneOf: [
      {
        type: "object",
        required: ["kind"],
        properties: {
          kind: {
            type: "string",
            description: localize(913, "The kind of the paste edit to try pasting with.\nIf there are multiple edits for this kind, the editor will show a picker. If there are no edits of this kind, the editor will show an error message.")
          }
        }
      },
      {
        type: "object",
        required: ["preferences"],
        properties: {
          preferences: {
            type: "array",
            description: localize(914, "List of preferred paste edit kind to try applying.\nThe first edit matching the preferences will be applied."),
            items: { type: "string" }
          }
        }
      }
    ]
  }, _T));
  registerEditorAction(class extends EditorAction {
    constructor() {
      super({
        id: "editor.action.pasteAsText",
        label: localize2(916, "Paste as Text"),
        precondition: EditorContextKeys.writable,
        canTriggerInlineEdits: true
      });
    }
    run(_accessor, editor2) {
      return CopyPasteController.get(editor2)?.pasteAs({ providerId: DefaultTextPasteOrDropEditProvider.id });
    }
  });
  class TreeViewsDnDService {
    constructor() {
      this._dragOperations = /* @__PURE__ */ new Map();
    }
    removeDragOperationTransfer(uuid) {
      if (uuid && this._dragOperations.has(uuid)) {
        const operation = this._dragOperations.get(uuid);
        this._dragOperations.delete(uuid);
        return operation;
      }
      return void 0;
    }
  }
  class DraggedTreeItemsIdentifier {
    constructor(identifier) {
      this.identifier = identifier;
    }
  }
  const ITreeViewsDnDService = createDecorator("treeViewsDndService");
  registerSingleton(
    ITreeViewsDnDService,
    TreeViewsDnDService,
    1
    /* InstantiationType.Delayed */
  );
  var __decorate$1L = 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$1K = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  var DropIntoEditorController_1;
  const dropAsPreferenceConfig = "editor.dropIntoEditor.preferences";
  const changeDropTypeCommandId = "editor.changeDropType";
  const dropWidgetVisibleCtx = new RawContextKey("dropWidgetVisible", false, localize(934, "Whether the drop widget is showing"));
  let DropIntoEditorController = (_U = class extends Disposable {
    static get(editor2) {
      return editor2.getContribution(DropIntoEditorController_1.ID);
    }
    constructor(editor2, instantiationService, _configService, _languageFeaturesService, _treeViewsDragAndDropService) {
      super();
      this._configService = _configService;
      this._languageFeaturesService = _languageFeaturesService;
      this._treeViewsDragAndDropService = _treeViewsDragAndDropService;
      this.treeItemsTransfer = LocalSelectionTransfer.getInstance();
      this._dropProgressManager = this._register(instantiationService.createInstance(InlineProgressManager, "dropIntoEditor", editor2));
      this._postDropWidgetManager = this._register(instantiationService.createInstance(PostEditWidgetManager, "dropIntoEditor", editor2, dropWidgetVisibleCtx, { id: changeDropTypeCommandId, label: localize(935, "Show drop options...") }, () => DropIntoEditorController_1._configureDefaultAction ? [DropIntoEditorController_1._configureDefaultAction] : []));
      this._register(editor2.onDropIntoEditor((e) => this.onDropIntoEditor(editor2, e.position, e.event)));
    }
    clearWidgets() {
      this._postDropWidgetManager.clear();
    }
    changeDropType() {
      this._postDropWidgetManager.tryShowSelector();
    }
    async onDropIntoEditor(editor2, position, dragEvent) {
      if (!dragEvent.dataTransfer || !editor2.hasModel()) {
        return;
      }
      DropIntoEditorController_1._currentDropOperation?.cancel();
      editor2.focus();
      editor2.setPosition(position);
      const p = createCancelablePromise(async (token) => {
        const disposables = new DisposableStore();
        const tokenSource = disposables.add(new EditorStateCancellationTokenSource(editor2, 1, void 0, token));
        try {
          const ourDataTransfer = await this.extractDataTransferData(dragEvent);
          if (ourDataTransfer.size === 0 || tokenSource.token.isCancellationRequested) {
            return;
          }
          const model = editor2.getModel();
          if (!model) {
            return;
          }
          const providers = this._languageFeaturesService.documentDropEditProvider.ordered(model).filter((provider) => {
            if (!provider.dropMimeTypes) {
              return true;
            }
            return provider.dropMimeTypes.some((mime) => ourDataTransfer.matches(mime));
          });
          const editSession = disposables.add(await this.getDropEdits(providers, model, position, ourDataTransfer, tokenSource.token));
          if (tokenSource.token.isCancellationRequested) {
            return;
          }
          if (editSession.edits.length) {
            const activeEditIndex = this.getInitialActiveEditIndex(model, editSession.edits);
            const canShowWidget = editor2.getOption(
              43
              /* EditorOption.dropIntoEditor */
            ).showDropSelector === "afterDrop";
            await this._postDropWidgetManager.applyEditAndShowIfNeeded([Range$2.fromPositions(position)], { activeEditIndex, allEdits: editSession.edits }, canShowWidget, async (edit2) => edit2, token);
          }
        } finally {
          disposables.dispose();
          if (DropIntoEditorController_1._currentDropOperation === p) {
            DropIntoEditorController_1._currentDropOperation = void 0;
          }
        }
      });
      this._dropProgressManager.showWhile(position, localize(936, "Running drop handlers. Click to cancel"), p, { cancel: () => p.cancel() });
      DropIntoEditorController_1._currentDropOperation = p;
    }
    async getDropEdits(providers, model, position, dataTransfer, token) {
      const disposables = new DisposableStore();
      const results = await raceCancellation(Promise.all(providers.map(async (provider) => {
        try {
          const edits2 = await provider.provideDocumentDropEdits(model, position, dataTransfer, token);
          if (edits2) {
            disposables.add(edits2);
          }
          return edits2?.edits.map((edit2) => ({ ...edit2, providerId: provider.id }));
        } catch (err) {
          if (!isCancellationError(err)) {
            console.error(err);
          }
          console.error(err);
        }
        return void 0;
      })), token);
      const edits = coalesce(results ?? []).flat();
      return {
        edits: sortEditsByYieldTo(edits),
        dispose: () => disposables.dispose()
      };
    }
    getInitialActiveEditIndex(model, edits) {
      const preferredProviders = this._configService.getValue(dropAsPreferenceConfig, { resource: model.uri });
      for (const config of Array.isArray(preferredProviders) ? preferredProviders : []) {
        const desiredKind = new HierarchicalKind(config);
        const editIndex = edits.findIndex((edit2) => edit2.kind && desiredKind.contains(edit2.kind));
        if (editIndex >= 0) {
          return editIndex;
        }
      }
      return 0;
    }
    async extractDataTransferData(dragEvent) {
      if (!dragEvent.dataTransfer) {
        return new VSDataTransfer();
      }
      const dataTransfer = toExternalVSDataTransfer(dragEvent.dataTransfer);
      if (this.treeItemsTransfer.hasData(DraggedTreeItemsIdentifier.prototype)) {
        const data = this.treeItemsTransfer.getData(DraggedTreeItemsIdentifier.prototype);
        if (Array.isArray(data)) {
          for (const id of data) {
            const treeDataTransfer = await this._treeViewsDragAndDropService.removeDragOperationTransfer(id.identifier);
            if (treeDataTransfer) {
              for (const [type, value] of treeDataTransfer) {
                dataTransfer.replace(type, value);
              }
            }
          }
        }
      }
      return dataTransfer;
    }
  }, DropIntoEditorController_1 = _U, _U.ID = "editor.contrib.dropIntoEditorController", _U);
  DropIntoEditorController = DropIntoEditorController_1 = __decorate$1L([
    __param$1K(1, IInstantiationService),
    __param$1K(2, IConfigurationService),
    __param$1K(3, ILanguageFeaturesService),
    __param$1K(4, ITreeViewsDnDService)
  ], DropIntoEditorController);
  registerEditorContribution(
    DropIntoEditorController.ID,
    DropIntoEditorController,
    2
    /* EditorContributionInstantiation.BeforeFirstInteraction */
  );
  registerEditorFeature(DefaultDropProvidersFeature);
  registerEditorCommand(new class extends EditorCommand {
    constructor() {
      super({
        id: changeDropTypeCommandId,
        precondition: dropWidgetVisibleCtx,
        kbOpts: {
          weight: 100,
          primary: 2048 | 89
        }
      });
    }
    runEditorCommand(_accessor, editor2, _args) {
      DropIntoEditorController.get(editor2)?.changeDropType();
    }
  }());
  registerEditorCommand(new class extends EditorCommand {
    constructor() {
      super({
        id: "editor.hideDropWidget",
        precondition: dropWidgetVisibleCtx,
        kbOpts: {
          weight: 100,
          primary: 9
        }
      });
    }
    runEditorCommand(_accessor, editor2, _args) {
      DropIntoEditorController.get(editor2)?.clearWidgets();
    }
  }());
  const _FindOptionsWidget = class _FindOptionsWidget extends Widget$1 {
    constructor(editor2, state, keybindingService) {
      super();
      this._hideSoon = this._register(new RunOnceScheduler(() => this._hide(), 2e3));
      this._isVisible = false;
      this._editor = editor2;
      this._state = state;
      this._keybindingService = keybindingService;
      this._domNode = document.createElement("div");
      this._domNode.className = "findOptionsWidget";
      this._domNode.style.display = "none";
      this._domNode.style.top = "10px";
      this._domNode.style.zIndex = "12";
      this._domNode.setAttribute("role", "presentation");
      this._domNode.setAttribute("aria-hidden", "true");
      const toggleStyles = {
        inputActiveOptionBorder: asCssVariable(inputActiveOptionBorder),
        inputActiveOptionForeground: asCssVariable(inputActiveOptionForeground),
        inputActiveOptionBackground: asCssVariable(inputActiveOptionBackground)
      };
      const hoverLifecycleOptions = { groupId: "find-options-widget" };
      this.caseSensitive = this._register(new CaseSensitiveToggle({
        appendTitle: this._keybindingLabelFor(FIND_IDS.ToggleCaseSensitiveCommand),
        isChecked: this._state.matchCase,
        hoverLifecycleOptions,
        ...toggleStyles
      }));
      this._domNode.appendChild(this.caseSensitive.domNode);
      this._register(this.caseSensitive.onChange(() => {
        this._state.change({
          matchCase: this.caseSensitive.checked
        }, false);
      }));
      this.wholeWords = this._register(new WholeWordsToggle({
        appendTitle: this._keybindingLabelFor(FIND_IDS.ToggleWholeWordCommand),
        isChecked: this._state.wholeWord,
        hoverLifecycleOptions,
        ...toggleStyles
      }));
      this._domNode.appendChild(this.wholeWords.domNode);
      this._register(this.wholeWords.onChange(() => {
        this._state.change({
          wholeWord: this.wholeWords.checked
        }, false);
      }));
      this.regex = this._register(new RegexToggle({
        appendTitle: this._keybindingLabelFor(FIND_IDS.ToggleRegexCommand),
        isChecked: this._state.isRegex,
        hoverLifecycleOptions,
        ...toggleStyles
      }));
      this._domNode.appendChild(this.regex.domNode);
      this._register(this.regex.onChange(() => {
        this._state.change({
          isRegex: this.regex.checked
        }, false);
      }));
      this._editor.addOverlayWidget(this);
      this._register(this._state.onFindReplaceStateChange((e) => {
        let somethingChanged = false;
        if (e.isRegex) {
          this.regex.checked = this._state.isRegex;
          somethingChanged = true;
        }
        if (e.wholeWord) {
          this.wholeWords.checked = this._state.wholeWord;
          somethingChanged = true;
        }
        if (e.matchCase) {
          this.caseSensitive.checked = this._state.matchCase;
          somethingChanged = true;
        }
        if (!this._state.isRevealed && somethingChanged) {
          this._revealTemporarily();
        }
      }));
      this._register(addDisposableListener(this._domNode, EventType$1.MOUSE_LEAVE, (e) => this._onMouseLeave()));
      this._register(addDisposableListener(this._domNode, "mouseover", (e) => this._onMouseOver()));
    }
    _keybindingLabelFor(actionId) {
      const kb = this._keybindingService.lookupKeybinding(actionId);
      if (!kb) {
        return "";
      }
      return ` (${kb.getLabel()})`;
    }
    dispose() {
      this._editor.removeOverlayWidget(this);
      super.dispose();
    }
    // ----- IOverlayWidget API
    getId() {
      return _FindOptionsWidget.ID;
    }
    getDomNode() {
      return this._domNode;
    }
    getPosition() {
      return {
        preference: 0
        /* OverlayWidgetPositionPreference.TOP_RIGHT_CORNER */
      };
    }
    highlightFindOptions() {
      this._revealTemporarily();
    }
    _revealTemporarily() {
      this._show();
      this._hideSoon.schedule();
    }
    _onMouseLeave() {
      this._hideSoon.schedule();
    }
    _onMouseOver() {
      this._hideSoon.cancel();
    }
    _show() {
      if (this._isVisible) {
        return;
      }
      this._isVisible = true;
      this._domNode.style.display = "block";
    }
    _hide() {
      if (!this._isVisible) {
        return;
      }
      this._isVisible = false;
      this._domNode.style.display = "none";
    }
  };
  _FindOptionsWidget.ID = "editor.contrib.findOptionsWidget";
  let FindOptionsWidget = _FindOptionsWidget;
  function effectiveOptionValue(override, value) {
    if (override === 1) {
      return true;
    }
    if (override === 2) {
      return false;
    }
    return value;
  }
  class FindReplaceState extends Disposable {
    get searchString() {
      return this._searchString;
    }
    get replaceString() {
      return this._replaceString;
    }
    get isRevealed() {
      return this._isRevealed;
    }
    get isReplaceRevealed() {
      return this._isReplaceRevealed;
    }
    get isRegex() {
      return effectiveOptionValue(this._isRegexOverride, this._isRegex);
    }
    get wholeWord() {
      return effectiveOptionValue(this._wholeWordOverride, this._wholeWord);
    }
    get matchCase() {
      return effectiveOptionValue(this._matchCaseOverride, this._matchCase);
    }
    get preserveCase() {
      return effectiveOptionValue(this._preserveCaseOverride, this._preserveCase);
    }
    get actualIsRegex() {
      return this._isRegex;
    }
    get actualWholeWord() {
      return this._wholeWord;
    }
    get actualMatchCase() {
      return this._matchCase;
    }
    get actualPreserveCase() {
      return this._preserveCase;
    }
    get searchScope() {
      return this._searchScope;
    }
    get matchesPosition() {
      return this._matchesPosition;
    }
    get matchesCount() {
      return this._matchesCount;
    }
    get currentMatch() {
      return this._currentMatch;
    }
    constructor() {
      super();
      this._onFindReplaceStateChange = this._register(new Emitter$1());
      this.onFindReplaceStateChange = this._onFindReplaceStateChange.event;
      this._searchString = "";
      this._replaceString = "";
      this._isRevealed = false;
      this._isReplaceRevealed = false;
      this._isRegex = false;
      this._isRegexOverride = 0;
      this._wholeWord = false;
      this._wholeWordOverride = 0;
      this._matchCase = false;
      this._matchCaseOverride = 0;
      this._preserveCase = false;
      this._preserveCaseOverride = 0;
      this._searchScope = null;
      this._matchesPosition = 0;
      this._matchesCount = 0;
      this._currentMatch = null;
      this._loop = true;
      this._isSearching = false;
      this._filters = null;
    }
    changeMatchInfo(matchesPosition, matchesCount, currentMatch) {
      const changeEvent = {
        moveCursor: false,
        updateHistory: false,
        searchString: false,
        replaceString: false,
        isRevealed: false,
        isReplaceRevealed: false,
        isRegex: false,
        wholeWord: false,
        matchCase: false,
        preserveCase: false,
        searchScope: false,
        matchesPosition: false,
        matchesCount: false,
        currentMatch: false,
        loop: false,
        isSearching: false,
        filters: false
      };
      let somethingChanged = false;
      if (matchesCount === 0) {
        matchesPosition = 0;
      }
      if (matchesPosition > matchesCount) {
        matchesPosition = matchesCount;
      }
      if (this._matchesPosition !== matchesPosition) {
        this._matchesPosition = matchesPosition;
        changeEvent.matchesPosition = true;
        somethingChanged = true;
      }
      if (this._matchesCount !== matchesCount) {
        this._matchesCount = matchesCount;
        changeEvent.matchesCount = true;
        somethingChanged = true;
      }
      if (typeof currentMatch !== "undefined") {
        if (!Range$2.equalsRange(this._currentMatch, currentMatch)) {
          this._currentMatch = currentMatch;
          changeEvent.currentMatch = true;
          somethingChanged = true;
        }
      }
      if (somethingChanged) {
        this._onFindReplaceStateChange.fire(changeEvent);
      }
    }
    change(newState, moveCursor, updateHistory = true) {
      const changeEvent = {
        moveCursor,
        updateHistory,
        searchString: false,
        replaceString: false,
        isRevealed: false,
        isReplaceRevealed: false,
        isRegex: false,
        wholeWord: false,
        matchCase: false,
        preserveCase: false,
        searchScope: false,
        matchesPosition: false,
        matchesCount: false,
        currentMatch: false,
        loop: false,
        isSearching: false,
        filters: false
      };
      let somethingChanged = false;
      const oldEffectiveIsRegex = this.isRegex;
      const oldEffectiveWholeWords = this.wholeWord;
      const oldEffectiveMatchCase = this.matchCase;
      const oldEffectivePreserveCase = this.preserveCase;
      if (typeof newState.searchString !== "undefined") {
        if (this._searchString !== newState.searchString) {
          this._searchString = newState.searchString;
          changeEvent.searchString = true;
          somethingChanged = true;
        }
      }
      if (typeof newState.replaceString !== "undefined") {
        if (this._replaceString !== newState.replaceString) {
          this._replaceString = newState.replaceString;
          changeEvent.replaceString = true;
          somethingChanged = true;
        }
      }
      if (typeof newState.isRevealed !== "undefined") {
        if (this._isRevealed !== newState.isRevealed) {
          this._isRevealed = newState.isRevealed;
          changeEvent.isRevealed = true;
          somethingChanged = true;
        }
      }
      if (typeof newState.isReplaceRevealed !== "undefined") {
        if (this._isReplaceRevealed !== newState.isReplaceRevealed) {
          this._isReplaceRevealed = newState.isReplaceRevealed;
          changeEvent.isReplaceRevealed = true;
          somethingChanged = true;
        }
      }
      if (typeof newState.isRegex !== "undefined") {
        this._isRegex = newState.isRegex;
      }
      if (typeof newState.wholeWord !== "undefined") {
        this._wholeWord = newState.wholeWord;
      }
      if (typeof newState.matchCase !== "undefined") {
        this._matchCase = newState.matchCase;
      }
      if (typeof newState.preserveCase !== "undefined") {
        this._preserveCase = newState.preserveCase;
      }
      if (typeof newState.searchScope !== "undefined") {
        if (!newState.searchScope?.every((newSearchScope) => {
          return this._searchScope?.some((existingSearchScope) => {
            return !Range$2.equalsRange(existingSearchScope, newSearchScope);
          });
        })) {
          this._searchScope = newState.searchScope;
          changeEvent.searchScope = true;
          somethingChanged = true;
        }
      }
      if (typeof newState.loop !== "undefined") {
        if (this._loop !== newState.loop) {
          this._loop = newState.loop;
          changeEvent.loop = true;
          somethingChanged = true;
        }
      }
      if (typeof newState.isSearching !== "undefined") {
        if (this._isSearching !== newState.isSearching) {
          this._isSearching = newState.isSearching;
          changeEvent.isSearching = true;
          somethingChanged = true;
        }
      }
      if (typeof newState.filters !== "undefined") {
        if (this._filters) {
          this._filters.update(newState.filters);
        } else {
          this._filters = newState.filters;
        }
        changeEvent.filters = true;
        somethingChanged = true;
      }
      this._isRegexOverride = typeof newState.isRegexOverride !== "undefined" ? newState.isRegexOverride : 0;
      this._wholeWordOverride = typeof newState.wholeWordOverride !== "undefined" ? newState.wholeWordOverride : 0;
      this._matchCaseOverride = typeof newState.matchCaseOverride !== "undefined" ? newState.matchCaseOverride : 0;
      this._preserveCaseOverride = typeof newState.preserveCaseOverride !== "undefined" ? newState.preserveCaseOverride : 0;
      if (oldEffectiveIsRegex !== this.isRegex) {
        somethingChanged = true;
        changeEvent.isRegex = true;
      }
      if (oldEffectiveWholeWords !== this.wholeWord) {
        somethingChanged = true;
        changeEvent.wholeWord = true;
      }
      if (oldEffectiveMatchCase !== this.matchCase) {
        somethingChanged = true;
        changeEvent.matchCase = true;
      }
      if (oldEffectivePreserveCase !== this.preserveCase) {
        somethingChanged = true;
        changeEvent.preserveCase = true;
      }
      if (somethingChanged) {
        this._onFindReplaceStateChange.fire(changeEvent);
      }
    }
    canNavigateBack() {
      return this.canNavigateInLoop() || this.matchesPosition !== 1;
    }
    canNavigateForward() {
      return this.canNavigateInLoop() || this.matchesPosition < this.matchesCount;
    }
    canNavigateInLoop() {
      return this._loop || this.matchesCount >= MATCHES_LIMIT;
    }
  }
  var __decorate$1K = 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$1J = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  var FindWidgetSearchHistory_1;
  let FindWidgetSearchHistory = (_V = class {
    static getOrCreate(storageService) {
      if (!FindWidgetSearchHistory_1._instance) {
        FindWidgetSearchHistory_1._instance = new FindWidgetSearchHistory_1(storageService);
      }
      return FindWidgetSearchHistory_1._instance;
    }
    constructor(storageService) {
      this.storageService = storageService;
      this.inMemoryValues = /* @__PURE__ */ new Set();
      this._onDidChangeEmitter = new Emitter$1();
      this.onDidChange = this._onDidChangeEmitter.event;
      this.load();
    }
    delete(t) {
      const result = this.inMemoryValues.delete(t);
      this.save();
      return result;
    }
    add(t) {
      this.inMemoryValues.add(t);
      this.save();
      return this;
    }
    has(t) {
      return this.inMemoryValues.has(t);
    }
    forEach(callbackfn, thisArg) {
      this.load();
      return this.inMemoryValues.forEach(callbackfn);
    }
    replace(t) {
      this.inMemoryValues = new Set(t);
      this.save();
    }
    load() {
      let result;
      const raw = this.storageService.get(
        FindWidgetSearchHistory_1.FIND_HISTORY_KEY,
        1
        /* StorageScope.WORKSPACE */
      );
      if (raw) {
        try {
          result = JSON.parse(raw);
        } catch (e) {
        }
      }
      this.inMemoryValues = new Set(result || []);
    }
    // Run saves async
    save() {
      const elements = [];
      this.inMemoryValues.forEach((e) => elements.push(e));
      return new Promise((resolve2) => {
        this.storageService.store(
          FindWidgetSearchHistory_1.FIND_HISTORY_KEY,
          JSON.stringify(elements),
          1,
          0
          /* StorageTarget.USER */
        );
        this._onDidChangeEmitter.fire(elements);
        resolve2();
      });
    }
  }, FindWidgetSearchHistory_1 = _V, _V.FIND_HISTORY_KEY = "workbench.find.history", _V._instance = null, _V);
  FindWidgetSearchHistory = FindWidgetSearchHistory_1 = __decorate$1K([
    __param$1J(0, IStorageService)
  ], FindWidgetSearchHistory);
  var __decorate$1J = 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$1I = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  var ReplaceWidgetHistory_1;
  let ReplaceWidgetHistory = (_W = class {
    static getOrCreate(storageService) {
      if (!ReplaceWidgetHistory_1._instance) {
        ReplaceWidgetHistory_1._instance = new ReplaceWidgetHistory_1(storageService);
      }
      return ReplaceWidgetHistory_1._instance;
    }
    constructor(storageService) {
      this.storageService = storageService;
      this.inMemoryValues = /* @__PURE__ */ new Set();
      this._onDidChangeEmitter = new Emitter$1();
      this.onDidChange = this._onDidChangeEmitter.event;
      this.load();
    }
    delete(t) {
      const result = this.inMemoryValues.delete(t);
      this.save();
      return result;
    }
    add(t) {
      this.inMemoryValues.add(t);
      this.save();
      return this;
    }
    has(t) {
      return this.inMemoryValues.has(t);
    }
    forEach(callbackfn, thisArg) {
      this.load();
      return this.inMemoryValues.forEach(callbackfn);
    }
    replace(t) {
      this.inMemoryValues = new Set(t);
      this.save();
    }
    load() {
      let result;
      const raw = this.storageService.get(
        ReplaceWidgetHistory_1.FIND_HISTORY_KEY,
        1
        /* StorageScope.WORKSPACE */
      );
      if (raw) {
        try {
          result = JSON.parse(raw);
        } catch (e) {
        }
      }
      this.inMemoryValues = new Set(result || []);
    }
    // Run saves async
    save() {
      const elements = [];
      this.inMemoryValues.forEach((e) => elements.push(e));
      return new Promise((resolve2) => {
        this.storageService.store(
          ReplaceWidgetHistory_1.FIND_HISTORY_KEY,
          JSON.stringify(elements),
          1,
          0
          /* StorageTarget.USER */
        );
        this._onDidChangeEmitter.fire(elements);
        resolve2();
      });
    }
  }, ReplaceWidgetHistory_1 = _W, _W.FIND_HISTORY_KEY = "workbench.replace.history", _W._instance = null, _W);
  ReplaceWidgetHistory = ReplaceWidgetHistory_1 = __decorate$1J([
    __param$1I(0, IStorageService)
  ], ReplaceWidgetHistory);
  var __decorate$1I = 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$1H = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  var CommonFindController_1;
  const SEARCH_STRING_MAX_LENGTH = 524288;
  function getSelectionSearchString(editor2, seedSearchStringFromSelection = "single", seedSearchStringFromNonEmptySelection = false) {
    if (!editor2.hasModel()) {
      return null;
    }
    const selection = editor2.getSelection();
    if (seedSearchStringFromSelection === "single" && selection.startLineNumber === selection.endLineNumber || seedSearchStringFromSelection === "multiple") {
      if (selection.isEmpty()) {
        const wordAtPosition = editor2.getConfiguredWordAtPosition(selection.getStartPosition());
        if (wordAtPosition && false === seedSearchStringFromNonEmptySelection) {
          return wordAtPosition.word;
        }
      } else {
        if (editor2.getModel().getValueLengthInRange(selection) < SEARCH_STRING_MAX_LENGTH) {
          return editor2.getModel().getValueInRange(selection);
        }
      }
    }
    return null;
  }
  let CommonFindController = (_X = class extends Disposable {
    get editor() {
      return this._editor;
    }
    static get(editor2) {
      return editor2.getContribution(CommonFindController_1.ID);
    }
    constructor(editor2, contextKeyService, storageService, clipboardService, notificationService, hoverService) {
      super();
      this._editor = editor2;
      this._findWidgetVisible = CONTEXT_FIND_WIDGET_VISIBLE.bindTo(contextKeyService);
      this._contextKeyService = contextKeyService;
      this._storageService = storageService;
      this._clipboardService = clipboardService;
      this._notificationService = notificationService;
      this._hoverService = hoverService;
      this._updateHistoryDelayer = new Delayer(500);
      this._state = this._register(new FindReplaceState());
      this.loadQueryState();
      this._register(this._state.onFindReplaceStateChange((e) => this._onStateChanged(e)));
      this._model = null;
      this._register(this._editor.onDidChangeModel(() => {
        const shouldRestartFind = this._editor.getModel() && this._state.isRevealed;
        this.disposeModel();
        this._state.change({
          searchScope: null,
          matchCase: this._storageService.getBoolean("editor.matchCase", 1, false),
          wholeWord: this._storageService.getBoolean("editor.wholeWord", 1, false),
          isRegex: this._storageService.getBoolean("editor.isRegex", 1, false),
          preserveCase: this._storageService.getBoolean("editor.preserveCase", 1, false)
        }, false);
        if (shouldRestartFind) {
          this._start({
            forceRevealReplace: false,
            seedSearchStringFromSelection: "none",
            seedSearchStringFromNonEmptySelection: false,
            seedSearchStringFromGlobalClipboard: false,
            shouldFocus: 0,
            shouldAnimate: false,
            updateSearchScope: false,
            loop: this._editor.getOption(
              50
              /* EditorOption.find */
            ).loop
          });
        }
      }));
    }
    dispose() {
      this.disposeModel();
      super.dispose();
    }
    disposeModel() {
      if (this._model) {
        this._model.dispose();
        this._model = null;
      }
    }
    _onStateChanged(e) {
      this.saveQueryState(e);
      if (e.isRevealed) {
        if (this._state.isRevealed) {
          this._findWidgetVisible.set(true);
        } else {
          this._findWidgetVisible.reset();
          this.disposeModel();
        }
      }
      if (e.searchString) {
        this.setGlobalBufferTerm(this._state.searchString);
      }
    }
    saveQueryState(e) {
      if (e.isRegex) {
        this._storageService.store(
          "editor.isRegex",
          this._state.actualIsRegex,
          1,
          1
          /* StorageTarget.MACHINE */
        );
      }
      if (e.wholeWord) {
        this._storageService.store(
          "editor.wholeWord",
          this._state.actualWholeWord,
          1,
          1
          /* StorageTarget.MACHINE */
        );
      }
      if (e.matchCase) {
        this._storageService.store(
          "editor.matchCase",
          this._state.actualMatchCase,
          1,
          1
          /* StorageTarget.MACHINE */
        );
      }
      if (e.preserveCase) {
        this._storageService.store(
          "editor.preserveCase",
          this._state.actualPreserveCase,
          1,
          1
          /* StorageTarget.MACHINE */
        );
      }
    }
    loadQueryState() {
      this._state.change({
        matchCase: this._storageService.getBoolean("editor.matchCase", 1, this._state.matchCase),
        wholeWord: this._storageService.getBoolean("editor.wholeWord", 1, this._state.wholeWord),
        isRegex: this._storageService.getBoolean("editor.isRegex", 1, this._state.isRegex),
        preserveCase: this._storageService.getBoolean("editor.preserveCase", 1, this._state.preserveCase)
      }, false);
    }
    isFindInputFocused() {
      return !!CONTEXT_FIND_INPUT_FOCUSED.getValue(this._contextKeyService);
    }
    getState() {
      return this._state;
    }
    closeFindWidget() {
      this._state.change({
        isRevealed: false,
        searchScope: null
      }, false);
      this._editor.focus();
    }
    toggleCaseSensitive() {
      this._state.change({ matchCase: !this._state.matchCase }, false);
      if (!this._state.isRevealed) {
        this.highlightFindOptions();
      }
    }
    toggleWholeWords() {
      this._state.change({ wholeWord: !this._state.wholeWord }, false);
      if (!this._state.isRevealed) {
        this.highlightFindOptions();
      }
    }
    toggleRegex() {
      this._state.change({ isRegex: !this._state.isRegex }, false);
      if (!this._state.isRevealed) {
        this.highlightFindOptions();
      }
    }
    togglePreserveCase() {
      this._state.change({ preserveCase: !this._state.preserveCase }, false);
      if (!this._state.isRevealed) {
        this.highlightFindOptions();
      }
    }
    toggleSearchScope() {
      if (this._state.searchScope) {
        this._state.change({ searchScope: null }, true);
      } else {
        if (this._editor.hasModel()) {
          let selections = this._editor.getSelections();
          selections = selections.map((selection) => {
            if (selection.endColumn === 1 && selection.endLineNumber > selection.startLineNumber) {
              selection = selection.setEndPosition(selection.endLineNumber - 1, this._editor.getModel().getLineMaxColumn(selection.endLineNumber - 1));
            }
            if (!selection.isEmpty()) {
              return selection;
            }
            return null;
          }).filter((element) => !!element);
          if (selections.length) {
            this._state.change({ searchScope: selections }, true);
          }
        }
      }
    }
    setSearchString(searchString) {
      if (this._state.isRegex) {
        searchString = escapeRegExpCharacters(searchString);
      }
      this._state.change({ searchString }, false);
    }
    highlightFindOptions(ignoreWhenVisible = false) {
    }
    async _start(opts, newState) {
      this.disposeModel();
      if (!this._editor.hasModel()) {
        return;
      }
      const stateChanges = {
        ...newState,
        isRevealed: true
      };
      if (opts.seedSearchStringFromSelection === "single") {
        const selectionSearchString = getSelectionSearchString(this._editor, opts.seedSearchStringFromSelection, opts.seedSearchStringFromNonEmptySelection);
        if (selectionSearchString) {
          if (this._state.isRegex) {
            stateChanges.searchString = escapeRegExpCharacters(selectionSearchString);
          } else {
            stateChanges.searchString = selectionSearchString;
          }
        }
      } else if (opts.seedSearchStringFromSelection === "multiple" && !opts.updateSearchScope) {
        const selectionSearchString = getSelectionSearchString(this._editor, opts.seedSearchStringFromSelection);
        if (selectionSearchString) {
          stateChanges.searchString = selectionSearchString;
        }
      }
      if (!stateChanges.searchString && opts.seedSearchStringFromGlobalClipboard) {
        const selectionSearchString = await this.getGlobalBufferTerm();
        if (!this._editor.hasModel()) {
          return;
        }
        if (selectionSearchString) {
          stateChanges.searchString = selectionSearchString;
        }
      }
      if (opts.forceRevealReplace || stateChanges.isReplaceRevealed) {
        stateChanges.isReplaceRevealed = true;
      } else if (!this._findWidgetVisible.get()) {
        stateChanges.isReplaceRevealed = false;
      }
      if (opts.updateSearchScope) {
        const currentSelections = this._editor.getSelections();
        if (currentSelections.some((selection) => !selection.isEmpty())) {
          stateChanges.searchScope = currentSelections;
        }
      }
      stateChanges.loop = opts.loop;
      this._state.change(stateChanges, false);
      if (!this._model) {
        this._model = new FindModelBoundToEditorModel(this._editor, this._state);
      }
    }
    start(opts, newState) {
      return this._start(opts, newState);
    }
    moveToNextMatch() {
      if (this._model) {
        this._model.moveToNextMatch();
        return true;
      }
      return false;
    }
    moveToPrevMatch() {
      if (this._model) {
        this._model.moveToPrevMatch();
        return true;
      }
      return false;
    }
    goToMatch(index) {
      if (this._model) {
        this._model.moveToMatch(index);
        return true;
      }
      return false;
    }
    replace() {
      if (this._model) {
        this._model.replace();
        return true;
      }
      return false;
    }
    replaceAll() {
      if (this._model) {
        if (this._editor.getModel()?.isTooLargeForHeapOperation()) {
          this._notificationService.warn(localize(940, "The file is too large to perform a replace all operation."));
          return false;
        }
        this._model.replaceAll();
        return true;
      }
      return false;
    }
    selectAllMatches() {
      if (this._model) {
        this._model.selectAllMatches();
        this._editor.focus();
        return true;
      }
      return false;
    }
    async getGlobalBufferTerm() {
      if (this._editor.getOption(
        50
        /* EditorOption.find */
      ).globalFindClipboard && this._editor.hasModel() && !this._editor.getModel().isTooLargeForSyncing()) {
        return this._clipboardService.readFindText();
      }
      return "";
    }
    setGlobalBufferTerm(text2) {
      if (this._editor.getOption(
        50
        /* EditorOption.find */
      ).globalFindClipboard && this._editor.hasModel() && !this._editor.getModel().isTooLargeForSyncing()) {
        this._clipboardService.writeFindText(text2);
      }
    }
  }, CommonFindController_1 = _X, _X.ID = "editor.contrib.findController", _X);
  CommonFindController = CommonFindController_1 = __decorate$1I([
    __param$1H(1, IContextKeyService),
    __param$1H(2, IStorageService),
    __param$1H(3, IClipboardService),
    __param$1H(4, INotificationService),
    __param$1H(5, IHoverService)
  ], CommonFindController);
  let FindController = class FindController extends CommonFindController {
    constructor(editor2, _contextViewService, _contextKeyService, _keybindingService, notificationService, _storageService, clipboardService, hoverService) {
      super(editor2, _contextKeyService, _storageService, clipboardService, notificationService, hoverService);
      this._contextViewService = _contextViewService;
      this._keybindingService = _keybindingService;
      this._widget = null;
      this._findOptionsWidget = null;
      this._findWidgetSearchHistory = FindWidgetSearchHistory.getOrCreate(_storageService);
      this._replaceWidgetHistory = ReplaceWidgetHistory.getOrCreate(_storageService);
    }
    async _start(opts, newState) {
      if (!this._widget) {
        this._createFindWidget();
      }
      const selection = this._editor.getSelection();
      let updateSearchScope = false;
      switch (this._editor.getOption(
        50
        /* EditorOption.find */
      ).autoFindInSelection) {
        case "always":
          updateSearchScope = true;
          break;
        case "never":
          updateSearchScope = false;
          break;
        case "multiline": {
          const isSelectionMultipleLine = !!selection && selection.startLineNumber !== selection.endLineNumber;
          updateSearchScope = isSelectionMultipleLine;
          break;
        }
      }
      opts.updateSearchScope = opts.updateSearchScope || updateSearchScope;
      await super._start(opts, newState);
      if (this._widget) {
        if (opts.shouldFocus === 2) {
          this._widget.focusReplaceInput();
        } else if (opts.shouldFocus === 1) {
          this._widget.focusFindInput();
        }
      }
    }
    highlightFindOptions(ignoreWhenVisible = false) {
      if (!this._widget) {
        this._createFindWidget();
      }
      if (this._state.isRevealed && !ignoreWhenVisible) {
        this._widget.highlightFindOptions();
      } else {
        this._findOptionsWidget.highlightFindOptions();
      }
    }
    _createFindWidget() {
      this._widget = this._register(new FindWidget(this._editor, this, this._state, this._contextViewService, this._keybindingService, this._contextKeyService, this._hoverService, this._findWidgetSearchHistory, this._replaceWidgetHistory));
      this._findOptionsWidget = this._register(new FindOptionsWidget(this._editor, this._state, this._keybindingService));
    }
    saveViewState() {
      return this._widget?.getViewState();
    }
    restoreViewState(state) {
      this._widget?.setViewState(state);
    }
  };
  FindController = __decorate$1I([
    __param$1H(1, IContextViewService),
    __param$1H(2, IContextKeyService),
    __param$1H(3, IKeybindingService),
    __param$1H(4, INotificationService),
    __param$1H(5, IStorageService),
    __param$1H(6, IClipboardService),
    __param$1H(7, IHoverService)
  ], FindController);
  const StartFindAction = registerMultiEditorAction(new MultiEditorAction({
    id: FIND_IDS.StartFindAction,
    label: localize2(947, "Find"),
    precondition: ContextKeyExpr.or(EditorContextKeys.focus, ContextKeyExpr.has("editorIsOpen")),
    kbOpts: {
      kbExpr: null,
      primary: 2048 | 36,
      weight: 100
      /* KeybindingWeight.EditorContrib */
    },
    menuOpts: {
      menuId: MenuId.MenubarEditMenu,
      group: "3_find",
      title: localize(941, "&&Find"),
      order: 1
    }
  }));
  StartFindAction.addImplementation(0, (accessor, editor2, args) => {
    const controller = CommonFindController.get(editor2);
    if (!controller) {
      return false;
    }
    return controller.start({
      forceRevealReplace: false,
      seedSearchStringFromSelection: editor2.getOption(
        50
        /* EditorOption.find */
      ).seedSearchStringFromSelection !== "never" ? "single" : "none",
      seedSearchStringFromNonEmptySelection: editor2.getOption(
        50
        /* EditorOption.find */
      ).seedSearchStringFromSelection === "selection",
      seedSearchStringFromGlobalClipboard: editor2.getOption(
        50
        /* EditorOption.find */
      ).globalFindClipboard,
      shouldFocus: 1,
      shouldAnimate: true,
      updateSearchScope: false,
      loop: editor2.getOption(
        50
        /* EditorOption.find */
      ).loop
    });
  });
  const findArgDescription = {
    description: "Open a new In-Editor Find Widget.",
    args: [{
      name: "Open a new In-Editor Find Widget args",
      schema: {
        properties: {
          searchString: { type: "string" },
          replaceString: { type: "string" },
          isRegex: { type: "boolean" },
          matchWholeWord: { type: "boolean" },
          isCaseSensitive: { type: "boolean" },
          preserveCase: { type: "boolean" },
          findInSelection: { type: "boolean" }
        }
      }
    }]
  };
  class StartFindWithArgsAction extends EditorAction {
    constructor() {
      super({
        id: FIND_IDS.StartFindWithArgs,
        label: localize2(948, "Find with Arguments"),
        precondition: void 0,
        kbOpts: {
          kbExpr: null,
          primary: 0,
          weight: 100
          /* KeybindingWeight.EditorContrib */
        },
        metadata: findArgDescription
      });
    }
    async run(accessor, editor2, args) {
      const controller = CommonFindController.get(editor2);
      if (controller) {
        const newState = args ? {
          searchString: args.searchString,
          replaceString: args.replaceString,
          isReplaceRevealed: args.replaceString !== void 0,
          isRegex: args.isRegex,
          // isRegexOverride: args.regexOverride,
          wholeWord: args.matchWholeWord,
          // wholeWordOverride: args.wholeWordOverride,
          matchCase: args.isCaseSensitive,
          // matchCaseOverride: args.matchCaseOverride,
          preserveCase: args.preserveCase
          // preserveCaseOverride: args.preserveCaseOverride,
        } : {};
        await controller.start({
          forceRevealReplace: false,
          seedSearchStringFromSelection: controller.getState().searchString.length === 0 && editor2.getOption(
            50
            /* EditorOption.find */
          ).seedSearchStringFromSelection !== "never" ? "single" : "none",
          seedSearchStringFromNonEmptySelection: editor2.getOption(
            50
            /* EditorOption.find */
          ).seedSearchStringFromSelection === "selection",
          seedSearchStringFromGlobalClipboard: true,
          shouldFocus: 1,
          shouldAnimate: true,
          updateSearchScope: args?.findInSelection || false,
          loop: editor2.getOption(
            50
            /* EditorOption.find */
          ).loop
        }, newState);
        controller.setGlobalBufferTerm(controller.getState().searchString);
      }
    }
  }
  class StartFindWithSelectionAction extends EditorAction {
    constructor() {
      super({
        id: FIND_IDS.StartFindWithSelection,
        label: localize2(949, "Find with Selection"),
        precondition: void 0,
        kbOpts: {
          kbExpr: null,
          primary: 0,
          mac: {
            primary: 2048 | 35
          },
          weight: 100
          /* KeybindingWeight.EditorContrib */
        }
      });
    }
    async run(accessor, editor2) {
      const controller = CommonFindController.get(editor2);
      if (controller) {
        await controller.start({
          forceRevealReplace: false,
          seedSearchStringFromSelection: "multiple",
          seedSearchStringFromNonEmptySelection: false,
          seedSearchStringFromGlobalClipboard: false,
          shouldFocus: 0,
          shouldAnimate: true,
          updateSearchScope: false,
          loop: editor2.getOption(
            50
            /* EditorOption.find */
          ).loop
        });
        controller.setGlobalBufferTerm(controller.getState().searchString);
      }
    }
  }
  async function matchFindAction(editor2, next) {
    const controller = CommonFindController.get(editor2);
    if (!controller) {
      return;
    }
    const runMatch = () => {
      const result = next ? controller.moveToNextMatch() : controller.moveToPrevMatch();
      if (result) {
        controller.editor.pushUndoStop();
        return true;
      }
      return false;
    };
    if (!runMatch()) {
      await controller.start({
        forceRevealReplace: false,
        seedSearchStringFromSelection: controller.getState().searchString.length === 0 && editor2.getOption(
          50
          /* EditorOption.find */
        ).seedSearchStringFromSelection !== "never" ? "single" : "none",
        seedSearchStringFromNonEmptySelection: editor2.getOption(
          50
          /* EditorOption.find */
        ).seedSearchStringFromSelection === "selection",
        seedSearchStringFromGlobalClipboard: true,
        shouldFocus: 0,
        shouldAnimate: true,
        updateSearchScope: false,
        loop: editor2.getOption(
          50
          /* EditorOption.find */
        ).loop
      });
      runMatch();
    }
  }
  const NextMatchFindAction = registerMultiEditorAction(new MultiEditorAction({
    id: FIND_IDS.NextMatchFindAction,
    label: localize2(950, "Find Next"),
    precondition: void 0,
    kbOpts: [{
      kbExpr: EditorContextKeys.focus,
      primary: 61,
      mac: { primary: 2048 | 37, secondary: [
        61
        /* KeyCode.F3 */
      ] },
      weight: 100
      /* KeybindingWeight.EditorContrib */
    }, {
      kbExpr: ContextKeyExpr.and(EditorContextKeys.focus, CONTEXT_FIND_INPUT_FOCUSED),
      primary: 3,
      weight: 100
      /* KeybindingWeight.EditorContrib */
    }]
  }));
  NextMatchFindAction.addImplementation(0, async (accessor, editor2, args) => {
    return matchFindAction(editor2, true);
  });
  const PreviousMatchFindAction = registerMultiEditorAction(new MultiEditorAction({
    id: FIND_IDS.PreviousMatchFindAction,
    label: localize2(951, "Find Previous"),
    precondition: void 0,
    kbOpts: [{
      kbExpr: EditorContextKeys.focus,
      primary: 1024 | 61,
      mac: { primary: 2048 | 1024 | 37, secondary: [
        1024 | 61
        /* KeyCode.F3 */
      ] },
      weight: 100
      /* KeybindingWeight.EditorContrib */
    }, {
      kbExpr: ContextKeyExpr.and(EditorContextKeys.focus, CONTEXT_FIND_INPUT_FOCUSED),
      primary: 1024 | 3,
      weight: 100
      /* KeybindingWeight.EditorContrib */
    }]
  }));
  PreviousMatchFindAction.addImplementation(0, async (accessor, editor2, args) => {
    return matchFindAction(editor2, false);
  });
  class MoveToMatchFindAction extends EditorAction {
    constructor() {
      super({
        id: FIND_IDS.GoToMatchFindAction,
        label: localize2(952, "Go to Match..."),
        precondition: CONTEXT_FIND_WIDGET_VISIBLE
      });
      this._highlightDecorations = [];
    }
    run(accessor, editor2, args) {
      const controller = CommonFindController.get(editor2);
      if (!controller) {
        return;
      }
      const matchesCount = controller.getState().matchesCount;
      if (matchesCount < 1) {
        const notificationService = accessor.get(INotificationService);
        notificationService.notify({
          severity: Severity.Warning,
          message: localize(942, "No matches. Try searching for something else.")
        });
        return;
      }
      const quickInputService = accessor.get(IQuickInputService);
      const disposables = new DisposableStore();
      const inputBox = disposables.add(quickInputService.createInputBox());
      inputBox.placeholder = localize(943, "Type a number to go to a specific match (between 1 and {0})", matchesCount);
      const toFindMatchIndex = (value) => {
        const index = parseInt(value);
        if (isNaN(index)) {
          return void 0;
        }
        const matchCount = controller.getState().matchesCount;
        if (index > 0 && index <= matchCount) {
          return index - 1;
        } else if (index < 0 && index >= -matchCount) {
          return matchCount + index;
        }
        return void 0;
      };
      const updatePickerAndEditor = (value) => {
        const index = toFindMatchIndex(value);
        if (typeof index === "number") {
          inputBox.validationMessage = void 0;
          controller.goToMatch(index);
          const currentMatch = controller.getState().currentMatch;
          if (currentMatch) {
            this.addDecorations(editor2, currentMatch);
          }
        } else {
          inputBox.validationMessage = localize(944, "Please type a number between 1 and {0}", controller.getState().matchesCount);
          this.clearDecorations(editor2);
        }
      };
      disposables.add(inputBox.onDidChangeValue((value) => {
        updatePickerAndEditor(value);
      }));
      disposables.add(inputBox.onDidAccept(() => {
        const index = toFindMatchIndex(inputBox.value);
        if (typeof index === "number") {
          controller.goToMatch(index);
          inputBox.hide();
        } else {
          inputBox.validationMessage = localize(945, "Please type a number between 1 and {0}", controller.getState().matchesCount);
        }
      }));
      disposables.add(inputBox.onDidHide(() => {
        this.clearDecorations(editor2);
        disposables.dispose();
      }));
      inputBox.show();
    }
    clearDecorations(editor2) {
      editor2.changeDecorations((changeAccessor) => {
        this._highlightDecorations = changeAccessor.deltaDecorations(this._highlightDecorations, []);
      });
    }
    addDecorations(editor2, range2) {
      editor2.changeDecorations((changeAccessor) => {
        this._highlightDecorations = changeAccessor.deltaDecorations(this._highlightDecorations, [
          {
            range: range2,
            options: {
              description: "find-match-quick-access-range-highlight",
              className: "rangeHighlight",
              isWholeLine: true
            }
          },
          {
            range: range2,
            options: {
              description: "find-match-quick-access-range-highlight-overview",
              overviewRuler: {
                color: themeColorFromId(overviewRulerRangeHighlight),
                position: OverviewRulerLane$1.Full
              }
            }
          }
        ]);
      });
    }
  }
  class SelectionMatchFindAction extends EditorAction {
    async run(accessor, editor2) {
      const controller = CommonFindController.get(editor2);
      if (!controller) {
        return;
      }
      const selectionSearchString = getSelectionSearchString(editor2, "single", false);
      if (selectionSearchString) {
        controller.setSearchString(selectionSearchString);
      }
      if (!this._run(controller)) {
        await controller.start({
          forceRevealReplace: false,
          seedSearchStringFromSelection: "none",
          seedSearchStringFromNonEmptySelection: false,
          seedSearchStringFromGlobalClipboard: false,
          shouldFocus: 0,
          shouldAnimate: true,
          updateSearchScope: false,
          loop: editor2.getOption(
            50
            /* EditorOption.find */
          ).loop
        });
        this._run(controller);
      }
    }
  }
  class NextSelectionMatchFindAction extends SelectionMatchFindAction {
    constructor() {
      super({
        id: FIND_IDS.NextSelectionMatchFindAction,
        label: localize2(953, "Find Next Selection"),
        precondition: void 0,
        kbOpts: {
          kbExpr: EditorContextKeys.focus,
          primary: 2048 | 61,
          weight: 100
          /* KeybindingWeight.EditorContrib */
        }
      });
    }
    _run(controller) {
      return controller.moveToNextMatch();
    }
  }
  class PreviousSelectionMatchFindAction extends SelectionMatchFindAction {
    constructor() {
      super({
        id: FIND_IDS.PreviousSelectionMatchFindAction,
        label: localize2(954, "Find Previous Selection"),
        precondition: void 0,
        kbOpts: {
          kbExpr: EditorContextKeys.focus,
          primary: 2048 | 1024 | 61,
          weight: 100
          /* KeybindingWeight.EditorContrib */
        }
      });
    }
    _run(controller) {
      return controller.moveToPrevMatch();
    }
  }
  const StartFindReplaceAction = registerMultiEditorAction(new MultiEditorAction({
    id: FIND_IDS.StartFindReplaceAction,
    label: localize2(955, "Replace"),
    precondition: ContextKeyExpr.or(EditorContextKeys.focus, ContextKeyExpr.has("editorIsOpen")),
    kbOpts: {
      kbExpr: null,
      primary: 2048 | 38,
      mac: {
        primary: 2048 | 512 | 36
        /* KeyCode.KeyF */
      },
      weight: 100
      /* KeybindingWeight.EditorContrib */
    },
    menuOpts: {
      menuId: MenuId.MenubarEditMenu,
      group: "3_find",
      title: localize(946, "&&Replace"),
      order: 2
    }
  }));
  StartFindReplaceAction.addImplementation(0, (accessor, editor2, args) => {
    if (!editor2.hasModel() || editor2.getOption(
      104
      /* EditorOption.readOnly */
    )) {
      return false;
    }
    const controller = CommonFindController.get(editor2);
    if (!controller) {
      return false;
    }
    const currentSelection = editor2.getSelection();
    const findInputFocused = controller.isFindInputFocused();
    const seedSearchStringFromSelection = !currentSelection.isEmpty() && currentSelection.startLineNumber === currentSelection.endLineNumber && editor2.getOption(
      50
      /* EditorOption.find */
    ).seedSearchStringFromSelection !== "never" && !findInputFocused;
    const shouldFocus = findInputFocused || seedSearchStringFromSelection ? 2 : 1;
    return controller.start({
      forceRevealReplace: true,
      seedSearchStringFromSelection: seedSearchStringFromSelection ? "single" : "none",
      seedSearchStringFromNonEmptySelection: editor2.getOption(
        50
        /* EditorOption.find */
      ).seedSearchStringFromSelection === "selection",
      seedSearchStringFromGlobalClipboard: editor2.getOption(
        50
        /* EditorOption.find */
      ).seedSearchStringFromSelection !== "never",
      shouldFocus,
      shouldAnimate: true,
      updateSearchScope: false,
      loop: editor2.getOption(
        50
        /* EditorOption.find */
      ).loop
    });
  });
  registerEditorContribution(
    CommonFindController.ID,
    FindController,
    0
    /* EditorContributionInstantiation.Eager */
  );
  registerEditorAction(StartFindWithArgsAction);
  registerEditorAction(StartFindWithSelectionAction);
  registerEditorAction(MoveToMatchFindAction);
  registerEditorAction(NextSelectionMatchFindAction);
  registerEditorAction(PreviousSelectionMatchFindAction);
  const FindCommand = EditorCommand.bindToContribution(CommonFindController.get);
  registerEditorCommand(new FindCommand({
    id: FIND_IDS.CloseFindWidgetCommand,
    precondition: CONTEXT_FIND_WIDGET_VISIBLE,
    handler: (x) => x.closeFindWidget(),
    kbOpts: {
      weight: 100 + 5,
      kbExpr: ContextKeyExpr.and(EditorContextKeys.focus, ContextKeyExpr.not("isComposing")),
      primary: 9,
      secondary: [
        1024 | 9
        /* KeyCode.Escape */
      ]
    }
  }));
  registerEditorCommand(new FindCommand({
    id: FIND_IDS.ToggleCaseSensitiveCommand,
    precondition: void 0,
    handler: (x) => x.toggleCaseSensitive(),
    kbOpts: {
      weight: 100 + 5,
      kbExpr: EditorContextKeys.focus,
      primary: ToggleCaseSensitiveKeybinding.primary,
      mac: ToggleCaseSensitiveKeybinding.mac,
      win: ToggleCaseSensitiveKeybinding.win,
      linux: ToggleCaseSensitiveKeybinding.linux
    }
  }));
  registerEditorCommand(new FindCommand({
    id: FIND_IDS.ToggleWholeWordCommand,
    precondition: void 0,
    handler: (x) => x.toggleWholeWords(),
    kbOpts: {
      weight: 100 + 5,
      kbExpr: EditorContextKeys.focus,
      primary: ToggleWholeWordKeybinding.primary,
      mac: ToggleWholeWordKeybinding.mac,
      win: ToggleWholeWordKeybinding.win,
      linux: ToggleWholeWordKeybinding.linux
    }
  }));
  registerEditorCommand(new FindCommand({
    id: FIND_IDS.ToggleRegexCommand,
    precondition: void 0,
    handler: (x) => x.toggleRegex(),
    kbOpts: {
      weight: 100 + 5,
      kbExpr: EditorContextKeys.focus,
      primary: ToggleRegexKeybinding.primary,
      mac: ToggleRegexKeybinding.mac,
      win: ToggleRegexKeybinding.win,
      linux: ToggleRegexKeybinding.linux
    }
  }));
  registerEditorCommand(new FindCommand({
    id: FIND_IDS.ToggleSearchScopeCommand,
    precondition: void 0,
    handler: (x) => x.toggleSearchScope(),
    kbOpts: {
      weight: 100 + 5,
      kbExpr: EditorContextKeys.focus,
      primary: ToggleSearchScopeKeybinding.primary,
      mac: ToggleSearchScopeKeybinding.mac,
      win: ToggleSearchScopeKeybinding.win,
      linux: ToggleSearchScopeKeybinding.linux
    }
  }));
  registerEditorCommand(new FindCommand({
    id: FIND_IDS.TogglePreserveCaseCommand,
    precondition: void 0,
    handler: (x) => x.togglePreserveCase(),
    kbOpts: {
      weight: 100 + 5,
      kbExpr: EditorContextKeys.focus,
      primary: TogglePreserveCaseKeybinding.primary,
      mac: TogglePreserveCaseKeybinding.mac,
      win: TogglePreserveCaseKeybinding.win,
      linux: TogglePreserveCaseKeybinding.linux
    }
  }));
  registerEditorCommand(new FindCommand({
    id: FIND_IDS.ReplaceOneAction,
    precondition: CONTEXT_FIND_WIDGET_VISIBLE,
    handler: (x) => x.replace(),
    kbOpts: {
      weight: 100 + 5,
      kbExpr: EditorContextKeys.focus,
      primary: 2048 | 1024 | 22
      /* KeyCode.Digit1 */
    }
  }));
  registerEditorCommand(new FindCommand({
    id: FIND_IDS.ReplaceOneAction,
    precondition: CONTEXT_FIND_WIDGET_VISIBLE,
    handler: (x) => x.replace(),
    kbOpts: {
      weight: 100 + 5,
      kbExpr: ContextKeyExpr.and(EditorContextKeys.focus, CONTEXT_REPLACE_INPUT_FOCUSED),
      primary: 3
      /* KeyCode.Enter */
    }
  }));
  registerEditorCommand(new FindCommand({
    id: FIND_IDS.ReplaceAllAction,
    precondition: CONTEXT_FIND_WIDGET_VISIBLE,
    handler: (x) => x.replaceAll(),
    kbOpts: {
      weight: 100 + 5,
      kbExpr: EditorContextKeys.focus,
      primary: 2048 | 512 | 3
      /* KeyCode.Enter */
    }
  }));
  registerEditorCommand(new FindCommand({
    id: FIND_IDS.ReplaceAllAction,
    precondition: CONTEXT_FIND_WIDGET_VISIBLE,
    handler: (x) => x.replaceAll(),
    kbOpts: {
      weight: 100 + 5,
      kbExpr: ContextKeyExpr.and(EditorContextKeys.focus, CONTEXT_REPLACE_INPUT_FOCUSED),
      primary: void 0,
      mac: {
        primary: 2048 | 3
      }
    }
  }));
  registerEditorCommand(new FindCommand({
    id: FIND_IDS.SelectAllMatchesAction,
    precondition: CONTEXT_FIND_WIDGET_VISIBLE,
    handler: (x) => x.selectAllMatches(),
    kbOpts: {
      weight: 100 + 5,
      kbExpr: EditorContextKeys.focus,
      primary: 512 | 3
      /* KeyCode.Enter */
    }
  }));
  const foldSourceAbbr = {
    [
      0
      /* FoldSource.provider */
    ]: " ",
    [
      1
      /* FoldSource.userDefined */
    ]: "u",
    [
      2
      /* FoldSource.recovered */
    ]: "r"
  };
  const MAX_FOLDING_REGIONS = 65535;
  const MAX_LINE_NUMBER = 16777215;
  const MASK_INDENT = 4278190080;
  class BitField {
    constructor(size2) {
      const numWords = Math.ceil(size2 / 32);
      this._states = new Uint32Array(numWords);
    }
    get(index) {
      const arrayIndex = index / 32 | 0;
      const bit = index % 32;
      return (this._states[arrayIndex] & 1 << bit) !== 0;
    }
    set(index, newState) {
      const arrayIndex = index / 32 | 0;
      const bit = index % 32;
      const value = this._states[arrayIndex];
      if (newState) {
        this._states[arrayIndex] = value | 1 << bit;
      } else {
        this._states[arrayIndex] = value & ~(1 << bit);
      }
    }
  }
  class FoldingRegions {
    constructor(startIndexes, endIndexes, types) {
      if (startIndexes.length !== endIndexes.length || startIndexes.length > MAX_FOLDING_REGIONS) {
        throw new Error("invalid startIndexes or endIndexes size");
      }
      this._startIndexes = startIndexes;
      this._endIndexes = endIndexes;
      this._collapseStates = new BitField(startIndexes.length);
      this._userDefinedStates = new BitField(startIndexes.length);
      this._recoveredStates = new BitField(startIndexes.length);
      this._types = types;
      this._parentsComputed = false;
    }
    ensureParentIndices() {
      if (!this._parentsComputed) {
        this._parentsComputed = true;
        const parentIndexes = [];
        const isInsideLast = (startLineNumber, endLineNumber) => {
          const index = parentIndexes[parentIndexes.length - 1];
          return this.getStartLineNumber(index) <= startLineNumber && this.getEndLineNumber(index) >= endLineNumber;
        };
        for (let i2 = 0, len = this._startIndexes.length; i2 < len; i2++) {
          const startLineNumber = this._startIndexes[i2];
          const endLineNumber = this._endIndexes[i2];
          if (startLineNumber > MAX_LINE_NUMBER || endLineNumber > MAX_LINE_NUMBER) {
            throw new Error("startLineNumber or endLineNumber must not exceed " + MAX_LINE_NUMBER);
          }
          while (parentIndexes.length > 0 && !isInsideLast(startLineNumber, endLineNumber)) {
            parentIndexes.pop();
          }
          const parentIndex = parentIndexes.length > 0 ? parentIndexes[parentIndexes.length - 1] : -1;
          parentIndexes.push(i2);
          this._startIndexes[i2] = startLineNumber + ((parentIndex & 255) << 24);
          this._endIndexes[i2] = endLineNumber + ((parentIndex & 65280) << 16);
        }
      }
    }
    get length() {
      return this._startIndexes.length;
    }
    getStartLineNumber(index) {
      return this._startIndexes[index] & MAX_LINE_NUMBER;
    }
    getEndLineNumber(index) {
      return this._endIndexes[index] & MAX_LINE_NUMBER;
    }
    getType(index) {
      return this._types ? this._types[index] : void 0;
    }
    hasTypes() {
      return !!this._types;
    }
    isCollapsed(index) {
      return this._collapseStates.get(index);
    }
    setCollapsed(index, newState) {
      this._collapseStates.set(index, newState);
    }
    isUserDefined(index) {
      return this._userDefinedStates.get(index);
    }
    setUserDefined(index, newState) {
      return this._userDefinedStates.set(index, newState);
    }
    isRecovered(index) {
      return this._recoveredStates.get(index);
    }
    setRecovered(index, newState) {
      return this._recoveredStates.set(index, newState);
    }
    getSource(index) {
      if (this.isUserDefined(index)) {
        return 1;
      } else if (this.isRecovered(index)) {
        return 2;
      }
      return 0;
    }
    setSource(index, source) {
      if (source === 1) {
        this.setUserDefined(index, true);
        this.setRecovered(index, false);
      } else if (source === 2) {
        this.setUserDefined(index, false);
        this.setRecovered(index, true);
      } else {
        this.setUserDefined(index, false);
        this.setRecovered(index, false);
      }
    }
    setCollapsedAllOfType(type, newState) {
      let hasChanged = false;
      if (this._types) {
        for (let i2 = 0; i2 < this._types.length; i2++) {
          if (this._types[i2] === type) {
            this.setCollapsed(i2, newState);
            hasChanged = true;
          }
        }
      }
      return hasChanged;
    }
    toRegion(index) {
      return new FoldingRegion(this, index);
    }
    getParentIndex(index) {
      this.ensureParentIndices();
      const parent = ((this._startIndexes[index] & MASK_INDENT) >>> 24) + ((this._endIndexes[index] & MASK_INDENT) >>> 16);
      if (parent === MAX_FOLDING_REGIONS) {
        return -1;
      }
      return parent;
    }
    contains(index, line) {
      return this.getStartLineNumber(index) <= line && this.getEndLineNumber(index) >= line;
    }
    findIndex(line) {
      let low = 0, high = this._startIndexes.length;
      if (high === 0) {
        return -1;
      }
      while (low < high) {
        const mid = Math.floor((low + high) / 2);
        if (line < this.getStartLineNumber(mid)) {
          high = mid;
        } else {
          low = mid + 1;
        }
      }
      return low - 1;
    }
    findRange(line) {
      let index = this.findIndex(line);
      if (index >= 0) {
        const endLineNumber = this.getEndLineNumber(index);
        if (endLineNumber >= line) {
          return index;
        }
        index = this.getParentIndex(index);
        while (index !== -1) {
          if (this.contains(index, line)) {
            return index;
          }
          index = this.getParentIndex(index);
        }
      }
      return -1;
    }
    toString() {
      const res = [];
      for (let i2 = 0; i2 < this.length; i2++) {
        res[i2] = `[${foldSourceAbbr[this.getSource(i2)]}${this.isCollapsed(i2) ? "+" : "-"}] ${this.getStartLineNumber(i2)}/${this.getEndLineNumber(i2)}`;
      }
      return res.join(", ");
    }
    toFoldRange(index) {
      return {
        startLineNumber: this._startIndexes[index] & MAX_LINE_NUMBER,
        endLineNumber: this._endIndexes[index] & MAX_LINE_NUMBER,
        type: this._types ? this._types[index] : void 0,
        isCollapsed: this.isCollapsed(index),
        source: this.getSource(index)
      };
    }
    static fromFoldRanges(ranges) {
      const rangesLength = ranges.length;
      const startIndexes = new Uint32Array(rangesLength);
      const endIndexes = new Uint32Array(rangesLength);
      let types = [];
      let gotTypes = false;
      for (let i2 = 0; i2 < rangesLength; i2++) {
        const range2 = ranges[i2];
        startIndexes[i2] = range2.startLineNumber;
        endIndexes[i2] = range2.endLineNumber;
        types.push(range2.type);
        if (range2.type) {
          gotTypes = true;
        }
      }
      if (!gotTypes) {
        types = void 0;
      }
      const regions = new FoldingRegions(startIndexes, endIndexes, types);
      for (let i2 = 0; i2 < rangesLength; i2++) {
        if (ranges[i2].isCollapsed) {
          regions.setCollapsed(i2, true);
        }
        regions.setSource(i2, ranges[i2].source);
      }
      return regions;
    }
    /**
     * Two inputs, each a FoldingRegions or a FoldRange[], are merged.
     * Each input must be pre-sorted on startLineNumber.
     * The first list is assumed to always include all regions currently defined by range providers.
     * The second list only contains the previously collapsed and all manual ranges.
     * If the line position matches, the range of the new range is taken, and the range is no longer manual
     * When an entry in one list overlaps an entry in the other, the second list's entry "wins" and
     * overlapping entries in the first list are discarded.
     * Invalid entries are discarded. An entry is invalid if:
     * 		the start and end line numbers aren't a valid range of line numbers,
     * 		it is out of sequence or has the same start line as a preceding entry,
     * 		it overlaps a preceding entry and is not fully contained by that entry.
     */
    static sanitizeAndMerge(rangesA, rangesB, maxLineNumber, selection) {
      maxLineNumber = maxLineNumber ?? Number.MAX_VALUE;
      const getIndexedFunction = (r, limit) => {
        return Array.isArray(r) ? ((i2) => {
          return i2 < limit ? r[i2] : void 0;
        }) : ((i2) => {
          return i2 < limit ? r.toFoldRange(i2) : void 0;
        });
      };
      const getA = getIndexedFunction(rangesA, rangesA.length);
      const getB = getIndexedFunction(rangesB, rangesB.length);
      let indexA = 0;
      let indexB = 0;
      let nextA = getA(0);
      let nextB = getB(0);
      const stackedRanges = [];
      let topStackedRange;
      let prevLineNumber = 0;
      const resultRanges = [];
      while (nextA || nextB) {
        let useRange = void 0;
        if (nextB && (!nextA || nextA.startLineNumber >= nextB.startLineNumber)) {
          if (nextA && nextA.startLineNumber === nextB.startLineNumber) {
            if (nextB.source === 1) {
              useRange = nextB;
            } else {
              useRange = nextA;
              useRange.isCollapsed = nextB.isCollapsed && (nextA.endLineNumber === nextB.endLineNumber || !selection?.startsInside(nextA.startLineNumber + 1, nextA.endLineNumber + 1));
              useRange.source = 0;
            }
            nextA = getA(++indexA);
          } else {
            useRange = nextB;
            if (nextB.isCollapsed && nextB.source === 0) {
              useRange.source = 2;
            }
          }
          nextB = getB(++indexB);
        } else {
          let scanIndex = indexB;
          let prescanB = nextB;
          while (true) {
            if (!prescanB || prescanB.startLineNumber > nextA.endLineNumber) {
              useRange = nextA;
              break;
            }
            if (prescanB.source === 1 && prescanB.endLineNumber > nextA.endLineNumber) {
              break;
            }
            prescanB = getB(++scanIndex);
          }
          nextA = getA(++indexA);
        }
        if (useRange) {
          while (topStackedRange && topStackedRange.endLineNumber < useRange.startLineNumber) {
            topStackedRange = stackedRanges.pop();
          }
          if (useRange.endLineNumber > useRange.startLineNumber && useRange.startLineNumber > prevLineNumber && useRange.endLineNumber <= maxLineNumber && (!topStackedRange || topStackedRange.endLineNumber >= useRange.endLineNumber)) {
            resultRanges.push(useRange);
            prevLineNumber = useRange.startLineNumber;
            if (topStackedRange) {
              stackedRanges.push(topStackedRange);
            }
            topStackedRange = useRange;
          }
        }
      }
      return resultRanges;
    }
  }
  class FoldingRegion {
    constructor(ranges, index) {
      this.ranges = ranges;
      this.index = index;
    }
    get startLineNumber() {
      return this.ranges.getStartLineNumber(this.index);
    }
    get endLineNumber() {
      return this.ranges.getEndLineNumber(this.index);
    }
    get regionIndex() {
      return this.index;
    }
    get parentIndex() {
      return this.ranges.getParentIndex(this.index);
    }
    get isCollapsed() {
      return this.ranges.isCollapsed(this.index);
    }
    containedBy(range2) {
      return range2.startLineNumber <= this.startLineNumber && range2.endLineNumber >= this.endLineNumber;
    }
    containsLine(lineNumber) {
      return this.startLineNumber <= lineNumber && lineNumber <= this.endLineNumber;
    }
  }
  class FoldingModel {
    get regions() {
      return this._regions;
    }
    get textModel() {
      return this._textModel;
    }
    constructor(textModel, decorationProvider) {
      this._updateEventEmitter = new Emitter$1();
      this.onDidChange = this._updateEventEmitter.event;
      this._textModel = textModel;
      this._decorationProvider = decorationProvider;
      this._regions = new FoldingRegions(new Uint32Array(0), new Uint32Array(0));
      this._editorDecorationIds = [];
    }
    toggleCollapseState(toggledRegions) {
      if (!toggledRegions.length) {
        return;
      }
      toggledRegions = toggledRegions.sort((r1, r2) => r1.regionIndex - r2.regionIndex);
      const processed = {};
      this._decorationProvider.changeDecorations((accessor) => {
        let k = 0;
        let dirtyRegionEndLine = -1;
        let lastHiddenLine = -1;
        const updateDecorationsUntil = (index) => {
          while (k < index) {
            const endLineNumber = this._regions.getEndLineNumber(k);
            const isCollapsed = this._regions.isCollapsed(k);
            if (endLineNumber <= dirtyRegionEndLine) {
              const isManual = this.regions.getSource(k) !== 0;
              accessor.changeDecorationOptions(this._editorDecorationIds[k], this._decorationProvider.getDecorationOption(isCollapsed, endLineNumber <= lastHiddenLine, isManual));
            }
            if (isCollapsed && endLineNumber > lastHiddenLine) {
              lastHiddenLine = endLineNumber;
            }
            k++;
          }
        };
        for (const region of toggledRegions) {
          const index = region.regionIndex;
          const editorDecorationId = this._editorDecorationIds[index];
          if (editorDecorationId && !processed[editorDecorationId]) {
            processed[editorDecorationId] = true;
            updateDecorationsUntil(index);
            const newCollapseState = !this._regions.isCollapsed(index);
            this._regions.setCollapsed(index, newCollapseState);
            dirtyRegionEndLine = Math.max(dirtyRegionEndLine, this._regions.getEndLineNumber(index));
          }
        }
        updateDecorationsUntil(this._regions.length);
      });
      this._updateEventEmitter.fire({ model: this, collapseStateChanged: toggledRegions });
    }
    removeManualRanges(ranges) {
      const newFoldingRanges = new Array();
      const intersects2 = (foldRange) => {
        for (const range2 of ranges) {
          if (!(range2.startLineNumber > foldRange.endLineNumber || foldRange.startLineNumber > range2.endLineNumber)) {
            return true;
          }
        }
        return false;
      };
      for (let i2 = 0; i2 < this._regions.length; i2++) {
        const foldRange = this._regions.toFoldRange(i2);
        if (foldRange.source === 0 || !intersects2(foldRange)) {
          newFoldingRanges.push(foldRange);
        }
      }
      this.updatePost(FoldingRegions.fromFoldRanges(newFoldingRanges));
    }
    update(newRegions, selection) {
      const foldedOrManualRanges = this._currentFoldedOrManualRanges(selection);
      const newRanges = FoldingRegions.sanitizeAndMerge(newRegions, foldedOrManualRanges, this._textModel.getLineCount(), selection);
      this.updatePost(FoldingRegions.fromFoldRanges(newRanges));
    }
    updatePost(newRegions) {
      const newEditorDecorations = [];
      let lastHiddenLine = -1;
      for (let index = 0, limit = newRegions.length; index < limit; index++) {
        const startLineNumber = newRegions.getStartLineNumber(index);
        const endLineNumber = newRegions.getEndLineNumber(index);
        const isCollapsed = newRegions.isCollapsed(index);
        const isManual = newRegions.getSource(index) !== 0;
        const decorationRange = {
          startLineNumber,
          startColumn: this._textModel.getLineMaxColumn(startLineNumber),
          endLineNumber,
          endColumn: this._textModel.getLineMaxColumn(endLineNumber) + 1
        };
        newEditorDecorations.push({ range: decorationRange, options: this._decorationProvider.getDecorationOption(isCollapsed, endLineNumber <= lastHiddenLine, isManual) });
        if (isCollapsed && endLineNumber > lastHiddenLine) {
          lastHiddenLine = endLineNumber;
        }
      }
      this._decorationProvider.changeDecorations((accessor) => this._editorDecorationIds = accessor.deltaDecorations(this._editorDecorationIds, newEditorDecorations));
      this._regions = newRegions;
      this._updateEventEmitter.fire({ model: this });
    }
    _currentFoldedOrManualRanges(selection) {
      const foldedRanges = [];
      for (let i2 = 0, limit = this._regions.length; i2 < limit; i2++) {
        let isCollapsed = this.regions.isCollapsed(i2);
        const source = this.regions.getSource(i2);
        if (isCollapsed || source !== 0) {
          const foldRange = this._regions.toFoldRange(i2);
          const decRange = this._textModel.getDecorationRange(this._editorDecorationIds[i2]);
          if (decRange) {
            if (isCollapsed && selection?.startsInside(decRange.startLineNumber + 1, decRange.endLineNumber)) {
              isCollapsed = false;
            }
            foldedRanges.push({
              startLineNumber: decRange.startLineNumber,
              endLineNumber: decRange.endLineNumber,
              type: foldRange.type,
              isCollapsed,
              source
            });
          }
        }
      }
      return foldedRanges;
    }
    /**
     * Collapse state memento, for persistence only
     */
    getMemento() {
      const foldedOrManualRanges = this._currentFoldedOrManualRanges();
      const result = [];
      const maxLineNumber = this._textModel.getLineCount();
      for (let i2 = 0, limit = foldedOrManualRanges.length; i2 < limit; i2++) {
        const range2 = foldedOrManualRanges[i2];
        if (range2.startLineNumber >= range2.endLineNumber || range2.startLineNumber < 1 || range2.endLineNumber > maxLineNumber) {
          continue;
        }
        const checksum = this._getLinesChecksum(range2.startLineNumber + 1, range2.endLineNumber);
        result.push({
          startLineNumber: range2.startLineNumber,
          endLineNumber: range2.endLineNumber,
          isCollapsed: range2.isCollapsed,
          source: range2.source,
          checksum
        });
      }
      return result.length > 0 ? result : void 0;
    }
    /**
     * Apply persisted state, for persistence only
     */
    applyMemento(state) {
      if (!Array.isArray(state)) {
        return;
      }
      const rangesToRestore = [];
      const maxLineNumber = this._textModel.getLineCount();
      for (const range2 of state) {
        if (range2.startLineNumber >= range2.endLineNumber || range2.startLineNumber < 1 || range2.endLineNumber > maxLineNumber) {
          continue;
        }
        const checksum = this._getLinesChecksum(range2.startLineNumber + 1, range2.endLineNumber);
        if (!range2.checksum || checksum === range2.checksum) {
          rangesToRestore.push({
            startLineNumber: range2.startLineNumber,
            endLineNumber: range2.endLineNumber,
            type: void 0,
            isCollapsed: range2.isCollapsed ?? true,
            source: range2.source ?? 0
            /* FoldSource.provider */
          });
        }
      }
      const newRanges = FoldingRegions.sanitizeAndMerge(this._regions, rangesToRestore, maxLineNumber);
      this.updatePost(FoldingRegions.fromFoldRanges(newRanges));
    }
    _getLinesChecksum(lineNumber1, lineNumber2) {
      const h2 = hash(this._textModel.getLineContent(lineNumber1) + this._textModel.getLineContent(lineNumber2));
      return h2 % 1e6;
    }
    dispose() {
      this._decorationProvider.removeDecorations(this._editorDecorationIds);
    }
    getAllRegionsAtLine(lineNumber, filter) {
      const result = [];
      if (this._regions) {
        let index = this._regions.findRange(lineNumber);
        let level = 1;
        while (index >= 0) {
          const current = this._regions.toRegion(index);
          if (!filter || filter(current, level)) {
            result.push(current);
          }
          level++;
          index = current.parentIndex;
        }
      }
      return result;
    }
    getRegionAtLine(lineNumber) {
      if (this._regions) {
        const index = this._regions.findRange(lineNumber);
        if (index >= 0) {
          return this._regions.toRegion(index);
        }
      }
      return null;
    }
    getRegionsInside(region, filter) {
      const result = [];
      const index = region ? region.regionIndex + 1 : 0;
      const endLineNumber = region ? region.endLineNumber : Number.MAX_VALUE;
      if (filter && filter.length === 2) {
        const levelStack = [];
        for (let i2 = index, len = this._regions.length; i2 < len; i2++) {
          const current = this._regions.toRegion(i2);
          if (this._regions.getStartLineNumber(i2) < endLineNumber) {
            while (levelStack.length > 0 && !current.containedBy(levelStack[levelStack.length - 1])) {
              levelStack.pop();
            }
            levelStack.push(current);
            if (filter(current, levelStack.length)) {
              result.push(current);
            }
          } else {
            break;
          }
        }
      } else {
        for (let i2 = index, len = this._regions.length; i2 < len; i2++) {
          const current = this._regions.toRegion(i2);
          if (this._regions.getStartLineNumber(i2) < endLineNumber) {
            if (!filter || filter(current)) {
              result.push(current);
            }
          } else {
            break;
          }
        }
      }
      return result;
    }
  }
  function toggleCollapseState(foldingModel, levels, lineNumbers) {
    const toToggle = [];
    for (const lineNumber of lineNumbers) {
      const region = foldingModel.getRegionAtLine(lineNumber);
      if (region) {
        const doCollapse = !region.isCollapsed;
        toToggle.push(region);
        if (levels > 1) {
          const regionsInside = foldingModel.getRegionsInside(region, (r, level) => r.isCollapsed !== doCollapse && level < levels);
          toToggle.push(...regionsInside);
        }
      }
    }
    foldingModel.toggleCollapseState(toToggle);
  }
  function setCollapseStateLevelsDown(foldingModel, doCollapse, levels = Number.MAX_VALUE, lineNumbers) {
    const toToggle = [];
    if (lineNumbers && lineNumbers.length > 0) {
      for (const lineNumber of lineNumbers) {
        const region = foldingModel.getRegionAtLine(lineNumber);
        if (region) {
          if (region.isCollapsed !== doCollapse) {
            toToggle.push(region);
          }
          if (levels > 1) {
            const regionsInside = foldingModel.getRegionsInside(region, (r, level) => r.isCollapsed !== doCollapse && level < levels);
            toToggle.push(...regionsInside);
          }
        }
      }
    } else {
      const regionsInside = foldingModel.getRegionsInside(null, (r, level) => r.isCollapsed !== doCollapse && level < levels);
      toToggle.push(...regionsInside);
    }
    foldingModel.toggleCollapseState(toToggle);
  }
  function setCollapseStateLevelsUp(foldingModel, doCollapse, levels, lineNumbers) {
    const toToggle = [];
    for (const lineNumber of lineNumbers) {
      const regions = foldingModel.getAllRegionsAtLine(lineNumber, (region, level) => region.isCollapsed !== doCollapse && level <= levels);
      toToggle.push(...regions);
    }
    foldingModel.toggleCollapseState(toToggle);
  }
  function setCollapseStateUp(foldingModel, doCollapse, lineNumbers) {
    const toToggle = [];
    for (const lineNumber of lineNumbers) {
      const regions = foldingModel.getAllRegionsAtLine(lineNumber, (region) => region.isCollapsed !== doCollapse);
      if (regions.length > 0) {
        toToggle.push(regions[0]);
      }
    }
    foldingModel.toggleCollapseState(toToggle);
  }
  function setCollapseStateAtLevel(foldingModel, foldLevel, doCollapse, blockedLineNumbers) {
    const filter = (region, level) => level === foldLevel && region.isCollapsed !== doCollapse && !blockedLineNumbers.some((line) => region.containsLine(line));
    const toToggle = foldingModel.getRegionsInside(null, filter);
    foldingModel.toggleCollapseState(toToggle);
  }
  function setCollapseStateForRest(foldingModel, doCollapse, blockedLineNumbers) {
    const filteredRegions = [];
    for (const lineNumber of blockedLineNumbers) {
      const regions = foldingModel.getAllRegionsAtLine(lineNumber, void 0);
      if (regions.length > 0) {
        filteredRegions.push(regions[0]);
      }
    }
    const filter = (region) => filteredRegions.every((filteredRegion) => !filteredRegion.containedBy(region) && !region.containedBy(filteredRegion)) && region.isCollapsed !== doCollapse;
    const toToggle = foldingModel.getRegionsInside(null, filter);
    foldingModel.toggleCollapseState(toToggle);
  }
  function setCollapseStateForMatchingLines(foldingModel, regExp, doCollapse) {
    const editorModel = foldingModel.textModel;
    const regions = foldingModel.regions;
    const toToggle = [];
    for (let i2 = regions.length - 1; i2 >= 0; i2--) {
      if (doCollapse !== regions.isCollapsed(i2)) {
        const startLineNumber = regions.getStartLineNumber(i2);
        if (regExp.test(editorModel.getLineContent(startLineNumber))) {
          toToggle.push(regions.toRegion(i2));
        }
      }
    }
    foldingModel.toggleCollapseState(toToggle);
  }
  function setCollapseStateForType(foldingModel, type, doCollapse) {
    const regions = foldingModel.regions;
    const toToggle = [];
    for (let i2 = regions.length - 1; i2 >= 0; i2--) {
      if (doCollapse !== regions.isCollapsed(i2) && type === regions.getType(i2)) {
        toToggle.push(regions.toRegion(i2));
      }
    }
    foldingModel.toggleCollapseState(toToggle);
  }
  function getParentFoldLine(lineNumber, foldingModel) {
    let startLineNumber = null;
    const foldingRegion = foldingModel.getRegionAtLine(lineNumber);
    if (foldingRegion !== null) {
      startLineNumber = foldingRegion.startLineNumber;
      if (lineNumber === startLineNumber) {
        const parentFoldingIdx = foldingRegion.parentIndex;
        if (parentFoldingIdx !== -1) {
          startLineNumber = foldingModel.regions.getStartLineNumber(parentFoldingIdx);
        } else {
          startLineNumber = null;
        }
      }
    }
    return startLineNumber;
  }
  function getPreviousFoldLine(lineNumber, foldingModel) {
    let foldingRegion = foldingModel.getRegionAtLine(lineNumber);
    if (foldingRegion !== null && foldingRegion.startLineNumber === lineNumber) {
      if (lineNumber !== foldingRegion.startLineNumber) {
        return foldingRegion.startLineNumber;
      } else {
        const expectedParentIndex = foldingRegion.parentIndex;
        let minLineNumber = 0;
        if (expectedParentIndex !== -1) {
          minLineNumber = foldingModel.regions.getStartLineNumber(foldingRegion.parentIndex);
        }
        while (foldingRegion !== null) {
          if (foldingRegion.regionIndex > 0) {
            foldingRegion = foldingModel.regions.toRegion(foldingRegion.regionIndex - 1);
            if (foldingRegion.startLineNumber <= minLineNumber) {
              return null;
            } else if (foldingRegion.parentIndex === expectedParentIndex) {
              return foldingRegion.startLineNumber;
            }
          } else {
            return null;
          }
        }
      }
    } else {
      if (foldingModel.regions.length > 0) {
        foldingRegion = foldingModel.regions.toRegion(foldingModel.regions.length - 1);
        while (foldingRegion !== null) {
          if (foldingRegion.startLineNumber < lineNumber) {
            return foldingRegion.startLineNumber;
          }
          if (foldingRegion.regionIndex > 0) {
            foldingRegion = foldingModel.regions.toRegion(foldingRegion.regionIndex - 1);
          } else {
            foldingRegion = null;
          }
        }
      }
    }
    return null;
  }
  function getNextFoldLine(lineNumber, foldingModel) {
    let foldingRegion = foldingModel.getRegionAtLine(lineNumber);
    if (foldingRegion !== null && foldingRegion.startLineNumber === lineNumber) {
      const expectedParentIndex = foldingRegion.parentIndex;
      let maxLineNumber = 0;
      if (expectedParentIndex !== -1) {
        maxLineNumber = foldingModel.regions.getEndLineNumber(foldingRegion.parentIndex);
      } else if (foldingModel.regions.length === 0) {
        return null;
      } else {
        maxLineNumber = foldingModel.regions.getEndLineNumber(foldingModel.regions.length - 1);
      }
      while (foldingRegion !== null) {
        if (foldingRegion.regionIndex < foldingModel.regions.length) {
          foldingRegion = foldingModel.regions.toRegion(foldingRegion.regionIndex + 1);
          if (foldingRegion.startLineNumber >= maxLineNumber) {
            return null;
          } else if (foldingRegion.parentIndex === expectedParentIndex) {
            return foldingRegion.startLineNumber;
          }
        } else {
          return null;
        }
      }
    } else {
      if (foldingModel.regions.length > 0) {
        foldingRegion = foldingModel.regions.toRegion(0);
        while (foldingRegion !== null) {
          if (foldingRegion.startLineNumber > lineNumber) {
            return foldingRegion.startLineNumber;
          }
          if (foldingRegion.regionIndex < foldingModel.regions.length) {
            foldingRegion = foldingModel.regions.toRegion(foldingRegion.regionIndex + 1);
          } else {
            foldingRegion = null;
          }
        }
      }
    }
    return null;
  }
  class HiddenRangeModel {
    get onDidChange() {
      return this._updateEventEmitter.event;
    }
    get hiddenRanges() {
      return this._hiddenRanges;
    }
    constructor(model) {
      this._updateEventEmitter = new Emitter$1();
      this._hasLineChanges = false;
      this._foldingModel = model;
      this._foldingModelListener = model.onDidChange((_) => this.updateHiddenRanges());
      this._hiddenRanges = [];
      if (model.regions.length) {
        this.updateHiddenRanges();
      }
    }
    notifyChangeModelContent(e) {
      if (this._hiddenRanges.length && !this._hasLineChanges) {
        this._hasLineChanges = e.changes.some((change) => {
          return change.range.endLineNumber !== change.range.startLineNumber || countEOL(change.text)[0] !== 0;
        });
      }
    }
    updateHiddenRanges() {
      let updateHiddenAreas = false;
      const newHiddenAreas = [];
      let i2 = 0;
      let k = 0;
      let lastCollapsedStart = Number.MAX_VALUE;
      let lastCollapsedEnd = -1;
      const ranges = this._foldingModel.regions;
      for (; i2 < ranges.length; i2++) {
        if (!ranges.isCollapsed(i2)) {
          continue;
        }
        const startLineNumber = ranges.getStartLineNumber(i2) + 1;
        const endLineNumber = ranges.getEndLineNumber(i2);
        if (lastCollapsedStart <= startLineNumber && endLineNumber <= lastCollapsedEnd) {
          continue;
        }
        if (!updateHiddenAreas && k < this._hiddenRanges.length && this._hiddenRanges[k].startLineNumber === startLineNumber && this._hiddenRanges[k].endLineNumber === endLineNumber) {
          newHiddenAreas.push(this._hiddenRanges[k]);
          k++;
        } else {
          updateHiddenAreas = true;
          newHiddenAreas.push(new Range$2(startLineNumber, 1, endLineNumber, 1));
        }
        lastCollapsedStart = startLineNumber;
        lastCollapsedEnd = endLineNumber;
      }
      if (this._hasLineChanges || updateHiddenAreas || k < this._hiddenRanges.length) {
        this.applyHiddenRanges(newHiddenAreas);
      }
    }
    applyHiddenRanges(newHiddenAreas) {
      this._hiddenRanges = newHiddenAreas;
      this._hasLineChanges = false;
      this._updateEventEmitter.fire(newHiddenAreas);
    }
    hasRanges() {
      return this._hiddenRanges.length > 0;
    }
    isHidden(line) {
      return findRange(this._hiddenRanges, line) !== null;
    }
    adjustSelections(selections) {
      let hasChanges = false;
      const editorModel = this._foldingModel.textModel;
      let lastRange = null;
      const adjustLine = (line) => {
        if (!lastRange || !isInside(line, lastRange)) {
          lastRange = findRange(this._hiddenRanges, line);
        }
        if (lastRange) {
          return lastRange.startLineNumber - 1;
        }
        return null;
      };
      for (let i2 = 0, len = selections.length; i2 < len; i2++) {
        let selection = selections[i2];
        const adjustedStartLine = adjustLine(selection.startLineNumber);
        if (adjustedStartLine) {
          selection = selection.setStartPosition(adjustedStartLine, editorModel.getLineMaxColumn(adjustedStartLine));
          hasChanges = true;
        }
        const adjustedEndLine = adjustLine(selection.endLineNumber);
        if (adjustedEndLine) {
          selection = selection.setEndPosition(adjustedEndLine, editorModel.getLineMaxColumn(adjustedEndLine));
          hasChanges = true;
        }
        selections[i2] = selection;
      }
      return hasChanges;
    }
    dispose() {
      if (this.hiddenRanges.length > 0) {
        this._hiddenRanges = [];
        this._updateEventEmitter.fire(this._hiddenRanges);
      }
      if (this._foldingModelListener) {
        this._foldingModelListener.dispose();
        this._foldingModelListener = null;
      }
    }
  }
  function isInside(line, range2) {
    return line >= range2.startLineNumber && line <= range2.endLineNumber;
  }
  function findRange(ranges, line) {
    const i2 = findFirstIdxMonotonousOrArrLen(ranges, (r) => line < r.startLineNumber) - 1;
    if (i2 >= 0 && ranges[i2].endLineNumber >= line) {
      return ranges[i2];
    }
    return null;
  }
  const MAX_FOLDING_REGIONS_FOR_INDENT_DEFAULT = 5e3;
  const ID_INDENT_PROVIDER = "indent";
  class IndentRangeProvider {
    constructor(editorModel, languageConfigurationService, foldingRangesLimit) {
      this.editorModel = editorModel;
      this.languageConfigurationService = languageConfigurationService;
      this.foldingRangesLimit = foldingRangesLimit;
      this.id = ID_INDENT_PROVIDER;
    }
    dispose() {
    }
    compute(cancelationToken) {
      const foldingRules = this.languageConfigurationService.getLanguageConfiguration(this.editorModel.getLanguageId()).foldingRules;
      const offSide = foldingRules && !!foldingRules.offSide;
      const markers = foldingRules && foldingRules.markers;
      return Promise.resolve(computeRanges(this.editorModel, offSide, markers, this.foldingRangesLimit));
    }
  }
  let RangesCollector$1 = class RangesCollector {
    constructor(foldingRangesLimit) {
      this._startIndexes = [];
      this._endIndexes = [];
      this._indentOccurrences = [];
      this._length = 0;
      this._foldingRangesLimit = foldingRangesLimit;
    }
    insertFirst(startLineNumber, endLineNumber, indent) {
      if (startLineNumber > MAX_LINE_NUMBER || endLineNumber > MAX_LINE_NUMBER) {
        return;
      }
      const index = this._length;
      this._startIndexes[index] = startLineNumber;
      this._endIndexes[index] = endLineNumber;
      this._length++;
      if (indent < 1e3) {
        this._indentOccurrences[indent] = (this._indentOccurrences[indent] || 0) + 1;
      }
    }
    toIndentRanges(model) {
      const limit = this._foldingRangesLimit.limit;
      if (this._length <= limit) {
        this._foldingRangesLimit.update(this._length, false);
        const startIndexes = new Uint32Array(this._length);
        const endIndexes = new Uint32Array(this._length);
        for (let i2 = this._length - 1, k = 0; i2 >= 0; i2--, k++) {
          startIndexes[k] = this._startIndexes[i2];
          endIndexes[k] = this._endIndexes[i2];
        }
        return new FoldingRegions(startIndexes, endIndexes);
      } else {
        this._foldingRangesLimit.update(this._length, limit);
        let entries2 = 0;
        let maxIndent = this._indentOccurrences.length;
        for (let i2 = 0; i2 < this._indentOccurrences.length; i2++) {
          const n2 = this._indentOccurrences[i2];
          if (n2) {
            if (n2 + entries2 > limit) {
              maxIndent = i2;
              break;
            }
            entries2 += n2;
          }
        }
        const tabSize = model.getOptions().tabSize;
        const startIndexes = new Uint32Array(limit);
        const endIndexes = new Uint32Array(limit);
        for (let i2 = this._length - 1, k = 0; i2 >= 0; i2--) {
          const startIndex = this._startIndexes[i2];
          const lineContent = model.getLineContent(startIndex);
          const indent = computeIndentLevel(lineContent, tabSize);
          if (indent < maxIndent || indent === maxIndent && entries2++ < limit) {
            startIndexes[k] = startIndex;
            endIndexes[k] = this._endIndexes[i2];
            k++;
          }
        }
        return new FoldingRegions(startIndexes, endIndexes);
      }
    }
  };
  const foldingRangesLimitDefault = {
    limit: MAX_FOLDING_REGIONS_FOR_INDENT_DEFAULT,
    update: () => {
    }
  };
  function computeRanges(model, offSide, markers, foldingRangesLimit = foldingRangesLimitDefault) {
    const tabSize = model.getOptions().tabSize;
    const result = new RangesCollector$1(foldingRangesLimit);
    let pattern = void 0;
    if (markers) {
      pattern = new RegExp(`(${markers.start.source})|(?:${markers.end.source})`);
    }
    const previousRegions = [];
    const line = model.getLineCount() + 1;
    previousRegions.push({ indent: -1, endAbove: line, line });
    for (let line2 = model.getLineCount(); line2 > 0; line2--) {
      const lineContent = model.getLineContent(line2);
      const indent = computeIndentLevel(lineContent, tabSize);
      let previous = previousRegions[previousRegions.length - 1];
      if (indent === -1) {
        if (offSide) {
          previous.endAbove = line2;
        }
        continue;
      }
      let m;
      if (pattern && (m = lineContent.match(pattern))) {
        if (m[1]) {
          let i2 = previousRegions.length - 1;
          while (i2 > 0 && previousRegions[i2].indent !== -2) {
            i2--;
          }
          if (i2 > 0) {
            previousRegions.length = i2 + 1;
            previous = previousRegions[i2];
            result.insertFirst(line2, previous.line, indent);
            previous.line = line2;
            previous.indent = indent;
            previous.endAbove = line2;
            continue;
          }
        } else {
          previousRegions.push({ indent: -2, endAbove: line2, line: line2 });
          continue;
        }
      }
      if (previous.indent > indent) {
        do {
          previousRegions.pop();
          previous = previousRegions[previousRegions.length - 1];
        } while (previous.indent > indent);
        const endLineNumber = previous.endAbove - 1;
        if (endLineNumber - line2 >= 1) {
          result.insertFirst(line2, endLineNumber, indent);
        }
      }
      if (previous.indent === indent) {
        previous.endAbove = line2;
      } else {
        previousRegions.push({ indent, endAbove: line2, line: line2 });
      }
    }
    return result.toIndentRanges(model);
  }
  const foldBackground = registerColor("editor.foldBackground", { light: transparent(editorSelectionBackground, 0.3), dark: transparent(editorSelectionBackground, 0.3), hcDark: null, hcLight: null }, localize(1002, "Background color behind folded ranges. The color must not be opaque so as not to hide underlying decorations."), true);
  registerColor("editor.foldPlaceholderForeground", { light: "#808080", dark: "#808080", hcDark: null, hcLight: null }, localize(1003, "Color of the collapsed text after the first line of a folded range."));
  registerColor("editorGutter.foldingControlForeground", iconForeground, localize(1004, "Color of the folding control in the editor gutter."));
  const foldingExpandedIcon = registerIcon("folding-expanded", Codicon.chevronDown, localize(1005, "Icon for expanded ranges in the editor glyph margin."));
  const foldingCollapsedIcon = registerIcon("folding-collapsed", Codicon.chevronRight, localize(1006, "Icon for collapsed ranges in the editor glyph margin."));
  const foldingManualCollapsedIcon = registerIcon("folding-manual-collapsed", foldingCollapsedIcon, localize(1007, "Icon for manually collapsed ranges in the editor glyph margin."));
  const foldingManualExpandedIcon = registerIcon("folding-manual-expanded", foldingExpandedIcon, localize(1008, "Icon for manually expanded ranges in the editor glyph margin."));
  const foldedBackgroundMinimap = {
    color: themeColorFromId(foldBackground),
    position: 1
    /* MinimapPosition.Inline */
  };
  const collapsed = localize(1009, "Click to expand the range.");
  const expanded = localize(1010, "Click to collapse the range.");
  const _FoldingDecorationProvider = class _FoldingDecorationProvider {
    constructor(editor2) {
      this.editor = editor2;
      this.showFoldingControls = "mouseover";
      this.showFoldingHighlights = true;
    }
    getDecorationOption(isCollapsed, isHidden, isManual) {
      if (isHidden) {
        return _FoldingDecorationProvider.HIDDEN_RANGE_DECORATION;
      }
      if (this.showFoldingControls === "never") {
        if (isCollapsed) {
          return this.showFoldingHighlights ? _FoldingDecorationProvider.NO_CONTROLS_COLLAPSED_HIGHLIGHTED_RANGE_DECORATION : _FoldingDecorationProvider.NO_CONTROLS_COLLAPSED_RANGE_DECORATION;
        }
        return _FoldingDecorationProvider.NO_CONTROLS_EXPANDED_RANGE_DECORATION;
      }
      if (isCollapsed) {
        return isManual ? this.showFoldingHighlights ? _FoldingDecorationProvider.MANUALLY_COLLAPSED_HIGHLIGHTED_VISUAL_DECORATION : _FoldingDecorationProvider.MANUALLY_COLLAPSED_VISUAL_DECORATION : this.showFoldingHighlights ? _FoldingDecorationProvider.COLLAPSED_HIGHLIGHTED_VISUAL_DECORATION : _FoldingDecorationProvider.COLLAPSED_VISUAL_DECORATION;
      } else if (this.showFoldingControls === "mouseover") {
        return isManual ? _FoldingDecorationProvider.MANUALLY_EXPANDED_AUTO_HIDE_VISUAL_DECORATION : _FoldingDecorationProvider.EXPANDED_AUTO_HIDE_VISUAL_DECORATION;
      } else {
        return isManual ? _FoldingDecorationProvider.MANUALLY_EXPANDED_VISUAL_DECORATION : _FoldingDecorationProvider.EXPANDED_VISUAL_DECORATION;
      }
    }
    changeDecorations(callback) {
      return this.editor.changeDecorations(callback);
    }
    removeDecorations(decorationIds) {
      this.editor.removeDecorations(decorationIds);
    }
  };
  _FoldingDecorationProvider.COLLAPSED_VISUAL_DECORATION = ModelDecorationOptions.register({
    description: "folding-collapsed-visual-decoration",
    stickiness: 0,
    afterContentClassName: "inline-folded",
    isWholeLine: true,
    linesDecorationsTooltip: collapsed,
    firstLineDecorationClassName: ThemeIcon.asClassName(foldingCollapsedIcon)
  });
  _FoldingDecorationProvider.COLLAPSED_HIGHLIGHTED_VISUAL_DECORATION = ModelDecorationOptions.register({
    description: "folding-collapsed-highlighted-visual-decoration",
    stickiness: 0,
    afterContentClassName: "inline-folded",
    className: "folded-background",
    minimap: foldedBackgroundMinimap,
    isWholeLine: true,
    linesDecorationsTooltip: collapsed,
    firstLineDecorationClassName: ThemeIcon.asClassName(foldingCollapsedIcon)
  });
  _FoldingDecorationProvider.MANUALLY_COLLAPSED_VISUAL_DECORATION = ModelDecorationOptions.register({
    description: "folding-manually-collapsed-visual-decoration",
    stickiness: 0,
    afterContentClassName: "inline-folded",
    isWholeLine: true,
    linesDecorationsTooltip: collapsed,
    firstLineDecorationClassName: ThemeIcon.asClassName(foldingManualCollapsedIcon)
  });
  _FoldingDecorationProvider.MANUALLY_COLLAPSED_HIGHLIGHTED_VISUAL_DECORATION = ModelDecorationOptions.register({
    description: "folding-manually-collapsed-highlighted-visual-decoration",
    stickiness: 0,
    afterContentClassName: "inline-folded",
    className: "folded-background",
    minimap: foldedBackgroundMinimap,
    isWholeLine: true,
    linesDecorationsTooltip: collapsed,
    firstLineDecorationClassName: ThemeIcon.asClassName(foldingManualCollapsedIcon)
  });
  _FoldingDecorationProvider.NO_CONTROLS_COLLAPSED_RANGE_DECORATION = ModelDecorationOptions.register({
    description: "folding-no-controls-range-decoration",
    stickiness: 0,
    afterContentClassName: "inline-folded",
    isWholeLine: true,
    linesDecorationsTooltip: collapsed
  });
  _FoldingDecorationProvider.NO_CONTROLS_COLLAPSED_HIGHLIGHTED_RANGE_DECORATION = ModelDecorationOptions.register({
    description: "folding-no-controls-range-decoration",
    stickiness: 0,
    afterContentClassName: "inline-folded",
    className: "folded-background",
    minimap: foldedBackgroundMinimap,
    isWholeLine: true,
    linesDecorationsTooltip: collapsed
  });
  _FoldingDecorationProvider.EXPANDED_VISUAL_DECORATION = ModelDecorationOptions.register({
    description: "folding-expanded-visual-decoration",
    stickiness: 1,
    isWholeLine: true,
    firstLineDecorationClassName: "alwaysShowFoldIcons " + ThemeIcon.asClassName(foldingExpandedIcon),
    linesDecorationsTooltip: expanded
  });
  _FoldingDecorationProvider.EXPANDED_AUTO_HIDE_VISUAL_DECORATION = ModelDecorationOptions.register({
    description: "folding-expanded-auto-hide-visual-decoration",
    stickiness: 1,
    isWholeLine: true,
    firstLineDecorationClassName: ThemeIcon.asClassName(foldingExpandedIcon),
    linesDecorationsTooltip: expanded
  });
  _FoldingDecorationProvider.MANUALLY_EXPANDED_VISUAL_DECORATION = ModelDecorationOptions.register({
    description: "folding-manually-expanded-visual-decoration",
    stickiness: 0,
    isWholeLine: true,
    firstLineDecorationClassName: "alwaysShowFoldIcons " + ThemeIcon.asClassName(foldingManualExpandedIcon),
    linesDecorationsTooltip: expanded
  });
  _FoldingDecorationProvider.MANUALLY_EXPANDED_AUTO_HIDE_VISUAL_DECORATION = ModelDecorationOptions.register({
    description: "folding-manually-expanded-auto-hide-visual-decoration",
    stickiness: 0,
    isWholeLine: true,
    firstLineDecorationClassName: ThemeIcon.asClassName(foldingManualExpandedIcon),
    linesDecorationsTooltip: expanded
  });
  _FoldingDecorationProvider.NO_CONTROLS_EXPANDED_RANGE_DECORATION = ModelDecorationOptions.register({
    description: "folding-no-controls-range-decoration",
    stickiness: 0,
    isWholeLine: true
  });
  _FoldingDecorationProvider.HIDDEN_RANGE_DECORATION = ModelDecorationOptions.register({
    description: "folding-hidden-range-decoration",
    stickiness: 1
    /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */
  });
  let FoldingDecorationProvider = _FoldingDecorationProvider;
  const foldingContext = {};
  const ID_SYNTAX_PROVIDER = "syntax";
  class SyntaxRangeProvider {
    constructor(editorModel, providers, handleFoldingRangesChange, foldingRangesLimit, fallbackRangeProvider) {
      this.editorModel = editorModel;
      this.providers = providers;
      this.handleFoldingRangesChange = handleFoldingRangesChange;
      this.foldingRangesLimit = foldingRangesLimit;
      this.fallbackRangeProvider = fallbackRangeProvider;
      this.id = ID_SYNTAX_PROVIDER;
      this.disposables = new DisposableStore();
      if (fallbackRangeProvider) {
        this.disposables.add(fallbackRangeProvider);
      }
      for (const provider of providers) {
        if (typeof provider.onDidChange === "function") {
          this.disposables.add(provider.onDidChange(handleFoldingRangesChange));
        }
      }
    }
    compute(cancellationToken) {
      return collectSyntaxRanges(this.providers, this.editorModel, cancellationToken).then((ranges) => {
        if (this.editorModel.isDisposed()) {
          return null;
        }
        if (ranges) {
          const res = sanitizeRanges(ranges, this.foldingRangesLimit);
          return res;
        }
        return this.fallbackRangeProvider?.compute(cancellationToken) ?? null;
      });
    }
    dispose() {
      this.disposables.dispose();
    }
  }
  function collectSyntaxRanges(providers, model, cancellationToken) {
    let rangeData = null;
    const promises = providers.map((provider, i2) => {
      return Promise.resolve(provider.provideFoldingRanges(model, foldingContext, cancellationToken)).then((ranges) => {
        if (cancellationToken.isCancellationRequested) {
          return;
        }
        if (Array.isArray(ranges)) {
          if (!Array.isArray(rangeData)) {
            rangeData = [];
          }
          const nLines = model.getLineCount();
          for (const r of ranges) {
            if (r.start > 0 && r.end > r.start && r.end <= nLines) {
              rangeData.push({ start: r.start, end: r.end, rank: i2, kind: r.kind });
            }
          }
        }
      }, onUnexpectedExternalError);
    });
    return Promise.all(promises).then((_) => {
      return rangeData;
    });
  }
  class RangesCollector {
    constructor(foldingRangesLimit) {
      this._startIndexes = [];
      this._endIndexes = [];
      this._nestingLevels = [];
      this._nestingLevelCounts = [];
      this._types = [];
      this._length = 0;
      this._foldingRangesLimit = foldingRangesLimit;
    }
    add(startLineNumber, endLineNumber, type, nestingLevel) {
      if (startLineNumber > MAX_LINE_NUMBER || endLineNumber > MAX_LINE_NUMBER) {
        return;
      }
      const index = this._length;
      this._startIndexes[index] = startLineNumber;
      this._endIndexes[index] = endLineNumber;
      this._nestingLevels[index] = nestingLevel;
      this._types[index] = type;
      this._length++;
      if (nestingLevel < 30) {
        this._nestingLevelCounts[nestingLevel] = (this._nestingLevelCounts[nestingLevel] || 0) + 1;
      }
    }
    toIndentRanges() {
      const limit = this._foldingRangesLimit.limit;
      if (this._length <= limit) {
        this._foldingRangesLimit.update(this._length, false);
        const startIndexes = new Uint32Array(this._length);
        const endIndexes = new Uint32Array(this._length);
        for (let i2 = 0; i2 < this._length; i2++) {
          startIndexes[i2] = this._startIndexes[i2];
          endIndexes[i2] = this._endIndexes[i2];
        }
        return new FoldingRegions(startIndexes, endIndexes, this._types);
      } else {
        this._foldingRangesLimit.update(this._length, limit);
        let entries2 = 0;
        let maxLevel = this._nestingLevelCounts.length;
        for (let i2 = 0; i2 < this._nestingLevelCounts.length; i2++) {
          const n2 = this._nestingLevelCounts[i2];
          if (n2) {
            if (n2 + entries2 > limit) {
              maxLevel = i2;
              break;
            }
            entries2 += n2;
          }
        }
        const startIndexes = new Uint32Array(limit);
        const endIndexes = new Uint32Array(limit);
        const types = [];
        for (let i2 = 0, k = 0; i2 < this._length; i2++) {
          const level = this._nestingLevels[i2];
          if (level < maxLevel || level === maxLevel && entries2++ < limit) {
            startIndexes[k] = this._startIndexes[i2];
            endIndexes[k] = this._endIndexes[i2];
            types[k] = this._types[i2];
            k++;
          }
        }
        return new FoldingRegions(startIndexes, endIndexes, types);
      }
    }
  }
  function sanitizeRanges(rangeData, foldingRangesLimit) {
    const sorted = rangeData.sort((d1, d2) => {
      let diff = d1.start - d2.start;
      if (diff === 0) {
        diff = d1.rank - d2.rank;
      }
      return diff;
    });
    const collector = new RangesCollector(foldingRangesLimit);
    let top = void 0;
    const previous = [];
    for (const entry of sorted) {
      if (!top) {
        top = entry;
        collector.add(entry.start, entry.end, entry.kind && entry.kind.value, previous.length);
      } else {
        if (entry.start > top.start) {
          if (entry.end <= top.end) {
            previous.push(top);
            top = entry;
            collector.add(entry.start, entry.end, entry.kind && entry.kind.value, previous.length);
          } else {
            if (entry.start > top.end) {
              do {
                top = previous.pop();
              } while (top && entry.start > top.end);
              if (top) {
                previous.push(top);
              }
              top = entry;
            }
            collector.add(entry.start, entry.end, entry.kind && entry.kind.value, previous.length);
          }
        }
      }
    }
    return collector.toIndentRanges();
  }
  var __decorate$1H = 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$1G = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  var FoldingController_1;
  const CONTEXT_FOLDING_ENABLED = new RawContextKey("foldingEnabled", false);
  let FoldingController = (_Y = class extends Disposable {
    static get(editor2) {
      return editor2.getContribution(FoldingController_1.ID);
    }
    static getFoldingRangeProviders(languageFeaturesService, model) {
      const foldingRangeProviders = languageFeaturesService.foldingRangeProvider.ordered(model);
      return FoldingController_1._foldingRangeSelector?.(foldingRangeProviders, model) ?? foldingRangeProviders;
    }
    constructor(editor2, contextKeyService, languageConfigurationService, notificationService, languageFeatureDebounceService, languageFeaturesService) {
      super();
      this.contextKeyService = contextKeyService;
      this.languageConfigurationService = languageConfigurationService;
      this.languageFeaturesService = languageFeaturesService;
      this.localToDispose = this._register(new DisposableStore());
      this.editor = editor2;
      this._foldingLimitReporter = this._register(new RangesLimitReporter(editor2));
      const options = this.editor.getOptions();
      this._isEnabled = options.get(
        52
        /* EditorOption.folding */
      );
      this._useFoldingProviders = options.get(
        53
        /* EditorOption.foldingStrategy */
      ) !== "indentation";
      this._unfoldOnClickAfterEndOfLine = options.get(
        57
        /* EditorOption.unfoldOnClickAfterEndOfLine */
      );
      this._restoringViewState = false;
      this._currentModelHasFoldedImports = false;
      this._foldingImportsByDefault = options.get(
        55
        /* EditorOption.foldingImportsByDefault */
      );
      this.updateDebounceInfo = languageFeatureDebounceService.for(languageFeaturesService.foldingRangeProvider, "Folding", { min: 200 });
      this.foldingModel = null;
      this.hiddenRangeModel = null;
      this.rangeProvider = null;
      this.foldingRegionPromise = null;
      this.foldingModelPromise = null;
      this.updateScheduler = null;
      this.cursorChangedScheduler = null;
      this.mouseDownInfo = null;
      this.foldingDecorationProvider = new FoldingDecorationProvider(editor2);
      this.foldingDecorationProvider.showFoldingControls = options.get(
        126
        /* EditorOption.showFoldingControls */
      );
      this.foldingDecorationProvider.showFoldingHighlights = options.get(
        54
        /* EditorOption.foldingHighlight */
      );
      this.foldingEnabled = CONTEXT_FOLDING_ENABLED.bindTo(this.contextKeyService);
      this.foldingEnabled.set(this._isEnabled);
      this._register(this.editor.onDidChangeModel(() => this.onModelChanged()));
      this._register(this.editor.onDidChangeConfiguration((e) => {
        if (e.hasChanged(
          52
          /* EditorOption.folding */
        )) {
          this._isEnabled = this.editor.getOptions().get(
            52
            /* EditorOption.folding */
          );
          this.foldingEnabled.set(this._isEnabled);
          this.onModelChanged();
        }
        if (e.hasChanged(
          56
          /* EditorOption.foldingMaximumRegions */
        )) {
          this.onModelChanged();
        }
        if (e.hasChanged(
          126
          /* EditorOption.showFoldingControls */
        ) || e.hasChanged(
          54
          /* EditorOption.foldingHighlight */
        )) {
          const options2 = this.editor.getOptions();
          this.foldingDecorationProvider.showFoldingControls = options2.get(
            126
            /* EditorOption.showFoldingControls */
          );
          this.foldingDecorationProvider.showFoldingHighlights = options2.get(
            54
            /* EditorOption.foldingHighlight */
          );
          this.triggerFoldingModelChanged();
        }
        if (e.hasChanged(
          53
          /* EditorOption.foldingStrategy */
        )) {
          this._useFoldingProviders = this.editor.getOptions().get(
            53
            /* EditorOption.foldingStrategy */
          ) !== "indentation";
          this.onFoldingStrategyChanged();
        }
        if (e.hasChanged(
          57
          /* EditorOption.unfoldOnClickAfterEndOfLine */
        )) {
          this._unfoldOnClickAfterEndOfLine = this.editor.getOptions().get(
            57
            /* EditorOption.unfoldOnClickAfterEndOfLine */
          );
        }
        if (e.hasChanged(
          55
          /* EditorOption.foldingImportsByDefault */
        )) {
          this._foldingImportsByDefault = this.editor.getOptions().get(
            55
            /* EditorOption.foldingImportsByDefault */
          );
        }
      }));
      this.onModelChanged();
    }
    /**
     * Store view state.
     */
    saveViewState() {
      const model = this.editor.getModel();
      if (!model || !this._isEnabled || model.isTooLargeForTokenization()) {
        return {};
      }
      if (this.foldingModel) {
        const collapsedRegions = this.foldingModel.getMemento();
        const provider = this.rangeProvider ? this.rangeProvider.id : void 0;
        return { collapsedRegions, lineCount: model.getLineCount(), provider, foldedImports: this._currentModelHasFoldedImports };
      }
      return void 0;
    }
    /**
     * Restore view state.
     */
    restoreViewState(state) {
      const model = this.editor.getModel();
      if (!model || !this._isEnabled || model.isTooLargeForTokenization() || !this.hiddenRangeModel) {
        return;
      }
      if (!state) {
        return;
      }
      this._currentModelHasFoldedImports = !!state.foldedImports;
      if (state.collapsedRegions && state.collapsedRegions.length > 0 && this.foldingModel) {
        this._restoringViewState = true;
        try {
          this.foldingModel.applyMemento(state.collapsedRegions);
        } finally {
          this._restoringViewState = false;
        }
      }
    }
    onModelChanged() {
      this.localToDispose.clear();
      const model = this.editor.getModel();
      if (!this._isEnabled || !model || model.isTooLargeForTokenization()) {
        return;
      }
      this._currentModelHasFoldedImports = false;
      this.foldingModel = new FoldingModel(model, this.foldingDecorationProvider);
      this.localToDispose.add(this.foldingModel);
      this.hiddenRangeModel = new HiddenRangeModel(this.foldingModel);
      this.localToDispose.add(this.hiddenRangeModel);
      this.localToDispose.add(this.hiddenRangeModel.onDidChange((hr2) => this.onHiddenRangesChanges(hr2)));
      this.updateScheduler = new Delayer(this.updateDebounceInfo.get(model));
      this.localToDispose.add(this.updateScheduler);
      this.cursorChangedScheduler = new RunOnceScheduler(() => this.revealCursor(), 200);
      this.localToDispose.add(this.cursorChangedScheduler);
      this.localToDispose.add(this.languageFeaturesService.foldingRangeProvider.onDidChange(() => this.onFoldingStrategyChanged()));
      this.localToDispose.add(this.editor.onDidChangeModelLanguageConfiguration(() => this.onFoldingStrategyChanged()));
      this.localToDispose.add(this.editor.onDidChangeModelContent((e) => this.onDidChangeModelContent(e)));
      this.localToDispose.add(this.editor.onDidChangeCursorPosition(() => this.onCursorPositionChanged()));
      this.localToDispose.add(this.editor.onMouseDown((e) => this.onEditorMouseDown(e)));
      this.localToDispose.add(this.editor.onMouseUp((e) => this.onEditorMouseUp(e)));
      this.localToDispose.add({
        dispose: () => {
          if (this.foldingRegionPromise) {
            this.foldingRegionPromise.cancel();
            this.foldingRegionPromise = null;
          }
          this.updateScheduler?.cancel();
          this.updateScheduler = null;
          this.foldingModel = null;
          this.foldingModelPromise = null;
          this.hiddenRangeModel = null;
          this.cursorChangedScheduler = null;
          this.rangeProvider?.dispose();
          this.rangeProvider = null;
        }
      });
      this.triggerFoldingModelChanged();
    }
    onFoldingStrategyChanged() {
      this.rangeProvider?.dispose();
      this.rangeProvider = null;
      this.triggerFoldingModelChanged();
    }
    getRangeProvider(editorModel) {
      if (this.rangeProvider) {
        return this.rangeProvider;
      }
      const indentRangeProvider = new IndentRangeProvider(editorModel, this.languageConfigurationService, this._foldingLimitReporter);
      this.rangeProvider = indentRangeProvider;
      if (this._useFoldingProviders && this.foldingModel) {
        const selectedProviders = FoldingController_1.getFoldingRangeProviders(this.languageFeaturesService, editorModel);
        if (selectedProviders.length > 0) {
          this.rangeProvider = new SyntaxRangeProvider(editorModel, selectedProviders, () => this.triggerFoldingModelChanged(), this._foldingLimitReporter, indentRangeProvider);
        }
      }
      return this.rangeProvider;
    }
    getFoldingModel() {
      return this.foldingModelPromise;
    }
    onDidChangeModelContent(e) {
      this.hiddenRangeModel?.notifyChangeModelContent(e);
      this.triggerFoldingModelChanged();
    }
    triggerFoldingModelChanged() {
      if (this.updateScheduler) {
        if (this.foldingRegionPromise) {
          this.foldingRegionPromise.cancel();
          this.foldingRegionPromise = null;
        }
        this.foldingModelPromise = this.updateScheduler.trigger(() => {
          const foldingModel = this.foldingModel;
          if (!foldingModel) {
            return null;
          }
          const sw = new StopWatch();
          const provider = this.getRangeProvider(foldingModel.textModel);
          const foldingRegionPromise = this.foldingRegionPromise = createCancelablePromise((token) => provider.compute(token));
          return foldingRegionPromise.then((foldingRanges) => {
            if (foldingRanges && foldingRegionPromise === this.foldingRegionPromise) {
              let scrollState;
              if (this._foldingImportsByDefault && !this._currentModelHasFoldedImports) {
                const hasChanges = foldingRanges.setCollapsedAllOfType(FoldingRangeKind.Imports.value, true);
                if (hasChanges) {
                  scrollState = StableEditorScrollState.capture(this.editor);
                  this._currentModelHasFoldedImports = hasChanges;
                }
              }
              const selections = this.editor.getSelections();
              foldingModel.update(foldingRanges, toSelectedLines(selections));
              scrollState?.restore(this.editor);
              const newValue = this.updateDebounceInfo.update(foldingModel.textModel, sw.elapsed());
              if (this.updateScheduler) {
                this.updateScheduler.defaultDelay = newValue;
              }
            }
            return foldingModel;
          });
        }).then(void 0, (err) => {
          onUnexpectedError(err);
          return null;
        });
      }
    }
    onHiddenRangesChanges(hiddenRanges) {
      if (this.hiddenRangeModel && hiddenRanges.length && !this._restoringViewState) {
        const selections = this.editor.getSelections();
        if (selections) {
          if (this.hiddenRangeModel.adjustSelections(selections)) {
            this.editor.setSelections(selections);
          }
        }
      }
      this.editor.setHiddenAreas(hiddenRanges, this);
    }
    onCursorPositionChanged() {
      if (this.hiddenRangeModel && this.hiddenRangeModel.hasRanges()) {
        this.cursorChangedScheduler.schedule();
      }
    }
    revealCursor() {
      const foldingModel = this.getFoldingModel();
      if (!foldingModel) {
        return;
      }
      foldingModel.then((foldingModel2) => {
        if (foldingModel2) {
          const selections = this.editor.getSelections();
          if (selections && selections.length > 0) {
            const toToggle = [];
            for (const selection of selections) {
              const lineNumber = selection.selectionStartLineNumber;
              if (this.hiddenRangeModel && this.hiddenRangeModel.isHidden(lineNumber)) {
                toToggle.push(...foldingModel2.getAllRegionsAtLine(lineNumber, (r) => r.isCollapsed && lineNumber > r.startLineNumber));
              }
            }
            if (toToggle.length) {
              foldingModel2.toggleCollapseState(toToggle);
              this.reveal(selections[0].getPosition());
            }
          }
        }
      }).then(void 0, onUnexpectedError);
    }
    onEditorMouseDown(e) {
      this.mouseDownInfo = null;
      if (!this.hiddenRangeModel || !e.target || !e.target.range) {
        return;
      }
      if (!e.event.leftButton && !e.event.middleButton) {
        return;
      }
      const range2 = e.target.range;
      let iconClicked = false;
      switch (e.target.type) {
        case 4: {
          const data = e.target.detail;
          const offsetLeftInGutter = e.target.element.offsetLeft;
          const gutterOffsetX = data.offsetX - offsetLeftInGutter;
          if (gutterOffsetX < 4) {
            return;
          }
          iconClicked = true;
          break;
        }
        case 7: {
          if (this._unfoldOnClickAfterEndOfLine && this.hiddenRangeModel.hasRanges()) {
            const data = e.target.detail;
            if (!data.isAfterLines) {
              break;
            }
          }
          return;
        }
        case 6: {
          if (this.hiddenRangeModel.hasRanges()) {
            const model = this.editor.getModel();
            if (model && range2.startColumn === model.getLineMaxColumn(range2.startLineNumber)) {
              break;
            }
          }
          return;
        }
        default:
          return;
      }
      this.mouseDownInfo = { lineNumber: range2.startLineNumber, iconClicked };
    }
    onEditorMouseUp(e) {
      const foldingModel = this.foldingModel;
      if (!foldingModel || !this.mouseDownInfo || !e.target) {
        return;
      }
      const lineNumber = this.mouseDownInfo.lineNumber;
      const iconClicked = this.mouseDownInfo.iconClicked;
      const range2 = e.target.range;
      if (!range2 || range2.startLineNumber !== lineNumber) {
        return;
      }
      if (iconClicked) {
        if (e.target.type !== 4) {
          return;
        }
      } else {
        const model = this.editor.getModel();
        if (!model || range2.startColumn !== model.getLineMaxColumn(lineNumber)) {
          return;
        }
      }
      const region = foldingModel.getRegionAtLine(lineNumber);
      if (region && region.startLineNumber === lineNumber) {
        const isCollapsed = region.isCollapsed;
        if (iconClicked || isCollapsed) {
          const surrounding = e.event.altKey;
          let toToggle = [];
          if (surrounding) {
            const filter = (otherRegion) => !otherRegion.containedBy(region) && !region.containedBy(otherRegion);
            const toMaybeToggle = foldingModel.getRegionsInside(null, filter);
            for (const r of toMaybeToggle) {
              if (r.isCollapsed) {
                toToggle.push(r);
              }
            }
            if (toToggle.length === 0) {
              toToggle = toMaybeToggle;
            }
          } else {
            const recursive = e.event.middleButton || e.event.shiftKey;
            if (recursive) {
              for (const r of foldingModel.getRegionsInside(region)) {
                if (r.isCollapsed === isCollapsed) {
                  toToggle.push(r);
                }
              }
            }
            if (isCollapsed || !recursive || toToggle.length === 0) {
              toToggle.push(region);
            }
          }
          foldingModel.toggleCollapseState(toToggle);
          this.reveal({ lineNumber, column: 1 });
        }
      }
    }
    reveal(position) {
      this.editor.revealPositionInCenterIfOutsideViewport(
        position,
        0
        /* ScrollType.Smooth */
      );
    }
  }, FoldingController_1 = _Y, _Y.ID = "editor.contrib.folding", _Y);
  FoldingController = FoldingController_1 = __decorate$1H([
    __param$1G(1, IContextKeyService),
    __param$1G(2, ILanguageConfigurationService),
    __param$1G(3, INotificationService),
    __param$1G(4, ILanguageFeatureDebounceService),
    __param$1G(5, ILanguageFeaturesService)
  ], FoldingController);
  class RangesLimitReporter extends Disposable {
    constructor(editor2) {
      super();
      this.editor = editor2;
      this._onDidChange = this._register(new Emitter$1());
      this._computed = 0;
      this._limited = false;
    }
    get limit() {
      return this.editor.getOptions().get(
        56
        /* EditorOption.foldingMaximumRegions */
      );
    }
    update(computed, limited) {
      if (computed !== this._computed || limited !== this._limited) {
        this._computed = computed;
        this._limited = limited;
        this._onDidChange.fire();
      }
    }
  }
  class FoldingAction extends EditorAction {
    runEditorCommand(accessor, editor2, args) {
      const languageConfigurationService = accessor.get(ILanguageConfigurationService);
      const foldingController = FoldingController.get(editor2);
      if (!foldingController) {
        return;
      }
      const foldingModelPromise = foldingController.getFoldingModel();
      if (foldingModelPromise) {
        this.reportTelemetry(accessor, editor2);
        return foldingModelPromise.then((foldingModel) => {
          if (foldingModel) {
            this.invoke(foldingController, foldingModel, editor2, args, languageConfigurationService);
            const selection = editor2.getSelection();
            if (selection) {
              foldingController.reveal(selection.getStartPosition());
            }
          }
        });
      }
    }
    getSelectedLines(editor2) {
      const selections = editor2.getSelections();
      return selections ? selections.map((s) => s.startLineNumber) : [];
    }
    getLineNumbers(args, editor2) {
      if (args && args.selectionLines) {
        return args.selectionLines.map((l) => l + 1);
      }
      return this.getSelectedLines(editor2);
    }
    run(_accessor, _editor) {
    }
  }
  function toSelectedLines(selections) {
    if (!selections || selections.length === 0) {
      return {
        startsInside: () => false
      };
    }
    return {
      startsInside(startLine, endLine) {
        for (const s of selections) {
          const line = s.startLineNumber;
          if (line >= startLine && line <= endLine) {
            return true;
          }
        }
        return false;
      }
    };
  }
  function foldingArgumentsConstraint(args) {
    if (!isUndefined(args)) {
      if (!isObject(args)) {
        return false;
      }
      const foldingArgs = args;
      if (!isUndefined(foldingArgs.levels) && !isNumber$1(foldingArgs.levels)) {
        return false;
      }
      if (!isUndefined(foldingArgs.direction) && !isString$1(foldingArgs.direction)) {
        return false;
      }
      if (!isUndefined(foldingArgs.selectionLines) && (!Array.isArray(foldingArgs.selectionLines) || !foldingArgs.selectionLines.every(isNumber$1))) {
        return false;
      }
    }
    return true;
  }
  class UnfoldAction extends FoldingAction {
    constructor() {
      super({
        id: "editor.unfold",
        label: localize2(982, "Unfold"),
        precondition: CONTEXT_FOLDING_ENABLED,
        kbOpts: {
          kbExpr: EditorContextKeys.editorTextFocus,
          primary: 2048 | 1024 | 94,
          mac: {
            primary: 2048 | 512 | 94
            /* KeyCode.BracketRight */
          },
          weight: 100
          /* KeybindingWeight.EditorContrib */
        },
        metadata: {
          description: "Unfold the content in the editor",
          args: [
            {
              name: "Unfold editor argument",
              description: `Property-value pairs that can be passed through this argument:
						* 'levels': Number of levels to unfold. If not set, defaults to 1.
						* 'direction': If 'up', unfold given number of levels up otherwise unfolds down.
						* 'selectionLines': Array of the start lines (0-based) of the editor selections to apply the unfold action to. If not set, the active selection(s) will be used.
						`,
              constraint: foldingArgumentsConstraint,
              schema: {
                "type": "object",
                "properties": {
                  "levels": {
                    "type": "number",
                    "default": 1
                  },
                  "direction": {
                    "type": "string",
                    "enum": ["up", "down"],
                    "default": "down"
                  },
                  "selectionLines": {
                    "type": "array",
                    "items": {
                      "type": "number"
                    }
                  }
                }
              }
            }
          ]
        }
      });
    }
    invoke(_foldingController, foldingModel, editor2, args) {
      const levels = args && args.levels || 1;
      const lineNumbers = this.getLineNumbers(args, editor2);
      if (args && args.direction === "up") {
        setCollapseStateLevelsUp(foldingModel, false, levels, lineNumbers);
      } else {
        setCollapseStateLevelsDown(foldingModel, false, levels, lineNumbers);
      }
    }
  }
  class UnFoldRecursivelyAction extends FoldingAction {
    constructor() {
      super({
        id: "editor.unfoldRecursively",
        label: localize2(983, "Unfold Recursively"),
        precondition: CONTEXT_FOLDING_ENABLED,
        kbOpts: {
          kbExpr: EditorContextKeys.editorTextFocus,
          primary: KeyChord(
            2048 | 41,
            2048 | 94
            /* KeyCode.BracketRight */
          ),
          weight: 100
          /* KeybindingWeight.EditorContrib */
        }
      });
    }
    invoke(_foldingController, foldingModel, editor2, _args) {
      setCollapseStateLevelsDown(foldingModel, false, Number.MAX_VALUE, this.getSelectedLines(editor2));
    }
  }
  class FoldAction extends FoldingAction {
    constructor() {
      super({
        id: "editor.fold",
        label: localize2(984, "Fold"),
        precondition: CONTEXT_FOLDING_ENABLED,
        kbOpts: {
          kbExpr: EditorContextKeys.editorTextFocus,
          primary: 2048 | 1024 | 92,
          mac: {
            primary: 2048 | 512 | 92
            /* KeyCode.BracketLeft */
          },
          weight: 100
          /* KeybindingWeight.EditorContrib */
        },
        metadata: {
          description: "Fold the content in the editor",
          args: [
            {
              name: "Fold editor argument",
              description: `Property-value pairs that can be passed through this argument:
							* 'levels': Number of levels to fold.
							* 'direction': If 'up', folds given number of levels up otherwise folds down.
							* 'selectionLines': Array of the start lines (0-based) of the editor selections to apply the fold action to. If not set, the active selection(s) will be used.
							If no levels or direction is set, folds the region at the locations or if already collapsed, the first uncollapsed parent instead.
						`,
              constraint: foldingArgumentsConstraint,
              schema: {
                "type": "object",
                "properties": {
                  "levels": {
                    "type": "number"
                  },
                  "direction": {
                    "type": "string",
                    "enum": ["up", "down"]
                  },
                  "selectionLines": {
                    "type": "array",
                    "items": {
                      "type": "number"
                    }
                  }
                }
              }
            }
          ]
        }
      });
    }
    invoke(_foldingController, foldingModel, editor2, args) {
      const lineNumbers = this.getLineNumbers(args, editor2);
      const levels = args && args.levels;
      const direction = args && args.direction;
      if (typeof levels !== "number" && typeof direction !== "string") {
        setCollapseStateUp(foldingModel, true, lineNumbers);
      } else {
        if (direction === "up") {
          setCollapseStateLevelsUp(foldingModel, true, levels || 1, lineNumbers);
        } else {
          setCollapseStateLevelsDown(foldingModel, true, levels || 1, lineNumbers);
        }
      }
    }
  }
  class ToggleFoldAction extends FoldingAction {
    constructor() {
      super({
        id: "editor.toggleFold",
        label: localize2(985, "Toggle Fold"),
        precondition: CONTEXT_FOLDING_ENABLED,
        kbOpts: {
          kbExpr: EditorContextKeys.editorTextFocus,
          primary: KeyChord(
            2048 | 41,
            2048 | 42
            /* KeyCode.KeyL */
          ),
          weight: 100
          /* KeybindingWeight.EditorContrib */
        }
      });
    }
    invoke(_foldingController, foldingModel, editor2) {
      const selectedLines = this.getSelectedLines(editor2);
      toggleCollapseState(foldingModel, 1, selectedLines);
    }
  }
  class FoldRecursivelyAction extends FoldingAction {
    constructor() {
      super({
        id: "editor.foldRecursively",
        label: localize2(986, "Fold Recursively"),
        precondition: CONTEXT_FOLDING_ENABLED,
        kbOpts: {
          kbExpr: EditorContextKeys.editorTextFocus,
          primary: KeyChord(
            2048 | 41,
            2048 | 92
            /* KeyCode.BracketLeft */
          ),
          weight: 100
          /* KeybindingWeight.EditorContrib */
        }
      });
    }
    invoke(_foldingController, foldingModel, editor2) {
      const selectedLines = this.getSelectedLines(editor2);
      setCollapseStateLevelsDown(foldingModel, true, Number.MAX_VALUE, selectedLines);
    }
  }
  class ToggleFoldRecursivelyAction extends FoldingAction {
    constructor() {
      super({
        id: "editor.toggleFoldRecursively",
        label: localize2(987, "Toggle Fold Recursively"),
        precondition: CONTEXT_FOLDING_ENABLED,
        kbOpts: {
          kbExpr: EditorContextKeys.editorTextFocus,
          primary: KeyChord(
            2048 | 41,
            2048 | 1024 | 42
            /* KeyCode.KeyL */
          ),
          weight: 100
          /* KeybindingWeight.EditorContrib */
        }
      });
    }
    invoke(_foldingController, foldingModel, editor2) {
      const selectedLines = this.getSelectedLines(editor2);
      toggleCollapseState(foldingModel, Number.MAX_VALUE, selectedLines);
    }
  }
  class FoldAllBlockCommentsAction extends FoldingAction {
    constructor() {
      super({
        id: "editor.foldAllBlockComments",
        label: localize2(988, "Fold All Block Comments"),
        precondition: CONTEXT_FOLDING_ENABLED,
        kbOpts: {
          kbExpr: EditorContextKeys.editorTextFocus,
          primary: KeyChord(
            2048 | 41,
            2048 | 90
            /* KeyCode.Slash */
          ),
          weight: 100
          /* KeybindingWeight.EditorContrib */
        }
      });
    }
    invoke(_foldingController, foldingModel, editor2, args, languageConfigurationService) {
      if (foldingModel.regions.hasTypes()) {
        setCollapseStateForType(foldingModel, FoldingRangeKind.Comment.value, true);
      } else {
        const editorModel = editor2.getModel();
        if (!editorModel) {
          return;
        }
        const comments = languageConfigurationService.getLanguageConfiguration(editorModel.getLanguageId()).comments;
        if (comments && comments.blockCommentStartToken) {
          const regExp = new RegExp("^\\s*" + escapeRegExpCharacters(comments.blockCommentStartToken));
          setCollapseStateForMatchingLines(foldingModel, regExp, true);
        }
      }
    }
  }
  class FoldAllRegionsAction extends FoldingAction {
    constructor() {
      super({
        id: "editor.foldAllMarkerRegions",
        label: localize2(989, "Fold All Regions"),
        precondition: CONTEXT_FOLDING_ENABLED,
        kbOpts: {
          kbExpr: EditorContextKeys.editorTextFocus,
          primary: KeyChord(
            2048 | 41,
            2048 | 29
            /* KeyCode.Digit8 */
          ),
          weight: 100
          /* KeybindingWeight.EditorContrib */
        }
      });
    }
    invoke(_foldingController, foldingModel, editor2, args, languageConfigurationService) {
      if (foldingModel.regions.hasTypes()) {
        setCollapseStateForType(foldingModel, FoldingRangeKind.Region.value, true);
      } else {
        const editorModel = editor2.getModel();
        if (!editorModel) {
          return;
        }
        const foldingRules = languageConfigurationService.getLanguageConfiguration(editorModel.getLanguageId()).foldingRules;
        if (foldingRules && foldingRules.markers && foldingRules.markers.start) {
          const regExp = new RegExp(foldingRules.markers.start);
          setCollapseStateForMatchingLines(foldingModel, regExp, true);
        }
      }
    }
  }
  class UnfoldAllRegionsAction extends FoldingAction {
    constructor() {
      super({
        id: "editor.unfoldAllMarkerRegions",
        label: localize2(990, "Unfold All Regions"),
        precondition: CONTEXT_FOLDING_ENABLED,
        kbOpts: {
          kbExpr: EditorContextKeys.editorTextFocus,
          primary: KeyChord(
            2048 | 41,
            2048 | 30
            /* KeyCode.Digit9 */
          ),
          weight: 100
          /* KeybindingWeight.EditorContrib */
        }
      });
    }
    invoke(_foldingController, foldingModel, editor2, args, languageConfigurationService) {
      if (foldingModel.regions.hasTypes()) {
        setCollapseStateForType(foldingModel, FoldingRangeKind.Region.value, false);
      } else {
        const editorModel = editor2.getModel();
        if (!editorModel) {
          return;
        }
        const foldingRules = languageConfigurationService.getLanguageConfiguration(editorModel.getLanguageId()).foldingRules;
        if (foldingRules && foldingRules.markers && foldingRules.markers.start) {
          const regExp = new RegExp(foldingRules.markers.start);
          setCollapseStateForMatchingLines(foldingModel, regExp, false);
        }
      }
    }
  }
  class FoldAllExceptAction extends FoldingAction {
    constructor() {
      super({
        id: "editor.foldAllExcept",
        label: localize2(991, "Fold All Except Selected"),
        precondition: CONTEXT_FOLDING_ENABLED,
        kbOpts: {
          kbExpr: EditorContextKeys.editorTextFocus,
          primary: KeyChord(
            2048 | 41,
            2048 | 88
            /* KeyCode.Minus */
          ),
          weight: 100
          /* KeybindingWeight.EditorContrib */
        }
      });
    }
    invoke(_foldingController, foldingModel, editor2) {
      const selectedLines = this.getSelectedLines(editor2);
      setCollapseStateForRest(foldingModel, true, selectedLines);
    }
  }
  class UnfoldAllExceptAction extends FoldingAction {
    constructor() {
      super({
        id: "editor.unfoldAllExcept",
        label: localize2(992, "Unfold All Except Selected"),
        precondition: CONTEXT_FOLDING_ENABLED,
        kbOpts: {
          kbExpr: EditorContextKeys.editorTextFocus,
          primary: KeyChord(
            2048 | 41,
            2048 | 86
            /* KeyCode.Equal */
          ),
          weight: 100
          /* KeybindingWeight.EditorContrib */
        }
      });
    }
    invoke(_foldingController, foldingModel, editor2) {
      const selectedLines = this.getSelectedLines(editor2);
      setCollapseStateForRest(foldingModel, false, selectedLines);
    }
  }
  class FoldAllAction extends FoldingAction {
    constructor() {
      super({
        id: "editor.foldAll",
        label: localize2(993, "Fold All"),
        precondition: CONTEXT_FOLDING_ENABLED,
        kbOpts: {
          kbExpr: EditorContextKeys.editorTextFocus,
          primary: KeyChord(
            2048 | 41,
            2048 | 21
            /* KeyCode.Digit0 */
          ),
          weight: 100
          /* KeybindingWeight.EditorContrib */
        }
      });
    }
    invoke(_foldingController, foldingModel, _editor) {
      setCollapseStateLevelsDown(foldingModel, true);
    }
  }
  class UnfoldAllAction extends FoldingAction {
    constructor() {
      super({
        id: "editor.unfoldAll",
        label: localize2(994, "Unfold All"),
        precondition: CONTEXT_FOLDING_ENABLED,
        kbOpts: {
          kbExpr: EditorContextKeys.editorTextFocus,
          primary: KeyChord(
            2048 | 41,
            2048 | 40
            /* KeyCode.KeyJ */
          ),
          weight: 100
          /* KeybindingWeight.EditorContrib */
        }
      });
    }
    invoke(_foldingController, foldingModel, _editor) {
      setCollapseStateLevelsDown(foldingModel, false);
    }
  }
  const _FoldLevelAction = class _FoldLevelAction extends FoldingAction {
    getFoldingLevel() {
      return parseInt(this.id.substr(_FoldLevelAction.ID_PREFIX.length));
    }
    invoke(_foldingController, foldingModel, editor2) {
      setCollapseStateAtLevel(foldingModel, this.getFoldingLevel(), true, this.getSelectedLines(editor2));
    }
  };
  _FoldLevelAction.ID_PREFIX = "editor.foldLevel";
  _FoldLevelAction.ID = (level) => _FoldLevelAction.ID_PREFIX + level;
  let FoldLevelAction = _FoldLevelAction;
  class GotoParentFoldAction extends FoldingAction {
    constructor() {
      super({
        id: "editor.gotoParentFold",
        label: localize2(995, "Go to Parent Fold"),
        precondition: CONTEXT_FOLDING_ENABLED,
        kbOpts: {
          kbExpr: EditorContextKeys.editorTextFocus,
          weight: 100
          /* KeybindingWeight.EditorContrib */
        }
      });
    }
    invoke(_foldingController, foldingModel, editor2) {
      const selectedLines = this.getSelectedLines(editor2);
      if (selectedLines.length > 0) {
        const startLineNumber = getParentFoldLine(selectedLines[0], foldingModel);
        if (startLineNumber !== null) {
          editor2.setSelection({
            startLineNumber,
            startColumn: 1,
            endLineNumber: startLineNumber,
            endColumn: 1
          });
        }
      }
    }
  }
  class GotoPreviousFoldAction extends FoldingAction {
    constructor() {
      super({
        id: "editor.gotoPreviousFold",
        label: localize2(996, "Go to Previous Folding Range"),
        precondition: CONTEXT_FOLDING_ENABLED,
        kbOpts: {
          kbExpr: EditorContextKeys.editorTextFocus,
          weight: 100
          /* KeybindingWeight.EditorContrib */
        }
      });
    }
    invoke(_foldingController, foldingModel, editor2) {
      const selectedLines = this.getSelectedLines(editor2);
      if (selectedLines.length > 0) {
        const startLineNumber = getPreviousFoldLine(selectedLines[0], foldingModel);
        if (startLineNumber !== null) {
          editor2.setSelection({
            startLineNumber,
            startColumn: 1,
            endLineNumber: startLineNumber,
            endColumn: 1
          });
        }
      }
    }
  }
  class GotoNextFoldAction extends FoldingAction {
    constructor() {
      super({
        id: "editor.gotoNextFold",
        label: localize2(997, "Go to Next Folding Range"),
        precondition: CONTEXT_FOLDING_ENABLED,
        kbOpts: {
          kbExpr: EditorContextKeys.editorTextFocus,
          weight: 100
          /* KeybindingWeight.EditorContrib */
        }
      });
    }
    invoke(_foldingController, foldingModel, editor2) {
      const selectedLines = this.getSelectedLines(editor2);
      if (selectedLines.length > 0) {
        const startLineNumber = getNextFoldLine(selectedLines[0], foldingModel);
        if (startLineNumber !== null) {
          editor2.setSelection({
            startLineNumber,
            startColumn: 1,
            endLineNumber: startLineNumber,
            endColumn: 1
          });
        }
      }
    }
  }
  class FoldRangeFromSelectionAction extends FoldingAction {
    constructor() {
      super({
        id: "editor.createFoldingRangeFromSelection",
        label: localize2(998, "Create Folding Range from Selection"),
        precondition: CONTEXT_FOLDING_ENABLED,
        kbOpts: {
          kbExpr: EditorContextKeys.editorTextFocus,
          primary: KeyChord(
            2048 | 41,
            2048 | 87
            /* KeyCode.Comma */
          ),
          weight: 100
          /* KeybindingWeight.EditorContrib */
        }
      });
    }
    invoke(_foldingController, foldingModel, editor2) {
      const collapseRanges = [];
      const selections = editor2.getSelections();
      if (selections) {
        for (const selection of selections) {
          let endLineNumber = selection.endLineNumber;
          if (selection.endColumn === 1) {
            --endLineNumber;
          }
          if (endLineNumber > selection.startLineNumber) {
            collapseRanges.push({
              startLineNumber: selection.startLineNumber,
              endLineNumber,
              type: void 0,
              isCollapsed: true,
              source: 1
              /* FoldSource.userDefined */
            });
            editor2.setSelection({
              startLineNumber: selection.startLineNumber,
              startColumn: 1,
              endLineNumber: selection.startLineNumber,
              endColumn: 1
            });
          }
        }
        if (collapseRanges.length > 0) {
          collapseRanges.sort((a, b) => {
            return a.startLineNumber - b.startLineNumber;
          });
          const newRanges = FoldingRegions.sanitizeAndMerge(foldingModel.regions, collapseRanges, editor2.getModel()?.getLineCount());
          foldingModel.updatePost(FoldingRegions.fromFoldRanges(newRanges));
        }
      }
    }
  }
  class RemoveFoldRangeFromSelectionAction extends FoldingAction {
    constructor() {
      super({
        id: "editor.removeManualFoldingRanges",
        label: localize2(999, "Remove Manual Folding Ranges"),
        precondition: CONTEXT_FOLDING_ENABLED,
        kbOpts: {
          kbExpr: EditorContextKeys.editorTextFocus,
          primary: KeyChord(
            2048 | 41,
            2048 | 89
            /* KeyCode.Period */
          ),
          weight: 100
          /* KeybindingWeight.EditorContrib */
        }
      });
    }
    invoke(foldingController, foldingModel, editor2) {
      const selections = editor2.getSelections();
      if (selections) {
        const ranges = [];
        for (const selection of selections) {
          const { startLineNumber, endLineNumber } = selection;
          ranges.push(endLineNumber >= startLineNumber ? { startLineNumber, endLineNumber } : { endLineNumber, startLineNumber });
        }
        foldingModel.removeManualRanges(ranges);
        foldingController.triggerFoldingModelChanged();
      }
    }
  }
  class ToggleImportFoldAction extends FoldingAction {
    constructor() {
      super({
        id: "editor.toggleImportFold",
        label: localize2(1e3, "Toggle Import Fold"),
        precondition: CONTEXT_FOLDING_ENABLED,
        kbOpts: {
          kbExpr: EditorContextKeys.editorTextFocus,
          weight: 100
          /* KeybindingWeight.EditorContrib */
        }
      });
    }
    async invoke(foldingController, foldingModel) {
      const regionsToToggle = [];
      const regions = foldingModel.regions;
      for (let i2 = regions.length - 1; i2 >= 0; i2--) {
        if (regions.getType(i2) === FoldingRangeKind.Imports.value) {
          regionsToToggle.push(regions.toRegion(i2));
        }
      }
      foldingModel.toggleCollapseState(regionsToToggle);
      foldingController.triggerFoldingModelChanged();
    }
  }
  registerEditorContribution(
    FoldingController.ID,
    FoldingController,
    0
    /* EditorContributionInstantiation.Eager */
  );
  registerEditorAction(UnfoldAction);
  registerEditorAction(UnFoldRecursivelyAction);
  registerEditorAction(FoldAction);
  registerEditorAction(FoldRecursivelyAction);
  registerEditorAction(ToggleFoldRecursivelyAction);
  registerEditorAction(FoldAllAction);
  registerEditorAction(UnfoldAllAction);
  registerEditorAction(FoldAllBlockCommentsAction);
  registerEditorAction(FoldAllRegionsAction);
  registerEditorAction(UnfoldAllRegionsAction);
  registerEditorAction(FoldAllExceptAction);
  registerEditorAction(UnfoldAllExceptAction);
  registerEditorAction(ToggleFoldAction);
  registerEditorAction(GotoParentFoldAction);
  registerEditorAction(GotoPreviousFoldAction);
  registerEditorAction(GotoNextFoldAction);
  registerEditorAction(FoldRangeFromSelectionAction);
  registerEditorAction(RemoveFoldRangeFromSelectionAction);
  registerEditorAction(ToggleImportFoldAction);
  for (let i2 = 1; i2 <= 7; i2++) {
    registerInstantiatedEditorAction(new FoldLevelAction({
      id: FoldLevelAction.ID(i2),
      label: localize2(1001, "Fold Level {0}", i2),
      precondition: CONTEXT_FOLDING_ENABLED,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: KeyChord(2048 | 41, 2048 | 21 + i2),
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    }));
  }
  CommandsRegistry.registerCommand("_executeFoldingRangeProvider", async function(accessor, ...args) {
    const [resource] = args;
    if (!(resource instanceof URI)) {
      throw illegalArgument();
    }
    const languageFeaturesService = accessor.get(ILanguageFeaturesService);
    const model = accessor.get(IModelService).getModel(resource);
    if (!model) {
      throw illegalArgument();
    }
    const configurationService = accessor.get(IConfigurationService);
    if (!configurationService.getValue("editor.folding", { resource })) {
      return [];
    }
    const languageConfigurationService = accessor.get(ILanguageConfigurationService);
    const strategy = configurationService.getValue("editor.foldingStrategy", { resource });
    const foldingLimitReporter = {
      get limit() {
        return configurationService.getValue("editor.foldingMaximumRegions", { resource });
      },
      update: (computed, limited) => {
      }
    };
    const indentRangeProvider = new IndentRangeProvider(model, languageConfigurationService, foldingLimitReporter);
    let rangeProvider = indentRangeProvider;
    if (strategy !== "indentation") {
      const providers = FoldingController.getFoldingRangeProviders(languageFeaturesService, model);
      if (providers.length) {
        rangeProvider = new SyntaxRangeProvider(model, providers, () => {
        }, foldingLimitReporter, indentRangeProvider);
      }
    }
    const ranges = await rangeProvider.compute(CancellationToken.None);
    const result = [];
    try {
      if (ranges) {
        for (let i2 = 0; i2 < ranges.length; i2++) {
          const type = ranges.getType(i2);
          result.push({ start: ranges.getStartLineNumber(i2), end: ranges.getEndLineNumber(i2), kind: type ? FoldingRangeKind.fromValue(type) : void 0 });
        }
      }
      return result;
    } finally {
      rangeProvider.dispose();
    }
  });
  class EditorFontZoomIn extends EditorAction {
    constructor() {
      super({
        id: "editor.action.fontZoomIn",
        label: localize2(1011, "Increase Editor Font Size"),
        precondition: void 0
      });
    }
    run(accessor, editor2) {
      EditorZoom.setZoomLevel(EditorZoom.getZoomLevel() + 1);
    }
  }
  class EditorFontZoomOut extends EditorAction {
    constructor() {
      super({
        id: "editor.action.fontZoomOut",
        label: localize2(1012, "Decrease Editor Font Size"),
        precondition: void 0
      });
    }
    run(accessor, editor2) {
      EditorZoom.setZoomLevel(EditorZoom.getZoomLevel() - 1);
    }
  }
  class EditorFontZoomReset extends EditorAction {
    constructor() {
      super({
        id: "editor.action.fontZoomReset",
        label: localize2(1013, "Reset Editor Font Size"),
        precondition: void 0
      });
    }
    run(accessor, editor2) {
      EditorZoom.setZoomLevel(0);
    }
  }
  registerEditorAction(EditorFontZoomIn);
  registerEditorAction(EditorFontZoomOut);
  registerEditorAction(EditorFontZoomReset);
  class FormattingEdit {
    static _handleEolEdits(editor2, edits) {
      let newEol = void 0;
      const singleEdits = [];
      for (const edit2 of edits) {
        if (typeof edit2.eol === "number") {
          newEol = edit2.eol;
        }
        if (edit2.range && typeof edit2.text === "string") {
          singleEdits.push(edit2);
        }
      }
      if (typeof newEol === "number") {
        if (editor2.hasModel()) {
          editor2.getModel().pushEOL(newEol);
        }
      }
      return singleEdits;
    }
    static _isFullModelReplaceEdit(editor2, edit2) {
      if (!editor2.hasModel()) {
        return false;
      }
      const model = editor2.getModel();
      const editRange = model.validateRange(edit2.range);
      const fullModelRange = model.getFullModelRange();
      return fullModelRange.equalsRange(editRange);
    }
    static execute(editor2, _edits, addUndoStops) {
      if (addUndoStops) {
        editor2.pushUndoStop();
      }
      const scrollState = StableEditorScrollState.capture(editor2);
      const edits = FormattingEdit._handleEolEdits(editor2, _edits);
      if (edits.length === 1 && FormattingEdit._isFullModelReplaceEdit(editor2, edits[0])) {
        editor2.executeEdits("formatEditsCommand", edits.map((edit2) => EditOperation.replace(Range$2.lift(edit2.range), edit2.text)));
      } else {
        editor2.executeEdits("formatEditsCommand", edits.map((edit2) => EditOperation.replaceMove(Range$2.lift(edit2.range), edit2.text)));
      }
      if (addUndoStops) {
        editor2.pushUndoStop();
      }
      scrollState.restoreRelativeVerticalPositionOfCursor(editor2);
    }
  }
  class ExtensionIdentifier {
    constructor(value) {
      this.value = value;
      this._lower = value.toLowerCase();
    }
    /**
     * Gives the value by which to index (for equality).
     */
    static toKey(id) {
      if (typeof id === "string") {
        return id.toLowerCase();
      }
      return id._lower;
    }
  }
  class ExtensionIdentifierSet {
    constructor(iterable) {
      this._set = /* @__PURE__ */ new Set();
      if (iterable) {
        for (const value of iterable) {
          this.add(value);
        }
      }
    }
    add(id) {
      this._set.add(ExtensionIdentifier.toKey(id));
    }
    has(id) {
      return this._set.has(ExtensionIdentifier.toKey(id));
    }
  }
  function getRealAndSyntheticDocumentFormattersOrdered(documentFormattingEditProvider, documentRangeFormattingEditProvider, model) {
    const result = [];
    const seen = new ExtensionIdentifierSet();
    const docFormatter = documentFormattingEditProvider.ordered(model);
    for (const formatter of docFormatter) {
      result.push(formatter);
      if (formatter.extensionId) {
        seen.add(formatter.extensionId);
      }
    }
    const rangeFormatter = documentRangeFormattingEditProvider.ordered(model);
    for (const formatter of rangeFormatter) {
      if (formatter.extensionId) {
        if (seen.has(formatter.extensionId)) {
          continue;
        }
        seen.add(formatter.extensionId);
      }
      result.push({
        displayName: formatter.displayName,
        extensionId: formatter.extensionId,
        provideDocumentFormattingEdits(model2, options, token) {
          return formatter.provideDocumentRangeFormattingEdits(model2, model2.getFullModelRange(), options, token);
        }
      });
    }
    return result;
  }
  const _FormattingConflicts = class _FormattingConflicts {
    static setFormatterSelector(selector) {
      const remove = _FormattingConflicts._selectors.unshift(selector);
      return { dispose: remove };
    }
    static async select(formatter, document2, mode, kind) {
      if (formatter.length === 0) {
        return void 0;
      }
      const selector = Iterable.first(_FormattingConflicts._selectors);
      if (selector) {
        return await selector(formatter, document2, mode, kind);
      }
      return void 0;
    }
  };
  _FormattingConflicts._selectors = new LinkedList();
  let FormattingConflicts = _FormattingConflicts;
  async function formatDocumentRangesWithSelectedProvider(accessor, editorOrModel, rangeOrRanges, mode, progress, token, userGesture) {
    const instaService = accessor.get(IInstantiationService);
    const { documentRangeFormattingEditProvider: documentRangeFormattingEditProviderRegistry } = accessor.get(ILanguageFeaturesService);
    const model = isCodeEditor(editorOrModel) ? editorOrModel.getModel() : editorOrModel;
    const provider = documentRangeFormattingEditProviderRegistry.ordered(model);
    const selected = await FormattingConflicts.select(
      provider,
      model,
      mode,
      2
      /* FormattingKind.Selection */
    );
    if (selected) {
      progress.report(selected);
      await instaService.invokeFunction(formatDocumentRangesWithProvider, selected, editorOrModel, rangeOrRanges, token, userGesture);
    }
  }
  async function formatDocumentRangesWithProvider(accessor, provider, editorOrModel, rangeOrRanges, token, userGesture) {
    const workerService = accessor.get(IEditorWorkerService);
    const logService = accessor.get(ILogService);
    const accessibilitySignalService = accessor.get(IAccessibilitySignalService);
    let model;
    let cts;
    if (isCodeEditor(editorOrModel)) {
      model = editorOrModel.getModel();
      cts = new EditorStateCancellationTokenSource(editorOrModel, 1 | 4, void 0, token);
    } else {
      model = editorOrModel;
      cts = new TextModelCancellationTokenSource(editorOrModel, token);
    }
    const ranges = [];
    let len = 0;
    for (const range2 of asArray(rangeOrRanges).sort(Range$2.compareRangesUsingStarts)) {
      if (len > 0 && Range$2.areIntersectingOrTouching(ranges[len - 1], range2)) {
        ranges[len - 1] = Range$2.fromPositions(ranges[len - 1].getStartPosition(), range2.getEndPosition());
      } else {
        len = ranges.push(range2);
      }
    }
    const computeEdits = async (range2) => {
      logService.trace(`[format][provideDocumentRangeFormattingEdits] (request)`, provider.extensionId?.value, range2);
      const result = await provider.provideDocumentRangeFormattingEdits(model, range2, model.getFormattingOptions(), cts.token) || [];
      logService.trace(`[format][provideDocumentRangeFormattingEdits] (response)`, provider.extensionId?.value, result);
      return result;
    };
    const hasIntersectingEdit = (a, b) => {
      if (!a.length || !b.length) {
        return false;
      }
      const mergedA = a.reduce((acc, val) => {
        return Range$2.plusRange(acc, val.range);
      }, a[0].range);
      if (!b.some((x) => {
        return Range$2.intersectRanges(mergedA, x.range);
      })) {
        return false;
      }
      for (const edit2 of a) {
        for (const otherEdit of b) {
          if (Range$2.intersectRanges(edit2.range, otherEdit.range)) {
            return true;
          }
        }
      }
      return false;
    };
    const allEdits = [];
    const rawEditsList = [];
    try {
      if (typeof provider.provideDocumentRangesFormattingEdits === "function") {
        logService.trace(`[format][provideDocumentRangeFormattingEdits] (request)`, provider.extensionId?.value, ranges);
        const result = await provider.provideDocumentRangesFormattingEdits(model, ranges, model.getFormattingOptions(), cts.token) || [];
        logService.trace(`[format][provideDocumentRangeFormattingEdits] (response)`, provider.extensionId?.value, result);
        rawEditsList.push(result);
      } else {
        for (const range2 of ranges) {
          if (cts.token.isCancellationRequested) {
            return true;
          }
          rawEditsList.push(await computeEdits(range2));
        }
        for (let i2 = 0; i2 < ranges.length; ++i2) {
          for (let j = i2 + 1; j < ranges.length; ++j) {
            if (cts.token.isCancellationRequested) {
              return true;
            }
            if (hasIntersectingEdit(rawEditsList[i2], rawEditsList[j])) {
              const mergedRange = Range$2.plusRange(ranges[i2], ranges[j]);
              const edits = await computeEdits(mergedRange);
              ranges.splice(j, 1);
              ranges.splice(i2, 1);
              ranges.push(mergedRange);
              rawEditsList.splice(j, 1);
              rawEditsList.splice(i2, 1);
              rawEditsList.push(edits);
              i2 = 0;
              j = 0;
            }
          }
        }
      }
      for (const rawEdits of rawEditsList) {
        if (cts.token.isCancellationRequested) {
          return true;
        }
        const minimalEdits = await workerService.computeMoreMinimalEdits(model.uri, rawEdits);
        if (minimalEdits) {
          allEdits.push(...minimalEdits);
        }
      }
      if (cts.token.isCancellationRequested) {
        return true;
      }
    } finally {
      cts.dispose();
    }
    if (allEdits.length === 0) {
      return false;
    }
    if (isCodeEditor(editorOrModel)) {
      FormattingEdit.execute(editorOrModel, allEdits, true);
      editorOrModel.revealPositionInCenterIfOutsideViewport(
        editorOrModel.getPosition(),
        1
        /* ScrollType.Immediate */
      );
    } else {
      const [{ range: range2 }] = allEdits;
      const initialSelection = new Selection$1(range2.startLineNumber, range2.startColumn, range2.endLineNumber, range2.endColumn);
      model.pushEditOperations([initialSelection], allEdits.map((edit2) => {
        return {
          text: edit2.text,
          range: Range$2.lift(edit2.range),
          forceMoveMarkers: true
        };
      }), (undoEdits) => {
        for (const { range: range3 } of undoEdits) {
          if (Range$2.areIntersectingOrTouching(range3, initialSelection)) {
            return [new Selection$1(range3.startLineNumber, range3.startColumn, range3.endLineNumber, range3.endColumn)];
          }
        }
        return null;
      });
    }
    accessibilitySignalService.playSignal(AccessibilitySignal.format, { userGesture });
    return true;
  }
  async function formatDocumentWithSelectedProvider(accessor, editorOrModel, mode, progress, token, userGesture) {
    const instaService = accessor.get(IInstantiationService);
    const languageFeaturesService = accessor.get(ILanguageFeaturesService);
    const model = isCodeEditor(editorOrModel) ? editorOrModel.getModel() : editorOrModel;
    const provider = getRealAndSyntheticDocumentFormattersOrdered(languageFeaturesService.documentFormattingEditProvider, languageFeaturesService.documentRangeFormattingEditProvider, model);
    const selected = await FormattingConflicts.select(
      provider,
      model,
      mode,
      1
      /* FormattingKind.File */
    );
    if (selected) {
      progress.report(selected);
      await instaService.invokeFunction(formatDocumentWithProvider, selected, editorOrModel, mode, token, userGesture);
    }
  }
  async function formatDocumentWithProvider(accessor, provider, editorOrModel, mode, token, userGesture) {
    const workerService = accessor.get(IEditorWorkerService);
    const accessibilitySignalService = accessor.get(IAccessibilitySignalService);
    let model;
    let cts;
    if (isCodeEditor(editorOrModel)) {
      model = editorOrModel.getModel();
      cts = new EditorStateCancellationTokenSource(editorOrModel, 1 | 4, void 0, token);
    } else {
      model = editorOrModel;
      cts = new TextModelCancellationTokenSource(editorOrModel, token);
    }
    let edits;
    try {
      const rawEdits = await provider.provideDocumentFormattingEdits(model, model.getFormattingOptions(), cts.token);
      edits = await workerService.computeMoreMinimalEdits(model.uri, rawEdits);
      if (cts.token.isCancellationRequested) {
        return true;
      }
    } finally {
      cts.dispose();
    }
    if (!edits || edits.length === 0) {
      return false;
    }
    if (isCodeEditor(editorOrModel)) {
      FormattingEdit.execute(
        editorOrModel,
        edits,
        mode !== 2
        /* FormattingMode.Silent */
      );
      if (mode !== 2) {
        editorOrModel.revealPositionInCenterIfOutsideViewport(
          editorOrModel.getPosition(),
          1
          /* ScrollType.Immediate */
        );
      }
    } else {
      const [{ range: range2 }] = edits;
      const initialSelection = new Selection$1(range2.startLineNumber, range2.startColumn, range2.endLineNumber, range2.endColumn);
      model.pushEditOperations([initialSelection], edits.map((edit2) => {
        return {
          text: edit2.text,
          range: Range$2.lift(edit2.range),
          forceMoveMarkers: true
        };
      }), (undoEdits) => {
        for (const { range: range3 } of undoEdits) {
          if (Range$2.areIntersectingOrTouching(range3, initialSelection)) {
            return [new Selection$1(range3.startLineNumber, range3.startColumn, range3.endLineNumber, range3.endColumn)];
          }
        }
        return null;
      });
    }
    accessibilitySignalService.playSignal(AccessibilitySignal.format, { userGesture });
    return true;
  }
  async function getDocumentRangeFormattingEditsUntilResult(workerService, languageFeaturesService, model, range2, options, token) {
    const providers = languageFeaturesService.documentRangeFormattingEditProvider.ordered(model);
    for (const provider of providers) {
      const rawEdits = await Promise.resolve(provider.provideDocumentRangeFormattingEdits(model, range2, options, token)).catch(onUnexpectedExternalError);
      if (isNonEmptyArray(rawEdits)) {
        return await workerService.computeMoreMinimalEdits(model.uri, rawEdits);
      }
    }
    return void 0;
  }
  async function getDocumentFormattingEditsUntilResult(workerService, languageFeaturesService, model, options, token) {
    const providers = getRealAndSyntheticDocumentFormattersOrdered(languageFeaturesService.documentFormattingEditProvider, languageFeaturesService.documentRangeFormattingEditProvider, model);
    for (const provider of providers) {
      const rawEdits = await Promise.resolve(provider.provideDocumentFormattingEdits(model, options, token)).catch(onUnexpectedExternalError);
      if (isNonEmptyArray(rawEdits)) {
        return await workerService.computeMoreMinimalEdits(model.uri, rawEdits);
      }
    }
    return void 0;
  }
  function getOnTypeFormattingEdits(workerService, languageFeaturesService, model, position, ch, options, token) {
    const providers = languageFeaturesService.onTypeFormattingEditProvider.ordered(model);
    if (providers.length === 0) {
      return Promise.resolve(void 0);
    }
    if (providers[0].autoFormatTriggerCharacters.indexOf(ch) < 0) {
      return Promise.resolve(void 0);
    }
    return Promise.resolve(providers[0].provideOnTypeFormattingEdits(model, position, ch, options, token)).catch(onUnexpectedExternalError).then((edits) => {
      return workerService.computeMoreMinimalEdits(model.uri, edits);
    });
  }
  CommandsRegistry.registerCommand("_executeFormatRangeProvider", async function(accessor, ...args) {
    const [resource, range2, options] = args;
    assertType(URI.isUri(resource));
    assertType(Range$2.isIRange(range2));
    const resolverService = accessor.get(ITextModelService);
    const workerService = accessor.get(IEditorWorkerService);
    const languageFeaturesService = accessor.get(ILanguageFeaturesService);
    const reference = await resolverService.createModelReference(resource);
    try {
      return getDocumentRangeFormattingEditsUntilResult(workerService, languageFeaturesService, reference.object.textEditorModel, Range$2.lift(range2), options, CancellationToken.None);
    } finally {
      reference.dispose();
    }
  });
  CommandsRegistry.registerCommand("_executeFormatDocumentProvider", async function(accessor, ...args) {
    const [resource, options] = args;
    assertType(URI.isUri(resource));
    const resolverService = accessor.get(ITextModelService);
    const workerService = accessor.get(IEditorWorkerService);
    const languageFeaturesService = accessor.get(ILanguageFeaturesService);
    const reference = await resolverService.createModelReference(resource);
    try {
      return getDocumentFormattingEditsUntilResult(workerService, languageFeaturesService, reference.object.textEditorModel, options, CancellationToken.None);
    } finally {
      reference.dispose();
    }
  });
  CommandsRegistry.registerCommand("_executeFormatOnTypeProvider", async function(accessor, ...args) {
    const [resource, position, ch, options] = args;
    assertType(URI.isUri(resource));
    assertType(Position$1.isIPosition(position));
    assertType(typeof ch === "string");
    const resolverService = accessor.get(ITextModelService);
    const workerService = accessor.get(IEditorWorkerService);
    const languageFeaturesService = accessor.get(ILanguageFeaturesService);
    const reference = await resolverService.createModelReference(resource);
    try {
      return getOnTypeFormattingEdits(workerService, languageFeaturesService, reference.object.textEditorModel, Position$1.lift(position), ch, options, CancellationToken.None);
    } finally {
      reference.dispose();
    }
  });
  var __decorate$1G = 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$1F = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  let FormatOnType = (_Z = class {
    constructor(_editor, _languageFeaturesService, _workerService, _accessibilitySignalService) {
      this._editor = _editor;
      this._languageFeaturesService = _languageFeaturesService;
      this._workerService = _workerService;
      this._accessibilitySignalService = _accessibilitySignalService;
      this._disposables = new DisposableStore();
      this._sessionDisposables = new DisposableStore();
      this._disposables.add(_languageFeaturesService.onTypeFormattingEditProvider.onDidChange(this._update, this));
      this._disposables.add(_editor.onDidChangeModel(() => this._update()));
      this._disposables.add(_editor.onDidChangeModelLanguage(() => this._update()));
      this._disposables.add(_editor.onDidChangeConfiguration((e) => {
        if (e.hasChanged(
          65
          /* EditorOption.formatOnType */
        )) {
          this._update();
        }
      }));
      this._update();
    }
    dispose() {
      this._disposables.dispose();
      this._sessionDisposables.dispose();
    }
    _update() {
      this._sessionDisposables.clear();
      if (!this._editor.getOption(
        65
        /* EditorOption.formatOnType */
      )) {
        return;
      }
      if (!this._editor.hasModel()) {
        return;
      }
      const model = this._editor.getModel();
      const [support] = this._languageFeaturesService.onTypeFormattingEditProvider.ordered(model);
      if (!support || !support.autoFormatTriggerCharacters) {
        return;
      }
      const triggerChars = new CharacterSet();
      for (const ch of support.autoFormatTriggerCharacters) {
        triggerChars.add(ch.charCodeAt(0));
      }
      this._sessionDisposables.add(this._editor.onDidType((text2) => {
        const lastCharCode = text2.charCodeAt(text2.length - 1);
        if (triggerChars.has(lastCharCode)) {
          this._trigger(String.fromCharCode(lastCharCode));
        }
      }));
    }
    _trigger(ch) {
      if (!this._editor.hasModel()) {
        return;
      }
      if (this._editor.getSelections().length > 1 || !this._editor.getSelection().isEmpty()) {
        return;
      }
      const model = this._editor.getModel();
      const position = this._editor.getPosition();
      const cts = new CancellationTokenSource$1();
      const unbind = this._editor.onDidChangeModelContent((e) => {
        if (e.isFlush) {
          cts.cancel();
          unbind.dispose();
          return;
        }
        for (let i2 = 0, len = e.changes.length; i2 < len; i2++) {
          const change = e.changes[i2];
          if (change.range.endLineNumber <= position.lineNumber) {
            cts.cancel();
            unbind.dispose();
            return;
          }
        }
      });
      getOnTypeFormattingEdits(this._workerService, this._languageFeaturesService, model, position, ch, model.getFormattingOptions(), cts.token).then((edits) => {
        if (cts.token.isCancellationRequested) {
          return;
        }
        if (isNonEmptyArray(edits)) {
          this._accessibilitySignalService.playSignal(AccessibilitySignal.format, { userGesture: false });
          FormattingEdit.execute(this._editor, edits, true);
        }
      }).finally(() => {
        unbind.dispose();
      });
    }
  }, _Z.ID = "editor.contrib.autoFormat", _Z);
  FormatOnType = __decorate$1G([
    __param$1F(1, ILanguageFeaturesService),
    __param$1F(2, IEditorWorkerService),
    __param$1F(3, IAccessibilitySignalService)
  ], FormatOnType);
  let FormatOnPaste = (__ = class {
    constructor(editor2, _languageFeaturesService, _instantiationService) {
      this.editor = editor2;
      this._languageFeaturesService = _languageFeaturesService;
      this._instantiationService = _instantiationService;
      this._callOnDispose = new DisposableStore();
      this._callOnModel = new DisposableStore();
      this._callOnDispose.add(editor2.onDidChangeConfiguration(() => this._update()));
      this._callOnDispose.add(editor2.onDidChangeModel(() => this._update()));
      this._callOnDispose.add(editor2.onDidChangeModelLanguage(() => this._update()));
      this._callOnDispose.add(_languageFeaturesService.documentRangeFormattingEditProvider.onDidChange(this._update, this));
    }
    dispose() {
      this._callOnDispose.dispose();
      this._callOnModel.dispose();
    }
    _update() {
      this._callOnModel.clear();
      if (!this.editor.getOption(
        64
        /* EditorOption.formatOnPaste */
      )) {
        return;
      }
      if (!this.editor.hasModel()) {
        return;
      }
      if (!this._languageFeaturesService.documentRangeFormattingEditProvider.has(this.editor.getModel())) {
        return;
      }
      this._callOnModel.add(this.editor.onDidPaste(({ range: range2 }) => this._trigger(range2)));
    }
    _trigger(range2) {
      if (!this.editor.hasModel()) {
        return;
      }
      if (this.editor.getSelections().length > 1) {
        return;
      }
      this._instantiationService.invokeFunction(formatDocumentRangesWithSelectedProvider, this.editor, range2, 2, Progress.None, CancellationToken.None, false).catch(onUnexpectedError);
    }
  }, __.ID = "editor.contrib.formatOnPaste", __);
  FormatOnPaste = __decorate$1G([
    __param$1F(1, ILanguageFeaturesService),
    __param$1F(2, IInstantiationService)
  ], FormatOnPaste);
  class FormatDocumentAction extends EditorAction {
    constructor() {
      super({
        id: "editor.action.formatDocument",
        label: localize2(1014, "Format Document"),
        precondition: ContextKeyExpr.and(EditorContextKeys.notInCompositeEditor, EditorContextKeys.writable, EditorContextKeys.hasDocumentFormattingProvider),
        kbOpts: {
          kbExpr: EditorContextKeys.editorTextFocus,
          primary: 1024 | 512 | 36,
          linux: {
            primary: 2048 | 1024 | 39
            /* KeyCode.KeyI */
          },
          weight: 100
          /* KeybindingWeight.EditorContrib */
        },
        contextMenuOpts: {
          group: "1_modification",
          order: 1.3
        }
      });
    }
    async run(accessor, editor2) {
      if (editor2.hasModel()) {
        const instaService = accessor.get(IInstantiationService);
        const progressService = accessor.get(IEditorProgressService);
        await progressService.showWhile(instaService.invokeFunction(formatDocumentWithSelectedProvider, editor2, 1, Progress.None, CancellationToken.None, true), 250);
      }
    }
  }
  class FormatSelectionAction extends EditorAction {
    constructor() {
      super({
        id: "editor.action.formatSelection",
        label: localize2(1015, "Format Selection"),
        precondition: ContextKeyExpr.and(EditorContextKeys.writable, EditorContextKeys.hasDocumentSelectionFormattingProvider),
        kbOpts: {
          kbExpr: EditorContextKeys.editorTextFocus,
          primary: KeyChord(
            2048 | 41,
            2048 | 36
            /* KeyCode.KeyF */
          ),
          weight: 100
          /* KeybindingWeight.EditorContrib */
        },
        contextMenuOpts: {
          when: EditorContextKeys.hasNonEmptySelection,
          group: "1_modification",
          order: 1.31
        }
      });
    }
    async run(accessor, editor2) {
      if (!editor2.hasModel()) {
        return;
      }
      const instaService = accessor.get(IInstantiationService);
      const model = editor2.getModel();
      const ranges = editor2.getSelections().map((range2) => {
        return range2.isEmpty() ? new Range$2(range2.startLineNumber, 1, range2.startLineNumber, model.getLineMaxColumn(range2.startLineNumber)) : range2;
      });
      const progressService = accessor.get(IEditorProgressService);
      await progressService.showWhile(instaService.invokeFunction(formatDocumentRangesWithSelectedProvider, editor2, ranges, 1, Progress.None, CancellationToken.None, true), 250);
    }
  }
  registerEditorContribution(
    FormatOnType.ID,
    FormatOnType,
    2
    /* EditorContributionInstantiation.BeforeFirstInteraction */
  );
  registerEditorContribution(
    FormatOnPaste.ID,
    FormatOnPaste,
    2
    /* EditorContributionInstantiation.BeforeFirstInteraction */
  );
  registerEditorAction(FormatDocumentAction);
  registerEditorAction(FormatSelectionAction);
  CommandsRegistry.registerCommand("editor.action.format", async (accessor) => {
    const editor2 = accessor.get(ICodeEditorService).getFocusedCodeEditor();
    if (!editor2 || !editor2.hasModel()) {
      return;
    }
    const commandService = accessor.get(ICommandService);
    if (editor2.getSelection().isEmpty()) {
      await commandService.executeCommand("editor.action.formatDocument");
    } else {
      await commandService.executeCommand("editor.action.formatSelection");
    }
  });
  var __decorate$1F = 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$1E = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  class TreeElement {
    remove() {
      this.parent?.children.delete(this.id);
    }
    static findId(candidate, container) {
      let candidateId;
      if (typeof candidate === "string") {
        candidateId = `${container.id}/${candidate}`;
      } else {
        candidateId = `${container.id}/${candidate.name}`;
        if (container.children.get(candidateId) !== void 0) {
          candidateId = `${container.id}/${candidate.name}_${candidate.range.startLineNumber}_${candidate.range.startColumn}`;
        }
      }
      let id = candidateId;
      for (let i2 = 0; container.children.get(id) !== void 0; i2++) {
        id = `${candidateId}_${i2}`;
      }
      return id;
    }
    static empty(element) {
      return element.children.size === 0;
    }
  }
  class OutlineElement extends TreeElement {
    constructor(id, parent, symbol) {
      super();
      this.id = id;
      this.parent = parent;
      this.symbol = symbol;
      this.children = /* @__PURE__ */ new Map();
    }
  }
  class OutlineGroup extends TreeElement {
    constructor(id, parent, label, order) {
      super();
      this.id = id;
      this.parent = parent;
      this.label = label;
      this.order = order;
      this.children = /* @__PURE__ */ new Map();
    }
  }
  class OutlineModel extends TreeElement {
    static create(registry, textModel, token) {
      const cts = new CancellationTokenSource$1(token);
      const result = new OutlineModel(textModel.uri);
      const provider = registry.ordered(textModel);
      const promises = provider.map((provider2, index) => {
        const id = TreeElement.findId(`provider_${index}`, result);
        const group = new OutlineGroup(id, result, provider2.displayName ?? "Unknown Outline Provider", index);
        return Promise.resolve(provider2.provideDocumentSymbols(textModel, cts.token)).then((result2) => {
          for (const info of result2 || []) {
            OutlineModel._makeOutlineElement(info, group);
          }
          return group;
        }, (err) => {
          onUnexpectedExternalError(err);
          return group;
        }).then((group2) => {
          if (!TreeElement.empty(group2)) {
            result._groups.set(id, group2);
          } else {
            group2.remove();
          }
        });
      });
      const listener = registry.onDidChange(() => {
        const newProvider = registry.ordered(textModel);
        if (!equals$1(newProvider, provider)) {
          cts.cancel();
        }
      });
      return Promise.all(promises).then(() => {
        if (cts.token.isCancellationRequested && !token.isCancellationRequested) {
          return OutlineModel.create(registry, textModel, token);
        } else {
          return result._compact();
        }
      }).finally(() => {
        cts.dispose();
        listener.dispose();
        cts.dispose();
      });
    }
    static _makeOutlineElement(info, container) {
      const id = TreeElement.findId(info, container);
      const res = new OutlineElement(id, container, info);
      if (info.children) {
        for (const childInfo of info.children) {
          OutlineModel._makeOutlineElement(childInfo, res);
        }
      }
      container.children.set(res.id, res);
    }
    constructor(uri) {
      super();
      this.uri = uri;
      this.id = "root";
      this.parent = void 0;
      this._groups = /* @__PURE__ */ new Map();
      this.children = /* @__PURE__ */ new Map();
      this.id = "root";
      this.parent = void 0;
    }
    _compact() {
      let count = 0;
      for (const [key, group] of this._groups) {
        if (group.children.size === 0) {
          this._groups.delete(key);
        } else {
          count += 1;
        }
      }
      if (count !== 1) {
        this.children = this._groups;
      } else {
        const group = Iterable.first(this._groups.values());
        for (const [, child] of group.children) {
          child.parent = this;
          this.children.set(child.id, child);
        }
      }
      return this;
    }
    getTopLevelSymbols() {
      const roots = [];
      for (const child of this.children.values()) {
        if (child instanceof OutlineElement) {
          roots.push(child.symbol);
        } else {
          roots.push(...Iterable.map(child.children.values(), (child2) => child2.symbol));
        }
      }
      return roots.sort((a, b) => Range$2.compareRangesUsingStarts(a.range, b.range));
    }
    asListOfDocumentSymbols() {
      const roots = this.getTopLevelSymbols();
      const bucket = [];
      OutlineModel._flattenDocumentSymbols(bucket, roots, "");
      return bucket.sort((a, b) => Position$1.compare(Range$2.getStartPosition(a.range), Range$2.getStartPosition(b.range)) || Position$1.compare(Range$2.getEndPosition(b.range), Range$2.getEndPosition(a.range)));
    }
    static _flattenDocumentSymbols(bucket, entries2, overrideContainerLabel) {
      for (const entry of entries2) {
        bucket.push({
          kind: entry.kind,
          tags: entry.tags,
          name: entry.name,
          detail: entry.detail,
          containerName: entry.containerName || overrideContainerLabel,
          range: entry.range,
          selectionRange: entry.selectionRange,
          children: void 0
          // we flatten it...
        });
        if (entry.children) {
          OutlineModel._flattenDocumentSymbols(bucket, entry.children, entry.name);
        }
      }
    }
  }
  const IOutlineModelService = createDecorator("IOutlineModelService");
  let OutlineModelService = class OutlineModelService {
    constructor(_languageFeaturesService, debounces, modelService) {
      this._languageFeaturesService = _languageFeaturesService;
      this._disposables = new DisposableStore();
      this._cache = new LRUCache(15, 0.7);
      this._debounceInformation = debounces.for(_languageFeaturesService.documentSymbolProvider, "DocumentSymbols", { min: 350 });
      this._disposables.add(modelService.onModelRemoved((textModel) => {
        this._cache.delete(textModel.id);
      }));
    }
    dispose() {
      this._disposables.dispose();
    }
    async getOrCreate(textModel, token) {
      const registry = this._languageFeaturesService.documentSymbolProvider;
      const provider = registry.ordered(textModel);
      let data = this._cache.get(textModel.id);
      if (!data || data.versionId !== textModel.getVersionId() || !equals$1(data.provider, provider)) {
        const source = new CancellationTokenSource$1();
        data = {
          versionId: textModel.getVersionId(),
          provider,
          promiseCnt: 0,
          source,
          promise: OutlineModel.create(registry, textModel, source.token),
          model: void 0
        };
        this._cache.set(textModel.id, data);
        const now = Date.now();
        data.promise.then((outlineModel) => {
          data.model = outlineModel;
          this._debounceInformation.update(textModel, Date.now() - now);
        }).catch((_err) => {
          this._cache.delete(textModel.id);
        });
      }
      if (data.model) {
        return data.model;
      }
      data.promiseCnt += 1;
      const listener = token.onCancellationRequested(() => {
        if (--data.promiseCnt === 0) {
          data.source.cancel();
          this._cache.delete(textModel.id);
        }
      });
      try {
        return await data.promise;
      } finally {
        listener.dispose();
      }
    }
  };
  OutlineModelService = __decorate$1F([
    __param$1E(0, ILanguageFeaturesService),
    __param$1E(1, ILanguageFeatureDebounceService),
    __param$1E(2, IModelService)
  ], OutlineModelService);
  registerSingleton(
    IOutlineModelService,
    OutlineModelService,
    1
    /* InstantiationType.Delayed */
  );
  CommandsRegistry.registerCommand("_executeDocumentSymbolProvider", async function(accessor, ...args) {
    const [resource] = args;
    assertType(URI.isUri(resource));
    const outlineService = accessor.get(IOutlineModelService);
    const modelService = accessor.get(ITextModelService);
    const reference = await modelService.createModelReference(resource);
    try {
      return (await outlineService.getOrCreate(reference.object.textEditorModel, CancellationToken.None)).getTopLevelSymbols();
    } finally {
      reference.dispose();
    }
  });
  const AccessibleViewRegistry = new class AccessibleViewRegistry {
    constructor() {
      this._implementations = [];
    }
    register(implementation) {
      this._implementations.push(implementation);
      return {
        dispose: () => {
          const idx = this._implementations.indexOf(implementation);
          if (idx !== -1) {
            this._implementations.splice(idx, 1);
          }
        }
      };
    }
    getImplementations() {
      return this._implementations;
    }
  }();
  var __decorate$1E = 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$1D = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  function hotClassGetOriginalInstance(value) {
    if (value instanceof BaseClass$1) {
      return value._instance;
    }
    return value;
  }
  let BaseClass$1 = class BaseClass {
    constructor(instantiationService) {
      this.instantiationService = instantiationService;
    }
    init(...params) {
    }
  };
  function wrapInHotClass1(clazz) {
    return clazz.get();
  }
  let BaseClass1$1 = class BaseClass1 extends BaseClass$1 {
    constructor(param1, i2) {
      super(i2);
      this.init(param1);
    }
  };
  BaseClass1$1 = __decorate$1E([
    __param$1D(1, IInstantiationService)
  ], BaseClass1$1);
  class ValidatorBase {
    validateOrThrow(content) {
      const result = this.validate(content);
      if (result.error) {
        throw new Error(result.error.message);
      }
      return result.content;
    }
  }
  class TypeofValidator extends ValidatorBase {
    constructor(type) {
      super();
      this.type = type;
    }
    validate(content) {
      if (typeof content !== this.type) {
        return { content: void 0, error: { message: `Expected ${this.type}, but got ${typeof content}` } };
      }
      return { content, error: void 0 };
    }
    getJSONSchema() {
      return { type: this.type };
    }
  }
  const vStringValidator = new TypeofValidator("string");
  function vString() {
    return vStringValidator;
  }
  new TypeofValidator("number");
  const vBooleanValidator = new TypeofValidator("boolean");
  function vBoolean() {
    return vBooleanValidator;
  }
  new TypeofValidator("object");
  class UndefinedValidator extends ValidatorBase {
    validate(content) {
      if (content !== void 0) {
        return { content: void 0, error: { message: `Expected undefined, but got ${typeof content}` } };
      }
      return { content: void 0, error: void 0 };
    }
    getJSONSchema() {
      return {};
    }
  }
  function vUndefined() {
    return new UndefinedValidator();
  }
  class Optional {
    constructor(validator) {
      this.validator = validator;
    }
  }
  function vOptionalProp(validator) {
    return new Optional(validator);
  }
  class ObjValidator extends ValidatorBase {
    constructor(properties) {
      super();
      this.properties = properties;
    }
    validate(content) {
      if (typeof content !== "object" || content === null) {
        return { content: void 0, error: { message: "Expected object" } };
      }
      const result = {};
      for (const key in this.properties) {
        const prop = this.properties[key];
        const fieldValue = content[key];
        const isOptional = prop instanceof Optional;
        const validator = isOptional ? prop.validator : prop;
        if (isOptional && fieldValue === void 0) {
          continue;
        }
        const { content: value, error } = validator.validate(fieldValue);
        if (error) {
          return { content: void 0, error: { message: `Error in property '${key}': ${error.message}` } };
        }
        result[key] = value;
      }
      return { content: result, error: void 0 };
    }
    getJSONSchema() {
      const requiredFields = [];
      const schemaProperties = {};
      for (const [key, prop] of Object.entries(this.properties)) {
        const isOptional = prop instanceof Optional;
        const validator = isOptional ? prop.validator : prop;
        schemaProperties[key] = validator.getJSONSchema();
        if (!isOptional) {
          requiredFields.push(key);
        }
      }
      const schema = {
        type: "object",
        properties: schemaProperties,
        ...requiredFields.length > 0 ? { required: requiredFields } : {}
      };
      return schema;
    }
  }
  function vObj(properties) {
    return new ObjValidator(properties);
  }
  class UnionValidator extends ValidatorBase {
    constructor(validators) {
      super();
      this.validators = validators;
    }
    validate(content) {
      let lastError;
      for (const validator of this.validators) {
        const { content: value, error } = validator.validate(content);
        if (!error) {
          return { content: value, error: void 0 };
        }
        lastError = error;
      }
      return { content: void 0, error: lastError };
    }
    getJSONSchema() {
      return {
        oneOf: mapFilter(this.validators, (validator) => {
          if (validator instanceof UndefinedValidator) {
            return void 0;
          }
          return validator.getJSONSchema();
        })
      };
    }
  }
  function vUnion(...validators) {
    return new UnionValidator(validators);
  }
  class UseRefSchemaValidator extends ValidatorBase {
    constructor(_ref, _validator) {
      super();
      this._ref = _ref;
      this._validator = _validator;
    }
    validate(content) {
      return this._validator.validate(content);
    }
    getJSONSchema() {
      return { $ref: this._ref };
    }
  }
  function vWithJsonSchemaRef(ref, validator) {
    return new UseRefSchemaValidator(ref, validator);
  }
  const Context$2 = {
    Visible: historyNavigationVisible,
    HasFocusedSuggestion: new RawContextKey("suggestWidgetHasFocusedSuggestion", false, localize(1455, "Whether any suggestion is focused")),
    DetailsVisible: new RawContextKey("suggestWidgetDetailsVisible", false, localize(1456, "Whether suggestion details are visible")),
    MultipleSuggestions: new RawContextKey("suggestWidgetMultipleSuggestions", false, localize(1457, "Whether there are multiple suggestions to pick from")),
    MakesTextEdit: new RawContextKey("suggestionMakesTextEdit", true, localize(1458, "Whether inserting the current suggestion yields in a change or has everything already been typed")),
    AcceptSuggestionsOnEnter: new RawContextKey("acceptSuggestionOnEnter", true, localize(1459, "Whether suggestions are inserted when pressing Enter")),
    HasInsertAndReplaceRange: new RawContextKey("suggestionHasInsertAndReplaceRange", false, localize(1460, "Whether the current suggestion has insert and replace behaviour")),
    InsertMode: new RawContextKey("suggestionInsertMode", void 0, { type: "string", description: localize(1461, "Whether the default behaviour is to insert or replace") }),
    CanResolve: new RawContextKey("suggestionCanResolve", false, localize(1462, "Whether the current suggestion supports to resolve further details"))
  };
  const suggestWidgetStatusbarMenu = new MenuId("suggestWidgetStatusBar");
  class CompletionItem {
    constructor(position, completion, container, provider) {
      this.position = position;
      this.completion = completion;
      this.container = container;
      this.provider = provider;
      this.isInvalid = false;
      this.score = FuzzyScore.Default;
      this.distance = 0;
      this.textLabel = typeof completion.label === "string" ? completion.label : completion.label?.label;
      this.labelLow = this.textLabel.toLowerCase();
      this.isInvalid = !this.textLabel;
      this.sortTextLow = completion.sortText && completion.sortText.toLowerCase();
      this.filterTextLow = completion.filterText && completion.filterText.toLowerCase();
      this.extensionId = completion.extensionId;
      if (Range$2.isIRange(completion.range)) {
        this.editStart = new Position$1(completion.range.startLineNumber, completion.range.startColumn);
        this.editInsertEnd = new Position$1(completion.range.endLineNumber, completion.range.endColumn);
        this.editReplaceEnd = new Position$1(completion.range.endLineNumber, completion.range.endColumn);
        this.isInvalid = this.isInvalid || Range$2.spansMultipleLines(completion.range) || completion.range.startLineNumber !== position.lineNumber;
      } else {
        this.editStart = new Position$1(completion.range.insert.startLineNumber, completion.range.insert.startColumn);
        this.editInsertEnd = new Position$1(completion.range.insert.endLineNumber, completion.range.insert.endColumn);
        this.editReplaceEnd = new Position$1(completion.range.replace.endLineNumber, completion.range.replace.endColumn);
        this.isInvalid = this.isInvalid || Range$2.spansMultipleLines(completion.range.insert) || Range$2.spansMultipleLines(completion.range.replace) || completion.range.insert.startLineNumber !== position.lineNumber || completion.range.replace.startLineNumber !== position.lineNumber || completion.range.insert.startColumn !== completion.range.replace.startColumn;
      }
      if (typeof provider.resolveCompletionItem !== "function") {
        this._resolveCache = Promise.resolve();
        this._resolveDuration = 0;
      }
    }
    // ---- resolving
    get isResolved() {
      return this._resolveDuration !== void 0;
    }
    get resolveDuration() {
      return this._resolveDuration !== void 0 ? this._resolveDuration : -1;
    }
    async resolve(token) {
      if (!this._resolveCache) {
        const sub = token.onCancellationRequested(() => {
          this._resolveCache = void 0;
          this._resolveDuration = void 0;
        });
        const sw = new StopWatch(true);
        this._resolveCache = Promise.resolve(this.provider.resolveCompletionItem(this.completion, token)).then((value) => {
          Object.assign(this.completion, value);
          this._resolveDuration = sw.elapsed();
        }, (err) => {
          if (isCancellationError(err)) {
            this._resolveCache = void 0;
            this._resolveDuration = void 0;
          }
        }).finally(() => {
          sub.dispose();
        });
      }
      return this._resolveCache;
    }
  }
  const _CompletionOptions = class _CompletionOptions {
    constructor(snippetSortOrder = 2, kindFilter = /* @__PURE__ */ new Set(), providerFilter = /* @__PURE__ */ new Set(), providerItemsToReuse = /* @__PURE__ */ new Map(), showDeprecated = true) {
      this.snippetSortOrder = snippetSortOrder;
      this.kindFilter = kindFilter;
      this.providerFilter = providerFilter;
      this.providerItemsToReuse = providerItemsToReuse;
      this.showDeprecated = showDeprecated;
    }
  };
  _CompletionOptions.default = new _CompletionOptions();
  let CompletionOptions = _CompletionOptions;
  class CompletionItemModel {
    constructor(items, needsClipboard, durations, disposable) {
      this.items = items;
      this.needsClipboard = needsClipboard;
      this.durations = durations;
      this.disposable = disposable;
    }
  }
  async function provideSuggestionItems(registry, model, position, options = CompletionOptions.default, context = {
    triggerKind: 0
    /* languages.CompletionTriggerKind.Invoke */
  }, token = CancellationToken.None) {
    const sw = new StopWatch();
    position = position.clone();
    const word = model.getWordAtPosition(position);
    const defaultReplaceRange = word ? new Range$2(position.lineNumber, word.startColumn, position.lineNumber, word.endColumn) : Range$2.fromPositions(position);
    const defaultRange = { replace: defaultReplaceRange, insert: defaultReplaceRange.setEndPosition(position.lineNumber, position.column) };
    const result = [];
    const disposables = new DisposableStore();
    const durations = [];
    let needsClipboard = false;
    const onCompletionList = (provider, container, sw2) => {
      let didAddResult = false;
      if (!container) {
        return didAddResult;
      }
      for (const suggestion of container.suggestions) {
        if (!options.kindFilter.has(suggestion.kind)) {
          if (!options.showDeprecated && suggestion?.tags?.includes(
            1
            /* languages.CompletionItemTag.Deprecated */
          )) {
            continue;
          }
          if (!suggestion.range) {
            suggestion.range = defaultRange;
          }
          if (!suggestion.sortText) {
            suggestion.sortText = typeof suggestion.label === "string" ? suggestion.label : suggestion.label.label;
          }
          if (!needsClipboard && suggestion.insertTextRules && suggestion.insertTextRules & 4) {
            needsClipboard = SnippetParser.guessNeedsClipboard(suggestion.insertText);
          }
          result.push(new CompletionItem(position, suggestion, container, provider));
          didAddResult = true;
        }
      }
      if (isDisposable(container)) {
        disposables.add(container);
      }
      durations.push({
        providerName: provider._debugDisplayName ?? "unknown_provider",
        elapsedProvider: container.duration ?? -1,
        elapsedOverall: sw2.elapsed()
      });
      return didAddResult;
    };
    const snippetCompletions = (async () => {
      {
        return;
      }
    })();
    for (const providerGroup of registry.orderedGroups(model)) {
      let didAddResult = false;
      await Promise.all(providerGroup.map(async (provider) => {
        if (options.providerItemsToReuse.has(provider)) {
          const items = options.providerItemsToReuse.get(provider);
          items.forEach((item) => result.push(item));
          didAddResult = didAddResult || items.length > 0;
          return;
        }
        if (options.providerFilter.size > 0 && !options.providerFilter.has(provider)) {
          return;
        }
        try {
          const sw2 = new StopWatch();
          const list2 = await provider.provideCompletionItems(model, position, context, token);
          didAddResult = onCompletionList(provider, list2, sw2) || didAddResult;
        } catch (err) {
          onUnexpectedExternalError(err);
        }
      }));
      if (didAddResult || token.isCancellationRequested) {
        break;
      }
    }
    await snippetCompletions;
    if (token.isCancellationRequested) {
      disposables.dispose();
      return Promise.reject(new CancellationError());
    }
    return new CompletionItemModel(result.sort(getSuggestionComparator(options.snippetSortOrder)), needsClipboard, { entries: durations, elapsed: sw.elapsed() }, disposables);
  }
  function defaultComparator(a, b) {
    if (a.sortTextLow && b.sortTextLow) {
      if (a.sortTextLow < b.sortTextLow) {
        return -1;
      } else if (a.sortTextLow > b.sortTextLow) {
        return 1;
      }
    }
    if (a.textLabel < b.textLabel) {
      return -1;
    } else if (a.textLabel > b.textLabel) {
      return 1;
    }
    return a.completion.kind - b.completion.kind;
  }
  function snippetUpComparator(a, b) {
    if (a.completion.kind !== b.completion.kind) {
      if (a.completion.kind === 28) {
        return -1;
      } else if (b.completion.kind === 28) {
        return 1;
      }
    }
    return defaultComparator(a, b);
  }
  function snippetDownComparator(a, b) {
    if (a.completion.kind !== b.completion.kind) {
      if (a.completion.kind === 28) {
        return 1;
      } else if (b.completion.kind === 28) {
        return -1;
      }
    }
    return defaultComparator(a, b);
  }
  const _snippetComparators = /* @__PURE__ */ new Map();
  _snippetComparators.set(0, snippetUpComparator);
  _snippetComparators.set(2, snippetDownComparator);
  _snippetComparators.set(1, defaultComparator);
  function getSuggestionComparator(snippetConfig) {
    return _snippetComparators.get(snippetConfig);
  }
  CommandsRegistry.registerCommand("_executeCompletionItemProvider", async (accessor, ...args) => {
    const [uri, position, triggerCharacter, maxItemsToResolve] = args;
    assertType(URI.isUri(uri));
    assertType(Position$1.isIPosition(position));
    assertType(typeof triggerCharacter === "string" || !triggerCharacter);
    assertType(typeof maxItemsToResolve === "number" || !maxItemsToResolve);
    const { completionProvider } = accessor.get(ILanguageFeaturesService);
    const ref = await accessor.get(ITextModelService).createModelReference(uri);
    try {
      const result = {
        incomplete: false,
        suggestions: []
      };
      const resolving = [];
      const actualPosition = ref.object.textEditorModel.validatePosition(position);
      const completions = await provideSuggestionItems(completionProvider, ref.object.textEditorModel, actualPosition, void 0, {
        triggerCharacter: triggerCharacter ?? void 0,
        triggerKind: triggerCharacter ? 1 : 0
        /* languages.CompletionTriggerKind.Invoke */
      });
      for (const item of completions.items) {
        if (resolving.length < (maxItemsToResolve ?? 0)) {
          resolving.push(item.resolve(CancellationToken.None));
        }
        result.incomplete = result.incomplete || item.container.incomplete;
        result.suggestions.push(item.completion);
      }
      try {
        await Promise.all(resolving);
        return result;
      } finally {
        setTimeout(() => completions.disposable.dispose(), 100);
      }
    } finally {
      ref.dispose();
    }
  });
  function showSimpleSuggestions(editor2, provider) {
    editor2.getContribution("editor.contrib.suggestController")?.triggerSuggest((/* @__PURE__ */ new Set()).add(provider), void 0, true);
  }
  class QuickSuggestionsOptions {
    static isAllOff(config) {
      return config.other === "off" && config.comments === "off" && config.strings === "off";
    }
    static isAllOn(config) {
      return config.other === "on" && config.comments === "on" && config.strings === "on";
    }
    static valueFor(config, tokenType) {
      switch (tokenType) {
        case 1:
          return config.comments;
        case 2:
          return config.strings;
        default:
          return config.other;
      }
    }
  }
  const _InlineCompletionContextKeys = class _InlineCompletionContextKeys {
  };
  _InlineCompletionContextKeys.inlineSuggestionVisible = new RawContextKey("inlineSuggestionVisible", false, localize(1192, "Whether an inline suggestion is visible"));
  _InlineCompletionContextKeys.inlineSuggestionHasIndentation = new RawContextKey("inlineSuggestionHasIndentation", false, localize(1193, "Whether the inline suggestion starts with whitespace"));
  _InlineCompletionContextKeys.inlineSuggestionHasIndentationLessThanTabSize = new RawContextKey("inlineSuggestionHasIndentationLessThanTabSize", true, localize(1194, "Whether the inline suggestion starts with whitespace that is less than what would be inserted by tab"));
  _InlineCompletionContextKeys.suppressSuggestions = new RawContextKey("inlineSuggestionSuppressSuggestions", void 0, localize(1195, "Whether suggestions should be suppressed for the current suggestion"));
  _InlineCompletionContextKeys.cursorBeforeGhostText = new RawContextKey("cursorBeforeGhostText", false, localize(1196, "Whether the cursor is at ghost text"));
  _InlineCompletionContextKeys.cursorInIndentation = new RawContextKey("cursorInIndentation", false, localize(1197, "Whether the cursor is in indentation"));
  _InlineCompletionContextKeys.hasSelection = new RawContextKey("editor.hasSelection", false, localize(1198, "Whether the editor has a selection"));
  _InlineCompletionContextKeys.cursorAtInlineEdit = new RawContextKey("cursorAtInlineEdit", false, localize(1199, "Whether the cursor is at an inline edit"));
  _InlineCompletionContextKeys.inlineEditVisible = new RawContextKey("inlineEditIsVisible", false, localize(1200, "Whether an inline edit is visible"));
  _InlineCompletionContextKeys.tabShouldJumpToInlineEdit = new RawContextKey("tabShouldJumpToInlineEdit", false, localize(1201, "Whether tab should jump to an inline edit."));
  _InlineCompletionContextKeys.tabShouldAcceptInlineEdit = new RawContextKey("tabShouldAcceptInlineEdit", false, localize(1202, "Whether tab should accept the inline edit."));
  _InlineCompletionContextKeys.inInlineEditsPreviewEditor = new RawContextKey("inInlineEditsPreviewEditor", true, localize(1203, "Whether the current code editor is showing an inline edits preview"));
  let InlineCompletionContextKeys = _InlineCompletionContextKeys;
  class TrimTrailingWhitespaceCommand {
    constructor(selection, cursors, trimInRegexesAndStrings) {
      this._selection = selection;
      this._cursors = cursors;
      this._selectionId = null;
      this._trimInRegexesAndStrings = trimInRegexesAndStrings;
    }
    getEditOperations(model, builder) {
      const ops = trimTrailingWhitespace(model, this._cursors, this._trimInRegexesAndStrings);
      for (let i2 = 0, len = ops.length; i2 < len; i2++) {
        const op = ops[i2];
        builder.addEditOperation(op.range, op.text);
      }
      this._selectionId = builder.trackSelection(this._selection);
    }
    computeCursorState(model, helper) {
      return helper.getTrackedSelection(this._selectionId);
    }
  }
  function trimTrailingWhitespace(model, cursors, trimInRegexesAndStrings) {
    cursors.sort((a, b) => {
      if (a.lineNumber === b.lineNumber) {
        return a.column - b.column;
      }
      return a.lineNumber - b.lineNumber;
    });
    for (let i2 = cursors.length - 2; i2 >= 0; i2--) {
      if (cursors[i2].lineNumber === cursors[i2 + 1].lineNumber) {
        cursors.splice(i2, 1);
      }
    }
    const r = [];
    let rLen = 0;
    let cursorIndex = 0;
    const cursorLen = cursors.length;
    for (let lineNumber = 1, lineCount = model.getLineCount(); lineNumber <= lineCount; lineNumber++) {
      const lineContent = model.getLineContent(lineNumber);
      const maxLineColumn = lineContent.length + 1;
      let minEditColumn = 0;
      if (cursorIndex < cursorLen && cursors[cursorIndex].lineNumber === lineNumber) {
        minEditColumn = cursors[cursorIndex].column;
        cursorIndex++;
        if (minEditColumn === maxLineColumn) {
          continue;
        }
      }
      if (lineContent.length === 0) {
        continue;
      }
      const lastNonWhitespaceIndex$1 = lastNonWhitespaceIndex(lineContent);
      let fromColumn = 0;
      if (lastNonWhitespaceIndex$1 === -1) {
        fromColumn = 1;
      } else if (lastNonWhitespaceIndex$1 !== lineContent.length - 1) {
        fromColumn = lastNonWhitespaceIndex$1 + 2;
      } else {
        continue;
      }
      if (!trimInRegexesAndStrings) {
        if (!model.tokenization.hasAccurateTokensForLine(lineNumber)) {
          continue;
        }
        const lineTokens = model.tokenization.getLineTokens(lineNumber);
        const fromColumnType = lineTokens.getStandardTokenType(lineTokens.findTokenIndexAtOffset(fromColumn));
        if (fromColumnType === 2 || fromColumnType === 3) {
          continue;
        }
      }
      fromColumn = Math.max(minEditColumn, fromColumn);
      r[rLen++] = EditOperation.delete(new Range$2(lineNumber, fromColumn, lineNumber, maxLineColumn));
    }
    return r;
  }
  class CopyLinesCommand {
    constructor(selection, isCopyingDown, noop) {
      this._selection = selection;
      this._isCopyingDown = isCopyingDown;
      this._noop = noop || false;
      this._selectionDirection = 0;
      this._selectionId = null;
      this._startLineNumberDelta = 0;
      this._endLineNumberDelta = 0;
    }
    getEditOperations(model, builder) {
      let s = this._selection;
      this._startLineNumberDelta = 0;
      this._endLineNumberDelta = 0;
      if (s.startLineNumber < s.endLineNumber && s.endColumn === 1) {
        this._endLineNumberDelta = 1;
        s = s.setEndPosition(s.endLineNumber - 1, model.getLineMaxColumn(s.endLineNumber - 1));
      }
      const sourceLines = [];
      for (let i2 = s.startLineNumber; i2 <= s.endLineNumber; i2++) {
        sourceLines.push(model.getLineContent(i2));
      }
      const sourceText = sourceLines.join("\n");
      if (sourceText === "") {
        if (this._isCopyingDown) {
          this._startLineNumberDelta++;
          this._endLineNumberDelta++;
        }
      }
      if (this._noop) {
        builder.addEditOperation(new Range$2(s.endLineNumber, model.getLineMaxColumn(s.endLineNumber), s.endLineNumber + 1, 1), s.endLineNumber === model.getLineCount() ? "" : "\n");
      } else {
        if (!this._isCopyingDown) {
          builder.addEditOperation(new Range$2(s.endLineNumber, model.getLineMaxColumn(s.endLineNumber), s.endLineNumber, model.getLineMaxColumn(s.endLineNumber)), "\n" + sourceText);
        } else {
          builder.addEditOperation(new Range$2(s.startLineNumber, 1, s.startLineNumber, 1), sourceText + "\n");
        }
      }
      this._selectionId = builder.trackSelection(s);
      this._selectionDirection = this._selection.getDirection();
    }
    computeCursorState(model, helper) {
      let result = helper.getTrackedSelection(this._selectionId);
      if (this._startLineNumberDelta !== 0 || this._endLineNumberDelta !== 0) {
        let startLineNumber = result.startLineNumber;
        let startColumn = result.startColumn;
        let endLineNumber = result.endLineNumber;
        let endColumn = result.endColumn;
        if (this._startLineNumberDelta !== 0) {
          startLineNumber = startLineNumber + this._startLineNumberDelta;
          startColumn = 1;
        }
        if (this._endLineNumberDelta !== 0) {
          endLineNumber = endLineNumber + this._endLineNumberDelta;
          endColumn = 1;
        }
        result = Selection$1.createWithDirection(startLineNumber, startColumn, endLineNumber, endColumn, this._selectionDirection);
      }
      return result;
    }
  }
  function getSpaceCnt(str, tabSize) {
    let spacesCnt = 0;
    for (let i2 = 0; i2 < str.length; i2++) {
      if (str.charAt(i2) === "	") {
        spacesCnt += tabSize;
      } else {
        spacesCnt++;
      }
    }
    return spacesCnt;
  }
  function generateIndent(spacesCnt, tabSize, insertSpaces) {
    spacesCnt = spacesCnt < 0 ? 0 : spacesCnt;
    let result = "";
    if (!insertSpaces) {
      const tabsCnt = Math.floor(spacesCnt / tabSize);
      spacesCnt = spacesCnt % tabSize;
      for (let i2 = 0; i2 < tabsCnt; i2++) {
        result += "	";
      }
    }
    for (let i2 = 0; i2 < spacesCnt; i2++) {
      result += " ";
    }
    return result;
  }
  var __decorate$1D = 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$1C = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  let MoveLinesCommand = class MoveLinesCommand {
    constructor(selection, isMovingDown, autoIndent, _languageConfigurationService) {
      this._languageConfigurationService = _languageConfigurationService;
      this._selection = selection;
      this._isMovingDown = isMovingDown;
      this._autoIndent = autoIndent;
      this._selectionId = null;
      this._moveEndLineSelectionShrink = false;
    }
    getEditOperations(model, builder) {
      const getLanguageId = () => {
        return model.getLanguageId();
      };
      const getLanguageIdAtPosition = (lineNumber, column) => {
        return model.getLanguageIdAtPosition(lineNumber, column);
      };
      const modelLineCount = model.getLineCount();
      if (this._isMovingDown && this._selection.endLineNumber === modelLineCount) {
        this._selectionId = builder.trackSelection(this._selection);
        return;
      }
      if (!this._isMovingDown && this._selection.startLineNumber === 1) {
        this._selectionId = builder.trackSelection(this._selection);
        return;
      }
      this._moveEndPositionDown = false;
      let s = this._selection;
      if (s.startLineNumber < s.endLineNumber && s.endColumn === 1) {
        this._moveEndPositionDown = true;
        s = s.setEndPosition(s.endLineNumber - 1, model.getLineMaxColumn(s.endLineNumber - 1));
      }
      const { tabSize, indentSize, insertSpaces } = model.getOptions();
      const indentConverter = this.buildIndentConverter(tabSize, indentSize, insertSpaces);
      if (s.startLineNumber === s.endLineNumber && model.getLineMaxColumn(s.startLineNumber) === 1) {
        const lineNumber = s.startLineNumber;
        const otherLineNumber = this._isMovingDown ? lineNumber + 1 : lineNumber - 1;
        if (model.getLineMaxColumn(otherLineNumber) === 1) {
          builder.addEditOperation(new Range$2(1, 1, 1, 1), null);
        } else {
          builder.addEditOperation(new Range$2(lineNumber, 1, lineNumber, 1), model.getLineContent(otherLineNumber));
          builder.addEditOperation(new Range$2(otherLineNumber, 1, otherLineNumber, model.getLineMaxColumn(otherLineNumber)), null);
        }
        s = new Selection$1(otherLineNumber, 1, otherLineNumber, 1);
      } else {
        let movingLineNumber;
        let movingLineText;
        if (this._isMovingDown) {
          movingLineNumber = s.endLineNumber + 1;
          movingLineText = model.getLineContent(movingLineNumber);
          builder.addEditOperation(new Range$2(movingLineNumber - 1, model.getLineMaxColumn(movingLineNumber - 1), movingLineNumber, model.getLineMaxColumn(movingLineNumber)), null);
          let insertingText = movingLineText;
          if (this.shouldAutoIndent(model, s)) {
            const movingLineMatchResult = this.matchEnterRule(model, indentConverter, tabSize, movingLineNumber, s.startLineNumber - 1);
            if (movingLineMatchResult !== null) {
              const oldIndentation = getLeadingWhitespace(model.getLineContent(movingLineNumber));
              const newSpaceCnt = movingLineMatchResult + getSpaceCnt(oldIndentation, tabSize);
              const newIndentation = generateIndent(newSpaceCnt, tabSize, insertSpaces);
              insertingText = newIndentation + this.trimStart(movingLineText);
            } else {
              const virtualModel = {
                tokenization: {
                  getLineTokens: (lineNumber) => {
                    if (lineNumber === s.startLineNumber) {
                      return model.tokenization.getLineTokens(movingLineNumber);
                    } else {
                      return model.tokenization.getLineTokens(lineNumber);
                    }
                  },
                  getLanguageId,
                  getLanguageIdAtPosition
                },
                getLineContent: (lineNumber) => {
                  if (lineNumber === s.startLineNumber) {
                    return model.getLineContent(movingLineNumber);
                  } else {
                    return model.getLineContent(lineNumber);
                  }
                }
              };
              const indentOfMovingLine = getGoodIndentForLine(this._autoIndent, virtualModel, model.getLanguageIdAtPosition(movingLineNumber, 1), s.startLineNumber, indentConverter, this._languageConfigurationService);
              if (indentOfMovingLine !== null) {
                const oldIndentation = getLeadingWhitespace(model.getLineContent(movingLineNumber));
                const newSpaceCnt = getSpaceCnt(indentOfMovingLine, tabSize);
                const oldSpaceCnt = getSpaceCnt(oldIndentation, tabSize);
                if (newSpaceCnt !== oldSpaceCnt) {
                  const newIndentation = generateIndent(newSpaceCnt, tabSize, insertSpaces);
                  insertingText = newIndentation + this.trimStart(movingLineText);
                }
              }
            }
            builder.addEditOperation(new Range$2(s.startLineNumber, 1, s.startLineNumber, 1), insertingText + "\n");
            const ret = this.matchEnterRuleMovingDown(model, indentConverter, tabSize, s.startLineNumber, movingLineNumber, insertingText);
            if (ret !== null) {
              if (ret !== 0) {
                this.getIndentEditsOfMovingBlock(model, builder, s, tabSize, insertSpaces, ret);
              }
            } else {
              const virtualModel = {
                tokenization: {
                  getLineTokens: (lineNumber) => {
                    if (lineNumber === s.startLineNumber) {
                      return model.tokenization.getLineTokens(movingLineNumber);
                    } else if (lineNumber >= s.startLineNumber + 1 && lineNumber <= s.endLineNumber + 1) {
                      return model.tokenization.getLineTokens(lineNumber - 1);
                    } else {
                      return model.tokenization.getLineTokens(lineNumber);
                    }
                  },
                  getLanguageId,
                  getLanguageIdAtPosition
                },
                getLineContent: (lineNumber) => {
                  if (lineNumber === s.startLineNumber) {
                    return insertingText;
                  } else if (lineNumber >= s.startLineNumber + 1 && lineNumber <= s.endLineNumber + 1) {
                    return model.getLineContent(lineNumber - 1);
                  } else {
                    return model.getLineContent(lineNumber);
                  }
                }
              };
              const newIndentatOfMovingBlock = getGoodIndentForLine(this._autoIndent, virtualModel, model.getLanguageIdAtPosition(movingLineNumber, 1), s.startLineNumber + 1, indentConverter, this._languageConfigurationService);
              if (newIndentatOfMovingBlock !== null) {
                const oldIndentation = getLeadingWhitespace(model.getLineContent(s.startLineNumber));
                const newSpaceCnt = getSpaceCnt(newIndentatOfMovingBlock, tabSize);
                const oldSpaceCnt = getSpaceCnt(oldIndentation, tabSize);
                if (newSpaceCnt !== oldSpaceCnt) {
                  const spaceCntOffset = newSpaceCnt - oldSpaceCnt;
                  this.getIndentEditsOfMovingBlock(model, builder, s, tabSize, insertSpaces, spaceCntOffset);
                }
              }
            }
          } else {
            builder.addEditOperation(new Range$2(s.startLineNumber, 1, s.startLineNumber, 1), insertingText + "\n");
          }
        } else {
          movingLineNumber = s.startLineNumber - 1;
          movingLineText = model.getLineContent(movingLineNumber);
          builder.addEditOperation(new Range$2(movingLineNumber, 1, movingLineNumber + 1, 1), null);
          builder.addEditOperation(new Range$2(s.endLineNumber, model.getLineMaxColumn(s.endLineNumber), s.endLineNumber, model.getLineMaxColumn(s.endLineNumber)), "\n" + movingLineText);
          if (this.shouldAutoIndent(model, s)) {
            const virtualModel = {
              tokenization: {
                getLineTokens: (lineNumber) => {
                  if (lineNumber === movingLineNumber) {
                    return model.tokenization.getLineTokens(s.startLineNumber);
                  } else {
                    return model.tokenization.getLineTokens(lineNumber);
                  }
                },
                getLanguageId,
                getLanguageIdAtPosition
              },
              getLineContent: (lineNumber) => {
                if (lineNumber === movingLineNumber) {
                  return model.getLineContent(s.startLineNumber);
                } else {
                  return model.getLineContent(lineNumber);
                }
              }
            };
            const ret = this.matchEnterRule(model, indentConverter, tabSize, s.startLineNumber, s.startLineNumber - 2);
            if (ret !== null) {
              if (ret !== 0) {
                this.getIndentEditsOfMovingBlock(model, builder, s, tabSize, insertSpaces, ret);
              }
            } else {
              const indentOfFirstLine = getGoodIndentForLine(this._autoIndent, virtualModel, model.getLanguageIdAtPosition(s.startLineNumber, 1), movingLineNumber, indentConverter, this._languageConfigurationService);
              if (indentOfFirstLine !== null) {
                const oldIndent = getLeadingWhitespace(model.getLineContent(s.startLineNumber));
                const newSpaceCnt = getSpaceCnt(indentOfFirstLine, tabSize);
                const oldSpaceCnt = getSpaceCnt(oldIndent, tabSize);
                if (newSpaceCnt !== oldSpaceCnt) {
                  const spaceCntOffset = newSpaceCnt - oldSpaceCnt;
                  this.getIndentEditsOfMovingBlock(model, builder, s, tabSize, insertSpaces, spaceCntOffset);
                }
              }
            }
          }
        }
      }
      this._selectionId = builder.trackSelection(s);
    }
    buildIndentConverter(tabSize, indentSize, insertSpaces) {
      return {
        shiftIndent: (indentation) => {
          return ShiftCommand.shiftIndent(indentation, indentation.length + 1, tabSize, indentSize, insertSpaces);
        },
        unshiftIndent: (indentation) => {
          return ShiftCommand.unshiftIndent(indentation, indentation.length + 1, tabSize, indentSize, insertSpaces);
        }
      };
    }
    parseEnterResult(model, indentConverter, tabSize, line, enter) {
      if (enter) {
        let enterPrefix = enter.indentation;
        if (enter.indentAction === IndentAction$1.None) {
          enterPrefix = enter.indentation + enter.appendText;
        } else if (enter.indentAction === IndentAction$1.Indent) {
          enterPrefix = enter.indentation + enter.appendText;
        } else if (enter.indentAction === IndentAction$1.IndentOutdent) {
          enterPrefix = enter.indentation;
        } else if (enter.indentAction === IndentAction$1.Outdent) {
          enterPrefix = indentConverter.unshiftIndent(enter.indentation) + enter.appendText;
        }
        const movingLineText = model.getLineContent(line);
        if (this.trimStart(movingLineText).indexOf(this.trimStart(enterPrefix)) >= 0) {
          const oldIndentation = getLeadingWhitespace(model.getLineContent(line));
          let newIndentation = getLeadingWhitespace(enterPrefix);
          const indentMetadataOfMovelingLine = getIndentMetadata(model, line, this._languageConfigurationService);
          if (indentMetadataOfMovelingLine !== null && indentMetadataOfMovelingLine & 2) {
            newIndentation = indentConverter.unshiftIndent(newIndentation);
          }
          const newSpaceCnt = getSpaceCnt(newIndentation, tabSize);
          const oldSpaceCnt = getSpaceCnt(oldIndentation, tabSize);
          return newSpaceCnt - oldSpaceCnt;
        }
      }
      return null;
    }
    /**
     *
     * @param model
     * @param indentConverter
     * @param tabSize
     * @param line the line moving down
     * @param futureAboveLineNumber the line which will be at the `line` position
     * @param futureAboveLineText
     */
    matchEnterRuleMovingDown(model, indentConverter, tabSize, line, futureAboveLineNumber, futureAboveLineText) {
      if (lastNonWhitespaceIndex(futureAboveLineText) >= 0) {
        const maxColumn = model.getLineMaxColumn(futureAboveLineNumber);
        const enter = getEnterAction(this._autoIndent, model, new Range$2(futureAboveLineNumber, maxColumn, futureAboveLineNumber, maxColumn), this._languageConfigurationService);
        return this.parseEnterResult(model, indentConverter, tabSize, line, enter);
      } else {
        let validPrecedingLine = line - 1;
        while (validPrecedingLine >= 1) {
          const lineContent = model.getLineContent(validPrecedingLine);
          const nonWhitespaceIdx = lastNonWhitespaceIndex(lineContent);
          if (nonWhitespaceIdx >= 0) {
            break;
          }
          validPrecedingLine--;
        }
        if (validPrecedingLine < 1 || line > model.getLineCount()) {
          return null;
        }
        const maxColumn = model.getLineMaxColumn(validPrecedingLine);
        const enter = getEnterAction(this._autoIndent, model, new Range$2(validPrecedingLine, maxColumn, validPrecedingLine, maxColumn), this._languageConfigurationService);
        return this.parseEnterResult(model, indentConverter, tabSize, line, enter);
      }
    }
    matchEnterRule(model, indentConverter, tabSize, line, oneLineAbove, previousLineText) {
      let validPrecedingLine = oneLineAbove;
      while (validPrecedingLine >= 1) {
        let lineContent;
        if (validPrecedingLine === oneLineAbove && previousLineText !== void 0) {
          lineContent = previousLineText;
        } else {
          lineContent = model.getLineContent(validPrecedingLine);
        }
        const nonWhitespaceIdx = lastNonWhitespaceIndex(lineContent);
        if (nonWhitespaceIdx >= 0) {
          break;
        }
        validPrecedingLine--;
      }
      if (validPrecedingLine < 1 || line > model.getLineCount()) {
        return null;
      }
      const maxColumn = model.getLineMaxColumn(validPrecedingLine);
      const enter = getEnterAction(this._autoIndent, model, new Range$2(validPrecedingLine, maxColumn, validPrecedingLine, maxColumn), this._languageConfigurationService);
      return this.parseEnterResult(model, indentConverter, tabSize, line, enter);
    }
    trimStart(str) {
      return str.replace(/^\s+/, "");
    }
    shouldAutoIndent(model, selection) {
      if (this._autoIndent < 4) {
        return false;
      }
      if (!model.tokenization.isCheapToTokenize(selection.startLineNumber)) {
        return false;
      }
      const languageAtSelectionStart = model.getLanguageIdAtPosition(selection.startLineNumber, 1);
      const languageAtSelectionEnd = model.getLanguageIdAtPosition(selection.endLineNumber, 1);
      if (languageAtSelectionStart !== languageAtSelectionEnd) {
        return false;
      }
      if (this._languageConfigurationService.getLanguageConfiguration(languageAtSelectionStart).indentRulesSupport === null) {
        return false;
      }
      return true;
    }
    getIndentEditsOfMovingBlock(model, builder, s, tabSize, insertSpaces, offset) {
      for (let i2 = s.startLineNumber; i2 <= s.endLineNumber; i2++) {
        const lineContent = model.getLineContent(i2);
        const originalIndent = getLeadingWhitespace(lineContent);
        const originalSpacesCnt = getSpaceCnt(originalIndent, tabSize);
        const newSpacesCnt = originalSpacesCnt + offset;
        const newIndent = generateIndent(newSpacesCnt, tabSize, insertSpaces);
        if (newIndent !== originalIndent) {
          builder.addEditOperation(new Range$2(i2, 1, i2, originalIndent.length + 1), newIndent);
          if (i2 === s.endLineNumber && s.endColumn <= originalIndent.length + 1 && newIndent === "") {
            this._moveEndLineSelectionShrink = true;
          }
        }
      }
    }
    computeCursorState(model, helper) {
      let result = helper.getTrackedSelection(this._selectionId);
      if (this._moveEndPositionDown) {
        result = result.setEndPosition(result.endLineNumber + 1, 1);
      }
      if (this._moveEndLineSelectionShrink && result.startLineNumber < result.endLineNumber) {
        result = result.setEndPosition(result.endLineNumber, 2);
      }
      return result;
    }
  };
  MoveLinesCommand = __decorate$1D([
    __param$1C(3, ILanguageConfigurationService)
  ], MoveLinesCommand);
  const _SortLinesCommand = class _SortLinesCommand {
    constructor(selection, descending) {
      this.selection = selection;
      this.descending = descending;
      this.selectionId = null;
    }
    getEditOperations(model, builder) {
      const op = sortLines(model, this.selection, this.descending);
      if (op) {
        builder.addEditOperation(op.range, op.text);
      }
      this.selectionId = builder.trackSelection(this.selection);
    }
    computeCursorState(model, helper) {
      return helper.getTrackedSelection(this.selectionId);
    }
    static canRun(model, selection, descending) {
      if (model === null) {
        return false;
      }
      const data = getSortData(model, selection, descending);
      if (!data) {
        return false;
      }
      for (let i2 = 0, len = data.before.length; i2 < len; i2++) {
        if (data.before[i2] !== data.after[i2]) {
          return true;
        }
      }
      return false;
    }
  };
  _SortLinesCommand._COLLATOR = safeIntl.Collator();
  let SortLinesCommand = _SortLinesCommand;
  function getSortData(model, selection, descending) {
    const startLineNumber = selection.startLineNumber;
    let endLineNumber = selection.endLineNumber;
    if (selection.endColumn === 1) {
      endLineNumber--;
    }
    if (startLineNumber >= endLineNumber) {
      return null;
    }
    const linesToSort = [];
    for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
      linesToSort.push(model.getLineContent(lineNumber));
    }
    let sorted = linesToSort.slice(0);
    sorted.sort(SortLinesCommand._COLLATOR.value.compare);
    if (descending === true) {
      sorted = sorted.reverse();
    }
    return {
      startLineNumber,
      endLineNumber,
      before: linesToSort,
      after: sorted
    };
  }
  function sortLines(model, selection, descending) {
    const data = getSortData(model, selection, descending);
    if (!data) {
      return null;
    }
    return EditOperation.replace(new Range$2(data.startLineNumber, 1, data.endLineNumber, model.getLineMaxColumn(data.endLineNumber)), data.after.join("\n"));
  }
  class AbstractCopyLinesAction extends EditorAction {
    constructor(down, opts) {
      super(opts);
      this.down = down;
    }
    run(_accessor, editor2) {
      if (!editor2.hasModel()) {
        return;
      }
      const selections = editor2.getSelections().map((selection, index) => ({ selection, index, ignore: false }));
      selections.sort((a, b) => Range$2.compareRangesUsingStarts(a.selection, b.selection));
      let prev = selections[0];
      for (let i2 = 1; i2 < selections.length; i2++) {
        const curr = selections[i2];
        if (prev.selection.endLineNumber === curr.selection.startLineNumber) {
          if (prev.index < curr.index) {
            curr.ignore = true;
          } else {
            prev.ignore = true;
            prev = curr;
          }
        }
      }
      const commands = [];
      for (const selection of selections) {
        commands.push(new CopyLinesCommand(selection.selection, this.down, selection.ignore));
      }
      editor2.pushUndoStop();
      editor2.executeCommands(this.id, commands);
      editor2.pushUndoStop();
    }
  }
  class CopyLinesUpAction extends AbstractCopyLinesAction {
    constructor() {
      super(false, {
        id: "editor.action.copyLinesUpAction",
        label: localize2(1249, "Copy Line Up"),
        precondition: EditorContextKeys.writable,
        kbOpts: {
          kbExpr: EditorContextKeys.editorTextFocus,
          primary: 512 | 1024 | 16,
          linux: {
            primary: 2048 | 512 | 1024 | 16
            /* KeyCode.UpArrow */
          },
          weight: 100
          /* KeybindingWeight.EditorContrib */
        },
        menuOpts: {
          menuId: MenuId.MenubarSelectionMenu,
          group: "2_line",
          title: localize(1244, "&&Copy Line Up"),
          order: 1
        },
        canTriggerInlineEdits: true
      });
    }
  }
  class CopyLinesDownAction extends AbstractCopyLinesAction {
    constructor() {
      super(true, {
        id: "editor.action.copyLinesDownAction",
        label: localize2(1250, "Copy Line Down"),
        precondition: EditorContextKeys.writable,
        kbOpts: {
          kbExpr: EditorContextKeys.editorTextFocus,
          primary: 512 | 1024 | 18,
          linux: {
            primary: 2048 | 512 | 1024 | 18
            /* KeyCode.DownArrow */
          },
          weight: 100
          /* KeybindingWeight.EditorContrib */
        },
        menuOpts: {
          menuId: MenuId.MenubarSelectionMenu,
          group: "2_line",
          title: localize(1245, "Co&&py Line Down"),
          order: 2
        },
        canTriggerInlineEdits: true
      });
    }
  }
  class DuplicateSelectionAction extends EditorAction {
    constructor() {
      super({
        id: "editor.action.duplicateSelection",
        label: localize2(1251, "Duplicate Selection"),
        precondition: EditorContextKeys.writable,
        menuOpts: {
          menuId: MenuId.MenubarSelectionMenu,
          group: "2_line",
          title: localize(1246, "&&Duplicate Selection"),
          order: 5
        },
        canTriggerInlineEdits: true
      });
    }
    run(accessor, editor2, args) {
      if (!editor2.hasModel()) {
        return;
      }
      const commands = [];
      const selections = editor2.getSelections();
      const model = editor2.getModel();
      for (const selection of selections) {
        if (selection.isEmpty()) {
          commands.push(new CopyLinesCommand(selection, true));
        } else {
          const insertSelection = new Selection$1(selection.endLineNumber, selection.endColumn, selection.endLineNumber, selection.endColumn);
          commands.push(new ReplaceCommandThatSelectsText(insertSelection, model.getValueInRange(selection)));
        }
      }
      editor2.pushUndoStop();
      editor2.executeCommands(this.id, commands);
      editor2.pushUndoStop();
    }
  }
  class AbstractMoveLinesAction extends EditorAction {
    constructor(down, opts) {
      super(opts);
      this.down = down;
    }
    run(accessor, editor2) {
      const languageConfigurationService = accessor.get(ILanguageConfigurationService);
      const commands = [];
      const selections = editor2.getSelections() || [];
      const autoIndent = editor2.getOption(
        16
        /* EditorOption.autoIndent */
      );
      for (const selection of selections) {
        commands.push(new MoveLinesCommand(selection, this.down, autoIndent, languageConfigurationService));
      }
      editor2.pushUndoStop();
      editor2.executeCommands(this.id, commands);
      editor2.pushUndoStop();
    }
  }
  class MoveLinesUpAction extends AbstractMoveLinesAction {
    constructor() {
      super(false, {
        id: "editor.action.moveLinesUpAction",
        label: localize2(1252, "Move Line Up"),
        precondition: EditorContextKeys.writable,
        kbOpts: {
          kbExpr: EditorContextKeys.editorTextFocus,
          primary: 512 | 16,
          linux: {
            primary: 512 | 16
            /* KeyCode.UpArrow */
          },
          weight: 100
          /* KeybindingWeight.EditorContrib */
        },
        menuOpts: {
          menuId: MenuId.MenubarSelectionMenu,
          group: "2_line",
          title: localize(1247, "Mo&&ve Line Up"),
          order: 3
        },
        canTriggerInlineEdits: true
      });
    }
  }
  class MoveLinesDownAction extends AbstractMoveLinesAction {
    constructor() {
      super(true, {
        id: "editor.action.moveLinesDownAction",
        label: localize2(1253, "Move Line Down"),
        precondition: EditorContextKeys.writable,
        kbOpts: {
          kbExpr: EditorContextKeys.editorTextFocus,
          primary: 512 | 18,
          linux: {
            primary: 512 | 18
            /* KeyCode.DownArrow */
          },
          weight: 100
          /* KeybindingWeight.EditorContrib */
        },
        menuOpts: {
          menuId: MenuId.MenubarSelectionMenu,
          group: "2_line",
          title: localize(1248, "Move &&Line Down"),
          order: 4
        },
        canTriggerInlineEdits: true
      });
    }
  }
  class AbstractSortLinesAction extends EditorAction {
    constructor(descending, opts) {
      super(opts);
      this.descending = descending;
    }
    run(_accessor, editor2) {
      if (!editor2.hasModel()) {
        return;
      }
      const model = editor2.getModel();
      let selections = editor2.getSelections();
      if (selections.length === 1 && selections[0].isEmpty()) {
        selections = [new Selection$1(1, 1, model.getLineCount(), model.getLineMaxColumn(model.getLineCount()))];
      }
      for (const selection of selections) {
        if (!SortLinesCommand.canRun(editor2.getModel(), selection, this.descending)) {
          return;
        }
      }
      const commands = [];
      for (let i2 = 0, len = selections.length; i2 < len; i2++) {
        commands[i2] = new SortLinesCommand(selections[i2], this.descending);
      }
      editor2.pushUndoStop();
      editor2.executeCommands(this.id, commands);
      editor2.pushUndoStop();
    }
  }
  class SortLinesAscendingAction extends AbstractSortLinesAction {
    constructor() {
      super(false, {
        id: "editor.action.sortLinesAscending",
        label: localize2(1254, "Sort Lines Ascending"),
        precondition: EditorContextKeys.writable,
        canTriggerInlineEdits: true
      });
    }
  }
  class SortLinesDescendingAction extends AbstractSortLinesAction {
    constructor() {
      super(true, {
        id: "editor.action.sortLinesDescending",
        label: localize2(1255, "Sort Lines Descending"),
        precondition: EditorContextKeys.writable,
        canTriggerInlineEdits: true
      });
    }
  }
  class DeleteDuplicateLinesAction extends EditorAction {
    constructor() {
      super({
        id: "editor.action.removeDuplicateLines",
        label: localize2(1256, "Delete Duplicate Lines"),
        precondition: EditorContextKeys.writable,
        canTriggerInlineEdits: true
      });
    }
    run(_accessor, editor2) {
      if (!editor2.hasModel()) {
        return;
      }
      const model = editor2.getModel();
      if (model.getLineCount() === 1 && model.getLineMaxColumn(1) === 1) {
        return;
      }
      const edits = [];
      const endCursorState = [];
      let linesDeleted = 0;
      let updateSelection = true;
      let selections = editor2.getSelections();
      if (selections.length === 1 && selections[0].isEmpty()) {
        selections = [new Selection$1(1, 1, model.getLineCount(), model.getLineMaxColumn(model.getLineCount()))];
        updateSelection = false;
      }
      for (const selection of selections) {
        const uniqueLines = /* @__PURE__ */ new Set();
        const lines = [];
        for (let i2 = selection.startLineNumber; i2 <= selection.endLineNumber; i2++) {
          const line = model.getLineContent(i2);
          if (uniqueLines.has(line)) {
            continue;
          }
          lines.push(line);
          uniqueLines.add(line);
        }
        const selectionToReplace = new Selection$1(selection.startLineNumber, 1, selection.endLineNumber, model.getLineMaxColumn(selection.endLineNumber));
        const adjustedSelectionStart = selection.startLineNumber - linesDeleted;
        const finalSelection = new Selection$1(adjustedSelectionStart, 1, adjustedSelectionStart + lines.length - 1, lines[lines.length - 1].length);
        edits.push(EditOperation.replace(selectionToReplace, lines.join("\n")));
        endCursorState.push(finalSelection);
        linesDeleted += selection.endLineNumber - selection.startLineNumber + 1 - lines.length;
      }
      editor2.pushUndoStop();
      editor2.executeEdits(this.id, edits, updateSelection ? endCursorState : void 0);
      editor2.pushUndoStop();
    }
  }
  class ReverseLinesAction extends EditorAction {
    constructor() {
      super({
        id: "editor.action.reverseLines",
        label: localize2(1257, "Reverse lines"),
        precondition: EditorContextKeys.writable,
        canTriggerInlineEdits: true
      });
    }
    run(_accessor, editor2) {
      if (!editor2.hasModel()) {
        return;
      }
      const model = editor2.getModel();
      const originalSelections = editor2.getSelections();
      let selections = originalSelections;
      if (selections.length === 1 && selections[0].isEmpty()) {
        selections = [new Selection$1(1, 1, model.getLineCount(), model.getLineMaxColumn(model.getLineCount()))];
      }
      const edits = [];
      const resultingSelections = [];
      for (let i2 = 0; i2 < selections.length; i2++) {
        const selection = selections[i2];
        const originalSelection = originalSelections[i2];
        let endLineNumber = selection.endLineNumber;
        if (selection.startLineNumber < selection.endLineNumber && selection.endColumn === 1) {
          endLineNumber--;
        }
        let range2 = new Range$2(selection.startLineNumber, 1, endLineNumber, model.getLineMaxColumn(endLineNumber));
        if (endLineNumber === model.getLineCount() && model.getLineContent(range2.endLineNumber) === "") {
          range2 = range2.setEndPosition(range2.endLineNumber - 1, model.getLineMaxColumn(range2.endLineNumber - 1));
        }
        const lines = [];
        for (let i3 = range2.endLineNumber; i3 >= range2.startLineNumber; i3--) {
          lines.push(model.getLineContent(i3));
        }
        const edit2 = EditOperation.replace(range2, lines.join("\n"));
        edits.push(edit2);
        const updateLineNumber = function(lineNumber) {
          return lineNumber <= range2.endLineNumber ? range2.endLineNumber - lineNumber + range2.startLineNumber : lineNumber;
        };
        const updateSelection = function(sel) {
          if (sel.isEmpty()) {
            return new Selection$1(updateLineNumber(sel.positionLineNumber), sel.positionColumn, updateLineNumber(sel.positionLineNumber), sel.positionColumn);
          } else {
            const newSelectionStart = updateLineNumber(sel.selectionStartLineNumber);
            const newPosition = updateLineNumber(sel.positionLineNumber);
            const newSelectionStartColumn = sel.selectionStartColumn;
            const newPositionColumn = sel.positionColumn;
            return new Selection$1(newSelectionStart, newSelectionStartColumn, newPosition, newPositionColumn);
          }
        };
        resultingSelections.push(updateSelection(originalSelection));
      }
      editor2.pushUndoStop();
      editor2.executeEdits(this.id, edits, resultingSelections);
      editor2.pushUndoStop();
    }
  }
  const _TrimTrailingWhitespaceAction = class _TrimTrailingWhitespaceAction extends EditorAction {
    constructor() {
      super({
        id: _TrimTrailingWhitespaceAction.ID,
        label: localize2(1258, "Trim Trailing Whitespace"),
        precondition: EditorContextKeys.writable,
        kbOpts: {
          kbExpr: EditorContextKeys.editorTextFocus,
          primary: KeyChord(
            2048 | 41,
            2048 | 54
            /* KeyCode.KeyX */
          ),
          weight: 100
          /* KeybindingWeight.EditorContrib */
        }
      });
    }
    run(_accessor, editor2, args) {
      let cursors = [];
      if (args.reason === "auto-save") {
        cursors = (editor2.getSelections() || []).map((s) => new Position$1(s.positionLineNumber, s.positionColumn));
      }
      const selection = editor2.getSelection();
      if (selection === null) {
        return;
      }
      const config = _accessor.get(IConfigurationService);
      const model = editor2.getModel();
      const trimInRegexAndStrings = config.getValue("files.trimTrailingWhitespaceInRegexAndStrings", { overrideIdentifier: model?.getLanguageId(), resource: model?.uri });
      const command = new TrimTrailingWhitespaceCommand(selection, cursors, trimInRegexAndStrings);
      editor2.pushUndoStop();
      editor2.executeCommands(this.id, [command]);
      editor2.pushUndoStop();
    }
  };
  _TrimTrailingWhitespaceAction.ID = "editor.action.trimTrailingWhitespace";
  let TrimTrailingWhitespaceAction = _TrimTrailingWhitespaceAction;
  class DeleteLinesAction extends EditorAction {
    constructor() {
      super({
        id: "editor.action.deleteLines",
        label: localize2(1259, "Delete Line"),
        precondition: EditorContextKeys.writable,
        kbOpts: {
          kbExpr: EditorContextKeys.textInputFocus,
          primary: 2048 | 1024 | 41,
          weight: 100
          /* KeybindingWeight.EditorContrib */
        },
        canTriggerInlineEdits: true
      });
    }
    run(_accessor, editor2) {
      if (!editor2.hasModel()) {
        return;
      }
      const ops = this._getLinesToRemove(editor2);
      const model = editor2.getModel();
      if (model.getLineCount() === 1 && model.getLineMaxColumn(1) === 1) {
        return;
      }
      let linesDeleted = 0;
      const edits = [];
      const cursorState = [];
      for (let i2 = 0, len = ops.length; i2 < len; i2++) {
        const op = ops[i2];
        let startLineNumber = op.startLineNumber;
        let endLineNumber = op.endLineNumber;
        let startColumn = 1;
        let endColumn = model.getLineMaxColumn(endLineNumber);
        if (endLineNumber < model.getLineCount()) {
          endLineNumber += 1;
          endColumn = 1;
        } else if (startLineNumber > 1) {
          startLineNumber -= 1;
          startColumn = model.getLineMaxColumn(startLineNumber);
        }
        edits.push(EditOperation.replace(new Selection$1(startLineNumber, startColumn, endLineNumber, endColumn), ""));
        cursorState.push(new Selection$1(startLineNumber - linesDeleted, op.positionColumn, startLineNumber - linesDeleted, op.positionColumn));
        linesDeleted += op.endLineNumber - op.startLineNumber + 1;
      }
      editor2.pushUndoStop();
      editor2.executeEdits(this.id, edits, cursorState);
      editor2.pushUndoStop();
    }
    _getLinesToRemove(editor2) {
      const operations = editor2.getSelections().map((s) => {
        let endLineNumber = s.endLineNumber;
        if (s.startLineNumber < s.endLineNumber && s.endColumn === 1) {
          endLineNumber -= 1;
        }
        return {
          startLineNumber: s.startLineNumber,
          selectionStartColumn: s.selectionStartColumn,
          endLineNumber,
          positionColumn: s.positionColumn
        };
      });
      operations.sort((a, b) => {
        if (a.startLineNumber === b.startLineNumber) {
          return a.endLineNumber - b.endLineNumber;
        }
        return a.startLineNumber - b.startLineNumber;
      });
      const mergedOperations = [];
      let previousOperation = operations[0];
      for (let i2 = 1; i2 < operations.length; i2++) {
        if (previousOperation.endLineNumber + 1 >= operations[i2].startLineNumber) {
          previousOperation.endLineNumber = operations[i2].endLineNumber;
        } else {
          mergedOperations.push(previousOperation);
          previousOperation = operations[i2];
        }
      }
      mergedOperations.push(previousOperation);
      return mergedOperations;
    }
  }
  class IndentLinesAction extends EditorAction {
    constructor() {
      super({
        id: "editor.action.indentLines",
        label: localize2(1260, "Indent Line"),
        precondition: EditorContextKeys.writable,
        kbOpts: {
          kbExpr: EditorContextKeys.editorTextFocus,
          primary: 2048 | 94,
          weight: 100
          /* KeybindingWeight.EditorContrib */
        },
        canTriggerInlineEdits: true
      });
    }
    run(_accessor, editor2) {
      const viewModel = editor2._getViewModel();
      if (!viewModel) {
        return;
      }
      editor2.pushUndoStop();
      editor2.executeCommands(this.id, TypeOperations.indent(viewModel.cursorConfig, editor2.getModel(), editor2.getSelections()));
      editor2.pushUndoStop();
    }
  }
  class OutdentLinesAction extends EditorAction {
    constructor() {
      super({
        id: "editor.action.outdentLines",
        label: localize2(1261, "Outdent Line"),
        precondition: EditorContextKeys.writable,
        kbOpts: {
          kbExpr: EditorContextKeys.editorTextFocus,
          primary: 2048 | 92,
          weight: 100
          /* KeybindingWeight.EditorContrib */
        },
        canTriggerInlineEdits: true
      });
    }
    run(_accessor, editor2) {
      CoreEditingCommands.Outdent.runEditorCommand(_accessor, editor2, null);
    }
  }
  const _InsertLineBeforeAction = class _InsertLineBeforeAction extends EditorAction {
    constructor() {
      super({
        id: _InsertLineBeforeAction.ID,
        label: localize2(1262, "Insert Line Above"),
        precondition: EditorContextKeys.writable,
        kbOpts: {
          kbExpr: EditorContextKeys.editorTextFocus,
          primary: 2048 | 1024 | 3,
          weight: 100
          /* KeybindingWeight.EditorContrib */
        },
        canTriggerInlineEdits: true
      });
    }
    run(_accessor, editor2) {
      const viewModel = editor2._getViewModel();
      if (!viewModel) {
        return;
      }
      editor2.pushUndoStop();
      editor2.executeCommands(this.id, EnterOperation.lineInsertBefore(viewModel.cursorConfig, editor2.getModel(), editor2.getSelections()));
    }
  };
  _InsertLineBeforeAction.ID = "editor.action.insertLineBefore";
  let InsertLineBeforeAction = _InsertLineBeforeAction;
  const _InsertLineAfterAction = class _InsertLineAfterAction extends EditorAction {
    constructor() {
      super({
        id: _InsertLineAfterAction.ID,
        label: localize2(1263, "Insert Line Below"),
        precondition: EditorContextKeys.writable,
        kbOpts: {
          kbExpr: EditorContextKeys.editorTextFocus,
          primary: 2048 | 3,
          weight: 100
          /* KeybindingWeight.EditorContrib */
        },
        canTriggerInlineEdits: true
      });
    }
    run(_accessor, editor2) {
      const viewModel = editor2._getViewModel();
      if (!viewModel) {
        return;
      }
      editor2.pushUndoStop();
      editor2.executeCommands(this.id, EnterOperation.lineInsertAfter(viewModel.cursorConfig, editor2.getModel(), editor2.getSelections()));
    }
  };
  _InsertLineAfterAction.ID = "editor.action.insertLineAfter";
  let InsertLineAfterAction = _InsertLineAfterAction;
  class AbstractDeleteAllToBoundaryAction extends EditorAction {
    run(_accessor, editor2) {
      if (!editor2.hasModel()) {
        return;
      }
      const primaryCursor = editor2.getSelection();
      const rangesToDelete = this._getRangesToDelete(editor2);
      const effectiveRanges = [];
      for (let i2 = 0, count = rangesToDelete.length - 1; i2 < count; i2++) {
        const range2 = rangesToDelete[i2];
        const nextRange = rangesToDelete[i2 + 1];
        if (Range$2.intersectRanges(range2, nextRange) === null) {
          effectiveRanges.push(range2);
        } else {
          rangesToDelete[i2 + 1] = Range$2.plusRange(range2, nextRange);
        }
      }
      effectiveRanges.push(rangesToDelete[rangesToDelete.length - 1]);
      const endCursorState = this._getEndCursorState(primaryCursor, effectiveRanges);
      const edits = effectiveRanges.map((range2) => {
        return EditOperation.replace(range2, "");
      });
      editor2.pushUndoStop();
      editor2.executeEdits(this.id, edits, endCursorState);
      editor2.pushUndoStop();
    }
  }
  class DeleteAllLeftAction extends AbstractDeleteAllToBoundaryAction {
    constructor() {
      super({
        id: "deleteAllLeft",
        label: localize2(1264, "Delete All Left"),
        precondition: EditorContextKeys.writable,
        kbOpts: {
          kbExpr: EditorContextKeys.textInputFocus,
          primary: 0,
          mac: {
            primary: 2048 | 1
            /* KeyCode.Backspace */
          },
          weight: 100
          /* KeybindingWeight.EditorContrib */
        },
        canTriggerInlineEdits: true
      });
    }
    _getEndCursorState(primaryCursor, rangesToDelete) {
      let endPrimaryCursor = null;
      const endCursorState = [];
      let deletedLines = 0;
      rangesToDelete.forEach((range2) => {
        let endCursor;
        if (range2.endColumn === 1 && deletedLines > 0) {
          const newStartLine = range2.startLineNumber - deletedLines;
          endCursor = new Selection$1(newStartLine, range2.startColumn, newStartLine, range2.startColumn);
        } else {
          endCursor = new Selection$1(range2.startLineNumber, range2.startColumn, range2.startLineNumber, range2.startColumn);
        }
        deletedLines += range2.endLineNumber - range2.startLineNumber;
        if (range2.intersectRanges(primaryCursor)) {
          endPrimaryCursor = endCursor;
        } else {
          endCursorState.push(endCursor);
        }
      });
      if (endPrimaryCursor) {
        endCursorState.unshift(endPrimaryCursor);
      }
      return endCursorState;
    }
    _getRangesToDelete(editor2) {
      const selections = editor2.getSelections();
      if (selections === null) {
        return [];
      }
      let rangesToDelete = selections;
      const model = editor2.getModel();
      if (model === null) {
        return [];
      }
      rangesToDelete.sort(Range$2.compareRangesUsingStarts);
      rangesToDelete = rangesToDelete.map((selection) => {
        if (selection.isEmpty()) {
          if (selection.startColumn === 1) {
            const deleteFromLine = Math.max(1, selection.startLineNumber - 1);
            const deleteFromColumn = selection.startLineNumber === 1 ? 1 : model.getLineLength(deleteFromLine) + 1;
            return new Range$2(deleteFromLine, deleteFromColumn, selection.startLineNumber, 1);
          } else {
            return new Range$2(selection.startLineNumber, 1, selection.startLineNumber, selection.startColumn);
          }
        } else {
          return new Range$2(selection.startLineNumber, 1, selection.endLineNumber, selection.endColumn);
        }
      });
      return rangesToDelete;
    }
  }
  class DeleteAllRightAction extends AbstractDeleteAllToBoundaryAction {
    constructor() {
      super({
        id: "deleteAllRight",
        label: localize2(1265, "Delete All Right"),
        precondition: EditorContextKeys.writable,
        kbOpts: {
          kbExpr: EditorContextKeys.textInputFocus,
          primary: 0,
          mac: { primary: 256 | 41, secondary: [
            2048 | 20
            /* KeyCode.Delete */
          ] },
          weight: 100
          /* KeybindingWeight.EditorContrib */
        },
        canTriggerInlineEdits: true
      });
    }
    _getEndCursorState(primaryCursor, rangesToDelete) {
      let endPrimaryCursor = null;
      const endCursorState = [];
      for (let i2 = 0, len = rangesToDelete.length, offset = 0; i2 < len; i2++) {
        const range2 = rangesToDelete[i2];
        const endCursor = new Selection$1(range2.startLineNumber - offset, range2.startColumn, range2.startLineNumber - offset, range2.startColumn);
        if (range2.intersectRanges(primaryCursor)) {
          endPrimaryCursor = endCursor;
        } else {
          endCursorState.push(endCursor);
        }
      }
      if (endPrimaryCursor) {
        endCursorState.unshift(endPrimaryCursor);
      }
      return endCursorState;
    }
    _getRangesToDelete(editor2) {
      const model = editor2.getModel();
      if (model === null) {
        return [];
      }
      const selections = editor2.getSelections();
      if (selections === null) {
        return [];
      }
      const rangesToDelete = selections.map((sel) => {
        if (sel.isEmpty()) {
          const maxColumn = model.getLineMaxColumn(sel.startLineNumber);
          if (sel.startColumn === maxColumn) {
            return new Range$2(sel.startLineNumber, sel.startColumn, sel.startLineNumber + 1, 1);
          } else {
            return new Range$2(sel.startLineNumber, sel.startColumn, sel.startLineNumber, maxColumn);
          }
        }
        return sel;
      });
      rangesToDelete.sort(Range$2.compareRangesUsingStarts);
      return rangesToDelete;
    }
  }
  class JoinLinesAction extends EditorAction {
    constructor() {
      super({
        id: "editor.action.joinLines",
        label: localize2(1266, "Join Lines"),
        precondition: EditorContextKeys.writable,
        kbOpts: {
          kbExpr: EditorContextKeys.editorTextFocus,
          primary: 0,
          mac: {
            primary: 256 | 40
            /* KeyCode.KeyJ */
          },
          weight: 100
          /* KeybindingWeight.EditorContrib */
        },
        canTriggerInlineEdits: true
      });
    }
    run(_accessor, editor2) {
      const selections = editor2.getSelections();
      if (selections === null) {
        return;
      }
      let primaryCursor = editor2.getSelection();
      if (primaryCursor === null) {
        return;
      }
      selections.sort(Range$2.compareRangesUsingStarts);
      const reducedSelections = [];
      const lastSelection = selections.reduce((previousValue, currentValue) => {
        if (previousValue.isEmpty()) {
          if (previousValue.endLineNumber === currentValue.startLineNumber) {
            if (primaryCursor.equalsSelection(previousValue)) {
              primaryCursor = currentValue;
            }
            return currentValue;
          }
          if (currentValue.startLineNumber > previousValue.endLineNumber + 1) {
            reducedSelections.push(previousValue);
            return currentValue;
          } else {
            return new Selection$1(previousValue.startLineNumber, previousValue.startColumn, currentValue.endLineNumber, currentValue.endColumn);
          }
        } else {
          if (currentValue.startLineNumber > previousValue.endLineNumber) {
            reducedSelections.push(previousValue);
            return currentValue;
          } else {
            return new Selection$1(previousValue.startLineNumber, previousValue.startColumn, currentValue.endLineNumber, currentValue.endColumn);
          }
        }
      });
      reducedSelections.push(lastSelection);
      const model = editor2.getModel();
      if (model === null) {
        return;
      }
      const edits = [];
      const endCursorState = [];
      let endPrimaryCursor = primaryCursor;
      let lineOffset = 0;
      for (let i2 = 0, len = reducedSelections.length; i2 < len; i2++) {
        const selection = reducedSelections[i2];
        const startLineNumber = selection.startLineNumber;
        const startColumn = 1;
        let columnDeltaOffset = 0;
        let endLineNumber, endColumn;
        const selectionEndPositionOffset = model.getLineLength(selection.endLineNumber) - selection.endColumn;
        if (selection.isEmpty() || selection.startLineNumber === selection.endLineNumber) {
          const position = selection.getStartPosition();
          if (position.lineNumber < model.getLineCount()) {
            endLineNumber = startLineNumber + 1;
            endColumn = model.getLineMaxColumn(endLineNumber);
          } else {
            endLineNumber = position.lineNumber;
            endColumn = model.getLineMaxColumn(position.lineNumber);
          }
        } else {
          endLineNumber = selection.endLineNumber;
          endColumn = model.getLineMaxColumn(endLineNumber);
        }
        let trimmedLinesContent = model.getLineContent(startLineNumber);
        for (let i3 = startLineNumber + 1; i3 <= endLineNumber; i3++) {
          const lineText = model.getLineContent(i3);
          const firstNonWhitespaceIdx = model.getLineFirstNonWhitespaceColumn(i3);
          if (firstNonWhitespaceIdx >= 1) {
            let insertSpace = true;
            if (trimmedLinesContent === "") {
              insertSpace = false;
            }
            if (insertSpace && (trimmedLinesContent.charAt(trimmedLinesContent.length - 1) === " " || trimmedLinesContent.charAt(trimmedLinesContent.length - 1) === "	")) {
              insertSpace = false;
              trimmedLinesContent = trimmedLinesContent.replace(/[\s\uFEFF\xA0]+$/g, " ");
            }
            const lineTextWithoutIndent = lineText.substr(firstNonWhitespaceIdx - 1);
            trimmedLinesContent += (insertSpace ? " " : "") + lineTextWithoutIndent;
            if (insertSpace) {
              columnDeltaOffset = lineTextWithoutIndent.length + 1;
            } else {
              columnDeltaOffset = lineTextWithoutIndent.length;
            }
          } else {
            columnDeltaOffset = 0;
          }
        }
        const deleteSelection = new Range$2(startLineNumber, startColumn, endLineNumber, endColumn);
        if (!deleteSelection.isEmpty()) {
          let resultSelection;
          if (selection.isEmpty()) {
            edits.push(EditOperation.replace(deleteSelection, trimmedLinesContent));
            resultSelection = new Selection$1(deleteSelection.startLineNumber - lineOffset, trimmedLinesContent.length - columnDeltaOffset + 1, startLineNumber - lineOffset, trimmedLinesContent.length - columnDeltaOffset + 1);
          } else {
            if (selection.startLineNumber === selection.endLineNumber) {
              edits.push(EditOperation.replace(deleteSelection, trimmedLinesContent));
              resultSelection = new Selection$1(selection.startLineNumber - lineOffset, selection.startColumn, selection.endLineNumber - lineOffset, selection.endColumn);
            } else {
              edits.push(EditOperation.replace(deleteSelection, trimmedLinesContent));
              resultSelection = new Selection$1(selection.startLineNumber - lineOffset, selection.startColumn, selection.startLineNumber - lineOffset, trimmedLinesContent.length - selectionEndPositionOffset);
            }
          }
          if (Range$2.intersectRanges(deleteSelection, primaryCursor) !== null) {
            endPrimaryCursor = resultSelection;
          } else {
            endCursorState.push(resultSelection);
          }
        }
        lineOffset += deleteSelection.endLineNumber - deleteSelection.startLineNumber;
      }
      endCursorState.unshift(endPrimaryCursor);
      editor2.pushUndoStop();
      editor2.executeEdits(this.id, edits, endCursorState);
      editor2.pushUndoStop();
    }
  }
  class TransposeAction extends EditorAction {
    constructor() {
      super({
        id: "editor.action.transpose",
        label: localize2(1267, "Transpose Characters around the Cursor"),
        precondition: EditorContextKeys.writable,
        canTriggerInlineEdits: true
      });
    }
    run(_accessor, editor2) {
      const selections = editor2.getSelections();
      if (selections === null) {
        return;
      }
      const model = editor2.getModel();
      if (model === null) {
        return;
      }
      const commands = [];
      for (let i2 = 0, len = selections.length; i2 < len; i2++) {
        const selection = selections[i2];
        if (!selection.isEmpty()) {
          continue;
        }
        const cursor = selection.getStartPosition();
        const maxColumn = model.getLineMaxColumn(cursor.lineNumber);
        if (cursor.column >= maxColumn) {
          if (cursor.lineNumber === model.getLineCount()) {
            continue;
          }
          const deleteSelection = new Range$2(cursor.lineNumber, Math.max(1, cursor.column - 1), cursor.lineNumber + 1, 1);
          const chars = model.getValueInRange(deleteSelection).split("").reverse().join("");
          commands.push(new ReplaceCommand(new Selection$1(cursor.lineNumber, Math.max(1, cursor.column - 1), cursor.lineNumber + 1, 1), chars));
        } else {
          const deleteSelection = new Range$2(cursor.lineNumber, Math.max(1, cursor.column - 1), cursor.lineNumber, cursor.column + 1);
          const chars = model.getValueInRange(deleteSelection).split("").reverse().join("");
          commands.push(new ReplaceCommandThatPreservesSelection(deleteSelection, chars, new Selection$1(cursor.lineNumber, cursor.column + 1, cursor.lineNumber, cursor.column + 1)));
        }
      }
      editor2.pushUndoStop();
      editor2.executeCommands(this.id, commands);
      editor2.pushUndoStop();
    }
  }
  class AbstractCaseAction extends EditorAction {
    run(_accessor, editor2) {
      const selections = editor2.getSelections();
      if (selections === null) {
        return;
      }
      const model = editor2.getModel();
      if (model === null) {
        return;
      }
      const wordSeparators2 = editor2.getOption(
        148
        /* EditorOption.wordSeparators */
      );
      const textEdits = [];
      for (const selection of selections) {
        if (selection.isEmpty()) {
          const cursor = selection.getStartPosition();
          const word = editor2.getConfiguredWordAtPosition(cursor);
          if (!word) {
            continue;
          }
          const wordRange = new Range$2(cursor.lineNumber, word.startColumn, cursor.lineNumber, word.endColumn);
          const text2 = model.getValueInRange(wordRange);
          textEdits.push(EditOperation.replace(wordRange, this._modifyText(text2, wordSeparators2)));
        } else {
          const text2 = model.getValueInRange(selection);
          textEdits.push(EditOperation.replace(selection, this._modifyText(text2, wordSeparators2)));
        }
      }
      editor2.pushUndoStop();
      editor2.executeEdits(this.id, textEdits);
      editor2.pushUndoStop();
    }
  }
  class UpperCaseAction extends AbstractCaseAction {
    constructor() {
      super({
        id: "editor.action.transformToUppercase",
        label: localize2(1268, "Transform to Uppercase"),
        precondition: EditorContextKeys.writable,
        canTriggerInlineEdits: true
      });
    }
    _modifyText(text2, wordSeparators2) {
      return text2.toLocaleUpperCase();
    }
  }
  class LowerCaseAction extends AbstractCaseAction {
    constructor() {
      super({
        id: "editor.action.transformToLowercase",
        label: localize2(1269, "Transform to Lowercase"),
        precondition: EditorContextKeys.writable,
        canTriggerInlineEdits: true
      });
    }
    _modifyText(text2, wordSeparators2) {
      return text2.toLocaleLowerCase();
    }
  }
  class BackwardsCompatibleRegExp {
    constructor(_pattern, _flags) {
      this._pattern = _pattern;
      this._flags = _flags;
      this._actual = null;
      this._evaluated = false;
    }
    get() {
      if (!this._evaluated) {
        this._evaluated = true;
        try {
          this._actual = new RegExp(this._pattern, this._flags);
        } catch (err) {
        }
      }
      return this._actual;
    }
    isSupported() {
      return this.get() !== null;
    }
  }
  const _TitleCaseAction = class _TitleCaseAction extends AbstractCaseAction {
    constructor() {
      super({
        id: "editor.action.transformToTitlecase",
        label: localize2(1270, "Transform to Title Case"),
        precondition: EditorContextKeys.writable,
        canTriggerInlineEdits: true
      });
    }
    _modifyText(text2, wordSeparators2) {
      const titleBoundary = _TitleCaseAction.titleBoundary.get();
      if (!titleBoundary) {
        return text2;
      }
      return text2.toLocaleLowerCase().replace(titleBoundary, (b) => b.toLocaleUpperCase());
    }
  };
  _TitleCaseAction.titleBoundary = new BackwardsCompatibleRegExp("(^|[^\\p{L}\\p{N}']|((^|\\P{L})'))\\p{L}", "gmu");
  let TitleCaseAction = _TitleCaseAction;
  const _SnakeCaseAction = class _SnakeCaseAction extends AbstractCaseAction {
    constructor() {
      super({
        id: "editor.action.transformToSnakecase",
        label: localize2(1271, "Transform to Snake Case"),
        precondition: EditorContextKeys.writable,
        canTriggerInlineEdits: true
      });
    }
    _modifyText(text2, wordSeparators2) {
      const caseBoundary = _SnakeCaseAction.caseBoundary.get();
      const singleLetters = _SnakeCaseAction.singleLetters.get();
      if (!caseBoundary || !singleLetters) {
        return text2;
      }
      return text2.replace(caseBoundary, "$1_$2").replace(singleLetters, "$1_$2$3").toLocaleLowerCase();
    }
  };
  _SnakeCaseAction.caseBoundary = new BackwardsCompatibleRegExp("(\\p{Ll})(\\p{Lu})", "gmu");
  _SnakeCaseAction.singleLetters = new BackwardsCompatibleRegExp("(\\p{Lu}|\\p{N})(\\p{Lu})(\\p{Ll})", "gmu");
  let SnakeCaseAction = _SnakeCaseAction;
  const _CamelCaseAction = class _CamelCaseAction extends AbstractCaseAction {
    constructor() {
      super({
        id: "editor.action.transformToCamelcase",
        label: localize2(1272, "Transform to Camel Case"),
        precondition: EditorContextKeys.writable,
        canTriggerInlineEdits: true
      });
    }
    _modifyText(text2, wordSeparators2) {
      const wordBoundary = /\r\n|\r|\n/.test(text2) ? _CamelCaseAction.multiLineWordBoundary.get() : _CamelCaseAction.singleLineWordBoundary.get();
      const validWordStart = _CamelCaseAction.validWordStart.get();
      if (!wordBoundary || !validWordStart) {
        return text2;
      }
      const words = text2.split(wordBoundary);
      const firstWord = words.shift()?.replace(validWordStart, (start) => start.toLocaleLowerCase());
      return firstWord + words.map((word) => word.substring(0, 1).toLocaleUpperCase() + word.substring(1)).join("");
    }
  };
  _CamelCaseAction.singleLineWordBoundary = new BackwardsCompatibleRegExp("[_\\s-]+", "gm");
  _CamelCaseAction.multiLineWordBoundary = new BackwardsCompatibleRegExp("[_-]+", "gm");
  _CamelCaseAction.validWordStart = new BackwardsCompatibleRegExp("^(\\p{Lu}[^\\p{Lu}])", "gmu");
  let CamelCaseAction = _CamelCaseAction;
  const _PascalCaseAction = class _PascalCaseAction extends AbstractCaseAction {
    constructor() {
      super({
        id: "editor.action.transformToPascalcase",
        label: localize2(1273, "Transform to Pascal Case"),
        precondition: EditorContextKeys.writable,
        canTriggerInlineEdits: true
      });
    }
    _modifyText(text2, wordSeparators2) {
      const wordBoundary = _PascalCaseAction.wordBoundary.get();
      const wordBoundaryToMaintain = _PascalCaseAction.wordBoundaryToMaintain.get();
      const upperCaseWordMatcher = _PascalCaseAction.upperCaseWordMatcher.get();
      if (!wordBoundary || !wordBoundaryToMaintain || !upperCaseWordMatcher) {
        return text2;
      }
      const wordsWithMaintainBoundaries = text2.split(wordBoundaryToMaintain);
      const words = wordsWithMaintainBoundaries.map((word) => word.split(wordBoundary)).flat();
      return words.map((word) => {
        const normalizedWord = word.charAt(0).toLocaleUpperCase() + word.slice(1);
        const isAllCaps = normalizedWord.length > 1 && upperCaseWordMatcher.test(normalizedWord);
        if (isAllCaps) {
          return normalizedWord.charAt(0) + normalizedWord.slice(1).toLocaleLowerCase();
        }
        return normalizedWord;
      }).join("");
    }
  };
  _PascalCaseAction.wordBoundary = new BackwardsCompatibleRegExp("[_ \\t-]", "gm");
  _PascalCaseAction.wordBoundaryToMaintain = new BackwardsCompatibleRegExp("(?<=\\.)", "gm");
  _PascalCaseAction.upperCaseWordMatcher = new BackwardsCompatibleRegExp("^\\p{Lu}+$", "mu");
  let PascalCaseAction = _PascalCaseAction;
  const _KebabCaseAction = class _KebabCaseAction extends AbstractCaseAction {
    static isSupported() {
      const areAllRegexpsSupported = [
        this.caseBoundary,
        this.singleLetters,
        this.underscoreBoundary
      ].every((regexp) => regexp.isSupported());
      return areAllRegexpsSupported;
    }
    constructor() {
      super({
        id: "editor.action.transformToKebabcase",
        label: localize2(1274, "Transform to Kebab Case"),
        precondition: EditorContextKeys.writable,
        canTriggerInlineEdits: true
      });
    }
    _modifyText(text2, _) {
      const caseBoundary = _KebabCaseAction.caseBoundary.get();
      const singleLetters = _KebabCaseAction.singleLetters.get();
      const underscoreBoundary = _KebabCaseAction.underscoreBoundary.get();
      if (!caseBoundary || !singleLetters || !underscoreBoundary) {
        return text2;
      }
      return text2.replace(underscoreBoundary, "$1-$3").replace(caseBoundary, "$1-$2").replace(singleLetters, "$1-$2").toLocaleLowerCase();
    }
  };
  _KebabCaseAction.caseBoundary = new BackwardsCompatibleRegExp("(\\p{Ll})(\\p{Lu})", "gmu");
  _KebabCaseAction.singleLetters = new BackwardsCompatibleRegExp("(\\p{Lu}|\\p{N})(\\p{Lu}\\p{Ll})", "gmu");
  _KebabCaseAction.underscoreBoundary = new BackwardsCompatibleRegExp("(\\S)(_)(\\S)", "gm");
  let KebabCaseAction = _KebabCaseAction;
  registerEditorAction(CopyLinesUpAction);
  registerEditorAction(CopyLinesDownAction);
  registerEditorAction(DuplicateSelectionAction);
  registerEditorAction(MoveLinesUpAction);
  registerEditorAction(MoveLinesDownAction);
  registerEditorAction(SortLinesAscendingAction);
  registerEditorAction(SortLinesDescendingAction);
  registerEditorAction(DeleteDuplicateLinesAction);
  registerEditorAction(TrimTrailingWhitespaceAction);
  registerEditorAction(DeleteLinesAction);
  registerEditorAction(IndentLinesAction);
  registerEditorAction(OutdentLinesAction);
  registerEditorAction(InsertLineBeforeAction);
  registerEditorAction(InsertLineAfterAction);
  registerEditorAction(DeleteAllLeftAction);
  registerEditorAction(DeleteAllRightAction);
  registerEditorAction(JoinLinesAction);
  registerEditorAction(TransposeAction);
  registerEditorAction(UpperCaseAction);
  registerEditorAction(LowerCaseAction);
  registerEditorAction(ReverseLinesAction);
  if (SnakeCaseAction.caseBoundary.isSupported() && SnakeCaseAction.singleLetters.isSupported()) {
    registerEditorAction(SnakeCaseAction);
  }
  if (CamelCaseAction.singleLineWordBoundary.isSupported() && CamelCaseAction.multiLineWordBoundary.isSupported()) {
    registerEditorAction(CamelCaseAction);
  }
  if (PascalCaseAction.wordBoundary.isSupported()) {
    registerEditorAction(PascalCaseAction);
  }
  if (TitleCaseAction.titleBoundary.isSupported()) {
    registerEditorAction(TitleCaseAction);
  }
  if (KebabCaseAction.isSupported()) {
    registerEditorAction(KebabCaseAction);
  }
  const IDataChannelService = createDecorator("dataChannelService");
  class NullDataChannelService {
    getDataChannel(_channelId) {
      return {
        sendData: () => {
        }
      };
    }
  }
  var __decorate$1C = 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$1B = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  function formatRecordableLogEntry(entry) {
    return entry.sourceId + " @@ " + JSON.stringify({ ...entry, modelUri: entry.modelUri?.toString(), sourceId: void 0 });
  }
  let StructuredLogger = class StructuredLogger extends Disposable {
    static cast() {
      return this;
    }
    constructor(_key, _contextKeyService, _dataChannelService) {
      super();
      this._key = _key;
      this._contextKeyService = _contextKeyService;
      this._dataChannelService = _dataChannelService;
      this._isEnabledContextKeyValue = observableContextKey("structuredLogger.enabled:" + this._key, this._contextKeyService).recomputeInitiallyAndOnChange(this._store);
      this.isEnabled = this._isEnabledContextKeyValue.map((v) => v !== void 0);
    }
    log(data) {
      const enabled = this._isEnabledContextKeyValue.get();
      if (!enabled) {
        return false;
      }
      this._dataChannelService.getDataChannel("structuredLogger:" + this._key).sendData(data);
      return true;
    }
  };
  StructuredLogger = __decorate$1C([
    __param$1B(1, IContextKeyService),
    __param$1B(2, IDataChannelService)
  ], StructuredLogger);
  function observableContextKey(key, contextKeyService) {
    return observableFromEvent(contextKeyService.onDidChangeContext, () => contextKeyService.getContextKeyValue(key));
  }
  var __decorate$1B = 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$1A = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  let TextModelChangeRecorder = class TextModelChangeRecorder extends Disposable {
    constructor(_editor, _instantiationService, _loggerService) {
      super();
      this._editor = _editor;
      this._instantiationService = _instantiationService;
      this._loggerService = _loggerService;
      this._structuredLogger = this._register(this._instantiationService.createInstance(StructuredLogger.cast(), "editor.inlineSuggest.logChangeReason.commandId"));
      const logger = this._loggerService?.createLogger("textModelChanges", { hidden: false, name: "Text Model Changes Reason" });
      const loggingLevel = observableFromEvent(this, logger.onDidChangeLogLevel, () => logger.getLevel());
      this._register(autorun((reader) => {
        if (!canLog(loggingLevel.read(reader), LogLevel.Trace)) {
          return;
        }
        reader.store.add(this._editor.onDidChangeModelContent((e) => {
          if (this._editor.getModel()?.uri.scheme === "output") {
            return;
          }
          logger.trace("onDidChangeModelContent: " + e.detailedReasons.map((r) => r.toKey(Number.MAX_VALUE)).join(", "));
        }));
      }));
      this._register(autorun((reader) => {
        if (!(this._editor instanceof CodeEditorWidget)) {
          return;
        }
        if (!this._structuredLogger.isEnabled.read(reader)) {
          return;
        }
        reader.store.add(this._editor.onDidChangeModelContent((e) => {
          const tm = this._editor.getModel();
          if (!tm) {
            return;
          }
          const reason = e.detailedReasons[0];
          const data = {
            ...reason.metadata,
            sourceId: "TextModel.setChangeReason",
            source: reason.metadata.source,
            time: Date.now(),
            modelUri: tm.uri,
            modelVersion: tm.getVersionId()
          };
          setTimeout(() => {
            this._structuredLogger.log(data);
          }, 0);
        }));
      }));
    }
  };
  TextModelChangeRecorder = __decorate$1B([
    __param$1A(1, IInstantiationService),
    __param$1A(2, ILoggerService)
  ], TextModelChangeRecorder);
  function normalizeDriveLetter(path, isWindowsOS = isWindows) {
    if (hasDriveLetter(path, isWindowsOS)) {
      return path.charAt(0).toUpperCase() + path.slice(1);
    }
    return path;
  }
  var __decorate$1A = 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$1z = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  class CompositeSnippetVariableResolver {
    constructor(_delegates) {
      this._delegates = _delegates;
    }
    resolve(variable) {
      for (const delegate of this._delegates) {
        const value = delegate.resolve(variable);
        if (value !== void 0) {
          return value;
        }
      }
      return void 0;
    }
  }
  class SelectionBasedVariableResolver {
    constructor(_model, _selection, _selectionIdx, _overtypingCapturer) {
      this._model = _model;
      this._selection = _selection;
      this._selectionIdx = _selectionIdx;
      this._overtypingCapturer = _overtypingCapturer;
    }
    resolve(variable) {
      const { name } = variable;
      if (name === "SELECTION" || name === "TM_SELECTED_TEXT") {
        let value = this._model.getValueInRange(this._selection) || void 0;
        let isMultiline = this._selection.startLineNumber !== this._selection.endLineNumber;
        if (!value && this._overtypingCapturer) {
          const info = this._overtypingCapturer.getLastOvertypedInfo(this._selectionIdx);
          if (info) {
            value = info.value;
            isMultiline = info.multiline;
          }
        }
        if (value && isMultiline && variable.snippet) {
          const line = this._model.getLineContent(this._selection.startLineNumber);
          const lineLeadingWhitespace = getLeadingWhitespace(line, 0, this._selection.startColumn - 1);
          let varLeadingWhitespace = lineLeadingWhitespace;
          variable.snippet.walk((marker) => {
            if (marker === variable) {
              return false;
            }
            if (marker instanceof Text) {
              varLeadingWhitespace = getLeadingWhitespace(splitLines(marker.value).pop());
            }
            return true;
          });
          const whitespaceCommonLength = commonPrefixLength(varLeadingWhitespace, lineLeadingWhitespace);
          value = value.replace(/(\r\n|\r|\n)(.*)/g, (m, newline2, rest) => `${newline2}${varLeadingWhitespace.substr(whitespaceCommonLength)}${rest}`);
        }
        return value;
      } else if (name === "TM_CURRENT_LINE") {
        return this._model.getLineContent(this._selection.positionLineNumber);
      } else if (name === "TM_CURRENT_WORD") {
        const info = this._model.getWordAtPosition({
          lineNumber: this._selection.positionLineNumber,
          column: this._selection.positionColumn
        });
        return info && info.word || void 0;
      } else if (name === "TM_LINE_INDEX") {
        return String(this._selection.positionLineNumber - 1);
      } else if (name === "TM_LINE_NUMBER") {
        return String(this._selection.positionLineNumber);
      } else if (name === "CURSOR_INDEX") {
        return String(this._selectionIdx);
      } else if (name === "CURSOR_NUMBER") {
        return String(this._selectionIdx + 1);
      }
      return void 0;
    }
  }
  class ModelBasedVariableResolver {
    constructor(_labelService, _model) {
      this._labelService = _labelService;
      this._model = _model;
    }
    resolve(variable) {
      const { name } = variable;
      if (name === "TM_FILENAME") {
        return basename$1(this._model.uri.fsPath);
      } else if (name === "TM_FILENAME_BASE") {
        const name2 = basename$1(this._model.uri.fsPath);
        const idx = name2.lastIndexOf(".");
        if (idx <= 0) {
          return name2;
        } else {
          return name2.slice(0, idx);
        }
      } else if (name === "TM_DIRECTORY") {
        if (dirname$1(this._model.uri.fsPath) === ".") {
          return "";
        }
        return this._labelService.getUriLabel(dirname(this._model.uri));
      } else if (name === "TM_DIRECTORY_BASE") {
        if (dirname$1(this._model.uri.fsPath) === ".") {
          return "";
        }
        return basename$1(dirname$1(this._model.uri.fsPath));
      } else if (name === "TM_FILEPATH") {
        return this._labelService.getUriLabel(this._model.uri);
      } else if (name === "RELATIVE_FILEPATH") {
        return this._labelService.getUriLabel(this._model.uri, { relative: true, noPrefix: true });
      }
      return void 0;
    }
  }
  class ClipboardBasedVariableResolver {
    constructor(_readClipboardText, _selectionIdx, _selectionCount, _spread) {
      this._readClipboardText = _readClipboardText;
      this._selectionIdx = _selectionIdx;
      this._selectionCount = _selectionCount;
      this._spread = _spread;
    }
    resolve(variable) {
      if (variable.name !== "CLIPBOARD") {
        return void 0;
      }
      const clipboardText = this._readClipboardText();
      if (!clipboardText) {
        return void 0;
      }
      if (this._spread) {
        const lines = clipboardText.split(/\r\n|\n|\r/).filter((s) => !isFalsyOrWhitespace(s));
        if (lines.length === this._selectionCount) {
          return lines[this._selectionIdx];
        }
      }
      return clipboardText;
    }
  }
  let CommentBasedVariableResolver = class CommentBasedVariableResolver {
    constructor(_model, _selection, _languageConfigurationService) {
      this._model = _model;
      this._selection = _selection;
      this._languageConfigurationService = _languageConfigurationService;
    }
    resolve(variable) {
      const { name } = variable;
      const langId = this._model.getLanguageIdAtPosition(this._selection.selectionStartLineNumber, this._selection.selectionStartColumn);
      const config = this._languageConfigurationService.getLanguageConfiguration(langId).comments;
      if (!config) {
        return void 0;
      }
      if (name === "LINE_COMMENT") {
        return config.lineCommentToken || void 0;
      } else if (name === "BLOCK_COMMENT_START") {
        return config.blockCommentStartToken || void 0;
      } else if (name === "BLOCK_COMMENT_END") {
        return config.blockCommentEndToken || void 0;
      }
      return void 0;
    }
  };
  CommentBasedVariableResolver = __decorate$1A([
    __param$1z(2, ILanguageConfigurationService)
  ], CommentBasedVariableResolver);
  const _TimeBasedVariableResolver = class _TimeBasedVariableResolver {
    constructor() {
      this._date = /* @__PURE__ */ new Date();
    }
    resolve(variable) {
      const { name } = variable;
      if (name === "CURRENT_YEAR") {
        return String(this._date.getFullYear());
      } else if (name === "CURRENT_YEAR_SHORT") {
        return String(this._date.getFullYear()).slice(-2);
      } else if (name === "CURRENT_MONTH") {
        return String(this._date.getMonth().valueOf() + 1).padStart(2, "0");
      } else if (name === "CURRENT_DATE") {
        return String(this._date.getDate().valueOf()).padStart(2, "0");
      } else if (name === "CURRENT_HOUR") {
        return String(this._date.getHours().valueOf()).padStart(2, "0");
      } else if (name === "CURRENT_MINUTE") {
        return String(this._date.getMinutes().valueOf()).padStart(2, "0");
      } else if (name === "CURRENT_SECOND") {
        return String(this._date.getSeconds().valueOf()).padStart(2, "0");
      } else if (name === "CURRENT_DAY_NAME") {
        return _TimeBasedVariableResolver.dayNames[this._date.getDay()];
      } else if (name === "CURRENT_DAY_NAME_SHORT") {
        return _TimeBasedVariableResolver.dayNamesShort[this._date.getDay()];
      } else if (name === "CURRENT_MONTH_NAME") {
        return _TimeBasedVariableResolver.monthNames[this._date.getMonth()];
      } else if (name === "CURRENT_MONTH_NAME_SHORT") {
        return _TimeBasedVariableResolver.monthNamesShort[this._date.getMonth()];
      } else if (name === "CURRENT_SECONDS_UNIX") {
        return String(Math.floor(this._date.getTime() / 1e3));
      } else if (name === "CURRENT_TIMEZONE_OFFSET") {
        const rawTimeOffset = this._date.getTimezoneOffset();
        const sign = rawTimeOffset > 0 ? "-" : "+";
        const hours = Math.trunc(Math.abs(rawTimeOffset / 60));
        const hoursString = hours < 10 ? "0" + hours : hours;
        const minutes = Math.abs(rawTimeOffset) - hours * 60;
        const minutesString = minutes < 10 ? "0" + minutes : minutes;
        return sign + hoursString + ":" + minutesString;
      }
      return void 0;
    }
  };
  _TimeBasedVariableResolver.dayNames = [localize(1406, "Sunday"), localize(1407, "Monday"), localize(1408, "Tuesday"), localize(1409, "Wednesday"), localize(1410, "Thursday"), localize(1411, "Friday"), localize(1412, "Saturday")];
  _TimeBasedVariableResolver.dayNamesShort = [localize(1413, "Sun"), localize(1414, "Mon"), localize(1415, "Tue"), localize(1416, "Wed"), localize(1417, "Thu"), localize(1418, "Fri"), localize(1419, "Sat")];
  _TimeBasedVariableResolver.monthNames = [localize(1420, "January"), localize(1421, "February"), localize(1422, "March"), localize(1423, "April"), localize(1424, "May"), localize(1425, "June"), localize(1426, "July"), localize(1427, "August"), localize(1428, "September"), localize(1429, "October"), localize(1430, "November"), localize(1431, "December")];
  _TimeBasedVariableResolver.monthNamesShort = [localize(1432, "Jan"), localize(1433, "Feb"), localize(1434, "Mar"), localize(1435, "Apr"), localize(1436, "May"), localize(1437, "Jun"), localize(1438, "Jul"), localize(1439, "Aug"), localize(1440, "Sep"), localize(1441, "Oct"), localize(1442, "Nov"), localize(1443, "Dec")];
  let TimeBasedVariableResolver = _TimeBasedVariableResolver;
  class WorkspaceBasedVariableResolver {
    constructor(_workspaceService) {
      this._workspaceService = _workspaceService;
    }
    resolve(variable) {
      if (!this._workspaceService) {
        return void 0;
      }
      const workspaceIdentifier = toWorkspaceIdentifier(this._workspaceService.getWorkspace());
      if (isEmptyWorkspaceIdentifier(workspaceIdentifier)) {
        return void 0;
      }
      if (variable.name === "WORKSPACE_NAME") {
        return this._resolveWorkspaceName(workspaceIdentifier);
      } else if (variable.name === "WORKSPACE_FOLDER") {
        return this._resoveWorkspacePath(workspaceIdentifier);
      }
      return void 0;
    }
    _resolveWorkspaceName(workspaceIdentifier) {
      if (isSingleFolderWorkspaceIdentifier(workspaceIdentifier)) {
        return basename$1(workspaceIdentifier.uri.path);
      }
      let filename = basename$1(workspaceIdentifier.configPath.path);
      if (filename.endsWith(WORKSPACE_EXTENSION)) {
        filename = filename.substr(0, filename.length - WORKSPACE_EXTENSION.length - 1);
      }
      return filename;
    }
    _resoveWorkspacePath(workspaceIdentifier) {
      if (isSingleFolderWorkspaceIdentifier(workspaceIdentifier)) {
        return normalizeDriveLetter(workspaceIdentifier.uri.fsPath);
      }
      const filename = basename$1(workspaceIdentifier.configPath.path);
      let folderpath = workspaceIdentifier.configPath.fsPath;
      if (folderpath.endsWith(filename)) {
        folderpath = folderpath.substr(0, folderpath.length - filename.length - 1);
      }
      return folderpath ? normalizeDriveLetter(folderpath) : "/";
    }
  }
  class RandomBasedVariableResolver {
    resolve(variable) {
      const { name } = variable;
      if (name === "RANDOM") {
        return Math.random().toString().slice(-6);
      } else if (name === "RANDOM_HEX") {
        return Math.random().toString(16).slice(-6);
      } else if (name === "UUID") {
        return generateUuid();
      }
      return void 0;
    }
  }
  var __decorate$1z = 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$1y = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  var SnippetSession_1;
  const _OneSnippet = class _OneSnippet {
    constructor(_editor, _snippet, _snippetLineLeadingWhitespace) {
      this._editor = _editor;
      this._snippet = _snippet;
      this._snippetLineLeadingWhitespace = _snippetLineLeadingWhitespace;
      this._offset = -1;
      this._nestingLevel = 1;
      this._placeholderGroups = groupBy(_snippet.placeholders, Placeholder.compareByIndex);
      this._placeholderGroupsIdx = -1;
    }
    initialize(textChange) {
      this._offset = textChange.newPosition;
    }
    dispose() {
      if (this._placeholderDecorations) {
        this._editor.removeDecorations([...this._placeholderDecorations.values()]);
      }
      this._placeholderGroups.length = 0;
    }
    _initDecorations() {
      if (this._offset === -1) {
        throw new Error(`Snippet not initialized!`);
      }
      if (this._placeholderDecorations) {
        return;
      }
      this._placeholderDecorations = /* @__PURE__ */ new Map();
      const model = this._editor.getModel();
      this._editor.changeDecorations((accessor) => {
        for (const placeholder of this._snippet.placeholders) {
          const placeholderOffset = this._snippet.offset(placeholder);
          const placeholderLen = this._snippet.fullLen(placeholder);
          const range2 = Range$2.fromPositions(model.getPositionAt(this._offset + placeholderOffset), model.getPositionAt(this._offset + placeholderOffset + placeholderLen));
          const options = placeholder.isFinalTabstop ? _OneSnippet._decor.inactiveFinal : _OneSnippet._decor.inactive;
          const handle = accessor.addDecoration(range2, options);
          this._placeholderDecorations.set(placeholder, handle);
        }
      });
    }
    move(fwd) {
      if (!this._editor.hasModel()) {
        return [];
      }
      this._initDecorations();
      if (this._placeholderGroupsIdx >= 0) {
        const operations = [];
        for (const placeholder of this._placeholderGroups[this._placeholderGroupsIdx]) {
          if (placeholder.transform) {
            const id = this._placeholderDecorations.get(placeholder);
            const range2 = this._editor.getModel().getDecorationRange(id);
            const currentValue = this._editor.getModel().getValueInRange(range2);
            const transformedValueLines = placeholder.transform.resolve(currentValue).split(/\r\n|\r|\n/);
            for (let i2 = 1; i2 < transformedValueLines.length; i2++) {
              transformedValueLines[i2] = this._editor.getModel().normalizeIndentation(this._snippetLineLeadingWhitespace + transformedValueLines[i2]);
            }
            operations.push(EditOperation.replace(range2, transformedValueLines.join(this._editor.getModel().getEOL())));
          }
        }
        if (operations.length > 0) {
          this._editor.executeEdits("snippet.placeholderTransform", operations);
        }
      }
      let couldSkipThisPlaceholder = false;
      if (fwd === true && this._placeholderGroupsIdx < this._placeholderGroups.length - 1) {
        this._placeholderGroupsIdx += 1;
        couldSkipThisPlaceholder = true;
      } else if (fwd === false && this._placeholderGroupsIdx > 0) {
        this._placeholderGroupsIdx -= 1;
        couldSkipThisPlaceholder = true;
      } else ;
      const newSelections = this._editor.getModel().changeDecorations((accessor) => {
        const activePlaceholders = /* @__PURE__ */ new Set();
        const selections = [];
        for (const placeholder of this._placeholderGroups[this._placeholderGroupsIdx]) {
          const id = this._placeholderDecorations.get(placeholder);
          const range2 = this._editor.getModel().getDecorationRange(id);
          selections.push(new Selection$1(range2.startLineNumber, range2.startColumn, range2.endLineNumber, range2.endColumn));
          couldSkipThisPlaceholder = couldSkipThisPlaceholder && this._hasPlaceholderBeenCollapsed(placeholder);
          accessor.changeDecorationOptions(id, placeholder.isFinalTabstop ? _OneSnippet._decor.activeFinal : _OneSnippet._decor.active);
          activePlaceholders.add(placeholder);
          for (const enclosingPlaceholder of this._snippet.enclosingPlaceholders(placeholder)) {
            const id2 = this._placeholderDecorations.get(enclosingPlaceholder);
            accessor.changeDecorationOptions(id2, enclosingPlaceholder.isFinalTabstop ? _OneSnippet._decor.activeFinal : _OneSnippet._decor.active);
            activePlaceholders.add(enclosingPlaceholder);
          }
        }
        for (const [placeholder, id] of this._placeholderDecorations) {
          if (!activePlaceholders.has(placeholder)) {
            accessor.changeDecorationOptions(id, placeholder.isFinalTabstop ? _OneSnippet._decor.inactiveFinal : _OneSnippet._decor.inactive);
          }
        }
        return selections;
      });
      return !couldSkipThisPlaceholder ? newSelections ?? [] : this.move(fwd);
    }
    _hasPlaceholderBeenCollapsed(placeholder) {
      let marker = placeholder;
      while (marker) {
        if (marker instanceof Placeholder) {
          const id = this._placeholderDecorations.get(marker);
          const range2 = this._editor.getModel().getDecorationRange(id);
          if (range2.isEmpty() && marker.toString().length > 0) {
            return true;
          }
        }
        marker = marker.parent;
      }
      return false;
    }
    get isAtFirstPlaceholder() {
      return this._placeholderGroupsIdx <= 0 || this._placeholderGroups.length === 0;
    }
    get isAtLastPlaceholder() {
      return this._placeholderGroupsIdx === this._placeholderGroups.length - 1;
    }
    get hasPlaceholder() {
      return this._snippet.placeholders.length > 0;
    }
    /**
     * A snippet is trivial when it has no placeholder or only a final placeholder at
     * its very end
     */
    get isTrivialSnippet() {
      if (this._snippet.placeholders.length === 0) {
        return true;
      }
      if (this._snippet.placeholders.length === 1) {
        const [placeholder] = this._snippet.placeholders;
        if (placeholder.isFinalTabstop) {
          if (this._snippet.rightMostDescendant === placeholder) {
            return true;
          }
        }
      }
      return false;
    }
    computePossibleSelections() {
      const result = /* @__PURE__ */ new Map();
      for (const placeholdersWithEqualIndex of this._placeholderGroups) {
        let ranges;
        for (const placeholder of placeholdersWithEqualIndex) {
          if (placeholder.isFinalTabstop) {
            break;
          }
          if (!ranges) {
            ranges = [];
            result.set(placeholder.index, ranges);
          }
          const id = this._placeholderDecorations.get(placeholder);
          const range2 = this._editor.getModel().getDecorationRange(id);
          if (!range2) {
            result.delete(placeholder.index);
            break;
          }
          ranges.push(range2);
        }
      }
      return result;
    }
    get activeChoice() {
      if (!this._placeholderDecorations) {
        return void 0;
      }
      const placeholder = this._placeholderGroups[this._placeholderGroupsIdx][0];
      if (!placeholder?.choice) {
        return void 0;
      }
      const id = this._placeholderDecorations.get(placeholder);
      if (!id) {
        return void 0;
      }
      const range2 = this._editor.getModel().getDecorationRange(id);
      if (!range2) {
        return void 0;
      }
      return { range: range2, choice: placeholder.choice };
    }
    get hasChoice() {
      let result = false;
      this._snippet.walk((marker) => {
        result = marker instanceof Choice;
        return !result;
      });
      return result;
    }
    merge(others) {
      const model = this._editor.getModel();
      this._nestingLevel *= 10;
      this._editor.changeDecorations((accessor) => {
        for (const placeholder of this._placeholderGroups[this._placeholderGroupsIdx]) {
          const nested = others.shift();
          console.assert(nested._offset !== -1);
          console.assert(!nested._placeholderDecorations);
          const indexLastPlaceholder = nested._snippet.placeholderInfo.last.index;
          for (const nestedPlaceholder of nested._snippet.placeholderInfo.all) {
            if (nestedPlaceholder.isFinalTabstop) {
              nestedPlaceholder.index = placeholder.index + (indexLastPlaceholder + 1) / this._nestingLevel;
            } else {
              nestedPlaceholder.index = placeholder.index + nestedPlaceholder.index / this._nestingLevel;
            }
          }
          this._snippet.replace(placeholder, nested._snippet.children);
          const id = this._placeholderDecorations.get(placeholder);
          accessor.removeDecoration(id);
          this._placeholderDecorations.delete(placeholder);
          for (const placeholder2 of nested._snippet.placeholders) {
            const placeholderOffset = nested._snippet.offset(placeholder2);
            const placeholderLen = nested._snippet.fullLen(placeholder2);
            const range2 = Range$2.fromPositions(model.getPositionAt(nested._offset + placeholderOffset), model.getPositionAt(nested._offset + placeholderOffset + placeholderLen));
            const handle = accessor.addDecoration(range2, _OneSnippet._decor.inactive);
            this._placeholderDecorations.set(placeholder2, handle);
          }
        }
        this._placeholderGroups = groupBy(this._snippet.placeholders, Placeholder.compareByIndex);
      });
    }
  };
  _OneSnippet._decor = {
    active: ModelDecorationOptions.register({ description: "snippet-placeholder-1", stickiness: 0, className: "snippet-placeholder" }),
    inactive: ModelDecorationOptions.register({ description: "snippet-placeholder-2", stickiness: 1, className: "snippet-placeholder" }),
    activeFinal: ModelDecorationOptions.register({ description: "snippet-placeholder-3", stickiness: 1, className: "finish-snippet-placeholder" }),
    inactiveFinal: ModelDecorationOptions.register({ description: "snippet-placeholder-4", stickiness: 1, className: "finish-snippet-placeholder" })
  };
  let OneSnippet = _OneSnippet;
  const _defaultOptions$1 = {
    overwriteBefore: 0,
    overwriteAfter: 0,
    adjustWhitespace: true,
    clipboardText: void 0,
    overtypingCapturer: void 0
  };
  let SnippetSession = SnippetSession_1 = class SnippetSession {
    static adjustWhitespace(model, position, adjustIndentation, snippet, filter) {
      const line = model.getLineContent(position.lineNumber);
      const lineLeadingWhitespace = getLeadingWhitespace(line, 0, position.column - 1);
      let snippetTextString;
      snippet.walk((marker) => {
        if (!(marker instanceof Text) || marker.parent instanceof Choice) {
          return true;
        }
        if (filter && !filter.has(marker)) {
          return true;
        }
        const lines = marker.value.split(/\r\n|\r|\n/);
        if (adjustIndentation) {
          const offset = snippet.offset(marker);
          if (offset === 0) {
            lines[0] = model.normalizeIndentation(lines[0]);
          } else {
            snippetTextString = snippetTextString ?? snippet.toString();
            const prevChar = snippetTextString.charCodeAt(offset - 1);
            if (prevChar === 10 || prevChar === 13) {
              lines[0] = model.normalizeIndentation(lineLeadingWhitespace + lines[0]);
            }
          }
          for (let i2 = 1; i2 < lines.length; i2++) {
            lines[i2] = model.normalizeIndentation(lineLeadingWhitespace + lines[i2]);
          }
        }
        const newValue = lines.join(model.getEOL());
        if (newValue !== marker.value) {
          marker.parent.replace(marker, [new Text(newValue)]);
          snippetTextString = void 0;
        }
        return true;
      });
      return lineLeadingWhitespace;
    }
    static adjustSelection(model, selection, overwriteBefore, overwriteAfter) {
      if (overwriteBefore !== 0 || overwriteAfter !== 0) {
        const { positionLineNumber, positionColumn } = selection;
        const positionColumnBefore = positionColumn - overwriteBefore;
        const positionColumnAfter = positionColumn + overwriteAfter;
        const range2 = model.validateRange({
          startLineNumber: positionLineNumber,
          startColumn: positionColumnBefore,
          endLineNumber: positionLineNumber,
          endColumn: positionColumnAfter
        });
        selection = Selection$1.createWithDirection(range2.startLineNumber, range2.startColumn, range2.endLineNumber, range2.endColumn, selection.getDirection());
      }
      return selection;
    }
    static createEditsAndSnippetsFromSelections(editor2, template, overwriteBefore, overwriteAfter, enforceFinalTabstop, adjustWhitespace, clipboardText, overtypingCapturer, languageConfigurationService) {
      const edits = [];
      const snippets = [];
      if (!editor2.hasModel()) {
        return { edits, snippets };
      }
      const model = editor2.getModel();
      const workspaceService = editor2.invokeWithinContext((accessor) => accessor.get(IWorkspaceContextService));
      const modelBasedVariableResolver = editor2.invokeWithinContext((accessor) => new ModelBasedVariableResolver(accessor.get(ILabelService), model));
      const readClipboardText = () => clipboardText;
      const firstBeforeText = model.getValueInRange(SnippetSession_1.adjustSelection(model, editor2.getSelection(), overwriteBefore, 0));
      const firstAfterText = model.getValueInRange(SnippetSession_1.adjustSelection(model, editor2.getSelection(), 0, overwriteAfter));
      const firstLineFirstNonWhitespace = model.getLineFirstNonWhitespaceColumn(editor2.getSelection().positionLineNumber);
      const indexedSelections = editor2.getSelections().map((selection, idx) => ({ selection, idx })).sort((a, b) => Range$2.compareRangesUsingStarts(a.selection, b.selection));
      for (const { selection, idx } of indexedSelections) {
        let extensionBefore = SnippetSession_1.adjustSelection(model, selection, overwriteBefore, 0);
        let extensionAfter = SnippetSession_1.adjustSelection(model, selection, 0, overwriteAfter);
        if (firstBeforeText !== model.getValueInRange(extensionBefore)) {
          extensionBefore = selection;
        }
        if (firstAfterText !== model.getValueInRange(extensionAfter)) {
          extensionAfter = selection;
        }
        const snippetSelection = selection.setStartPosition(extensionBefore.startLineNumber, extensionBefore.startColumn).setEndPosition(extensionAfter.endLineNumber, extensionAfter.endColumn);
        const snippet = new SnippetParser().parse(template, true, enforceFinalTabstop);
        const start = snippetSelection.getStartPosition();
        const snippetLineLeadingWhitespace = SnippetSession_1.adjustWhitespace(model, start, adjustWhitespace || idx > 0 && firstLineFirstNonWhitespace !== model.getLineFirstNonWhitespaceColumn(selection.positionLineNumber), snippet);
        snippet.resolveVariables(new CompositeSnippetVariableResolver([
          modelBasedVariableResolver,
          new ClipboardBasedVariableResolver(readClipboardText, idx, indexedSelections.length, editor2.getOption(
            88
            /* EditorOption.multiCursorPaste */
          ) === "spread"),
          new SelectionBasedVariableResolver(model, selection, idx, overtypingCapturer),
          new CommentBasedVariableResolver(model, selection, languageConfigurationService),
          new TimeBasedVariableResolver(),
          new WorkspaceBasedVariableResolver(workspaceService),
          new RandomBasedVariableResolver()
        ]));
        edits[idx] = EditOperation.replace(snippetSelection, snippet.toString());
        edits[idx].identifier = { major: idx, minor: 0 };
        edits[idx]._isTracked = true;
        snippets[idx] = new OneSnippet(editor2, snippet, snippetLineLeadingWhitespace);
      }
      return { edits, snippets };
    }
    static createEditsAndSnippetsFromEdits(editor2, snippetEdits, enforceFinalTabstop, adjustWhitespace, clipboardText, overtypingCapturer, languageConfigurationService) {
      if (!editor2.hasModel() || snippetEdits.length === 0) {
        return { edits: [], snippets: [] };
      }
      const edits = [];
      const model = editor2.getModel();
      const parser = new SnippetParser();
      const snippet = new TextmateSnippet();
      const resolver = new CompositeSnippetVariableResolver([
        editor2.invokeWithinContext((accessor) => new ModelBasedVariableResolver(accessor.get(ILabelService), model)),
        new ClipboardBasedVariableResolver(() => clipboardText, 0, editor2.getSelections().length, editor2.getOption(
          88
          /* EditorOption.multiCursorPaste */
        ) === "spread"),
        new SelectionBasedVariableResolver(model, editor2.getSelection(), 0, overtypingCapturer),
        new CommentBasedVariableResolver(model, editor2.getSelection(), languageConfigurationService),
        new TimeBasedVariableResolver(),
        new WorkspaceBasedVariableResolver(editor2.invokeWithinContext((accessor) => accessor.get(IWorkspaceContextService))),
        new RandomBasedVariableResolver()
      ]);
      snippetEdits = snippetEdits.sort((a, b) => Range$2.compareRangesUsingStarts(a.range, b.range));
      let offset = 0;
      for (let i2 = 0; i2 < snippetEdits.length; i2++) {
        const { range: range2, template, keepWhitespace } = snippetEdits[i2];
        if (i2 > 0) {
          const lastRange = snippetEdits[i2 - 1].range;
          const textRange = Range$2.fromPositions(lastRange.getEndPosition(), range2.getStartPosition());
          const textNode = new Text(model.getValueInRange(textRange));
          snippet.appendChild(textNode);
          offset += textNode.value.length;
        }
        const newNodes = parser.parseFragment(template, snippet);
        SnippetSession_1.adjustWhitespace(model, range2.getStartPosition(), keepWhitespace !== void 0 ? !keepWhitespace : adjustWhitespace, snippet, new Set(newNodes));
        snippet.resolveVariables(resolver);
        const snippetText = snippet.toString();
        const snippetFragmentText = snippetText.slice(offset);
        offset = snippetText.length;
        const edit2 = EditOperation.replace(range2, snippetFragmentText);
        edit2.identifier = { major: i2, minor: 0 };
        edit2._isTracked = true;
        edits.push(edit2);
      }
      parser.ensureFinalTabstop(snippet, enforceFinalTabstop, true);
      return {
        edits,
        snippets: [new OneSnippet(editor2, snippet, "")]
      };
    }
    constructor(_editor, _template, _options = _defaultOptions$1, _languageConfigurationService) {
      this._editor = _editor;
      this._template = _template;
      this._options = _options;
      this._languageConfigurationService = _languageConfigurationService;
      this._templateMerges = [];
      this._snippets = [];
    }
    dispose() {
      dispose(this._snippets);
    }
    _logInfo() {
      return `template="${this._template}", merged_templates="${this._templateMerges.join(" -> ")}"`;
    }
    insert(editReason) {
      if (!this._editor.hasModel()) {
        return;
      }
      const { edits, snippets } = typeof this._template === "string" ? SnippetSession_1.createEditsAndSnippetsFromSelections(this._editor, this._template, this._options.overwriteBefore, this._options.overwriteAfter, false, this._options.adjustWhitespace, this._options.clipboardText, this._options.overtypingCapturer, this._languageConfigurationService) : SnippetSession_1.createEditsAndSnippetsFromEdits(this._editor, this._template, false, this._options.adjustWhitespace, this._options.clipboardText, this._options.overtypingCapturer, this._languageConfigurationService);
      this._snippets = snippets;
      this._editor.executeEdits(editReason ?? EditSources.snippet(), edits, (_undoEdits) => {
        const undoEdits = _undoEdits.filter((edit2) => !!edit2.identifier);
        for (let idx = 0; idx < snippets.length; idx++) {
          snippets[idx].initialize(undoEdits[idx].textChange);
        }
        if (this._snippets[0].hasPlaceholder) {
          return this._move(true);
        } else {
          return undoEdits.map((edit2) => Selection$1.fromPositions(edit2.range.getEndPosition()));
        }
      });
      this._editor.revealRange(this._editor.getSelections()[0]);
    }
    merge(template, options = _defaultOptions$1) {
      if (!this._editor.hasModel()) {
        return;
      }
      this._templateMerges.push([this._snippets[0]._nestingLevel, this._snippets[0]._placeholderGroupsIdx, template]);
      const { edits, snippets } = SnippetSession_1.createEditsAndSnippetsFromSelections(this._editor, template, options.overwriteBefore, options.overwriteAfter, true, options.adjustWhitespace, options.clipboardText, options.overtypingCapturer, this._languageConfigurationService);
      this._editor.executeEdits("snippet", edits, (_undoEdits) => {
        const undoEdits = _undoEdits.filter((edit2) => !!edit2.identifier);
        for (let idx = 0; idx < snippets.length; idx++) {
          snippets[idx].initialize(undoEdits[idx].textChange);
        }
        const isTrivialSnippet = snippets[0].isTrivialSnippet;
        if (!isTrivialSnippet) {
          for (const snippet of this._snippets) {
            snippet.merge(snippets);
          }
          console.assert(snippets.length === 0);
        }
        if (this._snippets[0].hasPlaceholder && !isTrivialSnippet) {
          return this._move(void 0);
        } else {
          return undoEdits.map((edit2) => Selection$1.fromPositions(edit2.range.getEndPosition()));
        }
      });
    }
    next() {
      const newSelections = this._move(true);
      this._editor.setSelections(newSelections);
      this._editor.revealPositionInCenterIfOutsideViewport(newSelections[0].getPosition());
    }
    prev() {
      const newSelections = this._move(false);
      this._editor.setSelections(newSelections);
      this._editor.revealPositionInCenterIfOutsideViewport(newSelections[0].getPosition());
    }
    _move(fwd) {
      const selections = [];
      for (const snippet of this._snippets) {
        const oneSelection = snippet.move(fwd);
        selections.push(...oneSelection);
      }
      return selections;
    }
    get isAtFirstPlaceholder() {
      return this._snippets[0].isAtFirstPlaceholder;
    }
    get isAtLastPlaceholder() {
      return this._snippets[0].isAtLastPlaceholder;
    }
    get hasPlaceholder() {
      return this._snippets[0].hasPlaceholder;
    }
    get hasChoice() {
      return this._snippets[0].hasChoice;
    }
    get activeChoice() {
      return this._snippets[0].activeChoice;
    }
    isSelectionWithinPlaceholders() {
      if (!this.hasPlaceholder) {
        return false;
      }
      const selections = this._editor.getSelections();
      if (selections.length < this._snippets.length) {
        return false;
      }
      const allPossibleSelections = /* @__PURE__ */ new Map();
      for (const snippet of this._snippets) {
        const possibleSelections = snippet.computePossibleSelections();
        if (allPossibleSelections.size === 0) {
          for (const [index, ranges] of possibleSelections) {
            ranges.sort(Range$2.compareRangesUsingStarts);
            for (const selection of selections) {
              if (ranges[0].containsRange(selection)) {
                allPossibleSelections.set(index, []);
                break;
              }
            }
          }
        }
        if (allPossibleSelections.size === 0) {
          return false;
        }
        allPossibleSelections.forEach((array2, index) => {
          array2.push(...possibleSelections.get(index));
        });
      }
      selections.sort(Range$2.compareRangesUsingStarts);
      for (const [index, ranges] of allPossibleSelections) {
        if (ranges.length !== selections.length) {
          allPossibleSelections.delete(index);
          continue;
        }
        ranges.sort(Range$2.compareRangesUsingStarts);
        for (let i2 = 0; i2 < ranges.length; i2++) {
          if (!ranges[i2].containsRange(selections[i2])) {
            allPossibleSelections.delete(index);
            continue;
          }
        }
      }
      return allPossibleSelections.size > 0;
    }
  };
  SnippetSession = SnippetSession_1 = __decorate$1z([
    __param$1y(3, ILanguageConfigurationService)
  ], SnippetSession);
  var __decorate$1y = 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$1x = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  var SnippetController2_1;
  const _defaultOptions = {
    overwriteBefore: 0,
    overwriteAfter: 0,
    undoStopBefore: true,
    undoStopAfter: true,
    adjustWhitespace: true,
    clipboardText: void 0,
    overtypingCapturer: void 0
  };
  let SnippetController2 = (_$2 = class {
    static get(editor2) {
      return editor2.getContribution(SnippetController2_1.ID);
    }
    constructor(_editor, _logService, _languageFeaturesService, contextKeyService, _languageConfigurationService) {
      this._editor = _editor;
      this._logService = _logService;
      this._languageFeaturesService = _languageFeaturesService;
      this._languageConfigurationService = _languageConfigurationService;
      this._inSnippetObservable = observableValue(this, false);
      this._snippetListener = new DisposableStore();
      this._modelVersionId = -1;
      this._inSnippet = SnippetController2_1.InSnippetMode.bindTo(contextKeyService);
      this._hasNextTabstop = SnippetController2_1.HasNextTabstop.bindTo(contextKeyService);
      this._hasPrevTabstop = SnippetController2_1.HasPrevTabstop.bindTo(contextKeyService);
    }
    dispose() {
      this._inSnippet.reset();
      this._inSnippetObservable.set(false, void 0);
      this._hasPrevTabstop.reset();
      this._hasNextTabstop.reset();
      this._session?.dispose();
      this._snippetListener.dispose();
    }
    insert(template, opts) {
      try {
        this._doInsert(template, typeof opts === "undefined" ? _defaultOptions : { ..._defaultOptions, ...opts });
      } catch (e) {
        this.cancel();
        this._logService.error(e);
        this._logService.error("snippet_error");
        this._logService.error("insert_template=", template);
        this._logService.error("existing_template=", this._session ? this._session._logInfo() : "<no_session>");
      }
    }
    _doInsert(template, opts) {
      if (!this._editor.hasModel()) {
        return;
      }
      this._snippetListener.clear();
      if (opts.undoStopBefore) {
        this._editor.getModel().pushStackElement();
      }
      if (this._session && typeof template !== "string") {
        this.cancel();
      }
      if (!this._session) {
        this._modelVersionId = this._editor.getModel().getAlternativeVersionId();
        this._session = new SnippetSession(this._editor, template, opts, this._languageConfigurationService);
        this._session.insert(opts.reason);
      } else {
        assertType(typeof template === "string");
        this._session.merge(template, opts);
      }
      if (opts.undoStopAfter) {
        this._editor.getModel().pushStackElement();
      }
      if (this._session?.hasChoice) {
        const provider = {
          _debugDisplayName: "snippetChoiceCompletions",
          provideCompletionItems: (model2, position) => {
            if (!this._session || model2 !== this._editor.getModel() || !Position$1.equals(this._editor.getPosition(), position)) {
              return void 0;
            }
            const { activeChoice } = this._session;
            if (!activeChoice || activeChoice.choice.options.length === 0) {
              return void 0;
            }
            const word = model2.getValueInRange(activeChoice.range);
            const isAnyOfOptions = Boolean(activeChoice.choice.options.find((o) => o.value === word));
            const suggestions = [];
            for (let i2 = 0; i2 < activeChoice.choice.options.length; i2++) {
              const option2 = activeChoice.choice.options[i2];
              suggestions.push({
                kind: 13,
                label: option2.value,
                insertText: option2.value,
                sortText: "a".repeat(i2 + 1),
                range: activeChoice.range,
                filterText: isAnyOfOptions ? `${word}_${option2.value}` : void 0,
                command: { id: "jumpToNextSnippetPlaceholder", title: localize(1405, "Go to next placeholder...") }
              });
            }
            return { suggestions };
          }
        };
        const model = this._editor.getModel();
        let registration;
        let isRegistered = false;
        const disable = () => {
          registration?.dispose();
          isRegistered = false;
        };
        const enable = () => {
          if (!isRegistered) {
            registration = this._languageFeaturesService.completionProvider.register({
              language: model.getLanguageId(),
              pattern: model.uri.fsPath,
              scheme: model.uri.scheme,
              exclusive: true
            }, provider);
            this._snippetListener.add(registration);
            isRegistered = true;
          }
        };
        this._choiceCompletions = { provider, enable, disable };
      }
      this._updateState();
      this._snippetListener.add(this._editor.onDidChangeModelContent((e) => e.isFlush && this.cancel()));
      this._snippetListener.add(this._editor.onDidChangeModel(() => this.cancel()));
      this._snippetListener.add(this._editor.onDidChangeCursorSelection(() => this._updateState()));
    }
    _updateState() {
      if (!this._session || !this._editor.hasModel()) {
        return;
      }
      if (this._modelVersionId === this._editor.getModel().getAlternativeVersionId()) {
        return this.cancel();
      }
      if (!this._session.hasPlaceholder) {
        return this.cancel();
      }
      if (this._session.isAtLastPlaceholder || !this._session.isSelectionWithinPlaceholders()) {
        this._editor.getModel().pushStackElement();
        return this.cancel();
      }
      this._inSnippet.set(true);
      this._inSnippetObservable.set(true, void 0);
      this._hasPrevTabstop.set(!this._session.isAtFirstPlaceholder);
      this._hasNextTabstop.set(!this._session.isAtLastPlaceholder);
      this._handleChoice();
    }
    _handleChoice() {
      if (!this._session || !this._editor.hasModel()) {
        this._currentChoice = void 0;
        return;
      }
      const { activeChoice } = this._session;
      if (!activeChoice || !this._choiceCompletions) {
        this._choiceCompletions?.disable();
        this._currentChoice = void 0;
        return;
      }
      if (this._currentChoice !== activeChoice.choice) {
        this._currentChoice = activeChoice.choice;
        this._choiceCompletions.enable();
        queueMicrotask(() => {
          showSimpleSuggestions(this._editor, this._choiceCompletions.provider);
        });
      }
    }
    finish() {
      while (this._inSnippet.get()) {
        this.next();
      }
    }
    cancel(resetSelection = false) {
      this._inSnippet.reset();
      this._inSnippetObservable.set(false, void 0);
      this._hasPrevTabstop.reset();
      this._hasNextTabstop.reset();
      this._snippetListener.clear();
      this._currentChoice = void 0;
      this._session?.dispose();
      this._session = void 0;
      this._modelVersionId = -1;
      if (resetSelection) {
        this._editor.setSelections([this._editor.getSelection()]);
      }
    }
    prev() {
      this._session?.prev();
      this._updateState();
    }
    next() {
      this._session?.next();
      this._updateState();
    }
    isInSnippet() {
      return Boolean(this._inSnippet.get());
    }
    get isInSnippetObservable() {
      return this._inSnippetObservable;
    }
  }, SnippetController2_1 = _$2, _$2.ID = "snippetController2", _$2.InSnippetMode = new RawContextKey("inSnippetMode", false, localize(1402, "Whether the editor in current in snippet mode")), _$2.HasNextTabstop = new RawContextKey("hasNextTabstop", false, localize(1403, "Whether there is a next tab stop when in snippet mode")), _$2.HasPrevTabstop = new RawContextKey("hasPrevTabstop", false, localize(1404, "Whether there is a previous tab stop when in snippet mode")), _$2);
  SnippetController2 = SnippetController2_1 = __decorate$1y([
    __param$1x(1, ILogService),
    __param$1x(2, ILanguageFeaturesService),
    __param$1x(3, IContextKeyService),
    __param$1x(4, ILanguageConfigurationService)
  ], SnippetController2);
  registerEditorContribution(
    SnippetController2.ID,
    SnippetController2,
    4
    /* EditorContributionInstantiation.Lazy */
  );
  const CommandCtor = EditorCommand.bindToContribution(SnippetController2.get);
  registerEditorCommand(new CommandCtor({
    id: "jumpToNextSnippetPlaceholder",
    precondition: ContextKeyExpr.and(SnippetController2.InSnippetMode, SnippetController2.HasNextTabstop),
    handler: (ctrl) => ctrl.next(),
    kbOpts: {
      weight: 100 + 30,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 2
      /* KeyCode.Tab */
    }
  }));
  registerEditorCommand(new CommandCtor({
    id: "jumpToPrevSnippetPlaceholder",
    precondition: ContextKeyExpr.and(SnippetController2.InSnippetMode, SnippetController2.HasPrevTabstop),
    handler: (ctrl) => ctrl.prev(),
    kbOpts: {
      weight: 100 + 30,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 1024 | 2
      /* KeyCode.Tab */
    }
  }));
  registerEditorCommand(new CommandCtor({
    id: "leaveSnippet",
    precondition: SnippetController2.InSnippetMode,
    handler: (ctrl) => ctrl.cancel(true),
    kbOpts: {
      weight: 100 + 30,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 9,
      secondary: [
        1024 | 9
        /* KeyCode.Escape */
      ]
    }
  }));
  registerEditorCommand(new CommandCtor({
    id: "acceptSnippet",
    precondition: SnippetController2.InSnippetMode,
    handler: (ctrl) => ctrl.finish()
    // kbOpts: {
    // 	weight: KeybindingWeight.EditorContrib + 30,
    // 	kbExpr: EditorContextKeys.textFocus,
    // 	primary: KeyCode.Enter,
    // }
  }));
  function getPositionOffsetTransformerFromTextModel(textModel) {
    return new PositionOffsetTransformerWithTextModel(textModel);
  }
  class PositionOffsetTransformerWithTextModel extends PositionOffsetTransformerBase {
    constructor(_textModel) {
      super();
      this._textModel = _textModel;
    }
    getOffset(position) {
      return this._textModel.getOffsetAt(position);
    }
    getPosition(offset) {
      return this._textModel.getPositionAt(offset);
    }
  }
  const array = [];
  function getReadonlyEmptyArray() {
    return array;
  }
  function getEndPositionsAfterApplying(edits) {
    const newRanges = getModifiedRangesAfterApplying(edits);
    return newRanges.map((range2) => range2.getEndPosition());
  }
  function getModifiedRangesAfterApplying(edits) {
    const sortPerm = Permutation.createSortPermutation(edits, compareBy((e) => e.range, Range$2.compareRangesUsingStarts));
    const edit2 = new TextEdit(sortPerm.apply(edits));
    const sortedNewRanges = edit2.getNewRanges();
    return sortPerm.inverse().apply(sortedNewRanges);
  }
  function removeTextReplacementCommonSuffixPrefix(edits, textModel) {
    const transformer = getPositionOffsetTransformerFromTextModel(textModel);
    const text2 = textModel.getValue();
    const stringReplacements = edits.map((edit2) => transformer.getStringReplacement(edit2));
    const minimalStringReplacements = stringReplacements.map((replacement) => replacement.removeCommonSuffixPrefix(text2));
    return minimalStringReplacements.map((replacement) => transformer.getTextReplacement(replacement));
  }
  function convertItemsToStableObservables(items, store) {
    const result = observableValue("result", []);
    const innerObservables = [];
    store.add(autorun((reader) => {
      const itemsValue = items.read(reader);
      transaction((tx) => {
        if (itemsValue.length !== innerObservables.length) {
          innerObservables.length = itemsValue.length;
          for (let i2 = 0; i2 < innerObservables.length; i2++) {
            if (!innerObservables[i2]) {
              innerObservables[i2] = observableValue("item", itemsValue[i2]);
            }
          }
          result.set([...innerObservables], tx);
        }
        innerObservables.forEach((o, i2) => o.set(itemsValue[i2], tx));
      });
    }));
    return result;
  }
  class ObservableContextKeyService {
    constructor(_contextKeyService) {
      this._contextKeyService = _contextKeyService;
    }
    bind(key, obs) {
      return bindContextKey(key, this._contextKeyService, obs instanceof Function ? obs : (reader) => obs.read(reader));
    }
  }
  function wait(ms, cancellationToken) {
    return new Promise((resolve2) => {
      let d = void 0;
      const handle = setTimeout(() => {
        if (d) {
          d.dispose();
        }
        resolve2();
      }, ms);
      if (cancellationToken) {
        d = cancellationToken.onCancellationRequested(() => {
          clearTimeout(handle);
          if (d) {
            d.dispose();
          }
          resolve2();
        });
      }
    });
  }
  class AnimatedValue {
    constructor(startValue, endValue, durationMs, _interpolationFunction = easeOutExpo) {
      this.startValue = startValue;
      this.endValue = endValue;
      this.durationMs = durationMs;
      this._interpolationFunction = _interpolationFunction;
      this.startTimeMs = Date.now();
      if (startValue === endValue) {
        this.durationMs = 0;
      }
    }
    isFinished() {
      return Date.now() >= this.startTimeMs + this.durationMs;
    }
    getValue() {
      const timePassed = Date.now() - this.startTimeMs;
      if (timePassed >= this.durationMs) {
        return this.endValue;
      }
      const value = this._interpolationFunction(timePassed, this.startValue, this.endValue - this.startValue, this.durationMs);
      return value;
    }
  }
  function easeOutExpo(passedTime, start, length, totalDuration) {
    return passedTime === totalDuration ? start + length : length * (-Math.pow(2, -10 * passedTime / totalDuration) + 1) + start;
  }
  function easeOutCubic(passedTime, start, length, totalDuration) {
    return length * ((passedTime = passedTime / totalDuration - 1) * passedTime * passedTime + 1) + start;
  }
  class ObservableAnimatedValue {
    constructor(initialValue) {
      this._value = observableValue(this, initialValue);
    }
    getValue(reader) {
      const value = this._value.read(reader);
      if (!value.isFinished()) {
        AnimationFrameScheduler.instance.invalidateOnNextAnimationFrame(reader);
      }
      return value.getValue();
    }
  }
  const _AnimationFrameScheduler = class _AnimationFrameScheduler {
    constructor() {
      this._counter = observableSignal(this);
      this._isScheduled = false;
    }
    invalidateOnNextAnimationFrame(reader) {
      this._counter.read(reader);
      if (!this._isScheduled) {
        this._isScheduled = true;
        getActiveWindow().requestAnimationFrame(() => {
          this._isScheduled = false;
          this._update();
        });
      }
    }
    _update() {
      this._counter.trigger(void 0);
    }
  };
  _AnimationFrameScheduler.instance = new _AnimationFrameScheduler();
  let AnimationFrameScheduler = _AnimationFrameScheduler;
  class GhostText {
    constructor(lineNumber, parts) {
      this.lineNumber = lineNumber;
      this.parts = parts;
      assertFn(() => checkAdjacentItems(parts, (p1, p2) => p1.column <= p2.column));
    }
    equals(other) {
      return this.lineNumber === other.lineNumber && this.parts.length === other.parts.length && this.parts.every((part, index) => part.equals(other.parts[index]));
    }
    renderForScreenReader(lineText) {
      if (this.parts.length === 0) {
        return "";
      }
      const lastPart = this.parts[this.parts.length - 1];
      const cappedLineText = lineText.substr(0, lastPart.column - 1);
      const text2 = new TextEdit([
        ...this.parts.map((p) => new TextReplacement(Range$2.fromPositions(new Position$1(1, p.column)), p.lines.map((line) => line.line).join("\n")))
      ]).applyToString(cappedLineText);
      return text2.substring(this.parts[0].column - 1);
    }
    isEmpty() {
      return this.parts.every((p) => p.lines.length === 0);
    }
    get lineCount() {
      return 1 + this.parts.reduce((r, p) => r + p.lines.length - 1, 0);
    }
  }
  class GhostTextPart {
    constructor(column, text2, preview, _inlineDecorations = []) {
      this.column = column;
      this.text = text2;
      this.preview = preview;
      this._inlineDecorations = _inlineDecorations;
      this.lines = splitLines(this.text).map((line, i2) => ({
        line,
        lineDecorations: LineDecoration.filter(this._inlineDecorations, i2 + 1, 1, line.length + 1)
      }));
    }
    equals(other) {
      return this.column === other.column && this.lines.length === other.lines.length && this.lines.every((line, index) => line.line === other.lines[index].line && LineDecoration.equalsArr(line.lineDecorations, other.lines[index].lineDecorations));
    }
  }
  class GhostTextReplacement {
    constructor(lineNumber, columnRange, text2, additionalReservedLineCount = 0) {
      this.lineNumber = lineNumber;
      this.columnRange = columnRange;
      this.text = text2;
      this.additionalReservedLineCount = additionalReservedLineCount;
      this.parts = [
        new GhostTextPart(this.columnRange.endColumnExclusive, this.text, false)
      ];
      this.newLines = splitLines(this.text);
    }
    renderForScreenReader(_lineText) {
      return this.newLines.join("\n");
    }
    get lineCount() {
      return this.newLines.length;
    }
    isEmpty() {
      return this.parts.every((p) => p.lines.length === 0);
    }
    equals(other) {
      return this.lineNumber === other.lineNumber && this.columnRange.equals(other.columnRange) && this.newLines.length === other.newLines.length && this.newLines.every((line, index) => line === other.newLines[index]) && this.additionalReservedLineCount === other.additionalReservedLineCount;
    }
  }
  function ghostTextsOrReplacementsEqual(a, b) {
    return equals$1(a, b, ghostTextOrReplacementEquals);
  }
  function ghostTextOrReplacementEquals(a, b) {
    if (a === b) {
      return true;
    }
    if (!a || !b) {
      return false;
    }
    if (a instanceof GhostText && b instanceof GhostText) {
      return a.equals(b);
    }
    if (a instanceof GhostTextReplacement && b instanceof GhostTextReplacement) {
      return a.equals(b);
    }
    return false;
  }
  function singleTextRemoveCommonPrefix(edit2, model, validModelRange) {
    const modelRange = validModelRange ? edit2.range.intersectRanges(validModelRange) : edit2.range;
    if (!modelRange) {
      return edit2;
    }
    const normalizedText = edit2.text.replaceAll("\r\n", "\n");
    const valueToReplace = model.getValueInRange(
      modelRange,
      1
      /* EndOfLinePreference.LF */
    );
    const commonPrefixLen = commonPrefixLength(valueToReplace, normalizedText);
    const start = TextLength.ofText(valueToReplace.substring(0, commonPrefixLen)).addToPosition(edit2.range.getStartPosition());
    const text2 = normalizedText.substring(commonPrefixLen);
    const range2 = Range$2.fromPositions(start, edit2.range.getEndPosition());
    return new TextReplacement(range2, text2);
  }
  function singleTextEditAugments(edit2, base) {
    return edit2.text.startsWith(base.text) && rangeExtends(edit2.range, base.range);
  }
  function rangeExtends(extendingRange, rangeToExtend) {
    return rangeToExtend.getStartPosition().equals(extendingRange.getStartPosition()) && rangeToExtend.getEndPosition().isBeforeOrEqual(extendingRange.getEndPosition());
  }
  function computeGhostText(edit2, model, mode, cursorPosition, previewSuffixLength = 0) {
    let e = singleTextRemoveCommonPrefix(edit2, model);
    if (e.range.endLineNumber !== e.range.startLineNumber) {
      return void 0;
    }
    const sourceLine = model.getLineContent(e.range.startLineNumber);
    const sourceIndentationLength = getLeadingWhitespace(sourceLine).length;
    const suggestionTouchesIndentation = e.range.startColumn - 1 <= sourceIndentationLength;
    if (suggestionTouchesIndentation) {
      const suggestionAddedIndentationLength = getLeadingWhitespace(e.text).length;
      const replacedIndentation = sourceLine.substring(e.range.startColumn - 1, sourceIndentationLength);
      const [startPosition, endPosition] = [e.range.getStartPosition(), e.range.getEndPosition()];
      const newStartPosition = startPosition.column + replacedIndentation.length <= endPosition.column ? startPosition.delta(0, replacedIndentation.length) : endPosition;
      const rangeThatDoesNotReplaceIndentation = Range$2.fromPositions(newStartPosition, endPosition);
      const suggestionWithoutIndentationChange = e.text.startsWith(replacedIndentation) ? e.text.substring(replacedIndentation.length) : e.text.substring(suggestionAddedIndentationLength);
      e = new TextReplacement(rangeThatDoesNotReplaceIndentation, suggestionWithoutIndentationChange);
    }
    const valueToBeReplaced = model.getValueInRange(e.range);
    const changes = cachingDiff(valueToBeReplaced, e.text);
    if (!changes) {
      return void 0;
    }
    const lineNumber = e.range.startLineNumber;
    const parts = new Array();
    if (mode === "prefix") {
      const filteredChanges = changes.filter((c) => c.originalLength === 0);
      if (filteredChanges.length > 1 || filteredChanges.length === 1 && filteredChanges[0].originalStart !== valueToBeReplaced.length) {
        return void 0;
      }
    }
    const previewStartInCompletionText = e.text.length - previewSuffixLength;
    for (const c of changes) {
      const insertColumn = e.range.startColumn + c.originalStart + c.originalLength;
      if (mode === "subwordSmart" && cursorPosition && cursorPosition.lineNumber === e.range.startLineNumber && insertColumn < cursorPosition.column) {
        return void 0;
      }
      if (c.originalLength > 0) {
        return void 0;
      }
      if (c.modifiedLength === 0) {
        continue;
      }
      const modifiedEnd = c.modifiedStart + c.modifiedLength;
      const nonPreviewTextEnd = Math.max(c.modifiedStart, Math.min(modifiedEnd, previewStartInCompletionText));
      const nonPreviewText = e.text.substring(c.modifiedStart, nonPreviewTextEnd);
      const italicText = e.text.substring(nonPreviewTextEnd, Math.max(c.modifiedStart, modifiedEnd));
      if (nonPreviewText.length > 0) {
        parts.push(new GhostTextPart(insertColumn, nonPreviewText, false));
      }
      if (italicText.length > 0) {
        parts.push(new GhostTextPart(insertColumn, italicText, true));
      }
    }
    return new GhostText(lineNumber, parts);
  }
  let lastRequest = void 0;
  function cachingDiff(originalValue, newValue) {
    if (lastRequest?.originalValue === originalValue && lastRequest?.newValue === newValue) {
      return lastRequest?.changes;
    } else {
      let changes = smartDiff(originalValue, newValue, true);
      if (changes) {
        const deletedChars = deletedCharacters(changes);
        if (deletedChars > 0) {
          const newChanges = smartDiff(originalValue, newValue, false);
          if (newChanges && deletedCharacters(newChanges) < deletedChars) {
            changes = newChanges;
          }
        }
      }
      lastRequest = {
        originalValue,
        newValue,
        changes
      };
      return changes;
    }
  }
  function deletedCharacters(changes) {
    let sum2 = 0;
    for (const c of changes) {
      sum2 += c.originalLength;
    }
    return sum2;
  }
  function smartDiff(originalValue, newValue, smartBracketMatching) {
    if (originalValue.length > 5e3 || newValue.length > 5e3) {
      return void 0;
    }
    function getMaxCharCode(val) {
      let maxCharCode2 = 0;
      for (let i2 = 0, len = val.length; i2 < len; i2++) {
        const charCode = val.charCodeAt(i2);
        if (charCode > maxCharCode2) {
          maxCharCode2 = charCode;
        }
      }
      return maxCharCode2;
    }
    const maxCharCode = Math.max(getMaxCharCode(originalValue), getMaxCharCode(newValue));
    function getUniqueCharCode(id) {
      if (id < 0) {
        throw new Error("unexpected");
      }
      return maxCharCode + id + 1;
    }
    function getElements(source) {
      let level = 0;
      let group = 0;
      const characters = new Int32Array(source.length);
      for (let i2 = 0, len = source.length; i2 < len; i2++) {
        if (smartBracketMatching && source[i2] === "(") {
          const id = group * 100 + level;
          characters[i2] = getUniqueCharCode(2 * id);
          level++;
        } else if (smartBracketMatching && source[i2] === ")") {
          level = Math.max(level - 1, 0);
          const id = group * 100 + level;
          characters[i2] = getUniqueCharCode(2 * id + 1);
          if (level === 0) {
            group++;
          }
        } else {
          characters[i2] = source.charCodeAt(i2);
        }
      }
      return characters;
    }
    const elements1 = getElements(originalValue);
    const elements2 = getElements(newValue);
    return new LcsDiff({ getElements: () => elements1 }, { getElements: () => elements2 }).ComputeDiff(false).changes;
  }
  function observableReducerSettable(owner, options) {
    let prevValue = void 0;
    let hasValue = false;
    const d = new DerivedWithSetter(new DebugNameData(owner, void 0, options.update), (reader, changeSummary) => {
      if (!hasValue) {
        prevValue = options.initial instanceof Function ? options.initial() : options.initial;
        hasValue = true;
      }
      const newValue = options.update(reader, prevValue, changeSummary);
      prevValue = newValue;
      return newValue;
    }, options.changeTracker, () => {
      if (hasValue) {
        options.disposeFinal?.(prevValue);
        hasValue = false;
      }
    }, options.equalityComparer ?? strictEquals, (value, tx, change) => {
      if (!hasValue) {
        throw new BugIndicatingError("Can only set when there is a listener! This is to prevent leaks.");
      }
      subtransaction(tx, (tx2) => {
        prevValue = value;
        d.setValue(value, tx2, change);
      });
    }, DebugLocation.ofCaller());
    return d;
  }
  var __decorate$1x = 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$1w = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  class InterceptingTelemetryService {
    constructor(_baseService, _intercept) {
      this._baseService = _baseService;
      this._intercept = _intercept;
    }
    publicLog2(eventName, data) {
      this._intercept(eventName, data);
      this._baseService.publicLog2(eventName, data);
    }
  }
  let DataChannelForwardingTelemetryService = class DataChannelForwardingTelemetryService extends InterceptingTelemetryService {
    constructor(telemetryService, dataChannelService) {
      super(telemetryService, (eventName, data) => {
        let forward = true;
        if (data && shouldForwardToChannel in data) {
          forward = Boolean(data[shouldForwardToChannel]);
        }
        if (forward) {
          dataChannelService.getDataChannel("editTelemetry").sendData({ eventName, data: data ?? {} });
        }
      });
    }
  };
  DataChannelForwardingTelemetryService = __decorate$1x([
    __param$1w(0, ITelemetryService),
    __param$1w(1, IDataChannelService)
  ], DataChannelForwardingTelemetryService);
  const shouldForwardToChannel = Symbol("shouldForwardToChannel");
  function forwardToChannelIf(value) {
    return {
      // This will not be sent via telemetry, it is just a marker
      [shouldForwardToChannel]: value
    };
  }
  function isCopilotLikeExtension(extensionId) {
    if (!extensionId) {
      return false;
    }
    const extIdLowerCase = extensionId.toLowerCase();
    return extIdLowerCase === "github.copilot" || extIdLowerCase === "github.copilot-chat";
  }
  function offsetEditFromContentChanges(contentChanges) {
    const editsArr = contentChanges.map((c) => new StringReplacement(OffsetRange.ofStartAndLength(c.rangeOffset, c.rangeLength), c.text));
    editsArr.reverse();
    const edits = new StringEdit(editsArr);
    return edits;
  }
  function sendInlineCompletionsEndOfLifeTelemetry(dataChannel, endOfLifeSummary) {
    dataChannel.publicLog2("inlineCompletion.endOfLife", endOfLifeSummary);
  }
  const MINIMUM_MATCHING_CHARACTER_LENGTH = 3;
  class LegacyLinesDiffComputer {
    computeDiff(originalLines, modifiedLines, options) {
      const diffComputer = new DiffComputer(originalLines, modifiedLines, {
        maxComputationTime: options.maxComputationTimeMs,
        shouldIgnoreTrimWhitespace: options.ignoreTrimWhitespace,
        shouldComputeCharChanges: true,
        shouldMakePrettyDiff: true,
        shouldPostProcessCharChanges: true
      });
      const result = diffComputer.computeDiff();
      const changes = [];
      let lastChange = null;
      for (const c of result.changes) {
        let originalRange;
        if (c.originalEndLineNumber === 0) {
          originalRange = new LineRange(c.originalStartLineNumber + 1, c.originalStartLineNumber + 1);
        } else {
          originalRange = new LineRange(c.originalStartLineNumber, c.originalEndLineNumber + 1);
        }
        let modifiedRange;
        if (c.modifiedEndLineNumber === 0) {
          modifiedRange = new LineRange(c.modifiedStartLineNumber + 1, c.modifiedStartLineNumber + 1);
        } else {
          modifiedRange = new LineRange(c.modifiedStartLineNumber, c.modifiedEndLineNumber + 1);
        }
        let change = new DetailedLineRangeMapping(originalRange, modifiedRange, c.charChanges?.map((c2) => new RangeMapping(new Range$2(c2.originalStartLineNumber, c2.originalStartColumn, c2.originalEndLineNumber, c2.originalEndColumn), new Range$2(c2.modifiedStartLineNumber, c2.modifiedStartColumn, c2.modifiedEndLineNumber, c2.modifiedEndColumn))));
        if (lastChange) {
          if (lastChange.modified.endLineNumberExclusive === change.modified.startLineNumber || lastChange.original.endLineNumberExclusive === change.original.startLineNumber) {
            change = new DetailedLineRangeMapping(lastChange.original.join(change.original), lastChange.modified.join(change.modified), lastChange.innerChanges && change.innerChanges ? lastChange.innerChanges.concat(change.innerChanges) : void 0);
            changes.pop();
          }
        }
        changes.push(change);
        lastChange = change;
      }
      assertFn(() => {
        return checkAdjacentItems(changes, (m1, m2) => m2.original.startLineNumber - m1.original.endLineNumberExclusive === m2.modified.startLineNumber - m1.modified.endLineNumberExclusive && // There has to be an unchanged line in between (otherwise both diffs should have been joined)
        m1.original.endLineNumberExclusive < m2.original.startLineNumber && m1.modified.endLineNumberExclusive < m2.modified.startLineNumber);
      });
      return new LinesDiff(changes, [], result.quitEarly);
    }
  }
  function computeDiff(originalSequence, modifiedSequence, continueProcessingPredicate, pretty) {
    const diffAlgo = new LcsDiff(originalSequence, modifiedSequence, continueProcessingPredicate);
    return diffAlgo.ComputeDiff(pretty);
  }
  class LineSequence {
    constructor(lines) {
      const startColumns = [];
      const endColumns = [];
      for (let i2 = 0, length = lines.length; i2 < length; i2++) {
        startColumns[i2] = getFirstNonBlankColumn(lines[i2], 1);
        endColumns[i2] = getLastNonBlankColumn(lines[i2], 1);
      }
      this.lines = lines;
      this._startColumns = startColumns;
      this._endColumns = endColumns;
    }
    getElements() {
      const elements = [];
      for (let i2 = 0, len = this.lines.length; i2 < len; i2++) {
        elements[i2] = this.lines[i2].substring(this._startColumns[i2] - 1, this._endColumns[i2] - 1);
      }
      return elements;
    }
    getStrictElement(index) {
      return this.lines[index];
    }
    getStartLineNumber(i2) {
      return i2 + 1;
    }
    getEndLineNumber(i2) {
      return i2 + 1;
    }
    createCharSequence(shouldIgnoreTrimWhitespace, startIndex, endIndex) {
      const charCodes = [];
      const lineNumbers = [];
      const columns = [];
      let len = 0;
      for (let index = startIndex; index <= endIndex; index++) {
        const lineContent = this.lines[index];
        const startColumn = shouldIgnoreTrimWhitespace ? this._startColumns[index] : 1;
        const endColumn = shouldIgnoreTrimWhitespace ? this._endColumns[index] : lineContent.length + 1;
        for (let col = startColumn; col < endColumn; col++) {
          charCodes[len] = lineContent.charCodeAt(col - 1);
          lineNumbers[len] = index + 1;
          columns[len] = col;
          len++;
        }
        if (!shouldIgnoreTrimWhitespace && index < endIndex) {
          charCodes[len] = 10;
          lineNumbers[len] = index + 1;
          columns[len] = lineContent.length + 1;
          len++;
        }
      }
      return new CharSequence(charCodes, lineNumbers, columns);
    }
  }
  class CharSequence {
    constructor(charCodes, lineNumbers, columns) {
      this._charCodes = charCodes;
      this._lineNumbers = lineNumbers;
      this._columns = columns;
    }
    toString() {
      return "[" + this._charCodes.map((s, idx) => (s === 10 ? "\\n" : String.fromCharCode(s)) + `-(${this._lineNumbers[idx]},${this._columns[idx]})`).join(", ") + "]";
    }
    _assertIndex(index, arr) {
      if (index < 0 || index >= arr.length) {
        throw new Error(`Illegal index`);
      }
    }
    getElements() {
      return this._charCodes;
    }
    getStartLineNumber(i2) {
      if (i2 > 0 && i2 === this._lineNumbers.length) {
        return this.getEndLineNumber(i2 - 1);
      }
      this._assertIndex(i2, this._lineNumbers);
      return this._lineNumbers[i2];
    }
    getEndLineNumber(i2) {
      if (i2 === -1) {
        return this.getStartLineNumber(i2 + 1);
      }
      this._assertIndex(i2, this._lineNumbers);
      if (this._charCodes[i2] === 10) {
        return this._lineNumbers[i2] + 1;
      }
      return this._lineNumbers[i2];
    }
    getStartColumn(i2) {
      if (i2 > 0 && i2 === this._columns.length) {
        return this.getEndColumn(i2 - 1);
      }
      this._assertIndex(i2, this._columns);
      return this._columns[i2];
    }
    getEndColumn(i2) {
      if (i2 === -1) {
        return this.getStartColumn(i2 + 1);
      }
      this._assertIndex(i2, this._columns);
      if (this._charCodes[i2] === 10) {
        return 1;
      }
      return this._columns[i2] + 1;
    }
  }
  class CharChange {
    constructor(originalStartLineNumber, originalStartColumn, originalEndLineNumber, originalEndColumn, modifiedStartLineNumber, modifiedStartColumn, modifiedEndLineNumber, modifiedEndColumn) {
      this.originalStartLineNumber = originalStartLineNumber;
      this.originalStartColumn = originalStartColumn;
      this.originalEndLineNumber = originalEndLineNumber;
      this.originalEndColumn = originalEndColumn;
      this.modifiedStartLineNumber = modifiedStartLineNumber;
      this.modifiedStartColumn = modifiedStartColumn;
      this.modifiedEndLineNumber = modifiedEndLineNumber;
      this.modifiedEndColumn = modifiedEndColumn;
    }
    static createFromDiffChange(diffChange, originalCharSequence, modifiedCharSequence) {
      const originalStartLineNumber = originalCharSequence.getStartLineNumber(diffChange.originalStart);
      const originalStartColumn = originalCharSequence.getStartColumn(diffChange.originalStart);
      const originalEndLineNumber = originalCharSequence.getEndLineNumber(diffChange.originalStart + diffChange.originalLength - 1);
      const originalEndColumn = originalCharSequence.getEndColumn(diffChange.originalStart + diffChange.originalLength - 1);
      const modifiedStartLineNumber = modifiedCharSequence.getStartLineNumber(diffChange.modifiedStart);
      const modifiedStartColumn = modifiedCharSequence.getStartColumn(diffChange.modifiedStart);
      const modifiedEndLineNumber = modifiedCharSequence.getEndLineNumber(diffChange.modifiedStart + diffChange.modifiedLength - 1);
      const modifiedEndColumn = modifiedCharSequence.getEndColumn(diffChange.modifiedStart + diffChange.modifiedLength - 1);
      return new CharChange(originalStartLineNumber, originalStartColumn, originalEndLineNumber, originalEndColumn, modifiedStartLineNumber, modifiedStartColumn, modifiedEndLineNumber, modifiedEndColumn);
    }
  }
  function postProcessCharChanges(rawChanges) {
    if (rawChanges.length <= 1) {
      return rawChanges;
    }
    const result = [rawChanges[0]];
    let prevChange = result[0];
    for (let i2 = 1, len = rawChanges.length; i2 < len; i2++) {
      const currChange = rawChanges[i2];
      const originalMatchingLength = currChange.originalStart - (prevChange.originalStart + prevChange.originalLength);
      const modifiedMatchingLength = currChange.modifiedStart - (prevChange.modifiedStart + prevChange.modifiedLength);
      const matchingLength = Math.min(originalMatchingLength, modifiedMatchingLength);
      if (matchingLength < MINIMUM_MATCHING_CHARACTER_LENGTH) {
        prevChange.originalLength = currChange.originalStart + currChange.originalLength - prevChange.originalStart;
        prevChange.modifiedLength = currChange.modifiedStart + currChange.modifiedLength - prevChange.modifiedStart;
      } else {
        result.push(currChange);
        prevChange = currChange;
      }
    }
    return result;
  }
  class LineChange {
    constructor(originalStartLineNumber, originalEndLineNumber, modifiedStartLineNumber, modifiedEndLineNumber, charChanges) {
      this.originalStartLineNumber = originalStartLineNumber;
      this.originalEndLineNumber = originalEndLineNumber;
      this.modifiedStartLineNumber = modifiedStartLineNumber;
      this.modifiedEndLineNumber = modifiedEndLineNumber;
      this.charChanges = charChanges;
    }
    static createFromDiffResult(shouldIgnoreTrimWhitespace, diffChange, originalLineSequence, modifiedLineSequence, continueCharDiff, shouldComputeCharChanges, shouldPostProcessCharChanges) {
      let originalStartLineNumber;
      let originalEndLineNumber;
      let modifiedStartLineNumber;
      let modifiedEndLineNumber;
      let charChanges = void 0;
      if (diffChange.originalLength === 0) {
        originalStartLineNumber = originalLineSequence.getStartLineNumber(diffChange.originalStart) - 1;
        originalEndLineNumber = 0;
      } else {
        originalStartLineNumber = originalLineSequence.getStartLineNumber(diffChange.originalStart);
        originalEndLineNumber = originalLineSequence.getEndLineNumber(diffChange.originalStart + diffChange.originalLength - 1);
      }
      if (diffChange.modifiedLength === 0) {
        modifiedStartLineNumber = modifiedLineSequence.getStartLineNumber(diffChange.modifiedStart) - 1;
        modifiedEndLineNumber = 0;
      } else {
        modifiedStartLineNumber = modifiedLineSequence.getStartLineNumber(diffChange.modifiedStart);
        modifiedEndLineNumber = modifiedLineSequence.getEndLineNumber(diffChange.modifiedStart + diffChange.modifiedLength - 1);
      }
      if (shouldComputeCharChanges && diffChange.originalLength > 0 && diffChange.originalLength < 20 && diffChange.modifiedLength > 0 && diffChange.modifiedLength < 20 && continueCharDiff()) {
        const originalCharSequence = originalLineSequence.createCharSequence(shouldIgnoreTrimWhitespace, diffChange.originalStart, diffChange.originalStart + diffChange.originalLength - 1);
        const modifiedCharSequence = modifiedLineSequence.createCharSequence(shouldIgnoreTrimWhitespace, diffChange.modifiedStart, diffChange.modifiedStart + diffChange.modifiedLength - 1);
        if (originalCharSequence.getElements().length > 0 && modifiedCharSequence.getElements().length > 0) {
          let rawChanges = computeDiff(originalCharSequence, modifiedCharSequence, continueCharDiff, true).changes;
          if (shouldPostProcessCharChanges) {
            rawChanges = postProcessCharChanges(rawChanges);
          }
          charChanges = [];
          for (let i2 = 0, length = rawChanges.length; i2 < length; i2++) {
            charChanges.push(CharChange.createFromDiffChange(rawChanges[i2], originalCharSequence, modifiedCharSequence));
          }
        }
      }
      return new LineChange(originalStartLineNumber, originalEndLineNumber, modifiedStartLineNumber, modifiedEndLineNumber, charChanges);
    }
  }
  class DiffComputer {
    constructor(originalLines, modifiedLines, opts) {
      this.shouldComputeCharChanges = opts.shouldComputeCharChanges;
      this.shouldPostProcessCharChanges = opts.shouldPostProcessCharChanges;
      this.shouldIgnoreTrimWhitespace = opts.shouldIgnoreTrimWhitespace;
      this.shouldMakePrettyDiff = opts.shouldMakePrettyDiff;
      this.originalLines = originalLines;
      this.modifiedLines = modifiedLines;
      this.original = new LineSequence(originalLines);
      this.modified = new LineSequence(modifiedLines);
      this.continueLineDiff = createContinueProcessingPredicate(opts.maxComputationTime);
      this.continueCharDiff = createContinueProcessingPredicate(opts.maxComputationTime === 0 ? 0 : Math.min(opts.maxComputationTime, 5e3));
    }
    computeDiff() {
      if (this.original.lines.length === 1 && this.original.lines[0].length === 0) {
        if (this.modified.lines.length === 1 && this.modified.lines[0].length === 0) {
          return {
            quitEarly: false,
            changes: []
          };
        }
        return {
          quitEarly: false,
          changes: [{
            originalStartLineNumber: 1,
            originalEndLineNumber: 1,
            modifiedStartLineNumber: 1,
            modifiedEndLineNumber: this.modified.lines.length,
            charChanges: void 0
          }]
        };
      }
      if (this.modified.lines.length === 1 && this.modified.lines[0].length === 0) {
        return {
          quitEarly: false,
          changes: [{
            originalStartLineNumber: 1,
            originalEndLineNumber: this.original.lines.length,
            modifiedStartLineNumber: 1,
            modifiedEndLineNumber: 1,
            charChanges: void 0
          }]
        };
      }
      const diffResult = computeDiff(this.original, this.modified, this.continueLineDiff, this.shouldMakePrettyDiff);
      const rawChanges = diffResult.changes;
      const quitEarly = diffResult.quitEarly;
      if (this.shouldIgnoreTrimWhitespace) {
        const lineChanges = [];
        for (let i2 = 0, length = rawChanges.length; i2 < length; i2++) {
          lineChanges.push(LineChange.createFromDiffResult(this.shouldIgnoreTrimWhitespace, rawChanges[i2], this.original, this.modified, this.continueCharDiff, this.shouldComputeCharChanges, this.shouldPostProcessCharChanges));
        }
        return {
          quitEarly,
          changes: lineChanges
        };
      }
      const result = [];
      let originalLineIndex = 0;
      let modifiedLineIndex = 0;
      for (let i2 = -1, len = rawChanges.length; i2 < len; i2++) {
        const nextChange = i2 + 1 < len ? rawChanges[i2 + 1] : null;
        const originalStop = nextChange ? nextChange.originalStart : this.originalLines.length;
        const modifiedStop = nextChange ? nextChange.modifiedStart : this.modifiedLines.length;
        while (originalLineIndex < originalStop && modifiedLineIndex < modifiedStop) {
          const originalLine = this.originalLines[originalLineIndex];
          const modifiedLine = this.modifiedLines[modifiedLineIndex];
          if (originalLine !== modifiedLine) {
            {
              let originalStartColumn = getFirstNonBlankColumn(originalLine, 1);
              let modifiedStartColumn = getFirstNonBlankColumn(modifiedLine, 1);
              while (originalStartColumn > 1 && modifiedStartColumn > 1) {
                const originalChar = originalLine.charCodeAt(originalStartColumn - 2);
                const modifiedChar = modifiedLine.charCodeAt(modifiedStartColumn - 2);
                if (originalChar !== modifiedChar) {
                  break;
                }
                originalStartColumn--;
                modifiedStartColumn--;
              }
              if (originalStartColumn > 1 || modifiedStartColumn > 1) {
                this._pushTrimWhitespaceCharChange(result, originalLineIndex + 1, 1, originalStartColumn, modifiedLineIndex + 1, 1, modifiedStartColumn);
              }
            }
            {
              let originalEndColumn = getLastNonBlankColumn(originalLine, 1);
              let modifiedEndColumn = getLastNonBlankColumn(modifiedLine, 1);
              const originalMaxColumn = originalLine.length + 1;
              const modifiedMaxColumn = modifiedLine.length + 1;
              while (originalEndColumn < originalMaxColumn && modifiedEndColumn < modifiedMaxColumn) {
                const originalChar = originalLine.charCodeAt(originalEndColumn - 1);
                const modifiedChar = originalLine.charCodeAt(modifiedEndColumn - 1);
                if (originalChar !== modifiedChar) {
                  break;
                }
                originalEndColumn++;
                modifiedEndColumn++;
              }
              if (originalEndColumn < originalMaxColumn || modifiedEndColumn < modifiedMaxColumn) {
                this._pushTrimWhitespaceCharChange(result, originalLineIndex + 1, originalEndColumn, originalMaxColumn, modifiedLineIndex + 1, modifiedEndColumn, modifiedMaxColumn);
              }
            }
          }
          originalLineIndex++;
          modifiedLineIndex++;
        }
        if (nextChange) {
          result.push(LineChange.createFromDiffResult(this.shouldIgnoreTrimWhitespace, nextChange, this.original, this.modified, this.continueCharDiff, this.shouldComputeCharChanges, this.shouldPostProcessCharChanges));
          originalLineIndex += nextChange.originalLength;
          modifiedLineIndex += nextChange.modifiedLength;
        }
      }
      return {
        quitEarly,
        changes: result
      };
    }
    _pushTrimWhitespaceCharChange(result, originalLineNumber, originalStartColumn, originalEndColumn, modifiedLineNumber, modifiedStartColumn, modifiedEndColumn) {
      if (this._mergeTrimWhitespaceCharChange(result, originalLineNumber, originalStartColumn, originalEndColumn, modifiedLineNumber, modifiedStartColumn, modifiedEndColumn)) {
        return;
      }
      let charChanges = void 0;
      if (this.shouldComputeCharChanges) {
        charChanges = [new CharChange(originalLineNumber, originalStartColumn, originalLineNumber, originalEndColumn, modifiedLineNumber, modifiedStartColumn, modifiedLineNumber, modifiedEndColumn)];
      }
      result.push(new LineChange(originalLineNumber, originalLineNumber, modifiedLineNumber, modifiedLineNumber, charChanges));
    }
    _mergeTrimWhitespaceCharChange(result, originalLineNumber, originalStartColumn, originalEndColumn, modifiedLineNumber, modifiedStartColumn, modifiedEndColumn) {
      const len = result.length;
      if (len === 0) {
        return false;
      }
      const prevChange = result[len - 1];
      if (prevChange.originalEndLineNumber === 0 || prevChange.modifiedEndLineNumber === 0) {
        return false;
      }
      if (prevChange.originalEndLineNumber === originalLineNumber && prevChange.modifiedEndLineNumber === modifiedLineNumber) {
        if (this.shouldComputeCharChanges && prevChange.charChanges) {
          prevChange.charChanges.push(new CharChange(originalLineNumber, originalStartColumn, originalLineNumber, originalEndColumn, modifiedLineNumber, modifiedStartColumn, modifiedLineNumber, modifiedEndColumn));
        }
        return true;
      }
      if (prevChange.originalEndLineNumber + 1 === originalLineNumber && prevChange.modifiedEndLineNumber + 1 === modifiedLineNumber) {
        prevChange.originalEndLineNumber = originalLineNumber;
        prevChange.modifiedEndLineNumber = modifiedLineNumber;
        if (this.shouldComputeCharChanges && prevChange.charChanges) {
          prevChange.charChanges.push(new CharChange(originalLineNumber, originalStartColumn, originalLineNumber, originalEndColumn, modifiedLineNumber, modifiedStartColumn, modifiedLineNumber, modifiedEndColumn));
        }
        return true;
      }
      return false;
    }
  }
  function getFirstNonBlankColumn(txt, defaultValue) {
    const r = firstNonWhitespaceIndex(txt);
    if (r === -1) {
      return defaultValue;
    }
    return r + 1;
  }
  function getLastNonBlankColumn(txt, defaultValue) {
    const r = lastNonWhitespaceIndex(txt);
    if (r === -1) {
      return defaultValue;
    }
    return r + 2;
  }
  function createContinueProcessingPredicate(maximumRuntime) {
    if (maximumRuntime === 0) {
      return () => true;
    }
    const startTime = Date.now();
    return () => {
      return Date.now() - startTime < maximumRuntime;
    };
  }
  const linesDiffComputers = {
    getLegacy: () => new LegacyLinesDiffComputer(),
    getDefault: () => new DefaultLinesDiffComputer()
  };
  var InlineSuggestionItem;
  (function(InlineSuggestionItem2) {
    function create2(data, textModel) {
      if (!data.isInlineEdit && !data.uri) {
        return InlineCompletionItem.create(data, textModel);
      } else {
        return InlineEditItem.create(data, textModel);
      }
    }
    InlineSuggestionItem2.create = create2;
  })(InlineSuggestionItem || (InlineSuggestionItem = {}));
  class InlineSuggestionItemBase {
    constructor(_data, identity2, hint) {
      this._data = _data;
      this.identity = identity2;
      this.hint = hint;
    }
    /**
     * A reference to the original inline completion list this inline completion has been constructed from.
     * Used for event data to ensure referential equality.
    */
    get source() {
      return this._data.source;
    }
    get isFromExplicitRequest() {
      return this._data.context.triggerKind === InlineCompletionTriggerKind$1.Explicit;
    }
    get forwardStable() {
      return this.source.inlineSuggestions.enableForwardStability ?? false;
    }
    get editRange() {
      return this.getSingleTextEdit().range;
    }
    get targetRange() {
      return this.hint?.range && !this.hint.jumpToEdit ? this.hint?.range : this.editRange;
    }
    get insertText() {
      return this.getSingleTextEdit().text;
    }
    get semanticId() {
      return this.hash;
    }
    get action() {
      return this._sourceInlineCompletion.gutterMenuLinkAction;
    }
    get command() {
      return this._sourceInlineCompletion.command;
    }
    get warning() {
      return this._sourceInlineCompletion.warning;
    }
    get showInlineEditMenu() {
      return !!this._sourceInlineCompletion.showInlineEditMenu;
    }
    get hash() {
      return JSON.stringify([
        this.getSingleTextEdit().text,
        this.getSingleTextEdit().range.getStartPosition().toString()
      ]);
    }
    get requestUuid() {
      return this._data.context.requestUuid;
    }
    get partialAccepts() {
      return this._data.partialAccepts;
    }
    /**
     * A reference to the original inline completion this inline completion has been constructed from.
     * Used for event data to ensure referential equality.
    */
    get _sourceInlineCompletion() {
      return this._data.sourceInlineCompletion;
    }
    addRef() {
      this.identity.addRef();
      this.source.addRef();
    }
    removeRef() {
      this.identity.removeRef();
      this.source.removeRef();
    }
    reportInlineEditShown(commandService, viewKind, viewData) {
      this._data.reportInlineEditShown(commandService, this.insertText, viewKind, viewData);
    }
    reportPartialAccept(acceptedCharacters, info, partialAcceptance) {
      this._data.reportPartialAccept(acceptedCharacters, info, partialAcceptance);
    }
    reportEndOfLife(reason) {
      this._data.reportEndOfLife(reason);
    }
    setEndOfLifeReason(reason) {
      this._data.setEndOfLifeReason(reason);
    }
    setIsPreceeded(item) {
      this._data.setIsPreceeded(item.partialAccepts);
    }
    setNotShownReasonIfNotSet(reason) {
      this._data.setNotShownReason(reason);
    }
    /**
     * Avoid using this method. Instead introduce getters for the needed properties.
    */
    getSourceCompletion() {
      return this._sourceInlineCompletion;
    }
  }
  const _InlineSuggestionIdentity = class _InlineSuggestionIdentity {
    constructor() {
      this._onDispose = observableSignal(this);
      this._jumpedTo = observableValue(this, false);
      this._refCount = 1;
      this.id = "InlineCompletionIdentity" + _InlineSuggestionIdentity.idCounter++;
    }
    get jumpedTo() {
      return this._jumpedTo;
    }
    addRef() {
      this._refCount++;
    }
    removeRef() {
      this._refCount--;
      if (this._refCount === 0) {
        this._onDispose.trigger(void 0);
      }
    }
    setJumpTo(tx) {
      this._jumpedTo.set(true, tx);
    }
  };
  _InlineSuggestionIdentity.idCounter = 0;
  let InlineSuggestionIdentity = _InlineSuggestionIdentity;
  class InlineSuggestHint {
    static create(displayLocation) {
      return new InlineSuggestHint(Range$2.lift(displayLocation.range), displayLocation.content, displayLocation.style, displayLocation.jumpToEdit);
    }
    constructor(range2, content, style, jumpToEdit) {
      this.range = range2;
      this.content = content;
      this.style = style;
      this.jumpToEdit = jumpToEdit;
    }
    withEdit(edit2, positionOffsetTransformer) {
      const offsetRange = new OffsetRange(positionOffsetTransformer.getOffset(this.range.getStartPosition()), positionOffsetTransformer.getOffset(this.range.getEndPosition()));
      const newOffsetRange = applyEditsToRanges([offsetRange], edit2)[0];
      if (!newOffsetRange) {
        return void 0;
      }
      const newRange = positionOffsetTransformer.getRange(newOffsetRange);
      return new InlineSuggestHint(newRange, this.content, this.style, this.jumpToEdit);
    }
  }
  class InlineCompletionItem extends InlineSuggestionItemBase {
    static create(data, textModel) {
      const identity2 = new InlineSuggestionIdentity();
      const transformer = getPositionOffsetTransformerFromTextModel(textModel);
      const insertText = data.insertText.replace(/\r\n|\r|\n/g, textModel.getEOL());
      const edit2 = reshapeInlineCompletion(new StringReplacement(transformer.getOffsetRange(data.range), insertText), textModel);
      const trimmedEdit = edit2.removeCommonSuffixAndPrefix(textModel.getValue());
      const textEdit = transformer.getTextReplacement(edit2);
      const displayLocation = data.hint ? InlineSuggestHint.create(data.hint) : void 0;
      return new InlineCompletionItem(edit2, trimmedEdit, textEdit, textEdit.range, data.snippetInfo, data.additionalTextEdits, data, identity2, displayLocation);
    }
    constructor(_edit, _trimmedEdit, _textEdit, _originalRange, snippetInfo, additionalTextEdits, data, identity2, displayLocation) {
      super(data, identity2, displayLocation);
      this._edit = _edit;
      this._trimmedEdit = _trimmedEdit;
      this._textEdit = _textEdit;
      this._originalRange = _originalRange;
      this.snippetInfo = snippetInfo;
      this.additionalTextEdits = additionalTextEdits;
      this.isInlineEdit = false;
    }
    get hash() {
      return JSON.stringify(this._trimmedEdit.toJson());
    }
    getSingleTextEdit() {
      return this._textEdit;
    }
    withIdentity(identity2) {
      return new InlineCompletionItem(this._edit, this._trimmedEdit, this._textEdit, this._originalRange, this.snippetInfo, this.additionalTextEdits, this._data, identity2, this.hint);
    }
    withEdit(textModelEdit, textModel) {
      const newEditRange = applyEditsToRanges([this._edit.replaceRange], textModelEdit);
      if (newEditRange.length === 0) {
        return void 0;
      }
      const newEdit = new StringReplacement(newEditRange[0], this._textEdit.text);
      const positionOffsetTransformer = getPositionOffsetTransformerFromTextModel(textModel);
      const newTextEdit = positionOffsetTransformer.getTextReplacement(newEdit);
      let newDisplayLocation = this.hint;
      if (newDisplayLocation) {
        newDisplayLocation = newDisplayLocation.withEdit(textModelEdit, positionOffsetTransformer);
        if (!newDisplayLocation) {
          return void 0;
        }
      }
      const trimmedEdit = newEdit.removeCommonSuffixAndPrefix(textModel.getValue());
      return new InlineCompletionItem(newEdit, trimmedEdit, newTextEdit, this._originalRange, this.snippetInfo, this.additionalTextEdits, this._data, this.identity, newDisplayLocation);
    }
    canBeReused(model, position) {
      const updatedRange = this._textEdit.range;
      const result = !!updatedRange && updatedRange.containsPosition(position) && this.isVisible(model, position) && TextLength.ofRange(updatedRange).isGreaterThanOrEqualTo(TextLength.ofRange(this._originalRange));
      return result;
    }
    isVisible(model, cursorPosition) {
      const singleTextEdit = this.getSingleTextEdit();
      return inlineCompletionIsVisible(singleTextEdit, this._originalRange, model, cursorPosition);
    }
  }
  function inlineCompletionIsVisible(singleTextEdit, originalRange, model, cursorPosition) {
    const minimizedReplacement = singleTextRemoveCommonPrefix(singleTextEdit, model);
    const editRange = singleTextEdit.range;
    if (!editRange || originalRange && !originalRange.getStartPosition().equals(editRange.getStartPosition()) || cursorPosition.lineNumber !== minimizedReplacement.range.startLineNumber || minimizedReplacement.isEmpty) {
      return false;
    }
    const originalValue = model.getValueInRange(
      minimizedReplacement.range,
      1
      /* EndOfLinePreference.LF */
    );
    const filterText = minimizedReplacement.text;
    const cursorPosIndex = Math.max(0, cursorPosition.column - minimizedReplacement.range.startColumn);
    let filterTextBefore = filterText.substring(0, cursorPosIndex);
    let filterTextAfter = filterText.substring(cursorPosIndex);
    let originalValueBefore = originalValue.substring(0, cursorPosIndex);
    let originalValueAfter = originalValue.substring(cursorPosIndex);
    const originalValueIndent = model.getLineIndentColumn(minimizedReplacement.range.startLineNumber);
    if (minimizedReplacement.range.startColumn <= originalValueIndent) {
      originalValueBefore = originalValueBefore.trimStart();
      if (originalValueBefore.length === 0) {
        originalValueAfter = originalValueAfter.trimStart();
      }
      filterTextBefore = filterTextBefore.trimStart();
      if (filterTextBefore.length === 0) {
        filterTextAfter = filterTextAfter.trimStart();
      }
    }
    return filterTextBefore.startsWith(originalValueBefore) && !!matchesSubString(originalValueAfter, filterTextAfter);
  }
  class InlineEditItem extends InlineSuggestionItemBase {
    static create(data, textModel) {
      const offsetEdit = getStringEdit(textModel, data.range, data.insertText);
      const text2 = new TextModelText(textModel);
      const textEdit = TextEdit.fromStringEdit(offsetEdit, text2);
      const singleTextEdit = offsetEdit.isEmpty() ? new TextReplacement(new Range$2(1, 1, 1, 1), "") : textEdit.toReplacement(text2);
      const identity2 = new InlineSuggestionIdentity();
      const edits = offsetEdit.replacements.map((edit2) => {
        const replacedRange = Range$2.fromPositions(textModel.getPositionAt(edit2.replaceRange.start), textModel.getPositionAt(edit2.replaceRange.endExclusive));
        const replacedText = textModel.getValueInRange(replacedRange);
        return SingleUpdatedNextEdit.create(edit2, replacedText);
      });
      const hint = data.hint ? InlineSuggestHint.create(data.hint) : void 0;
      return new InlineEditItem(offsetEdit, singleTextEdit, data.uri, data, identity2, edits, hint, false, textModel.getVersionId());
    }
    constructor(_edit, _textEdit, uri, data, identity2, _edits, hint, _lastChangePartOfInlineEdit = false, _inlineEditModelVersion) {
      super(data, identity2, hint);
      this._edit = _edit;
      this._textEdit = _textEdit;
      this.uri = uri;
      this._edits = _edits;
      this._lastChangePartOfInlineEdit = _lastChangePartOfInlineEdit;
      this._inlineEditModelVersion = _inlineEditModelVersion;
      this.snippetInfo = void 0;
      this.additionalTextEdits = [];
      this.isInlineEdit = true;
    }
    get updatedEditModelVersion() {
      return this._inlineEditModelVersion;
    }
    get updatedEdit() {
      return this._edit;
    }
    getSingleTextEdit() {
      return this._textEdit;
    }
    withIdentity(identity2) {
      return new InlineEditItem(this._edit, this._textEdit, this.uri, this._data, identity2, this._edits, this.hint, this._lastChangePartOfInlineEdit, this._inlineEditModelVersion);
    }
    canBeReused(model, position) {
      return this._lastChangePartOfInlineEdit && this.updatedEditModelVersion === model.getVersionId();
    }
    withEdit(textModelChanges, textModel) {
      const edit2 = this._applyTextModelChanges(textModelChanges, this._edits, textModel);
      return edit2;
    }
    _applyTextModelChanges(textModelChanges, edits, textModel) {
      edits = edits.map((innerEdit) => innerEdit.applyTextModelChanges(textModelChanges));
      if (edits.some((edit2) => edit2.edit === void 0)) {
        return void 0;
      }
      const newTextModelVersion = textModel.getVersionId();
      let inlineEditModelVersion = this._inlineEditModelVersion;
      const lastChangePartOfInlineEdit = edits.some((edit2) => edit2.lastChangeUpdatedEdit);
      if (lastChangePartOfInlineEdit) {
        inlineEditModelVersion = newTextModelVersion ?? -1;
      }
      if (newTextModelVersion === null || inlineEditModelVersion + 20 < newTextModelVersion) {
        return void 0;
      }
      edits = edits.filter((innerEdit) => !innerEdit.edit.isEmpty);
      if (edits.length === 0) {
        return void 0;
      }
      const newEdit = new StringEdit(edits.map((edit2) => edit2.edit));
      const positionOffsetTransformer = getPositionOffsetTransformerFromTextModel(textModel);
      const newTextEdit = positionOffsetTransformer.getTextEdit(newEdit).toReplacement(new TextModelText(textModel));
      let newDisplayLocation = this.hint;
      if (newDisplayLocation) {
        newDisplayLocation = newDisplayLocation.withEdit(textModelChanges, positionOffsetTransformer);
        if (!newDisplayLocation) {
          return void 0;
        }
      }
      return new InlineEditItem(newEdit, newTextEdit, this.uri, this._data, this.identity, edits, newDisplayLocation, lastChangePartOfInlineEdit, inlineEditModelVersion);
    }
  }
  function getStringEdit(textModel, editRange, replaceText) {
    const eol = textModel.getEOL();
    const editOriginalText = textModel.getValueInRange(editRange);
    const editReplaceText = replaceText.replace(/\r\n|\r|\n/g, eol);
    const diffAlgorithm = linesDiffComputers.getDefault();
    const lineDiffs = diffAlgorithm.computeDiff(splitLines(editOriginalText), splitLines(editReplaceText), {
      ignoreTrimWhitespace: false,
      computeMoves: false,
      extendToSubwords: true,
      maxComputationTimeMs: 500
    });
    const innerChanges = lineDiffs.changes.flatMap((c) => c.innerChanges ?? []);
    function addRangeToPos(pos, range2) {
      const start = TextLength.fromPosition(range2.getStartPosition());
      return TextLength.ofRange(range2).createRange(start.addToPosition(pos));
    }
    const modifiedText = new StringText(editReplaceText);
    const offsetEdit = new StringEdit(innerChanges.map((c) => {
      const rangeInModel = addRangeToPos(editRange.getStartPosition(), c.originalRange);
      const originalRange = getPositionOffsetTransformerFromTextModel(textModel).getOffsetRange(rangeInModel);
      const replaceText2 = modifiedText.getValueOfRange(c.modifiedRange);
      const edit2 = new StringReplacement(originalRange, replaceText2);
      const originalText = textModel.getValueInRange(rangeInModel);
      return reshapeInlineEdit(edit2, originalText, innerChanges.length, textModel);
    }));
    return offsetEdit;
  }
  class SingleUpdatedNextEdit {
    static create(edit2, replacedText) {
      const prefixLength = commonPrefixLength(edit2.newText, replacedText);
      const suffixLength = commonSuffixLength(edit2.newText, replacedText);
      const trimmedNewText = edit2.newText.substring(prefixLength, edit2.newText.length - suffixLength);
      return new SingleUpdatedNextEdit(edit2, trimmedNewText, prefixLength, suffixLength);
    }
    get edit() {
      return this._edit;
    }
    get lastChangeUpdatedEdit() {
      return this._lastChangeUpdatedEdit;
    }
    constructor(_edit, _trimmedNewText, _prefixLength, _suffixLength, _lastChangeUpdatedEdit = false) {
      this._edit = _edit;
      this._trimmedNewText = _trimmedNewText;
      this._prefixLength = _prefixLength;
      this._suffixLength = _suffixLength;
      this._lastChangeUpdatedEdit = _lastChangeUpdatedEdit;
    }
    applyTextModelChanges(textModelChanges) {
      const c = this._clone();
      c._applyTextModelChanges(textModelChanges);
      return c;
    }
    _clone() {
      return new SingleUpdatedNextEdit(this._edit, this._trimmedNewText, this._prefixLength, this._suffixLength, this._lastChangeUpdatedEdit);
    }
    _applyTextModelChanges(textModelChanges) {
      this._lastChangeUpdatedEdit = false;
      if (!this._edit) {
        throw new BugIndicatingError("UpdatedInnerEdits: No edit to apply changes to");
      }
      const result = this._applyChanges(this._edit, textModelChanges);
      if (!result) {
        this._edit = void 0;
        return;
      }
      this._edit = result.edit;
      this._lastChangeUpdatedEdit = result.editHasChanged;
    }
    _applyChanges(edit2, textModelChanges) {
      let editStart = edit2.replaceRange.start;
      let editEnd = edit2.replaceRange.endExclusive;
      let editReplaceText = edit2.newText;
      let editHasChanged = false;
      const shouldPreserveEditShape = this._prefixLength > 0 || this._suffixLength > 0;
      for (let i2 = textModelChanges.replacements.length - 1; i2 >= 0; i2--) {
        const change = textModelChanges.replacements[i2];
        const isInsertion2 = change.newText.length > 0 && change.replaceRange.isEmpty;
        if (isInsertion2 && !shouldPreserveEditShape && change.replaceRange.start === editStart && editReplaceText.startsWith(change.newText)) {
          editStart += change.newText.length;
          editReplaceText = editReplaceText.substring(change.newText.length);
          editEnd = Math.max(editStart, editEnd);
          editHasChanged = true;
          continue;
        }
        if (isInsertion2 && shouldPreserveEditShape && change.replaceRange.start === editStart + this._prefixLength && this._trimmedNewText.startsWith(change.newText)) {
          editEnd += change.newText.length;
          editHasChanged = true;
          this._prefixLength += change.newText.length;
          this._trimmedNewText = this._trimmedNewText.substring(change.newText.length);
          continue;
        }
        const isDeletion2 = change.newText.length === 0 && change.replaceRange.length > 0;
        if (isDeletion2 && change.replaceRange.start >= editStart + this._prefixLength && change.replaceRange.endExclusive <= editEnd - this._suffixLength) {
          editEnd -= change.replaceRange.length;
          editHasChanged = true;
          continue;
        }
        if (change.equals(edit2)) {
          editHasChanged = true;
          editStart = change.replaceRange.endExclusive;
          editReplaceText = "";
          continue;
        }
        if (change.replaceRange.start > editEnd) {
          continue;
        }
        if (change.replaceRange.endExclusive < editStart) {
          editStart += change.newText.length - change.replaceRange.length;
          editEnd += change.newText.length - change.replaceRange.length;
          continue;
        }
        return void 0;
      }
      if (this._trimmedNewText.length === 0 && editStart + this._prefixLength === editEnd - this._suffixLength) {
        return { edit: new StringReplacement(new OffsetRange(editStart + this._prefixLength, editStart + this._prefixLength), ""), editHasChanged: true };
      }
      return { edit: new StringReplacement(new OffsetRange(editStart, editEnd), editReplaceText), editHasChanged };
    }
  }
  function reshapeInlineCompletion(edit2, textModel) {
    const eol = textModel.getEOL();
    if (edit2.replaceRange.isEmpty && edit2.newText.includes(eol)) {
      edit2 = reshapeMultiLineInsertion(edit2, textModel);
    }
    return edit2;
  }
  function reshapeInlineEdit(edit2, originalText, totalInnerEdits, textModel) {
    const eol = textModel.getEOL();
    if (edit2.newText.endsWith(eol) && originalText.endsWith(eol)) {
      edit2 = new StringReplacement(edit2.replaceRange.deltaEnd(-eol.length), edit2.newText.slice(0, -eol.length));
    }
    if (totalInnerEdits === 1 && edit2.replaceRange.isEmpty && edit2.newText.includes(eol)) {
      const startPosition = textModel.getPositionAt(edit2.replaceRange.start);
      const hasTextOnInsertionLine = textModel.getLineLength(startPosition.lineNumber) !== 0;
      if (hasTextOnInsertionLine) {
        edit2 = reshapeMultiLineInsertion(edit2, textModel);
      }
    }
    if (totalInnerEdits === 1) {
      const prefixLength = commonPrefixLength(originalText, edit2.newText);
      const suffixLength = commonSuffixLength(originalText.slice(prefixLength), edit2.newText.slice(prefixLength));
      if (prefixLength + suffixLength === originalText.length) {
        return new StringReplacement(edit2.replaceRange.deltaStart(prefixLength).deltaEnd(-suffixLength), edit2.newText.substring(prefixLength, edit2.newText.length - suffixLength));
      }
      if (prefixLength + suffixLength === edit2.newText.length) {
        return new StringReplacement(edit2.replaceRange.deltaStart(prefixLength).deltaEnd(-suffixLength), "");
      }
    }
    return edit2;
  }
  function reshapeMultiLineInsertion(edit2, textModel) {
    if (!edit2.replaceRange.isEmpty) {
      throw new BugIndicatingError("Unexpected original range");
    }
    if (edit2.replaceRange.start === 0) {
      return edit2;
    }
    const eol = textModel.getEOL();
    const startPosition = textModel.getPositionAt(edit2.replaceRange.start);
    const startColumn = startPosition.column;
    const startLineNumber = startPosition.lineNumber;
    if (startColumn === 1 && startLineNumber > 1 && edit2.newText.endsWith(eol) && !edit2.newText.startsWith(eol)) {
      return new StringReplacement(edit2.replaceRange.delta(-1), eol + edit2.newText.slice(0, -eol.length));
    }
    return edit2;
  }
  function fixBracketsInLine(tokens, languageConfigurationService) {
    const denseKeyProvider = new DenseKeyProvider();
    const bracketTokens = new LanguageAgnosticBracketTokens(denseKeyProvider, (languageId) => languageConfigurationService.getLanguageConfiguration(languageId));
    const tokenizer = new TextBufferTokenizer(new StaticTokenizerSource([tokens]), bracketTokens);
    const node = parseDocument(tokenizer, [], void 0, true);
    let str = "";
    const line = tokens.getLineContent();
    function processNode(node2, offset) {
      if (node2.kind === 2) {
        processNode(node2.openingBracket, offset);
        offset = lengthAdd(offset, node2.openingBracket.length);
        if (node2.child) {
          processNode(node2.child, offset);
          offset = lengthAdd(offset, node2.child.length);
        }
        if (node2.closingBracket) {
          processNode(node2.closingBracket, offset);
          offset = lengthAdd(offset, node2.closingBracket.length);
        } else {
          const singleLangBracketTokens = bracketTokens.getSingleLanguageBracketTokens(node2.openingBracket.languageId);
          const closingTokenText = singleLangBracketTokens.findClosingTokenText(node2.openingBracket.bracketIds);
          str += closingTokenText;
        }
      } else if (node2.kind === 3) ;
      else if (node2.kind === 0 || node2.kind === 1) {
        str += line.substring(lengthGetColumnCountIfZeroLineCount(offset), lengthGetColumnCountIfZeroLineCount(lengthAdd(offset, node2.length)));
      } else if (node2.kind === 4) {
        for (const child of node2.children) {
          processNode(child, offset);
          offset = lengthAdd(offset, child.length);
        }
      }
    }
    processNode(node, lengthZero);
    return str;
  }
  class StaticTokenizerSource {
    constructor(lines) {
      this.lines = lines;
      this.tokenization = {
        getLineTokens: (lineNumber) => {
          return this.lines[lineNumber - 1];
        }
      };
    }
    getLineCount() {
      return this.lines.length;
    }
    getLineLength(lineNumber) {
      return this.lines[lineNumber - 1].getLineContent().length;
    }
  }
  class DirectedGraph {
    constructor() {
      this._nodes = /* @__PURE__ */ new Set();
      this._outgoingEdges = /* @__PURE__ */ new Map();
    }
    static from(nodes, getOutgoing) {
      const graph = new DirectedGraph();
      for (const node of nodes) {
        graph._nodes.add(node);
      }
      for (const node of nodes) {
        const outgoing = getOutgoing(node);
        if (outgoing.length > 0) {
          const outgoingSet = /* @__PURE__ */ new Set();
          for (const target of outgoing) {
            outgoingSet.add(target);
          }
          graph._outgoingEdges.set(node, outgoingSet);
        }
      }
      return graph;
    }
    /**
     * After this, the graph is guaranteed to have no cycles.
     */
    removeCycles() {
      const foundCycles = [];
      const visited = /* @__PURE__ */ new Set();
      const recursionStack = /* @__PURE__ */ new Set();
      const toRemove = [];
      const dfs2 = (node) => {
        visited.add(node);
        recursionStack.add(node);
        const outgoing = this._outgoingEdges.get(node);
        if (outgoing) {
          for (const neighbor of outgoing) {
            if (!visited.has(neighbor)) {
              dfs2(neighbor);
            } else if (recursionStack.has(neighbor)) {
              foundCycles.push(neighbor);
              toRemove.push({ from: node, to: neighbor });
            }
          }
        }
        recursionStack.delete(node);
      };
      for (const node of this._nodes) {
        if (!visited.has(node)) {
          dfs2(node);
        }
      }
      for (const { from, to } of toRemove) {
        const outgoingSet = this._outgoingEdges.get(from);
        if (outgoingSet) {
          outgoingSet.delete(to);
        }
      }
      return { foundCycles };
    }
    getOutgoing(node) {
      const outgoing = this._outgoingEdges.get(node);
      return outgoing ? Array.from(outgoing) : [];
    }
  }
  var InlineEditTabAction;
  (function(InlineEditTabAction2) {
    InlineEditTabAction2["Jump"] = "jump";
    InlineEditTabAction2["Accept"] = "accept";
    InlineEditTabAction2["Inactive"] = "inactive";
  })(InlineEditTabAction || (InlineEditTabAction = {}));
  var InlineCompletionViewKind;
  (function(InlineCompletionViewKind2) {
    InlineCompletionViewKind2["GhostText"] = "ghostText";
    InlineCompletionViewKind2["Custom"] = "custom";
    InlineCompletionViewKind2["SideBySide"] = "sideBySide";
    InlineCompletionViewKind2["Deletion"] = "deletion";
    InlineCompletionViewKind2["InsertionInline"] = "insertionInline";
    InlineCompletionViewKind2["InsertionMultiLine"] = "insertionMultiLine";
    InlineCompletionViewKind2["WordReplacements"] = "wordReplacements";
    InlineCompletionViewKind2["LineReplacement"] = "lineReplacement";
    InlineCompletionViewKind2["Collapsed"] = "collapsed";
  })(InlineCompletionViewKind || (InlineCompletionViewKind = {}));
  function provideInlineCompletions(providers, position, model, context, requestInfo, languageConfigurationService) {
    const requestUuid = prefixedUuid("icr");
    const cancellationTokenSource = new CancellationTokenSource$1();
    let cancelReason = void 0;
    const contextWithUuid = { ...context, requestUuid };
    const defaultReplaceRange = getDefaultRange(position, model);
    const providersByGroupId = groupByMap(providers, (p) => p.groupId);
    const yieldsToGraph = DirectedGraph.from(providers, (p) => {
      return p.yieldsToGroupIds?.flatMap((groupId) => providersByGroupId.get(groupId) ?? []) ?? [];
    });
    const { foundCycles } = yieldsToGraph.removeCycles();
    if (foundCycles.length > 0) {
      onUnexpectedExternalError(new Error(`Inline completions: cyclic yield-to dependency detected. Path: ${foundCycles.map((s) => s.toString ? s.toString() : "" + s).join(" -> ")}`));
    }
    let runningCount = 0;
    const queryProvider = new CachedFunction(async (provider) => {
      try {
        runningCount++;
        if (cancellationTokenSource.token.isCancellationRequested) {
          return void 0;
        }
        const yieldsTo = yieldsToGraph.getOutgoing(provider);
        for (const p of yieldsTo) {
          const result2 = await queryProvider.get(p);
          if (result2) {
            for (const item of result2.inlineSuggestions.items) {
              if (item.isInlineEdit || typeof item.insertText !== "string" && item.insertText !== void 0) {
                return void 0;
              }
              if (item.insertText !== void 0) {
                const t = new TextReplacement(Range$2.lift(item.range) ?? defaultReplaceRange, item.insertText);
                if (inlineCompletionIsVisible(t, void 0, model, position)) {
                  return void 0;
                }
              }
            }
          }
        }
        let result;
        const providerStartTime = Date.now();
        try {
          result = await provider.provideInlineCompletions(model, position, contextWithUuid, cancellationTokenSource.token);
        } catch (e) {
          onUnexpectedExternalError(e);
          return void 0;
        }
        const providerEndTime = Date.now();
        if (!result) {
          return void 0;
        }
        const data = [];
        const list2 = new InlineSuggestionList(result, data, provider);
        list2.addRef();
        runWhenCancelled(cancellationTokenSource.token, () => {
          return list2.removeRef(cancelReason);
        });
        if (cancellationTokenSource.token.isCancellationRequested) {
          return void 0;
        }
        for (const item of result.items) {
          data.push(toInlineSuggestData(item, list2, defaultReplaceRange, model, languageConfigurationService, contextWithUuid, requestInfo, { startTime: providerStartTime, endTime: providerEndTime }));
        }
        return list2;
      } finally {
        runningCount--;
      }
    });
    const inlineCompletionLists = AsyncIterableProducer.fromPromisesResolveOrder(providers.map((p) => queryProvider.get(p))).filter(isDefined);
    return {
      contextWithUuid,
      get didAllProvidersReturn() {
        return runningCount === 0;
      },
      lists: inlineCompletionLists,
      cancelAndDispose: (reason) => {
        if (cancelReason !== void 0) {
          return;
        }
        cancelReason = reason;
        cancellationTokenSource.dispose(true);
      }
    };
  }
  function runWhenCancelled(token, callback) {
    if (token.isCancellationRequested) {
      callback();
      return Disposable.None;
    } else {
      const listener = token.onCancellationRequested(() => {
        listener.dispose();
        callback();
      });
      return { dispose: () => listener.dispose() };
    }
  }
  function toInlineSuggestData(inlineCompletion, source, defaultReplaceRange, textModel, languageConfigurationService, context, requestInfo, providerRequestInfo) {
    let insertText;
    let snippetInfo;
    let range2 = inlineCompletion.range ? Range$2.lift(inlineCompletion.range) : defaultReplaceRange;
    if (typeof inlineCompletion.insertText === "string") {
      insertText = inlineCompletion.insertText;
      if (languageConfigurationService && inlineCompletion.completeBracketPairs) {
        insertText = closeBrackets(insertText, range2.getStartPosition(), textModel, languageConfigurationService);
        const diff = insertText.length - inlineCompletion.insertText.length;
        if (diff !== 0) {
          range2 = new Range$2(range2.startLineNumber, range2.startColumn, range2.endLineNumber, range2.endColumn + diff);
        }
      }
      snippetInfo = void 0;
    } else if (inlineCompletion.insertText === void 0) {
      insertText = "";
      snippetInfo = void 0;
      range2 = new Range$2(1, 1, 1, 1);
    } else if ("snippet" in inlineCompletion.insertText) {
      const preBracketCompletionLength = inlineCompletion.insertText.snippet.length;
      if (languageConfigurationService && inlineCompletion.completeBracketPairs) {
        inlineCompletion.insertText.snippet = closeBrackets(inlineCompletion.insertText.snippet, range2.getStartPosition(), textModel, languageConfigurationService);
        const diff = inlineCompletion.insertText.snippet.length - preBracketCompletionLength;
        if (diff !== 0) {
          range2 = new Range$2(range2.startLineNumber, range2.startColumn, range2.endLineNumber, range2.endColumn + diff);
        }
      }
      const snippet = new SnippetParser().parse(inlineCompletion.insertText.snippet);
      if (snippet.children.length === 1 && snippet.children[0] instanceof Text) {
        insertText = snippet.children[0].value;
        snippetInfo = void 0;
      } else {
        insertText = snippet.toString();
        snippetInfo = {
          snippet: inlineCompletion.insertText.snippet,
          range: range2
        };
      }
    } else {
      assertNever(inlineCompletion.insertText);
    }
    return new InlineSuggestData(range2, insertText, snippetInfo, URI.revive(inlineCompletion.uri), inlineCompletion.hint, inlineCompletion.additionalTextEdits || getReadonlyEmptyArray(), inlineCompletion, source, context, inlineCompletion.isInlineEdit ?? false, requestInfo, providerRequestInfo, inlineCompletion.correlationId);
  }
  class InlineSuggestData {
    constructor(range2, insertText, snippetInfo, uri, hint, additionalTextEdits, sourceInlineCompletion, source, context, isInlineEdit, _requestInfo, _providerRequestInfo, _correlationId) {
      this.range = range2;
      this.insertText = insertText;
      this.snippetInfo = snippetInfo;
      this.uri = uri;
      this.hint = hint;
      this.additionalTextEdits = additionalTextEdits;
      this.sourceInlineCompletion = sourceInlineCompletion;
      this.source = source;
      this.context = context;
      this.isInlineEdit = isInlineEdit;
      this._requestInfo = _requestInfo;
      this._providerRequestInfo = _providerRequestInfo;
      this._correlationId = _correlationId;
      this._didShow = false;
      this._timeUntilShown = void 0;
      this._showStartTime = void 0;
      this._shownDuration = 0;
      this._showUncollapsedStartTime = void 0;
      this._showUncollapsedDuration = 0;
      this._notShownReason = void 0;
      this._didReportEndOfLife = false;
      this._lastSetEndOfLifeReason = void 0;
      this._isPreceeded = false;
      this._partiallyAcceptedCount = 0;
      this._partiallyAcceptedSinceOriginal = { characters: 0, ratio: 0, count: 0 };
      this._viewData = { editorType: _requestInfo.editorType };
    }
    get showInlineEditMenu() {
      return this.sourceInlineCompletion.showInlineEditMenu ?? false;
    }
    get partialAccepts() {
      return this._partiallyAcceptedSinceOriginal;
    }
    async reportInlineEditShown(commandService, updatedInsertText, viewKind, viewData) {
      this.updateShownDuration(viewKind);
      if (this._didShow) {
        return;
      }
      this._didShow = true;
      this._viewData.viewKind = viewKind;
      this._viewData.renderData = viewData;
      this._timeUntilShown = Date.now() - this._requestInfo.startTime;
      const editDeltaInfo = new EditDeltaInfo(viewData.lineCountModified, viewData.lineCountOriginal, viewData.characterCountModified, viewData.characterCountOriginal);
      this.source.provider.handleItemDidShow?.(this.source.inlineSuggestions, this.sourceInlineCompletion, updatedInsertText, editDeltaInfo);
      if (this.sourceInlineCompletion.shownCommand) {
        await commandService.executeCommand(this.sourceInlineCompletion.shownCommand.id, ...this.sourceInlineCompletion.shownCommand.arguments || []);
      }
    }
    reportPartialAccept(acceptedCharacters, info, partialAcceptance) {
      this._partiallyAcceptedCount++;
      this._partiallyAcceptedSinceOriginal.characters += partialAcceptance.characters;
      this._partiallyAcceptedSinceOriginal.ratio = Math.min(this._partiallyAcceptedSinceOriginal.ratio + (1 - this._partiallyAcceptedSinceOriginal.ratio) * partialAcceptance.ratio, 1);
      this._partiallyAcceptedSinceOriginal.count += partialAcceptance.count;
      this.source.provider.handlePartialAccept?.(this.source.inlineSuggestions, this.sourceInlineCompletion, acceptedCharacters, info);
    }
    /**
     * Sends the end of life event to the provider.
     * If no reason is provided, the last set reason is used.
     * If no reason was set, the default reason is used.
    */
    reportEndOfLife(reason) {
      if (this._didReportEndOfLife) {
        return;
      }
      this._didReportEndOfLife = true;
      this.reportInlineEditHidden();
      if (!reason) {
        reason = this._lastSetEndOfLifeReason ?? { kind: InlineCompletionEndOfLifeReasonKind$1.Ignored, userTypingDisagreed: false, supersededBy: void 0 };
      }
      if (reason.kind === InlineCompletionEndOfLifeReasonKind$1.Rejected && this.source.provider.handleRejection) {
        this.source.provider.handleRejection(this.source.inlineSuggestions, this.sourceInlineCompletion);
      }
      if (this.source.provider.handleEndOfLifetime) {
        const summary = {
          requestUuid: this.context.requestUuid,
          correlationId: this._correlationId,
          selectedSuggestionInfo: !!this.context.selectedSuggestionInfo,
          partiallyAccepted: this._partiallyAcceptedCount,
          partiallyAcceptedCountSinceOriginal: this._partiallyAcceptedSinceOriginal.count,
          partiallyAcceptedRatioSinceOriginal: this._partiallyAcceptedSinceOriginal.ratio,
          partiallyAcceptedCharactersSinceOriginal: this._partiallyAcceptedSinceOriginal.characters,
          shown: this._didShow,
          shownDuration: this._shownDuration,
          shownDurationUncollapsed: this._showUncollapsedDuration,
          preceeded: this._isPreceeded,
          timeUntilShown: this._timeUntilShown,
          timeUntilProviderRequest: this._providerRequestInfo.startTime - this._requestInfo.startTime,
          timeUntilProviderResponse: this._providerRequestInfo.endTime - this._requestInfo.startTime,
          editorType: this._viewData.editorType,
          languageId: this._requestInfo.languageId,
          requestReason: this._requestInfo.reason,
          viewKind: this._viewData.viewKind,
          notShownReason: this._notShownReason,
          typingInterval: this._requestInfo.typingInterval,
          typingIntervalCharacterCount: this._requestInfo.typingIntervalCharacterCount,
          availableProviders: this._requestInfo.availableProviders.map((p) => p.toString()).join(","),
          ...this._viewData.renderData
        };
        this.source.provider.handleEndOfLifetime(this.source.inlineSuggestions, this.sourceInlineCompletion, reason, summary);
      }
    }
    setIsPreceeded(partialAccepts) {
      this._isPreceeded = true;
      if (this._partiallyAcceptedSinceOriginal.characters !== 0 || this._partiallyAcceptedSinceOriginal.ratio !== 0 || this._partiallyAcceptedSinceOriginal.count !== 0) {
        console.warn("Expected partiallyAcceptedCountSinceOriginal to be { characters: 0, rate: 0, partialAcceptances: 0 } before setIsPreceeded.");
      }
      this._partiallyAcceptedSinceOriginal = partialAccepts;
    }
    setNotShownReason(reason) {
      this._notShownReason ??= reason;
    }
    /**
     * Sets the end of life reason, but does not send the event to the provider yet.
    */
    setEndOfLifeReason(reason) {
      this.reportInlineEditHidden();
      this._lastSetEndOfLifeReason = reason;
    }
    updateShownDuration(viewKind) {
      const timeNow = Date.now();
      if (!this._showStartTime) {
        this._showStartTime = timeNow;
      }
      const isCollapsed = viewKind === InlineCompletionViewKind.Collapsed;
      if (!isCollapsed && this._showUncollapsedStartTime === void 0) {
        this._showUncollapsedStartTime = timeNow;
      }
      if (isCollapsed && this._showUncollapsedStartTime !== void 0) {
        this._showUncollapsedDuration += timeNow - this._showUncollapsedStartTime;
      }
    }
    reportInlineEditHidden() {
      if (this._showStartTime === void 0) {
        return;
      }
      const timeNow = Date.now();
      this._shownDuration += timeNow - this._showStartTime;
      this._showStartTime = void 0;
      if (this._showUncollapsedStartTime === void 0) {
        return;
      }
      this._showUncollapsedDuration += timeNow - this._showUncollapsedStartTime;
      this._showUncollapsedStartTime = void 0;
    }
  }
  var InlineCompletionEditorType;
  (function(InlineCompletionEditorType2) {
    InlineCompletionEditorType2["TextEditor"] = "textEditor";
    InlineCompletionEditorType2["DiffEditor"] = "diffEditor";
    InlineCompletionEditorType2["Notebook"] = "notebook";
  })(InlineCompletionEditorType || (InlineCompletionEditorType = {}));
  class InlineSuggestionList {
    constructor(inlineSuggestions, inlineSuggestionsData, provider) {
      this.inlineSuggestions = inlineSuggestions;
      this.inlineSuggestionsData = inlineSuggestionsData;
      this.provider = provider;
      this.refCount = 0;
    }
    addRef() {
      this.refCount++;
    }
    removeRef(reason = { kind: "other" }) {
      this.refCount--;
      if (this.refCount === 0) {
        for (const item of this.inlineSuggestionsData) {
          item.reportEndOfLife();
        }
        this.provider.disposeInlineCompletions(this.inlineSuggestions, reason);
      }
    }
  }
  function getDefaultRange(position, model) {
    const word = model.getWordAtPosition(position);
    const maxColumn = model.getLineMaxColumn(position.lineNumber);
    return word ? new Range$2(position.lineNumber, word.startColumn, position.lineNumber, maxColumn) : Range$2.fromPositions(position, position.with(void 0, maxColumn));
  }
  function closeBrackets(text2, position, model, languageConfigurationService) {
    const currentLine = model.getLineContent(position.lineNumber);
    const edit2 = StringReplacement.replace(new OffsetRange(position.column - 1, currentLine.length), text2);
    const proposedLineTokens = model.tokenization.tokenizeLinesAt(position.lineNumber, [edit2.replace(currentLine)]);
    const textTokens = proposedLineTokens?.[0].sliceZeroCopy(edit2.getRangeAfterReplace());
    if (!textTokens) {
      return text2;
    }
    const fixedText = fixBracketsInLine(textTokens, languageConfigurationService);
    return fixedText;
  }
  var __decorate$1w = 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$1v = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  var InlineCompletionsSource_1;
  let InlineCompletionsSource = (_aa = class extends Disposable {
    constructor(_textModel, _versionId, _debounceValue, _cursorPosition, _languageConfigurationService, _logService, _configurationService, _instantiationService, _contextKeyService) {
      super();
      this._textModel = _textModel;
      this._versionId = _versionId;
      this._debounceValue = _debounceValue;
      this._cursorPosition = _cursorPosition;
      this._languageConfigurationService = _languageConfigurationService;
      this._logService = _logService;
      this._configurationService = _configurationService;
      this._instantiationService = _instantiationService;
      this._contextKeyService = _contextKeyService;
      this._updateOperation = this._register(new MutableDisposable());
      this._state = observableReducerSettable(this, {
        initial: () => ({
          inlineCompletions: InlineCompletionsState.createEmpty(),
          suggestWidgetInlineCompletions: InlineCompletionsState.createEmpty()
        }),
        disposeFinal: (values) => {
          values.inlineCompletions.dispose();
          values.suggestWidgetInlineCompletions.dispose();
        },
        changeTracker: recordChangesLazy(() => ({ versionId: this._versionId })),
        update: (reader, previousValue, changes) => {
          const edit2 = StringEdit.compose(changes.changes.map((c) => c.change ? offsetEditFromContentChanges(c.change.changes) : StringEdit.empty).filter(isDefined));
          if (edit2.isEmpty()) {
            return previousValue;
          }
          try {
            return {
              inlineCompletions: previousValue.inlineCompletions.createStateWithAppliedEdit(edit2, this._textModel),
              suggestWidgetInlineCompletions: previousValue.suggestWidgetInlineCompletions.createStateWithAppliedEdit(edit2, this._textModel)
            };
          } finally {
            previousValue.inlineCompletions.dispose();
            previousValue.suggestWidgetInlineCompletions.dispose();
          }
        }
      });
      this.inlineCompletions = this._state.map(this, (v) => v.inlineCompletions);
      this.suggestWidgetInlineCompletions = this._state.map(this, (v) => v.suggestWidgetInlineCompletions);
      this._completionsEnabled = void 0;
      this.clearOperationOnTextModelChange = derived(this, (reader) => {
        this._versionId.read(reader);
        this._updateOperation.clear();
        return void 0;
      });
      this._loadingCount = observableValue(this, 0);
      this._loggingEnabled = observableConfigValue("editor.inlineSuggest.logFetch", false, this._configurationService).recomputeInitiallyAndOnChange(this._store);
      this._sendRequestData = observableConfigValue("editor.inlineSuggest.emptyResponseInformation", true, this._configurationService).recomputeInitiallyAndOnChange(this._store);
      this._structuredFetchLogger = this._register(this._instantiationService.createInstance(StructuredLogger.cast(), "editor.inlineSuggest.logFetch.commandId"));
      this.clearOperationOnTextModelChange.recomputeInitiallyAndOnChange(this._store);
      const enablementSetting = product$1.defaultChatAgent?.completionsEnablementSetting ?? void 0;
      if (enablementSetting) {
        this._updateCompletionsEnablement(enablementSetting);
        this._register(this._configurationService.onDidChangeConfiguration((e) => {
          if (e.affectsConfiguration(enablementSetting)) {
            this._updateCompletionsEnablement(enablementSetting);
          }
        }));
      }
      this._state.recomputeInitiallyAndOnChange(this._store);
    }
    _updateCompletionsEnablement(enalementSetting) {
      const result = this._configurationService.getValue(enalementSetting);
      if (!isObject(result)) {
        this._completionsEnabled = void 0;
      } else {
        this._completionsEnabled = result;
      }
    }
    _log(entry) {
      if (this._loggingEnabled.get()) {
        this._logService.info(formatRecordableLogEntry(entry));
      }
      this._structuredFetchLogger.log(entry);
    }
    fetch(providers, providersLabel, context, activeInlineCompletion, withDebounce, userJumpedToActiveCompletion, requestInfo) {
      const position = this._cursorPosition.get();
      const request = new UpdateRequest(position, context, this._textModel.getVersionId(), new Set(providers));
      const target = context.selectedSuggestionInfo ? this.suggestWidgetInlineCompletions.get() : this.inlineCompletions.get();
      if (this._updateOperation.value?.request.satisfies(request)) {
        return this._updateOperation.value.promise;
      } else if (target?.request?.satisfies(request)) {
        return Promise.resolve(true);
      }
      const updateOngoing = !!this._updateOperation.value;
      this._updateOperation.clear();
      const source = new CancellationTokenSource$1();
      const promise = (async () => {
        const store = new DisposableStore();
        this._loadingCount.set(this._loadingCount.get() + 1, void 0);
        let didDecrease = false;
        const decreaseLoadingCount = () => {
          if (!didDecrease) {
            didDecrease = true;
            this._loadingCount.set(this._loadingCount.get() - 1, void 0);
          }
        };
        const loadingReset = store.add(new RunOnceScheduler(() => decreaseLoadingCount(), 10 * 1e3));
        loadingReset.schedule();
        const inlineSuggestionsProviders = providers.filter((p) => p.providerId);
        const requestResponseInfo = new RequestResponseData(context, requestInfo, inlineSuggestionsProviders);
        try {
          const recommendedDebounceValue = this._debounceValue.get(this._textModel);
          const debounceValue = findLastMax(providers.map((p) => p.debounceDelayMs), compareUndefinedSmallest(numberComparator)) ?? recommendedDebounceValue;
          const shouldDebounce = updateOngoing || withDebounce && context.triggerKind === InlineCompletionTriggerKind$1.Automatic;
          if (shouldDebounce) {
            await wait(debounceValue, source.token);
          }
          if (source.token.isCancellationRequested || this._store.isDisposed || this._textModel.getVersionId() !== request.versionId) {
            requestResponseInfo.setNoSuggestionReasonIfNotSet("canceled:beforeFetch");
            return false;
          }
          const requestId = InlineCompletionsSource_1._requestId++;
          if (this._loggingEnabled.get() || this._structuredFetchLogger.isEnabled.get()) {
            this._log({
              sourceId: "InlineCompletions.fetch",
              kind: "start",
              requestId,
              modelUri: this._textModel.uri,
              modelVersion: this._textModel.getVersionId(),
              context: { triggerKind: context.triggerKind, suggestInfo: context.selectedSuggestionInfo ? true : void 0 },
              time: Date.now(),
              provider: providersLabel
            });
          }
          const startTime = /* @__PURE__ */ new Date();
          const providerResult = provideInlineCompletions(providers, this._cursorPosition.get(), this._textModel, context, requestInfo, this._languageConfigurationService);
          runWhenCancelled(source.token, () => providerResult.cancelAndDispose({ kind: "tokenCancellation" }));
          let shouldStopEarly = false;
          let producedSuggestion = false;
          const suggestions = [];
          for await (const list2 of providerResult.lists) {
            if (!list2) {
              continue;
            }
            list2.addRef();
            store.add(toDisposable(() => list2.removeRef(list2.inlineSuggestionsData.length === 0 ? { kind: "empty" } : { kind: "notTaken" })));
            for (const item of list2.inlineSuggestionsData) {
              producedSuggestion = true;
              if (!context.includeInlineEdits && (item.isInlineEdit || item.showInlineEditMenu)) {
                item.setNotShownReason("notInlineEditRequested");
                continue;
              }
              if (!context.includeInlineCompletions && !(item.isInlineEdit || item.showInlineEditMenu)) {
                item.setNotShownReason("notInlineCompletionRequested");
                continue;
              }
              const i2 = InlineSuggestionItem.create(item, this._textModel);
              suggestions.push(i2);
              if (!i2.isInlineEdit && !i2.showInlineEditMenu && context.triggerKind === InlineCompletionTriggerKind$1.Automatic) {
                if (i2.isVisible(this._textModel, this._cursorPosition.get())) {
                  shouldStopEarly = true;
                }
              }
            }
            if (shouldStopEarly) {
              break;
            }
          }
          providerResult.cancelAndDispose({ kind: "lostRace" });
          if (this._loggingEnabled.get() || this._structuredFetchLogger.isEnabled.get()) {
            const didAllProvidersReturn = providerResult.didAllProvidersReturn;
            let error = void 0;
            if (source.token.isCancellationRequested || this._store.isDisposed || this._textModel.getVersionId() !== request.versionId) {
              error = "canceled";
            }
            const result = suggestions.map((c) => ({
              range: c.editRange.toString(),
              text: c.insertText,
              hint: c.hint,
              isInlineEdit: c.isInlineEdit,
              showInlineEditMenu: c.showInlineEditMenu,
              providerId: c.source.provider.providerId?.toString()
            }));
            this._log({ sourceId: "InlineCompletions.fetch", kind: "end", requestId, durationMs: Date.now() - startTime.getTime(), error, result, time: Date.now(), didAllProvidersReturn });
          }
          requestResponseInfo.setRequestUuid(providerResult.contextWithUuid.requestUuid);
          if (producedSuggestion) {
            requestResponseInfo.setHasProducedSuggestion();
            if (suggestions.length > 0 && source.token.isCancellationRequested) {
              suggestions.forEach((s) => s.setNotShownReasonIfNotSet("canceled:whileAwaitingOtherProviders"));
            }
          } else {
            if (source.token.isCancellationRequested) {
              requestResponseInfo.setNoSuggestionReasonIfNotSet("canceled:whileFetching");
            } else {
              const completionsQuotaExceeded = this._contextKeyService.getContextKeyValue("completionsQuotaExceeded");
              requestResponseInfo.setNoSuggestionReasonIfNotSet(completionsQuotaExceeded ? "completionsQuotaExceeded" : "noSuggestion");
            }
          }
          const remainingTimeToWait = context.earliestShownDateTime - Date.now();
          if (remainingTimeToWait > 0) {
            await wait(remainingTimeToWait, source.token);
          }
          if (source.token.isCancellationRequested || this._store.isDisposed || this._textModel.getVersionId() !== request.versionId || userJumpedToActiveCompletion.get()) {
            const notShownReason = source.token.isCancellationRequested ? "canceled:afterMinShowDelay" : this._store.isDisposed ? "canceled:disposed" : this._textModel.getVersionId() !== request.versionId ? "canceled:documentChanged" : userJumpedToActiveCompletion.get() ? "canceled:userJumped" : "unknown";
            suggestions.forEach((s) => s.setNotShownReasonIfNotSet(notShownReason));
            return false;
          }
          const endTime = /* @__PURE__ */ new Date();
          this._debounceValue.update(this._textModel, endTime.getTime() - startTime.getTime());
          const cursorPosition = this._cursorPosition.get();
          this._updateOperation.clear();
          transaction((tx) => {
            const v = this._state.get();
            if (context.selectedSuggestionInfo) {
              this._state.set({
                inlineCompletions: InlineCompletionsState.createEmpty(),
                suggestWidgetInlineCompletions: v.suggestWidgetInlineCompletions.createStateWithAppliedResults(suggestions, request, this._textModel, cursorPosition, activeInlineCompletion)
              }, tx);
            } else {
              this._state.set({
                inlineCompletions: v.inlineCompletions.createStateWithAppliedResults(suggestions, request, this._textModel, cursorPosition, activeInlineCompletion),
                suggestWidgetInlineCompletions: InlineCompletionsState.createEmpty()
              }, tx);
            }
            v.inlineCompletions.dispose();
            v.suggestWidgetInlineCompletions.dispose();
          });
        } finally {
          store.dispose();
          decreaseLoadingCount();
          this.sendInlineCompletionsRequestTelemetry(requestResponseInfo);
        }
        return true;
      })();
      const updateOperation = new UpdateOperation(request, source, promise);
      this._updateOperation.value = updateOperation;
      return promise;
    }
    clear(tx) {
      this._updateOperation.clear();
      const v = this._state.get();
      this._state.set({
        inlineCompletions: InlineCompletionsState.createEmpty(),
        suggestWidgetInlineCompletions: InlineCompletionsState.createEmpty()
      }, tx);
      v.inlineCompletions.dispose();
      v.suggestWidgetInlineCompletions.dispose();
    }
    seedInlineCompletionsWithSuggestWidget() {
      const inlineCompletions = this.inlineCompletions.get();
      const suggestWidgetInlineCompletions = this.suggestWidgetInlineCompletions.get();
      if (!suggestWidgetInlineCompletions) {
        return;
      }
      transaction((tx) => {
        if (!inlineCompletions || (suggestWidgetInlineCompletions.request?.versionId ?? -1) > (inlineCompletions.request?.versionId ?? -1)) {
          inlineCompletions?.dispose();
          const s = this._state.get();
          this._state.set({
            inlineCompletions: suggestWidgetInlineCompletions.clone(),
            suggestWidgetInlineCompletions: InlineCompletionsState.createEmpty()
          }, tx);
          s.inlineCompletions.dispose();
          s.suggestWidgetInlineCompletions.dispose();
        }
        this.clearSuggestWidgetInlineCompletions(tx);
      });
    }
    sendInlineCompletionsRequestTelemetry(requestResponseInfo) {
      if (!this._sendRequestData.get() && !this._contextKeyService.getContextKeyValue("isRunningUnificationExperiment")) {
        return;
      }
      if (requestResponseInfo.requestUuid === void 0 || requestResponseInfo.hasProducedSuggestion) {
        return;
      }
      if (!isCompletionsEnabled(this._completionsEnabled, this._textModel.getLanguageId())) {
        return;
      }
      if (!requestResponseInfo.providers.some((p) => isCopilotLikeExtension(p.providerId?.extensionId))) {
        return;
      }
      const emptyEndOfLifeEvent = {
        opportunityId: requestResponseInfo.requestUuid,
        noSuggestionReason: requestResponseInfo.noSuggestionReason ?? "unknown",
        extensionId: "vscode-core",
        extensionVersion: "0.0.0",
        groupId: "empty",
        shown: false,
        editorType: requestResponseInfo.requestInfo.editorType,
        requestReason: requestResponseInfo.requestInfo.reason,
        typingInterval: requestResponseInfo.requestInfo.typingInterval,
        typingIntervalCharacterCount: requestResponseInfo.requestInfo.typingIntervalCharacterCount,
        languageId: requestResponseInfo.requestInfo.languageId,
        selectedSuggestionInfo: !!requestResponseInfo.context.selectedSuggestionInfo,
        availableProviders: requestResponseInfo.providers.map((p) => p.providerId?.toString()).filter(isDefined).join(","),
        ...forwardToChannelIf(requestResponseInfo.providers.some((p) => isCopilotLikeExtension(p.providerId?.extensionId))),
        timeUntilProviderRequest: void 0,
        timeUntilProviderResponse: void 0,
        viewKind: void 0,
        preceeded: void 0,
        superseded: void 0,
        reason: void 0,
        correlationId: void 0,
        shownDuration: void 0,
        shownDurationUncollapsed: void 0,
        timeUntilShown: void 0,
        partiallyAccepted: void 0,
        partiallyAcceptedCountSinceOriginal: void 0,
        partiallyAcceptedRatioSinceOriginal: void 0,
        partiallyAcceptedCharactersSinceOriginal: void 0,
        cursorColumnDistance: void 0,
        cursorLineDistance: void 0,
        lineCountOriginal: void 0,
        lineCountModified: void 0,
        characterCountOriginal: void 0,
        characterCountModified: void 0,
        disjointReplacements: void 0,
        sameShapeReplacements: void 0,
        notShownReason: void 0
      };
      const dataChannel = this._instantiationService.createInstance(DataChannelForwardingTelemetryService);
      sendInlineCompletionsEndOfLifeTelemetry(dataChannel, emptyEndOfLifeEvent);
    }
    clearSuggestWidgetInlineCompletions(tx) {
      if (this._updateOperation.value?.request.context.selectedSuggestionInfo) {
        this._updateOperation.clear();
      }
    }
    cancelUpdate() {
      this._updateOperation.clear();
    }
  }, InlineCompletionsSource_1 = _aa, _aa._requestId = 0, _aa);
  InlineCompletionsSource = InlineCompletionsSource_1 = __decorate$1w([
    __param$1v(4, ILanguageConfigurationService),
    __param$1v(5, ILogService),
    __param$1v(6, IConfigurationService),
    __param$1v(7, IInstantiationService),
    __param$1v(8, IContextKeyService)
  ], InlineCompletionsSource);
  class UpdateRequest {
    constructor(position, context, versionId, providers) {
      this.position = position;
      this.context = context;
      this.versionId = versionId;
      this.providers = providers;
    }
    satisfies(other) {
      return this.position.equals(other.position) && equalsIfDefined(this.context.selectedSuggestionInfo, other.context.selectedSuggestionInfo, itemEquals()) && (other.context.triggerKind === InlineCompletionTriggerKind$1.Automatic || this.context.triggerKind === InlineCompletionTriggerKind$1.Explicit) && this.versionId === other.versionId && isSubset(other.providers, this.providers);
    }
  }
  class RequestResponseData {
    constructor(context, requestInfo, providers) {
      this.context = context;
      this.requestInfo = requestInfo;
      this.providers = providers;
      this.hasProducedSuggestion = false;
    }
    setRequestUuid(uuid) {
      this.requestUuid = uuid;
    }
    setNoSuggestionReasonIfNotSet(type) {
      this.noSuggestionReason ??= type;
    }
    setHasProducedSuggestion() {
      this.hasProducedSuggestion = true;
    }
  }
  function isSubset(set1, set2) {
    return [...set1].every((item) => set2.has(item));
  }
  function isCompletionsEnabled(completionsEnablementObject, modeId = "*") {
    if (completionsEnablementObject === void 0) {
      return false;
    }
    if (typeof completionsEnablementObject[modeId] !== "undefined") {
      return Boolean(completionsEnablementObject[modeId]);
    }
    return Boolean(completionsEnablementObject["*"]);
  }
  class UpdateOperation {
    constructor(request, cancellationTokenSource, promise) {
      this.request = request;
      this.cancellationTokenSource = cancellationTokenSource;
      this.promise = promise;
    }
    dispose() {
      this.cancellationTokenSource.cancel();
    }
  }
  class InlineCompletionsState extends Disposable {
    static createEmpty() {
      return new InlineCompletionsState([], void 0);
    }
    constructor(inlineCompletions, request) {
      for (const inlineCompletion of inlineCompletions) {
        inlineCompletion.addRef();
      }
      super();
      this.inlineCompletions = inlineCompletions;
      this.request = request;
      this._register({
        dispose: () => {
          for (const inlineCompletion of this.inlineCompletions) {
            inlineCompletion.removeRef();
          }
        }
      });
    }
    _findById(id) {
      return this.inlineCompletions.find((i2) => i2.identity === id);
    }
    _findByHash(hash2) {
      return this.inlineCompletions.find((i2) => i2.hash === hash2);
    }
    /**
     * Applies the edit on the state.
    */
    createStateWithAppliedEdit(edit2, textModel) {
      const newInlineCompletions = this.inlineCompletions.map((i2) => i2.withEdit(edit2, textModel)).filter(isDefined);
      return new InlineCompletionsState(newInlineCompletions, this.request);
    }
    createStateWithAppliedResults(updatedSuggestions, request, textModel, cursorPosition, itemIdToPreserveAtTop) {
      let itemToPreserve = void 0;
      if (itemIdToPreserveAtTop) {
        const itemToPreserveCandidate = this._findById(itemIdToPreserveAtTop);
        if (itemToPreserveCandidate && itemToPreserveCandidate.canBeReused(textModel, request.position)) {
          itemToPreserve = itemToPreserveCandidate;
          const updatedItemToPreserve = updatedSuggestions.find((i2) => i2.hash === itemToPreserveCandidate.hash);
          if (updatedItemToPreserve) {
            updatedSuggestions = moveToFront(updatedItemToPreserve, updatedSuggestions);
          } else {
            updatedSuggestions = [itemToPreserveCandidate, ...updatedSuggestions];
          }
        }
      }
      const preferInlineCompletions = itemToPreserve ? !itemToPreserve.isInlineEdit : updatedSuggestions.some((i2) => !i2.isInlineEdit && i2.isVisible(textModel, cursorPosition));
      let updatedItems = [];
      for (const i2 of updatedSuggestions) {
        const oldItem = this._findByHash(i2.hash);
        let item;
        if (oldItem && oldItem !== i2) {
          item = i2.withIdentity(oldItem.identity);
          i2.setIsPreceeded(oldItem);
          oldItem.setEndOfLifeReason({ kind: InlineCompletionEndOfLifeReasonKind$1.Ignored, userTypingDisagreed: false, supersededBy: i2.getSourceCompletion() });
        } else {
          item = i2;
        }
        if (preferInlineCompletions !== item.isInlineEdit) {
          updatedItems.push(item);
        }
      }
      updatedItems.sort(compareBy((i2) => i2.showInlineEditMenu, booleanComparator));
      updatedItems = distinctByKey(updatedItems, (i2) => i2.semanticId);
      return new InlineCompletionsState(updatedItems, request);
    }
    clone() {
      return new InlineCompletionsState(this.inlineCompletions, this.request);
    }
  }
  function distinctByKey(items, key) {
    const seen = /* @__PURE__ */ new Set();
    return items.filter((item) => {
      const k = key(item);
      if (seen.has(k)) {
        return false;
      }
      seen.add(k);
      return true;
    });
  }
  function moveToFront(item, items) {
    const index = items.indexOf(item);
    if (index > -1) {
      return [item, ...items.slice(0, index), ...items.slice(index + 1)];
    }
    return items;
  }
  class InlineEdit {
    constructor(edit2, commands, inlineCompletion) {
      this.edit = edit2;
      this.commands = commands;
      this.inlineCompletion = inlineCompletion;
    }
    equals(other) {
      return this.edit.equals(other.edit) && this.inlineCompletion === other.inlineCompletion;
    }
  }
  var __decorate$1v = 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$1u = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  const IInlineCompletionsService = createDecorator("IInlineCompletionsService");
  const InlineCompletionsSnoozing = new RawContextKey("inlineCompletions.snoozed", false, localize(79, "Whether inline completions are currently snoozed"));
  let InlineCompletionsService = class InlineCompletionsService extends Disposable {
    get snoozeTimeLeft() {
      if (this._snoozeTimeEnd === void 0) {
        return 0;
      }
      return Math.max(0, this._snoozeTimeEnd - Date.now());
    }
    constructor(_contextKeyService, _telemetryService) {
      super();
      this._contextKeyService = _contextKeyService;
      this._telemetryService = _telemetryService;
      this._onDidChangeIsSnoozing = this._register(new Emitter$1());
      this.onDidChangeIsSnoozing = this._onDidChangeIsSnoozing.event;
      this._snoozeTimeEnd = void 0;
      this._recentCompletionIds = [];
      this._timer = this._register(new TimeoutTimer());
      const inlineCompletionsSnoozing = InlineCompletionsSnoozing.bindTo(this._contextKeyService);
      this._register(this.onDidChangeIsSnoozing(() => inlineCompletionsSnoozing.set(this.isSnoozing())));
    }
    setSnoozeDuration(durationMs) {
      if (durationMs < 0) {
        throw new BugIndicatingError(`Invalid snooze duration: ${durationMs}. Duration must be non-negative.`);
      }
      if (durationMs === 0) {
        this.cancelSnooze();
        return;
      }
      const wasSnoozing = this.isSnoozing();
      const timeLeft = this.snoozeTimeLeft;
      this._snoozeTimeEnd = Date.now() + durationMs;
      if (!wasSnoozing) {
        this._onDidChangeIsSnoozing.fire(true);
      }
      this._timer.cancelAndSet(() => {
        if (!this.isSnoozing()) {
          this._onDidChangeIsSnoozing.fire(false);
        } else {
          throw new BugIndicatingError("Snooze timer did not fire as expected");
        }
      }, this.snoozeTimeLeft + 1);
      this._reportSnooze(durationMs - timeLeft, durationMs);
    }
    isSnoozing() {
      return this.snoozeTimeLeft > 0;
    }
    cancelSnooze() {
      if (this.isSnoozing()) {
        this._reportSnooze(-this.snoozeTimeLeft, 0);
        this._snoozeTimeEnd = void 0;
        this._timer.cancel();
        this._onDidChangeIsSnoozing.fire(false);
      }
    }
    reportNewCompletion(requestUuid) {
      this._lastCompletionId = requestUuid;
      this._recentCompletionIds.unshift(requestUuid);
      if (this._recentCompletionIds.length > 5) {
        this._recentCompletionIds.pop();
      }
    }
    _reportSnooze(deltaMs, totalMs) {
      const deltaSeconds = Math.round(deltaMs / 1e3);
      const totalSeconds = Math.round(totalMs / 1e3);
      this._telemetryService.publicLog2("inlineCompletions.snooze", {
        deltaSeconds,
        totalSeconds,
        lastCompletionId: this._lastCompletionId,
        recentCompletionIds: this._recentCompletionIds
      });
    }
  };
  InlineCompletionsService = __decorate$1v([
    __param$1u(0, IContextKeyService),
    __param$1u(1, ITelemetryService)
  ], InlineCompletionsService);
  registerSingleton(
    IInlineCompletionsService,
    InlineCompletionsService,
    1
    /* InstantiationType.Delayed */
  );
  const snoozeInlineSuggestId = "editor.action.inlineSuggest.snooze";
  const cancelSnoozeInlineSuggestId = "editor.action.inlineSuggest.cancelSnooze";
  const LAST_SNOOZE_DURATION_KEY = "inlineCompletions.lastSnoozeDuration";
  const _SnoozeInlineCompletion = class _SnoozeInlineCompletion extends Action2 {
    constructor() {
      super({
        id: _SnoozeInlineCompletion.ID,
        title: localize2(81, "Snooze Inline Suggestions"),
        precondition: ContextKeyExpr.true(),
        f1: true
      });
    }
    async run(accessor, ...args) {
      const quickInputService = accessor.get(IQuickInputService);
      const inlineCompletionsService = accessor.get(IInlineCompletionsService);
      const storageService = accessor.get(IStorageService);
      let durationMs;
      if (args.length > 0 && typeof args[0] === "number") {
        durationMs = args[0] * 6e4;
      }
      if (!durationMs) {
        durationMs = await this.getDurationFromUser(quickInputService, storageService);
      }
      if (durationMs) {
        inlineCompletionsService.setSnoozeDuration(durationMs);
      }
    }
    async getDurationFromUser(quickInputService, storageService) {
      const lastSelectedDuration = storageService.getNumber(LAST_SNOOZE_DURATION_KEY, 0, 3e5);
      const items = [
        { label: "1 minute", id: "1", value: 6e4 },
        { label: "5 minutes", id: "5", value: 3e5 },
        { label: "10 minutes", id: "10", value: 6e5 },
        { label: "15 minutes", id: "15", value: 9e5 },
        { label: "30 minutes", id: "30", value: 18e5 },
        { label: "60 minutes", id: "60", value: 36e5 }
      ];
      const picked = await quickInputService.pick(items, {
        placeHolder: localize(80, "Select snooze duration for Inline Suggestions"),
        activeItem: items.find((item) => item.value === lastSelectedDuration)
      });
      if (picked) {
        storageService.store(
          LAST_SNOOZE_DURATION_KEY,
          picked.value,
          0,
          0
          /* StorageTarget.USER */
        );
        return picked.value;
      }
      return void 0;
    }
  };
  _SnoozeInlineCompletion.ID = snoozeInlineSuggestId;
  let SnoozeInlineCompletion = _SnoozeInlineCompletion;
  const _CancelSnoozeInlineCompletion = class _CancelSnoozeInlineCompletion extends Action2 {
    constructor() {
      super({
        id: _CancelSnoozeInlineCompletion.ID,
        title: localize2(82, "Cancel Snooze Inline Suggestions"),
        precondition: InlineCompletionsSnoozing,
        f1: true
      });
    }
    async run(accessor) {
      accessor.get(IInlineCompletionsService).cancelSnooze();
    }
  };
  _CancelSnoozeInlineCompletion.ID = cancelSnoozeInlineSuggestId;
  let CancelSnoozeInlineCompletion = _CancelSnoozeInlineCompletion;
  const _TypingInterval = class _TypingInterval extends Disposable {
    // Minimum characters needed for reliable speed calculation
    /**
     * Gets the current typing interval as average milliseconds between keystrokes
     * and the number of characters involved in the computation.
     * Higher interval values indicate slower typing.
     * Returns { interval: 0, characterCount: 0 } if no typing data is available.
     */
    getTypingInterval() {
      if (this._cacheInvalidated || this._cachedTypingIntervalResult === null) {
        this._cachedTypingIntervalResult = this._calculateTypingInterval();
        this._cacheInvalidated = false;
      }
      return this._cachedTypingIntervalResult;
    }
    constructor(_textModel) {
      super();
      this._textModel = _textModel;
      this._typingSessions = [];
      this._currentSession = null;
      this._lastChangeTime = 0;
      this._cachedTypingIntervalResult = null;
      this._cacheInvalidated = true;
      this._register(this._textModel.onDidChangeContent((e) => this._updateTypingSpeed(e)));
    }
    _updateTypingSpeed(change) {
      const now = Date.now();
      if (!this._isUserTyping(change)) {
        this._finalizeCurrentSession();
        return;
      }
      if (this._currentSession && now - this._lastChangeTime > _TypingInterval.MAX_SESSION_GAP_MS) {
        this._finalizeCurrentSession();
      }
      if (!this._currentSession) {
        this._currentSession = {
          startTime: now,
          endTime: now,
          characterCount: 0
        };
      }
      this._currentSession.endTime = now;
      this._currentSession.characterCount += this._getActualCharacterCount(change);
      this._lastChangeTime = now;
      this._cacheInvalidated = true;
    }
    _getActualCharacterCount(change) {
      let totalChars = 0;
      for (const c of change.changes) {
        totalChars += Math.max(c.text.length, c.rangeLength);
      }
      return totalChars;
    }
    _isUserTyping(change) {
      if (!change.detailedReasons || change.detailedReasons.length === 0) {
        return false;
      }
      for (const reason of change.detailedReasons) {
        if (this._isUserTypingReason(reason)) {
          return true;
        }
      }
      return false;
    }
    _isUserTypingReason(reason) {
      if (reason.metadata.isUndoing || reason.metadata.isRedoing) {
        return false;
      }
      switch (reason.metadata.source) {
        case "cursor": {
          const kind = reason.metadata.kind;
          return kind === "type" || kind === "compositionType" || kind === "compositionEnd";
        }
        default:
          return false;
      }
    }
    _finalizeCurrentSession() {
      if (!this._currentSession) {
        return;
      }
      const sessionDuration = this._currentSession.endTime - this._currentSession.startTime;
      if (sessionDuration >= _TypingInterval.MIN_SESSION_DURATION_MS && this._currentSession.characterCount > 0) {
        this._typingSessions.push(this._currentSession);
        if (this._typingSessions.length > _TypingInterval.SESSION_HISTORY_LIMIT) {
          this._typingSessions.shift();
        }
      }
      this._currentSession = null;
    }
    _calculateTypingInterval() {
      if (this._currentSession) {
        const tempSession = { ...this._currentSession };
        const sessionDuration = tempSession.endTime - tempSession.startTime;
        if (sessionDuration >= _TypingInterval.MIN_SESSION_DURATION_MS && tempSession.characterCount > 0) {
          const allSessions = [...this._typingSessions, tempSession];
          return this._calculateSpeedFromSessions(allSessions);
        }
      }
      return this._calculateSpeedFromSessions(this._typingSessions);
    }
    _calculateSpeedFromSessions(sessions) {
      if (sessions.length === 0) {
        return { averageInterval: 0, characterCount: 0 };
      }
      const sortedSessions = [...sessions].sort((a, b) => b.endTime - a.endTime);
      const cutoffTime = Date.now() - _TypingInterval.TYPING_SPEED_WINDOW_MS;
      const recentSessions = sortedSessions.filter((session) => session.endTime > cutoffTime);
      const olderSessions = sortedSessions.splice(recentSessions.length);
      let totalChars = sum(recentSessions.map((session) => session.characterCount));
      for (let i2 = 0; i2 < olderSessions.length && totalChars < _TypingInterval.MIN_CHARS_FOR_RELIABLE_SPEED; i2++) {
        recentSessions.push(olderSessions[i2]);
        totalChars += olderSessions[i2].characterCount;
      }
      const totalTime = sum(recentSessions.map((session) => session.endTime - session.startTime));
      if (totalTime === 0 || totalChars <= 1) {
        return { averageInterval: 0, characterCount: totalChars };
      }
      const keystrokeIntervals = Math.max(1, totalChars - 1);
      const avgMsBetweenKeystrokes = totalTime / keystrokeIntervals;
      return {
        averageInterval: Math.round(avgMsBetweenKeystrokes),
        characterCount: totalChars
      };
    }
    dispose() {
      this._finalizeCurrentSession();
      super.dispose();
    }
  };
  _TypingInterval.MAX_SESSION_GAP_MS = 3e3;
  _TypingInterval.MIN_SESSION_DURATION_MS = 1e3;
  _TypingInterval.SESSION_HISTORY_LIMIT = 50;
  _TypingInterval.TYPING_SPEED_WINDOW_MS = 3e5;
  _TypingInterval.MIN_CHARS_FOR_RELIABLE_SPEED = 20;
  let TypingInterval = _TypingInterval;
  var __decorate$1u = 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$1t = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  let InlineCompletionsModel = class InlineCompletionsModel extends Disposable {
    get isAcceptingPartially() {
      return this._isAcceptingPartially;
    }
    constructor(textModel, _selectedSuggestItem, _textModelVersionId, _positions, _debounceValue, _enabled, _editor, _instantiationService, _commandService, _languageConfigurationService, _accessibilityService, _languageFeaturesService, _codeEditorService, _inlineCompletionsService) {
      super();
      this.textModel = textModel;
      this._selectedSuggestItem = _selectedSuggestItem;
      this._textModelVersionId = _textModelVersionId;
      this._positions = _positions;
      this._debounceValue = _debounceValue;
      this._enabled = _enabled;
      this._editor = _editor;
      this._instantiationService = _instantiationService;
      this._commandService = _commandService;
      this._languageConfigurationService = _languageConfigurationService;
      this._accessibilityService = _accessibilityService;
      this._languageFeaturesService = _languageFeaturesService;
      this._codeEditorService = _codeEditorService;
      this._inlineCompletionsService = _inlineCompletionsService;
      this._isActive = observableValue(this, false);
      this._onlyRequestInlineEditsSignal = observableSignal(this);
      this._forceUpdateExplicitlySignal = observableSignal(this);
      this._noDelaySignal = observableSignal(this);
      this._fetchSpecificProviderSignal = observableSignal(this);
      this._selectedInlineCompletionId = observableValue(this, void 0);
      this.primaryPosition = derived(this, (reader) => this._positions.read(reader)[0] ?? new Position$1(1, 1));
      this.allPositions = derived(this, (reader) => this._positions.read(reader));
      this._isAcceptingPartially = false;
      this._appearedInsideViewport = derived(this, (reader) => {
        const state = this.state.read(reader);
        if (!state || !state.inlineCompletion) {
          return false;
        }
        return isSuggestionInViewport(this._editor, state.inlineCompletion);
      });
      this._onDidAccept = new Emitter$1();
      this.onDidAccept = this._onDidAccept.event;
      this._lastShownInlineCompletionInfo = void 0;
      this._lastAcceptedInlineCompletionInfo = void 0;
      this._didUndoInlineEdits = derivedHandleChanges({
        owner: this,
        changeTracker: {
          createChangeSummary: () => ({ didUndo: false }),
          handleChange: (ctx, changeSummary) => {
            changeSummary.didUndo = ctx.didChange(this._textModelVersionId) && !!ctx.change?.isUndoing;
            return true;
          }
        }
      }, (reader, changeSummary) => {
        const versionId = this._textModelVersionId.read(reader);
        if (versionId !== null && this._lastAcceptedInlineCompletionInfo && this._lastAcceptedInlineCompletionInfo.textModelVersionIdAfter === versionId - 1 && this._lastAcceptedInlineCompletionInfo.inlineCompletion.isInlineEdit && changeSummary.didUndo) {
          this._lastAcceptedInlineCompletionInfo = void 0;
          return true;
        }
        return false;
      });
      this._preserveCurrentCompletionReasons = /* @__PURE__ */ new Set([
        VersionIdChangeReason.Redo,
        VersionIdChangeReason.Undo,
        VersionIdChangeReason.AcceptWord
      ]);
      this.dontRefetchSignal = observableSignal(this);
      this._fetchInlineCompletionsPromise = derivedHandleChanges({
        owner: this,
        changeTracker: {
          createChangeSummary: () => ({
            dontRefetch: false,
            preserveCurrentCompletion: false,
            inlineCompletionTriggerKind: InlineCompletionTriggerKind$1.Automatic,
            onlyRequestInlineEdits: false,
            shouldDebounce: true,
            provider: void 0,
            textChange: false,
            changeReason: ""
          }),
          handleChange: (ctx, changeSummary) => {
            if (ctx.didChange(this._textModelVersionId)) {
              if (this._preserveCurrentCompletionReasons.has(this._getReason(ctx.change))) {
                changeSummary.preserveCurrentCompletion = true;
              }
              const detailedReasons = ctx.change?.detailedReasons ?? [];
              changeSummary.changeReason = detailedReasons.length > 0 ? detailedReasons[0].getType() : "";
              changeSummary.textChange = true;
            } else if (ctx.didChange(this._forceUpdateExplicitlySignal)) {
              changeSummary.preserveCurrentCompletion = true;
              changeSummary.inlineCompletionTriggerKind = InlineCompletionTriggerKind$1.Explicit;
            } else if (ctx.didChange(this.dontRefetchSignal)) {
              changeSummary.dontRefetch = true;
            } else if (ctx.didChange(this._onlyRequestInlineEditsSignal)) {
              changeSummary.onlyRequestInlineEdits = true;
            } else if (ctx.didChange(this._fetchSpecificProviderSignal)) {
              changeSummary.provider = ctx.change;
            }
            return true;
          }
        }
      }, (reader, changeSummary) => {
        this._source.clearOperationOnTextModelChange.read(reader);
        this._noDelaySignal.read(reader);
        this.dontRefetchSignal.read(reader);
        this._onlyRequestInlineEditsSignal.read(reader);
        this._forceUpdateExplicitlySignal.read(reader);
        this._fetchSpecificProviderSignal.read(reader);
        const shouldUpdate = (this._enabled.read(reader) && this._selectedSuggestItem.read(reader) || this._isActive.read(reader)) && (!this._inlineCompletionsService.isSnoozing() || changeSummary.inlineCompletionTriggerKind === InlineCompletionTriggerKind$1.Explicit);
        if (!shouldUpdate) {
          this._source.cancelUpdate();
          return void 0;
        }
        this._textModelVersionId.read(reader);
        const suggestWidgetInlineCompletions = this._source.suggestWidgetInlineCompletions.read(void 0);
        let suggestItem = this._selectedSuggestItem.read(reader);
        if (this._shouldShowOnSuggestConflict.read(void 0)) {
          suggestItem = void 0;
        }
        if (suggestWidgetInlineCompletions && !suggestItem) {
          this._source.seedInlineCompletionsWithSuggestWidget();
        }
        if (changeSummary.dontRefetch) {
          return Promise.resolve(true);
        }
        if (this._didUndoInlineEdits.read(reader) && changeSummary.inlineCompletionTriggerKind !== InlineCompletionTriggerKind$1.Explicit) {
          transaction((tx) => {
            this._source.clear(tx);
          });
          return void 0;
        }
        let reason = "";
        if (changeSummary.provider) {
          reason += "providerOnDidChange";
        } else if (changeSummary.inlineCompletionTriggerKind === InlineCompletionTriggerKind$1.Explicit) {
          reason += "explicit";
        }
        if (changeSummary.changeReason) {
          reason += reason.length > 0 ? `:${changeSummary.changeReason}` : changeSummary.changeReason;
        }
        const typingInterval = this._typing.getTypingInterval();
        const requestInfo = {
          editorType: this.editorType,
          startTime: Date.now(),
          languageId: this.textModel.getLanguageId(),
          reason,
          typingInterval: typingInterval.averageInterval,
          typingIntervalCharacterCount: typingInterval.characterCount,
          availableProviders: []
        };
        let context = {
          triggerKind: changeSummary.inlineCompletionTriggerKind,
          selectedSuggestionInfo: suggestItem?.toSelectedSuggestionInfo(),
          includeInlineCompletions: !changeSummary.onlyRequestInlineEdits,
          includeInlineEdits: this._inlineEditsEnabled.read(reader),
          requestIssuedDateTime: requestInfo.startTime,
          earliestShownDateTime: requestInfo.startTime + (changeSummary.inlineCompletionTriggerKind === InlineCompletionTriggerKind$1.Explicit || this.inAcceptFlow.read(void 0) ? 0 : this._minShowDelay.read(void 0))
        };
        if (context.triggerKind === InlineCompletionTriggerKind$1.Automatic && changeSummary.textChange) {
          if (this.textModel.getAlternativeVersionId() === this._lastShownInlineCompletionInfo?.alternateTextModelVersionId) {
            context = {
              ...context,
              includeInlineCompletions: !this._lastShownInlineCompletionInfo.inlineCompletion.isInlineEdit,
              includeInlineEdits: this._lastShownInlineCompletionInfo.inlineCompletion.isInlineEdit
            };
          }
        }
        const itemToPreserveCandidate = this.selectedInlineCompletion.read(void 0) ?? this._inlineCompletionItems.read(void 0)?.inlineEdit;
        const itemToPreserve = changeSummary.preserveCurrentCompletion || itemToPreserveCandidate?.forwardStable ? itemToPreserveCandidate : void 0;
        const userJumpedToActiveCompletion = this._jumpedToId.map((jumpedTo) => !!jumpedTo && jumpedTo === this._inlineCompletionItems.read(void 0)?.inlineEdit?.semanticId);
        const providers = changeSummary.provider ? { providers: [changeSummary.provider], label: "single:" + changeSummary.provider.providerId?.toString() } : { providers: this._languageFeaturesService.inlineCompletionsProvider.all(this.textModel), label: void 0 };
        const availableProviders = this.getAvailableProviders(providers.providers);
        requestInfo.availableProviders = availableProviders.map((p) => p.providerId).filter(isDefined);
        return this._source.fetch(availableProviders, providers.label, context, itemToPreserve?.identity, changeSummary.shouldDebounce, userJumpedToActiveCompletion, requestInfo);
      });
      this._inlineCompletionItems = derivedOpts({ owner: this }, (reader) => {
        const c = this._source.inlineCompletions.read(reader);
        if (!c) {
          return void 0;
        }
        const cursorPosition = this.primaryPosition.read(reader);
        let inlineEdit = void 0;
        const visibleCompletions = [];
        for (const completion of c.inlineCompletions) {
          if (!completion.isInlineEdit) {
            if (completion.isVisible(this.textModel, cursorPosition)) {
              visibleCompletions.push(completion);
            }
          } else {
            inlineEdit = completion;
          }
        }
        if (visibleCompletions.length !== 0) {
          inlineEdit = void 0;
        }
        return {
          inlineCompletions: visibleCompletions,
          inlineEdit
        };
      });
      this._filteredInlineCompletionItems = derivedOpts({ owner: this, equalsFn: itemsEquals() }, (reader) => {
        const c = this._inlineCompletionItems.read(reader);
        return c?.inlineCompletions ?? [];
      });
      this.selectedInlineCompletionIndex = derived(this, (reader) => {
        const selectedInlineCompletionId = this._selectedInlineCompletionId.read(reader);
        const filteredCompletions = this._filteredInlineCompletionItems.read(reader);
        const idx = this._selectedInlineCompletionId === void 0 ? -1 : filteredCompletions.findIndex((v) => v.semanticId === selectedInlineCompletionId);
        if (idx === -1) {
          this._selectedInlineCompletionId.set(void 0, void 0);
          return 0;
        }
        return idx;
      });
      this.selectedInlineCompletion = derived(this, (reader) => {
        const filteredCompletions = this._filteredInlineCompletionItems.read(reader);
        const idx = this.selectedInlineCompletionIndex.read(reader);
        return filteredCompletions[idx];
      });
      this.activeCommands = derivedOpts({ owner: this, equalsFn: itemsEquals() }, (r) => this.selectedInlineCompletion.read(r)?.source.inlineSuggestions.commands ?? []);
      this.inlineCompletionsCount = derived(this, (reader) => {
        if (this.lastTriggerKind.read(reader) === InlineCompletionTriggerKind$1.Explicit) {
          return this._filteredInlineCompletionItems.read(reader).length;
        } else {
          return void 0;
        }
      });
      this._hasVisiblePeekWidgets = derived(this, (reader) => this._editorObs.openedPeekWidgets.read(reader) > 0);
      this._shouldShowOnSuggestConflict = derived(this, (reader) => {
        const showOnSuggestConflict = this._showOnSuggestConflict.read(reader);
        if (showOnSuggestConflict !== "never") {
          const hasInlineCompletion = !!this.selectedInlineCompletion.read(reader);
          if (hasInlineCompletion) {
            const item = this._selectedSuggestItem.read(reader);
            if (!item) {
              return false;
            }
            if (showOnSuggestConflict === "whenSuggestListIsIncomplete") {
              return item.listIncomplete;
            }
            return true;
          }
        }
        return false;
      });
      this.state = derivedOpts({
        owner: this,
        equalsFn: (a, b) => {
          if (!a || !b) {
            return a === b;
          }
          if (a.kind === "ghostText" && b.kind === "ghostText") {
            return ghostTextsOrReplacementsEqual(a.ghostTexts, b.ghostTexts) && a.inlineCompletion === b.inlineCompletion && a.suggestItem === b.suggestItem;
          } else if (a.kind === "inlineEdit" && b.kind === "inlineEdit") {
            return a.inlineEdit.equals(b.inlineEdit);
          }
          return false;
        }
      }, (reader) => {
        const model = this.textModel;
        if (this._suppressInSnippetMode.read(reader) && this._isInSnippetMode.read(reader)) {
          return void 0;
        }
        const item = this._inlineCompletionItems.read(reader);
        const inlineEditResult = item?.inlineEdit;
        if (inlineEditResult) {
          if (this._hasVisiblePeekWidgets.read(reader)) {
            return void 0;
          }
          let edit2 = inlineEditResult.getSingleTextEdit();
          edit2 = singleTextRemoveCommonPrefix(edit2, model);
          const cursorAtInlineEdit = this.primaryPosition.map((cursorPos) => LineRange.fromRangeInclusive(inlineEditResult.targetRange).addMargin(1, 1).contains(cursorPos.lineNumber));
          const commands = inlineEditResult.source.inlineSuggestions.commands;
          const inlineEdit = new InlineEdit(edit2, commands ?? [], inlineEditResult);
          const edits = inlineEditResult.updatedEdit;
          const e = edits ? TextEdit.fromStringEdit(edits, new TextModelText(this.textModel)).replacements : [edit2];
          const nextEditUri = (item.inlineEdit?.command?.id === "vscode.open" || item.inlineEdit?.command?.id === "_workbench.open") && // eslint-disable-next-line local/code-no-any-casts
          item.inlineEdit?.command.arguments?.length ? URI.from(item.inlineEdit?.command.arguments[0]) : void 0;
          return { kind: "inlineEdit", inlineEdit, inlineCompletion: inlineEditResult, edits: e, cursorAtInlineEdit, nextEditUri };
        }
        const suggestItem = this._selectedSuggestItem.read(reader);
        if (!this._shouldShowOnSuggestConflict.read(reader) && suggestItem) {
          const suggestCompletionEdit = singleTextRemoveCommonPrefix(suggestItem.getSingleTextEdit(), model);
          const augmentation = this._computeAugmentation(suggestCompletionEdit, reader);
          const isSuggestionPreviewEnabled = this._suggestPreviewEnabled.read(reader);
          if (!isSuggestionPreviewEnabled && !augmentation) {
            return void 0;
          }
          const fullEdit = augmentation?.edit ?? suggestCompletionEdit;
          const fullEditPreviewLength = augmentation ? augmentation.edit.text.length - suggestCompletionEdit.text.length : 0;
          const mode = this._suggestPreviewMode.read(reader);
          const positions = this._positions.read(reader);
          const allPotentialEdits = [fullEdit, ...getSecondaryEdits(this.textModel, positions, fullEdit)];
          const validEditsAndGhostTexts = allPotentialEdits.map((edit2, idx) => ({ edit: edit2, ghostText: edit2 ? computeGhostText(edit2, model, mode, positions[idx], fullEditPreviewLength) : void 0 })).filter(({ edit: edit2, ghostText }) => edit2 !== void 0 && ghostText !== void 0);
          const edits = validEditsAndGhostTexts.map(({ edit: edit2 }) => edit2);
          const ghostTexts = validEditsAndGhostTexts.map(({ ghostText }) => ghostText);
          const primaryGhostText = ghostTexts[0] ?? new GhostText(fullEdit.range.endLineNumber, []);
          return { kind: "ghostText", edits, primaryGhostText, ghostTexts, inlineCompletion: augmentation?.completion, suggestItem };
        } else {
          if (!this._isActive.read(reader)) {
            return void 0;
          }
          const inlineCompletion = this.selectedInlineCompletion.read(reader);
          if (!inlineCompletion) {
            return void 0;
          }
          const replacement = inlineCompletion.getSingleTextEdit();
          const mode = this._inlineSuggestMode.read(reader);
          const positions = this._positions.read(reader);
          const allPotentialEdits = [replacement, ...getSecondaryEdits(this.textModel, positions, replacement)];
          const validEditsAndGhostTexts = allPotentialEdits.map((edit2, idx) => ({ edit: edit2, ghostText: edit2 ? computeGhostText(edit2, model, mode, positions[idx], 0) : void 0 })).filter(({ edit: edit2, ghostText }) => edit2 !== void 0 && ghostText !== void 0);
          const edits = validEditsAndGhostTexts.map(({ edit: edit2 }) => edit2);
          const ghostTexts = validEditsAndGhostTexts.map(({ ghostText }) => ghostText);
          if (!ghostTexts[0]) {
            return void 0;
          }
          return { kind: "ghostText", edits, primaryGhostText: ghostTexts[0], ghostTexts, inlineCompletion, suggestItem: void 0 };
        }
      });
      this.inlineCompletionState = derived(this, (reader) => {
        const s = this.state.read(reader);
        if (!s || s.kind !== "ghostText") {
          return void 0;
        }
        if (this._editorObs.inComposition.read(reader)) {
          return void 0;
        }
        return s;
      });
      this.inlineEditState = derived(this, (reader) => {
        const s = this.state.read(reader);
        if (!s || s.kind !== "inlineEdit") {
          return void 0;
        }
        return s;
      });
      this.inlineEditAvailable = derived(this, (reader) => {
        const s = this.inlineEditState.read(reader);
        return !!s;
      });
      this.warning = derived(this, (reader) => {
        return this.inlineCompletionState.read(reader)?.inlineCompletion?.warning;
      });
      this.ghostTexts = derivedOpts({ owner: this, equalsFn: ghostTextsOrReplacementsEqual }, (reader) => {
        const v = this.inlineCompletionState.read(reader);
        if (!v) {
          return void 0;
        }
        return v.ghostTexts;
      });
      this.primaryGhostText = derivedOpts({ owner: this, equalsFn: ghostTextOrReplacementEquals }, (reader) => {
        const v = this.inlineCompletionState.read(reader);
        if (!v) {
          return void 0;
        }
        return v?.primaryGhostText;
      });
      this.showCollapsed = derived(this, (reader) => {
        const state = this.state.read(reader);
        if (!state || state.kind !== "inlineEdit") {
          return false;
        }
        if (state.inlineCompletion.hint) {
          return false;
        }
        const isCurrentModelVersion = state.inlineCompletion.updatedEditModelVersion === this._textModelVersionId.read(reader);
        return (this._inlineEditsShowCollapsedEnabled.read(reader) || !isCurrentModelVersion) && this._jumpedToId.read(reader) !== state.inlineCompletion.semanticId && !this._inAcceptFlow.read(reader);
      });
      this._tabShouldIndent = derived(this, (reader) => {
        if (this._inAcceptFlow.read(reader)) {
          return false;
        }
        function isMultiLine(range2) {
          return range2.startLineNumber !== range2.endLineNumber;
        }
        function getNonIndentationRange(model, lineNumber) {
          const columnStart = model.getLineIndentColumn(lineNumber);
          const lastNonWsColumn = model.getLineLastNonWhitespaceColumn(lineNumber);
          const columnEnd = Math.max(lastNonWsColumn, columnStart);
          return new Range$2(lineNumber, columnStart, lineNumber, columnEnd);
        }
        const selections = this._editorObs.selections.read(reader);
        return selections?.some((s) => {
          if (s.isEmpty()) {
            return this.textModel.getLineLength(s.startLineNumber) === 0;
          } else {
            return isMultiLine(s) || s.containsRange(getNonIndentationRange(this.textModel, s.startLineNumber));
          }
        });
      });
      this.tabShouldJumpToInlineEdit = derived(this, (reader) => {
        if (this._tabShouldIndent.read(reader)) {
          return false;
        }
        const s = this.inlineEditState.read(reader);
        if (!s) {
          return false;
        }
        if (this.showCollapsed.read(reader)) {
          return true;
        }
        if (this._inAcceptFlow.read(reader) && this._appearedInsideViewport.read(reader) && !s.inlineCompletion.hint?.jumpToEdit) {
          return false;
        }
        return !s.cursorAtInlineEdit.read(reader);
      });
      this.tabShouldAcceptInlineEdit = derived(this, (reader) => {
        const s = this.inlineEditState.read(reader);
        if (!s) {
          return false;
        }
        if (this.showCollapsed.read(reader)) {
          return false;
        }
        if (this._tabShouldIndent.read(reader)) {
          return false;
        }
        if (this._inAcceptFlow.read(reader) && this._appearedInsideViewport.read(reader) && !s.inlineCompletion.hint?.jumpToEdit) {
          return true;
        }
        if (s.inlineCompletion.targetRange.startLineNumber === this._editorObs.cursorLineNumber.read(reader)) {
          return true;
        }
        if (this._jumpedToId.read(reader) === s.inlineCompletion.semanticId) {
          return true;
        }
        return s.cursorAtInlineEdit.read(reader);
      });
      this._jumpedToId = observableValue(this, void 0);
      this._inAcceptFlow = observableValue(this, false);
      this.inAcceptFlow = this._inAcceptFlow;
      this._source = this._register(this._instantiationService.createInstance(InlineCompletionsSource, this.textModel, this._textModelVersionId, this._debounceValue, this.primaryPosition));
      this.lastTriggerKind = this._source.inlineCompletions.map(this, (v) => v?.request?.context.triggerKind);
      this._editorObs = observableCodeEditor(this._editor);
      const suggest = this._editorObs.getOption(
        134
        /* EditorOption.suggest */
      );
      this._suggestPreviewEnabled = suggest.map((v) => v.preview);
      this._suggestPreviewMode = suggest.map((v) => v.previewMode);
      const inlineSuggest = this._editorObs.getOption(
        71
        /* EditorOption.inlineSuggest */
      );
      this._inlineSuggestMode = inlineSuggest.map((v) => v.mode);
      this._suppressedInlineCompletionGroupIds = inlineSuggest.map((v) => new Set(v.experimental.suppressInlineSuggestions.split(",")));
      this._inlineEditsEnabled = inlineSuggest.map((v) => !!v.edits.enabled);
      this._inlineEditsShowCollapsedEnabled = inlineSuggest.map((s) => s.edits.showCollapsed);
      this._triggerCommandOnProviderChange = inlineSuggest.map((s) => s.triggerCommandOnProviderChange);
      this._minShowDelay = inlineSuggest.map((s) => s.minShowDelay);
      this._showOnSuggestConflict = inlineSuggest.map((s) => s.experimental.showOnSuggestConflict);
      this._suppressInSnippetMode = inlineSuggest.map((s) => s.suppressInSnippetMode);
      const snippetController = SnippetController2.get(this._editor);
      this._isInSnippetMode = snippetController?.isInSnippetObservable ?? constObservable(false);
      this._typing = this._register(new TypingInterval(this.textModel));
      this._register(this._inlineCompletionsService.onDidChangeIsSnoozing((isSnoozing) => {
        if (isSnoozing) {
          this.stop();
        }
      }));
      {
        const isNotebook = this.textModel.uri.scheme === "vscode-notebook-cell";
        const [diffEditor] = this._codeEditorService.listDiffEditors().filter((d) => d.getOriginalEditor().getId() === this._editor.getId() || d.getModifiedEditor().getId() === this._editor.getId());
        this.isInDiffEditor = !!diffEditor;
        this.editorType = isNotebook ? InlineCompletionEditorType.Notebook : this.isInDiffEditor ? InlineCompletionEditorType.DiffEditor : InlineCompletionEditorType.TextEditor;
      }
      this._register(recomputeInitiallyAndOnChange(this.state, (s) => {
        if (s && s.inlineCompletion) {
          this._inlineCompletionsService.reportNewCompletion(s.inlineCompletion.requestUuid);
        }
      }));
      this._register(recomputeInitiallyAndOnChange(this._fetchInlineCompletionsPromise));
      this._register(autorun((reader) => {
        this._editorObs.versionId.read(reader);
        this._inAcceptFlow.set(false, void 0);
      }));
      this._register(autorun((reader) => {
        const jumpToReset = this.state.map((s, reader2) => !s || s.kind === "inlineEdit" && !s.cursorAtInlineEdit.read(reader2)).read(reader);
        if (jumpToReset) {
          this._jumpedToId.set(void 0, void 0);
        }
      }));
      const inlineEditSemanticId = this.inlineEditState.map((s) => s?.inlineCompletion.semanticId);
      this._register(autorun((reader) => {
        const id = inlineEditSemanticId.read(reader);
        if (id) {
          this._editor.pushUndoStop();
          this._lastShownInlineCompletionInfo = {
            alternateTextModelVersionId: this.textModel.getAlternativeVersionId(),
            inlineCompletion: this.state.get().inlineCompletion
          };
        }
      }));
      const inlineCompletionProviders = observableFromEvent(this._languageFeaturesService.inlineCompletionsProvider.onDidChange, () => this._languageFeaturesService.inlineCompletionsProvider.all(textModel));
      mapObservableArrayCached(this, inlineCompletionProviders, (provider, store) => {
        if (!provider.onDidChangeInlineCompletions) {
          return;
        }
        store.add(provider.onDidChangeInlineCompletions(() => {
          if (!this._enabled.get()) {
            return;
          }
          const activeEditor = this._codeEditorService.getFocusedCodeEditor() || this._codeEditorService.getActiveCodeEditor();
          if (activeEditor !== this._editor) {
            return;
          }
          if (this._triggerCommandOnProviderChange.get()) {
            this.trigger(void 0, { onlyFetchInlineEdits: true });
            return;
          }
          const activeState = this.state.get();
          if (activeState && (activeState.inlineCompletion || activeState.edits) && activeState.inlineCompletion?.source.provider !== provider) {
            return;
          }
          transaction((tx) => {
            this._fetchSpecificProviderSignal.trigger(tx, provider);
            this.trigger(tx);
          });
        }));
      }).recomputeInitiallyAndOnChange(this._store);
      this._didUndoInlineEdits.recomputeInitiallyAndOnChange(this._store);
    }
    getIndentationInfo(reader) {
      let startsWithIndentation = false;
      let startsWithIndentationLessThanTabSize = true;
      const ghostText = this?.primaryGhostText.read(reader);
      if (!!this?._selectedSuggestItem && ghostText && ghostText.parts.length > 0) {
        const { column, lines } = ghostText.parts[0];
        const firstLine = lines[0].line;
        const indentationEndColumn = this.textModel.getLineIndentColumn(ghostText.lineNumber);
        const inIndentation = column <= indentationEndColumn;
        if (inIndentation) {
          let firstNonWsIdx = firstNonWhitespaceIndex(firstLine);
          if (firstNonWsIdx === -1) {
            firstNonWsIdx = firstLine.length - 1;
          }
          startsWithIndentation = firstNonWsIdx > 0;
          const tabSize = this.textModel.getOptions().tabSize;
          const visibleColumnIndentation = CursorColumns.visibleColumnFromColumn(firstLine, firstNonWsIdx + 1, tabSize);
          startsWithIndentationLessThanTabSize = visibleColumnIndentation < tabSize;
        }
      }
      return {
        startsWithIndentation,
        startsWithIndentationLessThanTabSize
      };
    }
    _getReason(e) {
      if (e?.isUndoing) {
        return VersionIdChangeReason.Undo;
      }
      if (e?.isRedoing) {
        return VersionIdChangeReason.Redo;
      }
      if (this.isAcceptingPartially) {
        return VersionIdChangeReason.AcceptWord;
      }
      return VersionIdChangeReason.Other;
    }
    // TODO: This is not an ideal implementation of excludesGroupIds, however as this is currently still behind proposed API
    // and due to the time constraints, we are using a simplified approach
    getAvailableProviders(providers) {
      const suppressedProviderGroupIds = this._suppressedInlineCompletionGroupIds.get();
      const unsuppressedProviders = providers.filter((provider) => !(provider.groupId && suppressedProviderGroupIds.has(provider.groupId)));
      const excludedGroupIds = /* @__PURE__ */ new Set();
      for (const provider of unsuppressedProviders) {
        provider.excludesGroupIds?.forEach((p) => excludedGroupIds.add(p));
      }
      const availableProviders = [];
      for (const provider of unsuppressedProviders) {
        if (provider.groupId && excludedGroupIds.has(provider.groupId)) {
          continue;
        }
        availableProviders.push(provider);
      }
      return availableProviders;
    }
    async trigger(tx, options = {}) {
      subtransaction(tx, (tx2) => {
        if (options.onlyFetchInlineEdits) {
          this._onlyRequestInlineEditsSignal.trigger(tx2);
        }
        if (options.noDelay) {
          this._noDelaySignal.trigger(tx2);
        }
        this._isActive.set(true, tx2);
        if (options.explicit) {
          this._inAcceptFlow.set(true, tx2);
          this._forceUpdateExplicitlySignal.trigger(tx2);
        }
        if (options.provider) {
          this._fetchSpecificProviderSignal.trigger(tx2, options.provider);
        }
      });
      await this._fetchInlineCompletionsPromise.get();
    }
    async triggerExplicitly(tx, onlyFetchInlineEdits = false) {
      return this.trigger(tx, { onlyFetchInlineEdits, explicit: true });
    }
    stop(stopReason = "automatic", tx) {
      subtransaction(tx, (tx2) => {
        if (stopReason === "explicitCancel") {
          const inlineCompletion = this.state.get()?.inlineCompletion;
          if (inlineCompletion) {
            inlineCompletion.reportEndOfLife({ kind: InlineCompletionEndOfLifeReasonKind$1.Rejected });
          }
        }
        this._isActive.set(false, tx2);
        this._source.clear(tx2);
      });
    }
    _computeAugmentation(suggestCompletion, reader) {
      const model = this.textModel;
      const suggestWidgetInlineCompletions = this._source.suggestWidgetInlineCompletions.read(reader);
      const candidateInlineCompletions = suggestWidgetInlineCompletions ? suggestWidgetInlineCompletions.inlineCompletions.filter((c) => !c.isInlineEdit) : [this.selectedInlineCompletion.read(reader)].filter(isDefined);
      const augmentedCompletion = mapFindFirst(candidateInlineCompletions, (completion) => {
        let r = completion.getSingleTextEdit();
        r = singleTextRemoveCommonPrefix(r, model, Range$2.fromPositions(r.range.getStartPosition(), suggestCompletion.range.getEndPosition()));
        return singleTextEditAugments(r, suggestCompletion) ? { completion, edit: r } : void 0;
      });
      return augmentedCompletion;
    }
    async _deltaSelectedInlineCompletionIndex(delta) {
      await this.triggerExplicitly();
      const completions = this._filteredInlineCompletionItems.get() || [];
      if (completions.length > 0) {
        const newIdx = (this.selectedInlineCompletionIndex.get() + delta + completions.length) % completions.length;
        this._selectedInlineCompletionId.set(completions[newIdx].semanticId, void 0);
      } else {
        this._selectedInlineCompletionId.set(void 0, void 0);
      }
    }
    async next() {
      await this._deltaSelectedInlineCompletionIndex(1);
    }
    async previous() {
      await this._deltaSelectedInlineCompletionIndex(-1);
    }
    _getMetadata(completion, languageId, type = void 0) {
      if (type) {
        return EditSources.inlineCompletionPartialAccept({
          nes: completion.isInlineEdit,
          requestUuid: completion.requestUuid,
          providerId: completion.source.provider.providerId,
          languageId,
          type
        });
      } else {
        return EditSources.inlineCompletionAccept({
          nes: completion.isInlineEdit,
          requestUuid: completion.requestUuid,
          providerId: completion.source.provider.providerId,
          languageId
        });
      }
    }
    async accept(editor2 = this._editor) {
      if (editor2.getModel() !== this.textModel) {
        throw new BugIndicatingError();
      }
      let completion;
      let isNextEditUri = false;
      const state = this.state.get();
      if (state?.kind === "ghostText") {
        if (!state || state.primaryGhostText.isEmpty() || !state.inlineCompletion) {
          return;
        }
        completion = state.inlineCompletion;
      } else if (state?.kind === "inlineEdit") {
        completion = state.inlineCompletion;
        isNextEditUri = !!state.nextEditUri;
      } else {
        return;
      }
      completion.addRef();
      try {
        editor2.pushUndoStop();
        if (isNextEditUri) {
        } else if (completion.snippetInfo) {
          const mainEdit = TextReplacement.delete(completion.editRange);
          const additionalEdits = completion.additionalTextEdits.map((e) => new TextReplacement(Range$2.lift(e.range), e.text ?? ""));
          const edit2 = TextEdit.fromParallelReplacementsUnsorted([mainEdit, ...additionalEdits]);
          editor2.edit(edit2, this._getMetadata(completion, this.textModel.getLanguageId()));
          editor2.setPosition(completion.snippetInfo.range.getStartPosition(), "inlineCompletionAccept");
          SnippetController2.get(editor2)?.insert(completion.snippetInfo.snippet, { undoStopBefore: false });
        } else {
          const edits = state.edits;
          let minimalEdits = edits;
          if (state.kind === "ghostText") {
            minimalEdits = removeTextReplacementCommonSuffixPrefix(edits, this.textModel);
          }
          const selections = getEndPositionsAfterApplying(minimalEdits).map((p) => Selection$1.fromPositions(p));
          const additionalEdits = completion.additionalTextEdits.map((e) => new TextReplacement(Range$2.lift(e.range), e.text ?? ""));
          const edit2 = TextEdit.fromParallelReplacementsUnsorted([...edits, ...additionalEdits]);
          editor2.edit(edit2, this._getMetadata(completion, this.textModel.getLanguageId()));
          if (completion.hint === void 0) {
            editor2.setSelections(state.kind === "inlineEdit" ? selections.slice(-1) : selections, "inlineCompletionAccept");
          }
          if (state.kind === "inlineEdit" && !this._accessibilityService.isMotionReduced()) {
            const editRanges = edit2.getNewRanges();
            const dec = this._store.add(new FadeoutDecoration(editor2, editRanges, () => {
              this._store.delete(dec);
            }));
          }
        }
        this._onDidAccept.fire();
        this.stop();
        if (completion.command) {
          await this._commandService.executeCommand(completion.command.id, ...completion.command.arguments || []).then(void 0, onUnexpectedExternalError);
        }
        completion.reportEndOfLife({ kind: InlineCompletionEndOfLifeReasonKind$1.Accepted });
      } finally {
        completion.removeRef();
        this._inAcceptFlow.set(true, void 0);
        this._lastAcceptedInlineCompletionInfo = { textModelVersionIdAfter: this.textModel.getVersionId(), inlineCompletion: completion };
      }
    }
    async acceptNextWord() {
      await this._acceptNext(
        this._editor,
        "word",
        (pos, text2) => {
          const langId = this.textModel.getLanguageIdAtPosition(pos.lineNumber, pos.column);
          const config = this._languageConfigurationService.getLanguageConfiguration(langId);
          const wordRegExp = new RegExp(config.wordDefinition.source, config.wordDefinition.flags.replace("g", ""));
          const m1 = text2.match(wordRegExp);
          let acceptUntilIndexExclusive = 0;
          if (m1 && m1.index !== void 0) {
            if (m1.index === 0) {
              acceptUntilIndexExclusive = m1[0].length;
            } else {
              acceptUntilIndexExclusive = m1.index;
            }
          } else {
            acceptUntilIndexExclusive = text2.length;
          }
          const wsRegExp = /\s+/g;
          const m2 = wsRegExp.exec(text2);
          if (m2 && m2.index !== void 0) {
            if (m2.index + m2[0].length < acceptUntilIndexExclusive) {
              acceptUntilIndexExclusive = m2.index + m2[0].length;
            }
          }
          return acceptUntilIndexExclusive;
        },
        0
        /* PartialAcceptTriggerKind.Word */
      );
    }
    async acceptNextLine() {
      await this._acceptNext(
        this._editor,
        "line",
        (pos, text2) => {
          const m = text2.match(/\n/);
          if (m && m.index !== void 0) {
            return m.index + 1;
          }
          return text2.length;
        },
        1
        /* PartialAcceptTriggerKind.Line */
      );
    }
    async _acceptNext(editor2, type, getAcceptUntilIndex, kind) {
      if (editor2.getModel() !== this.textModel) {
        throw new BugIndicatingError();
      }
      const state = this.inlineCompletionState.get();
      if (!state || state.primaryGhostText.isEmpty() || !state.inlineCompletion) {
        return;
      }
      const ghostText = state.primaryGhostText;
      const completion = state.inlineCompletion;
      if (completion.snippetInfo) {
        await this.accept(editor2);
        return;
      }
      const firstPart = ghostText.parts[0];
      const ghostTextPos = new Position$1(ghostText.lineNumber, firstPart.column);
      const ghostTextVal = firstPart.text;
      const acceptUntilIndexExclusive = getAcceptUntilIndex(ghostTextPos, ghostTextVal);
      if (acceptUntilIndexExclusive === ghostTextVal.length && ghostText.parts.length === 1) {
        this.accept(editor2);
        return;
      }
      const partialGhostTextVal = ghostTextVal.substring(0, acceptUntilIndexExclusive);
      const positions = this._positions.get();
      const cursorPosition = positions[0];
      completion.addRef();
      try {
        this._isAcceptingPartially = true;
        try {
          editor2.pushUndoStop();
          const replaceRange = Range$2.fromPositions(cursorPosition, ghostTextPos);
          const newText = editor2.getModel().getValueInRange(replaceRange) + partialGhostTextVal;
          const primaryEdit = new TextReplacement(replaceRange, newText);
          const edits = [primaryEdit, ...getSecondaryEdits(this.textModel, positions, primaryEdit)].filter(isDefined);
          const selections = getEndPositionsAfterApplying(edits).map((p) => Selection$1.fromPositions(p));
          editor2.edit(TextEdit.fromParallelReplacementsUnsorted(edits), this._getMetadata(completion, type));
          editor2.setSelections(selections, "inlineCompletionPartialAccept");
          editor2.revealPositionInCenterIfOutsideViewport(
            editor2.getPosition(),
            1
            /* ScrollType.Immediate */
          );
        } finally {
          this._isAcceptingPartially = false;
        }
        const acceptedRange = Range$2.fromPositions(completion.editRange.getStartPosition(), TextLength.ofText(partialGhostTextVal).addToPosition(ghostTextPos));
        const text2 = editor2.getModel().getValueInRange(
          acceptedRange,
          1
          /* EndOfLinePreference.LF */
        );
        const acceptedLength = text2.length;
        completion.reportPartialAccept(acceptedLength, { kind, acceptedLength }, { characters: acceptUntilIndexExclusive, ratio: acceptUntilIndexExclusive / ghostTextVal.length, count: 1 });
      } finally {
        completion.removeRef();
      }
    }
    handleSuggestAccepted(item) {
      const itemEdit = singleTextRemoveCommonPrefix(item.getSingleTextEdit(), this.textModel);
      const augmentedCompletion = this._computeAugmentation(itemEdit, void 0);
      if (!augmentedCompletion) {
        return;
      }
      const alreadyAcceptedLength = this.textModel.getValueInRange(
        augmentedCompletion.completion.editRange,
        1
        /* EndOfLinePreference.LF */
      ).length;
      const acceptedLength = alreadyAcceptedLength + itemEdit.text.length;
      augmentedCompletion.completion.reportPartialAccept(itemEdit.text.length, {
        kind: 2,
        acceptedLength
      }, {
        characters: itemEdit.text.length,
        count: 1,
        ratio: 1
      });
    }
    extractReproSample() {
      const value = this.textModel.getValue();
      const item = this.state.get()?.inlineCompletion;
      return {
        documentValue: value,
        inlineCompletion: item?.getSourceCompletion()
      };
    }
    jump() {
      const s = this.inlineEditState.get();
      if (!s) {
        return;
      }
      transaction((tx) => {
        this._jumpedToId.set(s.inlineCompletion.semanticId, tx);
        this.dontRefetchSignal.trigger(tx);
        const targetRange = s.inlineCompletion.targetRange;
        const targetPosition = targetRange.getStartPosition();
        this._editor.setPosition(targetPosition, "inlineCompletions.jump");
        const isSingleLineChange = targetRange.isSingleLine() && (s.inlineCompletion.hint || !s.inlineCompletion.insertText.includes("\n"));
        if (isSingleLineChange) {
          this._editor.revealPosition(targetPosition);
        } else {
          const revealRange = new Range$2(targetRange.startLineNumber - 1, 1, targetRange.endLineNumber + 1, 1);
          this._editor.revealRange(
            revealRange,
            1
            /* ScrollType.Immediate */
          );
        }
        s.inlineCompletion.identity.setJumpTo(tx);
        this._editor.focus();
      });
    }
    async handleInlineSuggestionShown(inlineCompletion, viewKind, viewData) {
      await inlineCompletion.reportInlineEditShown(this._commandService, viewKind, viewData);
    }
  };
  InlineCompletionsModel = __decorate$1u([
    __param$1t(7, IInstantiationService),
    __param$1t(8, ICommandService),
    __param$1t(9, ILanguageConfigurationService),
    __param$1t(10, IAccessibilityService),
    __param$1t(11, ILanguageFeaturesService),
    __param$1t(12, ICodeEditorService),
    __param$1t(13, IInlineCompletionsService)
  ], InlineCompletionsModel);
  var VersionIdChangeReason;
  (function(VersionIdChangeReason2) {
    VersionIdChangeReason2[VersionIdChangeReason2["Undo"] = 0] = "Undo";
    VersionIdChangeReason2[VersionIdChangeReason2["Redo"] = 1] = "Redo";
    VersionIdChangeReason2[VersionIdChangeReason2["AcceptWord"] = 2] = "AcceptWord";
    VersionIdChangeReason2[VersionIdChangeReason2["Other"] = 3] = "Other";
  })(VersionIdChangeReason || (VersionIdChangeReason = {}));
  function getSecondaryEdits(textModel, positions, primaryTextRepl) {
    if (positions.length === 1) {
      return [];
    }
    const text2 = new TextModelText(textModel);
    const textTransformer = text2.getTransformer();
    const primaryOffset = textTransformer.getOffset(positions[0]);
    const secondaryOffsets = positions.slice(1).map((pos) => textTransformer.getOffset(pos));
    primaryTextRepl = primaryTextRepl.removeCommonPrefixAndSuffix(text2);
    const primaryStringRepl = textTransformer.getStringReplacement(primaryTextRepl);
    const deltaFromOffsetToRangeStart = primaryStringRepl.replaceRange.start - primaryOffset;
    const primaryContextRange = primaryStringRepl.replaceRange.join(OffsetRange.emptyAt(primaryOffset));
    const primaryContextValue = text2.getValueOfOffsetRange(primaryContextRange);
    const replacements = secondaryOffsets.map((secondaryOffset) => {
      const newRangeStart = secondaryOffset + deltaFromOffsetToRangeStart;
      const newRangeEnd = newRangeStart + primaryStringRepl.replaceRange.length;
      const range2 = new OffsetRange(newRangeStart, newRangeEnd);
      const contextRange = range2.join(OffsetRange.emptyAt(secondaryOffset));
      const contextValue = text2.getValueOfOffsetRange(contextRange);
      if (contextValue !== primaryContextValue) {
        return void 0;
      }
      const stringRepl = new StringReplacement(range2, primaryStringRepl.newText);
      const repl = textTransformer.getTextReplacement(stringRepl);
      return repl;
    }).filter(isDefined);
    return replacements;
  }
  class FadeoutDecoration extends Disposable {
    constructor(editor2, ranges, onDispose) {
      super();
      if (onDispose) {
        this._register({ dispose: () => onDispose() });
      }
      this._register(observableCodeEditor(editor2).setDecorations(constObservable(ranges.map((range2) => ({
        range: range2,
        options: {
          description: "animation",
          className: "edits-fadeout-decoration",
          zIndex: 1
        }
      })))));
      const animation = new AnimatedValue(1, 0, 1e3, easeOutCubic);
      const val = new ObservableAnimatedValue(animation);
      this._register(autorun((reader) => {
        const opacity = val.getValue(reader);
        editor2.getContainerDomNode().style.setProperty("--animation-opacity", opacity.toString());
        if (animation.isFinished()) {
          this.dispose();
        }
      }));
    }
  }
  function isSuggestionInViewport(editor2, suggestion) {
    const targetRange = suggestion.targetRange;
    const visibleRanges = editor2.getVisibleRanges();
    if (visibleRanges.length < 1) {
      return false;
    }
    const viewportRange = new Range$2(visibleRanges[0].startLineNumber, visibleRanges[0].startColumn, visibleRanges[visibleRanges.length - 1].endLineNumber, visibleRanges[visibleRanges.length - 1].endColumn);
    return viewportRange.containsRange(targetRange);
  }
  var __decorate$1t = 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$1s = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  var SuggestMemoryService_1;
  class Memory {
    constructor(name) {
      this.name = name;
    }
    select(model, pos, items) {
      if (items.length === 0) {
        return 0;
      }
      const topScore = items[0].score[0];
      for (let i2 = 0; i2 < items.length; i2++) {
        const { score: score2, completion: suggestion } = items[i2];
        if (score2[0] !== topScore) {
          break;
        }
        if (suggestion.preselect) {
          return i2;
        }
      }
      return 0;
    }
  }
  class NoMemory extends Memory {
    constructor() {
      super("first");
    }
    memorize(model, pos, item) {
    }
    toJSON() {
      return void 0;
    }
    fromJSON() {
    }
  }
  class LRUMemory extends Memory {
    constructor() {
      super("recentlyUsed");
      this._cache = new LRUCache(300, 0.66);
      this._seq = 0;
    }
    memorize(model, pos, item) {
      const key = `${model.getLanguageId()}/${item.textLabel}`;
      this._cache.set(key, {
        touch: this._seq++,
        type: item.completion.kind,
        insertText: item.completion.insertText
      });
    }
    select(model, pos, items) {
      if (items.length === 0) {
        return 0;
      }
      const lineSuffix = model.getLineContent(pos.lineNumber).substr(pos.column - 10, pos.column - 1);
      if (/\s$/.test(lineSuffix)) {
        return super.select(model, pos, items);
      }
      const topScore = items[0].score[0];
      let indexPreselect = -1;
      let indexRecency = -1;
      let seq = -1;
      for (let i2 = 0; i2 < items.length; i2++) {
        if (items[i2].score[0] !== topScore) {
          break;
        }
        const key = `${model.getLanguageId()}/${items[i2].textLabel}`;
        const item = this._cache.peek(key);
        if (item && item.touch > seq && item.type === items[i2].completion.kind && item.insertText === items[i2].completion.insertText) {
          seq = item.touch;
          indexRecency = i2;
        }
        if (items[i2].completion.preselect && indexPreselect === -1) {
          return indexPreselect = i2;
        }
      }
      if (indexRecency !== -1) {
        return indexRecency;
      } else if (indexPreselect !== -1) {
        return indexPreselect;
      } else {
        return 0;
      }
    }
    toJSON() {
      return this._cache.toJSON();
    }
    fromJSON(data) {
      this._cache.clear();
      const seq = 0;
      for (const [key, value] of data) {
        value.touch = seq;
        value.type = typeof value.type === "number" ? value.type : CompletionItemKinds.fromString(value.type);
        this._cache.set(key, value);
      }
      this._seq = this._cache.size;
    }
  }
  class PrefixMemory extends Memory {
    constructor() {
      super("recentlyUsedByPrefix");
      this._trie = TernarySearchTree.forStrings();
      this._seq = 0;
    }
    memorize(model, pos, item) {
      const { word } = model.getWordUntilPosition(pos);
      const key = `${model.getLanguageId()}/${word}`;
      this._trie.set(key, {
        type: item.completion.kind,
        insertText: item.completion.insertText,
        touch: this._seq++
      });
    }
    select(model, pos, items) {
      const { word } = model.getWordUntilPosition(pos);
      if (!word) {
        return super.select(model, pos, items);
      }
      const key = `${model.getLanguageId()}/${word}`;
      let item = this._trie.get(key);
      if (!item) {
        item = this._trie.findSubstr(key);
      }
      if (item) {
        for (let i2 = 0; i2 < items.length; i2++) {
          const { kind, insertText } = items[i2].completion;
          if (kind === item.type && insertText === item.insertText) {
            return i2;
          }
        }
      }
      return super.select(model, pos, items);
    }
    toJSON() {
      const entries2 = [];
      this._trie.forEach((value, key) => entries2.push([key, value]));
      entries2.sort((a, b) => -(a[1].touch - b[1].touch)).forEach((value, i2) => value[1].touch = i2);
      return entries2.slice(0, 200);
    }
    fromJSON(data) {
      this._trie.clear();
      if (data.length > 0) {
        this._seq = data[0][1].touch + 1;
        for (const [key, value] of data) {
          value.type = typeof value.type === "number" ? value.type : CompletionItemKinds.fromString(value.type);
          this._trie.set(key, value);
        }
      }
    }
  }
  let SuggestMemoryService = (_ba = class {
    constructor(_storageService, _configService) {
      this._storageService = _storageService;
      this._configService = _configService;
      this._disposables = new DisposableStore();
      this._persistSoon = new RunOnceScheduler(() => this._saveState(), 500);
      this._disposables.add(_storageService.onWillSaveState((e) => {
        if (e.reason === WillSaveStateReason.SHUTDOWN) {
          this._saveState();
        }
      }));
    }
    dispose() {
      this._disposables.dispose();
      this._persistSoon.dispose();
    }
    memorize(model, pos, item) {
      this._withStrategy(model, pos).memorize(model, pos, item);
      this._persistSoon.schedule();
    }
    select(model, pos, items) {
      return this._withStrategy(model, pos).select(model, pos, items);
    }
    _withStrategy(model, pos) {
      const mode = this._configService.getValue("editor.suggestSelection", {
        overrideIdentifier: model.getLanguageIdAtPosition(pos.lineNumber, pos.column),
        resource: model.uri
      });
      if (this._strategy?.name !== mode) {
        this._saveState();
        const ctor = SuggestMemoryService_1._strategyCtors.get(mode) || NoMemory;
        this._strategy = new ctor();
        try {
          const share = this._configService.getValue("editor.suggest.shareSuggestSelections");
          const scope = share ? 0 : 1;
          const raw = this._storageService.get(`${SuggestMemoryService_1._storagePrefix}/${mode}`, scope);
          if (raw) {
            this._strategy.fromJSON(JSON.parse(raw));
          }
        } catch (e) {
        }
      }
      return this._strategy;
    }
    _saveState() {
      if (this._strategy) {
        const share = this._configService.getValue("editor.suggest.shareSuggestSelections");
        const scope = share ? 0 : 1;
        const raw = JSON.stringify(this._strategy);
        this._storageService.store(
          `${SuggestMemoryService_1._storagePrefix}/${this._strategy.name}`,
          raw,
          scope,
          1
          /* StorageTarget.MACHINE */
        );
      }
    }
  }, SuggestMemoryService_1 = _ba, _ba._strategyCtors = /* @__PURE__ */ new Map([
    ["recentlyUsedByPrefix", PrefixMemory],
    ["recentlyUsed", LRUMemory],
    ["first", NoMemory]
  ]), _ba._storagePrefix = "suggest/memories", _ba);
  SuggestMemoryService = SuggestMemoryService_1 = __decorate$1t([
    __param$1s(0, IStorageService),
    __param$1s(1, IConfigurationService)
  ], SuggestMemoryService);
  const ISuggestMemoryService = createDecorator("ISuggestMemories");
  registerSingleton(
    ISuggestMemoryService,
    SuggestMemoryService,
    1
    /* InstantiationType.Delayed */
  );
  var __decorate$1s = 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$1r = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  var WordContextKey_1;
  let WordContextKey = (_ca = class {
    constructor(_editor, contextKeyService) {
      this._editor = _editor;
      this._enabled = false;
      this._ckAtEnd = WordContextKey_1.AtEnd.bindTo(contextKeyService);
      this._configListener = this._editor.onDidChangeConfiguration((e) => e.hasChanged(
        139
        /* EditorOption.tabCompletion */
      ) && this._update());
      this._update();
    }
    dispose() {
      this._configListener.dispose();
      this._selectionListener?.dispose();
      this._ckAtEnd.reset();
    }
    _update() {
      const enabled = this._editor.getOption(
        139
        /* EditorOption.tabCompletion */
      ) === "on";
      if (this._enabled === enabled) {
        return;
      }
      this._enabled = enabled;
      if (this._enabled) {
        const checkForWordEnd = () => {
          if (!this._editor.hasModel()) {
            this._ckAtEnd.set(false);
            return;
          }
          const model = this._editor.getModel();
          const selection = this._editor.getSelection();
          const word = model.getWordAtPosition(selection.getStartPosition());
          if (!word) {
            this._ckAtEnd.set(false);
            return;
          }
          this._ckAtEnd.set(word.endColumn === selection.getStartPosition().column && selection.getStartPosition().lineNumber === selection.getEndPosition().lineNumber);
        };
        this._selectionListener = this._editor.onDidChangeCursorSelection(checkForWordEnd);
        checkForWordEnd();
      } else if (this._selectionListener) {
        this._ckAtEnd.reset();
        this._selectionListener.dispose();
        this._selectionListener = void 0;
      }
    }
  }, WordContextKey_1 = _ca, _ca.AtEnd = new RawContextKey("atEndOfWord", false, { type: "boolean", description: localize(1494, "A context key that is true when at the end of a word. Note that this is only defined when tab-completions are enabled") }), _ca);
  WordContextKey = WordContextKey_1 = __decorate$1s([
    __param$1r(1, IContextKeyService)
  ], WordContextKey);
  var __decorate$1r = 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$1q = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  var SuggestAlternatives_1;
  let SuggestAlternatives = (_da = class {
    constructor(_editor, contextKeyService) {
      this._editor = _editor;
      this._index = 0;
      this._ckOtherSuggestions = SuggestAlternatives_1.OtherSuggestions.bindTo(contextKeyService);
    }
    dispose() {
      this.reset();
    }
    reset() {
      this._ckOtherSuggestions.reset();
      this._listener?.dispose();
      this._model = void 0;
      this._acceptNext = void 0;
      this._ignore = false;
    }
    set({ model, index }, acceptNext) {
      if (model.items.length === 0) {
        this.reset();
        return;
      }
      const nextIndex = SuggestAlternatives_1._moveIndex(true, model, index);
      if (nextIndex === index) {
        this.reset();
        return;
      }
      this._acceptNext = acceptNext;
      this._model = model;
      this._index = index;
      this._listener = this._editor.onDidChangeCursorPosition(() => {
        if (!this._ignore) {
          this.reset();
        }
      });
      this._ckOtherSuggestions.set(true);
    }
    static _moveIndex(fwd, model, index) {
      let newIndex = index;
      for (let rounds = model.items.length; rounds > 0; rounds--) {
        newIndex = (newIndex + model.items.length + (fwd ? 1 : -1)) % model.items.length;
        if (newIndex === index) {
          break;
        }
        if (!model.items[newIndex].completion.additionalTextEdits) {
          break;
        }
      }
      return newIndex;
    }
    next() {
      this._move(true);
    }
    prev() {
      this._move(false);
    }
    _move(fwd) {
      if (!this._model) {
        return;
      }
      try {
        this._ignore = true;
        this._index = SuggestAlternatives_1._moveIndex(fwd, this._model, this._index);
        this._acceptNext({ index: this._index, item: this._model.items[this._index], model: this._model });
      } finally {
        this._ignore = false;
      }
    }
  }, SuggestAlternatives_1 = _da, _da.OtherSuggestions = new RawContextKey("hasOtherSuggestions", false), _da);
  SuggestAlternatives = SuggestAlternatives_1 = __decorate$1r([
    __param$1q(1, IContextKeyService)
  ], SuggestAlternatives);
  class CommitCharacterController {
    constructor(editor2, widget, model, accept) {
      this._disposables = new DisposableStore();
      this._disposables.add(model.onDidSuggest((e) => {
        if (e.completionModel.items.length === 0) {
          this.reset();
        }
      }));
      this._disposables.add(model.onDidCancel((e) => {
        this.reset();
      }));
      this._disposables.add(widget.onDidShow(() => this._onItem(widget.getFocusedItem())));
      this._disposables.add(widget.onDidFocus(this._onItem, this));
      this._disposables.add(widget.onDidHide(this.reset, this));
      this._disposables.add(editor2.onWillType((text2) => {
        if (this._active && !widget.isFrozen() && model.state !== 0) {
          const ch = text2.charCodeAt(text2.length - 1);
          if (this._active.acceptCharacters.has(ch) && editor2.getOption(
            0
            /* EditorOption.acceptSuggestionOnCommitCharacter */
          )) {
            accept(this._active.item);
          }
        }
      }));
    }
    _onItem(selected) {
      if (!selected || !isNonEmptyArray(selected.item.completion.commitCharacters)) {
        this.reset();
        return;
      }
      if (this._active && this._active.item.item === selected.item) {
        return;
      }
      const acceptCharacters = new CharacterSet();
      for (const ch of selected.item.completion.commitCharacters) {
        if (ch.length > 0) {
          acceptCharacters.add(ch.charCodeAt(0));
        }
      }
      this._active = { acceptCharacters, item: selected };
    }
    reset() {
      this._active = void 0;
    }
    dispose() {
      this._disposables.dispose();
    }
  }
  const _BracketSelectionRangeProvider = class _BracketSelectionRangeProvider {
    async provideSelectionRanges(model, positions) {
      const result = [];
      for (const position of positions) {
        const bucket = [];
        result.push(bucket);
        const ranges = /* @__PURE__ */ new Map();
        await new Promise((resolve2) => _BracketSelectionRangeProvider._bracketsRightYield(resolve2, 0, model, position, ranges));
        await new Promise((resolve2) => _BracketSelectionRangeProvider._bracketsLeftYield(resolve2, 0, model, position, ranges, bucket));
      }
      return result;
    }
    static _bracketsRightYield(resolve2, round, model, pos, ranges) {
      const counts = /* @__PURE__ */ new Map();
      const t1 = Date.now();
      while (true) {
        if (round >= _BracketSelectionRangeProvider._maxRounds) {
          resolve2();
          break;
        }
        if (!pos) {
          resolve2();
          break;
        }
        const bracket = model.bracketPairs.findNextBracket(pos);
        if (!bracket) {
          resolve2();
          break;
        }
        const d = Date.now() - t1;
        if (d > _BracketSelectionRangeProvider._maxDuration) {
          setTimeout(() => _BracketSelectionRangeProvider._bracketsRightYield(resolve2, round + 1, model, pos, ranges));
          break;
        }
        if (bracket.bracketInfo.isOpeningBracket) {
          const key = bracket.bracketInfo.bracketText;
          const val = counts.has(key) ? counts.get(key) : 0;
          counts.set(key, val + 1);
        } else {
          const key = bracket.bracketInfo.getOpeningBrackets()[0].bracketText;
          let val = counts.has(key) ? counts.get(key) : 0;
          val -= 1;
          counts.set(key, Math.max(0, val));
          if (val < 0) {
            let list2 = ranges.get(key);
            if (!list2) {
              list2 = new LinkedList();
              ranges.set(key, list2);
            }
            list2.push(bracket.range);
          }
        }
        pos = bracket.range.getEndPosition();
      }
    }
    static _bracketsLeftYield(resolve2, round, model, pos, ranges, bucket) {
      const counts = /* @__PURE__ */ new Map();
      const t1 = Date.now();
      while (true) {
        if (round >= _BracketSelectionRangeProvider._maxRounds && ranges.size === 0) {
          resolve2();
          break;
        }
        if (!pos) {
          resolve2();
          break;
        }
        const bracket = model.bracketPairs.findPrevBracket(pos);
        if (!bracket) {
          resolve2();
          break;
        }
        const d = Date.now() - t1;
        if (d > _BracketSelectionRangeProvider._maxDuration) {
          setTimeout(() => _BracketSelectionRangeProvider._bracketsLeftYield(resolve2, round + 1, model, pos, ranges, bucket));
          break;
        }
        if (!bracket.bracketInfo.isOpeningBracket) {
          const key = bracket.bracketInfo.getOpeningBrackets()[0].bracketText;
          const val = counts.has(key) ? counts.get(key) : 0;
          counts.set(key, val + 1);
        } else {
          const key = bracket.bracketInfo.bracketText;
          let val = counts.has(key) ? counts.get(key) : 0;
          val -= 1;
          counts.set(key, Math.max(0, val));
          if (val < 0) {
            const list2 = ranges.get(key);
            if (list2) {
              const closing = list2.shift();
              if (list2.size === 0) {
                ranges.delete(key);
              }
              const innerBracket = Range$2.fromPositions(bracket.range.getEndPosition(), closing.getStartPosition());
              const outerBracket = Range$2.fromPositions(bracket.range.getStartPosition(), closing.getEndPosition());
              bucket.push({ range: innerBracket });
              bucket.push({ range: outerBracket });
              _BracketSelectionRangeProvider._addBracketLeading(model, outerBracket, bucket);
            }
          }
        }
        pos = bracket.range.getStartPosition();
      }
    }
    static _addBracketLeading(model, bracket, bucket) {
      if (bracket.startLineNumber === bracket.endLineNumber) {
        return;
      }
      const startLine = bracket.startLineNumber;
      const column = model.getLineFirstNonWhitespaceColumn(startLine);
      if (column !== 0 && column !== bracket.startColumn) {
        bucket.push({ range: Range$2.fromPositions(new Position$1(startLine, column), bracket.getEndPosition()) });
        bucket.push({ range: Range$2.fromPositions(new Position$1(startLine, 1), bracket.getEndPosition()) });
      }
      const aboveLine = startLine - 1;
      if (aboveLine > 0) {
        const column2 = model.getLineFirstNonWhitespaceColumn(aboveLine);
        if (column2 === bracket.startColumn && column2 !== model.getLineLastNonWhitespaceColumn(aboveLine)) {
          bucket.push({ range: Range$2.fromPositions(new Position$1(aboveLine, column2), bracket.getEndPosition()) });
          bucket.push({ range: Range$2.fromPositions(new Position$1(aboveLine, 1), bracket.getEndPosition()) });
        }
      }
    }
  };
  _BracketSelectionRangeProvider._maxDuration = 30;
  _BracketSelectionRangeProvider._maxRounds = 2;
  let BracketSelectionRangeProvider = _BracketSelectionRangeProvider;
  const _WordDistance = class _WordDistance {
    static async create(service, editor2) {
      if (!editor2.getOption(
        134
        /* EditorOption.suggest */
      ).localityBonus) {
        return _WordDistance.None;
      }
      if (!editor2.hasModel()) {
        return _WordDistance.None;
      }
      const model = editor2.getModel();
      const position = editor2.getPosition();
      if (!service.canComputeWordRanges(model.uri)) {
        return _WordDistance.None;
      }
      const [ranges] = await new BracketSelectionRangeProvider().provideSelectionRanges(model, [position]);
      if (ranges.length === 0) {
        return _WordDistance.None;
      }
      const wordRanges = await service.computeWordRanges(model.uri, ranges[0].range);
      if (!wordRanges) {
        return _WordDistance.None;
      }
      const wordUntilPos = model.getWordUntilPosition(position);
      delete wordRanges[wordUntilPos.word];
      return new class extends _WordDistance {
        distance(anchor, item) {
          if (!position.equals(editor2.getPosition())) {
            return 0;
          }
          if (item.kind === 17) {
            return 2 << 20;
          }
          const word = typeof item.label === "string" ? item.label : item.label.label;
          const wordLines = wordRanges[word];
          if (isFalsyOrEmpty(wordLines)) {
            return 2 << 20;
          }
          const idx = binarySearch(wordLines, Range$2.fromPositions(anchor), Range$2.compareRangesUsingStarts);
          const bestWordRange = idx >= 0 ? wordLines[idx] : wordLines[Math.max(0, ~idx - 1)];
          let blockDistance = ranges.length;
          for (const range2 of ranges) {
            if (!Range$2.containsRange(range2.range, bestWordRange)) {
              break;
            }
            blockDistance -= 1;
          }
          return blockDistance;
        }
      }();
    }
  };
  _WordDistance.None = new class extends _WordDistance {
    distance() {
      return 0;
    }
  }();
  let WordDistance = _WordDistance;
  let LineContext$1 = class LineContext {
    constructor(leadingLineContent, characterCountDelta) {
      this.leadingLineContent = leadingLineContent;
      this.characterCountDelta = characterCountDelta;
    }
  };
  class CompletionModel {
    constructor(items, column, lineContext, wordDistance, options, snippetSuggestions, fuzzyScoreOptions = FuzzyScoreOptions.default, clipboardText = void 0) {
      this.clipboardText = clipboardText;
      this._snippetCompareFn = CompletionModel._compareCompletionItems;
      this._items = items;
      this._column = column;
      this._wordDistance = wordDistance;
      this._options = options;
      this._refilterKind = 1;
      this._lineContext = lineContext;
      this._fuzzyScoreOptions = fuzzyScoreOptions;
      if (snippetSuggestions === "top") {
        this._snippetCompareFn = CompletionModel._compareCompletionItemsSnippetsUp;
      } else if (snippetSuggestions === "bottom") {
        this._snippetCompareFn = CompletionModel._compareCompletionItemsSnippetsDown;
      }
    }
    get lineContext() {
      return this._lineContext;
    }
    set lineContext(value) {
      if (this._lineContext.leadingLineContent !== value.leadingLineContent || this._lineContext.characterCountDelta !== value.characterCountDelta) {
        this._refilterKind = this._lineContext.characterCountDelta < value.characterCountDelta && this._filteredItems ? 2 : 1;
        this._lineContext = value;
      }
    }
    get items() {
      this._ensureCachedState();
      return this._filteredItems;
    }
    getItemsByProvider() {
      this._ensureCachedState();
      return this._itemsByProvider;
    }
    getIncompleteProvider() {
      this._ensureCachedState();
      const result = /* @__PURE__ */ new Set();
      for (const [provider, items] of this.getItemsByProvider()) {
        if (items.length > 0 && items[0].container.incomplete) {
          result.add(provider);
        }
      }
      return result;
    }
    get stats() {
      this._ensureCachedState();
      return this._stats;
    }
    _ensureCachedState() {
      if (this._refilterKind !== 0) {
        this._createCachedState();
      }
    }
    _createCachedState() {
      this._itemsByProvider = /* @__PURE__ */ new Map();
      const labelLengths = [];
      const { leadingLineContent, characterCountDelta } = this._lineContext;
      let word = "";
      let wordLow = "";
      const source = this._refilterKind === 1 ? this._items : this._filteredItems;
      const target = [];
      const scoreFn = !this._options.filterGraceful || source.length > 2e3 ? fuzzyScore : fuzzyScoreGracefulAggressive;
      for (let i2 = 0; i2 < source.length; i2++) {
        const item = source[i2];
        if (item.isInvalid) {
          continue;
        }
        const arr = this._itemsByProvider.get(item.provider);
        if (arr) {
          arr.push(item);
        } else {
          this._itemsByProvider.set(item.provider, [item]);
        }
        const overwriteBefore = item.position.column - item.editStart.column;
        const wordLen = overwriteBefore + characterCountDelta - (item.position.column - this._column);
        if (word.length !== wordLen) {
          word = wordLen === 0 ? "" : leadingLineContent.slice(-wordLen);
          wordLow = word.toLowerCase();
        }
        item.word = word;
        if (wordLen === 0) {
          item.score = FuzzyScore.Default;
        } else {
          let wordPos = 0;
          while (wordPos < overwriteBefore) {
            const ch = word.charCodeAt(wordPos);
            if (ch === 32 || ch === 9) {
              wordPos += 1;
            } else {
              break;
            }
          }
          if (wordPos >= wordLen) {
            item.score = FuzzyScore.Default;
          } else if (typeof item.completion.filterText === "string") {
            const match2 = scoreFn(word, wordLow, wordPos, item.completion.filterText, item.filterTextLow, 0, this._fuzzyScoreOptions);
            if (!match2) {
              continue;
            }
            if (compareIgnoreCase(item.completion.filterText, item.textLabel) === 0) {
              item.score = match2;
            } else {
              item.score = anyScore(word, wordLow, wordPos, item.textLabel, item.labelLow, 0);
              item.score[0] = match2[0];
            }
          } else {
            const match2 = scoreFn(word, wordLow, wordPos, item.textLabel, item.labelLow, 0, this._fuzzyScoreOptions);
            if (!match2) {
              continue;
            }
            item.score = match2;
          }
        }
        item.idx = i2;
        item.distance = this._wordDistance.distance(item.position, item.completion);
        target.push(item);
        labelLengths.push(item.textLabel.length);
      }
      this._filteredItems = target.sort(this._snippetCompareFn);
      this._refilterKind = 0;
      this._stats = {
        pLabelLen: labelLengths.length ? quickSelect(labelLengths.length - 0.85, labelLengths, (a, b) => a - b) : 0
      };
    }
    static _compareCompletionItems(a, b) {
      if (a.score[0] > b.score[0]) {
        return -1;
      } else if (a.score[0] < b.score[0]) {
        return 1;
      } else if (a.distance < b.distance) {
        return -1;
      } else if (a.distance > b.distance) {
        return 1;
      } else if (a.idx < b.idx) {
        return -1;
      } else if (a.idx > b.idx) {
        return 1;
      } else {
        return 0;
      }
    }
    static _compareCompletionItemsSnippetsDown(a, b) {
      if (a.completion.kind !== b.completion.kind) {
        if (a.completion.kind === 28) {
          return 1;
        } else if (b.completion.kind === 28) {
          return -1;
        }
      }
      return CompletionModel._compareCompletionItems(a, b);
    }
    static _compareCompletionItemsSnippetsUp(a, b) {
      if (a.completion.kind !== b.completion.kind) {
        if (a.completion.kind === 28) {
          return -1;
        } else if (b.completion.kind === 28) {
          return 1;
        }
      }
      return CompletionModel._compareCompletionItems(a, b);
    }
  }
  var __decorate$1q = 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$1p = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  var SuggestModel_1;
  class LineContext {
    static shouldAutoTrigger(editor2) {
      if (!editor2.hasModel()) {
        return false;
      }
      const model = editor2.getModel();
      const pos = editor2.getPosition();
      model.tokenization.tokenizeIfCheap(pos.lineNumber);
      const word = model.getWordAtPosition(pos);
      if (!word) {
        return false;
      }
      if (word.endColumn !== pos.column && word.startColumn + 1 !== pos.column) {
        return false;
      }
      if (!isNaN(Number(word.word))) {
        return false;
      }
      return true;
    }
    constructor(model, position, triggerOptions) {
      this.leadingLineContent = model.getLineContent(position.lineNumber).substr(0, position.column - 1);
      this.leadingWord = model.getWordUntilPosition(position);
      this.lineNumber = position.lineNumber;
      this.column = position.column;
      this.triggerOptions = triggerOptions;
    }
  }
  function canShowQuickSuggest(editor2, contextKeyService, configurationService) {
    if (!Boolean(contextKeyService.getContextKeyValue(InlineCompletionContextKeys.inlineSuggestionVisible.key))) {
      return true;
    }
    const suppressSuggestions = contextKeyService.getContextKeyValue(InlineCompletionContextKeys.suppressSuggestions.key);
    if (suppressSuggestions !== void 0) {
      return !suppressSuggestions;
    }
    return !editor2.getOption(
      71
      /* EditorOption.inlineSuggest */
    ).suppressSuggestions;
  }
  function canShowSuggestOnTriggerCharacters(editor2, contextKeyService, configurationService) {
    if (!Boolean(contextKeyService.getContextKeyValue("inlineSuggestionVisible"))) {
      return true;
    }
    const suppressSuggestions = contextKeyService.getContextKeyValue(InlineCompletionContextKeys.suppressSuggestions.key);
    if (suppressSuggestions !== void 0) {
      return !suppressSuggestions;
    }
    return !editor2.getOption(
      71
      /* EditorOption.inlineSuggest */
    ).suppressSuggestions;
  }
  let SuggestModel = SuggestModel_1 = class SuggestModel {
    constructor(_editor, _editorWorkerService, _clipboardService, _telemetryService, _logService, _contextKeyService, _configurationService, _languageFeaturesService, _envService) {
      this._editor = _editor;
      this._editorWorkerService = _editorWorkerService;
      this._clipboardService = _clipboardService;
      this._telemetryService = _telemetryService;
      this._logService = _logService;
      this._contextKeyService = _contextKeyService;
      this._configurationService = _configurationService;
      this._languageFeaturesService = _languageFeaturesService;
      this._envService = _envService;
      this._toDispose = new DisposableStore();
      this._triggerCharacterListener = new DisposableStore();
      this._triggerQuickSuggest = new TimeoutTimer();
      this._triggerState = void 0;
      this._completionDisposables = new DisposableStore();
      this._onDidCancel = new Emitter$1();
      this._onDidTrigger = new Emitter$1();
      this._onDidSuggest = new Emitter$1();
      this.onDidCancel = this._onDidCancel.event;
      this.onDidTrigger = this._onDidTrigger.event;
      this.onDidSuggest = this._onDidSuggest.event;
      this._currentSelection = this._editor.getSelection() || new Selection$1(1, 1, 1, 1);
      this._toDispose.add(this._editor.onDidChangeModel(() => {
        this._updateTriggerCharacters();
        this.cancel();
      }));
      this._toDispose.add(this._editor.onDidChangeModelLanguage(() => {
        this._updateTriggerCharacters();
        this.cancel();
      }));
      this._toDispose.add(this._editor.onDidChangeConfiguration(() => {
        this._updateTriggerCharacters();
      }));
      this._toDispose.add(this._languageFeaturesService.completionProvider.onDidChange(() => {
        this._updateTriggerCharacters();
        this._updateActiveSuggestSession();
      }));
      let editorIsComposing = false;
      this._toDispose.add(this._editor.onDidCompositionStart(() => {
        editorIsComposing = true;
      }));
      this._toDispose.add(this._editor.onDidCompositionEnd(() => {
        editorIsComposing = false;
        this._onCompositionEnd();
      }));
      this._toDispose.add(this._editor.onDidChangeCursorSelection((e) => {
        if (!editorIsComposing) {
          this._onCursorChange(e);
        }
      }));
      this._toDispose.add(this._editor.onDidChangeModelContent(() => {
        if (!editorIsComposing && this._triggerState !== void 0) {
          this._refilterCompletionItems();
        }
      }));
      this._updateTriggerCharacters();
    }
    dispose() {
      dispose(this._triggerCharacterListener);
      dispose([this._onDidCancel, this._onDidSuggest, this._onDidTrigger, this._triggerQuickSuggest]);
      this._toDispose.dispose();
      this._completionDisposables.dispose();
      this.cancel();
    }
    _updateTriggerCharacters() {
      this._triggerCharacterListener.clear();
      if (this._editor.getOption(
        104
        /* EditorOption.readOnly */
      ) || !this._editor.hasModel() || !this._editor.getOption(
        137
        /* EditorOption.suggestOnTriggerCharacters */
      )) {
        return;
      }
      const supportsByTriggerCharacter = /* @__PURE__ */ new Map();
      for (const support of this._languageFeaturesService.completionProvider.all(this._editor.getModel())) {
        for (const ch of support.triggerCharacters || []) {
          let set = supportsByTriggerCharacter.get(ch);
          if (!set) {
            set = /* @__PURE__ */ new Set();
            supportsByTriggerCharacter.set(ch, set);
          }
          set.add(support);
        }
      }
      const checkTriggerCharacter = (text2) => {
        if (!canShowSuggestOnTriggerCharacters(this._editor, this._contextKeyService, this._configurationService)) {
          return;
        }
        if (LineContext.shouldAutoTrigger(this._editor)) {
          return;
        }
        if (!text2) {
          const position = this._editor.getPosition();
          const model = this._editor.getModel();
          text2 = model.getLineContent(position.lineNumber).substr(0, position.column - 1);
        }
        let lastChar = "";
        if (isLowSurrogate(text2.charCodeAt(text2.length - 1))) {
          if (isHighSurrogate(text2.charCodeAt(text2.length - 2))) {
            lastChar = text2.substr(text2.length - 2);
          }
        } else {
          lastChar = text2.charAt(text2.length - 1);
        }
        const supports = supportsByTriggerCharacter.get(lastChar);
        if (supports) {
          const providerItemsToReuse = /* @__PURE__ */ new Map();
          if (this._completionModel) {
            for (const [provider, items] of this._completionModel.getItemsByProvider()) {
              if (!supports.has(provider)) {
                providerItemsToReuse.set(provider, items);
              }
            }
          }
          this.trigger({
            auto: true,
            triggerKind: 1,
            triggerCharacter: lastChar,
            retrigger: Boolean(this._completionModel),
            clipboardText: this._completionModel?.clipboardText,
            completionOptions: { providerFilter: supports, providerItemsToReuse }
          });
        }
      };
      this._triggerCharacterListener.add(this._editor.onDidType(checkTriggerCharacter));
      this._triggerCharacterListener.add(this._editor.onDidCompositionEnd(() => checkTriggerCharacter()));
    }
    // --- trigger/retrigger/cancel suggest
    get state() {
      if (!this._triggerState) {
        return 0;
      } else if (!this._triggerState.auto) {
        return 1;
      } else {
        return 2;
      }
    }
    cancel(retrigger = false) {
      if (this._triggerState !== void 0) {
        this._triggerQuickSuggest.cancel();
        this._requestToken?.cancel();
        this._requestToken = void 0;
        this._triggerState = void 0;
        this._completionModel = void 0;
        this._context = void 0;
        this._onDidCancel.fire({ retrigger });
      }
    }
    clear() {
      this._completionDisposables.clear();
    }
    _updateActiveSuggestSession() {
      if (this._triggerState !== void 0) {
        if (!this._editor.hasModel() || !this._languageFeaturesService.completionProvider.has(this._editor.getModel())) {
          this.cancel();
        } else {
          this.trigger({ auto: this._triggerState.auto, retrigger: true });
        }
      }
    }
    _onCursorChange(e) {
      if (!this._editor.hasModel()) {
        return;
      }
      const prevSelection = this._currentSelection;
      this._currentSelection = this._editor.getSelection();
      if (!e.selection.isEmpty() || e.reason !== 0 && e.reason !== 3 || e.source !== "keyboard" && e.source !== "deleteLeft") {
        this.cancel();
        return;
      }
      if (this._triggerState === void 0 && e.reason === 0) {
        if (prevSelection.containsRange(this._currentSelection) || prevSelection.getEndPosition().isBeforeOrEqual(this._currentSelection.getPosition())) {
          this._doTriggerQuickSuggest();
        }
      } else if (this._triggerState !== void 0 && e.reason === 3) {
        this._refilterCompletionItems();
      }
    }
    _onCompositionEnd() {
      if (this._triggerState === void 0) {
        this._doTriggerQuickSuggest();
      } else {
        this._refilterCompletionItems();
      }
    }
    _doTriggerQuickSuggest() {
      if (QuickSuggestionsOptions.isAllOff(this._editor.getOption(
        102
        /* EditorOption.quickSuggestions */
      ))) {
        return;
      }
      if (this._editor.getOption(
        134
        /* EditorOption.suggest */
      ).snippetsPreventQuickSuggestions && SnippetController2.get(this._editor)?.isInSnippet()) {
        return;
      }
      this.cancel();
      this._triggerQuickSuggest.cancelAndSet(() => {
        if (this._triggerState !== void 0) {
          return;
        }
        if (!LineContext.shouldAutoTrigger(this._editor)) {
          return;
        }
        if (!this._editor.hasModel() || !this._editor.hasWidgetFocus()) {
          return;
        }
        const model = this._editor.getModel();
        const pos = this._editor.getPosition();
        const config = this._editor.getOption(
          102
          /* EditorOption.quickSuggestions */
        );
        if (QuickSuggestionsOptions.isAllOff(config)) {
          return;
        }
        if (!QuickSuggestionsOptions.isAllOn(config)) {
          model.tokenization.tokenizeIfCheap(pos.lineNumber);
          const lineTokens = model.tokenization.getLineTokens(pos.lineNumber);
          const tokenType = lineTokens.getStandardTokenType(lineTokens.findTokenIndexAtOffset(Math.max(pos.column - 1 - 1, 0)));
          if (QuickSuggestionsOptions.valueFor(config, tokenType) !== "on") {
            return;
          }
        }
        if (!canShowQuickSuggest(this._editor, this._contextKeyService, this._configurationService)) {
          return;
        }
        if (!this._languageFeaturesService.completionProvider.has(model)) {
          return;
        }
        this.trigger({ auto: true });
      }, this._editor.getOption(
        103
        /* EditorOption.quickSuggestionsDelay */
      ));
    }
    _refilterCompletionItems() {
      assertType(this._editor.hasModel());
      assertType(this._triggerState !== void 0);
      const model = this._editor.getModel();
      const position = this._editor.getPosition();
      const ctx = new LineContext(model, position, { ...this._triggerState, refilter: true });
      this._onNewContext(ctx);
    }
    trigger(options) {
      if (!this._editor.hasModel()) {
        return;
      }
      const model = this._editor.getModel();
      const ctx = new LineContext(model, this._editor.getPosition(), options);
      this.cancel(options.retrigger);
      this._triggerState = options;
      this._onDidTrigger.fire({ auto: options.auto, shy: options.shy ?? false, position: this._editor.getPosition() });
      this._context = ctx;
      let suggestCtx = {
        triggerKind: options.triggerKind ?? 0
        /* CompletionTriggerKind.Invoke */
      };
      if (options.triggerCharacter) {
        suggestCtx = {
          triggerKind: 1,
          triggerCharacter: options.triggerCharacter
        };
      }
      this._requestToken = new CancellationTokenSource$1();
      const snippetSuggestions = this._editor.getOption(
        128
        /* EditorOption.snippetSuggestions */
      );
      let snippetSortOrder = 1;
      switch (snippetSuggestions) {
        case "top":
          snippetSortOrder = 0;
          break;
        // 	↓ that's the default anyways...
        // case 'inline':
        // 	snippetSortOrder = SnippetSortOrder.Inline;
        // 	break;
        case "bottom":
          snippetSortOrder = 2;
          break;
      }
      const { itemKind: itemKindFilter, showDeprecated } = SuggestModel_1.createSuggestFilter(this._editor);
      const completionOptions = new CompletionOptions(snippetSortOrder, options.completionOptions?.kindFilter ?? itemKindFilter, options.completionOptions?.providerFilter, options.completionOptions?.providerItemsToReuse, showDeprecated);
      const wordDistance = WordDistance.create(this._editorWorkerService, this._editor);
      const completions = provideSuggestionItems(this._languageFeaturesService.completionProvider, model, this._editor.getPosition(), completionOptions, suggestCtx, this._requestToken.token);
      Promise.all([completions, wordDistance]).then(async ([completions2, wordDistance2]) => {
        this._requestToken?.dispose();
        if (!this._editor.hasModel()) {
          completions2.disposable.dispose();
          return;
        }
        let clipboardText = options?.clipboardText;
        if (!clipboardText && completions2.needsClipboard) {
          clipboardText = await this._clipboardService.readText();
        }
        if (this._triggerState === void 0) {
          completions2.disposable.dispose();
          return;
        }
        const model2 = this._editor.getModel();
        const ctx2 = new LineContext(model2, this._editor.getPosition(), options);
        const fuzzySearchOptions = {
          ...FuzzyScoreOptions.default,
          firstMatchCanBeWeak: !this._editor.getOption(
            134
            /* EditorOption.suggest */
          ).matchOnWordStartOnly
        };
        this._completionModel = new CompletionModel(completions2.items, this._context.column, {
          leadingLineContent: ctx2.leadingLineContent,
          characterCountDelta: ctx2.column - this._context.column
        }, wordDistance2, this._editor.getOption(
          134
          /* EditorOption.suggest */
        ), this._editor.getOption(
          128
          /* EditorOption.snippetSuggestions */
        ), fuzzySearchOptions, clipboardText);
        this._completionDisposables.add(completions2.disposable);
        this._onNewContext(ctx2);
        this._reportDurationsTelemetry(completions2.durations);
        if (!this._envService.isBuilt || this._envService.isExtensionDevelopment) {
          for (const item of completions2.items) {
            if (item.isInvalid) {
              this._logService.warn(`[suggest] did IGNORE invalid completion item from ${item.provider._debugDisplayName}`, item.completion);
            }
          }
        }
      }).catch(onUnexpectedError);
    }
    /**
     * Report durations telemetry with a 1% sampling rate.
     * The telemetry is reported only if a random number between 0 and 100 is less than or equal to 1.
     */
    _reportDurationsTelemetry(durations) {
      if (Math.random() > 1e-4) {
        return;
      }
      setTimeout(() => {
        this._telemetryService.publicLog2("suggest.durations.json", { data: JSON.stringify(durations) });
        this._logService.debug("suggest.durations.json", durations);
      });
    }
    static createSuggestFilter(editor2) {
      const result = /* @__PURE__ */ new Set();
      const snippetSuggestions = editor2.getOption(
        128
        /* EditorOption.snippetSuggestions */
      );
      if (snippetSuggestions === "none") {
        result.add(
          28
          /* CompletionItemKind.Snippet */
        );
      }
      const suggestOptions = editor2.getOption(
        134
        /* EditorOption.suggest */
      );
      if (!suggestOptions.showMethods) {
        result.add(
          0
          /* CompletionItemKind.Method */
        );
      }
      if (!suggestOptions.showFunctions) {
        result.add(
          1
          /* CompletionItemKind.Function */
        );
      }
      if (!suggestOptions.showConstructors) {
        result.add(
          2
          /* CompletionItemKind.Constructor */
        );
      }
      if (!suggestOptions.showFields) {
        result.add(
          3
          /* CompletionItemKind.Field */
        );
      }
      if (!suggestOptions.showVariables) {
        result.add(
          4
          /* CompletionItemKind.Variable */
        );
      }
      if (!suggestOptions.showClasses) {
        result.add(
          5
          /* CompletionItemKind.Class */
        );
      }
      if (!suggestOptions.showStructs) {
        result.add(
          6
          /* CompletionItemKind.Struct */
        );
      }
      if (!suggestOptions.showInterfaces) {
        result.add(
          7
          /* CompletionItemKind.Interface */
        );
      }
      if (!suggestOptions.showModules) {
        result.add(
          8
          /* CompletionItemKind.Module */
        );
      }
      if (!suggestOptions.showProperties) {
        result.add(
          9
          /* CompletionItemKind.Property */
        );
      }
      if (!suggestOptions.showEvents) {
        result.add(
          10
          /* CompletionItemKind.Event */
        );
      }
      if (!suggestOptions.showOperators) {
        result.add(
          11
          /* CompletionItemKind.Operator */
        );
      }
      if (!suggestOptions.showUnits) {
        result.add(
          12
          /* CompletionItemKind.Unit */
        );
      }
      if (!suggestOptions.showValues) {
        result.add(
          13
          /* CompletionItemKind.Value */
        );
      }
      if (!suggestOptions.showConstants) {
        result.add(
          14
          /* CompletionItemKind.Constant */
        );
      }
      if (!suggestOptions.showEnums) {
        result.add(
          15
          /* CompletionItemKind.Enum */
        );
      }
      if (!suggestOptions.showEnumMembers) {
        result.add(
          16
          /* CompletionItemKind.EnumMember */
        );
      }
      if (!suggestOptions.showKeywords) {
        result.add(
          17
          /* CompletionItemKind.Keyword */
        );
      }
      if (!suggestOptions.showWords) {
        result.add(
          18
          /* CompletionItemKind.Text */
        );
      }
      if (!suggestOptions.showColors) {
        result.add(
          19
          /* CompletionItemKind.Color */
        );
      }
      if (!suggestOptions.showFiles) {
        result.add(
          20
          /* CompletionItemKind.File */
        );
      }
      if (!suggestOptions.showReferences) {
        result.add(
          21
          /* CompletionItemKind.Reference */
        );
      }
      if (!suggestOptions.showColors) {
        result.add(
          22
          /* CompletionItemKind.Customcolor */
        );
      }
      if (!suggestOptions.showFolders) {
        result.add(
          23
          /* CompletionItemKind.Folder */
        );
      }
      if (!suggestOptions.showTypeParameters) {
        result.add(
          24
          /* CompletionItemKind.TypeParameter */
        );
      }
      if (!suggestOptions.showSnippets) {
        result.add(
          28
          /* CompletionItemKind.Snippet */
        );
      }
      if (!suggestOptions.showUsers) {
        result.add(
          25
          /* CompletionItemKind.User */
        );
      }
      if (!suggestOptions.showIssues) {
        result.add(
          26
          /* CompletionItemKind.Issue */
        );
      }
      return { itemKind: result, showDeprecated: suggestOptions.showDeprecated };
    }
    _onNewContext(ctx) {
      if (!this._context) {
        return;
      }
      if (ctx.lineNumber !== this._context.lineNumber) {
        this.cancel();
        return;
      }
      if (getLeadingWhitespace(ctx.leadingLineContent) !== getLeadingWhitespace(this._context.leadingLineContent)) {
        this.cancel();
        return;
      }
      if (ctx.column < this._context.column) {
        if (ctx.leadingWord.word) {
          this.trigger({ auto: this._context.triggerOptions.auto, retrigger: true });
        } else {
          this.cancel();
        }
        return;
      }
      if (!this._completionModel) {
        return;
      }
      if (ctx.leadingWord.word.length !== 0 && ctx.leadingWord.startColumn > this._context.leadingWord.startColumn) {
        const shouldAutoTrigger = LineContext.shouldAutoTrigger(this._editor);
        if (shouldAutoTrigger && this._context) {
          const map = this._completionModel.getItemsByProvider();
          this.trigger({
            auto: this._context.triggerOptions.auto,
            retrigger: true,
            clipboardText: this._completionModel.clipboardText,
            completionOptions: { providerItemsToReuse: map }
          });
        }
        return;
      }
      if (ctx.column > this._context.column && this._completionModel.getIncompleteProvider().size > 0 && ctx.leadingWord.word.length !== 0) {
        const providerItemsToReuse = /* @__PURE__ */ new Map();
        const providerFilter = /* @__PURE__ */ new Set();
        for (const [provider, items] of this._completionModel.getItemsByProvider()) {
          if (items.length > 0 && items[0].container.incomplete) {
            providerFilter.add(provider);
          } else {
            providerItemsToReuse.set(provider, items);
          }
        }
        this.trigger({
          auto: this._context.triggerOptions.auto,
          triggerKind: 2,
          retrigger: true,
          clipboardText: this._completionModel.clipboardText,
          completionOptions: { providerFilter, providerItemsToReuse }
        });
      } else {
        const oldLineContext = this._completionModel.lineContext;
        let isFrozen2 = false;
        this._completionModel.lineContext = {
          leadingLineContent: ctx.leadingLineContent,
          characterCountDelta: ctx.column - this._context.column
        };
        if (this._completionModel.items.length === 0) {
          const shouldAutoTrigger = LineContext.shouldAutoTrigger(this._editor);
          if (!this._context) {
            this.cancel();
            return;
          }
          if (shouldAutoTrigger && this._context.leadingWord.endColumn < ctx.leadingWord.startColumn) {
            this.trigger({ auto: this._context.triggerOptions.auto, retrigger: true });
            return;
          }
          if (!this._context.triggerOptions.auto) {
            this._completionModel.lineContext = oldLineContext;
            isFrozen2 = this._completionModel.items.length > 0;
            if (isFrozen2 && ctx.leadingWord.word.length === 0) {
              this.cancel();
              return;
            }
          } else {
            this.cancel();
            return;
          }
        }
        this._onDidSuggest.fire({
          completionModel: this._completionModel,
          triggerOptions: ctx.triggerOptions,
          isFrozen: isFrozen2
        });
      }
    }
  };
  SuggestModel = SuggestModel_1 = __decorate$1q([
    __param$1p(1, IEditorWorkerService),
    __param$1p(2, IClipboardService),
    __param$1p(3, ITelemetryService),
    __param$1p(4, ILogService),
    __param$1p(5, IContextKeyService),
    __param$1p(6, IConfigurationService),
    __param$1p(7, ILanguageFeaturesService),
    __param$1p(8, IEnvironmentService)
  ], SuggestModel);
  const _OvertypingCapturer = class _OvertypingCapturer {
    constructor(editor2, suggestModel) {
      this._disposables = new DisposableStore();
      this._lastOvertyped = [];
      this._locked = false;
      this._disposables.add(editor2.onWillType(() => {
        if (this._locked || !editor2.hasModel()) {
          return;
        }
        const selections = editor2.getSelections();
        const selectionsLength = selections.length;
        let willOvertype = false;
        for (let i2 = 0; i2 < selectionsLength; i2++) {
          if (!selections[i2].isEmpty()) {
            willOvertype = true;
            break;
          }
        }
        if (!willOvertype) {
          if (this._lastOvertyped.length !== 0) {
            this._lastOvertyped.length = 0;
          }
          return;
        }
        this._lastOvertyped = [];
        const model = editor2.getModel();
        for (let i2 = 0; i2 < selectionsLength; i2++) {
          const selection = selections[i2];
          if (model.getValueLengthInRange(selection) > _OvertypingCapturer._maxSelectionLength) {
            return;
          }
          this._lastOvertyped[i2] = { value: model.getValueInRange(selection), multiline: selection.startLineNumber !== selection.endLineNumber };
        }
      }));
      this._disposables.add(suggestModel.onDidTrigger((e) => {
        this._locked = true;
      }));
      this._disposables.add(suggestModel.onDidCancel((e) => {
        this._locked = false;
      }));
    }
    getLastOvertypedInfo(idx) {
      if (idx >= 0 && idx < this._lastOvertyped.length) {
        return this._lastOvertyped[idx];
      }
      return void 0;
    }
    dispose() {
      this._disposables.dispose();
    }
  };
  _OvertypingCapturer._maxSelectionLength = 51200;
  let OvertypingCapturer = _OvertypingCapturer;
  var __decorate$1p = 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$1o = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  let SuggestWidgetStatus = class SuggestWidgetStatus {
    constructor(container, _menuId, instantiationService, _menuService, _contextKeyService) {
      this._menuId = _menuId;
      this._menuService = _menuService;
      this._contextKeyService = _contextKeyService;
      this._menuDisposables = new DisposableStore();
      this.element = append$2(container, $$l(".suggest-status-bar"));
      const actionViewItemProvider = ((action) => {
        return action instanceof MenuItemAction ? instantiationService.createInstance(TextOnlyMenuEntryActionViewItem, action, { useComma: false }) : void 0;
      });
      this._leftActions = new ActionBar(this.element, { actionViewItemProvider });
      this._rightActions = new ActionBar(this.element, { actionViewItemProvider });
      this._leftActions.domNode.classList.add("left");
      this._rightActions.domNode.classList.add("right");
    }
    dispose() {
      this._menuDisposables.dispose();
      this._leftActions.dispose();
      this._rightActions.dispose();
      this.element.remove();
    }
    show() {
      const menu = this._menuService.createMenu(this._menuId, this._contextKeyService);
      const renderMenu = () => {
        const left = [];
        const right = [];
        for (const [group, actions] of menu.getActions()) {
          if (group === "left") {
            left.push(...actions);
          } else {
            right.push(...actions);
          }
        }
        this._leftActions.clear();
        this._leftActions.push(left);
        this._rightActions.clear();
        this._rightActions.push(right);
      };
      this._menuDisposables.add(menu.onDidChange(() => renderMenu()));
      this._menuDisposables.add(menu);
    }
    hide() {
      this._menuDisposables.clear();
    }
  };
  SuggestWidgetStatus = __decorate$1p([
    __param$1o(2, IInstantiationService),
    __param$1o(3, IMenuService),
    __param$1o(4, IContextKeyService)
  ], SuggestWidgetStatus);
  var __decorate$1o = 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$1n = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  function canExpandCompletionItem(item) {
    return !!item && Boolean(item.completion.documentation || item.completion.detail && item.completion.detail !== item.completion.label);
  }
  let SuggestDetailsWidget = class SuggestDetailsWidget {
    constructor(_editor, _themeService, _markdownRendererService) {
      this._editor = _editor;
      this._themeService = _themeService;
      this._markdownRendererService = _markdownRendererService;
      this._onDidClose = new Emitter$1();
      this.onDidClose = this._onDidClose.event;
      this._onDidChangeContents = new Emitter$1();
      this.onDidChangeContents = this._onDidChangeContents.event;
      this._disposables = new DisposableStore();
      this._renderDisposeable = new DisposableStore();
      this._size = new Dimension(330, 0);
      this.domNode = $$l(".suggest-details");
      this.domNode.classList.add("no-docs");
      this._body = $$l(".body");
      this._scrollbar = new DomScrollableElement(this._body, {
        alwaysConsumeMouseWheel: true
      });
      append$2(this.domNode, this._scrollbar.getDomNode());
      this._disposables.add(this._scrollbar);
      this._header = append$2(this._body, $$l(".header"));
      this._close = append$2(this._header, $$l("span" + ThemeIcon.asCSSSelector(Codicon.close)));
      this._close.title = localize(1490, "Close");
      this._close.role = "button";
      this._close.tabIndex = -1;
      this._type = append$2(this._header, $$l("p.type"));
      this._docs = append$2(this._body, $$l("p.docs"));
      this._configureFont();
      this._disposables.add(this._editor.onDidChangeConfiguration((e) => {
        if (e.hasChanged(
          59
          /* EditorOption.fontInfo */
        )) {
          this._configureFont();
        }
      }));
    }
    dispose() {
      this._disposables.dispose();
      this._renderDisposeable.dispose();
    }
    _configureFont() {
      const options = this._editor.getOptions();
      const fontInfo = options.get(
        59
        /* EditorOption.fontInfo */
      );
      const fontFamily = fontInfo.getMassagedFontFamily();
      const fontSize = options.get(
        135
        /* EditorOption.suggestFontSize */
      ) || fontInfo.fontSize;
      const lineHeight = options.get(
        136
        /* EditorOption.suggestLineHeight */
      ) || fontInfo.lineHeight;
      const fontWeight = fontInfo.fontWeight;
      const fontSizePx = `${fontSize}px`;
      const lineHeightPx = `${lineHeight}px`;
      this.domNode.style.fontSize = fontSizePx;
      this.domNode.style.lineHeight = `${lineHeight / fontSize}`;
      this.domNode.style.fontWeight = fontWeight;
      this.domNode.style.fontFeatureSettings = fontInfo.fontFeatureSettings;
      this._type.style.fontFamily = fontFamily;
      this._close.style.height = lineHeightPx;
      this._close.style.width = lineHeightPx;
    }
    getLayoutInfo() {
      const lineHeight = this._editor.getOption(
        136
        /* EditorOption.suggestLineHeight */
      ) || this._editor.getOption(
        59
        /* EditorOption.fontInfo */
      ).lineHeight;
      const borderWidth = isHighContrast(this._themeService.getColorTheme().type) ? 2 : 1;
      const borderHeight = borderWidth * 2;
      return {
        lineHeight,
        borderWidth,
        borderHeight,
        verticalPadding: 22,
        horizontalPadding: 14
      };
    }
    renderLoading() {
      this._type.textContent = localize(1491, "Loading...");
      this._docs.textContent = "";
      this.domNode.classList.remove("no-docs", "no-type");
      this.layout(this.size.width, this.getLayoutInfo().lineHeight * 2);
      this._onDidChangeContents.fire(this);
    }
    renderItem(item, explainMode) {
      this._renderDisposeable.clear();
      let { detail, documentation } = item.completion;
      if (explainMode) {
        let md = "";
        md += `score: ${item.score[0]}
`;
        md += `prefix: ${item.word ?? "(no prefix)"}
`;
        md += `word: ${item.completion.filterText ? item.completion.filterText + " (filterText)" : item.textLabel}
`;
        md += `distance: ${item.distance} (localityBonus-setting)
`;
        md += `index: ${item.idx}, based on ${item.completion.sortText && `sortText: "${item.completion.sortText}"` || "label"}
`;
        md += `commit_chars: ${item.completion.commitCharacters?.join("")}
`;
        documentation = new MarkdownString().appendCodeblock("empty", md);
        detail = `Provider: ${item.provider._debugDisplayName}`;
      }
      if (!explainMode && !canExpandCompletionItem(item)) {
        this.clearContents();
        return;
      }
      this.domNode.classList.remove("no-docs", "no-type");
      if (detail) {
        const cappedDetail = detail.length > 1e5 ? `${detail.substr(0, 1e5)}…` : detail;
        this._type.textContent = cappedDetail;
        this._type.title = cappedDetail;
        show(this._type);
        this._type.classList.toggle("auto-wrap", !/\r?\n^\s+/gmi.test(cappedDetail));
      } else {
        clearNode(this._type);
        this._type.title = "";
        hide(this._type);
        this.domNode.classList.add("no-type");
      }
      clearNode(this._docs);
      if (typeof documentation === "string") {
        this._docs.classList.remove("markdown-docs");
        this._docs.textContent = documentation;
      } else if (documentation) {
        this._docs.classList.add("markdown-docs");
        clearNode(this._docs);
        const renderedContents = this._markdownRendererService.render(documentation, {
          context: this._editor,
          asyncRenderCallback: () => {
            this.layout(this._size.width, this._type.clientHeight + this._docs.clientHeight);
            this._onDidChangeContents.fire(this);
          }
        });
        this._docs.appendChild(renderedContents.element);
        this._renderDisposeable.add(renderedContents);
      }
      this.domNode.classList.toggle("detail-and-doc", !!detail && !!documentation);
      this.domNode.style.userSelect = "text";
      this.domNode.tabIndex = -1;
      this._close.onmousedown = (e) => {
        e.preventDefault();
        e.stopPropagation();
      };
      this._close.onclick = (e) => {
        e.preventDefault();
        e.stopPropagation();
        this._onDidClose.fire();
      };
      this._body.scrollTop = 0;
      this.layout(this._size.width, this._type.clientHeight + this._docs.clientHeight);
      this._onDidChangeContents.fire(this);
    }
    clearContents() {
      this.domNode.classList.add("no-docs");
      this._type.textContent = "";
      this._docs.textContent = "";
    }
    get isEmpty() {
      return this.domNode.classList.contains("no-docs");
    }
    get size() {
      return this._size;
    }
    layout(width2, height) {
      const newSize = new Dimension(width2, height);
      if (!Dimension.equals(newSize, this._size)) {
        this._size = newSize;
        size(this.domNode, width2, height);
      }
      this._scrollbar.scanDomNode();
    }
    scrollDown(much = 8) {
      this._body.scrollTop += much;
    }
    scrollUp(much = 8) {
      this._body.scrollTop -= much;
    }
    scrollTop() {
      this._body.scrollTop = 0;
    }
    scrollBottom() {
      this._body.scrollTop = this._body.scrollHeight;
    }
    pageDown() {
      this.scrollDown(80);
    }
    pageUp() {
      this.scrollUp(80);
    }
    focus() {
      this.domNode.focus();
    }
  };
  SuggestDetailsWidget = __decorate$1o([
    __param$1n(1, IThemeService),
    __param$1n(2, IMarkdownRendererService)
  ], SuggestDetailsWidget);
  class SuggestDetailsOverlay {
    constructor(widget, _editor) {
      this.widget = widget;
      this._editor = _editor;
      this.allowEditorOverflow = true;
      this._disposables = new DisposableStore();
      this._added = false;
      this._preferAlignAtTop = true;
      this._resizable = new ResizableHTMLElement();
      this._resizable.domNode.classList.add("suggest-details-container");
      this._resizable.domNode.appendChild(widget.domNode);
      this._resizable.enableSashes(false, true, true, false);
      let topLeftNow;
      let sizeNow;
      let deltaTop = 0;
      let deltaLeft = 0;
      this._disposables.add(this._resizable.onDidWillResize(() => {
        topLeftNow = this._topLeft;
        sizeNow = this._resizable.size;
      }));
      this._disposables.add(this._resizable.onDidResize((e) => {
        if (topLeftNow && sizeNow) {
          this.widget.layout(e.dimension.width, e.dimension.height);
          let updateTopLeft = false;
          if (e.west) {
            deltaLeft = sizeNow.width - e.dimension.width;
            updateTopLeft = true;
          }
          if (e.north) {
            deltaTop = sizeNow.height - e.dimension.height;
            updateTopLeft = true;
          }
          if (updateTopLeft) {
            this._applyTopLeft({
              top: topLeftNow.top + deltaTop,
              left: topLeftNow.left + deltaLeft
            });
          }
        }
        if (e.done) {
          topLeftNow = void 0;
          sizeNow = void 0;
          deltaTop = 0;
          deltaLeft = 0;
          this._userSize = e.dimension;
        }
      }));
      this._disposables.add(this.widget.onDidChangeContents(() => {
        if (this._anchorBox) {
          this._placeAtAnchor(this._anchorBox, this._userSize ?? this.widget.size, this._preferAlignAtTop);
        }
      }));
    }
    dispose() {
      this._resizable.dispose();
      this._disposables.dispose();
      this.hide();
    }
    getId() {
      return "suggest.details";
    }
    getDomNode() {
      return this._resizable.domNode;
    }
    getPosition() {
      return this._topLeft ? { preference: this._topLeft } : null;
    }
    show() {
      if (!this._added) {
        this._editor.addOverlayWidget(this);
        this._added = true;
      }
    }
    hide(sessionEnded = false) {
      this._resizable.clearSashHoverState();
      if (this._added) {
        this._editor.removeOverlayWidget(this);
        this._added = false;
        this._anchorBox = void 0;
        this._topLeft = void 0;
      }
      if (sessionEnded) {
        this._userSize = void 0;
        this.widget.clearContents();
      }
    }
    placeAtAnchor(anchor, preferAlignAtTop) {
      const anchorBox = anchor.getBoundingClientRect();
      this._anchorBox = anchorBox;
      this._preferAlignAtTop = preferAlignAtTop;
      this._placeAtAnchor(this._anchorBox, this._userSize ?? this.widget.size, preferAlignAtTop);
    }
    _placeAtAnchor(anchorBox, size2, preferAlignAtTop) {
      const bodyBox = getClientArea(this.getDomNode().ownerDocument.body);
      const info = this.widget.getLayoutInfo();
      const defaultMinSize = new Dimension(220, 2 * info.lineHeight);
      const defaultTop = anchorBox.top;
      const eastPlacement = (function() {
        const width2 = bodyBox.width - (anchorBox.left + anchorBox.width + info.borderWidth + info.horizontalPadding);
        const left2 = -info.borderWidth + anchorBox.left + anchorBox.width;
        const maxSizeTop = new Dimension(width2, bodyBox.height - anchorBox.top - info.borderHeight - info.verticalPadding);
        const maxSizeBottom = maxSizeTop.with(void 0, anchorBox.top + anchorBox.height - info.borderHeight - info.verticalPadding);
        return { top: defaultTop, left: left2, fit: width2 - size2.width, maxSizeTop, maxSizeBottom, minSize: defaultMinSize.with(Math.min(width2, defaultMinSize.width)) };
      })();
      const westPlacement = (function() {
        const width2 = anchorBox.left - info.borderWidth - info.horizontalPadding;
        const left2 = Math.max(info.horizontalPadding, anchorBox.left - size2.width - info.borderWidth);
        const maxSizeTop = new Dimension(width2, bodyBox.height - anchorBox.top - info.borderHeight - info.verticalPadding);
        const maxSizeBottom = maxSizeTop.with(void 0, anchorBox.top + anchorBox.height - info.borderHeight - info.verticalPadding);
        return { top: defaultTop, left: left2, fit: width2 - size2.width, maxSizeTop, maxSizeBottom, minSize: defaultMinSize.with(Math.min(width2, defaultMinSize.width)) };
      })();
      const southPacement = (function() {
        const left2 = anchorBox.left;
        const top2 = -info.borderWidth + anchorBox.top + anchorBox.height;
        const maxSizeBottom = new Dimension(anchorBox.width - info.borderHeight, bodyBox.height - anchorBox.top - anchorBox.height - info.verticalPadding);
        return { top: top2, left: left2, fit: maxSizeBottom.height - size2.height, maxSizeBottom, maxSizeTop: maxSizeBottom, minSize: defaultMinSize.with(maxSizeBottom.width) };
      })();
      const placements = [eastPlacement, westPlacement, southPacement];
      const placement = placements.find((p) => p.fit >= 0) ?? placements.sort((a, b) => b.fit - a.fit)[0];
      const bottom = anchorBox.top + anchorBox.height - info.borderHeight;
      let alignAtTop;
      let height = size2.height;
      const maxHeight = Math.max(placement.maxSizeTop.height, placement.maxSizeBottom.height);
      if (height > maxHeight) {
        height = maxHeight;
      }
      let maxSize;
      if (preferAlignAtTop) {
        if (height <= placement.maxSizeTop.height) {
          alignAtTop = true;
          maxSize = placement.maxSizeTop;
        } else {
          alignAtTop = false;
          maxSize = placement.maxSizeBottom;
        }
      } else {
        if (height <= placement.maxSizeBottom.height) {
          alignAtTop = false;
          maxSize = placement.maxSizeBottom;
        } else {
          alignAtTop = true;
          maxSize = placement.maxSizeTop;
        }
      }
      let { top, left } = placement;
      if (!alignAtTop && height > anchorBox.height) {
        top = bottom - height;
      }
      const editorDomNode = this._editor.getDomNode();
      if (editorDomNode) {
        const editorBoundingBox = editorDomNode.getBoundingClientRect();
        top -= editorBoundingBox.top;
        left -= editorBoundingBox.left;
      }
      this._applyTopLeft({ left, top });
      this._resizable.enableSashes(!alignAtTop, placement === eastPlacement, alignAtTop, placement !== eastPlacement);
      this._resizable.minSize = placement.minSize;
      this._resizable.maxSize = maxSize;
      this._resizable.layout(height, Math.min(maxSize.width, size2.width));
      this.widget.layout(this._resizable.size.width, this._resizable.size.height);
    }
    _applyTopLeft(topLeft) {
      this._topLeft = topLeft;
      this._editor.layoutOverlayWidget(this);
    }
  }
  const IFileService = createDecorator("fileService");
  var FileKind;
  (function(FileKind2) {
    FileKind2[FileKind2["FILE"] = 0] = "FILE";
    FileKind2[FileKind2["FOLDER"] = 1] = "FOLDER";
    FileKind2[FileKind2["ROOT_FOLDER"] = 2] = "ROOT_FOLDER";
  })(FileKind || (FileKind = {}));
  const fileIconDirectoryRegex = /(?:\/|^)(?:([^\/]+)\/)?([^\/]+)$/;
  function getIconClasses(modelService, languageService, resource, fileKind, icon) {
    if (ThemeIcon.isThemeIcon(icon)) {
      return [`codicon-${icon.id}`, "predefined-file-icon"];
    }
    if (URI.isUri(icon)) {
      return [];
    }
    const classes = fileKind === FileKind.ROOT_FOLDER ? ["rootfolder-icon"] : fileKind === FileKind.FOLDER ? ["folder-icon"] : ["file-icon"];
    if (resource) {
      let name;
      if (resource.scheme === Schemas.data) {
        const metadata = DataUri.parseMetaData(resource);
        name = metadata.get(DataUri.META_DATA_LABEL);
      } else {
        const match2 = resource.path.match(fileIconDirectoryRegex);
        if (match2) {
          name = fileIconSelectorEscape(match2[2].toLowerCase());
          if (match2[1]) {
            classes.push(`${fileIconSelectorEscape(match2[1].toLowerCase())}-name-dir-icon`);
          }
        } else {
          name = fileIconSelectorEscape(resource.authority.toLowerCase());
        }
      }
      if (fileKind === FileKind.ROOT_FOLDER) {
        classes.push(`${name}-root-name-folder-icon`);
      } else if (fileKind === FileKind.FOLDER) {
        classes.push(`${name}-name-folder-icon`);
      } else {
        if (name) {
          classes.push(`${name}-name-file-icon`);
          classes.push(`name-file-icon`);
          if (name.length <= 255) {
            const dotSegments = name.split(".");
            for (let i2 = 1; i2 < dotSegments.length; i2++) {
              classes.push(`${dotSegments.slice(i2).join(".")}-ext-file-icon`);
            }
          }
          classes.push(`ext-file-icon`);
        }
        const detectedLanguageId = detectLanguageId(modelService, languageService, resource);
        if (detectedLanguageId) {
          classes.push(`${fileIconSelectorEscape(detectedLanguageId)}-lang-file-icon`);
        }
      }
    }
    return classes;
  }
  function detectLanguageId(modelService, languageService, resource) {
    if (!resource) {
      return null;
    }
    let languageId = null;
    if (resource.scheme === Schemas.data) {
      const metadata = DataUri.parseMetaData(resource);
      const mime = metadata.get(DataUri.META_DATA_MIME);
      if (mime) {
        languageId = languageService.getLanguageIdByMimeType(mime);
      }
    } else {
      const model = modelService.getModel(resource);
      if (model) {
        languageId = model.getLanguageId();
      }
    }
    if (languageId && languageId !== PLAINTEXT_LANGUAGE_ID) {
      return languageId;
    }
    return languageService.guessLanguageIdByFilepathOrFirstLine(resource);
  }
  function fileIconSelectorEscape(str) {
    return str.replace(/[\s]/g, "/");
  }
  var __decorate$1n = 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$1m = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  const suggestMoreInfoIcon = registerIcon("suggest-more-info", Codicon.chevronRight, localize(1492, "Icon for more information in the suggest widget."));
  const _completionItemColor = new (_ea = class {
    extract(item, out) {
      if (item.textLabel.match(_ea._regexStrict)) {
        out[0] = item.textLabel;
        return true;
      }
      if (item.completion.detail && item.completion.detail.match(_ea._regexStrict)) {
        out[0] = item.completion.detail;
        return true;
      }
      if (item.completion.documentation) {
        const value = typeof item.completion.documentation === "string" ? item.completion.documentation : item.completion.documentation.value;
        const match2 = _ea._regexRelaxed.exec(value);
        if (match2 && (match2.index === 0 || match2.index + match2[0].length === value.length)) {
          out[0] = match2[0];
          return true;
        }
      }
      return false;
    }
  }, _ea._regexRelaxed = /(#([\da-fA-F]{3}){1,2}|(rgb|hsl)a\(\s*(\d{1,3}%?\s*,\s*){3}(1|0?\.\d+)\)|(rgb|hsl)\(\s*\d{1,3}%?(\s*,\s*\d{1,3}%?){2}\s*\))/, _ea._regexStrict = new RegExp(`^${_ea._regexRelaxed.source}$`, "i"), _ea)();
  let ItemRenderer = class ItemRenderer {
    constructor(_editor, _modelService, _languageService, _themeService) {
      this._editor = _editor;
      this._modelService = _modelService;
      this._languageService = _languageService;
      this._themeService = _themeService;
      this._onDidToggleDetails = new Emitter$1();
      this.onDidToggleDetails = this._onDidToggleDetails.event;
      this.templateId = "suggestion";
    }
    dispose() {
      this._onDidToggleDetails.dispose();
    }
    renderTemplate(container) {
      const disposables = new DisposableStore();
      const root = container;
      root.classList.add("show-file-icons");
      const icon = append$2(container, $$l(".icon"));
      const colorspan = append$2(icon, $$l("span.colorspan"));
      const text2 = append$2(container, $$l(".contents"));
      const main = append$2(text2, $$l(".main"));
      const iconContainer = append$2(main, $$l(".icon-label.codicon"));
      const left = append$2(main, $$l("span.left"));
      const right = append$2(main, $$l("span.right"));
      const iconLabel = new IconLabel(left, { supportHighlights: true, supportIcons: true });
      disposables.add(iconLabel);
      const parametersLabel = append$2(left, $$l("span.signature-label"));
      const qualifierLabel = append$2(left, $$l("span.qualifier-label"));
      const detailsLabel = append$2(right, $$l("span.details-label"));
      const readMore = append$2(right, $$l("span.readMore" + ThemeIcon.asCSSSelector(suggestMoreInfoIcon)));
      readMore.title = localize(1493, "Read More");
      const configureFont = () => {
        const options = this._editor.getOptions();
        const fontInfo = options.get(
          59
          /* EditorOption.fontInfo */
        );
        const fontFamily = fontInfo.getMassagedFontFamily();
        const fontFeatureSettings = fontInfo.fontFeatureSettings;
        const fontVariationSettings = fontInfo.fontVariationSettings;
        const fontSize = options.get(
          135
          /* EditorOption.suggestFontSize */
        ) || fontInfo.fontSize;
        const lineHeight = options.get(
          136
          /* EditorOption.suggestLineHeight */
        ) || fontInfo.lineHeight;
        const fontWeight = fontInfo.fontWeight;
        const letterSpacing = fontInfo.letterSpacing;
        const fontSizePx = `${fontSize}px`;
        const lineHeightPx = `${lineHeight}px`;
        const letterSpacingPx = `${letterSpacing}px`;
        root.style.fontSize = fontSizePx;
        root.style.fontWeight = fontWeight;
        root.style.letterSpacing = letterSpacingPx;
        main.style.fontFamily = fontFamily;
        main.style.fontFeatureSettings = fontFeatureSettings;
        main.style.fontVariationSettings = fontVariationSettings;
        main.style.lineHeight = lineHeightPx;
        icon.style.height = lineHeightPx;
        icon.style.width = lineHeightPx;
        readMore.style.height = lineHeightPx;
        readMore.style.width = lineHeightPx;
      };
      return { root, left, right, icon, colorspan, iconLabel, iconContainer, parametersLabel, qualifierLabel, detailsLabel, readMore, disposables, configureFont };
    }
    renderElement(element, index, data) {
      data.configureFont();
      const { completion } = element;
      data.colorspan.style.backgroundColor = "";
      const labelOptions = {
        labelEscapeNewLines: true,
        matches: createMatches(element.score)
      };
      const color = [];
      if (completion.kind === 19 && _completionItemColor.extract(element, color)) {
        data.icon.className = "icon customcolor";
        data.iconContainer.className = "icon hide";
        data.colorspan.style.backgroundColor = color[0];
      } else if (completion.kind === 20 && this._themeService.getFileIconTheme().hasFileIcons) {
        data.icon.className = "icon hide";
        data.iconContainer.className = "icon hide";
        const labelClasses = getIconClasses(this._modelService, this._languageService, URI.from({ scheme: "fake", path: element.textLabel }), FileKind.FILE);
        const detailClasses = getIconClasses(this._modelService, this._languageService, URI.from({ scheme: "fake", path: completion.detail }), FileKind.FILE);
        labelOptions.extraClasses = labelClasses.length > detailClasses.length ? labelClasses : detailClasses;
      } else if (completion.kind === 23 && this._themeService.getFileIconTheme().hasFolderIcons) {
        data.icon.className = "icon hide";
        data.iconContainer.className = "icon hide";
        labelOptions.extraClasses = [
          getIconClasses(this._modelService, this._languageService, URI.from({ scheme: "fake", path: element.textLabel }), FileKind.FOLDER),
          getIconClasses(this._modelService, this._languageService, URI.from({ scheme: "fake", path: completion.detail }), FileKind.FOLDER)
        ].flat();
      } else {
        data.icon.className = "icon hide";
        data.iconContainer.className = "";
        data.iconContainer.classList.add("suggest-icon", ...ThemeIcon.asClassNameArray(CompletionItemKinds.toIcon(completion.kind)));
      }
      if (completion.tags && completion.tags.indexOf(
        1
        /* CompletionItemTag.Deprecated */
      ) >= 0) {
        labelOptions.extraClasses = (labelOptions.extraClasses || []).concat(["deprecated"]);
        labelOptions.matches = [];
      }
      data.iconLabel.setLabel(element.textLabel, void 0, labelOptions);
      if (typeof completion.label === "string") {
        data.parametersLabel.textContent = "";
        data.detailsLabel.textContent = stripNewLines(completion.detail || "");
        data.root.classList.add("string-label");
      } else {
        data.parametersLabel.textContent = stripNewLines(completion.label.detail || "");
        data.detailsLabel.textContent = stripNewLines(completion.label.description || "");
        data.root.classList.remove("string-label");
      }
      if (this._editor.getOption(
        134
        /* EditorOption.suggest */
      ).showInlineDetails) {
        show(data.detailsLabel);
      } else {
        hide(data.detailsLabel);
      }
      if (canExpandCompletionItem(element)) {
        data.right.classList.add("can-expand-details");
        show(data.readMore);
        data.readMore.onmousedown = (e) => {
          e.stopPropagation();
          e.preventDefault();
        };
        data.readMore.onclick = (e) => {
          e.stopPropagation();
          e.preventDefault();
          this._onDidToggleDetails.fire();
        };
      } else {
        data.right.classList.remove("can-expand-details");
        hide(data.readMore);
        data.readMore.onmousedown = null;
        data.readMore.onclick = null;
      }
    }
    disposeTemplate(templateData) {
      templateData.disposables.dispose();
    }
  };
  ItemRenderer = __decorate$1n([
    __param$1m(1, IModelService),
    __param$1m(2, ILanguageService),
    __param$1m(3, IThemeService)
  ], ItemRenderer);
  function stripNewLines(str) {
    return str.replace(/\r\n|\r|\n/g, "");
  }
  var __decorate$1m = 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$1l = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  var SuggestWidget_1;
  registerColor("editorSuggestWidget.background", editorWidgetBackground, localize(1473, "Background color of the suggest widget."));
  registerColor("editorSuggestWidget.border", editorWidgetBorder, localize(1474, "Border color of the suggest widget."));
  const editorSuggestWidgetForeground = registerColor("editorSuggestWidget.foreground", editorForeground, localize(1475, "Foreground color of the suggest widget."));
  registerColor("editorSuggestWidget.selectedForeground", quickInputListFocusForeground, localize(1476, "Foreground color of the selected entry in the suggest widget."));
  registerColor("editorSuggestWidget.selectedIconForeground", quickInputListFocusIconForeground, localize(1477, "Icon foreground color of the selected entry in the suggest widget."));
  const editorSuggestWidgetSelectedBackground = registerColor("editorSuggestWidget.selectedBackground", quickInputListFocusBackground, localize(1478, "Background color of the selected entry in the suggest widget."));
  registerColor("editorSuggestWidget.highlightForeground", listHighlightForeground, localize(1479, "Color of the match highlights in the suggest widget."));
  registerColor("editorSuggestWidget.focusHighlightForeground", listFocusHighlightForeground, localize(1480, "Color of the match highlights in the suggest widget when an item is focused."));
  registerColor("editorSuggestWidgetStatus.foreground", transparent(editorSuggestWidgetForeground, 0.5), localize(1481, "Foreground color of the suggest widget status."));
  class PersistedWidgetSize {
    constructor(_service, editor2) {
      this._service = _service;
      this._key = `suggestWidget.size/${editor2.getEditorType()}/${editor2 instanceof EmbeddedCodeEditorWidget}`;
    }
    restore() {
      const raw = this._service.get(
        this._key,
        0
        /* StorageScope.PROFILE */
      ) ?? "";
      try {
        const obj = JSON.parse(raw);
        if (Dimension.is(obj)) {
          return Dimension.lift(obj);
        }
      } catch {
      }
      return void 0;
    }
    store(size2) {
      this._service.store(
        this._key,
        JSON.stringify(size2),
        0,
        1
        /* StorageTarget.MACHINE */
      );
    }
    reset() {
      this._service.remove(
        this._key,
        0
        /* StorageScope.PROFILE */
      );
    }
  }
  let SuggestWidget = (_fa = class {
    constructor(editor2, _storageService, _contextKeyService, _themeService, instantiationService) {
      this.editor = editor2;
      this._storageService = _storageService;
      this._state = 0;
      this._isAuto = false;
      this._pendingLayout = new MutableDisposable();
      this._pendingShowDetails = new MutableDisposable();
      this._ignoreFocusEvents = false;
      this._forceRenderingAbove = false;
      this._explainMode = false;
      this._showTimeout = new TimeoutTimer();
      this._disposables = new DisposableStore();
      this._onDidSelect = new PauseableEmitter();
      this._onDidFocus = new PauseableEmitter();
      this._onDidHide = new Emitter$1();
      this._onDidShow = new Emitter$1();
      this.onDidSelect = this._onDidSelect.event;
      this.onDidFocus = this._onDidFocus.event;
      this.onDidHide = this._onDidHide.event;
      this.onDidShow = this._onDidShow.event;
      this._onDetailsKeydown = new Emitter$1();
      this.onDetailsKeyDown = this._onDetailsKeydown.event;
      this.element = new ResizableHTMLElement();
      this.element.domNode.classList.add("editor-widget", "suggest-widget");
      this._contentWidget = new SuggestContentWidget(this, editor2);
      this._persistedSize = new PersistedWidgetSize(_storageService, editor2);
      class ResizeState {
        constructor(persistedSize, currentSize, persistHeight = false, persistWidth = false) {
          this.persistedSize = persistedSize;
          this.currentSize = currentSize;
          this.persistHeight = persistHeight;
          this.persistWidth = persistWidth;
        }
      }
      let state;
      this._disposables.add(this.element.onDidWillResize(() => {
        this._contentWidget.lockPreference();
        state = new ResizeState(this._persistedSize.restore(), this.element.size);
      }));
      this._disposables.add(this.element.onDidResize((e) => {
        this._resize(e.dimension.width, e.dimension.height);
        if (state) {
          state.persistHeight = state.persistHeight || !!e.north || !!e.south;
          state.persistWidth = state.persistWidth || !!e.east || !!e.west;
        }
        if (!e.done) {
          return;
        }
        if (state) {
          const { itemHeight, defaultSize } = this.getLayoutInfo();
          const threshold = Math.round(itemHeight / 2);
          let { width: width2, height } = this.element.size;
          if (!state.persistHeight || Math.abs(state.currentSize.height - height) <= threshold) {
            height = state.persistedSize?.height ?? defaultSize.height;
          }
          if (!state.persistWidth || Math.abs(state.currentSize.width - width2) <= threshold) {
            width2 = state.persistedSize?.width ?? defaultSize.width;
          }
          this._persistedSize.store(new Dimension(width2, height));
        }
        this._contentWidget.unlockPreference();
        state = void 0;
      }));
      this._messageElement = append$2(this.element.domNode, $$l(".message"));
      this._listElement = append$2(this.element.domNode, $$l(".tree"));
      const details = this._disposables.add(instantiationService.createInstance(SuggestDetailsWidget, this.editor));
      details.onDidClose(() => this.toggleDetails(), this, this._disposables);
      this._details = new SuggestDetailsOverlay(details, this.editor);
      const applyIconStyle = () => this.element.domNode.classList.toggle("no-icons", !this.editor.getOption(
        134
        /* EditorOption.suggest */
      ).showIcons);
      applyIconStyle();
      const renderer = instantiationService.createInstance(ItemRenderer, this.editor);
      this._disposables.add(renderer);
      this._disposables.add(renderer.onDidToggleDetails(() => this.toggleDetails()));
      this._list = new List("SuggestWidget", this._listElement, {
        getHeight: (_element) => this.getLayoutInfo().itemHeight,
        getTemplateId: (_element) => "suggestion"
      }, [renderer], {
        alwaysConsumeMouseWheel: true,
        useShadows: false,
        mouseSupport: false,
        multipleSelectionSupport: false,
        accessibilityProvider: {
          getRole: () => isWindows ? "listitem" : "option",
          getWidgetAriaLabel: () => localize(1484, "Suggest"),
          getWidgetRole: () => "listbox",
          getAriaLabel: (item) => {
            let label = item.textLabel;
            const kindLabel = CompletionItemKinds.toLabel(item.completion.kind);
            if (typeof item.completion.label !== "string") {
              const { detail: detail2, description } = item.completion.label;
              if (detail2 && description) {
                label = localize(1485, "{0} {1}, {2}, {3}", label, detail2, description, kindLabel);
              } else if (detail2) {
                label = localize(1486, "{0} {1}, {2}", label, detail2, kindLabel);
              } else if (description) {
                label = localize(1487, "{0}, {1}, {2}", label, description, kindLabel);
              }
            } else {
              label = localize(1488, "{0}, {1}", label, kindLabel);
            }
            if (!item.isResolved || !this._isDetailsVisible()) {
              return label;
            }
            const { documentation, detail } = item.completion;
            const docs = format("{0}{1}", detail || "", documentation ? typeof documentation === "string" ? documentation : documentation.value : "");
            return localize(1489, "{0}, docs: {1}", label, docs);
          }
        }
      });
      this._list.style(getListStyles({
        listInactiveFocusBackground: editorSuggestWidgetSelectedBackground,
        listInactiveFocusOutline: activeContrastBorder
      }));
      this._status = instantiationService.createInstance(SuggestWidgetStatus, this.element.domNode, suggestWidgetStatusbarMenu);
      const applyStatusBarStyle = () => this.element.domNode.classList.toggle("with-status-bar", this.editor.getOption(
        134
        /* EditorOption.suggest */
      ).showStatusBar);
      applyStatusBarStyle();
      this._disposables.add(this._list.onMouseDown((e) => this._onListMouseDownOrTap(e)));
      this._disposables.add(this._list.onTap((e) => this._onListMouseDownOrTap(e)));
      this._disposables.add(this._list.onDidChangeSelection((e) => this._onListSelection(e)));
      this._disposables.add(this._list.onDidChangeFocus((e) => this._onListFocus(e)));
      this._disposables.add(this.editor.onDidChangeCursorSelection(() => this._onCursorSelectionChanged()));
      this._disposables.add(this.editor.onDidChangeConfiguration((e) => {
        if (e.hasChanged(
          134
          /* EditorOption.suggest */
        )) {
          applyStatusBarStyle();
          applyIconStyle();
        }
        if (this._completionModel && (e.hasChanged(
          59
          /* EditorOption.fontInfo */
        ) || e.hasChanged(
          135
          /* EditorOption.suggestFontSize */
        ) || e.hasChanged(
          136
          /* EditorOption.suggestLineHeight */
        ))) {
          this._list.splice(0, this._list.length, this._completionModel.items);
        }
      }));
      this._ctxSuggestWidgetVisible = Context$2.Visible.bindTo(_contextKeyService);
      this._ctxSuggestWidgetDetailsVisible = Context$2.DetailsVisible.bindTo(_contextKeyService);
      this._ctxSuggestWidgetMultipleSuggestions = Context$2.MultipleSuggestions.bindTo(_contextKeyService);
      this._ctxSuggestWidgetHasFocusedSuggestion = Context$2.HasFocusedSuggestion.bindTo(_contextKeyService);
      this._disposables.add(addStandardDisposableListener(this._details.widget.domNode, "keydown", (e) => {
        this._onDetailsKeydown.fire(e);
      }));
      this._disposables.add(this.editor.onMouseDown((e) => this._onEditorMouseDown(e)));
    }
    dispose() {
      this._details.widget.dispose();
      this._details.dispose();
      this._list.dispose();
      this._status.dispose();
      this._disposables.dispose();
      this._loadingTimeout?.dispose();
      this._pendingLayout.dispose();
      this._pendingShowDetails.dispose();
      this._showTimeout.dispose();
      this._contentWidget.dispose();
      this.element.dispose();
    }
    _onEditorMouseDown(mouseEvent) {
      if (this._details.widget.domNode.contains(mouseEvent.target.element)) {
        this._details.widget.domNode.focus();
      } else {
        if (this.element.domNode.contains(mouseEvent.target.element)) {
          this.editor.focus();
        }
      }
    }
    _onCursorSelectionChanged() {
      if (this._state !== 0) {
        this._contentWidget.layout();
      }
    }
    _onListMouseDownOrTap(e) {
      if (typeof e.element === "undefined" || typeof e.index === "undefined") {
        return;
      }
      e.browserEvent.preventDefault();
      e.browserEvent.stopPropagation();
      this._select(e.element, e.index);
    }
    _onListSelection(e) {
      if (e.elements.length) {
        this._select(e.elements[0], e.indexes[0]);
      }
    }
    _select(item, index) {
      const completionModel = this._completionModel;
      if (completionModel) {
        this._onDidSelect.fire({ item, index, model: completionModel });
        this.editor.focus();
      }
    }
    _onListFocus(e) {
      if (this._ignoreFocusEvents) {
        return;
      }
      if (this._state === 5) {
        this._setState(
          3
          /* State.Open */
        );
      }
      if (!e.elements.length) {
        if (this._currentSuggestionDetails) {
          this._currentSuggestionDetails.cancel();
          this._currentSuggestionDetails = void 0;
          this._focusedItem = void 0;
        }
        this.editor.setAriaOptions({ activeDescendant: void 0 });
        this._ctxSuggestWidgetHasFocusedSuggestion.set(false);
        return;
      }
      if (!this._completionModel) {
        return;
      }
      this._ctxSuggestWidgetHasFocusedSuggestion.set(true);
      const item = e.elements[0];
      const index = e.indexes[0];
      if (item !== this._focusedItem) {
        this._currentSuggestionDetails?.cancel();
        this._currentSuggestionDetails = void 0;
        this._focusedItem = item;
        this._list.reveal(index);
        this._currentSuggestionDetails = createCancelablePromise(async (token) => {
          const loading = disposableTimeout(() => {
            if (this._isDetailsVisible()) {
              this._showDetails(true, false);
            }
          }, 250);
          const sub = token.onCancellationRequested(() => loading.dispose());
          try {
            return await item.resolve(token);
          } finally {
            loading.dispose();
            sub.dispose();
          }
        });
        this._currentSuggestionDetails.then(() => {
          if (index >= this._list.length || item !== this._list.element(index)) {
            return;
          }
          this._ignoreFocusEvents = true;
          this._list.splice(index, 1, [item]);
          this._list.setFocus([index]);
          this._ignoreFocusEvents = false;
          if (this._isDetailsVisible()) {
            this._showDetails(false, false);
          } else {
            this.element.domNode.classList.remove("docs-side");
          }
          this.editor.setAriaOptions({ activeDescendant: this._list.getElementID(index) });
        }).catch(onUnexpectedError);
      }
      this._onDidFocus.fire({ item, index, model: this._completionModel });
    }
    _setState(state) {
      if (this._state === state) {
        return;
      }
      this._state = state;
      this.element.domNode.classList.toggle(
        "frozen",
        state === 4
        /* State.Frozen */
      );
      this.element.domNode.classList.remove("message");
      switch (state) {
        case 0:
          hide(this._messageElement, this._listElement, this._status.element);
          this._details.hide(true);
          this._status.hide();
          this._contentWidget.hide();
          this._ctxSuggestWidgetVisible.reset();
          this._ctxSuggestWidgetMultipleSuggestions.reset();
          this._ctxSuggestWidgetHasFocusedSuggestion.reset();
          this._showTimeout.cancel();
          this.element.domNode.classList.remove("visible");
          this._list.splice(0, this._list.length);
          this._focusedItem = void 0;
          this._cappedHeight = void 0;
          this._explainMode = false;
          break;
        case 1:
          this.element.domNode.classList.add("message");
          this._messageElement.textContent = SuggestWidget_1.LOADING_MESSAGE;
          hide(this._listElement, this._status.element);
          show(this._messageElement);
          this._details.hide();
          this._show();
          this._focusedItem = void 0;
          status(SuggestWidget_1.LOADING_MESSAGE);
          break;
        case 2:
          this.element.domNode.classList.add("message");
          this._messageElement.textContent = SuggestWidget_1.NO_SUGGESTIONS_MESSAGE;
          hide(this._listElement, this._status.element);
          show(this._messageElement);
          this._details.hide();
          this._show();
          this._focusedItem = void 0;
          status(SuggestWidget_1.NO_SUGGESTIONS_MESSAGE);
          break;
        case 3:
          hide(this._messageElement);
          show(this._listElement, this._status.element);
          this._show();
          break;
        case 4:
          hide(this._messageElement);
          show(this._listElement, this._status.element);
          this._show();
          break;
        case 5:
          hide(this._messageElement);
          show(this._listElement, this._status.element);
          this._details.show();
          this._show();
          this._details.widget.focus();
          break;
      }
    }
    _show() {
      this._status.show();
      this._contentWidget.show();
      this._layout(this._persistedSize.restore());
      this._ctxSuggestWidgetVisible.set(true);
      this._showTimeout.cancelAndSet(() => {
        this.element.domNode.classList.add("visible");
        this._onDidShow.fire(this);
      }, 100);
    }
    showTriggered(auto, delay) {
      if (this._state !== 0) {
        return;
      }
      this._contentWidget.setPosition(this.editor.getPosition());
      this._isAuto = !!auto;
      if (!this._isAuto) {
        this._loadingTimeout = disposableTimeout(() => this._setState(
          1
          /* State.Loading */
        ), delay);
      }
    }
    showSuggestions(completionModel, selectionIndex, isFrozen2, isAuto, noFocus) {
      this._contentWidget.setPosition(this.editor.getPosition());
      this._loadingTimeout?.dispose();
      this._currentSuggestionDetails?.cancel();
      this._currentSuggestionDetails = void 0;
      if (this._completionModel !== completionModel) {
        this._completionModel = completionModel;
      }
      if (isFrozen2 && this._state !== 2 && this._state !== 0) {
        this._setState(
          4
          /* State.Frozen */
        );
        return;
      }
      const visibleCount = this._completionModel.items.length;
      const isEmpty = visibleCount === 0;
      this._ctxSuggestWidgetMultipleSuggestions.set(visibleCount > 1);
      if (isEmpty) {
        this._setState(
          isAuto ? 0 : 2
          /* State.Empty */
        );
        this._completionModel = void 0;
        return;
      }
      this._focusedItem = void 0;
      this._onDidFocus.pause();
      this._onDidSelect.pause();
      try {
        this._list.splice(0, this._list.length, this._completionModel.items);
        this._setState(
          isFrozen2 ? 4 : 3
          /* State.Open */
        );
        this._list.reveal(selectionIndex, 0, selectionIndex === 0 ? 0 : this.getLayoutInfo().itemHeight * 0.33);
        this._list.setFocus(noFocus ? [] : [selectionIndex]);
      } finally {
        this._onDidFocus.resume();
        this._onDidSelect.resume();
      }
      this._pendingLayout.value = runAtThisOrScheduleAtNextAnimationFrame(getWindow(this.element.domNode), () => {
        this._pendingLayout.clear();
        this._layout(this.element.size);
        this._details.widget.domNode.classList.remove("focused");
      });
    }
    focusSelected() {
      if (this._list.length > 0) {
        this._list.setFocus([0]);
      }
    }
    selectNextPage() {
      switch (this._state) {
        case 0:
          return false;
        case 5:
          this._details.widget.pageDown();
          return true;
        case 1:
          return !this._isAuto;
        default:
          this._list.focusNextPage();
          return true;
      }
    }
    selectNext() {
      switch (this._state) {
        case 0:
          return false;
        case 1:
          return !this._isAuto;
        default:
          this._list.focusNext(1, true);
          return true;
      }
    }
    selectLast() {
      switch (this._state) {
        case 0:
          return false;
        case 5:
          this._details.widget.scrollBottom();
          return true;
        case 1:
          return !this._isAuto;
        default:
          this._list.focusLast();
          return true;
      }
    }
    selectPreviousPage() {
      switch (this._state) {
        case 0:
          return false;
        case 5:
          this._details.widget.pageUp();
          return true;
        case 1:
          return !this._isAuto;
        default:
          this._list.focusPreviousPage();
          return true;
      }
    }
    selectPrevious() {
      switch (this._state) {
        case 0:
          return false;
        case 1:
          return !this._isAuto;
        default:
          this._list.focusPrevious(1, true);
          return false;
      }
    }
    selectFirst() {
      switch (this._state) {
        case 0:
          return false;
        case 5:
          this._details.widget.scrollTop();
          return true;
        case 1:
          return !this._isAuto;
        default:
          this._list.focusFirst();
          return true;
      }
    }
    getFocusedItem() {
      if (this._state !== 0 && this._state !== 2 && this._state !== 1 && this._completionModel && this._list.getFocus().length > 0) {
        return {
          item: this._list.getFocusedElements()[0],
          index: this._list.getFocus()[0],
          model: this._completionModel
        };
      }
      return void 0;
    }
    toggleDetailsFocus() {
      if (this._state === 5) {
        this._list.setFocus(this._list.getFocus());
        this._setState(
          3
          /* State.Open */
        );
      } else if (this._state === 3) {
        this._setState(
          5
          /* State.Details */
        );
        if (!this._isDetailsVisible()) {
          this.toggleDetails(true);
        } else {
          this._details.widget.focus();
        }
      }
    }
    toggleDetails(focused = false) {
      if (this._isDetailsVisible()) {
        this._pendingShowDetails.clear();
        this._ctxSuggestWidgetDetailsVisible.set(false);
        this._setDetailsVisible(false);
        this._details.hide();
        this.element.domNode.classList.remove("shows-details");
      } else if ((canExpandCompletionItem(this._list.getFocusedElements()[0]) || this._explainMode) && (this._state === 3 || this._state === 5 || this._state === 4)) {
        this._ctxSuggestWidgetDetailsVisible.set(true);
        this._setDetailsVisible(true);
        this._showDetails(false, focused);
      }
    }
    _showDetails(loading, focused) {
      this._pendingShowDetails.value = runAtThisOrScheduleAtNextAnimationFrame(getWindow(this.element.domNode), () => {
        this._pendingShowDetails.clear();
        this._details.show();
        let didFocusDetails = false;
        if (loading) {
          this._details.widget.renderLoading();
        } else {
          this._details.widget.renderItem(this._list.getFocusedElements()[0], this._explainMode);
        }
        if (!this._details.widget.isEmpty) {
          this._positionDetails();
          this.element.domNode.classList.add("shows-details");
          if (focused) {
            this._details.widget.focus();
            didFocusDetails = true;
          }
        } else {
          this._details.hide();
        }
        if (!didFocusDetails) {
          this.editor.focus();
        }
      });
    }
    toggleExplainMode() {
      if (this._list.getFocusedElements()[0]) {
        this._explainMode = !this._explainMode;
        if (!this._isDetailsVisible()) {
          this.toggleDetails();
        } else {
          this._showDetails(false, false);
        }
      }
    }
    resetPersistedSize() {
      this._persistedSize.reset();
    }
    hideWidget() {
      this._pendingLayout.clear();
      this._pendingShowDetails.clear();
      this._loadingTimeout?.dispose();
      this._setState(
        0
        /* State.Hidden */
      );
      this._onDidHide.fire(this);
      this.element.clearSashHoverState();
      const dim = this._persistedSize.restore();
      const minPersistedHeight = Math.ceil(this.getLayoutInfo().itemHeight * 4.3);
      if (dim && dim.height < minPersistedHeight) {
        this._persistedSize.store(dim.with(void 0, minPersistedHeight));
      }
    }
    isFrozen() {
      return this._state === 4;
    }
    _afterRender(position) {
      if (position === null) {
        if (this._isDetailsVisible()) {
          this._details.hide();
        }
        return;
      }
      if (this._state === 2 || this._state === 1) {
        return;
      }
      if (this._isDetailsVisible() && !this._details.widget.isEmpty) {
        this._details.show();
      }
      this._positionDetails();
    }
    _layout(size2) {
      if (!this.editor.hasModel()) {
        return;
      }
      if (!this.editor.getDomNode()) {
        return;
      }
      const bodyBox = getClientArea(this.element.domNode.ownerDocument.body);
      const info = this.getLayoutInfo();
      if (!size2) {
        size2 = info.defaultSize;
      }
      let height = size2.height;
      let width2 = size2.width;
      this._status.element.style.height = `${info.itemHeight}px`;
      if (this._state === 2 || this._state === 1) {
        height = info.itemHeight + info.borderHeight;
        width2 = info.defaultSize.width / 2;
        this.element.enableSashes(false, false, false, false);
        this.element.minSize = this.element.maxSize = new Dimension(width2, height);
        this._contentWidget.setPreference(
          2
          /* ContentWidgetPositionPreference.BELOW */
        );
      } else {
        const maxWidth = bodyBox.width - info.borderHeight - 2 * info.horizontalPadding;
        if (width2 > maxWidth) {
          width2 = maxWidth;
        }
        const preferredWidth = this._completionModel ? this._completionModel.stats.pLabelLen * info.typicalHalfwidthCharacterWidth : width2;
        const fullHeight = info.statusBarHeight + this._list.contentHeight + info.borderHeight;
        const minHeight = info.itemHeight + info.statusBarHeight;
        const editorBox = getDomNodePagePosition(this.editor.getDomNode());
        const cursorBox = this.editor.getScrolledVisiblePosition(this.editor.getPosition());
        const cursorBottom = editorBox.top + cursorBox.top + cursorBox.height;
        const maxHeightBelow = Math.min(bodyBox.height - cursorBottom - info.verticalPadding, fullHeight);
        const availableSpaceAbove = editorBox.top + cursorBox.top - info.verticalPadding;
        const maxHeightAbove = Math.min(availableSpaceAbove, fullHeight);
        let maxHeight = Math.min(Math.max(maxHeightAbove, maxHeightBelow) + info.borderHeight, fullHeight);
        if (height === this._cappedHeight?.capped) {
          height = this._cappedHeight.wanted;
        }
        if (height < minHeight) {
          height = minHeight;
        }
        if (height > maxHeight) {
          height = maxHeight;
        }
        const forceRenderingAboveRequiredSpace = 150;
        if (height > maxHeightBelow && maxHeightAbove > maxHeightBelow || this._forceRenderingAbove && availableSpaceAbove > forceRenderingAboveRequiredSpace) {
          this._contentWidget.setPreference(
            1
            /* ContentWidgetPositionPreference.ABOVE */
          );
          this.element.enableSashes(true, true, false, false);
          maxHeight = maxHeightAbove;
        } else {
          this._contentWidget.setPreference(
            2
            /* ContentWidgetPositionPreference.BELOW */
          );
          this.element.enableSashes(false, true, true, false);
          maxHeight = maxHeightBelow;
        }
        this.element.preferredSize = new Dimension(preferredWidth, info.defaultSize.height);
        this.element.maxSize = new Dimension(maxWidth, maxHeight);
        this.element.minSize = new Dimension(220, minHeight);
        this._cappedHeight = height === fullHeight ? { wanted: this._cappedHeight?.wanted ?? size2.height, capped: height } : void 0;
      }
      this._resize(width2, height);
    }
    _resize(width2, height) {
      const { width: maxWidth, height: maxHeight } = this.element.maxSize;
      width2 = Math.min(maxWidth, width2);
      height = Math.min(maxHeight, height);
      const { statusBarHeight } = this.getLayoutInfo();
      this._list.layout(height - statusBarHeight, width2);
      this._listElement.style.height = `${height - statusBarHeight}px`;
      this.element.layout(height, width2);
      this._contentWidget.layout();
      this._positionDetails();
    }
    _positionDetails() {
      if (this._isDetailsVisible()) {
        this._details.placeAtAnchor(
          this.element.domNode,
          this._contentWidget.getPosition()?.preference[0] === 2
          /* ContentWidgetPositionPreference.BELOW */
        );
      }
    }
    getLayoutInfo() {
      const fontInfo = this.editor.getOption(
        59
        /* EditorOption.fontInfo */
      );
      const itemHeight = clamp(this.editor.getOption(
        136
        /* EditorOption.suggestLineHeight */
      ) || fontInfo.lineHeight, 8, 1e3);
      const statusBarHeight = !this.editor.getOption(
        134
        /* EditorOption.suggest */
      ).showStatusBar || this._state === 2 || this._state === 1 ? 0 : itemHeight;
      const borderWidth = this._details.widget.getLayoutInfo().borderWidth;
      const borderHeight = 2 * borderWidth;
      return {
        itemHeight,
        statusBarHeight,
        borderWidth,
        borderHeight,
        typicalHalfwidthCharacterWidth: fontInfo.typicalHalfwidthCharacterWidth,
        verticalPadding: 22,
        horizontalPadding: 14,
        defaultSize: new Dimension(430, statusBarHeight + 12 * itemHeight)
      };
    }
    _isDetailsVisible() {
      return this._storageService.getBoolean("expandSuggestionDocs", 0, false);
    }
    _setDetailsVisible(value) {
      this._storageService.store(
        "expandSuggestionDocs",
        value,
        0,
        0
        /* StorageTarget.USER */
      );
    }
    forceRenderingAbove() {
      if (!this._forceRenderingAbove) {
        this._forceRenderingAbove = true;
        this._layout(this._persistedSize.restore());
      }
    }
    stopForceRenderingAbove() {
      this._forceRenderingAbove = false;
    }
  }, SuggestWidget_1 = _fa, _fa.LOADING_MESSAGE = localize(1482, "Loading..."), _fa.NO_SUGGESTIONS_MESSAGE = localize(1483, "No suggestions."), _fa);
  SuggestWidget = SuggestWidget_1 = __decorate$1m([
    __param$1l(1, IStorageService),
    __param$1l(2, IContextKeyService),
    __param$1l(3, IThemeService),
    __param$1l(4, IInstantiationService)
  ], SuggestWidget);
  class SuggestContentWidget {
    constructor(_widget, _editor) {
      this._widget = _widget;
      this._editor = _editor;
      this.allowEditorOverflow = true;
      this.suppressMouseDown = false;
      this._preferenceLocked = false;
      this._added = false;
      this._hidden = false;
    }
    dispose() {
      if (this._added) {
        this._added = false;
        this._editor.removeContentWidget(this);
      }
    }
    getId() {
      return "editor.widget.suggestWidget";
    }
    getDomNode() {
      return this._widget.element.domNode;
    }
    show() {
      this._hidden = false;
      if (!this._added) {
        this._added = true;
        this._editor.addContentWidget(this);
      }
    }
    hide() {
      if (!this._hidden) {
        this._hidden = true;
        this.layout();
      }
    }
    layout() {
      this._editor.layoutContentWidget(this);
    }
    getPosition() {
      if (this._hidden || !this._position || !this._preference) {
        return null;
      }
      return {
        position: this._position,
        preference: [this._preference]
      };
    }
    beforeRender() {
      const { height, width: width2 } = this._widget.element.size;
      const { borderWidth, horizontalPadding } = this._widget.getLayoutInfo();
      return new Dimension(width2 + 2 * borderWidth + horizontalPadding, height + 2 * borderWidth);
    }
    afterRender(position) {
      this._widget._afterRender(position);
    }
    setPreference(preference) {
      if (!this._preferenceLocked) {
        this._preference = preference;
      }
    }
    lockPreference() {
      this._preferenceLocked = true;
    }
    unlockPreference() {
      this._preferenceLocked = false;
    }
    setPosition(position) {
      this._position = position;
    }
  }
  var __decorate$1l = 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$1k = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  var SuggestController_1;
  class LineSuffix {
    constructor(_model, _position) {
      this._model = _model;
      this._position = _position;
      this._decorationOptions = ModelDecorationOptions.register({
        description: "suggest-line-suffix",
        stickiness: 1
        /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */
      });
      const maxColumn = _model.getLineMaxColumn(_position.lineNumber);
      if (maxColumn !== _position.column) {
        const offset = _model.getOffsetAt(_position);
        const end = _model.getPositionAt(offset + 1);
        _model.changeDecorations((accessor) => {
          if (this._marker) {
            accessor.removeDecoration(this._marker);
          }
          this._marker = accessor.addDecoration(Range$2.fromPositions(_position, end), this._decorationOptions);
        });
      }
    }
    dispose() {
      if (this._marker && !this._model.isDisposed()) {
        this._model.changeDecorations((accessor) => {
          accessor.removeDecoration(this._marker);
          this._marker = void 0;
        });
      }
    }
    delta(position) {
      if (this._model.isDisposed() || this._position.lineNumber !== position.lineNumber) {
        return 0;
      }
      if (this._marker) {
        const range2 = this._model.getDecorationRange(this._marker);
        const end = this._model.getOffsetAt(range2.getStartPosition());
        return end - this._model.getOffsetAt(position);
      } else {
        return this._model.getLineMaxColumn(position.lineNumber) - position.column;
      }
    }
  }
  let SuggestController = (_ga = class {
    static get(editor2) {
      return editor2.getContribution(SuggestController_1.ID);
    }
    get onWillInsertSuggestItem() {
      return this._onWillInsertSuggestItem.event;
    }
    constructor(editor2, _memoryService, _commandService, _contextKeyService, _instantiationService, _logService, _telemetryService) {
      this._memoryService = _memoryService;
      this._commandService = _commandService;
      this._contextKeyService = _contextKeyService;
      this._instantiationService = _instantiationService;
      this._logService = _logService;
      this._telemetryService = _telemetryService;
      this._lineSuffix = new MutableDisposable();
      this._toDispose = new DisposableStore();
      this._selectors = new PriorityRegistry((s) => s.priority);
      this._onWillInsertSuggestItem = new Emitter$1();
      this._wantsForceRenderingAbove = false;
      this.editor = editor2;
      this.model = _instantiationService.createInstance(SuggestModel, this.editor);
      this._selectors.register({
        priority: 0,
        select: (model, pos, items) => this._memoryService.select(model, pos, items)
      });
      const ctxInsertMode = Context$2.InsertMode.bindTo(_contextKeyService);
      ctxInsertMode.set(editor2.getOption(
        134
        /* EditorOption.suggest */
      ).insertMode);
      this._toDispose.add(this.model.onDidTrigger(() => ctxInsertMode.set(editor2.getOption(
        134
        /* EditorOption.suggest */
      ).insertMode)));
      this.widget = this._toDispose.add(new WindowIdleValue(getWindow(editor2.getDomNode()), () => {
        const widget = this._instantiationService.createInstance(SuggestWidget, this.editor);
        this._toDispose.add(widget);
        this._toDispose.add(widget.onDidSelect((item) => this._insertSuggestion(
          item,
          0
          /* InsertFlags.None */
        ), this));
        const commitCharacterController = new CommitCharacterController(this.editor, widget, this.model, (item) => this._insertSuggestion(
          item,
          2
          /* InsertFlags.NoAfterUndoStop */
        ));
        this._toDispose.add(commitCharacterController);
        const ctxMakesTextEdit = Context$2.MakesTextEdit.bindTo(this._contextKeyService);
        const ctxHasInsertAndReplace = Context$2.HasInsertAndReplaceRange.bindTo(this._contextKeyService);
        const ctxCanResolve = Context$2.CanResolve.bindTo(this._contextKeyService);
        this._toDispose.add(toDisposable(() => {
          ctxMakesTextEdit.reset();
          ctxHasInsertAndReplace.reset();
          ctxCanResolve.reset();
        }));
        this._toDispose.add(widget.onDidFocus(({ item }) => {
          const position = this.editor.getPosition();
          const startColumn = item.editStart.column;
          const endColumn = position.column;
          let value = true;
          if (this.editor.getOption(
            1
            /* EditorOption.acceptSuggestionOnEnter */
          ) === "smart" && this.model.state === 2 && !item.completion.additionalTextEdits && !(item.completion.insertTextRules & 4) && endColumn - startColumn === item.completion.insertText.length) {
            const oldText = this.editor.getModel().getValueInRange({
              startLineNumber: position.lineNumber,
              startColumn,
              endLineNumber: position.lineNumber,
              endColumn
            });
            value = oldText !== item.completion.insertText;
          }
          ctxMakesTextEdit.set(value);
          ctxHasInsertAndReplace.set(!Position$1.equals(item.editInsertEnd, item.editReplaceEnd));
          ctxCanResolve.set(Boolean(item.provider.resolveCompletionItem) || Boolean(item.completion.documentation) || item.completion.detail !== item.completion.label);
        }));
        this._toDispose.add(widget.onDetailsKeyDown((e) => {
          if (e.toKeyCodeChord().equals(new KeyCodeChord(
            true,
            false,
            false,
            false,
            33
            /* KeyCode.KeyC */
          )) || isMacintosh && e.toKeyCodeChord().equals(new KeyCodeChord(
            false,
            false,
            false,
            true,
            33
            /* KeyCode.KeyC */
          ))) {
            e.stopPropagation();
            return;
          }
          if (!e.toKeyCodeChord().isModifierKey()) {
            this.editor.focus();
          }
        }));
        if (this._wantsForceRenderingAbove) {
          widget.forceRenderingAbove();
        }
        return widget;
      }));
      this._overtypingCapturer = this._toDispose.add(new WindowIdleValue(getWindow(editor2.getDomNode()), () => {
        return this._toDispose.add(new OvertypingCapturer(this.editor, this.model));
      }));
      this._alternatives = this._toDispose.add(new WindowIdleValue(getWindow(editor2.getDomNode()), () => {
        return this._toDispose.add(new SuggestAlternatives(this.editor, this._contextKeyService));
      }));
      this._toDispose.add(_instantiationService.createInstance(WordContextKey, editor2));
      this._toDispose.add(this.model.onDidTrigger((e) => {
        this.widget.value.showTriggered(e.auto, e.shy ? 250 : 50);
        this._lineSuffix.value = new LineSuffix(this.editor.getModel(), e.position);
      }));
      this._toDispose.add(this.model.onDidSuggest((e) => {
        if (e.triggerOptions.shy) {
          return;
        }
        let index = -1;
        for (const selector of this._selectors.itemsOrderedByPriorityDesc) {
          index = selector.select(this.editor.getModel(), this.editor.getPosition(), e.completionModel.items);
          if (index !== -1) {
            break;
          }
        }
        if (index === -1) {
          index = 0;
        }
        if (this.model.state === 0) {
          return;
        }
        let noFocus = false;
        if (e.triggerOptions.auto) {
          const options = this.editor.getOption(
            134
            /* EditorOption.suggest */
          );
          if (options.selectionMode === "never" || options.selectionMode === "always") {
            noFocus = options.selectionMode === "never";
          } else if (options.selectionMode === "whenTriggerCharacter") {
            noFocus = e.triggerOptions.triggerKind !== 1;
          } else if (options.selectionMode === "whenQuickSuggestion") {
            noFocus = e.triggerOptions.triggerKind === 1 && !e.triggerOptions.refilter;
          }
        }
        this.widget.value.showSuggestions(e.completionModel, index, e.isFrozen, e.triggerOptions.auto, noFocus);
      }));
      this._toDispose.add(this.model.onDidCancel((e) => {
        if (!e.retrigger) {
          this.widget.value.hideWidget();
        }
      }));
      this._toDispose.add(this.editor.onDidBlurEditorWidget(() => {
        {
          this.model.cancel();
          this.model.clear();
        }
      }));
      const acceptSuggestionsOnEnter = Context$2.AcceptSuggestionsOnEnter.bindTo(_contextKeyService);
      const updateFromConfig = () => {
        const acceptSuggestionOnEnter = this.editor.getOption(
          1
          /* EditorOption.acceptSuggestionOnEnter */
        );
        acceptSuggestionsOnEnter.set(acceptSuggestionOnEnter === "on" || acceptSuggestionOnEnter === "smart");
      };
      this._toDispose.add(this.editor.onDidChangeConfiguration(() => updateFromConfig()));
      updateFromConfig();
    }
    dispose() {
      this._alternatives.dispose();
      this._toDispose.dispose();
      this.widget.dispose();
      this.model.dispose();
      this._lineSuffix.dispose();
      this._onWillInsertSuggestItem.dispose();
    }
    _insertSuggestion(event, flags) {
      if (!event || !event.item) {
        this._alternatives.value.reset();
        this.model.cancel();
        this.model.clear();
        return;
      }
      if (!this.editor.hasModel()) {
        return;
      }
      const snippetController = SnippetController2.get(this.editor);
      if (!snippetController) {
        return;
      }
      this._onWillInsertSuggestItem.fire({ item: event.item });
      const model = this.editor.getModel();
      const modelVersionNow = model.getAlternativeVersionId();
      const { item } = event;
      const tasks = [];
      const cts = new CancellationTokenSource$1();
      if (!(flags & 1)) {
        this.editor.pushUndoStop();
      }
      const info = this.getOverwriteInfo(item, Boolean(
        flags & 8
        /* InsertFlags.AlternativeOverwriteConfig */
      ));
      this._memoryService.memorize(model, this.editor.getPosition(), item);
      const isResolved = item.isResolved;
      let _commandExectionDuration = -1;
      let _additionalEditsAppliedAsync = -1;
      if (Array.isArray(item.completion.additionalTextEdits)) {
        this.model.cancel();
        const scrollState = StableEditorScrollState.capture(this.editor);
        this.editor.executeEdits("suggestController.additionalTextEdits.sync", item.completion.additionalTextEdits.map((edit2) => {
          let range2 = Range$2.lift(edit2.range);
          if (range2.startLineNumber === item.position.lineNumber && range2.startColumn > item.position.column) {
            const columnDelta = this.editor.getPosition().column - item.position.column;
            const startColumnDelta = columnDelta;
            const endColumnDelta = Range$2.spansMultipleLines(range2) ? 0 : columnDelta;
            range2 = new Range$2(range2.startLineNumber, range2.startColumn + startColumnDelta, range2.endLineNumber, range2.endColumn + endColumnDelta);
          }
          return EditOperation.replaceMove(range2, edit2.text);
        }));
        scrollState.restoreRelativeVerticalPositionOfCursor(this.editor);
      } else if (!isResolved) {
        const sw = new StopWatch();
        let position;
        const docListener = model.onDidChangeContent((e) => {
          if (e.isFlush) {
            cts.cancel();
            docListener.dispose();
            return;
          }
          for (const change of e.changes) {
            const thisPosition = Range$2.getEndPosition(change.range);
            if (!position || Position$1.isBefore(thisPosition, position)) {
              position = thisPosition;
            }
          }
        });
        const oldFlags = flags;
        flags |= 2;
        let didType = false;
        const typeListener = this.editor.onWillType(() => {
          typeListener.dispose();
          didType = true;
          if (!(oldFlags & 2)) {
            this.editor.pushUndoStop();
          }
        });
        tasks.push(item.resolve(cts.token).then(() => {
          if (!item.completion.additionalTextEdits || cts.token.isCancellationRequested) {
            return void 0;
          }
          if (position && item.completion.additionalTextEdits.some((edit2) => Position$1.isBefore(position, Range$2.getStartPosition(edit2.range)))) {
            return false;
          }
          if (didType) {
            this.editor.pushUndoStop();
          }
          const scrollState = StableEditorScrollState.capture(this.editor);
          this.editor.executeEdits("suggestController.additionalTextEdits.async", item.completion.additionalTextEdits.map((edit2) => EditOperation.replaceMove(Range$2.lift(edit2.range), edit2.text)));
          scrollState.restoreRelativeVerticalPositionOfCursor(this.editor);
          if (didType || !(oldFlags & 2)) {
            this.editor.pushUndoStop();
          }
          return true;
        }).then((applied) => {
          this._logService.trace("[suggest] async resolving of edits DONE (ms, applied?)", sw.elapsed(), applied);
          _additionalEditsAppliedAsync = applied === true ? 1 : applied === false ? 0 : -2;
        }).finally(() => {
          docListener.dispose();
          typeListener.dispose();
        }));
      }
      let { insertText } = item.completion;
      if (!(item.completion.insertTextRules & 4)) {
        insertText = SnippetParser.escape(insertText);
      }
      this.model.cancel();
      snippetController.insert(insertText, {
        overwriteBefore: info.overwriteBefore,
        overwriteAfter: info.overwriteAfter,
        undoStopBefore: false,
        undoStopAfter: false,
        adjustWhitespace: !(item.completion.insertTextRules & 1),
        clipboardText: event.model.clipboardText,
        overtypingCapturer: this._overtypingCapturer.value,
        reason: EditSources.suggest({ providerId: ProviderId.fromExtensionId(item.extensionId?.value) })
      });
      if (!(flags & 2)) {
        this.editor.pushUndoStop();
      }
      if (item.completion.command) {
        if (item.completion.command.id === TriggerSuggestAction.id) {
          this.model.trigger({ auto: true, retrigger: true });
        } else {
          const sw = new StopWatch();
          tasks.push(this._commandService.executeCommand(item.completion.command.id, ...item.completion.command.arguments ? [...item.completion.command.arguments] : []).catch((e) => {
            if (item.completion.extensionId) {
              onUnexpectedExternalError(e);
            } else {
              onUnexpectedError(e);
            }
          }).finally(() => {
            _commandExectionDuration = sw.elapsed();
          }));
        }
      }
      if (flags & 4) {
        this._alternatives.value.set(event, (next) => {
          cts.cancel();
          while (model.canUndo()) {
            if (modelVersionNow !== model.getAlternativeVersionId()) {
              model.undo();
            }
            this._insertSuggestion(next, 1 | 2 | (flags & 8 ? 8 : 0));
            break;
          }
        });
      }
      this._alertCompletionItem(item);
      Promise.all(tasks).finally(() => {
        this._reportSuggestionAcceptedTelemetry(item, model, isResolved, _commandExectionDuration, _additionalEditsAppliedAsync, event.index, event.model.items);
        this.model.clear();
        cts.dispose();
      });
    }
    _reportSuggestionAcceptedTelemetry(item, model, itemResolved, commandExectionDuration, additionalEditsAppliedAsync, index, completionItems) {
      if (Math.random() > 1e-4) {
        return;
      }
      const labelMap = /* @__PURE__ */ new Map();
      for (let i2 = 0; i2 < Math.min(30, completionItems.length); i2++) {
        const label = completionItems[i2].textLabel;
        if (labelMap.has(label)) {
          labelMap.get(label).push(i2);
        } else {
          labelMap.set(label, [i2]);
        }
      }
      const firstIndexArray = labelMap.get(item.textLabel);
      const hasDuplicates = firstIndexArray && firstIndexArray.length > 1;
      const firstIndex = hasDuplicates ? firstIndexArray[0] : -1;
      this._telemetryService.publicLog2("suggest.acceptedSuggestion", {
        extensionId: item.extensionId?.value ?? "unknown",
        providerId: item.provider._debugDisplayName ?? "unknown",
        kind: item.completion.kind,
        basenameHash: hash(basename(model.uri)).toString(16),
        languageId: model.getLanguageId(),
        fileExtension: extname(model.uri),
        resolveInfo: !item.provider.resolveCompletionItem ? -1 : itemResolved ? 1 : 0,
        resolveDuration: item.resolveDuration,
        commandDuration: commandExectionDuration,
        additionalEditsAsync: additionalEditsAppliedAsync,
        index,
        firstIndex
      });
    }
    getOverwriteInfo(item, toggleMode) {
      assertType(this.editor.hasModel());
      let replace = this.editor.getOption(
        134
        /* EditorOption.suggest */
      ).insertMode === "replace";
      if (toggleMode) {
        replace = !replace;
      }
      const overwriteBefore = item.position.column - item.editStart.column;
      const overwriteAfter = (replace ? item.editReplaceEnd.column : item.editInsertEnd.column) - item.position.column;
      const columnDelta = this.editor.getPosition().column - item.position.column;
      const suffixDelta = this._lineSuffix.value ? this._lineSuffix.value.delta(this.editor.getPosition()) : 0;
      return {
        overwriteBefore: overwriteBefore + columnDelta,
        overwriteAfter: overwriteAfter + suffixDelta
      };
    }
    _alertCompletionItem(item) {
      if (isNonEmptyArray(item.completion.additionalTextEdits)) {
        const msg = localize(1463, "Accepting '{0}' made {1} additional edits", item.textLabel, item.completion.additionalTextEdits.length);
        alert(msg);
      }
    }
    triggerSuggest(onlyFrom, auto, noFilter) {
      if (this.editor.hasModel()) {
        this.model.trigger({
          auto: auto ?? false,
          completionOptions: { providerFilter: onlyFrom, kindFilter: noFilter ? /* @__PURE__ */ new Set() : void 0 }
        });
        this.editor.revealPosition(
          this.editor.getPosition(),
          0
          /* ScrollType.Smooth */
        );
        this.editor.focus();
      }
    }
    triggerSuggestAndAcceptBest(arg) {
      if (!this.editor.hasModel()) {
        return;
      }
      const positionNow = this.editor.getPosition();
      const fallback2 = () => {
        if (positionNow.equals(this.editor.getPosition())) {
          this._commandService.executeCommand(arg.fallback);
        }
      };
      const makesTextEdit = (item) => {
        if (item.completion.insertTextRules & 4 || item.completion.additionalTextEdits) {
          return true;
        }
        const position = this.editor.getPosition();
        const startColumn = item.editStart.column;
        const endColumn = position.column;
        if (endColumn - startColumn !== item.completion.insertText.length) {
          return true;
        }
        const textNow = this.editor.getModel().getValueInRange({
          startLineNumber: position.lineNumber,
          startColumn,
          endLineNumber: position.lineNumber,
          endColumn
        });
        return textNow !== item.completion.insertText;
      };
      Event.once(this.model.onDidTrigger)((_) => {
        const listener = [];
        Event.any(this.model.onDidTrigger, this.model.onDidCancel)(() => {
          dispose(listener);
          fallback2();
        }, void 0, listener);
        this.model.onDidSuggest(({ completionModel }) => {
          dispose(listener);
          if (completionModel.items.length === 0) {
            fallback2();
            return;
          }
          const index = this._memoryService.select(this.editor.getModel(), this.editor.getPosition(), completionModel.items);
          const item = completionModel.items[index];
          if (!makesTextEdit(item)) {
            fallback2();
            return;
          }
          this.editor.pushUndoStop();
          this._insertSuggestion(
            { index, item, model: completionModel },
            4 | 1 | 2
            /* InsertFlags.NoAfterUndoStop */
          );
        }, void 0, listener);
      });
      this.model.trigger({ auto: false, shy: true });
      this.editor.revealPosition(
        positionNow,
        0
        /* ScrollType.Smooth */
      );
      this.editor.focus();
    }
    acceptSelectedSuggestion(keepAlternativeSuggestions, alternativeOverwriteConfig) {
      const item = this.widget.value.getFocusedItem();
      let flags = 0;
      if (keepAlternativeSuggestions) {
        flags |= 4;
      }
      if (alternativeOverwriteConfig) {
        flags |= 8;
      }
      this._insertSuggestion(item, flags);
    }
    acceptNextSuggestion() {
      this._alternatives.value.next();
    }
    acceptPrevSuggestion() {
      this._alternatives.value.prev();
    }
    cancelSuggestWidget() {
      this.model.cancel();
      this.model.clear();
      this.widget.value.hideWidget();
    }
    focusSuggestion() {
      this.widget.value.focusSelected();
    }
    selectNextSuggestion() {
      this.widget.value.selectNext();
    }
    selectNextPageSuggestion() {
      this.widget.value.selectNextPage();
    }
    selectLastSuggestion() {
      this.widget.value.selectLast();
    }
    selectPrevSuggestion() {
      this.widget.value.selectPrevious();
    }
    selectPrevPageSuggestion() {
      this.widget.value.selectPreviousPage();
    }
    selectFirstSuggestion() {
      this.widget.value.selectFirst();
    }
    toggleSuggestionDetails() {
      this.widget.value.toggleDetails();
    }
    toggleExplainMode() {
      this.widget.value.toggleExplainMode();
    }
    toggleSuggestionFocus() {
      this.widget.value.toggleDetailsFocus();
    }
    resetWidgetSize() {
      this.widget.value.resetPersistedSize();
    }
    forceRenderingAbove() {
      if (this.widget.isInitialized) {
        this.widget.value.forceRenderingAbove();
      } else {
        this._wantsForceRenderingAbove = true;
      }
    }
    stopForceRenderingAbove() {
      if (this.widget.isInitialized) {
        this.widget.value.stopForceRenderingAbove();
      } else {
        this._wantsForceRenderingAbove = false;
      }
    }
    registerSelector(selector) {
      return this._selectors.register(selector);
    }
  }, SuggestController_1 = _ga, _ga.ID = "editor.contrib.suggestController", _ga);
  SuggestController = SuggestController_1 = __decorate$1l([
    __param$1k(1, ISuggestMemoryService),
    __param$1k(2, ICommandService),
    __param$1k(3, IContextKeyService),
    __param$1k(4, IInstantiationService),
    __param$1k(5, ILogService),
    __param$1k(6, ITelemetryService)
  ], SuggestController);
  class PriorityRegistry {
    constructor(prioritySelector) {
      this.prioritySelector = prioritySelector;
      this._items = new Array();
    }
    register(value) {
      if (this._items.indexOf(value) !== -1) {
        throw new Error("Value is already registered");
      }
      this._items.push(value);
      this._items.sort((s1, s2) => this.prioritySelector(s2) - this.prioritySelector(s1));
      return {
        dispose: () => {
          const idx = this._items.indexOf(value);
          if (idx >= 0) {
            this._items.splice(idx, 1);
          }
        }
      };
    }
    get itemsOrderedByPriorityDesc() {
      return this._items;
    }
  }
  const _TriggerSuggestAction = class _TriggerSuggestAction extends EditorAction {
    constructor() {
      super({
        id: _TriggerSuggestAction.id,
        label: localize2(1471, "Trigger Suggest"),
        precondition: ContextKeyExpr.and(EditorContextKeys.writable, EditorContextKeys.hasCompletionItemProvider, Context$2.Visible.toNegated()),
        kbOpts: {
          kbExpr: EditorContextKeys.textInputFocus,
          primary: 2048 | 10,
          secondary: [
            2048 | 39
            /* KeyCode.KeyI */
          ],
          mac: { primary: 256 | 10, secondary: [
            512 | 9,
            2048 | 39
            /* KeyCode.KeyI */
          ] },
          weight: 100
          /* KeybindingWeight.EditorContrib */
        }
      });
    }
    run(_accessor, editor2, args) {
      const controller = SuggestController.get(editor2);
      if (!controller) {
        return;
      }
      let auto;
      if (args && typeof args === "object") {
        if (args.auto === true) {
          auto = true;
        }
      }
      controller.triggerSuggest(void 0, auto, void 0);
    }
  };
  _TriggerSuggestAction.id = "editor.action.triggerSuggest";
  let TriggerSuggestAction = _TriggerSuggestAction;
  registerEditorContribution(
    SuggestController.ID,
    SuggestController,
    2
    /* EditorContributionInstantiation.BeforeFirstInteraction */
  );
  registerEditorAction(TriggerSuggestAction);
  const weight$2 = 100 + 90;
  const SuggestCommand = EditorCommand.bindToContribution(SuggestController.get);
  registerEditorCommand(new SuggestCommand({
    id: "acceptSelectedSuggestion",
    precondition: ContextKeyExpr.and(Context$2.Visible, Context$2.HasFocusedSuggestion),
    handler(x) {
      x.acceptSelectedSuggestion(true, false);
    },
    kbOpts: [{
      // normal tab
      primary: 2,
      kbExpr: ContextKeyExpr.and(Context$2.Visible, EditorContextKeys.textInputFocus),
      weight: weight$2
    }, {
      // accept on enter has special rules
      primary: 3,
      kbExpr: ContextKeyExpr.and(Context$2.Visible, EditorContextKeys.textInputFocus, Context$2.AcceptSuggestionsOnEnter, Context$2.MakesTextEdit),
      weight: weight$2
    }],
    menuOpts: [{
      menuId: suggestWidgetStatusbarMenu,
      title: localize(1464, "Insert"),
      group: "left",
      order: 1,
      when: Context$2.HasInsertAndReplaceRange.toNegated()
    }, {
      menuId: suggestWidgetStatusbarMenu,
      title: localize(1465, "Insert"),
      group: "left",
      order: 1,
      when: ContextKeyExpr.and(Context$2.HasInsertAndReplaceRange, Context$2.InsertMode.isEqualTo("insert"))
    }, {
      menuId: suggestWidgetStatusbarMenu,
      title: localize(1466, "Replace"),
      group: "left",
      order: 1,
      when: ContextKeyExpr.and(Context$2.HasInsertAndReplaceRange, Context$2.InsertMode.isEqualTo("replace"))
    }]
  }));
  registerEditorCommand(new SuggestCommand({
    id: "acceptAlternativeSelectedSuggestion",
    precondition: ContextKeyExpr.and(Context$2.Visible, EditorContextKeys.textInputFocus, Context$2.HasFocusedSuggestion),
    kbOpts: {
      weight: weight$2,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 1024 | 3,
      secondary: [
        1024 | 2
        /* KeyCode.Tab */
      ]
    },
    handler(x) {
      x.acceptSelectedSuggestion(false, true);
    },
    menuOpts: [{
      menuId: suggestWidgetStatusbarMenu,
      group: "left",
      order: 2,
      when: ContextKeyExpr.and(Context$2.HasInsertAndReplaceRange, Context$2.InsertMode.isEqualTo("insert")),
      title: localize(1467, "Replace")
    }, {
      menuId: suggestWidgetStatusbarMenu,
      group: "left",
      order: 2,
      when: ContextKeyExpr.and(Context$2.HasInsertAndReplaceRange, Context$2.InsertMode.isEqualTo("replace")),
      title: localize(1468, "Insert")
    }]
  }));
  CommandsRegistry.registerCommandAlias("acceptSelectedSuggestionOnEnter", "acceptSelectedSuggestion");
  registerEditorCommand(new SuggestCommand({
    id: "hideSuggestWidget",
    precondition: Context$2.Visible,
    handler: (x) => x.cancelSuggestWidget(),
    kbOpts: {
      weight: weight$2,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 9,
      secondary: [
        1024 | 9
        /* KeyCode.Escape */
      ]
    }
  }));
  registerEditorCommand(new SuggestCommand({
    id: "selectNextSuggestion",
    precondition: ContextKeyExpr.and(Context$2.Visible, ContextKeyExpr.or(Context$2.MultipleSuggestions, Context$2.HasFocusedSuggestion.negate())),
    handler: (c) => c.selectNextSuggestion(),
    kbOpts: {
      weight: weight$2,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 18,
      secondary: [
        2048 | 18
        /* KeyCode.DownArrow */
      ],
      mac: { primary: 18, secondary: [
        2048 | 18,
        256 | 44
        /* KeyCode.KeyN */
      ] }
    }
  }));
  registerEditorCommand(new SuggestCommand({
    id: "selectNextPageSuggestion",
    precondition: ContextKeyExpr.and(Context$2.Visible, ContextKeyExpr.or(Context$2.MultipleSuggestions, Context$2.HasFocusedSuggestion.negate())),
    handler: (c) => c.selectNextPageSuggestion(),
    kbOpts: {
      weight: weight$2,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 12,
      secondary: [
        2048 | 12
        /* KeyCode.PageDown */
      ]
    }
  }));
  registerEditorCommand(new SuggestCommand({
    id: "selectLastSuggestion",
    precondition: ContextKeyExpr.and(Context$2.Visible, ContextKeyExpr.or(Context$2.MultipleSuggestions, Context$2.HasFocusedSuggestion.negate())),
    handler: (c) => c.selectLastSuggestion()
  }));
  registerEditorCommand(new SuggestCommand({
    id: "selectPrevSuggestion",
    precondition: ContextKeyExpr.and(Context$2.Visible, ContextKeyExpr.or(Context$2.MultipleSuggestions, Context$2.HasFocusedSuggestion.negate())),
    handler: (c) => c.selectPrevSuggestion(),
    kbOpts: {
      weight: weight$2,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 16,
      secondary: [
        2048 | 16
        /* KeyCode.UpArrow */
      ],
      mac: { primary: 16, secondary: [
        2048 | 16,
        256 | 46
        /* KeyCode.KeyP */
      ] }
    }
  }));
  registerEditorCommand(new SuggestCommand({
    id: "selectPrevPageSuggestion",
    precondition: ContextKeyExpr.and(Context$2.Visible, ContextKeyExpr.or(Context$2.MultipleSuggestions, Context$2.HasFocusedSuggestion.negate())),
    handler: (c) => c.selectPrevPageSuggestion(),
    kbOpts: {
      weight: weight$2,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 11,
      secondary: [
        2048 | 11
        /* KeyCode.PageUp */
      ]
    }
  }));
  registerEditorCommand(new SuggestCommand({
    id: "selectFirstSuggestion",
    precondition: ContextKeyExpr.and(Context$2.Visible, ContextKeyExpr.or(Context$2.MultipleSuggestions, Context$2.HasFocusedSuggestion.negate())),
    handler: (c) => c.selectFirstSuggestion()
  }));
  registerEditorCommand(new SuggestCommand({
    id: "focusSuggestion",
    precondition: ContextKeyExpr.and(Context$2.Visible, Context$2.HasFocusedSuggestion.negate()),
    handler: (x) => x.focusSuggestion(),
    kbOpts: {
      weight: weight$2,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 2048 | 10,
      secondary: [
        2048 | 39
        /* KeyCode.KeyI */
      ],
      mac: { primary: 256 | 10, secondary: [
        2048 | 39
        /* KeyCode.KeyI */
      ] }
    }
  }));
  registerEditorCommand(new SuggestCommand({
    id: "focusAndAcceptSuggestion",
    precondition: ContextKeyExpr.and(Context$2.Visible, Context$2.HasFocusedSuggestion.negate()),
    handler: (c) => {
      c.focusSuggestion();
      c.acceptSelectedSuggestion(true, false);
    }
  }));
  registerEditorCommand(new SuggestCommand({
    id: "toggleSuggestionDetails",
    precondition: ContextKeyExpr.and(Context$2.Visible, Context$2.HasFocusedSuggestion),
    handler: (x) => x.toggleSuggestionDetails(),
    kbOpts: {
      weight: weight$2,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 2048 | 10,
      secondary: [
        2048 | 39
        /* KeyCode.KeyI */
      ],
      mac: { primary: 256 | 10, secondary: [
        2048 | 39
        /* KeyCode.KeyI */
      ] }
    },
    menuOpts: [{
      menuId: suggestWidgetStatusbarMenu,
      group: "right",
      order: 1,
      when: ContextKeyExpr.and(Context$2.DetailsVisible, Context$2.CanResolve),
      title: localize(1469, "Show Less")
    }, {
      menuId: suggestWidgetStatusbarMenu,
      group: "right",
      order: 1,
      when: ContextKeyExpr.and(Context$2.DetailsVisible.toNegated(), Context$2.CanResolve),
      title: localize(1470, "Show More")
    }]
  }));
  registerEditorCommand(new SuggestCommand({
    id: "toggleExplainMode",
    precondition: Context$2.Visible,
    handler: (x) => x.toggleExplainMode(),
    kbOpts: {
      weight: 100,
      primary: 2048 | 90
    }
  }));
  registerEditorCommand(new SuggestCommand({
    id: "toggleSuggestionFocus",
    precondition: Context$2.Visible,
    handler: (x) => x.toggleSuggestionFocus(),
    kbOpts: {
      weight: weight$2,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 2048 | 512 | 10,
      mac: {
        primary: 256 | 512 | 10
        /* KeyCode.Space */
      }
    }
  }));
  registerEditorCommand(new SuggestCommand({
    id: "insertBestCompletion",
    precondition: ContextKeyExpr.and(EditorContextKeys.textInputFocus, ContextKeyExpr.equals("config.editor.tabCompletion", "on"), WordContextKey.AtEnd, Context$2.Visible.toNegated(), SuggestAlternatives.OtherSuggestions.toNegated(), SnippetController2.InSnippetMode.toNegated()),
    handler: (x, arg) => {
      x.triggerSuggestAndAcceptBest(isObject(arg) ? { fallback: "tab", ...arg } : { fallback: "tab" });
    },
    kbOpts: {
      weight: weight$2,
      primary: 2
      /* KeyCode.Tab */
    }
  }));
  registerEditorCommand(new SuggestCommand({
    id: "insertNextSuggestion",
    precondition: ContextKeyExpr.and(EditorContextKeys.textInputFocus, ContextKeyExpr.equals("config.editor.tabCompletion", "on"), SuggestAlternatives.OtherSuggestions, Context$2.Visible.toNegated(), SnippetController2.InSnippetMode.toNegated()),
    handler: (x) => x.acceptNextSuggestion(),
    kbOpts: {
      weight: weight$2,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 2
      /* KeyCode.Tab */
    }
  }));
  registerEditorCommand(new SuggestCommand({
    id: "insertPrevSuggestion",
    precondition: ContextKeyExpr.and(EditorContextKeys.textInputFocus, ContextKeyExpr.equals("config.editor.tabCompletion", "on"), SuggestAlternatives.OtherSuggestions, Context$2.Visible.toNegated(), SnippetController2.InSnippetMode.toNegated()),
    handler: (x) => x.acceptPrevSuggestion(),
    kbOpts: {
      weight: weight$2,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 1024 | 2
      /* KeyCode.Tab */
    }
  }));
  registerEditorAction(class extends EditorAction {
    constructor() {
      super({
        id: "editor.action.resetSuggestSize",
        label: localize2(1472, "Reset Suggest Widget Size"),
        precondition: void 0
      });
    }
    run(_accessor, editor2) {
      SuggestController.get(editor2)?.resetWidgetSize();
    }
  });
  class SuggestWidgetAdaptor extends Disposable {
    get selectedItem() {
      return this._currentSuggestItemInfo;
    }
    constructor(editor2, suggestControllerPreselector, onWillAccept) {
      super();
      this.editor = editor2;
      this.suggestControllerPreselector = suggestControllerPreselector;
      this.onWillAccept = onWillAccept;
      this.isSuggestWidgetVisible = false;
      this.isShiftKeyPressed = false;
      this._isActive = false;
      this._currentSuggestItemInfo = void 0;
      this._onDidSelectedItemChange = this._register(new Emitter$1());
      this.onDidSelectedItemChange = this._onDidSelectedItemChange.event;
      this._register(editor2.onKeyDown((e) => {
        if (e.shiftKey && !this.isShiftKeyPressed) {
          this.isShiftKeyPressed = true;
          this.update(this._isActive);
        }
      }));
      this._register(editor2.onKeyUp((e) => {
        if (e.shiftKey && this.isShiftKeyPressed) {
          this.isShiftKeyPressed = false;
          this.update(this._isActive);
        }
      }));
      const suggestController = SuggestController.get(this.editor);
      if (suggestController) {
        this._register(suggestController.registerSelector({
          priority: 100,
          select: (model, pos, suggestItems) => {
            const textModel = this.editor.getModel();
            if (!textModel) {
              return -1;
            }
            const i2 = this.suggestControllerPreselector();
            const itemToPreselect = i2 ? singleTextRemoveCommonPrefix(i2, textModel) : void 0;
            if (!itemToPreselect) {
              return -1;
            }
            const position = Position$1.lift(pos);
            const candidates = suggestItems.map((suggestItem, index) => {
              const suggestItemInfo = SuggestItemInfo.fromSuggestion(suggestController, textModel, position, suggestItem, this.isShiftKeyPressed);
              const suggestItemTextEdit = singleTextRemoveCommonPrefix(suggestItemInfo.getSingleTextEdit(), textModel);
              const valid = singleTextEditAugments(itemToPreselect, suggestItemTextEdit);
              return { index, valid, prefixLength: suggestItemTextEdit.text.length, suggestItem };
            }).filter((item) => item && item.valid && item.prefixLength > 0);
            const result = findFirstMax(candidates, compareBy((s) => s.prefixLength, numberComparator));
            return result ? result.index : -1;
          }
        }));
        let isBoundToSuggestWidget = false;
        const bindToSuggestWidget = () => {
          if (isBoundToSuggestWidget) {
            return;
          }
          isBoundToSuggestWidget = true;
          this._register(suggestController.widget.value.onDidShow(() => {
            this.isSuggestWidgetVisible = true;
            this.update(true);
          }));
          this._register(suggestController.widget.value.onDidHide(() => {
            this.isSuggestWidgetVisible = false;
            this.update(false);
          }));
          this._register(suggestController.widget.value.onDidFocus(() => {
            this.isSuggestWidgetVisible = true;
            this.update(true);
          }));
        };
        this._register(Event.once(suggestController.model.onDidTrigger)((e) => {
          bindToSuggestWidget();
        }));
        this._register(suggestController.onWillInsertSuggestItem((e) => {
          const position = this.editor.getPosition();
          const model = this.editor.getModel();
          if (!position || !model) {
            return void 0;
          }
          const suggestItemInfo = SuggestItemInfo.fromSuggestion(suggestController, model, position, e.item, this.isShiftKeyPressed);
          this.onWillAccept(suggestItemInfo);
        }));
      }
      this.update(this._isActive);
    }
    update(newActive) {
      const newInlineCompletion = this.getSuggestItemInfo();
      if (this._isActive !== newActive || !suggestItemInfoEquals(this._currentSuggestItemInfo, newInlineCompletion)) {
        this._isActive = newActive;
        this._currentSuggestItemInfo = newInlineCompletion;
        this._onDidSelectedItemChange.fire();
      }
    }
    getSuggestItemInfo() {
      const suggestController = SuggestController.get(this.editor);
      if (!suggestController || !this.isSuggestWidgetVisible) {
        return void 0;
      }
      const focusedItem = suggestController.widget.value.getFocusedItem();
      const position = this.editor.getPosition();
      const model = this.editor.getModel();
      if (!focusedItem || !position || !model) {
        return void 0;
      }
      return SuggestItemInfo.fromSuggestion(suggestController, model, position, focusedItem.item, this.isShiftKeyPressed);
    }
    stopForceRenderingAbove() {
      const suggestController = SuggestController.get(this.editor);
      suggestController?.stopForceRenderingAbove();
    }
    forceRenderingAbove() {
      const suggestController = SuggestController.get(this.editor);
      suggestController?.forceRenderingAbove();
    }
  }
  class SuggestItemInfo {
    static fromSuggestion(suggestController, model, position, item, toggleMode) {
      let { insertText } = item.completion;
      let isSnippetText = false;
      if (item.completion.insertTextRules & 4) {
        const snippet = new SnippetParser().parse(insertText);
        if (snippet.children.length < 100) {
          SnippetSession.adjustWhitespace(model, position, true, snippet);
        }
        insertText = snippet.toString();
        isSnippetText = true;
      }
      const info = suggestController.getOverwriteInfo(item, toggleMode);
      return new SuggestItemInfo(Range$2.fromPositions(position.delta(0, -info.overwriteBefore), position.delta(0, Math.max(info.overwriteAfter, 0))), insertText, item.completion.kind, isSnippetText, item.container.incomplete ?? false);
    }
    constructor(range2, insertText, completionItemKind, isSnippetText, listIncomplete) {
      this.range = range2;
      this.insertText = insertText;
      this.completionItemKind = completionItemKind;
      this.isSnippetText = isSnippetText;
      this.listIncomplete = listIncomplete;
    }
    equals(other) {
      return this.range.equalsRange(other.range) && this.insertText === other.insertText && this.completionItemKind === other.completionItemKind && this.isSnippetText === other.isSnippetText;
    }
    toSelectedSuggestionInfo() {
      return new SelectedSuggestionInfo(this.range, this.insertText, this.completionItemKind, this.isSnippetText);
    }
    getSingleTextEdit() {
      return new TextReplacement(this.range, this.insertText);
    }
  }
  function suggestItemInfoEquals(a, b) {
    if (a === b) {
      return true;
    }
    if (!a || !b) {
      return false;
    }
    return a.equals(b);
  }
  class ObservableSuggestWidgetAdapter extends Disposable {
    constructor(_editorObs, _handleSuggestAccepted, _suggestControllerPreselector) {
      super();
      this._editorObs = _editorObs;
      this._handleSuggestAccepted = _handleSuggestAccepted;
      this._suggestControllerPreselector = _suggestControllerPreselector;
      this._suggestWidgetAdaptor = this._register(new SuggestWidgetAdaptor(this._editorObs.editor, () => {
        this._editorObs.forceUpdate();
        return this._suggestControllerPreselector();
      }, (item) => this._editorObs.forceUpdate((_tx) => {
        this._handleSuggestAccepted(item);
      })));
      this.selectedItem = observableFromEvent(this, (cb) => this._suggestWidgetAdaptor.onDidSelectedItemChange(() => {
        this._editorObs.forceUpdate((_tx) => cb(void 0));
      }), () => this._suggestWidgetAdaptor.selectedItem);
    }
    stopForceRenderingAbove() {
      this._suggestWidgetAdaptor.stopForceRenderingAbove();
    }
    forceRenderingAbove() {
      this._suggestWidgetAdaptor.forceRenderingAbove();
    }
  }
  class RangeSingleLine {
    constructor(lineNumber, columnRange) {
      this.lineNumber = lineNumber;
      this.columnRange = columnRange;
    }
  }
  class ColumnRange {
    constructor(startColumn, endColumnExclusive) {
      this.startColumn = startColumn;
      this.endColumnExclusive = endColumnExclusive;
      if (startColumn > endColumnExclusive) {
        throw new BugIndicatingError(`startColumn ${startColumn} cannot be after endColumnExclusive ${endColumnExclusive}`);
      }
    }
    toRange(lineNumber) {
      return new Range$2(lineNumber, this.startColumn, lineNumber, this.endColumnExclusive);
    }
    equals(other) {
      return this.startColumn === other.startColumn && this.endColumnExclusive === other.endColumnExclusive;
    }
    toZeroBasedOffsetRange() {
      return new OffsetRange(this.startColumn - 1, this.endColumnExclusive - 1);
    }
  }
  class TokenWithTextArray {
    static fromLineTokens(lineTokens) {
      const tokenInfo = [];
      for (let i2 = 0; i2 < lineTokens.getCount(); i2++) {
        tokenInfo.push(new TokenWithTextInfo(lineTokens.getTokenText(i2), lineTokens.getMetadata(i2)));
      }
      return TokenWithTextArray.create(tokenInfo);
    }
    static create(tokenInfo) {
      return new TokenWithTextArray(tokenInfo);
    }
    constructor(_tokenInfo) {
      this._tokenInfo = _tokenInfo;
    }
    toLineTokens(decoder) {
      return LineTokens.createFromTextAndMetadata(this.map((_r2, t) => ({ text: t.text, metadata: t.metadata })), decoder);
    }
    map(cb) {
      const result = [];
      let lengthSum = 0;
      for (const tokenInfo of this._tokenInfo) {
        const range2 = new OffsetRange(lengthSum, lengthSum + tokenInfo.text.length);
        result.push(cb(range2, tokenInfo));
        lengthSum += tokenInfo.text.length;
      }
      return result;
    }
    slice(range2) {
      const result = [];
      let lengthSum = 0;
      for (const tokenInfo of this._tokenInfo) {
        const tokenStart = lengthSum;
        const tokenEndEx = tokenStart + tokenInfo.text.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 TokenWithTextInfo(tokenInfo.text.slice(deltaBefore, tokenInfo.text.length - deltaAfter), tokenInfo.metadata));
        }
        lengthSum += tokenInfo.text.length;
      }
      return TokenWithTextArray.create(result);
    }
    append(other) {
      const result = this._tokenInfo.concat(other._tokenInfo);
      return TokenWithTextArray.create(result);
    }
  }
  class TokenWithTextInfo {
    constructor(text2, metadata) {
      this.text = text2;
      this.metadata = metadata;
    }
  }
  var __decorate$1k = 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$1j = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  const GHOST_TEXT_CLASS_NAME = "ghost-text";
  let GhostTextView = (_ha = class extends Disposable {
    constructor(_editor, _model, _options, _shouldKeepCursorStable, _isClickable, _languageService) {
      super();
      this._editor = _editor;
      this._model = _model;
      this._options = _options;
      this._shouldKeepCursorStable = _shouldKeepCursorStable;
      this._isClickable = _isClickable;
      this._languageService = _languageService;
      this._isDisposed = observableValue(this, false);
      this._editorObs = observableCodeEditor(this._editor);
      this._warningState = derived((reader) => {
        const gt = this._model.ghostText.read(reader);
        if (!gt) {
          return void 0;
        }
        const warning = this._model.warning.read(reader);
        if (!warning) {
          return void 0;
        }
        return { lineNumber: gt.lineNumber, position: new Position$1(gt.lineNumber, gt.parts[0].column), icon: warning.icon };
      });
      this._onDidClick = this._register(new Emitter$1());
      this.onDidClick = this._onDidClick.event;
      this._useSyntaxHighlighting = this._options.map((o) => o.syntaxHighlightingEnabled);
      this._extraClassNames = derived(this, (reader) => {
        const extraClasses = [...this._options.read(reader).extraClasses ?? []];
        if (this._useSyntaxHighlighting.read(reader)) {
          extraClasses.push("syntax-highlighted");
        }
        if (this._warningState.read(reader)) {
          extraClasses.push("warning");
        }
        const extraClassNames = extraClasses.map((c) => ` ${c}`).join("");
        return extraClassNames;
      });
      this.uiState = derived(this, (reader) => {
        if (this._isDisposed.read(reader)) {
          return void 0;
        }
        const textModel = this._editorObs.model.read(reader);
        if (textModel !== this._model.targetTextModel.read(reader)) {
          return void 0;
        }
        const ghostText = this._model.ghostText.read(reader);
        if (!ghostText) {
          return void 0;
        }
        const replacedRange = ghostText instanceof GhostTextReplacement ? ghostText.columnRange : void 0;
        const syntaxHighlightingEnabled = this._useSyntaxHighlighting.read(reader);
        const extraClassNames = this._extraClassNames.read(reader);
        const { inlineTexts, additionalLines, hiddenRange, additionalLinesOriginalSuffix } = computeGhostTextViewData(ghostText, textModel, GHOST_TEXT_CLASS_NAME + extraClassNames);
        const currentLine = textModel.getLineContent(ghostText.lineNumber);
        const edit2 = new StringEdit(inlineTexts.map((t) => StringReplacement.insert(t.column - 1, t.text)));
        const tokens = syntaxHighlightingEnabled ? textModel.tokenization.tokenizeLinesAt(ghostText.lineNumber, [edit2.apply(currentLine), ...additionalLines.map((l) => l.content)]) : void 0;
        const newRanges = edit2.getNewRanges();
        const inlineTextsWithTokens = inlineTexts.map((t, idx) => ({ ...t, tokens: tokens?.[0]?.getTokensInRange(newRanges[idx]) }));
        const tokenizedAdditionalLines = additionalLines.map((l, idx) => {
          let content = tokens?.[idx + 1] ?? LineTokens.createEmpty(l.content, this._languageService.languageIdCodec);
          if (idx === additionalLines.length - 1 && additionalLinesOriginalSuffix) {
            const t = TokenWithTextArray.fromLineTokens(textModel.tokenization.getLineTokens(additionalLinesOriginalSuffix.lineNumber));
            const existingContent = t.slice(additionalLinesOriginalSuffix.columnRange.toZeroBasedOffsetRange());
            content = TokenWithTextArray.fromLineTokens(content).append(existingContent).toLineTokens(content.languageIdCodec);
          }
          return {
            content,
            decorations: l.decorations
          };
        });
        const cursorColumn = this._editor.getSelection()?.getStartPosition().column;
        const disjointInlineTexts = inlineTextsWithTokens.filter((inline2) => inline2.text !== "");
        const hasInsertionOnCurrentLine = disjointInlineTexts.length !== 0;
        const renderData = {
          cursorColumnDistance: (hasInsertionOnCurrentLine ? disjointInlineTexts[0].column : 1) - cursorColumn,
          cursorLineDistance: hasInsertionOnCurrentLine ? 0 : additionalLines.findIndex((line) => line.content !== "") + 1,
          lineCountOriginal: hasInsertionOnCurrentLine ? 1 : 0,
          lineCountModified: additionalLines.length + (hasInsertionOnCurrentLine ? 1 : 0),
          characterCountOriginal: 0,
          characterCountModified: sum(disjointInlineTexts.map((inline2) => inline2.text.length)) + sum(tokenizedAdditionalLines.map((line) => line.content.getTextLength())),
          disjointReplacements: disjointInlineTexts.length + (additionalLines.length > 0 ? 1 : 0),
          sameShapeReplacements: disjointInlineTexts.length > 1 && tokenizedAdditionalLines.length === 0 ? disjointInlineTexts.every((inline2) => inline2.text === disjointInlineTexts[0].text) : void 0
        };
        this._model.handleInlineCompletionShown.read(reader)?.(renderData);
        return {
          replacedRange,
          inlineTexts: inlineTextsWithTokens,
          additionalLines: tokenizedAdditionalLines,
          hiddenRange,
          lineNumber: ghostText.lineNumber,
          additionalReservedLineCount: this._model.minReservedLineCount.read(reader),
          targetTextModel: textModel,
          syntaxHighlightingEnabled
        };
      });
      this.decorations = derived(this, (reader) => {
        const uiState = this.uiState.read(reader);
        if (!uiState) {
          return [];
        }
        const decorations = [];
        const extraClassNames = this._extraClassNames.read(reader);
        if (uiState.replacedRange) {
          decorations.push({
            range: uiState.replacedRange.toRange(uiState.lineNumber),
            options: { inlineClassName: "inline-completion-text-to-replace" + extraClassNames, description: "GhostTextReplacement" }
          });
        }
        if (uiState.hiddenRange) {
          decorations.push({
            range: uiState.hiddenRange.toRange(uiState.lineNumber),
            options: { inlineClassName: "ghost-text-hidden", description: "ghost-text-hidden" }
          });
        }
        for (const p of uiState.inlineTexts) {
          decorations.push({
            range: Range$2.fromPositions(new Position$1(uiState.lineNumber, p.column)),
            options: {
              description: "ghost-text-decoration",
              after: {
                content: p.text,
                tokens: p.tokens,
                inlineClassName: (p.preview ? "ghost-text-decoration-preview" : "ghost-text-decoration") + (this._isClickable ? " clickable" : "") + extraClassNames + p.lineDecorations.map((d) => " " + d.className).join(" "),
                // TODO: take the ranges into account for line decorations
                cursorStops: InjectedTextCursorStops$1.Left,
                attachedData: new GhostTextAttachedData(this)
              },
              showIfCollapsed: true
            }
          });
        }
        return decorations;
      });
      this._additionalLinesWidget = this._register(new AdditionalLinesWidget(this._editor, derived((reader) => {
        const uiState = this.uiState.read(reader);
        return uiState ? {
          lineNumber: uiState.lineNumber,
          additionalLines: uiState.additionalLines,
          minReservedLineCount: uiState.additionalReservedLineCount,
          targetTextModel: uiState.targetTextModel
        } : void 0;
      }), this._shouldKeepCursorStable, this._isClickable));
      this._isInlineTextHovered = this._editorObs.isTargetHovered((p) => p.target.type === 6 && p.target.detail.injectedText?.options.attachedData instanceof GhostTextAttachedData && p.target.detail.injectedText.options.attachedData.owner === this, this._store);
      this.isHovered = derived(this, (reader) => {
        if (this._isDisposed.read(reader)) {
          return false;
        }
        return this._isInlineTextHovered.read(reader) || this._additionalLinesWidget.isHovered.read(reader);
      });
      this.height = derived(this, (reader) => {
        const lineHeight = this._editorObs.getOption(
          75
          /* EditorOption.lineHeight */
        ).read(reader);
        return lineHeight + (this._additionalLinesWidget.viewZoneHeight.read(reader) ?? 0);
      });
      this._register(toDisposable(() => {
        this._isDisposed.set(true, void 0);
      }));
      this._register(this._editorObs.setDecorations(this.decorations));
      if (this._isClickable) {
        this._register(this._additionalLinesWidget.onDidClick((e) => this._onDidClick.fire(e)));
        this._register(this._editor.onMouseUp((e) => {
          if (e.target.type !== 6) {
            return;
          }
          const a = e.target.detail.injectedText?.options.attachedData;
          if (a instanceof GhostTextAttachedData && a.owner === this) {
            this._onDidClick.fire(e.event);
          }
        }));
      }
      this._register(autorunWithStore((reader, store) => {
        {
          return;
        }
      }));
    }
    static getWarningWidgetContext(domNode) {
      const data = domNode.ghostTextViewWarningWidgetData;
      if (data) {
        return data;
      } else if (domNode.parentElement) {
        return this.getWarningWidgetContext(domNode.parentElement);
      }
      return void 0;
    }
    ownsViewZone(viewZoneId) {
      return this._additionalLinesWidget.viewZoneId === viewZoneId;
    }
  }, _ha.hot = createHotClass(_ha), _ha);
  GhostTextView = __decorate$1k([
    __param$1j(5, ILanguageService)
  ], GhostTextView);
  class GhostTextAttachedData {
    constructor(owner) {
      this.owner = owner;
    }
  }
  function computeGhostTextViewData(ghostText, textModel, ghostTextClassName) {
    const inlineTexts = [];
    const additionalLines = [];
    function addToAdditionalLines(ghLines, className2) {
      if (additionalLines.length > 0) {
        const lastLine = additionalLines[additionalLines.length - 1];
        if (className2) {
          lastLine.decorations.push(new LineDecoration(
            lastLine.content.length + 1,
            lastLine.content.length + 1 + ghLines[0].line.length,
            className2,
            0
            /* InlineDecorationType.Regular */
          ));
        }
        lastLine.content += ghLines[0].line;
        ghLines = ghLines.slice(1);
      }
      for (const ghLine of ghLines) {
        additionalLines.push({
          content: ghLine.line,
          decorations: className2 ? [new LineDecoration(
            1,
            ghLine.line.length + 1,
            className2,
            0
            /* InlineDecorationType.Regular */
          ), ...ghLine.lineDecorations] : [...ghLine.lineDecorations]
        });
      }
    }
    const textBufferLine = textModel.getLineContent(ghostText.lineNumber);
    let hiddenTextStartColumn = void 0;
    let lastIdx = 0;
    for (const part of ghostText.parts) {
      let ghLines = part.lines;
      if (hiddenTextStartColumn === void 0) {
        inlineTexts.push({ column: part.column, text: ghLines[0].line, preview: part.preview, lineDecorations: ghLines[0].lineDecorations });
        ghLines = ghLines.slice(1);
      } else {
        addToAdditionalLines([{ line: textBufferLine.substring(lastIdx, part.column - 1), lineDecorations: [] }], void 0);
      }
      if (ghLines.length > 0) {
        addToAdditionalLines(ghLines, ghostTextClassName);
        if (hiddenTextStartColumn === void 0 && part.column <= textBufferLine.length) {
          hiddenTextStartColumn = part.column;
        }
      }
      lastIdx = part.column - 1;
    }
    let additionalLinesOriginalSuffix = void 0;
    if (hiddenTextStartColumn !== void 0) {
      additionalLinesOriginalSuffix = new RangeSingleLine(ghostText.lineNumber, new ColumnRange(lastIdx + 1, textBufferLine.length + 1));
    }
    const hiddenRange = hiddenTextStartColumn !== void 0 ? new ColumnRange(hiddenTextStartColumn, textBufferLine.length + 1) : void 0;
    return {
      inlineTexts,
      additionalLines,
      hiddenRange,
      additionalLinesOriginalSuffix
    };
  }
  class AdditionalLinesWidget extends Disposable {
    get viewZoneId() {
      return this._viewZoneInfo?.viewZoneId;
    }
    get viewZoneHeight() {
      return this._viewZoneHeight;
    }
    constructor(_editor, _lines, _shouldKeepCursorStable, _isClickable) {
      super();
      this._editor = _editor;
      this._lines = _lines;
      this._shouldKeepCursorStable = _shouldKeepCursorStable;
      this._isClickable = _isClickable;
      this._viewZoneHeight = observableValue("viewZoneHeight", void 0);
      this.editorOptionsChanged = observableSignalFromEvent("editorOptionChanged", Event.filter(this._editor.onDidChangeConfiguration, (e) => e.hasChanged(
        40
        /* EditorOption.disableMonospaceOptimizations */
      ) || e.hasChanged(
        133
        /* EditorOption.stopRenderingLineAfter */
      ) || e.hasChanged(
        113
        /* EditorOption.renderWhitespace */
      ) || e.hasChanged(
        108
        /* EditorOption.renderControlCharacters */
      ) || e.hasChanged(
        60
        /* EditorOption.fontLigatures */
      ) || e.hasChanged(
        59
        /* EditorOption.fontInfo */
      ) || e.hasChanged(
        75
        /* EditorOption.lineHeight */
      )));
      this._onDidClick = this._register(new Emitter$1());
      this.onDidClick = this._onDidClick.event;
      this._viewZoneListener = this._register(new MutableDisposable());
      this.isHovered = observableCodeEditor(this._editor).isTargetHovered((p) => isTargetGhostText(p.target.element), this._store);
      this.hasBeenAccepted = false;
      if (this._editor instanceof CodeEditorWidget && this._shouldKeepCursorStable) {
        this._register(this._editor.onBeforeExecuteEdit((e) => this.hasBeenAccepted = e.source === "inlineSuggestion.accept"));
      }
      this._register(autorun((reader) => {
        const lines = this._lines.read(reader);
        this.editorOptionsChanged.read(reader);
        if (lines) {
          this.hasBeenAccepted = false;
          this.updateLines(lines.lineNumber, lines.additionalLines, lines.minReservedLineCount);
        } else {
          this.clear();
        }
      }));
    }
    dispose() {
      super.dispose();
      this.clear();
    }
    clear() {
      this._viewZoneListener.clear();
      this._editor.changeViewZones((changeAccessor) => {
        this.removeActiveViewZone(changeAccessor);
      });
    }
    updateLines(lineNumber, additionalLines, minReservedLineCount) {
      const textModel = this._editor.getModel();
      if (!textModel) {
        return;
      }
      const { tabSize } = textModel.getOptions();
      this._editor.changeViewZones((changeAccessor) => {
        const store = new DisposableStore();
        this.removeActiveViewZone(changeAccessor);
        const heightInLines = Math.max(additionalLines.length, minReservedLineCount);
        if (heightInLines > 0) {
          const domNode = document.createElement("div");
          renderLines(domNode, tabSize, additionalLines, this._editor.getOptions(), this._isClickable);
          if (this._isClickable) {
            store.add(addDisposableListener(domNode, "mousedown", (e) => {
              e.preventDefault();
            }));
            store.add(addDisposableListener(domNode, "click", (e) => {
              if (isTargetGhostText(e.target)) {
                this._onDidClick.fire(new StandardMouseEvent(getWindow(e), e));
              }
            }));
          }
          this.addViewZone(changeAccessor, lineNumber, heightInLines, domNode);
        }
        this._viewZoneListener.value = store;
      });
    }
    addViewZone(changeAccessor, afterLineNumber, heightInLines, domNode) {
      const id = changeAccessor.addZone({
        afterLineNumber,
        heightInLines,
        domNode,
        afterColumnAffinity: 1,
        onComputedHeight: (height) => {
          this._viewZoneHeight.set(height, void 0);
        }
      });
      this.keepCursorStable(afterLineNumber, heightInLines);
      this._viewZoneInfo = { viewZoneId: id, heightInLines, lineNumber: afterLineNumber };
    }
    removeActiveViewZone(changeAccessor) {
      if (this._viewZoneInfo) {
        changeAccessor.removeZone(this._viewZoneInfo.viewZoneId);
        if (!this.hasBeenAccepted) {
          this.keepCursorStable(this._viewZoneInfo.lineNumber, -this._viewZoneInfo.heightInLines);
        }
        this._viewZoneInfo = void 0;
        this._viewZoneHeight.set(void 0, void 0);
      }
    }
    keepCursorStable(lineNumber, heightInLines) {
      if (!this._shouldKeepCursorStable) {
        return;
      }
      const cursorLineNumber = this._editor.getSelection()?.getStartPosition()?.lineNumber;
      if (cursorLineNumber !== void 0 && lineNumber < cursorLineNumber) {
        this._editor.setScrollTop(this._editor.getScrollTop() + heightInLines * this._editor.getOption(
          75
          /* EditorOption.lineHeight */
        ));
      }
    }
  }
  function isTargetGhostText(target) {
    return isHTMLElement(target) && target.classList.contains(GHOST_TEXT_CLASS_NAME);
  }
  function renderLines(domNode, tabSize, lines, opts, isClickable) {
    const disableMonospaceOptimizations = opts.get(
      40
      /* EditorOption.disableMonospaceOptimizations */
    );
    const stopRenderingLineAfter = opts.get(
      133
      /* EditorOption.stopRenderingLineAfter */
    );
    const renderWhitespace = "none";
    const renderControlCharacters = opts.get(
      108
      /* EditorOption.renderControlCharacters */
    );
    const fontLigatures = opts.get(
      60
      /* EditorOption.fontLigatures */
    );
    const fontInfo = opts.get(
      59
      /* EditorOption.fontInfo */
    );
    const lineHeight = opts.get(
      75
      /* EditorOption.lineHeight */
    );
    let classNames2 = "suggest-preview-text";
    if (isClickable) {
      classNames2 += " clickable";
    }
    const sb = new StringBuilder(1e4);
    sb.appendString(`<div class="${classNames2}">`);
    for (let i2 = 0, len = lines.length; i2 < len; i2++) {
      const lineData = lines[i2];
      const lineTokens = lineData.content;
      sb.appendString('<div class="view-line');
      sb.appendString('" style="top:');
      sb.appendString(String(i2 * lineHeight));
      sb.appendString('px;width:1000000px;">');
      const line = lineTokens.getLineContent();
      const isBasicASCII$1 = isBasicASCII(line);
      const containsRTL$1 = containsRTL(line);
      renderViewLine(new RenderLineInput(fontInfo.isMonospace && !disableMonospaceOptimizations, fontInfo.canUseHalfwidthRightwardsArrow, line, false, isBasicASCII$1, containsRTL$1, 0, lineTokens, lineData.decorations, tabSize, 0, fontInfo.spaceWidth, fontInfo.middotWidth, fontInfo.wsmiddotWidth, stopRenderingLineAfter, renderWhitespace, renderControlCharacters, fontLigatures !== EditorFontLigatures.OFF, null, null, 0), sb);
      sb.appendString("</div>");
    }
    sb.appendString("</div>");
    applyFontInfo(domNode, fontInfo);
    const html2 = sb.build();
    const trustedhtml = ttPolicy$2 ? ttPolicy$2.createHTML(html2) : html2;
    domNode.innerHTML = trustedhtml;
  }
  const ttPolicy$2 = createTrustedTypesPolicy("editorGhostText", { createHTML: (value) => value });
  const _LineEdit = class _LineEdit {
    constructor(replacements) {
      this.replacements = replacements;
      assert(checkAdjacentItems(replacements, (i1, i2) => i1.lineRange.endLineNumberExclusive <= i2.lineRange.startLineNumber));
    }
    toString() {
      return this.replacements.map((e) => e.toString()).join(",");
    }
    getNewLineRanges() {
      const ranges = [];
      let offset = 0;
      for (const e of this.replacements) {
        ranges.push(LineRange.ofLength(e.lineRange.startLineNumber + offset, e.newLines.length));
        offset += e.newLines.length - e.lineRange.length;
      }
      return ranges;
    }
  };
  _LineEdit.empty = new _LineEdit([]);
  let LineEdit = _LineEdit;
  class LineReplacement {
    static fromSingleTextEdit(edit2, initialValue) {
      const newLines = splitLines(edit2.text);
      let startLineNumber = edit2.range.startLineNumber;
      const survivingFirstLineText = initialValue.getValueOfRange(Range$2.fromPositions(new Position$1(edit2.range.startLineNumber, 1), edit2.range.getStartPosition()));
      newLines[0] = survivingFirstLineText + newLines[0];
      let endLineNumberEx = edit2.range.endLineNumber + 1;
      const editEndLineNumberMaxColumn = initialValue.getTransformer().getLineLength(edit2.range.endLineNumber) + 1;
      const survivingEndLineText = initialValue.getValueOfRange(Range$2.fromPositions(edit2.range.getEndPosition(), new Position$1(edit2.range.endLineNumber, editEndLineNumberMaxColumn)));
      newLines[newLines.length - 1] = newLines[newLines.length - 1] + survivingEndLineText;
      const startBeforeNewLine = edit2.range.startColumn === initialValue.getTransformer().getLineLength(edit2.range.startLineNumber) + 1;
      const endAfterNewLine = edit2.range.endColumn === 1;
      if (startBeforeNewLine && newLines[0].length === survivingFirstLineText.length) {
        startLineNumber++;
        newLines.shift();
      }
      if (newLines.length > 0 && startLineNumber < endLineNumberEx && endAfterNewLine && newLines[newLines.length - 1].length === survivingEndLineText.length) {
        endLineNumberEx--;
        newLines.pop();
      }
      return new LineReplacement(new LineRange(startLineNumber, endLineNumberEx), newLines);
    }
    constructor(lineRange, newLines) {
      this.lineRange = lineRange;
      this.newLines = newLines;
    }
    toString() {
      return `${this.lineRange}->${JSON.stringify(this.newLines)}`;
    }
    toLineEdit() {
      return new LineEdit([this]);
    }
  }
  class InlineEditWithChanges {
    get lineEdit() {
      if (this.edit.replacements.length === 0) {
        return new LineReplacement(new LineRange(1, 1), []);
      }
      return LineReplacement.fromSingleTextEdit(this.edit.toReplacement(this.originalText), this.originalText);
    }
    get originalLineRange() {
      return this.lineEdit.lineRange;
    }
    get modifiedLineRange() {
      return this.lineEdit.toLineEdit().getNewLineRanges()[0];
    }
    get displayRange() {
      return this.originalText.lineRange.intersect(this.originalLineRange.join(LineRange.ofLength(this.originalLineRange.startLineNumber, this.lineEdit.newLines.length)));
    }
    constructor(originalText, edit2, cursorPosition, multiCursorPositions, commands, inlineCompletion) {
      this.originalText = originalText;
      this.edit = edit2;
      this.cursorPosition = cursorPosition;
      this.multiCursorPositions = multiCursorPositions;
      this.commands = commands;
      this.inlineCompletion = inlineCompletion;
    }
  }
  class InlineEditModel {
    constructor(_model, inlineEdit, tabAction) {
      this._model = _model;
      this.inlineEdit = inlineEdit;
      this.tabAction = tabAction;
      this.action = this.inlineEdit.inlineCompletion.action;
      this.displayName = this.inlineEdit.inlineCompletion.source.provider.displayName ?? localize(1219, "Inline Edit");
      this.extensionCommands = this.inlineEdit.inlineCompletion.source.inlineSuggestions.commands ?? [];
      this.isInDiffEditor = this._model.isInDiffEditor;
      this.displayLocation = this.inlineEdit.inlineCompletion.hint;
      this.showCollapsed = this._model.showCollapsed;
    }
    accept() {
      this._model.accept();
    }
    jump() {
      this._model.jump();
    }
    handleInlineEditShown(viewKind, viewData) {
      this._model.handleInlineSuggestionShown(this.inlineEdit.inlineCompletion, viewKind, viewData);
    }
  }
  class InlineEditHost {
    constructor(_model) {
      this._model = _model;
      this.onDidAccept = this._model.onDidAccept;
      this.inAcceptFlow = this._model.inAcceptFlow;
    }
  }
  class GhostTextIndicator {
    constructor(editor2, model, lineRange, inlineCompletion) {
      this.lineRange = lineRange;
      const editorObs = observableCodeEditor(editor2);
      const tabAction = derived(this, (reader) => {
        if (editorObs.isFocused.read(reader)) {
          if (inlineCompletion.showInlineEditMenu) {
            return InlineEditTabAction.Accept;
          }
        }
        return InlineEditTabAction.Inactive;
      });
      this.model = new InlineEditModel(model, new InlineEditWithChanges(new StringText(""), new TextEdit([inlineCompletion.getSingleTextEdit()]), model.primaryPosition.get(), model.allPositions.get(), inlineCompletion.source.inlineSuggestions.commands ?? [], inlineCompletion), tabAction);
    }
  }
  class Rect {
    static fromPoints(topLeft, bottomRight) {
      return new Rect(topLeft.x, topLeft.y, bottomRight.x, bottomRight.y);
    }
    static fromPointSize(point, size2) {
      return new Rect(point.x, point.y, point.x + size2.x, point.y + size2.y);
    }
    static fromLeftTopRightBottom(left, top, right, bottom) {
      return new Rect(left, top, right, bottom);
    }
    static fromLeftTopWidthHeight(left, top, width2, height) {
      return new Rect(left, top, left + width2, top + height);
    }
    static fromRanges(leftRight, topBottom) {
      return new Rect(leftRight.start, topBottom.start, leftRight.endExclusive, topBottom.endExclusive);
    }
    static hull(rects) {
      let left = Number.MAX_SAFE_INTEGER;
      let top = Number.MAX_SAFE_INTEGER;
      let right = Number.MIN_SAFE_INTEGER;
      let bottom = Number.MIN_SAFE_INTEGER;
      for (const rect of rects) {
        left = Math.min(left, rect.left);
        top = Math.min(top, rect.top);
        right = Math.max(right, rect.right);
        bottom = Math.max(bottom, rect.bottom);
      }
      return new Rect(left, top, right, bottom);
    }
    get width() {
      return this.right - this.left;
    }
    get height() {
      return this.bottom - this.top;
    }
    constructor(left, top, right, bottom) {
      this.left = left;
      this.top = top;
      this.right = right;
      this.bottom = bottom;
      if (left > right) {
        throw new BugIndicatingError("Invalid arguments: Horizontally offset by " + (left - right));
      }
      if (top > bottom) {
        throw new BugIndicatingError("Invalid arguments: Vertically offset by " + (top - bottom));
      }
    }
    withMargin(marginOrVerticalOrTop, rightOrHorizontal, bottom, left) {
      let marginLeft, marginRight, marginTop, marginBottom;
      if (rightOrHorizontal === void 0 && bottom === void 0 && left === void 0) {
        marginLeft = marginRight = marginTop = marginBottom = marginOrVerticalOrTop;
      } else if (bottom === void 0 && left === void 0) {
        marginLeft = marginRight = rightOrHorizontal;
        marginTop = marginBottom = marginOrVerticalOrTop;
      } else {
        marginLeft = left;
        marginRight = rightOrHorizontal;
        marginTop = marginOrVerticalOrTop;
        marginBottom = bottom;
      }
      return new Rect(this.left - marginLeft, this.top - marginTop, this.right + marginRight, this.bottom + marginBottom);
    }
    intersectVertical(range2) {
      const newTop = Math.max(this.top, range2.start);
      const newBottom = Math.min(this.bottom, range2.endExclusive);
      return new Rect(this.left, newTop, this.right, Math.max(newTop, newBottom));
    }
    intersectHorizontal(range2) {
      const newLeft = Math.max(this.left, range2.start);
      const newRight = Math.min(this.right, range2.endExclusive);
      return new Rect(newLeft, this.top, Math.max(newLeft, newRight), this.bottom);
    }
    toString() {
      return `Rect{(${this.left},${this.top}), (${this.right},${this.bottom})}`;
    }
    intersect(parent) {
      const left = Math.max(this.left, parent.left);
      const right = Math.min(this.right, parent.right);
      const top = Math.max(this.top, parent.top);
      const bottom = Math.min(this.bottom, parent.bottom);
      if (left > right || top > bottom) {
        return void 0;
      }
      return new Rect(left, top, right, bottom);
    }
    containsRect(other) {
      return this.left <= other.left && this.top <= other.top && this.right >= other.right && this.bottom >= other.bottom;
    }
    containsPoint(point) {
      return this.left <= point.x && this.top <= point.y && this.right >= point.x && this.bottom >= point.y;
    }
    moveToBeContainedIn(parent) {
      const width2 = this.width;
      const height = this.height;
      let left = this.left;
      let top = this.top;
      if (left < parent.left) {
        left = parent.left;
      } else if (left + width2 > parent.right) {
        left = parent.right - width2;
      }
      if (top < parent.top) {
        top = parent.top;
      } else if (top + height > parent.bottom) {
        top = parent.bottom - height;
      }
      return new Rect(left, top, left + width2, top + height);
    }
    withWidth(width2) {
      return new Rect(this.left, this.top, this.left + width2, this.bottom);
    }
    withHeight(height) {
      return new Rect(this.left, this.top, this.right, this.top + height);
    }
    withTop(top) {
      return new Rect(this.left, top, this.right, this.bottom);
    }
    withLeft(left) {
      return new Rect(left, this.top, this.right, this.bottom);
    }
    translateX(delta) {
      return new Rect(this.left + delta, this.top, this.right + delta, this.bottom);
    }
    translateY(delta) {
      return new Rect(this.left, this.top + delta, this.right, this.bottom + delta);
    }
    getLeftBottom() {
      return new Point(this.left, this.bottom);
    }
    getRightBottom() {
      return new Point(this.right, this.bottom);
    }
    getRightTop() {
      return new Point(this.right, this.top);
    }
    toStyles() {
      return {
        position: "absolute",
        left: `${this.left}px`,
        top: `${this.top}px`,
        width: `${this.width}px`,
        height: `${this.height}px`
      };
    }
  }
  class StickyScrollWidgetState {
    constructor(startLineNumbers, endLineNumbers, lastLineRelativePosition, showEndForLine = null) {
      this.startLineNumbers = startLineNumbers;
      this.endLineNumbers = endLineNumbers;
      this.lastLineRelativePosition = lastLineRelativePosition;
      this.showEndForLine = showEndForLine;
    }
    equals(other) {
      return !!other && this.lastLineRelativePosition === other.lastLineRelativePosition && this.showEndForLine === other.showEndForLine && equals$1(this.startLineNumbers, other.startLineNumbers) && equals$1(this.endLineNumbers, other.endLineNumbers);
    }
    static get Empty() {
      return new StickyScrollWidgetState([], [], 0);
    }
  }
  const _ttPolicy = createTrustedTypesPolicy("stickyScrollViewLayer", { createHTML: (value) => value });
  const STICKY_INDEX_ATTR = "data-sticky-line-index";
  const STICKY_IS_LINE_ATTR = "data-sticky-is-line";
  const STICKY_IS_LINE_NUMBER_ATTR = "data-sticky-is-line-number";
  const STICKY_IS_FOLDING_ICON_ATTR = "data-sticky-is-folding-icon";
  class StickyScrollWidget extends Disposable {
    get height() {
      return this._height;
    }
    constructor(editor2) {
      super();
      this._foldingIconStore = this._register(new DisposableStore());
      this._rootDomNode = document.createElement("div");
      this._lineNumbersDomNode = document.createElement("div");
      this._linesDomNodeScrollable = document.createElement("div");
      this._linesDomNode = document.createElement("div");
      this._renderedStickyLines = [];
      this._lineNumbers = [];
      this._lastLineRelativePosition = 0;
      this._minContentWidthInPx = 0;
      this._isOnGlyphMargin = false;
      this._height = -1;
      this._onDidChangeStickyScrollHeight = this._register(new Emitter$1());
      this.onDidChangeStickyScrollHeight = this._onDidChangeStickyScrollHeight.event;
      this._editor = editor2;
      this._lineHeight = editor2.getOption(
        75
        /* EditorOption.lineHeight */
      );
      this._lineNumbersDomNode.className = "sticky-widget-line-numbers";
      this._lineNumbersDomNode.setAttribute("role", "none");
      this._linesDomNode.className = "sticky-widget-lines";
      this._linesDomNode.setAttribute("role", "list");
      this._linesDomNodeScrollable.className = "sticky-widget-lines-scrollable";
      this._linesDomNodeScrollable.appendChild(this._linesDomNode);
      this._rootDomNode.className = "sticky-widget";
      this._rootDomNode.classList.toggle("peek", editor2 instanceof EmbeddedCodeEditorWidget);
      this._rootDomNode.appendChild(this._lineNumbersDomNode);
      this._rootDomNode.appendChild(this._linesDomNodeScrollable);
      this._setHeight(0);
      const updateScrollLeftPosition = () => {
        this._linesDomNode.style.left = this._editor.getOption(
          131
          /* EditorOption.stickyScroll */
        ).scrollWithEditor ? `-${this._editor.getScrollLeft()}px` : "0px";
      };
      this._register(this._editor.onDidChangeConfiguration((e) => {
        if (e.hasChanged(
          131
          /* EditorOption.stickyScroll */
        )) {
          updateScrollLeftPosition();
        }
        if (e.hasChanged(
          75
          /* EditorOption.lineHeight */
        )) {
          this._lineHeight = this._editor.getOption(
            75
            /* EditorOption.lineHeight */
          );
        }
      }));
      this._register(this._editor.onDidScrollChange((e) => {
        if (e.scrollLeftChanged) {
          updateScrollLeftPosition();
        }
        if (e.scrollWidthChanged) {
          this._updateWidgetWidth();
        }
      }));
      this._register(this._editor.onDidChangeModel(() => {
        updateScrollLeftPosition();
        this._updateWidgetWidth();
      }));
      updateScrollLeftPosition();
      this._register(this._editor.onDidLayoutChange((e) => {
        this._updateWidgetWidth();
      }));
      this._updateWidgetWidth();
    }
    get lineNumbers() {
      return this._lineNumbers;
    }
    get lineNumberCount() {
      return this._lineNumbers.length;
    }
    getRenderedStickyLine(lineNumber) {
      return this._renderedStickyLines.find((stickyLine) => stickyLine.lineNumber === lineNumber);
    }
    getCurrentLines() {
      return this._lineNumbers;
    }
    setState(state, foldingModel, rebuildFromIndexCandidate) {
      const currentStateAndPreviousStateUndefined = !this._state && !state;
      const currentStateDefinedAndEqualsPreviousState = this._state && this._state.equals(state);
      if (rebuildFromIndexCandidate === void 0 && (currentStateAndPreviousStateUndefined || currentStateDefinedAndEqualsPreviousState)) {
        return;
      }
      const data = this._findRenderingData(state);
      const previousLineNumbers = this._lineNumbers;
      this._lineNumbers = data.lineNumbers;
      this._lastLineRelativePosition = data.lastLineRelativePosition;
      const rebuildFromIndex = this._findIndexToRebuildFrom(previousLineNumbers, this._lineNumbers, rebuildFromIndexCandidate);
      this._renderRootNode(this._lineNumbers, this._lastLineRelativePosition, foldingModel, rebuildFromIndex);
      this._state = state;
    }
    _findRenderingData(state) {
      if (!state) {
        return { lineNumbers: [], lastLineRelativePosition: 0 };
      }
      const candidateLineNumbers = [...state.startLineNumbers];
      if (state.showEndForLine !== null) {
        candidateLineNumbers[state.showEndForLine] = state.endLineNumbers[state.showEndForLine];
      }
      let totalHeight = 0;
      for (let i2 = 0; i2 < candidateLineNumbers.length; i2++) {
        totalHeight += this._editor.getLineHeightForPosition(new Position$1(candidateLineNumbers[i2], 1));
      }
      if (totalHeight === 0) {
        return { lineNumbers: [], lastLineRelativePosition: 0 };
      }
      return { lineNumbers: candidateLineNumbers, lastLineRelativePosition: state.lastLineRelativePosition };
    }
    _findIndexToRebuildFrom(previousLineNumbers, newLineNumbers, rebuildFromIndexCandidate) {
      if (newLineNumbers.length === 0) {
        return 0;
      }
      if (rebuildFromIndexCandidate !== void 0) {
        return rebuildFromIndexCandidate;
      }
      const validIndex = newLineNumbers.findIndex((startLineNumber) => !previousLineNumbers.includes(startLineNumber));
      return validIndex === -1 ? 0 : validIndex;
    }
    _updateWidgetWidth() {
      const layoutInfo = this._editor.getLayoutInfo();
      const lineNumbersWidth = layoutInfo.contentLeft;
      this._lineNumbersDomNode.style.width = `${lineNumbersWidth}px`;
      this._linesDomNodeScrollable.style.setProperty("--vscode-editorStickyScroll-scrollableWidth", `${this._editor.getScrollWidth() - layoutInfo.verticalScrollbarWidth}px`);
      this._rootDomNode.style.width = `${layoutInfo.width - layoutInfo.verticalScrollbarWidth}px`;
    }
    _useFoldingOpacityTransition(requireTransitions) {
      this._lineNumbersDomNode.style.setProperty("--vscode-editorStickyScroll-foldingOpacityTransition", `opacity ${requireTransitions ? 0.5 : 0}s`);
    }
    _setFoldingIconsVisibility(allVisible) {
      for (const line of this._renderedStickyLines) {
        const foldingIcon = line.foldingIcon;
        if (!foldingIcon) {
          continue;
        }
        foldingIcon.setVisible(allVisible ? true : foldingIcon.isCollapsed);
      }
    }
    async _renderRootNode(lineNumbers, lastLineRelativePosition, foldingModel, rebuildFromIndex) {
      const viewModel = this._editor._getViewModel();
      if (!viewModel) {
        this._clearWidget();
        return;
      }
      if (lineNumbers.length === 0) {
        this._clearWidget();
        return;
      }
      const renderedStickyLines = [];
      const lastLineNumber = lineNumbers[lineNumbers.length - 1];
      let top = 0;
      for (let i2 = 0; i2 < this._renderedStickyLines.length; i2++) {
        if (i2 < rebuildFromIndex) {
          const renderedLine = this._renderedStickyLines[i2];
          renderedStickyLines.push(this._updatePosition(renderedLine, top, renderedLine.lineNumber === lastLineNumber));
          top += renderedLine.height;
        } else {
          const renderedLine = this._renderedStickyLines[i2];
          renderedLine.lineNumberDomNode.remove();
          renderedLine.lineDomNode.remove();
        }
      }
      const layoutInfo = this._editor.getLayoutInfo();
      for (let i2 = rebuildFromIndex; i2 < lineNumbers.length; i2++) {
        const stickyLine = this._renderChildNode(viewModel, i2, lineNumbers[i2], top, lastLineNumber === lineNumbers[i2], foldingModel, layoutInfo);
        top += stickyLine.height;
        this._linesDomNode.appendChild(stickyLine.lineDomNode);
        this._lineNumbersDomNode.appendChild(stickyLine.lineNumberDomNode);
        renderedStickyLines.push(stickyLine);
      }
      if (foldingModel) {
        this._setFoldingHoverListeners();
        this._useFoldingOpacityTransition(!this._isOnGlyphMargin);
      }
      this._minContentWidthInPx = Math.max(...this._renderedStickyLines.map((l) => l.scrollWidth)) + layoutInfo.verticalScrollbarWidth;
      this._renderedStickyLines = renderedStickyLines;
      this._setHeight(top + lastLineRelativePosition);
      this._editor.layoutOverlayWidget(this);
    }
    _clearWidget() {
      for (let i2 = 0; i2 < this._renderedStickyLines.length; i2++) {
        const stickyLine = this._renderedStickyLines[i2];
        stickyLine.lineNumberDomNode.remove();
        stickyLine.lineDomNode.remove();
      }
      this._setHeight(0);
    }
    _setHeight(height) {
      if (this._height === height) {
        return;
      }
      this._height = height;
      if (this._height === 0) {
        this._rootDomNode.style.display = "none";
      } else {
        this._rootDomNode.style.display = "block";
        this._lineNumbersDomNode.style.height = `${this._height}px`;
        this._linesDomNodeScrollable.style.height = `${this._height}px`;
        this._rootDomNode.style.height = `${this._height}px`;
      }
      this._onDidChangeStickyScrollHeight.fire({ height: this._height });
    }
    _setFoldingHoverListeners() {
      const showFoldingControls = this._editor.getOption(
        126
        /* EditorOption.showFoldingControls */
      );
      if (showFoldingControls !== "mouseover") {
        return;
      }
      this._foldingIconStore.clear();
      this._foldingIconStore.add(addDisposableListener(this._lineNumbersDomNode, EventType$1.MOUSE_ENTER, () => {
        this._isOnGlyphMargin = true;
        this._setFoldingIconsVisibility(true);
      }));
      this._foldingIconStore.add(addDisposableListener(this._lineNumbersDomNode, EventType$1.MOUSE_LEAVE, () => {
        this._isOnGlyphMargin = false;
        this._useFoldingOpacityTransition(true);
        this._setFoldingIconsVisibility(false);
      }));
    }
    _renderChildNode(viewModel, index, line, top, isLastLine, foldingModel, layoutInfo) {
      const viewLineNumber = viewModel.coordinatesConverter.convertModelPositionToViewPosition(new Position$1(line, 1)).lineNumber;
      const lineRenderingData = viewModel.getViewLineRenderingData(viewLineNumber);
      const lineNumberOption = this._editor.getOption(
        76
        /* EditorOption.lineNumbers */
      );
      const verticalScrollbarSize = this._editor.getOption(
        117
        /* EditorOption.scrollbar */
      ).verticalScrollbarSize;
      let actualInlineDecorations;
      try {
        actualInlineDecorations = LineDecoration.filter(lineRenderingData.inlineDecorations, viewLineNumber, lineRenderingData.minColumn, lineRenderingData.maxColumn);
      } catch (err) {
        actualInlineDecorations = [];
      }
      const lineHeight = this._editor.getLineHeightForPosition(new Position$1(line, 1));
      const textDirection = viewModel.getTextDirection(line);
      const renderLineInput = new RenderLineInput(true, true, lineRenderingData.content, lineRenderingData.continuesWithWrappedLine, lineRenderingData.isBasicASCII, lineRenderingData.containsRTL, 0, lineRenderingData.tokens, actualInlineDecorations, lineRenderingData.tabSize, lineRenderingData.startVisibleColumn, 1, 1, 1, 500, "none", true, true, null, textDirection, verticalScrollbarSize);
      const sb = new StringBuilder(2e3);
      const renderOutput = renderViewLine(renderLineInput, sb);
      let newLine;
      if (_ttPolicy) {
        newLine = _ttPolicy.createHTML(sb.build());
      } else {
        newLine = sb.build();
      }
      const lineHTMLNode = document.createElement("span");
      lineHTMLNode.setAttribute(STICKY_INDEX_ATTR, String(index));
      lineHTMLNode.setAttribute(STICKY_IS_LINE_ATTR, "");
      lineHTMLNode.setAttribute("role", "listitem");
      lineHTMLNode.tabIndex = 0;
      lineHTMLNode.className = "sticky-line-content";
      lineHTMLNode.classList.add(`stickyLine${line}`);
      lineHTMLNode.style.lineHeight = `${lineHeight}px`;
      lineHTMLNode.innerHTML = newLine;
      const lineNumberHTMLNode = document.createElement("span");
      lineNumberHTMLNode.setAttribute(STICKY_INDEX_ATTR, String(index));
      lineNumberHTMLNode.setAttribute(STICKY_IS_LINE_NUMBER_ATTR, "");
      lineNumberHTMLNode.className = "sticky-line-number";
      lineNumberHTMLNode.style.lineHeight = `${lineHeight}px`;
      const lineNumbersWidth = layoutInfo.contentLeft;
      lineNumberHTMLNode.style.width = `${lineNumbersWidth}px`;
      const innerLineNumberHTML = document.createElement("span");
      if (lineNumberOption.renderType === 1 || lineNumberOption.renderType === 3 && line % 10 === 0) {
        innerLineNumberHTML.innerText = line.toString();
      } else if (lineNumberOption.renderType === 2) {
        innerLineNumberHTML.innerText = Math.abs(line - this._editor.getPosition().lineNumber).toString();
      }
      innerLineNumberHTML.className = "sticky-line-number-inner";
      innerLineNumberHTML.style.width = `${layoutInfo.lineNumbersWidth}px`;
      innerLineNumberHTML.style.paddingLeft = `${layoutInfo.lineNumbersLeft}px`;
      lineNumberHTMLNode.appendChild(innerLineNumberHTML);
      const foldingIcon = this._renderFoldingIconForLine(foldingModel, line);
      if (foldingIcon) {
        lineNumberHTMLNode.appendChild(foldingIcon.domNode);
        foldingIcon.domNode.style.left = `${layoutInfo.lineNumbersWidth + layoutInfo.lineNumbersLeft}px`;
        foldingIcon.domNode.style.lineHeight = `${lineHeight}px`;
      }
      this._editor.applyFontInfo(lineHTMLNode);
      this._editor.applyFontInfo(lineNumberHTMLNode);
      lineNumberHTMLNode.style.lineHeight = `${lineHeight}px`;
      lineHTMLNode.style.lineHeight = `${lineHeight}px`;
      lineNumberHTMLNode.style.height = `${lineHeight}px`;
      lineHTMLNode.style.height = `${lineHeight}px`;
      const renderedLine = new RenderedStickyLine(index, line, lineHTMLNode, lineNumberHTMLNode, foldingIcon, renderOutput.characterMapping, lineHTMLNode.scrollWidth, lineHeight);
      return this._updatePosition(renderedLine, top, isLastLine);
    }
    _updatePosition(stickyLine, top, isLastLine) {
      const lineHTMLNode = stickyLine.lineDomNode;
      const lineNumberHTMLNode = stickyLine.lineNumberDomNode;
      if (isLastLine) {
        const zIndex = "0";
        lineHTMLNode.style.zIndex = zIndex;
        lineNumberHTMLNode.style.zIndex = zIndex;
        const updatedTop = `${top + this._lastLineRelativePosition + (stickyLine.foldingIcon?.isCollapsed ? 1 : 0)}px`;
        lineHTMLNode.style.top = updatedTop;
        lineNumberHTMLNode.style.top = updatedTop;
      } else {
        const zIndex = "1";
        lineHTMLNode.style.zIndex = zIndex;
        lineNumberHTMLNode.style.zIndex = zIndex;
        lineHTMLNode.style.top = `${top}px`;
        lineNumberHTMLNode.style.top = `${top}px`;
      }
      return stickyLine;
    }
    _renderFoldingIconForLine(foldingModel, line) {
      const showFoldingControls = this._editor.getOption(
        126
        /* EditorOption.showFoldingControls */
      );
      if (!foldingModel || showFoldingControls === "never") {
        return;
      }
      const foldingRegions = foldingModel.regions;
      const indexOfFoldingRegion = foldingRegions.findRange(line);
      const startLineNumber = foldingRegions.getStartLineNumber(indexOfFoldingRegion);
      const isFoldingScope = line === startLineNumber;
      if (!isFoldingScope) {
        return;
      }
      const isCollapsed = foldingRegions.isCollapsed(indexOfFoldingRegion);
      const foldingIcon = new StickyFoldingIcon(isCollapsed, startLineNumber, foldingRegions.getEndLineNumber(indexOfFoldingRegion), this._lineHeight);
      foldingIcon.setVisible(this._isOnGlyphMargin ? true : isCollapsed || showFoldingControls === "always");
      foldingIcon.domNode.setAttribute(STICKY_IS_FOLDING_ICON_ATTR, "");
      return foldingIcon;
    }
    getId() {
      return "editor.contrib.stickyScrollWidget";
    }
    getDomNode() {
      return this._rootDomNode;
    }
    getPosition() {
      return {
        preference: 2,
        stackOridinal: 10
      };
    }
    getMinContentWidthInPx() {
      return this._minContentWidthInPx;
    }
    focusLineWithIndex(index) {
      if (0 <= index && index < this._renderedStickyLines.length) {
        this._renderedStickyLines[index].lineDomNode.focus();
      }
    }
    /**
     * Given a leaf dom node, tries to find the editor position.
     */
    getEditorPositionFromNode(spanDomNode) {
      if (!spanDomNode || spanDomNode.children.length > 0) {
        return null;
      }
      const renderedStickyLine = this._getRenderedStickyLineFromChildDomNode(spanDomNode);
      if (!renderedStickyLine) {
        return null;
      }
      const column = getColumnOfNodeOffset(renderedStickyLine.characterMapping, spanDomNode, 0);
      return new Position$1(renderedStickyLine.lineNumber, column);
    }
    getLineNumberFromChildDomNode(domNode) {
      return this._getRenderedStickyLineFromChildDomNode(domNode)?.lineNumber ?? null;
    }
    _getRenderedStickyLineFromChildDomNode(domNode) {
      const index = this.getLineIndexFromChildDomNode(domNode);
      if (index === null || index < 0 || index >= this._renderedStickyLines.length) {
        return null;
      }
      return this._renderedStickyLines[index];
    }
    /**
     * Given a child dom node, tries to find the line number attribute that was stored in the node.
     * @returns the attribute value or null if none is found.
     */
    getLineIndexFromChildDomNode(domNode) {
      const lineIndex = this._getAttributeValue(domNode, STICKY_INDEX_ATTR);
      return lineIndex ? parseInt(lineIndex, 10) : null;
    }
    /**
     * Given a child dom node, tries to find if it is (contained in) a sticky line.
     * @returns a boolean.
     */
    isInStickyLine(domNode) {
      const isInLine = this._getAttributeValue(domNode, STICKY_IS_LINE_ATTR);
      return isInLine !== void 0;
    }
    /**
     * Given a child dom node, tries to find if this dom node is (contained in) a sticky folding icon.
     * @returns a boolean.
     */
    isInFoldingIconDomNode(domNode) {
      const isInFoldingIcon = this._getAttributeValue(domNode, STICKY_IS_FOLDING_ICON_ATTR);
      return isInFoldingIcon !== void 0;
    }
    /**
     * Given the dom node, finds if it or its parent sequence contains the given attribute.
     * @returns the attribute value or undefined.
     */
    _getAttributeValue(domNode, attribute) {
      while (domNode && domNode !== this._rootDomNode) {
        const line = domNode.getAttribute(attribute);
        if (line !== null) {
          return line;
        }
        domNode = domNode.parentElement;
      }
      return;
    }
  }
  class RenderedStickyLine {
    constructor(index, lineNumber, lineDomNode, lineNumberDomNode, foldingIcon, characterMapping, scrollWidth, height) {
      this.index = index;
      this.lineNumber = lineNumber;
      this.lineDomNode = lineDomNode;
      this.lineNumberDomNode = lineNumberDomNode;
      this.foldingIcon = foldingIcon;
      this.characterMapping = characterMapping;
      this.scrollWidth = scrollWidth;
      this.height = height;
    }
  }
  class StickyFoldingIcon {
    constructor(isCollapsed, foldingStartLine, foldingEndLine, dimension) {
      this.isCollapsed = isCollapsed;
      this.foldingStartLine = foldingStartLine;
      this.foldingEndLine = foldingEndLine;
      this.dimension = dimension;
      this.domNode = document.createElement("div");
      this.domNode.style.width = `26px`;
      this.domNode.style.height = `${dimension}px`;
      this.domNode.style.lineHeight = `${dimension}px`;
      this.domNode.className = ThemeIcon.asClassName(isCollapsed ? foldingCollapsedIcon : foldingExpandedIcon);
    }
    setVisible(visible) {
      this.domNode.style.cursor = visible ? "pointer" : "default";
      this.domNode.style.opacity = visible ? "1" : "0";
    }
  }
  class StickyRange {
    constructor(startLineNumber, endLineNumber) {
      this.startLineNumber = startLineNumber;
      this.endLineNumber = endLineNumber;
    }
  }
  class StickyElement {
    constructor(range2, children, parent) {
      this.range = range2;
      this.children = children;
      this.parent = parent;
    }
  }
  class StickyModel {
    constructor(uri, version, element, outlineProviderId) {
      this.uri = uri;
      this.version = version;
      this.element = element;
      this.outlineProviderId = outlineProviderId;
    }
  }
  var __decorate$1j = 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$1i = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  var ModelProvider;
  (function(ModelProvider2) {
    ModelProvider2["OUTLINE_MODEL"] = "outlineModel";
    ModelProvider2["FOLDING_PROVIDER_MODEL"] = "foldingProviderModel";
    ModelProvider2["INDENTATION_MODEL"] = "indentationModel";
  })(ModelProvider || (ModelProvider = {}));
  var Status;
  (function(Status2) {
    Status2[Status2["VALID"] = 0] = "VALID";
    Status2[Status2["INVALID"] = 1] = "INVALID";
    Status2[Status2["CANCELED"] = 2] = "CANCELED";
  })(Status || (Status = {}));
  let StickyModelProvider = class StickyModelProvider extends Disposable {
    constructor(_editor, onProviderUpdate, _languageConfigurationService, _languageFeaturesService) {
      super();
      this._editor = _editor;
      this._modelProviders = [];
      this._modelPromise = null;
      this._updateScheduler = this._register(new Delayer(300));
      this._updateOperation = this._register(new DisposableStore());
      switch (this._editor.getOption(
        131
        /* EditorOption.stickyScroll */
      ).defaultModel) {
        case ModelProvider.OUTLINE_MODEL:
          this._modelProviders.push(new StickyModelFromCandidateOutlineProvider(this._editor, _languageFeaturesService));
        // fall through
        case ModelProvider.FOLDING_PROVIDER_MODEL:
          this._modelProviders.push(new StickyModelFromCandidateSyntaxFoldingProvider(this._editor, onProviderUpdate, _languageFeaturesService));
        // fall through
        case ModelProvider.INDENTATION_MODEL:
          this._modelProviders.push(new StickyModelFromCandidateIndentationFoldingProvider(this._editor, _languageConfigurationService));
          break;
      }
    }
    dispose() {
      this._modelProviders.forEach((provider) => provider.dispose());
      this._updateOperation.clear();
      this._cancelModelPromise();
      super.dispose();
    }
    _cancelModelPromise() {
      if (this._modelPromise) {
        this._modelPromise.cancel();
        this._modelPromise = null;
      }
    }
    async update(token) {
      this._updateOperation.clear();
      this._updateOperation.add({
        dispose: () => {
          this._cancelModelPromise();
          this._updateScheduler.cancel();
        }
      });
      this._cancelModelPromise();
      return await this._updateScheduler.trigger(async () => {
        for (const modelProvider of this._modelProviders) {
          const { statusPromise, modelPromise } = modelProvider.computeStickyModel(token);
          this._modelPromise = modelPromise;
          const status2 = await statusPromise;
          if (this._modelPromise !== modelPromise) {
            return null;
          }
          switch (status2) {
            case Status.CANCELED:
              this._updateOperation.clear();
              return null;
            case Status.VALID:
              return modelProvider.stickyModel;
          }
        }
        return null;
      }).catch((error) => {
        onUnexpectedError(error);
        return null;
      });
    }
  };
  StickyModelProvider = __decorate$1j([
    __param$1i(2, IInstantiationService),
    __param$1i(3, ILanguageFeaturesService)
  ], StickyModelProvider);
  class StickyModelCandidateProvider extends Disposable {
    constructor(_editor) {
      super();
      this._editor = _editor;
      this._stickyModel = null;
    }
    get stickyModel() {
      return this._stickyModel;
    }
    _invalid() {
      this._stickyModel = null;
      return Status.INVALID;
    }
    computeStickyModel(token) {
      if (token.isCancellationRequested || !this.isProviderValid()) {
        return { statusPromise: this._invalid(), modelPromise: null };
      }
      const providerModelPromise = createCancelablePromise((token2) => this.createModelFromProvider(token2));
      return {
        statusPromise: providerModelPromise.then((providerModel) => {
          if (!this.isModelValid(providerModel)) {
            return this._invalid();
          }
          if (token.isCancellationRequested) {
            return Status.CANCELED;
          }
          this._stickyModel = this.createStickyModel(token, providerModel);
          return Status.VALID;
        }).then(void 0, (err) => {
          onUnexpectedError(err);
          return Status.CANCELED;
        }),
        modelPromise: providerModelPromise
      };
    }
    /**
     * Method which checks whether the model returned by the provider is valid and can be used to compute a sticky model.
     * This method by default returns true.
     * @param model model returned by the provider
     * @returns boolean indicating whether the model is valid
     */
    isModelValid(model) {
      return true;
    }
    /**
     * Method which checks whether the provider is valid before applying it to find the provider model.
     * This method by default returns true.
     * @returns boolean indicating whether the provider is valid
     */
    isProviderValid() {
      return true;
    }
  }
  let StickyModelFromCandidateOutlineProvider = class StickyModelFromCandidateOutlineProvider extends StickyModelCandidateProvider {
    constructor(_editor, _languageFeaturesService) {
      super(_editor);
      this._languageFeaturesService = _languageFeaturesService;
    }
    createModelFromProvider(token) {
      return OutlineModel.create(this._languageFeaturesService.documentSymbolProvider, this._editor.getModel(), token);
    }
    createStickyModel(token, model) {
      const { stickyOutlineElement, providerID } = this._stickyModelFromOutlineModel(model, this._stickyModel?.outlineProviderId);
      const textModel = this._editor.getModel();
      return new StickyModel(textModel.uri, textModel.getVersionId(), stickyOutlineElement, providerID);
    }
    isModelValid(model) {
      return model && model.children.size > 0;
    }
    _stickyModelFromOutlineModel(outlineModel, preferredProvider) {
      let outlineElements;
      if (Iterable.first(outlineModel.children.values()) instanceof OutlineGroup) {
        const provider = Iterable.find(outlineModel.children.values(), (outlineGroupOfModel) => outlineGroupOfModel.id === preferredProvider);
        if (provider) {
          outlineElements = provider.children;
        } else {
          let tempID = "";
          let maxTotalSumOfRanges = -1;
          let optimalOutlineGroup = void 0;
          for (const [_key, outlineGroup] of outlineModel.children.entries()) {
            const totalSumRanges = this._findSumOfRangesOfGroup(outlineGroup);
            if (totalSumRanges > maxTotalSumOfRanges) {
              optimalOutlineGroup = outlineGroup;
              maxTotalSumOfRanges = totalSumRanges;
              tempID = outlineGroup.id;
            }
          }
          preferredProvider = tempID;
          outlineElements = optimalOutlineGroup.children;
        }
      } else {
        outlineElements = outlineModel.children;
      }
      const stickyChildren = [];
      const outlineElementsArray = Array.from(outlineElements.values()).sort((element1, element2) => {
        const range1 = new StickyRange(element1.symbol.range.startLineNumber, element1.symbol.range.endLineNumber);
        const range2 = new StickyRange(element2.symbol.range.startLineNumber, element2.symbol.range.endLineNumber);
        return this._comparator(range1, range2);
      });
      for (const outlineElement of outlineElementsArray) {
        stickyChildren.push(this._stickyModelFromOutlineElement(outlineElement, outlineElement.symbol.selectionRange.startLineNumber));
      }
      const stickyOutlineElement = new StickyElement(void 0, stickyChildren, void 0);
      return {
        stickyOutlineElement,
        providerID: preferredProvider
      };
    }
    _stickyModelFromOutlineElement(outlineElement, previousStartLine) {
      const children = [];
      for (const child of outlineElement.children.values()) {
        if (child.symbol.selectionRange.startLineNumber !== child.symbol.range.endLineNumber) {
          if (child.symbol.selectionRange.startLineNumber !== previousStartLine) {
            children.push(this._stickyModelFromOutlineElement(child, child.symbol.selectionRange.startLineNumber));
          } else {
            for (const subchild of child.children.values()) {
              children.push(this._stickyModelFromOutlineElement(subchild, child.symbol.selectionRange.startLineNumber));
            }
          }
        }
      }
      children.sort((child1, child2) => this._comparator(child1.range, child2.range));
      const range2 = new StickyRange(outlineElement.symbol.selectionRange.startLineNumber, outlineElement.symbol.range.endLineNumber);
      return new StickyElement(range2, children, void 0);
    }
    _comparator(range1, range2) {
      if (range1.startLineNumber !== range2.startLineNumber) {
        return range1.startLineNumber - range2.startLineNumber;
      } else {
        return range2.endLineNumber - range1.endLineNumber;
      }
    }
    _findSumOfRangesOfGroup(outline) {
      let res = 0;
      for (const child of outline.children.values()) {
        res += this._findSumOfRangesOfGroup(child);
      }
      if (outline instanceof OutlineElement) {
        return res + outline.symbol.range.endLineNumber - outline.symbol.selectionRange.startLineNumber;
      } else {
        return res;
      }
    }
  };
  StickyModelFromCandidateOutlineProvider = __decorate$1j([
    __param$1i(1, ILanguageFeaturesService)
  ], StickyModelFromCandidateOutlineProvider);
  class StickyModelFromCandidateFoldingProvider extends StickyModelCandidateProvider {
    constructor(editor2) {
      super(editor2);
      this._foldingLimitReporter = this._register(new RangesLimitReporter(editor2));
    }
    createStickyModel(token, model) {
      const foldingElement = this._fromFoldingRegions(model);
      const textModel = this._editor.getModel();
      return new StickyModel(textModel.uri, textModel.getVersionId(), foldingElement, void 0);
    }
    isModelValid(model) {
      return model !== null;
    }
    _fromFoldingRegions(foldingRegions) {
      const length = foldingRegions.length;
      const orderedStickyElements = [];
      const stickyOutlineElement = new StickyElement(void 0, [], void 0);
      for (let i2 = 0; i2 < length; i2++) {
        const parentIndex = foldingRegions.getParentIndex(i2);
        let parentNode;
        if (parentIndex !== -1) {
          parentNode = orderedStickyElements[parentIndex];
        } else {
          parentNode = stickyOutlineElement;
        }
        const child = new StickyElement(new StickyRange(foldingRegions.getStartLineNumber(i2), foldingRegions.getEndLineNumber(i2) + 1), [], parentNode);
        parentNode.children.push(child);
        orderedStickyElements.push(child);
      }
      return stickyOutlineElement;
    }
  }
  let StickyModelFromCandidateIndentationFoldingProvider = class StickyModelFromCandidateIndentationFoldingProvider extends StickyModelFromCandidateFoldingProvider {
    constructor(editor2, _languageConfigurationService) {
      super(editor2);
      this._languageConfigurationService = _languageConfigurationService;
      this.provider = this._register(new IndentRangeProvider(editor2.getModel(), this._languageConfigurationService, this._foldingLimitReporter));
    }
    async createModelFromProvider(token) {
      return this.provider.compute(token);
    }
  };
  StickyModelFromCandidateIndentationFoldingProvider = __decorate$1j([
    __param$1i(1, ILanguageConfigurationService)
  ], StickyModelFromCandidateIndentationFoldingProvider);
  let StickyModelFromCandidateSyntaxFoldingProvider = class StickyModelFromCandidateSyntaxFoldingProvider extends StickyModelFromCandidateFoldingProvider {
    constructor(editor2, onProviderUpdate, _languageFeaturesService) {
      super(editor2);
      this._languageFeaturesService = _languageFeaturesService;
      this.provider = this._register(new MutableDisposable());
      this._register(this._languageFeaturesService.foldingRangeProvider.onDidChange(() => {
        this._updateProvider(editor2, onProviderUpdate);
      }));
      this._updateProvider(editor2, onProviderUpdate);
    }
    _updateProvider(editor2, onProviderUpdate) {
      const selectedProviders = FoldingController.getFoldingRangeProviders(this._languageFeaturesService, editor2.getModel());
      if (selectedProviders.length === 0) {
        return;
      }
      this.provider.value = new SyntaxRangeProvider(editor2.getModel(), selectedProviders, onProviderUpdate, this._foldingLimitReporter, void 0);
    }
    isProviderValid() {
      return this.provider !== void 0;
    }
    async createModelFromProvider(token) {
      return this.provider.value?.compute(token) ?? null;
    }
  };
  StickyModelFromCandidateSyntaxFoldingProvider = __decorate$1j([
    __param$1i(2, ILanguageFeaturesService)
  ], StickyModelFromCandidateSyntaxFoldingProvider);
  var __decorate$1i = 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$1h = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  class StickyLineCandidate {
    constructor(startLineNumber, endLineNumber, top, height) {
      this.startLineNumber = startLineNumber;
      this.endLineNumber = endLineNumber;
      this.top = top;
      this.height = height;
    }
  }
  let StickyLineCandidateProvider = class StickyLineCandidateProvider extends Disposable {
    constructor(editor2, _languageFeaturesService, _languageConfigurationService) {
      super();
      this._languageFeaturesService = _languageFeaturesService;
      this._languageConfigurationService = _languageConfigurationService;
      this._onDidChangeStickyScroll = this._register(new Emitter$1());
      this.onDidChangeStickyScroll = this._onDidChangeStickyScroll.event;
      this._model = null;
      this._cts = null;
      this._stickyModelProvider = null;
      this._editor = editor2;
      this._sessionStore = this._register(new DisposableStore());
      this._updateSoon = this._register(new RunOnceScheduler(() => this.update(), 50));
      this._register(this._editor.onDidChangeConfiguration((e) => {
        if (e.hasChanged(
          131
          /* EditorOption.stickyScroll */
        )) {
          this.readConfiguration();
        }
      }));
      this.readConfiguration();
    }
    /**
     * Read and apply the sticky scroll configuration.
     */
    readConfiguration() {
      this._sessionStore.clear();
      const options = this._editor.getOption(
        131
        /* EditorOption.stickyScroll */
      );
      if (!options.enabled) {
        return;
      }
      this._sessionStore.add(this._editor.onDidChangeModel(() => {
        this._model = null;
        this.updateStickyModelProvider();
        this._onDidChangeStickyScroll.fire();
        this.update();
      }));
      this._sessionStore.add(this._editor.onDidChangeHiddenAreas(() => this.update()));
      this._sessionStore.add(this._editor.onDidChangeModelContent(() => this._updateSoon.schedule()));
      this._sessionStore.add(this._languageFeaturesService.documentSymbolProvider.onDidChange(() => this.update()));
      this._sessionStore.add(toDisposable(() => {
        this._stickyModelProvider?.dispose();
        this._stickyModelProvider = null;
      }));
      this.updateStickyModelProvider();
      this.update();
    }
    /**
     * Get the version ID of the sticky model.
     */
    getVersionId() {
      return this._model?.version;
    }
    /**
     * Update the sticky model provider.
     */
    updateStickyModelProvider() {
      this._stickyModelProvider?.dispose();
      this._stickyModelProvider = null;
      if (this._editor.hasModel()) {
        this._stickyModelProvider = new StickyModelProvider(this._editor, () => this._updateSoon.schedule(), this._languageConfigurationService, this._languageFeaturesService);
      }
    }
    /**
     * Update the sticky line candidates.
     */
    async update() {
      this._cts?.dispose(true);
      this._cts = new CancellationTokenSource$1();
      await this.updateStickyModel(this._cts.token);
      this._onDidChangeStickyScroll.fire();
    }
    /**
     * Update the sticky model based on the current editor state.
     */
    async updateStickyModel(token) {
      if (!this._editor.hasModel() || !this._stickyModelProvider || this._editor.getModel().isTooLargeForTokenization()) {
        this._model = null;
        return;
      }
      const model = await this._stickyModelProvider.update(token);
      if (!token.isCancellationRequested) {
        this._model = model;
      }
    }
    /**
     * Get sticky line candidates intersecting a given range.
     */
    getCandidateStickyLinesIntersecting(range2) {
      if (!this._model?.element) {
        return [];
      }
      const stickyLineCandidates = [];
      this.getCandidateStickyLinesIntersectingFromStickyModel(range2, this._model.element, stickyLineCandidates, 0, 0, -1);
      return this.filterHiddenRanges(stickyLineCandidates);
    }
    /**
     * Get sticky line candidates intersecting a given range from the sticky model.
     */
    getCandidateStickyLinesIntersectingFromStickyModel(range2, outlineModel, result, depth, top, lastStartLineNumber) {
      const textModel = this._editor.getModel();
      if (!textModel) {
        return;
      }
      if (outlineModel.children.length === 0) {
        return;
      }
      let lastLine = lastStartLineNumber;
      const childrenStartLines = [];
      for (let i2 = 0; i2 < outlineModel.children.length; i2++) {
        const child = outlineModel.children[i2];
        if (child.range) {
          childrenStartLines.push(child.range.startLineNumber);
        }
      }
      const lowerBound = this.updateIndex(binarySearch(childrenStartLines, range2.startLineNumber, (a, b) => {
        return a - b;
      }));
      const upperBound = this.updateIndex(binarySearch(childrenStartLines, range2.endLineNumber, (a, b) => {
        return a - b;
      }));
      for (let i2 = lowerBound; i2 <= upperBound; i2++) {
        const child = outlineModel.children[i2];
        if (!child || !child.range) {
          continue;
        }
        const { startLineNumber, endLineNumber } = child.range;
        if (endLineNumber > startLineNumber + 1 && range2.startLineNumber <= endLineNumber + 1 && startLineNumber - 1 <= range2.endLineNumber && startLineNumber !== lastLine && textModel.isValidRange(new Range$2(startLineNumber, 1, endLineNumber, 1))) {
          lastLine = startLineNumber;
          const lineHeight = this._editor.getLineHeightForPosition(new Position$1(startLineNumber, 1));
          result.push(new StickyLineCandidate(startLineNumber, endLineNumber - 1, top, lineHeight));
          this.getCandidateStickyLinesIntersectingFromStickyModel(range2, child, result, depth + 1, top + lineHeight, startLineNumber);
        }
      }
    }
    /**
     * Filter out sticky line candidates that are within hidden ranges.
     */
    filterHiddenRanges(stickyLineCandidates) {
      const hiddenRanges = this._editor._getViewModel()?.getHiddenAreas();
      if (!hiddenRanges) {
        return stickyLineCandidates;
      }
      return stickyLineCandidates.filter((candidate) => {
        return !hiddenRanges.some((hiddenRange) => candidate.startLineNumber >= hiddenRange.startLineNumber && candidate.endLineNumber <= hiddenRange.endLineNumber + 1);
      });
    }
    /**
     * Update the binary search index.
     */
    updateIndex(index) {
      if (index === -1) {
        return 0;
      } else if (index < 0) {
        return -index - 2;
      }
      return index;
    }
  };
  StickyLineCandidateProvider = __decorate$1i([
    __param$1h(1, ILanguageFeaturesService),
    __param$1h(2, ILanguageConfigurationService)
  ], StickyLineCandidateProvider);
  var __decorate$1h = 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$1g = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  var StickyScrollController_1;
  let StickyScrollController = (_ia = class extends Disposable {
    constructor(_editor, _contextMenuService, _languageFeaturesService, _instaService, _languageConfigurationService, _languageFeatureDebounceService, _contextKeyService) {
      super();
      this._editor = _editor;
      this._contextMenuService = _contextMenuService;
      this._languageFeaturesService = _languageFeaturesService;
      this._instaService = _instaService;
      this._contextKeyService = _contextKeyService;
      this._sessionStore = new DisposableStore();
      this._maxStickyLines = Number.MAX_SAFE_INTEGER;
      this._candidateDefinitionsLength = -1;
      this._focusedStickyElementIndex = -1;
      this._enabled = false;
      this._focused = false;
      this._positionRevealed = false;
      this._onMouseDown = false;
      this._endLineNumbers = [];
      this._mouseTarget = null;
      this._onDidChangeStickyScrollHeight = this._register(new Emitter$1());
      this.onDidChangeStickyScrollHeight = this._onDidChangeStickyScrollHeight.event;
      this._stickyScrollWidget = new StickyScrollWidget(this._editor);
      this._stickyLineCandidateProvider = new StickyLineCandidateProvider(this._editor, _languageFeaturesService, _languageConfigurationService);
      this._register(this._stickyScrollWidget);
      this._register(this._stickyLineCandidateProvider);
      this._widgetState = StickyScrollWidgetState.Empty;
      const stickyScrollDomNode = this._stickyScrollWidget.getDomNode();
      this._register(this._editor.onDidChangeLineHeight((e) => {
        e.changes.forEach((change) => {
          const lineNumber = change.lineNumber;
          if (this._widgetState.startLineNumbers.includes(lineNumber)) {
            this._renderStickyScroll(lineNumber);
          }
        });
      }));
      this._register(this._editor.onDidChangeFont((e) => {
        e.changes.forEach((change) => {
          const lineNumber = change.lineNumber;
          if (this._widgetState.startLineNumbers.includes(lineNumber)) {
            this._renderStickyScroll(lineNumber);
          }
        });
      }));
      this._register(this._editor.onDidChangeConfiguration((e) => {
        this._readConfigurationChange(e);
      }));
      this._register(addDisposableListener(stickyScrollDomNode, EventType$1.CONTEXT_MENU, async (event) => {
        this._onContextMenu(getWindow(stickyScrollDomNode), event);
      }));
      this._stickyScrollFocusedContextKey = EditorContextKeys.stickyScrollFocused.bindTo(this._contextKeyService);
      this._stickyScrollVisibleContextKey = EditorContextKeys.stickyScrollVisible.bindTo(this._contextKeyService);
      const focusTracker = this._register(trackFocus(stickyScrollDomNode));
      this._register(focusTracker.onDidBlur((_) => {
        if (this._positionRevealed === false && stickyScrollDomNode.clientHeight === 0) {
          this._focusedStickyElementIndex = -1;
          this.focus();
        } else {
          this._disposeFocusStickyScrollStore();
        }
      }));
      this._register(focusTracker.onDidFocus((_) => {
        this.focus();
      }));
      this._registerMouseListeners();
      this._register(addDisposableListener(stickyScrollDomNode, EventType$1.MOUSE_DOWN, (e) => {
        this._onMouseDown = true;
      }));
      this._register(this._stickyScrollWidget.onDidChangeStickyScrollHeight((e) => {
        this._onDidChangeStickyScrollHeight.fire(e);
      }));
      this._onDidResize();
      this._readConfiguration();
    }
    get stickyScrollWidgetHeight() {
      return this._stickyScrollWidget.height;
    }
    static get(editor2) {
      return editor2.getContribution(StickyScrollController_1.ID);
    }
    _disposeFocusStickyScrollStore() {
      this._stickyScrollFocusedContextKey.set(false);
      this._focusDisposableStore?.dispose();
      this._focused = false;
      this._positionRevealed = false;
      this._onMouseDown = false;
    }
    isFocused() {
      return this._focused;
    }
    focus() {
      if (this._onMouseDown) {
        this._onMouseDown = false;
        this._editor.focus();
        return;
      }
      const focusState = this._stickyScrollFocusedContextKey.get();
      if (focusState === true) {
        return;
      }
      this._focused = true;
      this._focusDisposableStore = new DisposableStore();
      this._stickyScrollFocusedContextKey.set(true);
      this._focusedStickyElementIndex = this._stickyScrollWidget.lineNumbers.length - 1;
      this._stickyScrollWidget.focusLineWithIndex(this._focusedStickyElementIndex);
    }
    focusNext() {
      if (this._focusedStickyElementIndex < this._stickyScrollWidget.lineNumberCount - 1) {
        this._focusNav(true);
      }
    }
    focusPrevious() {
      if (this._focusedStickyElementIndex > 0) {
        this._focusNav(false);
      }
    }
    selectEditor() {
      this._editor.focus();
    }
    // True is next, false is previous
    _focusNav(direction) {
      this._focusedStickyElementIndex = direction ? this._focusedStickyElementIndex + 1 : this._focusedStickyElementIndex - 1;
      this._stickyScrollWidget.focusLineWithIndex(this._focusedStickyElementIndex);
    }
    goToFocused() {
      const lineNumbers = this._stickyScrollWidget.lineNumbers;
      this._disposeFocusStickyScrollStore();
      this._revealPosition({ lineNumber: lineNumbers[this._focusedStickyElementIndex], column: 1 });
    }
    _revealPosition(position) {
      this._reveaInEditor(position, () => this._editor.revealPosition(position));
    }
    _revealLineInCenterIfOutsideViewport(position) {
      this._reveaInEditor(position, () => this._editor.revealLineInCenterIfOutsideViewport(
        position.lineNumber,
        0
        /* ScrollType.Smooth */
      ));
    }
    _reveaInEditor(position, revealFunction) {
      if (this._focused) {
        this._disposeFocusStickyScrollStore();
      }
      this._positionRevealed = true;
      revealFunction();
      this._editor.setSelection(Range$2.fromPositions(position));
      this._editor.focus();
    }
    _registerMouseListeners() {
      const sessionStore = this._register(new DisposableStore());
      const gesture = this._register(new ClickLinkGesture(this._editor, {
        extractLineNumberFromMouseEvent: (e) => {
          const position = this._stickyScrollWidget.getEditorPositionFromNode(e.target.element);
          return position ? position.lineNumber : 0;
        }
      }));
      const getMouseEventTarget = (mouseEvent) => {
        if (!this._editor.hasModel()) {
          return null;
        }
        if (mouseEvent.target.type !== 12 || mouseEvent.target.detail !== this._stickyScrollWidget.getId()) {
          return null;
        }
        const mouseTargetElement = mouseEvent.target.element;
        if (!mouseTargetElement || mouseTargetElement.innerText !== mouseTargetElement.innerHTML) {
          return null;
        }
        const position = this._stickyScrollWidget.getEditorPositionFromNode(mouseTargetElement);
        if (!position) {
          return null;
        }
        return {
          range: new Range$2(position.lineNumber, position.column, position.lineNumber, position.column + mouseTargetElement.innerText.length),
          textElement: mouseTargetElement
        };
      };
      const stickyScrollWidgetDomNode = this._stickyScrollWidget.getDomNode();
      this._register(addStandardDisposableListener(stickyScrollWidgetDomNode, EventType$1.CLICK, (mouseEvent) => {
        if (mouseEvent.ctrlKey || mouseEvent.altKey || mouseEvent.metaKey) {
          return;
        }
        if (!mouseEvent.leftButton) {
          return;
        }
        if (mouseEvent.shiftKey) {
          const lineIndex = this._stickyScrollWidget.getLineIndexFromChildDomNode(mouseEvent.target);
          if (lineIndex === null) {
            return;
          }
          const position2 = new Position$1(this._endLineNumbers[lineIndex], 1);
          this._revealLineInCenterIfOutsideViewport(position2);
          return;
        }
        const isInFoldingIconDomNode = this._stickyScrollWidget.isInFoldingIconDomNode(mouseEvent.target);
        if (isInFoldingIconDomNode) {
          const lineNumber = this._stickyScrollWidget.getLineNumberFromChildDomNode(mouseEvent.target);
          this._toggleFoldingRegionForLine(lineNumber);
          return;
        }
        const isInStickyLine = this._stickyScrollWidget.isInStickyLine(mouseEvent.target);
        if (!isInStickyLine) {
          return;
        }
        let position = this._stickyScrollWidget.getEditorPositionFromNode(mouseEvent.target);
        if (!position) {
          const lineNumber = this._stickyScrollWidget.getLineNumberFromChildDomNode(mouseEvent.target);
          if (lineNumber === null) {
            return;
          }
          position = new Position$1(lineNumber, 1);
        }
        this._revealPosition(position);
      }));
      this._register(addDisposableListener(mainWindow, EventType$1.MOUSE_MOVE, (mouseEvent) => {
        this._mouseTarget = mouseEvent.target;
        this._onMouseMoveOrKeyDown(mouseEvent);
      }));
      this._register(addDisposableListener(mainWindow, EventType$1.KEY_DOWN, (mouseEvent) => {
        this._onMouseMoveOrKeyDown(mouseEvent);
      }));
      this._register(addDisposableListener(mainWindow, EventType$1.KEY_UP, () => {
        if (this._showEndForLine !== void 0) {
          this._showEndForLine = void 0;
          this._renderStickyScroll();
        }
      }));
      this._register(gesture.onMouseMoveOrRelevantKeyDown(([mouseEvent, _keyboardEvent]) => {
        const mouseTarget = getMouseEventTarget(mouseEvent);
        if (!mouseTarget || !mouseEvent.hasTriggerModifier || !this._editor.hasModel()) {
          sessionStore.clear();
          return;
        }
        const { range: range2, textElement } = mouseTarget;
        if (!range2.equalsRange(this._stickyRangeProjectedOnEditor)) {
          this._stickyRangeProjectedOnEditor = range2;
          sessionStore.clear();
        } else if (textElement.style.textDecoration === "underline") {
          return;
        }
        const cancellationToken = new CancellationTokenSource$1();
        sessionStore.add(toDisposable(() => cancellationToken.dispose(true)));
        let currentHTMLChild;
        getDefinitionsAtPosition(this._languageFeaturesService.definitionProvider, this._editor.getModel(), new Position$1(range2.startLineNumber, range2.startColumn + 1), false, cancellationToken.token).then(((candidateDefinitions) => {
          if (cancellationToken.token.isCancellationRequested) {
            return;
          }
          if (candidateDefinitions.length !== 0) {
            this._candidateDefinitionsLength = candidateDefinitions.length;
            const childHTML = textElement;
            if (currentHTMLChild !== childHTML) {
              sessionStore.clear();
              currentHTMLChild = childHTML;
              currentHTMLChild.style.textDecoration = "underline";
              sessionStore.add(toDisposable(() => {
                currentHTMLChild.style.textDecoration = "none";
              }));
            } else if (!currentHTMLChild) {
              currentHTMLChild = childHTML;
              currentHTMLChild.style.textDecoration = "underline";
              sessionStore.add(toDisposable(() => {
                currentHTMLChild.style.textDecoration = "none";
              }));
            }
          } else {
            sessionStore.clear();
          }
        }));
      }));
      this._register(gesture.onCancel(() => {
        sessionStore.clear();
      }));
      this._register(gesture.onExecute(async (e) => {
        if (e.target.type !== 12 || e.target.detail !== this._stickyScrollWidget.getId()) {
          return;
        }
        const position = this._stickyScrollWidget.getEditorPositionFromNode(e.target.element);
        if (!position) {
          return;
        }
        if (!this._editor.hasModel() || !this._stickyRangeProjectedOnEditor) {
          return;
        }
        if (this._candidateDefinitionsLength > 1) {
          if (this._focused) {
            this._disposeFocusStickyScrollStore();
          }
          this._revealPosition({ lineNumber: position.lineNumber, column: 1 });
        }
        this._instaService.invokeFunction(goToDefinitionWithLocation, e, this._editor, { uri: this._editor.getModel().uri, range: this._stickyRangeProjectedOnEditor });
      }));
    }
    _onContextMenu(targetWindow, e) {
      const event = new StandardMouseEvent(targetWindow, e);
      this._contextMenuService.showContextMenu({
        menuId: MenuId.StickyScrollContext,
        getAnchor: () => event
      });
    }
    _onMouseMoveOrKeyDown(mouseEvent) {
      if (!mouseEvent.shiftKey) {
        return;
      }
      if (!this._mouseTarget || !isHTMLElement(this._mouseTarget)) {
        return;
      }
      const currentEndForLineIndex = this._stickyScrollWidget.getLineIndexFromChildDomNode(this._mouseTarget);
      if (currentEndForLineIndex === null || this._showEndForLine === currentEndForLineIndex) {
        return;
      }
      this._showEndForLine = currentEndForLineIndex;
      this._renderStickyScroll();
    }
    _toggleFoldingRegionForLine(line) {
      if (!this._foldingModel || line === null) {
        return;
      }
      const stickyLine = this._stickyScrollWidget.getRenderedStickyLine(line);
      const foldingIcon = stickyLine?.foldingIcon;
      if (!foldingIcon) {
        return;
      }
      toggleCollapseState(this._foldingModel, 1, [line]);
      foldingIcon.isCollapsed = !foldingIcon.isCollapsed;
      const scrollTop = (foldingIcon.isCollapsed ? this._editor.getTopForLineNumber(foldingIcon.foldingEndLine) : this._editor.getTopForLineNumber(foldingIcon.foldingStartLine)) - this._editor.getOption(
        75
        /* EditorOption.lineHeight */
      ) * stickyLine.index + 1;
      this._editor.setScrollTop(scrollTop);
      this._renderStickyScroll(line);
    }
    _readConfiguration() {
      const options = this._editor.getOption(
        131
        /* EditorOption.stickyScroll */
      );
      if (options.enabled === false) {
        this._editor.removeOverlayWidget(this._stickyScrollWidget);
        this._resetState();
        this._sessionStore.clear();
        this._enabled = false;
        return;
      } else if (options.enabled && !this._enabled) {
        this._editor.addOverlayWidget(this._stickyScrollWidget);
        this._sessionStore.add(this._editor.onDidScrollChange((e) => {
          if (e.scrollTopChanged) {
            this._showEndForLine = void 0;
            this._renderStickyScroll();
          }
        }));
        this._sessionStore.add(this._editor.onDidLayoutChange(() => this._onDidResize()));
        this._sessionStore.add(this._editor.onDidChangeModelTokens((e) => this._onTokensChange(e)));
        this._sessionStore.add(this._stickyLineCandidateProvider.onDidChangeStickyScroll(() => {
          this._showEndForLine = void 0;
          this._renderStickyScroll();
        }));
        this._enabled = true;
      }
      const lineNumberOption = this._editor.getOption(
        76
        /* EditorOption.lineNumbers */
      );
      if (lineNumberOption.renderType === 2) {
        this._sessionStore.add(this._editor.onDidChangeCursorPosition(() => {
          this._showEndForLine = void 0;
          this._renderStickyScroll(0);
        }));
      }
    }
    _readConfigurationChange(event) {
      if (event.hasChanged(
        131
        /* EditorOption.stickyScroll */
      ) || event.hasChanged(
        81
        /* EditorOption.minimap */
      ) || event.hasChanged(
        75
        /* EditorOption.lineHeight */
      ) || event.hasChanged(
        126
        /* EditorOption.showFoldingControls */
      ) || event.hasChanged(
        76
        /* EditorOption.lineNumbers */
      )) {
        this._readConfiguration();
      }
      if (event.hasChanged(
        76
        /* EditorOption.lineNumbers */
      ) || event.hasChanged(
        52
        /* EditorOption.folding */
      ) || event.hasChanged(
        126
        /* EditorOption.showFoldingControls */
      )) {
        this._renderStickyScroll(0);
      }
    }
    _needsUpdate(event) {
      const stickyLineNumbers = this._stickyScrollWidget.getCurrentLines();
      for (const stickyLineNumber of stickyLineNumbers) {
        for (const range2 of event.ranges) {
          if (stickyLineNumber >= range2.fromLineNumber && stickyLineNumber <= range2.toLineNumber) {
            return true;
          }
        }
      }
      return false;
    }
    _onTokensChange(event) {
      if (this._needsUpdate(event)) {
        this._renderStickyScroll(0);
      }
    }
    _onDidResize() {
      const layoutInfo = this._editor.getLayoutInfo();
      const theoreticalLines = layoutInfo.height / this._editor.getOption(
        75
        /* EditorOption.lineHeight */
      );
      this._maxStickyLines = Math.round(theoreticalLines * 0.25);
      this._renderStickyScroll(0);
    }
    async _renderStickyScroll(rebuildFromLine) {
      const model = this._editor.getModel();
      if (!model || model.isTooLargeForTokenization()) {
        this._resetState();
        return;
      }
      const nextRebuildFromLine = this._updateAndGetMinRebuildFromLine(rebuildFromLine);
      const stickyWidgetVersion = this._stickyLineCandidateProvider.getVersionId();
      const shouldUpdateState = stickyWidgetVersion === void 0 || stickyWidgetVersion === model.getVersionId();
      if (shouldUpdateState) {
        if (!this._focused) {
          await this._updateState(nextRebuildFromLine);
        } else {
          if (this._focusedStickyElementIndex === -1) {
            await this._updateState(nextRebuildFromLine);
            this._focusedStickyElementIndex = this._stickyScrollWidget.lineNumberCount - 1;
            if (this._focusedStickyElementIndex !== -1) {
              this._stickyScrollWidget.focusLineWithIndex(this._focusedStickyElementIndex);
            }
          } else {
            const focusedStickyElementLineNumber = this._stickyScrollWidget.lineNumbers[this._focusedStickyElementIndex];
            await this._updateState(nextRebuildFromLine);
            if (this._stickyScrollWidget.lineNumberCount === 0) {
              this._focusedStickyElementIndex = -1;
            } else {
              const previousFocusedLineNumberExists = this._stickyScrollWidget.lineNumbers.includes(focusedStickyElementLineNumber);
              if (!previousFocusedLineNumberExists) {
                this._focusedStickyElementIndex = this._stickyScrollWidget.lineNumberCount - 1;
              }
              this._stickyScrollWidget.focusLineWithIndex(this._focusedStickyElementIndex);
            }
          }
        }
      }
    }
    _updateAndGetMinRebuildFromLine(rebuildFromLine) {
      if (rebuildFromLine !== void 0) {
        const minRebuildFromLineOrInfinity = this._minRebuildFromLine !== void 0 ? this._minRebuildFromLine : Infinity;
        this._minRebuildFromLine = Math.min(rebuildFromLine, minRebuildFromLineOrInfinity);
      }
      return this._minRebuildFromLine;
    }
    async _updateState(rebuildFromLine) {
      this._minRebuildFromLine = void 0;
      this._foldingModel = await FoldingController.get(this._editor)?.getFoldingModel() ?? void 0;
      this._widgetState = this.findScrollWidgetState();
      const stickyWidgetHasLines = this._widgetState.startLineNumbers.length > 0;
      this._stickyScrollVisibleContextKey.set(stickyWidgetHasLines);
      this._stickyScrollWidget.setState(this._widgetState, this._foldingModel, rebuildFromLine);
    }
    async _resetState() {
      this._minRebuildFromLine = void 0;
      this._foldingModel = void 0;
      this._widgetState = StickyScrollWidgetState.Empty;
      this._stickyScrollVisibleContextKey.set(false);
      this._stickyScrollWidget.setState(void 0, void 0);
    }
    findScrollWidgetState() {
      const maxNumberStickyLines = Math.min(this._maxStickyLines, this._editor.getOption(
        131
        /* EditorOption.stickyScroll */
      ).maxLineCount);
      const scrollTop = this._editor.getScrollTop();
      let lastLineRelativePosition = 0;
      const startLineNumbers = [];
      const endLineNumbers = [];
      const arrayVisibleRanges = this._editor.getVisibleRanges();
      if (arrayVisibleRanges.length !== 0) {
        const fullVisibleRange = new StickyRange(arrayVisibleRanges[0].startLineNumber, arrayVisibleRanges[arrayVisibleRanges.length - 1].endLineNumber);
        const candidateRanges = this._stickyLineCandidateProvider.getCandidateStickyLinesIntersecting(fullVisibleRange);
        for (const range2 of candidateRanges) {
          const start = range2.startLineNumber;
          const end = range2.endLineNumber;
          const topOfElement = range2.top;
          const bottomOfElement = topOfElement + range2.height;
          const topOfBeginningLine = this._editor.getTopForLineNumber(start) - scrollTop;
          const bottomOfEndLine = this._editor.getBottomForLineNumber(end) - scrollTop;
          if (topOfElement > topOfBeginningLine && topOfElement <= bottomOfEndLine) {
            startLineNumbers.push(start);
            endLineNumbers.push(end + 1);
            if (bottomOfElement > bottomOfEndLine) {
              lastLineRelativePosition = bottomOfEndLine - bottomOfElement;
            }
          }
          if (startLineNumbers.length === maxNumberStickyLines) {
            break;
          }
        }
      }
      this._endLineNumbers = endLineNumbers;
      return new StickyScrollWidgetState(startLineNumbers, endLineNumbers, lastLineRelativePosition, this._showEndForLine);
    }
    dispose() {
      super.dispose();
      this._sessionStore.dispose();
    }
  }, StickyScrollController_1 = _ia, _ia.ID = "store.contrib.stickyScrollController", _ia);
  StickyScrollController = StickyScrollController_1 = __decorate$1h([
    __param$1g(1, IContextMenuService),
    __param$1g(2, ILanguageFeaturesService),
    __param$1g(3, IInstantiationService),
    __param$1g(4, ILanguageConfigurationService),
    __param$1g(5, ILanguageFeatureDebounceService),
    __param$1g(6, IContextKeyService)
  ], StickyScrollController);
  const originalBackgroundColor = registerColor("inlineEdit.originalBackground", transparent(diffRemoved, 0.2), localize(1220, "Background color for the original text in inline edits."), true);
  const modifiedBackgroundColor = registerColor("inlineEdit.modifiedBackground", transparent(diffInserted, 0.3), localize(1221, "Background color for the modified text in inline edits."), true);
  registerColor("inlineEdit.originalChangedLineBackground", transparent(diffRemoved, 0.8), localize(1222, "Background color for the changed lines in the original text of inline edits."), true);
  const originalChangedTextOverlayColor = registerColor("inlineEdit.originalChangedTextBackground", transparent(diffRemoved, 0.8), localize(1223, "Overlay color for the changed text in the original text of inline edits."), true);
  const modifiedChangedLineBackgroundColor = registerColor("inlineEdit.modifiedChangedLineBackground", {
    light: transparent(diffInsertedLine, 0.7),
    dark: transparent(diffInsertedLine, 0.7),
    hcDark: diffInsertedLine,
    hcLight: diffInsertedLine
  }, localize(1224, "Background color for the changed lines in the modified text of inline edits."), true);
  const modifiedChangedTextOverlayColor = registerColor("inlineEdit.modifiedChangedTextBackground", transparent(diffInserted, 0.7), localize(1225, "Overlay color for the changed text in the modified text of inline edits."), true);
  const inlineEditIndicatorPrimaryForeground = registerColor("inlineEdit.gutterIndicator.primaryForeground", buttonForeground, localize(1226, "Foreground color for the primary inline edit gutter indicator."));
  const inlineEditIndicatorPrimaryBorder = registerColor("inlineEdit.gutterIndicator.primaryBorder", buttonBackground, localize(1227, "Border color for the primary inline edit gutter indicator."));
  const inlineEditIndicatorPrimaryBackground = registerColor("inlineEdit.gutterIndicator.primaryBackground", {
    light: transparent(inlineEditIndicatorPrimaryBorder, 0.5),
    dark: transparent(inlineEditIndicatorPrimaryBorder, 0.4),
    hcDark: transparent(inlineEditIndicatorPrimaryBorder, 0.4),
    hcLight: transparent(inlineEditIndicatorPrimaryBorder, 0.5)
  }, localize(1228, "Background color for the primary inline edit gutter indicator."));
  const inlineEditIndicatorSecondaryForeground = registerColor("inlineEdit.gutterIndicator.secondaryForeground", buttonSecondaryForeground, localize(1229, "Foreground color for the secondary inline edit gutter indicator."));
  const inlineEditIndicatorSecondaryBorder = registerColor("inlineEdit.gutterIndicator.secondaryBorder", buttonSecondaryBackground, localize(1230, "Border color for the secondary inline edit gutter indicator."));
  const inlineEditIndicatorSecondaryBackground = registerColor("inlineEdit.gutterIndicator.secondaryBackground", inlineEditIndicatorSecondaryBorder, localize(1231, "Background color for the secondary inline edit gutter indicator."));
  const inlineEditIndicatorsuccessfulForeground = registerColor("inlineEdit.gutterIndicator.successfulForeground", buttonForeground, localize(1232, "Foreground color for the successful inline edit gutter indicator."));
  const inlineEditIndicatorsuccessfulBorder = registerColor("inlineEdit.gutterIndicator.successfulBorder", buttonBackground, localize(1233, "Border color for the successful inline edit gutter indicator."));
  const inlineEditIndicatorsuccessfulBackground = registerColor("inlineEdit.gutterIndicator.successfulBackground", inlineEditIndicatorsuccessfulBorder, localize(1234, "Background color for the successful inline edit gutter indicator."));
  const inlineEditIndicatorBackground = registerColor("inlineEdit.gutterIndicator.background", {
    hcDark: transparent("tab.inactiveBackground", 0.5),
    hcLight: transparent("tab.inactiveBackground", 0.5),
    dark: transparent("tab.inactiveBackground", 0.5),
    light: "#5f5f5f18"
  }, localize(1235, "Background color for the inline edit gutter indicator."));
  const originalBorder = registerColor("inlineEdit.originalBorder", {
    light: diffRemoved,
    dark: diffRemoved,
    hcDark: diffRemoved,
    hcLight: diffRemoved
  }, localize(1236, "Border color for the original text in inline edits."));
  const modifiedBorder = registerColor("inlineEdit.modifiedBorder", {
    light: darken(diffInserted, 0.6),
    dark: diffInserted,
    hcDark: diffInserted,
    hcLight: diffInserted
  }, localize(1237, "Border color for the modified text in inline edits."));
  const tabWillAcceptModifiedBorder = registerColor("inlineEdit.tabWillAcceptModifiedBorder", {
    light: darken(modifiedBorder, 0),
    dark: darken(modifiedBorder, 0),
    hcDark: darken(modifiedBorder, 0),
    hcLight: darken(modifiedBorder, 0)
  }, localize(1238, "Modified border color for the inline edits widget when tab will accept it."));
  const tabWillAcceptOriginalBorder = registerColor("inlineEdit.tabWillAcceptOriginalBorder", {
    light: darken(originalBorder, 0),
    dark: darken(originalBorder, 0),
    hcDark: darken(originalBorder, 0),
    hcLight: darken(originalBorder, 0)
  }, localize(1239, "Original border color for the inline edits widget over the original text when tab will accept it."));
  function getModifiedBorderColor(tabAction) {
    return tabAction.map((a) => a === InlineEditTabAction.Accept ? tabWillAcceptModifiedBorder : modifiedBorder);
  }
  function getOriginalBorderColor(tabAction) {
    return tabAction.map((a) => a === InlineEditTabAction.Accept ? tabWillAcceptOriginalBorder : originalBorder);
  }
  function getEditorBlendedColor(colorIdentifier, themeService) {
    let color;
    if (typeof colorIdentifier === "string") {
      color = observeColor(colorIdentifier, themeService);
    } else {
      color = colorIdentifier.map((identifier, reader) => observeColor(identifier, themeService).read(reader));
    }
    const backgroundColor = observeColor(editorBackground, themeService);
    return color.map((c, reader) => (
      /** @description makeOpaque */
      c.makeOpaque(backgroundColor.read(reader))
    ));
  }
  function observeColor(colorIdentifier, themeService) {
    return observableFromEventOpts({
      owner: { observeColor: colorIdentifier },
      equalsFn: (a, b) => a.equals(b),
      debugName: () => `observeColor(${colorIdentifier})`
    }, themeService.onDidColorThemeChange, () => {
      const color = themeService.getColorTheme().getColor(colorIdentifier);
      if (!color) {
        throw new BugIndicatingError(`Missing color: ${colorIdentifier}`);
      }
      return color;
    });
  }
  function maxContentWidthInRange(editor2, range2, reader) {
    editor2.layoutInfo.read(reader);
    editor2.value.read(reader);
    const model = editor2.model.read(reader);
    if (!model) {
      return 0;
    }
    let maxContentWidth = 0;
    editor2.scrollTop.read(reader);
    for (let i2 = range2.startLineNumber; i2 < range2.endLineNumberExclusive; i2++) {
      const column = model.getLineMaxColumn(i2);
      let lineContentWidth = editor2.editor.getOffsetForColumn(i2, column);
      if (lineContentWidth === -1) {
        const typicalHalfwidthCharacterWidth = editor2.editor.getOption(
          59
          /* EditorOption.fontInfo */
        ).typicalHalfwidthCharacterWidth;
        const approximation = column * typicalHalfwidthCharacterWidth;
        lineContentWidth = approximation;
      }
      maxContentWidth = Math.max(maxContentWidth, lineContentWidth);
    }
    const lines = range2.mapToLineArray((l) => model.getLineContent(l));
    if (maxContentWidth < 5 && lines.some((l) => l.length > 0) && model.uri.scheme !== "file") {
      console.error("unexpected width");
    }
    return maxContentWidth;
  }
  function getOffsetForPos(editor2, pos, reader) {
    editor2.layoutInfo.read(reader);
    editor2.value.read(reader);
    const model = editor2.model.read(reader);
    if (!model) {
      return 0;
    }
    editor2.scrollTop.read(reader);
    const lineContentWidth = editor2.editor.getOffsetForColumn(pos.lineNumber, pos.column);
    return lineContentWidth;
  }
  function getPrefixTrim(diffRanges, originalLinesRange, modifiedLines, editor2, reader = void 0) {
    const textModel = editor2.getModel();
    if (!textModel) {
      return { prefixTrim: 0, prefixLeftOffset: 0 };
    }
    const replacementStart = diffRanges.map((r) => r.isSingleLine() ? r.startColumn - 1 : 0);
    const originalIndents = originalLinesRange.mapToLineArray((line) => indentOfLine(textModel.getLineContent(line)));
    const modifiedIndents = modifiedLines.filter((line) => line !== "").map((line) => indentOfLine(line));
    const prefixTrim = Math.min(...replacementStart, ...originalIndents, ...modifiedIndents);
    let prefixLeftOffset;
    const startLineIndent = textModel.getLineIndentColumn(originalLinesRange.startLineNumber);
    if (startLineIndent >= prefixTrim + 1) {
      observableCodeEditor(editor2).scrollTop.read(reader);
      prefixLeftOffset = editor2.getOffsetForColumn(originalLinesRange.startLineNumber, prefixTrim + 1);
    } else if (modifiedLines.length > 0) {
      prefixLeftOffset = getContentRenderWidth(modifiedLines[0].slice(0, prefixTrim), editor2, textModel);
    } else {
      return { prefixTrim: 0, prefixLeftOffset: 0 };
    }
    return { prefixTrim, prefixLeftOffset };
  }
  function getContentRenderWidth(content, editor2, textModel) {
    const w = editor2.getOption(
      59
      /* EditorOption.fontInfo */
    ).typicalHalfwidthCharacterWidth;
    const tabSize = textModel.getOptions().tabSize * w;
    const numTabs = content.split("	").length - 1;
    const numNoneTabs = content.length - numTabs;
    return numNoneTabs * w + numTabs * tabSize;
  }
  function getEditorValidOverlayRect(editor2) {
    const contentLeft = editor2.layoutInfoContentLeft;
    const width2 = derived({ name: "editor.validOverlay.width" }, (r) => {
      const hasMinimapOnTheRight = editor2.layoutInfoMinimap.read(r).minimapLeft !== 0;
      const editorWidth = editor2.layoutInfoWidth.read(r) - contentLeft.read(r);
      if (hasMinimapOnTheRight) {
        const minimapAndScrollbarWidth = editor2.layoutInfoMinimap.read(r).minimapWidth + editor2.layoutInfoVerticalScrollbarWidth.read(r);
        return editorWidth - minimapAndScrollbarWidth;
      }
      return editorWidth;
    });
    const height = derived({ name: "editor.validOverlay.height" }, (r) => editor2.layoutInfoHeight.read(r) + editor2.contentHeight.read(r));
    return derived({ name: "editor.validOverlay" }, (r) => Rect.fromLeftTopWidthHeight(contentLeft.read(r), 0, width2.read(r), height.read(r)));
  }
  function applyEditToModifiedRangeMappings(rangeMapping, edit2) {
    const updatedMappings = [];
    for (const m of rangeMapping) {
      const updatedRange = edit2.mapRange(m.modifiedRange);
      updatedMappings.push(new RangeMapping(m.originalRange, updatedRange));
    }
    return updatedMappings;
  }
  function classNames(...classes) {
    return classes.filter((c) => typeof c === "string").join(" ");
  }
  function offsetRangeToRange(columnOffsetRange, startPos) {
    return new Range$2(startPos.lineNumber, startPos.column + columnOffsetRange.start, startPos.lineNumber, startPos.column + columnOffsetRange.endExclusive);
  }
  function getIndentationSize(line, tabSize) {
    let currentSize = 0;
    loop: for (let i2 = 0, len = line.length; i2 < len; i2++) {
      switch (line.charCodeAt(i2)) {
        case 9:
          currentSize += tabSize;
          break;
        case 32:
          currentSize++;
          break;
        default:
          break loop;
      }
    }
    return currentSize - currentSize % tabSize;
  }
  function indentSizeToIndentLength(line, indentSize, tabSize) {
    let remainingSize = indentSize - indentSize % tabSize;
    let i2 = 0;
    for (; i2 < line.length; i2++) {
      if (remainingSize === 0) {
        break;
      }
      switch (line.charCodeAt(i2)) {
        case 9:
          remainingSize -= tabSize;
          break;
        case 32:
          remainingSize--;
          break;
        default:
          throw new BugIndicatingError("Unexpected character found while calculating indent length");
      }
    }
    return i2;
  }
  function createReindentEdit(text2, range2, tabSize) {
    const newLines = splitLines(text2);
    const edits = [];
    const minIndentSize = findFirstMin(range2.mapToLineArray((l) => getIndentationSize(newLines[l - 1], tabSize)), numberComparator);
    range2.forEach((lineNumber) => {
      const indentLength = indentSizeToIndentLength(newLines[lineNumber - 1], minIndentSize, tabSize);
      edits.push(new TextReplacement(offsetRangeToRange(new OffsetRange(0, indentLength), new Position$1(lineNumber, 1)), ""));
    });
    return new TextEdit(edits);
  }
  class PathBuilder {
    constructor() {
      this._data = "";
    }
    moveTo(point) {
      this._data += `M ${point.x} ${point.y} `;
      return this;
    }
    lineTo(point) {
      this._data += `L ${point.x} ${point.y} `;
      return this;
    }
    build() {
      return this._data;
    }
  }
  function mapOutFalsy(obs) {
    const nonUndefinedObs = derivedObservableWithCache(void 0, (reader, lastValue) => obs.read(reader) || lastValue);
    return derivedOpts({
      debugName: () => `${obs.debugName}.mapOutFalsy`
    }, (reader) => {
      nonUndefinedObs.read(reader);
      const val = obs.read(reader);
      if (!val) {
        return void 0;
      }
      return nonUndefinedObs;
    });
  }
  function rectToProps(fn, debugLocation = DebugLocation.ofCaller()) {
    return {
      left: derived({ name: "editor.validOverlay.left" }, (reader) => (
        /** @description left */
        fn(reader).left
      ), debugLocation),
      top: derived({ name: "editor.validOverlay.top" }, (reader) => (
        /** @description top */
        fn(reader).top
      ), debugLocation),
      width: derived({ name: "editor.validOverlay.width" }, (reader) => (
        /** @description width */
        fn(reader).right - fn(reader).left
      ), debugLocation),
      height: derived({ name: "editor.validOverlay.height" }, (reader) => (
        /** @description height */
        fn(reader).bottom - fn(reader).top
      ), debugLocation)
    };
  }
  var __decorate$1g = 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$1f = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  let GutterIndicatorMenuContent = class GutterIndicatorMenuContent {
    constructor(_model, _close, _editorObs, _contextKeyService, _keybindingService, _commandService) {
      this._model = _model;
      this._close = _close;
      this._editorObs = _editorObs;
      this._contextKeyService = _contextKeyService;
      this._keybindingService = _keybindingService;
      this._commandService = _commandService;
      this._inlineEditsShowCollapsed = this._editorObs.getOption(
        71
        /* EditorOption.inlineSuggest */
      ).map((s) => s.edits.showCollapsed);
    }
    toDisposableLiveElement() {
      return this._createHoverContent().toDisposableLiveElement();
    }
    _createHoverContent() {
      const activeElement = observableValue("active", void 0);
      const createOptionArgs = (options) => {
        return {
          title: options.title,
          icon: options.icon,
          keybinding: typeof options.commandId === "string" ? this._getKeybinding(options.commandArgs ? void 0 : options.commandId) : derived(this, (reader) => typeof options.commandId === "string" ? void 0 : this._getKeybinding(options.commandArgs ? void 0 : options.commandId.read(reader)).read(reader)),
          isActive: activeElement.map((v) => v === options.id),
          onHoverChange: (v) => activeElement.set(v ? options.id : void 0, void 0),
          onAction: () => {
            this._close(true);
            return this._commandService.executeCommand(typeof options.commandId === "string" ? options.commandId : options.commandId.get(), ...options.commandArgs ?? []);
          }
        };
      };
      const title = header(this._model.displayName);
      const gotoAndAccept = option(createOptionArgs({
        id: "gotoAndAccept",
        title: `${localize(1212, "Go To")} / ${localize(1213, "Accept")}`,
        icon: Codicon.check,
        commandId: inlineSuggestCommitId
      }));
      const reject = option(createOptionArgs({
        id: "reject",
        title: localize(1214, "Reject"),
        icon: Codicon.close,
        commandId: hideInlineCompletionId
      }));
      const extensionCommands = this._model.extensionCommands.map((c, idx) => option(createOptionArgs({
        id: c.command.id + "_" + idx,
        title: c.command.title,
        icon: c.icon ?? Codicon.symbolEvent,
        commandId: c.command.id,
        commandArgs: c.command.arguments
      })));
      const toggleCollapsedMode = this._inlineEditsShowCollapsed.map((showCollapsed) => showCollapsed ? option(createOptionArgs({
        id: "showExpanded",
        title: localize(1215, "Show Expanded"),
        icon: Codicon.expandAll,
        commandId: toggleShowCollapsedId
      })) : option(createOptionArgs({
        id: "showCollapsed",
        title: localize(1216, "Show Collapsed"),
        icon: Codicon.collapseAll,
        commandId: toggleShowCollapsedId
      })));
      const snooze = option(createOptionArgs({
        id: "snooze",
        title: localize(1217, "Snooze"),
        icon: Codicon.bellSlash,
        commandId: "editor.action.inlineSuggest.snooze"
      }));
      const settings = option(createOptionArgs({
        id: "settings",
        title: localize(1218, "Settings"),
        icon: Codicon.gear,
        commandId: "workbench.action.openSettings",
        commandArgs: ["@tag:nextEditSuggestions"]
      }));
      const actions = this._model.action ? [this._model.action] : [];
      const actionBarFooter = actions.length > 0 ? actionBar(actions.map((action) => ({
        id: action.id,
        label: action.title + "...",
        enabled: true,
        run: () => this._commandService.executeCommand(action.id, ...action.arguments ?? []),
        class: void 0,
        tooltip: action.tooltip ?? action.title
      })), {
        hoverDelegate: nativeHoverDelegate
        /* unable to show hover inside another hover */
      }) : void 0;
      return hoverContent([
        title,
        gotoAndAccept,
        reject,
        toggleCollapsedMode,
        extensionCommands.length ? separator() : void 0,
        snooze,
        settings,
        ...extensionCommands,
        actionBarFooter ? separator() : void 0,
        actionBarFooter
      ]);
    }
    _getKeybinding(commandId) {
      if (!commandId) {
        return constObservable(void 0);
      }
      return observableFromEvent(this._contextKeyService.onDidChangeContext, () => this._keybindingService.lookupKeybinding(commandId));
    }
  };
  GutterIndicatorMenuContent = __decorate$1g([
    __param$1f(3, IContextKeyService),
    __param$1f(4, IKeybindingService),
    __param$1f(5, ICommandService)
  ], GutterIndicatorMenuContent);
  function hoverContent(content) {
    return n.div({
      class: "content",
      style: {
        margin: 4,
        minWidth: 180
      }
    }, content);
  }
  function header(title) {
    return n.div({
      class: "header",
      style: {
        color: asCssVariable(descriptionForeground),
        fontSize: "13px",
        fontWeight: "600",
        padding: "0 4px",
        lineHeight: 28
      }
    }, [title]);
  }
  function option(props) {
    return derived({ name: "inlineEdits.option" }, (_reader) => n.div({
      class: ["monaco-menu-option", props.isActive?.map((v) => v && "active")],
      onmouseenter: () => props.onHoverChange?.(true),
      onmouseleave: () => props.onHoverChange?.(false),
      onclick: props.onAction,
      onkeydown: (e) => {
        if (e.key === "Enter") {
          props.onAction?.();
        }
      },
      tabIndex: 0,
      style: {
        borderRadius: 3
        // same as hover widget border radius
      }
    }, [
      n.elem("span", {
        style: {
          fontSize: 16,
          display: "flex"
        }
      }, [ThemeIcon.isThemeIcon(props.icon) ? renderIcon(props.icon) : props.icon.map((icon) => renderIcon(icon))]),
      n.elem("span", {}, [props.title]),
      n.div({
        style: { marginLeft: "auto" },
        ref: (elem) => {
          const keybindingLabel = _reader.store.add(new KeybindingLabel(elem, OS, {
            disableTitle: true,
            ...defaultKeybindingLabelStyles,
            keybindingLabelShadow: void 0,
            keybindingLabelForeground: asCssVariable(descriptionForeground),
            keybindingLabelBackground: "transparent",
            keybindingLabelBorder: "transparent",
            keybindingLabelBottomBorder: void 0
          }));
          _reader.store.add(autorun((reader) => {
            keybindingLabel.set(props.keybinding.read(reader));
          }));
        }
      })
    ]));
  }
  function actionBar(actions, options) {
    return derived({ name: "inlineEdits.actionBar" }, (_reader) => n.div({
      class: ["action-widget-action-bar"],
      style: {
        padding: "3px 24px"
      }
    }, [
      n.div({
        ref: (elem) => {
          const actionBar2 = _reader.store.add(new ActionBar(elem, options));
          actionBar2.push(actions, { icon: false, label: true });
        }
      })
    ]));
  }
  function separator() {
    return n.div({
      id: "inline-edit-gutter-indicator-menu-separator",
      class: "menu-separator",
      style: {
        color: asCssVariable(editorActionListForeground),
        padding: "2px 0"
      }
    }, n.div({
      style: {
        borderBottom: `1px solid ${asCssVariable(editorHoverBorder)}`
      }
    }));
  }
  var __decorate$1f = 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$1e = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  let InlineEditsGutterIndicator = class InlineEditsGutterIndicator extends Disposable {
    get model() {
      const model = this._model.get();
      if (!model) {
        throw new BugIndicatingError("Inline Edit Model not available");
      }
      return model;
    }
    constructor(_editorObs, _originalRange, _verticalOffset, _model, _isHoveringOverInlineEdit, _focusIsInMenu, _hoverService, _instantiationService, _accessibilityService, themeService) {
      super();
      this._editorObs = _editorObs;
      this._originalRange = _originalRange;
      this._verticalOffset = _verticalOffset;
      this._model = _model;
      this._isHoveringOverInlineEdit = _isHoveringOverInlineEdit;
      this._focusIsInMenu = _focusIsInMenu;
      this._hoverService = _hoverService;
      this._instantiationService = _instantiationService;
      this._accessibilityService = _accessibilityService;
      this._tabAction = derived(this, (reader) => {
        const model = this._model.read(reader);
        if (!model) {
          return InlineEditTabAction.Inactive;
        }
        return model.tabAction.read(reader);
      });
      this._hoverVisible = observableValue(this, false);
      this.isHoverVisible = this._hoverVisible;
      this._isHoveredOverIcon = observableValue(this, false);
      this._isHoveredOverIconDebounced = debouncedObservable(this._isHoveredOverIcon, 100);
      this.isHoveredOverIcon = this._isHoveredOverIconDebounced;
      this._isHoveredOverInlineEditDebounced = debouncedObservable(this._isHoveringOverInlineEdit, 100);
      this._gutterIndicatorStyles = this._tabAction.map(this, (v, reader) => {
        switch (v) {
          case InlineEditTabAction.Inactive:
            return {
              background: getEditorBlendedColor(inlineEditIndicatorSecondaryBackground, themeService).read(reader).toString(),
              foreground: getEditorBlendedColor(inlineEditIndicatorSecondaryForeground, themeService).read(reader).toString(),
              border: getEditorBlendedColor(inlineEditIndicatorSecondaryBorder, themeService).read(reader).toString()
            };
          case InlineEditTabAction.Jump:
            return {
              background: getEditorBlendedColor(inlineEditIndicatorPrimaryBackground, themeService).read(reader).toString(),
              foreground: getEditorBlendedColor(inlineEditIndicatorPrimaryForeground, themeService).read(reader).toString(),
              border: getEditorBlendedColor(inlineEditIndicatorPrimaryBorder, themeService).read(reader).toString()
            };
          case InlineEditTabAction.Accept:
            return {
              background: getEditorBlendedColor(inlineEditIndicatorsuccessfulBackground, themeService).read(reader).toString(),
              foreground: getEditorBlendedColor(inlineEditIndicatorsuccessfulForeground, themeService).read(reader).toString(),
              border: getEditorBlendedColor(inlineEditIndicatorsuccessfulBorder, themeService).read(reader).toString()
            };
          default:
            assertNever();
        }
      });
      this._originalRangeObs = mapOutFalsy(this._originalRange);
      this._state = derived(this, (reader) => {
        const range2 = this._originalRangeObs.read(reader);
        if (!range2) {
          return void 0;
        }
        return {
          range: range2,
          lineOffsetRange: this._editorObs.observeLineOffsetRange(range2, reader.store)
        };
      });
      this._stickyScrollController = StickyScrollController.get(this._editorObs.editor);
      this._stickyScrollHeight = this._stickyScrollController ? observableFromEvent(this._stickyScrollController.onDidChangeStickyScrollHeight, () => this._stickyScrollController.stickyScrollWidgetHeight) : constObservable(0);
      this._lineNumberToRender = derived(this, (reader) => {
        if (this._verticalOffset.read(reader) !== 0) {
          return "";
        }
        const lineNumber = this._originalRange.read(reader)?.startLineNumber;
        const lineNumberOptions = this._editorObs.getOption(
          76
          /* EditorOption.lineNumbers */
        ).read(reader);
        if (lineNumber === void 0 || lineNumberOptions.renderType === 0) {
          return "";
        }
        if (lineNumberOptions.renderType === 3) {
          const cursorPosition = this._editorObs.cursorPosition.read(reader);
          if (lineNumber % 10 === 0 || cursorPosition && cursorPosition.lineNumber === lineNumber) {
            return lineNumber.toString();
          }
          return "";
        }
        if (lineNumberOptions.renderType === 2) {
          const cursorPosition = this._editorObs.cursorPosition.read(reader);
          if (!cursorPosition) {
            return "";
          }
          const relativeLineNumber = Math.abs(lineNumber - cursorPosition.lineNumber);
          if (relativeLineNumber === 0) {
            return lineNumber.toString();
          }
          return relativeLineNumber.toString();
        }
        if (lineNumberOptions.renderType === 4) {
          if (lineNumberOptions.renderFn) {
            return lineNumberOptions.renderFn(lineNumber);
          }
          return "";
        }
        return lineNumber.toString();
      });
      this._availableWidthForIcon = derived(this, (reader) => {
        const textModel = this._editorObs.editor.getModel();
        const editor2 = this._editorObs.editor;
        const layout2 = this._editorObs.layoutInfo.read(reader);
        const gutterWidth = layout2.decorationsLeft + layout2.decorationsWidth - layout2.glyphMarginLeft;
        if (!textModel || gutterWidth <= 0) {
          return () => 0;
        }
        if (layout2.lineNumbersLeft === 0) {
          return () => gutterWidth;
        }
        const lineNumberOptions = this._editorObs.getOption(
          76
          /* EditorOption.lineNumbers */
        ).read(reader);
        if (lineNumberOptions.renderType === 2 || /* likely to flicker */
        lineNumberOptions.renderType === 0) {
          return () => gutterWidth;
        }
        const w = editor2.getOption(
          59
          /* EditorOption.fontInfo */
        ).typicalHalfwidthCharacterWidth;
        const rightOfLineNumber = layout2.lineNumbersLeft + layout2.lineNumbersWidth;
        const totalLines = textModel.getLineCount();
        const totalLinesDigits = (totalLines + 1).toString().length;
        const offsetDigits = [];
        for (let digits = 1; digits <= totalLinesDigits; digits++) {
          const firstLineNumberWithDigitCount = 10 ** (digits - 1);
          const topOfLineNumber = editor2.getTopForLineNumber(firstLineNumberWithDigitCount);
          const digitsWidth = digits * w;
          const usableWidthLeftOfLineNumber = Math.min(gutterWidth, Math.max(0, rightOfLineNumber - digitsWidth - layout2.glyphMarginLeft));
          offsetDigits.push({ firstLineNumberWithDigitCount, topOfLineNumber, usableWidthLeftOfLineNumber });
        }
        return (topOffset) => {
          for (let i2 = offsetDigits.length - 1; i2 >= 0; i2--) {
            if (topOffset >= offsetDigits[i2].topOfLineNumber) {
              return offsetDigits[i2].usableWidthLeftOfLineNumber;
            }
          }
          throw new BugIndicatingError("Could not find avilable width for icon");
        };
      });
      this._layout = derived(this, (reader) => {
        const s = this._state.read(reader);
        if (!s) {
          return void 0;
        }
        const layout2 = this._editorObs.layoutInfo.read(reader);
        const lineHeight = this._editorObs.observeLineHeightForLine(s.range.map((r) => r.startLineNumber)).read(reader);
        const gutterViewPortPadding = 2;
        const gutterWidthWithoutPadding = layout2.decorationsLeft + layout2.decorationsWidth - layout2.glyphMarginLeft - 2 * gutterViewPortPadding;
        const gutterHeightWithoutPadding = layout2.height - 2 * gutterViewPortPadding;
        const gutterViewPortWithStickyScroll = Rect.fromLeftTopWidthHeight(gutterViewPortPadding, gutterViewPortPadding, gutterWidthWithoutPadding, gutterHeightWithoutPadding);
        const gutterViewPortWithoutStickyScrollWithoutPaddingTop = gutterViewPortWithStickyScroll.withTop(this._stickyScrollHeight.read(reader));
        const gutterViewPortWithoutStickyScroll = gutterViewPortWithStickyScroll.withTop(gutterViewPortWithoutStickyScrollWithoutPaddingTop.top + gutterViewPortPadding);
        const verticalEditRange = s.lineOffsetRange.read(reader);
        const gutterEditArea = Rect.fromRanges(OffsetRange.fromTo(gutterViewPortWithoutStickyScroll.left, gutterViewPortWithoutStickyScroll.right), verticalEditRange);
        const pillHeight = lineHeight;
        const pillOffset = this._verticalOffset.read(reader);
        const pillFullyDockedRect = gutterEditArea.withHeight(pillHeight).translateY(pillOffset);
        const pillIsFullyDocked = gutterViewPortWithoutStickyScrollWithoutPaddingTop.containsRect(pillFullyDockedRect);
        const iconNoneDocked = this._tabAction.map((action) => action === InlineEditTabAction.Accept ? Codicon.keyboardTab : Codicon.arrowRight);
        const iconDocked = derived(this, (reader2) => {
          if (this._isHoveredOverIconDebounced.read(reader2) || this._isHoveredOverInlineEditDebounced.read(reader2)) {
            return Codicon.check;
          }
          if (this._tabAction.read(reader2) === InlineEditTabAction.Accept) {
            return Codicon.keyboardTab;
          }
          const cursorLineNumber = this._editorObs.cursorLineNumber.read(reader2) ?? 0;
          const editStartLineNumber = s.range.read(reader2).startLineNumber;
          return cursorLineNumber <= editStartLineNumber ? Codicon.keyboardTabAbove : Codicon.keyboardTabBelow;
        });
        const idealIconWidth = 22;
        const minimalIconWidth = 16;
        const iconWidth = (pillRect2) => {
          const availableWidth = this._availableWidthForIcon.read(void 0)(pillRect2.bottom + this._editorObs.editor.getScrollTop()) - gutterViewPortPadding;
          return Math.max(Math.min(availableWidth, idealIconWidth), minimalIconWidth);
        };
        if (pillIsFullyDocked) {
          const pillRect2 = pillFullyDockedRect;
          let lineNumberWidth;
          if (layout2.lineNumbersWidth === 0) {
            lineNumberWidth = Math.min(Math.max(layout2.lineNumbersLeft - gutterViewPortWithStickyScroll.left, 0), pillRect2.width - idealIconWidth);
          } else {
            lineNumberWidth = Math.max(layout2.lineNumbersLeft + layout2.lineNumbersWidth - gutterViewPortWithStickyScroll.left, 0);
          }
          const lineNumberRect = pillRect2.withWidth(lineNumberWidth);
          const iconWidth2 = Math.max(Math.min(layout2.decorationsWidth, idealIconWidth), minimalIconWidth);
          const iconRect2 = pillRect2.withWidth(iconWidth2).translateX(lineNumberWidth);
          return {
            gutterEditArea,
            icon: iconDocked,
            iconDirection: "right",
            iconRect: iconRect2,
            pillRect: pillRect2,
            lineNumberRect
          };
        }
        const pillPartiallyDockedPossibleArea = gutterViewPortWithStickyScroll.intersect(gutterEditArea);
        const pillIsPartiallyDocked = pillPartiallyDockedPossibleArea && pillPartiallyDockedPossibleArea.height >= pillHeight;
        if (pillIsPartiallyDocked) {
          const pillRectMoved2 = pillFullyDockedRect.moveToBeContainedIn(gutterViewPortWithoutStickyScroll).moveToBeContainedIn(pillPartiallyDockedPossibleArea);
          const pillRect2 = pillRectMoved2.withWidth(iconWidth(pillRectMoved2));
          const iconRect2 = pillRect2;
          return {
            gutterEditArea,
            icon: iconDocked,
            iconDirection: "right",
            iconRect: iconRect2,
            pillRect: pillRect2
          };
        }
        const pillRectMoved = pillFullyDockedRect.moveToBeContainedIn(gutterViewPortWithStickyScroll);
        const pillRect = pillRectMoved.withWidth(iconWidth(pillRectMoved));
        const iconRect = pillRect;
        const iconDirection = pillRect.top < pillFullyDockedRect.top ? "top" : "bottom";
        return {
          gutterEditArea,
          icon: iconNoneDocked,
          iconDirection,
          iconRect,
          pillRect
        };
      });
      this._iconRef = n.ref();
      this.isVisible = this._layout.map((l) => !!l);
      this._indicator = n.div({
        class: "inline-edits-view-gutter-indicator",
        onclick: () => {
          const layout2 = this._layout.get();
          const acceptOnClick = layout2?.icon.get() === Codicon.check;
          this._editorObs.editor.focus();
          if (acceptOnClick) {
            this.model.accept();
          } else {
            this.model.jump();
          }
        },
        tabIndex: 0,
        style: {
          position: "absolute",
          overflow: "visible"
        }
      }, mapOutFalsy(this._layout).map((layout2) => !layout2 ? [] : [
        n.div({
          style: {
            position: "absolute",
            background: asCssVariable(inlineEditIndicatorBackground),
            borderRadius: "4px",
            ...rectToProps((reader) => layout2.read(reader).gutterEditArea)
          }
        }),
        n.div({
          class: "icon",
          ref: this._iconRef,
          onmouseenter: () => {
            this._showHover();
          },
          style: {
            cursor: "pointer",
            zIndex: "20",
            position: "absolute",
            backgroundColor: this._gutterIndicatorStyles.map((v) => v.background),
            // eslint-disable-next-line local/code-no-any-casts
            ["--vscodeIconForeground"]: this._gutterIndicatorStyles.map((v) => v.foreground),
            border: this._gutterIndicatorStyles.map((v) => `1px solid ${v.border}`),
            boxSizing: "border-box",
            borderRadius: "4px",
            display: "flex",
            justifyContent: "flex-end",
            transition: "background-color 0.2s ease-in-out, width 0.2s ease-in-out",
            ...rectToProps((reader) => layout2.read(reader).pillRect)
          }
        }, [
          n.div({
            className: "line-number",
            style: {
              lineHeight: layout2.map((l) => l.lineNumberRect ? l.lineNumberRect.height : 0),
              display: layout2.map((l) => l.lineNumberRect ? "flex" : "none"),
              alignItems: "center",
              justifyContent: "flex-end",
              width: layout2.map((l) => l.lineNumberRect ? l.lineNumberRect.width : 0),
              height: "100%",
              color: this._gutterIndicatorStyles.map((v) => v.foreground)
            }
          }, this._lineNumberToRender),
          n.div({
            style: {
              rotate: layout2.map((l) => `${getRotationFromDirection(l.iconDirection)}deg`),
              transition: "rotate 0.2s ease-in-out",
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
              height: "100%",
              marginRight: layout2.map((l) => l.pillRect.width - l.iconRect.width - (l.lineNumberRect?.width ?? 0)),
              width: layout2.map((l) => l.iconRect.width)
            }
          }, [
            layout2.map((l, reader) => renderIcon(l.icon.read(reader)))
          ])
        ])
      ])).keepUpdated(this._store);
      this._register(this._editorObs.createOverlayWidget({
        domNode: this._indicator.element,
        position: constObservable(null),
        allowEditorOverflow: false,
        minContentWidthInPx: constObservable(0)
      }));
      this._register(this._editorObs.editor.onMouseMove((e) => {
        const state = this._state.get();
        if (state === void 0) {
          return;
        }
        const el = this._iconRef.element;
        const rect = el.getBoundingClientRect();
        const rectangularArea = Rect.fromLeftTopWidthHeight(rect.left, rect.top, rect.width, rect.height);
        const point = new Point(e.event.posx, e.event.posy);
        this._isHoveredOverIcon.set(rectangularArea.containsPoint(point), void 0);
      }));
      this._register(this._editorObs.editor.onDidScrollChange(() => {
        this._isHoveredOverIcon.set(false, void 0);
      }));
      this._register(runOnChange(this._isHoveredOverInlineEditDebounced, (isHovering) => {
        if (isHovering) {
          this.triggerAnimation();
        }
      }));
      this._register(autorun((reader) => {
        this._indicator.readEffect(reader);
        if (this._indicator.element) {
          this._editorObs.editor.applyFontInfo(this._indicator.element);
        }
      }));
    }
    triggerAnimation() {
      if (this._accessibilityService.isMotionReduced()) {
        return new Animation(null, null).finished;
      }
      const animation = this._iconRef.element.animate([
        {
          outline: `2px solid ${this._gutterIndicatorStyles.map((v) => v.border).get()}`,
          outlineOffset: "-1px",
          offset: 0
        },
        {
          outline: `2px solid transparent`,
          outlineOffset: "10px",
          offset: 1
        }
      ], { duration: 500 });
      return animation.finished;
    }
    _showHover() {
      if (this._hoverVisible.get()) {
        return;
      }
      const disposableStore = new DisposableStore();
      const content = disposableStore.add(this._instantiationService.createInstance(GutterIndicatorMenuContent, this.model, (focusEditor) => {
        if (focusEditor) {
          this._editorObs.editor.focus();
        }
        h2?.dispose();
      }, this._editorObs).toDisposableLiveElement());
      const focusTracker = disposableStore.add(trackFocus(content.element));
      disposableStore.add(focusTracker.onDidBlur(() => this._focusIsInMenu.set(false, void 0)));
      disposableStore.add(focusTracker.onDidFocus(() => this._focusIsInMenu.set(true, void 0)));
      disposableStore.add(toDisposable(() => this._focusIsInMenu.set(false, void 0)));
      const h2 = this._hoverService.showInstantHover({
        target: this._iconRef.element,
        content: content.element
      });
      if (h2) {
        this._hoverVisible.set(true, void 0);
        disposableStore.add(this._editorObs.editor.onDidScrollChange(() => h2.dispose()));
        disposableStore.add(h2.onDispose(() => {
          this._hoverVisible.set(false, void 0);
          disposableStore.dispose();
        }));
      } else {
        disposableStore.dispose();
      }
    }
  };
  InlineEditsGutterIndicator = __decorate$1f([
    __param$1e(6, IHoverService),
    __param$1e(7, IInstantiationService),
    __param$1e(8, IAccessibilityService),
    __param$1e(9, IThemeService)
  ], InlineEditsGutterIndicator);
  function getRotationFromDirection(direction) {
    switch (direction) {
      case "top":
        return 90;
      case "bottom":
        return -90;
      case "right":
        return 0;
    }
  }
  var __decorate$1e = 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$1d = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  var UserKind;
  (function(UserKind2) {
    UserKind2["FirstTime"] = "firstTime";
    UserKind2["SecondTime"] = "secondTime";
    UserKind2["Active"] = "active";
  })(UserKind || (UserKind = {}));
  let InlineEditsOnboardingExperience = class InlineEditsOnboardingExperience extends Disposable {
    constructor(_host, _model, _indicator, _collapsedView, _storageService, _configurationService) {
      super();
      this._host = _host;
      this._model = _model;
      this._indicator = _indicator;
      this._collapsedView = _collapsedView;
      this._storageService = _storageService;
      this._configurationService = _configurationService;
      this._disposables = this._register(new MutableDisposable());
      this._setupDone = observableValue({ name: "setupDone" }, false);
      this._activeCompletionId = derived((reader) => {
        const model = this._model.read(reader);
        if (!model) {
          return void 0;
        }
        if (!this._setupDone.read(reader)) {
          return void 0;
        }
        const indicator = this._indicator.read(reader);
        if (!indicator || !indicator.isVisible.read(reader)) {
          return void 0;
        }
        return model.inlineEdit.inlineCompletion.identity.id;
      });
      this._register(this._initializeDebugSetting());
      this._disposables.value = this.setupNewUserExperience();
      this._setupDone.set(true, void 0);
    }
    setupNewUserExperience() {
      if (this.getNewUserType() === UserKind.Active) {
        return void 0;
      }
      const disposableStore = new DisposableStore();
      let userHasHoveredOverIcon = false;
      let inlineEditHasBeenAccepted = false;
      let firstTimeUserAnimationCount = 0;
      let secondTimeUserAnimationCount = 0;
      disposableStore.add(runOnChangeWithCancellationToken(this._activeCompletionId, async (id, _, __2, token) => {
        if (id === void 0) {
          return;
        }
        let userType = this.getNewUserType();
        switch (userType) {
          case UserKind.FirstTime: {
            if (firstTimeUserAnimationCount++ >= 5 || userHasHoveredOverIcon) {
              userType = UserKind.SecondTime;
              this.setNewUserType(userType);
            }
            break;
          }
          case UserKind.SecondTime: {
            if (secondTimeUserAnimationCount++ >= 3 && inlineEditHasBeenAccepted) {
              userType = UserKind.Active;
              this.setNewUserType(userType);
            }
            break;
          }
        }
        switch (userType) {
          case UserKind.FirstTime: {
            for (let i2 = 0; i2 < 3 && !token.isCancellationRequested; i2++) {
              await this._indicator.get()?.triggerAnimation();
              await timeout(500);
            }
            break;
          }
          case UserKind.SecondTime: {
            this._indicator.get()?.triggerAnimation();
            break;
          }
        }
      }));
      disposableStore.add(autorun((reader) => {
        if (this._collapsedView.isVisible.read(reader)) {
          if (this.getNewUserType() !== UserKind.Active) {
            this._collapsedView.triggerAnimation();
          }
        }
      }));
      disposableStore.add(autorunWithStore((reader, store) => {
        const indicator = this._indicator.read(reader);
        if (!indicator) {
          return;
        }
        store.add(runOnChange(indicator.isHoveredOverIcon, async (isHovered) => {
          if (isHovered) {
            userHasHoveredOverIcon = true;
          }
        }));
      }));
      disposableStore.add(autorunWithStore((reader, store) => {
        const host = this._host.read(reader);
        if (!host) {
          return;
        }
        store.add(host.onDidAccept(() => {
          inlineEditHasBeenAccepted = true;
        }));
      }));
      return disposableStore;
    }
    getNewUserType() {
      return this._storageService.get("inlineEditsGutterIndicatorUserKind", -1, UserKind.FirstTime);
    }
    setNewUserType(value) {
      switch (value) {
        case UserKind.FirstTime:
          throw new BugIndicatingError("UserKind should not be set to first time");
        case UserKind.SecondTime:
          break;
        case UserKind.Active:
          this._disposables.clear();
          break;
      }
      this._storageService.store(
        "inlineEditsGutterIndicatorUserKind",
        value,
        -1,
        0
        /* StorageTarget.USER */
      );
    }
    _initializeDebugSetting() {
      const hiddenDebugSetting = "editor.inlineSuggest.edits.resetNewUserExperience";
      if (this._configurationService.getValue(hiddenDebugSetting)) {
        this._storageService.remove(
          "inlineEditsGutterIndicatorUserKind",
          -1
          /* StorageScope.APPLICATION */
        );
      }
      const disposable = this._configurationService.onDidChangeConfiguration((e) => {
        if (e.affectsConfiguration(hiddenDebugSetting) && this._configurationService.getValue(hiddenDebugSetting)) {
          this._storageService.remove(
            "inlineEditsGutterIndicatorUserKind",
            -1
            /* StorageScope.APPLICATION */
          );
          this._disposables.value = this.setupNewUserExperience();
        }
      });
      return disposable;
    }
  };
  InlineEditsOnboardingExperience = __decorate$1e([
    __param$1d(4, IStorageService),
    __param$1d(5, IConfigurationService)
  ], InlineEditsOnboardingExperience);
  var __decorate$1d = 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$1c = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  let InlineEditsCollapsedView = class InlineEditsCollapsedView extends Disposable {
    constructor(_editor, _edit, _accessibilityService) {
      super();
      this._editor = _editor;
      this._edit = _edit;
      this._accessibilityService = _accessibilityService;
      this._onDidClick = this._register(new Emitter$1());
      this.onDidClick = this._onDidClick.event;
      this._iconRef = n.ref();
      this.isHovered = constObservable(false);
      this._editorObs = observableCodeEditor(this._editor);
      const firstEdit = this._edit.map((inlineEdit) => inlineEdit?.edit.replacements[0] ?? null);
      const startPosition = firstEdit.map((edit2) => edit2 ? singleTextRemoveCommonPrefix(edit2, this._editor.getModel()).range.getStartPosition() : null);
      const observedStartPoint = this._editorObs.observePosition(startPosition, this._store);
      const startPoint = derived((reader) => {
        const point = observedStartPoint.read(reader);
        if (!point) {
          return null;
        }
        const contentLeft = this._editorObs.layoutInfoContentLeft.read(reader);
        const scrollLeft = this._editorObs.scrollLeft.read(reader);
        return new Point(contentLeft + point.x - scrollLeft, point.y);
      });
      const overlayElement = n.div({
        class: "inline-edits-collapsed-view",
        style: {
          position: "absolute",
          overflow: "visible",
          top: "0px",
          left: "0px",
          display: "block"
        }
      }, [
        [this.getCollapsedIndicator(startPoint)]
      ]).keepUpdated(this._store).element;
      this._register(this._editorObs.createOverlayWidget({
        domNode: overlayElement,
        position: constObservable(null),
        allowEditorOverflow: false,
        minContentWidthInPx: constObservable(0)
      }));
      this.isVisible = this._edit.map((inlineEdit, reader) => !!inlineEdit && startPoint.read(reader) !== null);
    }
    triggerAnimation() {
      if (this._accessibilityService.isMotionReduced()) {
        return new Animation(null, null).finished;
      }
      const animation = this._iconRef.element.animate([
        { offset: 0, transform: "translateY(-3px)" },
        { offset: 0.2, transform: "translateY(1px)" },
        { offset: 0.36, transform: "translateY(-1px)" },
        { offset: 0.52, transform: "translateY(1px)" },
        { offset: 0.68, transform: "translateY(-1px)" },
        { offset: 0.84, transform: "translateY(1px)" },
        { offset: 1, transform: "translateY(0px)" }
      ], { duration: 2e3 });
      return animation.finished;
    }
    getCollapsedIndicator(startPoint) {
      const contentLeft = this._editorObs.layoutInfoContentLeft;
      const startPointTranslated = startPoint.map((p, reader) => p ? p.deltaX(-contentLeft.read(reader)) : null);
      const iconPath = this.createIconPath(startPointTranslated);
      return n.svg({
        class: "collapsedView",
        ref: this._iconRef,
        style: {
          position: "absolute",
          ...rectToProps((r) => getEditorValidOverlayRect(this._editorObs).read(r)),
          overflow: "hidden",
          pointerEvents: "none"
        }
      }, [
        n.svgElem("path", {
          class: "collapsedViewPath",
          d: iconPath,
          fill: asCssVariable(inlineEditIndicatorPrimaryBorder)
        })
      ]);
    }
    createIconPath(indicatorPoint) {
      const width2 = 6;
      const triangleHeight = 3;
      const baseHeight = 1;
      return indicatorPoint.map((point) => {
        if (!point) {
          return new PathBuilder().build();
        }
        const baseTopLeft = point.deltaX(-width2 / 2).deltaY(-baseHeight);
        const baseTopRight = baseTopLeft.deltaX(width2);
        const baseBottomLeft = baseTopLeft.deltaY(baseHeight);
        const baseBottomRight = baseTopRight.deltaY(baseHeight);
        const triangleBottomCenter = baseBottomLeft.deltaX(width2 / 2).deltaY(triangleHeight);
        return new PathBuilder().moveTo(baseTopLeft).lineTo(baseTopRight).lineTo(baseBottomRight).lineTo(triangleBottomCenter).lineTo(baseBottomLeft).lineTo(baseTopLeft).build();
      });
    }
  };
  InlineEditsCollapsedView = __decorate$1d([
    __param$1c(2, IAccessibilityService)
  ], InlineEditsCollapsedView);
  var __decorate$1c = 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$1b = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  const MIN_END_OF_LINE_PADDING = 14;
  const PADDING_VERTICALLY = 0;
  const PADDING_HORIZONTALLY = 4;
  const HORIZONTAL_OFFSET_WHEN_ABOVE_BELOW = 4;
  const VERTICAL_OFFSET_WHEN_ABOVE_BELOW = 2;
  let InlineEditsCustomView = class InlineEditsCustomView extends Disposable {
    constructor(_editor, displayLocation, tabAction, themeService, _languageService) {
      super();
      this._editor = _editor;
      this._languageService = _languageService;
      this._onDidClick = this._register(new Emitter$1());
      this.onDidClick = this._onDidClick.event;
      this._isHovered = observableValue(this, false);
      this.isHovered = this._isHovered;
      this._viewRef = n.ref();
      this._editorObs = observableCodeEditor(this._editor);
      const styles = tabAction.map((v, reader) => {
        let border;
        switch (v) {
          case InlineEditTabAction.Inactive:
            border = inlineEditIndicatorSecondaryBackground;
            break;
          case InlineEditTabAction.Jump:
            border = inlineEditIndicatorPrimaryBackground;
            break;
          case InlineEditTabAction.Accept:
            border = inlineEditIndicatorsuccessfulBackground;
            break;
        }
        return {
          border: getEditorBlendedColor(border, themeService).read(reader).toString(),
          background: asCssVariable(editorBackground)
        };
      });
      const state = displayLocation.map((dl) => dl ? this.getState(dl) : void 0);
      const view = state.map((s) => s ? this.getRendering(s, styles) : void 0);
      this.minEditorScrollHeight = derived(this, (reader) => {
        const s = state.read(reader);
        if (!s) {
          return 0;
        }
        return s.rect.read(reader).bottom + this._editor.getScrollTop();
      });
      const overlay = n.div({
        class: "inline-edits-custom-view",
        style: {
          position: "absolute",
          overflow: "visible",
          top: "0px",
          left: "0px",
          display: "block"
        }
      }, [view]).keepUpdated(this._store);
      this._register(this._editorObs.createOverlayWidget({
        domNode: overlay.element,
        position: constObservable(null),
        allowEditorOverflow: false,
        minContentWidthInPx: derivedObservableWithCache(this, (reader, prev) => {
          const s = state.read(reader);
          if (!s) {
            return prev ?? 0;
          }
          const current = s.rect.map((rect) => rect.right).read(reader) + this._editorObs.layoutInfoVerticalScrollbarWidth.read(reader) + PADDING_HORIZONTALLY - this._editorObs.layoutInfoContentLeft.read(reader);
          return Math.max(prev ?? 0, current);
        }).recomputeInitiallyAndOnChange(this._store)
      }));
      this._register(autorun((reader) => {
        const v = view.read(reader);
        if (!v) {
          this._isHovered.set(false, void 0);
          return;
        }
        this._isHovered.set(overlay.isHovered.read(reader), void 0);
      }));
    }
    // TODO: this is very similar to side by side `fitsInsideViewport`, try to use the same function
    fitsInsideViewport(range2, displayLabel, reader) {
      const editorWidth = this._editorObs.layoutInfoWidth.read(reader);
      const editorContentLeft = this._editorObs.layoutInfoContentLeft.read(reader);
      const editorVerticalScrollbar = this._editor.getLayoutInfo().verticalScrollbarWidth;
      const minimapWidth = this._editorObs.layoutInfoMinimap.read(reader).minimapLeft !== 0 ? this._editorObs.layoutInfoMinimap.read(reader).minimapWidth : 0;
      const maxOriginalContent = maxContentWidthInRange(this._editorObs, range2, void 0);
      const maxModifiedContent = getContentRenderWidth(displayLabel, this._editor, this._editor.getModel());
      const padding = PADDING_HORIZONTALLY + MIN_END_OF_LINE_PADDING;
      return maxOriginalContent + maxModifiedContent + padding < editorWidth - editorContentLeft - editorVerticalScrollbar - minimapWidth;
    }
    getState(displayLocation) {
      const contentState = derived(this, (reader) => {
        const startLineNumber2 = displayLocation.range.startLineNumber;
        const endLineNumber2 = displayLocation.range.endLineNumber;
        const startColumn = displayLocation.range.startColumn;
        const endColumn = displayLocation.range.endColumn;
        const lineCount = this._editor.getModel()?.getLineCount() ?? 0;
        const lineWidth = maxContentWidthInRange(this._editorObs, new LineRange(startLineNumber2, startLineNumber2 + 1), reader);
        const lineWidthBelow = startLineNumber2 + 1 <= lineCount ? maxContentWidthInRange(this._editorObs, new LineRange(startLineNumber2 + 1, startLineNumber2 + 2), reader) : void 0;
        const lineWidthAbove = startLineNumber2 - 1 >= 1 ? maxContentWidthInRange(this._editorObs, new LineRange(startLineNumber2 - 1, startLineNumber2), reader) : void 0;
        const startContentLeftOffset = this._editor.getOffsetForColumn(startLineNumber2, startColumn);
        const endContentLeftOffset = this._editor.getOffsetForColumn(endLineNumber2, endColumn);
        return {
          lineWidth,
          lineWidthBelow,
          lineWidthAbove,
          startContentLeftOffset,
          endContentLeftOffset
        };
      });
      const startLineNumber = displayLocation.range.startLineNumber;
      const endLineNumber = displayLocation.range.endLineNumber;
      const fitsInsideViewport = this.fitsInsideViewport(new LineRange(startLineNumber, endLineNumber + 1), displayLocation.content, void 0);
      const rect = derived(this, (reader) => {
        const w = this._editorObs.getOption(
          59
          /* EditorOption.fontInfo */
        ).read(reader).typicalHalfwidthCharacterWidth;
        const { lineWidth, lineWidthBelow, lineWidthAbove, startContentLeftOffset, endContentLeftOffset } = contentState.read(reader);
        const contentLeft = this._editorObs.layoutInfoContentLeft.read(reader);
        const lineHeight = this._editorObs.observeLineHeightForLine(startLineNumber).recomputeInitiallyAndOnChange(reader.store).read(reader);
        const scrollTop = this._editorObs.scrollTop.read(reader);
        const scrollLeft = this._editorObs.scrollLeft.read(reader);
        let position;
        if (startLineNumber === endLineNumber && endContentLeftOffset + 5 * w >= lineWidth && fitsInsideViewport) {
          position = "end";
        } else if (lineWidthBelow !== void 0 && lineWidthBelow + MIN_END_OF_LINE_PADDING - HORIZONTAL_OFFSET_WHEN_ABOVE_BELOW - PADDING_HORIZONTALLY < startContentLeftOffset) {
          position = "below";
        } else if (lineWidthAbove !== void 0 && lineWidthAbove + MIN_END_OF_LINE_PADDING - HORIZONTAL_OFFSET_WHEN_ABOVE_BELOW - PADDING_HORIZONTALLY < startContentLeftOffset) {
          position = "above";
        } else {
          position = "end";
        }
        let topOfLine;
        let contentStartOffset;
        let deltaX = 0;
        let deltaY = 0;
        switch (position) {
          case "end": {
            topOfLine = this._editorObs.editor.getTopForLineNumber(startLineNumber);
            contentStartOffset = lineWidth;
            deltaX = PADDING_HORIZONTALLY + MIN_END_OF_LINE_PADDING;
            break;
          }
          case "below": {
            topOfLine = this._editorObs.editor.getTopForLineNumber(startLineNumber + 1);
            contentStartOffset = startContentLeftOffset;
            deltaX = PADDING_HORIZONTALLY + HORIZONTAL_OFFSET_WHEN_ABOVE_BELOW;
            deltaY = PADDING_VERTICALLY + VERTICAL_OFFSET_WHEN_ABOVE_BELOW;
            break;
          }
          case "above": {
            topOfLine = this._editorObs.editor.getTopForLineNumber(startLineNumber - 1);
            contentStartOffset = startContentLeftOffset;
            deltaX = PADDING_HORIZONTALLY + HORIZONTAL_OFFSET_WHEN_ABOVE_BELOW;
            deltaY = -PADDING_VERTICALLY + VERTICAL_OFFSET_WHEN_ABOVE_BELOW;
            break;
          }
        }
        const textRect = Rect.fromLeftTopWidthHeight(contentLeft + contentStartOffset - scrollLeft, topOfLine - scrollTop, w * displayLocation.content.length, lineHeight);
        return textRect.withMargin(PADDING_VERTICALLY, PADDING_HORIZONTALLY).translateX(deltaX).translateY(deltaY);
      });
      return {
        rect,
        label: displayLocation.content,
        kind: displayLocation.style
      };
    }
    getRendering(state, styles) {
      const line = document.createElement("div");
      const t = this._editor.getModel().tokenization.tokenizeLinesAt(1, [state.label])?.[0];
      let tokens;
      if (t && state.kind === InlineCompletionHintStyle$1.Code) {
        tokens = TokenArray.fromLineTokens(t).toLineTokens(state.label, this._languageService.languageIdCodec);
      } else {
        tokens = LineTokens.createEmpty(state.label, this._languageService.languageIdCodec);
      }
      const result = renderLines$1(new LineSource([tokens]), RenderOptions.fromEditor(this._editor).withSetWidth(false).withScrollBeyondLastColumn(0), [], line, true);
      line.style.width = `${result.minWidthInPx}px`;
      const rect = state.rect.map((r) => r.withMargin(0, PADDING_HORIZONTALLY));
      return n.div({
        class: "collapsedView",
        ref: this._viewRef,
        style: {
          position: "absolute",
          ...rectToProps((reader) => rect.read(reader)),
          overflow: "hidden",
          boxSizing: "border-box",
          cursor: "pointer",
          border: styles.map((s) => `1px solid ${s.border}`),
          borderRadius: "4px",
          backgroundColor: styles.map((s) => s.background),
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
          whiteSpace: "nowrap"
        },
        onmousedown: (e) => {
          e.preventDefault();
        },
        onclick: (e) => {
          this._onDidClick.fire(new StandardMouseEvent(getWindow(e), e));
        }
      }, [
        line
      ]);
    }
  };
  InlineEditsCustomView = __decorate$1c([
    __param$1b(3, IThemeService),
    __param$1b(4, ILanguageService)
  ], InlineEditsCustomView);
  const HORIZONTAL_PADDING$1 = 0;
  const VERTICAL_PADDING$1 = 0;
  const BORDER_WIDTH$3 = 1;
  const WIDGET_SEPARATOR_WIDTH$2 = 1;
  const WIDGET_SEPARATOR_DIFF_EDITOR_WIDTH$2 = 3;
  const BORDER_RADIUS$2 = 4;
  class InlineEditsDeletionView extends Disposable {
    constructor(_editor, _edit, _uiState, _tabAction) {
      super();
      this._editor = _editor;
      this._edit = _edit;
      this._uiState = _uiState;
      this._tabAction = _tabAction;
      this._onDidClick = this._register(new Emitter$1());
      this.onDidClick = this._onDidClick.event;
      this._display = derived(this, (reader) => !!this._uiState.read(reader) ? "block" : "none");
      this._editorMaxContentWidthInRange = derived(this, (reader) => {
        const originalDisplayRange = this._originalDisplayRange.read(reader);
        if (!originalDisplayRange) {
          return constObservable(0);
        }
        this._editorObs.versionId.read(reader);
        return derivedObservableWithCache(this, (reader2, lastValue) => {
          const maxWidth = maxContentWidthInRange(this._editorObs, originalDisplayRange, reader2);
          return Math.max(maxWidth, lastValue ?? 0);
        });
      }).map((v, r) => v.read(r));
      this._maxPrefixTrim = derived(this, (reader) => {
        const state = this._uiState.read(reader);
        if (!state) {
          return { prefixTrim: 0, prefixLeftOffset: 0 };
        }
        return getPrefixTrim(state.deletions, state.originalRange, [], this._editor);
      });
      this._editorLayoutInfo = derived(this, (reader) => {
        const inlineEdit = this._edit.read(reader);
        if (!inlineEdit) {
          return null;
        }
        const state = this._uiState.read(reader);
        if (!state) {
          return null;
        }
        const editorLayout = this._editorObs.layoutInfo.read(reader);
        const horizontalScrollOffset = this._editorObs.scrollLeft.read(reader);
        const w = this._editorObs.getOption(
          59
          /* EditorOption.fontInfo */
        ).map((f) => f.typicalHalfwidthCharacterWidth).read(reader);
        const right = editorLayout.contentLeft + Math.max(this._editorMaxContentWidthInRange.read(reader), w) - horizontalScrollOffset;
        const range2 = inlineEdit.originalLineRange;
        const selectionTop = this._originalVerticalStartPosition.read(reader) ?? this._editor.getTopForLineNumber(range2.startLineNumber) - this._editorObs.scrollTop.read(reader);
        const selectionBottom = this._originalVerticalEndPosition.read(reader) ?? this._editor.getTopForLineNumber(range2.endLineNumberExclusive) - this._editorObs.scrollTop.read(reader);
        const left = editorLayout.contentLeft + this._maxPrefixTrim.read(reader).prefixLeftOffset - horizontalScrollOffset;
        if (right <= left) {
          return null;
        }
        const codeRect = Rect.fromLeftTopRightBottom(left, selectionTop, right, selectionBottom).withMargin(VERTICAL_PADDING$1, HORIZONTAL_PADDING$1);
        return {
          codeRect,
          contentLeft: editorLayout.contentLeft
        };
      }).recomputeInitiallyAndOnChange(this._store);
      this._originalOverlay = n.div({
        style: { pointerEvents: "none" }
      }, derived(this, (reader) => {
        const layoutInfoObs = mapOutFalsy(this._editorLayoutInfo).read(reader);
        if (!layoutInfoObs) {
          return void 0;
        }
        const overlayhider = layoutInfoObs.map((layoutInfo) => Rect.fromLeftTopRightBottom(layoutInfo.contentLeft - BORDER_RADIUS$2 - BORDER_WIDTH$3, layoutInfo.codeRect.top, layoutInfo.contentLeft, layoutInfo.codeRect.bottom));
        const overlayRect = derived(this, (reader2) => {
          const rect = layoutInfoObs.read(reader2).codeRect;
          const overlayHider = overlayhider.read(reader2);
          return rect.intersectHorizontal(new OffsetRange(overlayHider.left, Number.MAX_SAFE_INTEGER));
        });
        const separatorWidth = this._uiState.map((s) => s?.inDiffEditor ? WIDGET_SEPARATOR_DIFF_EDITOR_WIDTH$2 : WIDGET_SEPARATOR_WIDTH$2).read(reader);
        const separatorRect = overlayRect.map((rect) => rect.withMargin(separatorWidth, separatorWidth));
        return [
          n.div({
            class: "originalSeparatorDeletion",
            style: {
              ...separatorRect.read(reader).toStyles(),
              borderRadius: `${BORDER_RADIUS$2}px`,
              border: `${BORDER_WIDTH$3 + separatorWidth}px solid ${asCssVariable(editorBackground)}`,
              boxSizing: "border-box"
            }
          }),
          n.div({
            class: "originalOverlayDeletion",
            style: {
              ...overlayRect.read(reader).toStyles(),
              borderRadius: `${BORDER_RADIUS$2}px`,
              border: getOriginalBorderColor(this._tabAction).map((bc) => `${BORDER_WIDTH$3}px solid ${asCssVariable(bc)}`),
              boxSizing: "border-box",
              backgroundColor: asCssVariable(originalBackgroundColor)
            }
          }),
          n.div({
            class: "originalOverlayHiderDeletion",
            style: {
              ...overlayhider.read(reader).toStyles(),
              backgroundColor: asCssVariable(editorBackground)
            }
          })
        ];
      })).keepUpdated(this._store);
      this._nonOverflowView = n.div({
        class: "inline-edits-view",
        style: {
          position: "absolute",
          overflow: "visible",
          top: "0px",
          left: "0px",
          display: this._display
        }
      }, [
        [this._originalOverlay]
      ]).keepUpdated(this._store);
      this.isHovered = constObservable(false);
      this._editorObs = observableCodeEditor(this._editor);
      const originalStartPosition = derived(this, (reader) => {
        const inlineEdit = this._edit.read(reader);
        return inlineEdit ? new Position$1(inlineEdit.originalLineRange.startLineNumber, 1) : null;
      });
      const originalEndPosition = derived(this, (reader) => {
        const inlineEdit = this._edit.read(reader);
        return inlineEdit ? new Position$1(inlineEdit.originalLineRange.endLineNumberExclusive, 1) : null;
      });
      this._originalDisplayRange = this._uiState.map((s) => s?.originalRange);
      this._originalVerticalStartPosition = this._editorObs.observePosition(originalStartPosition, this._store).map((p) => p?.y);
      this._originalVerticalEndPosition = this._editorObs.observePosition(originalEndPosition, this._store).map((p) => p?.y);
      this._register(this._editorObs.createOverlayWidget({
        domNode: this._nonOverflowView.element,
        position: constObservable(null),
        allowEditorOverflow: false,
        minContentWidthInPx: derived(this, (reader) => {
          const info = this._editorLayoutInfo.read(reader);
          if (info === null) {
            return 0;
          }
          return info.codeRect.width;
        })
      }));
    }
  }
  var __decorate$1b = 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$1a = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  const BORDER_WIDTH$2 = 1;
  const WIDGET_SEPARATOR_WIDTH$1 = 1;
  const WIDGET_SEPARATOR_DIFF_EDITOR_WIDTH$1 = 3;
  const BORDER_RADIUS$1 = 4;
  let InlineEditsInsertionView = class InlineEditsInsertionView extends Disposable {
    constructor(_editor, _input, _tabAction, instantiationService, _languageService) {
      super();
      this._editor = _editor;
      this._input = _input;
      this._tabAction = _tabAction;
      this._languageService = _languageService;
      this._onDidClick = this._register(new Emitter$1());
      this.onDidClick = this._onDidClick.event;
      this._state = derived(this, (reader) => {
        const state = this._input.read(reader);
        if (!state) {
          return void 0;
        }
        const textModel = this._editor.getModel();
        const eol = textModel.getEOL();
        if (state.startColumn === 1 && state.lineNumber > 1 && textModel.getLineLength(state.lineNumber) !== 0 && state.text.endsWith(eol) && !state.text.startsWith(eol)) {
          const endOfLineColumn = textModel.getLineLength(state.lineNumber - 1) + 1;
          return { lineNumber: state.lineNumber - 1, column: endOfLineColumn, text: eol + state.text.slice(0, -eol.length) };
        }
        return { lineNumber: state.lineNumber, column: state.startColumn, text: state.text };
      });
      this._trimVertically = derived(this, (reader) => {
        const state = this._state.read(reader);
        const text2 = state?.text;
        if (!text2 || text2.trim() === "") {
          return { topOffset: 0, bottomOffset: 0, linesTop: 0, linesBottom: 0 };
        }
        const lineHeight = this._editor.getLineHeightForPosition(new Position$1(state.lineNumber, 1));
        const eol = this._editor.getModel().getEOL();
        let linesTop = 0;
        let linesBottom = 0;
        let i2 = 0;
        for (; i2 < text2.length && text2.startsWith(eol, i2); i2 += eol.length) {
          linesTop += 1;
        }
        for (let j = text2.length; j > i2 && text2.endsWith(eol, j); j -= eol.length) {
          linesBottom += 1;
        }
        return { topOffset: linesTop * lineHeight, bottomOffset: linesBottom * lineHeight, linesTop, linesBottom };
      });
      this._maxPrefixTrim = derived(this, (reader) => {
        const state = this._state.read(reader);
        if (!state) {
          return { prefixLeftOffset: 0, prefixTrim: 0 };
        }
        const textModel = this._editor.getModel();
        const eol = textModel.getEOL();
        const trimVertically = this._trimVertically.read(reader);
        const lines = state.text.split(eol);
        const modifiedLines = lines.slice(trimVertically.linesTop, lines.length - trimVertically.linesBottom);
        if (trimVertically.linesTop === 0) {
          modifiedLines[0] = textModel.getLineContent(state.lineNumber) + modifiedLines[0];
        }
        const originalRange = new LineRange(state.lineNumber, state.lineNumber + (trimVertically.linesTop > 0 ? 0 : 1));
        return getPrefixTrim([], originalRange, modifiedLines, this._editor);
      });
      this._ghostText = derived((reader) => {
        const state = this._state.read(reader);
        const prefixTrim = this._maxPrefixTrim.read(reader);
        if (!state) {
          return void 0;
        }
        const textModel = this._editor.getModel();
        const eol = textModel.getEOL();
        const modifiedLines = state.text.split(eol);
        const inlineDecorations = modifiedLines.map((line, i2) => new InlineDecoration(
          new Range$2(i2 + 1, i2 === 0 ? 1 : prefixTrim.prefixTrim + 1, i2 + 1, line.length + 1),
          "modified-background",
          0
          /* InlineDecorationType.Regular */
        ));
        return new GhostText(state.lineNumber, [new GhostTextPart(state.column, state.text, false, inlineDecorations)]);
      });
      this._display = derived(this, (reader) => !!this._state.read(reader) ? "block" : "none");
      this._editorMaxContentWidthInRange = derived(this, (reader) => {
        const state = this._state.read(reader);
        if (!state) {
          return 0;
        }
        this._editorObs.versionId.read(reader);
        const textModel = this._editor.getModel();
        const eol = textModel.getEOL();
        const textBeforeInsertion = state.text.startsWith(eol) ? "" : textModel.getValueInRange(new Range$2(state.lineNumber, 1, state.lineNumber, state.column));
        const textAfterInsertion = textModel.getValueInRange(new Range$2(state.lineNumber, state.column, state.lineNumber, textModel.getLineLength(state.lineNumber) + 1));
        const text2 = textBeforeInsertion + state.text + textAfterInsertion;
        const lines = text2.split(eol);
        const renderOptions = RenderOptions.fromEditor(this._editor).withSetWidth(false).withScrollBeyondLastColumn(0);
        const lineWidths = lines.map((line) => {
          const t = textModel.tokenization.tokenizeLinesAt(state.lineNumber, [line])?.[0];
          let tokens;
          if (t) {
            tokens = TokenArray.fromLineTokens(t).toLineTokens(line, this._languageService.languageIdCodec);
          } else {
            tokens = LineTokens.createEmpty(line, this._languageService.languageIdCodec);
          }
          return renderLines$1(new LineSource([tokens]), renderOptions, [], $$l("div"), true).minWidthInPx;
        });
        return Math.max(...lineWidths);
      });
      this.startLineOffset = this._trimVertically.map((v) => v.topOffset);
      this.originalLines = this._state.map((s) => s ? new LineRange(s.lineNumber, Math.min(s.lineNumber + 2, this._editor.getModel().getLineCount() + 1)) : void 0);
      this._overlayLayout = derived(this, (reader) => {
        this._ghostText.read(reader);
        const state = this._state.read(reader);
        if (!state) {
          return null;
        }
        this._editorObs.observePosition(observableValue(this, new Position$1(state.lineNumber, state.column)), reader.store).read(reader);
        const editorLayout = this._editorObs.layoutInfo.read(reader);
        const horizontalScrollOffset = this._editorObs.scrollLeft.read(reader);
        const verticalScrollbarWidth = this._editorObs.layoutInfoVerticalScrollbarWidth.read(reader);
        const right = editorLayout.contentLeft + this._editorMaxContentWidthInRange.read(reader) - horizontalScrollOffset;
        const prefixLeftOffset = this._maxPrefixTrim.read(reader).prefixLeftOffset ?? 0;
        const left = editorLayout.contentLeft + prefixLeftOffset - horizontalScrollOffset;
        if (right <= left) {
          return null;
        }
        const { topOffset: topTrim, bottomOffset: bottomTrim } = this._trimVertically.read(reader);
        const scrollTop = this._editorObs.scrollTop.read(reader);
        const height = this._ghostTextView.height.read(reader) - topTrim - bottomTrim;
        const top = this._editor.getTopForLineNumber(state.lineNumber) - scrollTop + topTrim;
        const bottom = top + height;
        const overlay = new Rect(left, top, right, bottom);
        return {
          overlay,
          startsAtContentLeft: prefixLeftOffset === 0,
          contentLeft: editorLayout.contentLeft,
          minContentWidthRequired: prefixLeftOffset + overlay.width + verticalScrollbarWidth
        };
      }).recomputeInitiallyAndOnChange(this._store);
      this._modifiedOverlay = n.div({
        style: { pointerEvents: "none" }
      }, derived(this, (reader) => {
        const overlayLayoutObs = mapOutFalsy(this._overlayLayout).read(reader);
        if (!overlayLayoutObs) {
          return void 0;
        }
        const overlayHider = overlayLayoutObs.map((layoutInfo) => Rect.fromLeftTopRightBottom(layoutInfo.contentLeft - BORDER_RADIUS$1 - BORDER_WIDTH$2, layoutInfo.overlay.top, layoutInfo.contentLeft, layoutInfo.overlay.bottom)).read(reader);
        const separatorWidth = this._input.map((i2) => i2?.inDiffEditor ? WIDGET_SEPARATOR_DIFF_EDITOR_WIDTH$1 : WIDGET_SEPARATOR_WIDTH$1).read(reader);
        const overlayRect = overlayLayoutObs.map((l) => l.overlay.withMargin(0, BORDER_WIDTH$2, 0, l.startsAtContentLeft ? 0 : BORDER_WIDTH$2).intersectHorizontal(new OffsetRange(overlayHider.left, Number.MAX_SAFE_INTEGER)));
        const underlayRect = overlayRect.map((rect) => rect.withMargin(separatorWidth, separatorWidth));
        return [
          n.div({
            class: "originalUnderlayInsertion",
            style: {
              ...underlayRect.read(reader).toStyles(),
              borderRadius: BORDER_RADIUS$1,
              border: `${BORDER_WIDTH$2 + separatorWidth}px solid ${asCssVariable(editorBackground)}`,
              boxSizing: "border-box"
            }
          }),
          n.div({
            class: "originalOverlayInsertion",
            style: {
              ...overlayRect.read(reader).toStyles(),
              borderRadius: BORDER_RADIUS$1,
              border: getModifiedBorderColor(this._tabAction).map((bc) => `${BORDER_WIDTH$2}px solid ${asCssVariable(bc)}`),
              boxSizing: "border-box",
              backgroundColor: asCssVariable(modifiedBackgroundColor)
            }
          }),
          n.div({
            class: "originalOverlayHiderInsertion",
            style: {
              ...overlayHider.toStyles(),
              backgroundColor: asCssVariable(editorBackground)
            }
          })
        ];
      })).keepUpdated(this._store);
      this._view = n.div({
        class: "inline-edits-view",
        style: {
          position: "absolute",
          overflow: "visible",
          top: "0px",
          left: "0px",
          display: this._display
        }
      }, [
        [this._modifiedOverlay]
      ]).keepUpdated(this._store);
      this._editorObs = observableCodeEditor(this._editor);
      this._ghostTextView = this._register(instantiationService.createInstance(GhostTextView, this._editor, {
        ghostText: this._ghostText,
        minReservedLineCount: constObservable(0),
        targetTextModel: this._editorObs.model.map((model) => model ?? void 0),
        warning: constObservable(void 0),
        handleInlineCompletionShown: constObservable(() => {
        })
      }, observableValue(this, { syntaxHighlightingEnabled: true, extraClasses: ["inline-edit"] }), true, true));
      this.isHovered = this._ghostTextView.isHovered;
      this._register(this._ghostTextView.onDidClick((e) => {
        this._onDidClick.fire(e);
      }));
      this._register(this._editorObs.createOverlayWidget({
        domNode: this._view.element,
        position: constObservable(null),
        allowEditorOverflow: false,
        minContentWidthInPx: derived(this, (reader) => {
          const info = this._overlayLayout.read(reader);
          if (info === null) {
            return 0;
          }
          return info.minContentWidthRequired;
        })
      }));
    }
  };
  InlineEditsInsertionView = __decorate$1b([
    __param$1a(3, IInstantiationService),
    __param$1a(4, ILanguageService)
  ], InlineEditsInsertionView);
  var __decorate$1a = 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$19 = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  let InlineEditsLineReplacementView = class InlineEditsLineReplacementView extends Disposable {
    constructor(_editor, _edit, _isInDiffEditor, _tabAction, _languageService, _themeService) {
      super();
      this._editor = _editor;
      this._edit = _edit;
      this._isInDiffEditor = _isInDiffEditor;
      this._tabAction = _tabAction;
      this._languageService = _languageService;
      this._themeService = _themeService;
      this._onDidClick = this._register(new Emitter$1());
      this.onDidClick = this._onDidClick.event;
      this._maxPrefixTrim = this._edit.map((e, reader) => e ? getPrefixTrim(e.replacements.flatMap((r) => [r.originalRange, r.modifiedRange]), e.originalRange, e.modifiedLines, this._editor.editor, reader) : void 0);
      this._modifiedLineElements = derived(this, (reader) => {
        const lines = [];
        let requiredWidth = 0;
        const prefixTrim = this._maxPrefixTrim.read(reader);
        const edit2 = this._edit.read(reader);
        if (!edit2 || !prefixTrim) {
          return void 0;
        }
        const maxPrefixTrim = prefixTrim.prefixTrim;
        const modifiedBubbles = rangesToBubbleRanges(edit2.replacements.map((r) => r.modifiedRange)).map((r) => new Range$2(r.startLineNumber, r.startColumn - maxPrefixTrim, r.endLineNumber, r.endColumn - maxPrefixTrim));
        const textModel = this._editor.model.get();
        const startLineNumber = edit2.modifiedRange.startLineNumber;
        for (let i2 = 0; i2 < edit2.modifiedRange.length; i2++) {
          const line = document.createElement("div");
          const lineNumber = startLineNumber + i2;
          const modLine = edit2.modifiedLines[i2].slice(maxPrefixTrim);
          const t = textModel.tokenization.tokenizeLinesAt(lineNumber, [modLine])?.[0];
          let tokens;
          if (t) {
            tokens = TokenArray.fromLineTokens(t).toLineTokens(modLine, this._languageService.languageIdCodec);
          } else {
            tokens = LineTokens.createEmpty(modLine, this._languageService.languageIdCodec);
          }
          const decorations = [];
          for (const modified of modifiedBubbles.filter((b) => b.startLineNumber === lineNumber)) {
            const validatedEndColumn = Math.min(modified.endColumn, modLine.length + 1);
            decorations.push(new InlineDecoration(
              new Range$2(1, modified.startColumn, 1, validatedEndColumn),
              "inlineCompletions-modified-bubble",
              0
              /* InlineDecorationType.Regular */
            ));
          }
          const result = renderLines$1(new LineSource([tokens]), RenderOptions.fromEditor(this._editor.editor).withSetWidth(false).withScrollBeyondLastColumn(0), decorations, line, true);
          this._editor.getOption(
            59
            /* EditorOption.fontInfo */
          ).read(reader);
          requiredWidth = Math.max(requiredWidth, result.minWidthInPx);
          lines.push(line);
        }
        return { lines, requiredWidth };
      });
      this._layout = derived(this, (reader) => {
        const modifiedLines = this._modifiedLineElements.read(reader);
        const maxPrefixTrim = this._maxPrefixTrim.read(reader);
        const edit2 = this._edit.read(reader);
        if (!modifiedLines || !maxPrefixTrim || !edit2) {
          return void 0;
        }
        const { prefixLeftOffset } = maxPrefixTrim;
        const { requiredWidth } = modifiedLines;
        const originalLineHeights = this._editor.observeLineHeightsForLineRange(edit2.originalRange).read(reader);
        const modifiedLineHeights = (() => {
          const lineHeights = originalLineHeights.slice(0, edit2.modifiedRange.length);
          while (lineHeights.length < edit2.modifiedRange.length) {
            lineHeights.push(originalLineHeights[originalLineHeights.length - 1]);
          }
          return lineHeights;
        })();
        const contentLeft = this._editor.layoutInfoContentLeft.read(reader);
        const verticalScrollbarWidth = this._editor.layoutInfoVerticalScrollbarWidth.read(reader);
        const scrollLeft = this._editor.scrollLeft.read(reader);
        const scrollTop = this._editor.scrollTop.read(reader);
        const editorLeftOffset = contentLeft - scrollLeft;
        const textModel = this._editor.editor.getModel();
        const originalLineWidths = edit2.originalRange.mapToLineArray((line) => this._editor.editor.getOffsetForColumn(line, textModel.getLineMaxColumn(line)) - prefixLeftOffset);
        const maxLineWidth = Math.max(...originalLineWidths, requiredWidth);
        const startLineNumber = edit2.originalRange.startLineNumber;
        const endLineNumber = edit2.originalRange.endLineNumberExclusive - 1;
        const topOfOriginalLines = this._editor.editor.getTopForLineNumber(startLineNumber) - scrollTop;
        const bottomOfOriginalLines = this._editor.editor.getBottomForLineNumber(endLineNumber) - scrollTop;
        const originalLinesOverlay = Rect.fromLeftTopWidthHeight(editorLeftOffset + prefixLeftOffset, topOfOriginalLines, maxLineWidth, bottomOfOriginalLines - topOfOriginalLines);
        const modifiedLinesOverlay = Rect.fromLeftTopWidthHeight(originalLinesOverlay.left, originalLinesOverlay.bottom, originalLinesOverlay.width, modifiedLineHeights.reduce((sum2, h2) => sum2 + h2, 0));
        const background = Rect.hull([originalLinesOverlay, modifiedLinesOverlay]);
        const lowerBackground = background.intersectVertical(new OffsetRange(originalLinesOverlay.bottom, Number.MAX_SAFE_INTEGER));
        const lowerText = new Rect(lowerBackground.left, lowerBackground.top, lowerBackground.right, lowerBackground.bottom);
        return {
          originalLinesOverlay,
          modifiedLinesOverlay,
          background,
          lowerBackground,
          lowerText,
          modifiedLineHeights,
          minContentWidthRequired: prefixLeftOffset + maxLineWidth + verticalScrollbarWidth
        };
      });
      this._viewZoneInfo = derived((reader) => {
        const shouldShowViewZone = this._editor.getOption(
          71
          /* EditorOption.inlineSuggest */
        ).map((o) => o.edits.allowCodeShifting === "always").read(reader);
        if (!shouldShowViewZone) {
          return void 0;
        }
        const layout2 = this._layout.read(reader);
        const edit2 = this._edit.read(reader);
        if (!layout2 || !edit2) {
          return void 0;
        }
        const viewZoneHeight = layout2.lowerBackground.height;
        const viewZoneLineNumber = edit2.originalRange.endLineNumberExclusive;
        return { height: viewZoneHeight, lineNumber: viewZoneLineNumber };
      });
      this.minEditorScrollHeight = derived(this, (reader) => {
        const layout2 = mapOutFalsy(this._layout).read(reader);
        if (!layout2 || this._viewZoneInfo.read(reader) !== void 0) {
          return 0;
        }
        return layout2.read(reader).lowerText.bottom + this._editor.editor.getScrollTop();
      });
      this._div = n.div({
        class: "line-replacement"
      }, [
        derived(this, (reader) => {
          const layout2 = mapOutFalsy(this._layout).read(reader);
          const modifiedLineElements = this._modifiedLineElements.read(reader);
          if (!layout2 || !modifiedLineElements) {
            return [];
          }
          const layoutProps = layout2.read(reader);
          const contentLeft = this._editor.layoutInfoContentLeft.read(reader);
          const separatorWidth = this._isInDiffEditor.read(reader) ? 3 : 1;
          modifiedLineElements.lines.forEach((l, i2) => {
            l.style.width = `${layoutProps.lowerText.width}px`;
            l.style.height = `${layoutProps.modifiedLineHeights[i2]}px`;
            l.style.position = "relative";
          });
          const modifiedBorderColor = getModifiedBorderColor(this._tabAction).read(reader);
          const originalBorderColor = getOriginalBorderColor(this._tabAction).read(reader);
          return [
            n.div({
              style: {
                position: "absolute",
                ...rectToProps((r) => getEditorValidOverlayRect(this._editor).read(r)),
                overflow: "hidden",
                pointerEvents: "none"
              }
            }, [
              n.div({
                class: "borderAroundLineReplacement",
                style: {
                  position: "absolute",
                  ...rectToProps((reader2) => layout2.read(reader2).background.translateX(-contentLeft).withMargin(separatorWidth)),
                  borderRadius: "4px",
                  border: `${separatorWidth + 1}px solid ${asCssVariable(editorBackground)}`,
                  boxSizing: "border-box",
                  pointerEvents: "none"
                }
              }),
              n.div({
                class: "originalOverlayLineReplacement",
                style: {
                  position: "absolute",
                  ...rectToProps((reader2) => layout2.read(reader2).background.translateX(-contentLeft)),
                  borderRadius: "4px",
                  border: getEditorBlendedColor(originalBorderColor, this._themeService).map((c) => `1px solid ${c.toString()}`),
                  pointerEvents: "none",
                  boxSizing: "border-box",
                  background: asCssVariable(originalBackgroundColor)
                }
              }),
              n.div({
                class: "modifiedOverlayLineReplacement",
                style: {
                  position: "absolute",
                  ...rectToProps((reader2) => layout2.read(reader2).lowerBackground.translateX(-contentLeft)),
                  borderRadius: "0 0 4px 4px",
                  background: asCssVariable(editorBackground),
                  boxShadow: `${asCssVariable(scrollbarShadow)} 0 6px 6px -6px`,
                  border: `1px solid ${asCssVariable(modifiedBorderColor)}`,
                  boxSizing: "border-box",
                  overflow: "hidden",
                  cursor: "pointer",
                  pointerEvents: "auto"
                },
                onmousedown: (e) => {
                  e.preventDefault();
                },
                onclick: (e) => this._onDidClick.fire(new StandardMouseEvent(getWindow(e), e))
              }, [
                n.div({
                  style: {
                    position: "absolute",
                    top: 0,
                    left: 0,
                    width: "100%",
                    height: "100%",
                    background: asCssVariable(modifiedChangedLineBackgroundColor)
                  }
                })
              ]),
              n.div({
                class: "modifiedLinesLineReplacement",
                style: {
                  position: "absolute",
                  boxSizing: "border-box",
                  ...rectToProps((reader2) => layout2.read(reader2).lowerText.translateX(-contentLeft)),
                  fontFamily: this._editor.getOption(
                    58
                    /* EditorOption.fontFamily */
                  ),
                  fontSize: this._editor.getOption(
                    61
                    /* EditorOption.fontSize */
                  ),
                  fontWeight: this._editor.getOption(
                    62
                    /* EditorOption.fontWeight */
                  ),
                  pointerEvents: "none",
                  whiteSpace: "nowrap",
                  borderRadius: "0 0 4px 4px",
                  overflow: "hidden"
                }
              }, [...modifiedLineElements.lines])
            ])
          ];
        })
      ]).keepUpdated(this._store);
      this.isHovered = this._editor.isTargetHovered((e) => this._isMouseOverWidget(e), this._store);
      this._previousViewZoneInfo = void 0;
      this._register(toDisposable(() => this._editor.editor.changeViewZones((accessor) => this.removePreviousViewZone(accessor))));
      this._register(autorunDelta(this._viewZoneInfo, ({ lastValue, newValue }) => {
        if (lastValue === newValue || lastValue?.height === newValue?.height && lastValue?.lineNumber === newValue?.lineNumber) {
          return;
        }
        this._editor.editor.changeViewZones((changeAccessor) => {
          this.removePreviousViewZone(changeAccessor);
          if (!newValue) {
            return;
          }
          this.addViewZone(newValue, changeAccessor);
        });
      }));
      this._register(this._editor.createOverlayWidget({
        domNode: this._div.element,
        minContentWidthInPx: derived(this, (reader) => {
          return this._layout.read(reader)?.minContentWidthRequired ?? 0;
        }),
        position: constObservable({ preference: { top: 0, left: 0 } }),
        allowEditorOverflow: false
      }));
    }
    _isMouseOverWidget(e) {
      const layout2 = this._layout.get();
      if (!layout2 || !(e.event instanceof EditorMouseEvent)) {
        return false;
      }
      return layout2.lowerBackground.containsPoint(new Point(e.event.relativePos.x, e.event.relativePos.y));
    }
    removePreviousViewZone(changeAccessor) {
      if (!this._previousViewZoneInfo) {
        return;
      }
      changeAccessor.removeZone(this._previousViewZoneInfo.id);
      const cursorLineNumber = this._editor.cursorLineNumber.get();
      if (cursorLineNumber !== null && cursorLineNumber >= this._previousViewZoneInfo.lineNumber) {
        this._editor.editor.setScrollTop(this._editor.scrollTop.get() - this._previousViewZoneInfo.height);
      }
      this._previousViewZoneInfo = void 0;
    }
    addViewZone(viewZoneInfo, changeAccessor) {
      const activeViewZone = changeAccessor.addZone({
        afterLineNumber: viewZoneInfo.lineNumber - 1,
        heightInPx: viewZoneInfo.height,
        // move computation to layout?
        domNode: $$l("div")
      });
      this._previousViewZoneInfo = { height: viewZoneInfo.height, lineNumber: viewZoneInfo.lineNumber, id: activeViewZone };
      const cursorLineNumber = this._editor.cursorLineNumber.get();
      if (cursorLineNumber !== null && cursorLineNumber >= viewZoneInfo.lineNumber) {
        this._editor.editor.setScrollTop(this._editor.scrollTop.get() + viewZoneInfo.height);
      }
    }
  };
  InlineEditsLineReplacementView = __decorate$1a([
    __param$19(4, ILanguageService),
    __param$19(5, IThemeService)
  ], InlineEditsLineReplacementView);
  function rangesToBubbleRanges(ranges) {
    const result = [];
    while (ranges.length) {
      let range2 = ranges.shift();
      if (range2.startLineNumber !== range2.endLineNumber) {
        ranges.push(new Range$2(range2.startLineNumber + 1, 1, range2.endLineNumber, range2.endColumn));
        range2 = new Range$2(range2.startLineNumber, range2.startColumn, range2.startLineNumber, Number.MAX_SAFE_INTEGER);
      }
      result.push(range2);
    }
    return result;
  }
  var __decorate$19 = 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$18 = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  const HORIZONTAL_PADDING = 0;
  const VERTICAL_PADDING = 0;
  const BORDER_WIDTH$1 = 1;
  const WIDGET_SEPARATOR_WIDTH = 1;
  const WIDGET_SEPARATOR_DIFF_EDITOR_WIDTH = 3;
  const BORDER_RADIUS = 4;
  const ORIGINAL_END_PADDING = 20;
  const MODIFIED_END_PADDING = 12;
  let InlineEditsSideBySideView = class InlineEditsSideBySideView extends Disposable {
    // This is an approximation and should be improved by using the real parameters used bellow
    static fitsInsideViewport(editor2, textModel, edit2, reader) {
      const editorObs = observableCodeEditor(editor2);
      const editorWidth = editorObs.layoutInfoWidth.read(reader);
      const editorContentLeft = editorObs.layoutInfoContentLeft.read(reader);
      const editorVerticalScrollbar = editor2.getLayoutInfo().verticalScrollbarWidth;
      const minimapWidth = editorObs.layoutInfoMinimap.read(reader).minimapLeft !== 0 ? editorObs.layoutInfoMinimap.read(reader).minimapWidth : 0;
      const maxOriginalContent = maxContentWidthInRange(
        editorObs,
        edit2.displayRange,
        void 0
        /* do not reconsider on each layout info change */
      );
      const maxModifiedContent = edit2.lineEdit.newLines.reduce((max, line) => Math.max(max, getContentRenderWidth(line, editor2, textModel)), 0);
      const originalPadding = ORIGINAL_END_PADDING;
      const modifiedPadding = MODIFIED_END_PADDING + 2 * BORDER_WIDTH$1;
      return maxOriginalContent + maxModifiedContent + originalPadding + modifiedPadding < editorWidth - editorContentLeft - editorVerticalScrollbar - minimapWidth;
    }
    constructor(_editor, _edit, _previewTextModel, _uiState, _tabAction, _instantiationService, _themeService) {
      super();
      this._editor = _editor;
      this._edit = _edit;
      this._previewTextModel = _previewTextModel;
      this._uiState = _uiState;
      this._tabAction = _tabAction;
      this._instantiationService = _instantiationService;
      this._themeService = _themeService;
      this._editorObs = observableCodeEditor(this._editor);
      this._onDidClick = this._register(new Emitter$1());
      this.onDidClick = this._onDidClick.event;
      this._display = derived(this, (reader) => !!this._uiState.read(reader) ? "block" : "none");
      this.previewRef = n.ref();
      const separatorWidthObs = this._uiState.map((s) => s?.isInDiffEditor ? WIDGET_SEPARATOR_DIFF_EDITOR_WIDTH : WIDGET_SEPARATOR_WIDTH);
      this._editorContainer = n.div({
        class: ["editorContainer"],
        style: { position: "absolute", overflow: "hidden", cursor: "pointer" },
        onmousedown: (e) => {
          e.preventDefault();
        },
        onclick: (e) => {
          this._onDidClick.fire(new StandardMouseEvent(getWindow(e), e));
        }
      }, [
        n.div({ class: "preview", style: { pointerEvents: "none" }, ref: this.previewRef })
      ]).keepUpdated(this._store);
      this.isHovered = this._editorContainer.didMouseMoveDuringHover;
      this.previewEditor = this._register(this._instantiationService.createInstance(EmbeddedCodeEditorWidget, this.previewRef.element, {
        glyphMargin: false,
        lineNumbers: "off",
        minimap: { enabled: false },
        guides: {
          indentation: false,
          bracketPairs: false,
          bracketPairsHorizontal: false,
          highlightActiveIndentation: false
        },
        rulers: [],
        padding: { top: 0, bottom: 0 },
        folding: false,
        selectOnLineNumbers: false,
        selectionHighlight: false,
        columnSelection: false,
        overviewRulerBorder: false,
        overviewRulerLanes: 0,
        lineDecorationsWidth: 0,
        lineNumbersMinChars: 0,
        revealHorizontalRightPadding: 0,
        bracketPairColorization: { enabled: true, independentColorPoolPerBracketType: false },
        scrollBeyondLastLine: false,
        scrollbar: {
          vertical: "hidden",
          horizontal: "hidden",
          handleMouseWheel: false
        },
        readOnly: true,
        wordWrap: "off",
        wordWrapOverride1: "off",
        wordWrapOverride2: "off"
      }, {
        contextKeyValues: {
          [InlineCompletionContextKeys.inInlineEditsPreviewEditor.key]: true
        },
        contributions: []
      }, this._editor));
      this._previewEditorObs = observableCodeEditor(this.previewEditor);
      this._activeViewZones = [];
      this._updatePreviewEditor = derived(this, (reader) => {
        this._editorContainer.readEffect(reader);
        this._previewEditorObs.model.read(reader);
        this._display.read(reader);
        if (this._nonOverflowView) {
          this._nonOverflowView.element.style.display = this._display.read(reader);
        }
        const uiState = this._uiState.read(reader);
        const edit2 = this._edit.read(reader);
        if (!uiState || !edit2) {
          return;
        }
        const range2 = edit2.originalLineRange;
        const hiddenAreas = [];
        if (range2.startLineNumber > 1) {
          hiddenAreas.push(new Range$2(1, 1, range2.startLineNumber - 1, 1));
        }
        if (range2.startLineNumber + uiState.newTextLineCount < this._previewTextModel.getLineCount() + 1) {
          hiddenAreas.push(new Range$2(range2.startLineNumber + uiState.newTextLineCount, 1, this._previewTextModel.getLineCount() + 1, 1));
        }
        this.previewEditor.setHiddenAreas(hiddenAreas, void 0, true);
        const previousViewZones = [...this._activeViewZones];
        this._activeViewZones = [];
        const reducedLinesCount = range2.endLineNumberExclusive - range2.startLineNumber - uiState.newTextLineCount;
        this.previewEditor.changeViewZones((changeAccessor) => {
          previousViewZones.forEach((id) => changeAccessor.removeZone(id));
          if (reducedLinesCount > 0) {
            this._activeViewZones.push(changeAccessor.addZone({
              afterLineNumber: range2.startLineNumber + uiState.newTextLineCount - 1,
              heightInLines: reducedLinesCount,
              showInHiddenAreas: true,
              domNode: $$l("div.diagonal-fill.inline-edits-view-zone")
            }));
          }
        });
      });
      this._previewEditorWidth = derived(this, (reader) => {
        const edit2 = this._edit.read(reader);
        if (!edit2) {
          return 0;
        }
        this._updatePreviewEditor.read(reader);
        return maxContentWidthInRange(this._previewEditorObs, edit2.modifiedLineRange, reader);
      });
      this._cursorPosIfTouchesEdit = derived(this, (reader) => {
        const cursorPos = this._editorObs.cursorPosition.read(reader);
        const edit2 = this._edit.read(reader);
        if (!edit2 || !cursorPos) {
          return void 0;
        }
        return edit2.modifiedLineRange.contains(cursorPos.lineNumber) ? cursorPos : void 0;
      });
      this._originalStartPosition = derived(this, (reader) => {
        const inlineEdit = this._edit.read(reader);
        return inlineEdit ? new Position$1(inlineEdit.originalLineRange.startLineNumber, 1) : null;
      });
      this._originalEndPosition = derived(this, (reader) => {
        const inlineEdit = this._edit.read(reader);
        return inlineEdit ? new Position$1(inlineEdit.originalLineRange.endLineNumberExclusive, 1) : null;
      });
      this._originalVerticalStartPosition = this._editorObs.observePosition(this._originalStartPosition, this._store).map((p) => p?.y);
      this._originalVerticalEndPosition = this._editorObs.observePosition(this._originalEndPosition, this._store).map((p) => p?.y);
      this._originalDisplayRange = this._edit.map((e) => e?.displayRange);
      this._editorMaxContentWidthInRange = derived(this, (reader) => {
        const originalDisplayRange = this._originalDisplayRange.read(reader);
        if (!originalDisplayRange) {
          return constObservable(0);
        }
        this._editorObs.versionId.read(reader);
        return derivedObservableWithCache(this, (reader2, lastValue) => {
          const maxWidth = maxContentWidthInRange(this._editorObs, originalDisplayRange, reader2);
          return Math.max(maxWidth, lastValue ?? 0);
        });
      }).map((v, r) => v.read(r));
      this._previewEditorLayoutInfo = derived(this, (reader) => {
        const inlineEdit = this._edit.read(reader);
        if (!inlineEdit) {
          return null;
        }
        const state = this._uiState.read(reader);
        if (!state) {
          return null;
        }
        const range2 = inlineEdit.originalLineRange;
        const horizontalScrollOffset = this._editorObs.scrollLeft.read(reader);
        const editorContentMaxWidthInRange = this._editorMaxContentWidthInRange.read(reader);
        const editorLayout = this._editorObs.layoutInfo.read(reader);
        const previewContentWidth = this._previewEditorWidth.read(reader);
        const editorContentAreaWidth = editorLayout.contentWidth - editorLayout.verticalScrollbarWidth;
        const editorBoundingClientRect = this._editor.getContainerDomNode().getBoundingClientRect();
        const clientContentAreaRight = editorLayout.contentLeft + editorLayout.contentWidth + editorBoundingClientRect.left;
        const remainingWidthRightOfContent = getWindow(this._editor.getContainerDomNode()).innerWidth - clientContentAreaRight;
        const remainingWidthRightOfEditor = getWindow(this._editor.getContainerDomNode()).innerWidth - editorBoundingClientRect.right;
        const desiredMinimumWidth = Math.min(editorLayout.contentWidth * 0.3, previewContentWidth, 100);
        const IN_EDITOR_DISPLACEMENT = 0;
        const maximumAvailableWidth = IN_EDITOR_DISPLACEMENT + remainingWidthRightOfContent;
        const cursorPos = this._cursorPosIfTouchesEdit.read(reader);
        const maxPreviewEditorLeft = Math.max(
          // We're starting from the content area right and moving it left by IN_EDITOR_DISPLACEMENT and also by an amount to ensure some minimum desired width
          editorContentAreaWidth + horizontalScrollOffset - IN_EDITOR_DISPLACEMENT - Math.max(0, desiredMinimumWidth - maximumAvailableWidth),
          // But we don't want that the moving left ends up covering the cursor, so this will push it to the right again
          Math.min(cursorPos ? getOffsetForPos(this._editorObs, cursorPos, reader) + 50 : 0, editorContentAreaWidth + horizontalScrollOffset)
        );
        const previewEditorLeftInTextArea = Math.min(editorContentMaxWidthInRange + ORIGINAL_END_PADDING, maxPreviewEditorLeft);
        const maxContentWidth = editorContentMaxWidthInRange + ORIGINAL_END_PADDING + previewContentWidth + 70;
        const dist = maxPreviewEditorLeft - previewEditorLeftInTextArea;
        let desiredPreviewEditorScrollLeft;
        let codeRight;
        if (previewEditorLeftInTextArea > horizontalScrollOffset) {
          desiredPreviewEditorScrollLeft = 0;
          codeRight = editorLayout.contentLeft + previewEditorLeftInTextArea - horizontalScrollOffset;
        } else {
          desiredPreviewEditorScrollLeft = horizontalScrollOffset - previewEditorLeftInTextArea;
          codeRight = editorLayout.contentLeft;
        }
        const selectionTop = this._originalVerticalStartPosition.read(reader) ?? this._editor.getTopForLineNumber(range2.startLineNumber) - this._editorObs.scrollTop.read(reader);
        const selectionBottom = this._originalVerticalEndPosition.read(reader) ?? this._editor.getBottomForLineNumber(range2.endLineNumberExclusive - 1) - this._editorObs.scrollTop.read(reader);
        const codeLeft = editorLayout.contentLeft - horizontalScrollOffset;
        let codeRect = Rect.fromLeftTopRightBottom(codeLeft, selectionTop, codeRight, selectionBottom);
        const isInsertion2 = codeRect.height === 0;
        if (!isInsertion2) {
          codeRect = codeRect.withMargin(VERTICAL_PADDING, HORIZONTAL_PADDING);
        }
        const previewLineHeights = this._previewEditorObs.observeLineHeightsForLineRange(inlineEdit.modifiedLineRange).read(reader);
        const editHeight = previewLineHeights.reduce((acc, h2) => acc + h2, 0);
        const codeHeight = selectionBottom - selectionTop;
        const previewEditorHeight = Math.max(codeHeight, editHeight);
        const clipped = dist === 0;
        const codeEditDist = 0;
        const previewEditorWidth = Math.min(previewContentWidth + MODIFIED_END_PADDING, remainingWidthRightOfEditor + editorLayout.width - editorLayout.contentLeft - codeEditDist);
        let editRect = Rect.fromLeftTopWidthHeight(codeRect.right + codeEditDist, selectionTop, previewEditorWidth, previewEditorHeight);
        if (!isInsertion2) {
          editRect = editRect.withMargin(VERTICAL_PADDING, HORIZONTAL_PADDING).translateX(HORIZONTAL_PADDING + BORDER_WIDTH$1);
        } else {
          editRect = editRect.withMargin(VERTICAL_PADDING, HORIZONTAL_PADDING).translateY(VERTICAL_PADDING);
        }
        return {
          codeRect,
          editRect,
          codeScrollLeft: horizontalScrollOffset,
          contentLeft: editorLayout.contentLeft,
          isInsertion: isInsertion2,
          maxContentWidth,
          shouldShowShadow: clipped,
          desiredPreviewEditorScrollLeft,
          previewEditorWidth
        };
      });
      this._stickyScrollController = StickyScrollController.get(this._editorObs.editor);
      this._stickyScrollHeight = this._stickyScrollController ? observableFromEvent(this._stickyScrollController.onDidChangeStickyScrollHeight, () => this._stickyScrollController.stickyScrollWidgetHeight) : constObservable(0);
      this._shouldOverflow = derived(this, (reader) => {
        {
          return false;
        }
      });
      this._originalBackgroundColor = observableFromEvent(this, this._themeService.onDidColorThemeChange, () => {
        return this._themeService.getColorTheme().getColor(originalBackgroundColor) ?? Color.transparent;
      });
      this._backgroundSvg = n.svg({
        transform: "translate(-0.5 -0.5)",
        style: { overflow: "visible", pointerEvents: "none", position: "absolute" }
      }, [
        n.svgElem("path", {
          class: "rightOfModifiedBackgroundCoverUp",
          d: derived(this, (reader) => {
            const layoutInfo = this._previewEditorLayoutInfo.read(reader);
            if (!layoutInfo) {
              return void 0;
            }
            const originalBackgroundColor2 = this._originalBackgroundColor.read(reader);
            if (originalBackgroundColor2.isTransparent()) {
              return void 0;
            }
            return new PathBuilder().moveTo(layoutInfo.codeRect.getRightTop()).lineTo(layoutInfo.codeRect.getRightTop().deltaX(1e3)).lineTo(layoutInfo.codeRect.getRightBottom().deltaX(1e3)).lineTo(layoutInfo.codeRect.getRightBottom()).build();
          }),
          style: {
            fill: asCssVariableWithDefault(editorBackground, "transparent")
          }
        })
      ]).keepUpdated(this._store);
      this._originalOverlay = n.div({
        style: { pointerEvents: "none", display: this._previewEditorLayoutInfo.map((layoutInfo) => layoutInfo?.isInsertion ? "none" : "block") }
      }, derived(this, (reader) => {
        const layoutInfoObs = mapOutFalsy(this._previewEditorLayoutInfo).read(reader);
        if (!layoutInfoObs) {
          return void 0;
        }
        const separatorWidth = separatorWidthObs.read(reader);
        const borderStyling = getOriginalBorderColor(this._tabAction).map((bc) => `${BORDER_WIDTH$1}px solid ${asCssVariable(bc)}`);
        const borderStylingSeparator = `${BORDER_WIDTH$1 + separatorWidth}px solid ${asCssVariable(editorBackground)}`;
        const hasBorderLeft = layoutInfoObs.read(reader).codeScrollLeft !== 0;
        const isModifiedLower = layoutInfoObs.map((layoutInfo) => layoutInfo.codeRect.bottom < layoutInfo.editRect.bottom);
        const transitionRectSize = BORDER_RADIUS * 2 + BORDER_WIDTH$1 * 2;
        const overlayHider = layoutInfoObs.map((layoutInfo) => Rect.fromLeftTopRightBottom(layoutInfo.contentLeft - BORDER_RADIUS - BORDER_WIDTH$1, layoutInfo.codeRect.top, layoutInfo.contentLeft, layoutInfo.codeRect.bottom + transitionRectSize)).read(reader);
        const intersectionLine = new OffsetRange(overlayHider.left, Number.MAX_SAFE_INTEGER);
        const overlayRect = layoutInfoObs.map((layoutInfo) => layoutInfo.codeRect.intersectHorizontal(intersectionLine));
        const separatorRect = overlayRect.map((overlayRect2) => overlayRect2.withMargin(separatorWidth, 0, separatorWidth, separatorWidth).intersectHorizontal(intersectionLine));
        const transitionRect = overlayRect.map((overlayRect2) => Rect.fromLeftTopWidthHeight(overlayRect2.right - transitionRectSize + BORDER_WIDTH$1, overlayRect2.bottom - BORDER_WIDTH$1, transitionRectSize, transitionRectSize).intersectHorizontal(intersectionLine));
        return [
          n.div({
            class: "originalSeparatorSideBySide",
            style: {
              ...separatorRect.read(reader).toStyles(),
              boxSizing: "border-box",
              borderRadius: `${BORDER_RADIUS}px 0 0 ${BORDER_RADIUS}px`,
              borderTop: borderStylingSeparator,
              borderBottom: borderStylingSeparator,
              borderLeft: hasBorderLeft ? "none" : borderStylingSeparator
            }
          }),
          n.div({
            class: "originalOverlaySideBySide",
            style: {
              ...overlayRect.read(reader).toStyles(),
              boxSizing: "border-box",
              borderRadius: `${BORDER_RADIUS}px 0 0 ${BORDER_RADIUS}px`,
              borderTop: borderStyling,
              borderBottom: borderStyling,
              borderLeft: hasBorderLeft ? "none" : borderStyling,
              backgroundColor: asCssVariable(originalBackgroundColor)
            }
          }),
          n.div({
            class: "originalCornerCutoutSideBySide",
            style: {
              pointerEvents: "none",
              display: isModifiedLower.map((isLower2) => isLower2 ? "block" : "none"),
              ...transitionRect.read(reader).toStyles()
            }
          }, [
            n.div({
              class: "originalCornerCutoutBackground",
              style: {
                position: "absolute",
                top: "0px",
                left: "0px",
                width: "100%",
                height: "100%",
                backgroundColor: getEditorBlendedColor(originalBackgroundColor, this._themeService).map((c) => c.toString())
              }
            }),
            n.div({
              class: "originalCornerCutoutBorder",
              style: {
                position: "absolute",
                top: "0px",
                left: "0px",
                width: "100%",
                height: "100%",
                boxSizing: "border-box",
                borderTop: borderStyling,
                borderRight: borderStyling,
                borderRadius: `0 100% 0 0`,
                backgroundColor: asCssVariable(editorBackground)
              }
            })
          ]),
          n.div({
            class: "originalOverlaySideBySideHider",
            style: {
              ...overlayHider.toStyles(),
              backgroundColor: asCssVariable(editorBackground)
            }
          })
        ];
      })).keepUpdated(this._store);
      this._modifiedOverlay = n.div({
        style: { pointerEvents: "none" }
      }, derived(this, (reader) => {
        const layoutInfoObs = mapOutFalsy(this._previewEditorLayoutInfo).read(reader);
        if (!layoutInfoObs) {
          return void 0;
        }
        const isModifiedLower = layoutInfoObs.map((layoutInfo) => layoutInfo.codeRect.bottom < layoutInfo.editRect.bottom);
        const separatorWidth = separatorWidthObs.read(reader);
        const borderRadius = isModifiedLower.map((isLower2) => `0 ${BORDER_RADIUS}px ${BORDER_RADIUS}px ${isLower2 ? BORDER_RADIUS : 0}px`);
        const borderStyling = getEditorBlendedColor(getModifiedBorderColor(this._tabAction), this._themeService).map((c) => `1px solid ${c.toString()}`);
        const borderStylingSeparator = `${BORDER_WIDTH$1 + separatorWidth}px solid ${asCssVariable(editorBackground)}`;
        const overlayRect = layoutInfoObs.map((layoutInfo) => layoutInfo.editRect.withMargin(0, BORDER_WIDTH$1));
        const separatorRect = overlayRect.map((overlayRect2) => overlayRect2.withMargin(separatorWidth, separatorWidth, separatorWidth, 0));
        const insertionRect = derived(this, (reader2) => {
          const overlay = overlayRect.read(reader2);
          const layoutinfo = layoutInfoObs.read(reader2);
          if (!layoutinfo.isInsertion || layoutinfo.contentLeft >= overlay.left) {
            return Rect.fromLeftTopWidthHeight(overlay.left, overlay.top, 0, 0);
          }
          return new Rect(layoutinfo.contentLeft, overlay.top, overlay.left, overlay.top + BORDER_WIDTH$1 * 2);
        });
        return [
          n.div({
            class: "modifiedInsertionSideBySide",
            style: {
              ...insertionRect.read(reader).toStyles(),
              backgroundColor: getModifiedBorderColor(this._tabAction).map((c) => asCssVariable(c))
            }
          }),
          n.div({
            class: "modifiedSeparatorSideBySide",
            style: {
              ...separatorRect.read(reader).toStyles(),
              borderRadius,
              borderTop: borderStylingSeparator,
              borderBottom: borderStylingSeparator,
              borderRight: borderStylingSeparator,
              boxSizing: "border-box"
            }
          }),
          n.div({
            class: "modifiedOverlaySideBySide",
            style: {
              ...overlayRect.read(reader).toStyles(),
              borderRadius,
              border: borderStyling,
              boxSizing: "border-box",
              backgroundColor: asCssVariable(modifiedBackgroundColor)
            }
          })
        ];
      })).keepUpdated(this._store);
      this._nonOverflowView = n.div({
        class: "inline-edits-view",
        style: {
          position: "absolute",
          overflow: "visible",
          top: "0px",
          left: "0px",
          display: this._display
        }
      }, [
        this._backgroundSvg,
        derived(this, (reader) => this._shouldOverflow.read(reader) ? [] : [this._editorContainer, this._originalOverlay, this._modifiedOverlay])
      ]).keepUpdated(this._store);
      this._register(this._editorObs.createOverlayWidget({
        domNode: this._nonOverflowView.element,
        position: constObservable(null),
        allowEditorOverflow: false,
        minContentWidthInPx: derived(this, (reader) => {
          const x = this._previewEditorLayoutInfo.read(reader)?.maxContentWidth;
          if (x === void 0) {
            return 0;
          }
          return x;
        })
      }));
      this.previewEditor.setModel(this._previewTextModel);
      this._register(autorun((reader) => {
        const layoutInfo = this._previewEditorLayoutInfo.read(reader);
        if (!layoutInfo) {
          return;
        }
        const editorRect = layoutInfo.editRect.withMargin(-VERTICAL_PADDING, -HORIZONTAL_PADDING);
        this.previewEditor.layout({
          height: editorRect.height,
          width: layoutInfo.previewEditorWidth + 15
          /* Make sure editor does not scroll horizontally */
        });
        this._editorContainer.element.style.top = `${editorRect.top}px`;
        this._editorContainer.element.style.left = `${editorRect.left}px`;
        this._editorContainer.element.style.width = `${layoutInfo.previewEditorWidth + HORIZONTAL_PADDING}px`;
      }));
      this._register(autorun((reader) => {
        const layoutInfo = this._previewEditorLayoutInfo.read(reader);
        if (!layoutInfo) {
          return;
        }
        this._previewEditorObs.editor.setScrollLeft(layoutInfo.desiredPreviewEditorScrollLeft);
      }));
      this._updatePreviewEditor.recomputeInitiallyAndOnChange(this._store);
    }
  };
  InlineEditsSideBySideView = __decorate$19([
    __param$18(5, IInstantiationService),
    __param$18(6, IThemeService)
  ], InlineEditsSideBySideView);
  var __decorate$18 = 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$17 = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  const BORDER_WIDTH = 1;
  let InlineEditsWordReplacementView = (_ja = class extends Disposable {
    constructor(_editor, _edit, _tabAction, _languageService) {
      super();
      this._editor = _editor;
      this._edit = _edit;
      this._tabAction = _tabAction;
      this._languageService = _languageService;
      this._onDidClick = this._register(new Emitter$1());
      this.onDidClick = this._onDidClick.event;
      this._start = this._editor.observePosition(constObservable(this._edit.range.getStartPosition()), this._store);
      this._end = this._editor.observePosition(constObservable(this._edit.range.getEndPosition()), this._store);
      this._line = document.createElement("div");
      this._hoverableElement = observableValue(this, null);
      this.isHovered = this._hoverableElement.map((e, reader) => e?.didMouseMoveDuringHover.read(reader) ?? false);
      this._renderTextEffect = derived(this, (_reader) => {
        const tm = this._editor.model.get();
        const origLine = tm.getLineContent(this._edit.range.startLineNumber);
        const edit2 = StringReplacement.replace(new OffsetRange(this._edit.range.startColumn - 1, this._edit.range.endColumn - 1), this._edit.text);
        const lineToTokenize = edit2.replace(origLine);
        const t = tm.tokenization.tokenizeLinesAt(this._edit.range.startLineNumber, [lineToTokenize])?.[0];
        let tokens;
        if (t) {
          tokens = TokenArray.fromLineTokens(t).slice(edit2.getRangeAfterReplace()).toLineTokens(this._edit.text, this._languageService.languageIdCodec);
        } else {
          tokens = LineTokens.createEmpty(this._edit.text, this._languageService.languageIdCodec);
        }
        const res = renderLines$1(new LineSource([tokens]), RenderOptions.fromEditor(this._editor.editor).withSetWidth(false).withScrollBeyondLastColumn(0), [], this._line, true);
        this._line.style.width = `${res.minWidthInPx}px`;
      });
      const modifiedLineHeight = this._editor.observeLineHeightForPosition(this._edit.range.getStartPosition());
      this._layout = derived(this, (reader) => {
        this._renderTextEffect.read(reader);
        const widgetStart = this._start.read(reader);
        const widgetEnd = this._end.read(reader);
        if (!widgetStart || !widgetEnd || widgetStart.x > widgetEnd.x || widgetStart.y > widgetEnd.y) {
          return void 0;
        }
        const lineHeight = modifiedLineHeight.read(reader);
        const scrollLeft = this._editor.scrollLeft.read(reader);
        const w = this._editor.getOption(
          59
          /* EditorOption.fontInfo */
        ).read(reader).typicalHalfwidthCharacterWidth;
        const modifiedLeftOffset = 3 * w;
        const modifiedTopOffset = 4;
        const modifiedOffset = new Point(modifiedLeftOffset, modifiedTopOffset);
        const originalLine = Rect.fromPoints(widgetStart, widgetEnd).withHeight(lineHeight).translateX(-scrollLeft);
        const modifiedLine = Rect.fromPointSize(originalLine.getLeftBottom().add(modifiedOffset), new Point(this._edit.text.length * w, originalLine.height));
        const lowerBackground = modifiedLine.withLeft(originalLine.left);
        return {
          originalLine,
          modifiedLine,
          lowerBackground,
          lineHeight
        };
      });
      this.minEditorScrollHeight = derived(this, (reader) => {
        const layout2 = mapOutFalsy(this._layout).read(reader);
        if (!layout2) {
          return 0;
        }
        return layout2.read(reader).modifiedLine.bottom + BORDER_WIDTH + this._editor.editor.getScrollTop();
      });
      this._root = n.div({
        class: "word-replacement"
      }, [
        derived(this, (reader) => {
          const layout2 = mapOutFalsy(this._layout).read(reader);
          if (!layout2) {
            return [];
          }
          const originalBorderColor = getOriginalBorderColor(this._tabAction).map((c) => asCssVariable(c)).read(reader);
          const modifiedBorderColor = getModifiedBorderColor(this._tabAction).map((c) => asCssVariable(c)).read(reader);
          return [
            n.div({
              style: {
                position: "absolute",
                ...rectToProps((r) => getEditorValidOverlayRect(this._editor).read(r)),
                overflow: "hidden",
                pointerEvents: "none"
              }
            }, [
              n.div({
                style: {
                  position: "absolute",
                  ...rectToProps((reader2) => layout2.read(reader2).lowerBackground.withMargin(BORDER_WIDTH, 2 * BORDER_WIDTH, BORDER_WIDTH, 0)),
                  background: asCssVariable(editorBackground),
                  //boxShadow: `${asCssVariable(scrollbarShadow)} 0 6px 6px -6px`,
                  cursor: "pointer",
                  pointerEvents: "auto"
                },
                onmousedown: (e) => {
                  e.preventDefault();
                },
                onmouseup: (e) => this._onDidClick.fire(new StandardMouseEvent(getWindow(e), e)),
                obsRef: (elem) => {
                  this._hoverableElement.set(elem, void 0);
                }
              }),
              n.div({
                style: {
                  position: "absolute",
                  ...rectToProps((reader2) => layout2.read(reader2).modifiedLine.withMargin(BORDER_WIDTH, 2 * BORDER_WIDTH)),
                  fontFamily: this._editor.getOption(
                    58
                    /* EditorOption.fontFamily */
                  ),
                  fontSize: this._editor.getOption(
                    61
                    /* EditorOption.fontSize */
                  ),
                  fontWeight: this._editor.getOption(
                    62
                    /* EditorOption.fontWeight */
                  ),
                  pointerEvents: "none",
                  boxSizing: "border-box",
                  borderRadius: "4px",
                  border: `${BORDER_WIDTH}px solid ${modifiedBorderColor}`,
                  background: asCssVariable(modifiedChangedTextOverlayColor),
                  display: "flex",
                  justifyContent: "center",
                  alignItems: "center",
                  outline: `2px solid ${asCssVariable(editorBackground)}`
                }
              }, [this._line]),
              n.div({
                style: {
                  position: "absolute",
                  ...rectToProps((reader2) => layout2.read(reader2).originalLine.withMargin(BORDER_WIDTH)),
                  boxSizing: "border-box",
                  borderRadius: "4px",
                  border: `${BORDER_WIDTH}px solid ${originalBorderColor}`,
                  background: asCssVariable(originalChangedTextOverlayColor),
                  pointerEvents: "none"
                }
              }, []),
              n.svg({
                width: 11,
                height: 14,
                viewBox: "0 0 11 14",
                fill: "none",
                style: {
                  position: "absolute",
                  left: layout2.map((l) => l.modifiedLine.left - 16),
                  top: layout2.map((l) => l.modifiedLine.top + Math.round((l.lineHeight - 14 - 5) / 2))
                }
              }, [
                n.svgElem("path", {
                  d: "M1 0C1 2.98966 1 5.92087 1 8.49952C1 9.60409 1.89543 10.5 3 10.5H10.5",
                  stroke: asCssVariable(editorHoverForeground)
                }),
                n.svgElem("path", {
                  d: "M6 7.5L9.99999 10.49998L6 13.5",
                  stroke: asCssVariable(editorHoverForeground)
                })
              ])
            ])
          ];
        })
      ]).keepUpdated(this._store);
      this._register(this._editor.createOverlayWidget({
        domNode: this._root.element,
        minContentWidthInPx: constObservable(0),
        position: constObservable({ preference: { top: 0, left: 0 } }),
        allowEditorOverflow: false
      }));
    }
  }, _ja.MAX_LENGTH = 100, _ja);
  InlineEditsWordReplacementView = __decorate$18([
    __param$17(3, ILanguageService)
  ], InlineEditsWordReplacementView);
  class OriginalEditorInlineDiffView extends Disposable {
    constructor(_originalEditor, _state, _modifiedTextModel) {
      super();
      this._originalEditor = _originalEditor;
      this._state = _state;
      this._modifiedTextModel = _modifiedTextModel;
      this._onDidClick = this._register(new Emitter$1());
      this.onDidClick = this._onDidClick.event;
      this.isHovered = observableCodeEditor(this._originalEditor).isTargetHovered((p) => p.target.type === 6 && p.target.detail.injectedText?.options.attachedData instanceof InlineEditAttachedData && p.target.detail.injectedText.options.attachedData.owner === this, this._store);
      this._tokenizationFinished = modelTokenizationFinished(this._modifiedTextModel);
      this._decorations = derived(this, (reader) => {
        const diff = this._state.read(reader);
        if (!diff) {
          return void 0;
        }
        const modified = diff.modifiedText;
        const showInline = diff.mode === "insertionInline";
        const hasOneInnerChange = diff.diff.length === 1 && diff.diff[0].innerChanges?.length === 1;
        const showEmptyDecorations = true;
        const originalDecorations = [];
        const modifiedDecorations = [];
        const diffLineAddDecorationBackground2 = ModelDecorationOptions.register({
          className: "inlineCompletions-line-insert",
          description: "line-insert",
          isWholeLine: true,
          marginClassName: "gutter-insert"
        });
        const diffLineDeleteDecorationBackground2 = ModelDecorationOptions.register({
          className: "inlineCompletions-line-delete",
          description: "line-delete",
          isWholeLine: true,
          marginClassName: "gutter-delete"
        });
        const diffWholeLineDeleteDecoration2 = ModelDecorationOptions.register({
          className: "inlineCompletions-char-delete",
          description: "char-delete",
          isWholeLine: false,
          zIndex: 1
          // be on top of diff background decoration
        });
        const diffWholeLineAddDecoration2 = ModelDecorationOptions.register({
          className: "inlineCompletions-char-insert",
          description: "char-insert",
          isWholeLine: true
        });
        const diffAddDecoration2 = ModelDecorationOptions.register({
          className: "inlineCompletions-char-insert",
          description: "char-insert",
          shouldFillLineOnLineBreak: true
        });
        const diffAddDecorationEmpty2 = ModelDecorationOptions.register({
          className: "inlineCompletions-char-insert diff-range-empty",
          description: "char-insert diff-range-empty"
        });
        const NESOriginalBackground = ModelDecorationOptions.register({
          className: "inlineCompletions-original-lines",
          description: "inlineCompletions-original-lines",
          isWholeLine: false,
          shouldFillLineOnLineBreak: true
        });
        const showFullLineDecorations = diff.mode !== "sideBySide" && diff.mode !== "deletion" && diff.mode !== "insertionInline" && diff.mode !== "lineReplacement";
        const hideEmptyInnerDecorations = diff.mode === "lineReplacement";
        for (const m of diff.diff) {
          if (showFullLineDecorations) {
            if (!m.original.isEmpty) {
              originalDecorations.push({
                range: m.original.toInclusiveRange(),
                options: diffLineDeleteDecorationBackground2
              });
            }
            if (!m.modified.isEmpty) {
              modifiedDecorations.push({
                range: m.modified.toInclusiveRange(),
                options: diffLineAddDecorationBackground2
              });
            }
          }
          if (m.modified.isEmpty || m.original.isEmpty) {
            if (!m.original.isEmpty) {
              originalDecorations.push({ range: m.original.toInclusiveRange(), options: diffWholeLineDeleteDecoration2 });
            }
            if (!m.modified.isEmpty) {
              modifiedDecorations.push({ range: m.modified.toInclusiveRange(), options: diffWholeLineAddDecoration2 });
            }
          } else {
            const useInlineDiff = showInline && allowsTrueInlineDiffRendering(m);
            for (const i2 of m.innerChanges || []) {
              if (m.original.contains(i2.originalRange.startLineNumber) && !(hideEmptyInnerDecorations && i2.originalRange.isEmpty())) {
                const replacedText = this._originalEditor.getModel()?.getValueInRange(
                  i2.originalRange,
                  1
                  /* EndOfLinePreference.LF */
                );
                originalDecorations.push({
                  range: i2.originalRange,
                  options: {
                    description: "char-delete",
                    shouldFillLineOnLineBreak: false,
                    className: classNames("inlineCompletions-char-delete", i2.originalRange.isSingleLine() && diff.mode === "insertionInline" && "single-line-inline", i2.originalRange.isEmpty() && "empty", (i2.originalRange.isEmpty() && hasOneInnerChange || diff.mode === "deletion" && replacedText === "\n") && showEmptyDecorations && !useInlineDiff && "diff-range-empty"),
                    inlineClassName: useInlineDiff ? classNames("strike-through", "inlineCompletions") : null,
                    zIndex: 1
                  }
                });
              }
              if (m.modified.contains(i2.modifiedRange.startLineNumber)) {
                modifiedDecorations.push({
                  range: i2.modifiedRange,
                  options: i2.modifiedRange.isEmpty() && showEmptyDecorations && !useInlineDiff && hasOneInnerChange ? diffAddDecorationEmpty2 : diffAddDecoration2
                });
              }
              if (useInlineDiff) {
                const insertedText = modified.getValueOfRange(i2.modifiedRange);
                const textSegments = insertedText.length > 3 ? [
                  { text: insertedText.slice(0, 1), extraClasses: ["start"], offsetRange: new OffsetRange(i2.modifiedRange.startColumn - 1, i2.modifiedRange.startColumn) },
                  { text: insertedText.slice(1, -1), extraClasses: [], offsetRange: new OffsetRange(i2.modifiedRange.startColumn, i2.modifiedRange.endColumn - 2) },
                  { text: insertedText.slice(-1), extraClasses: ["end"], offsetRange: new OffsetRange(i2.modifiedRange.endColumn - 2, i2.modifiedRange.endColumn - 1) }
                ] : [
                  { text: insertedText, extraClasses: ["start", "end"], offsetRange: new OffsetRange(i2.modifiedRange.startColumn - 1, i2.modifiedRange.endColumn) }
                ];
                this._tokenizationFinished.read(reader);
                const lineTokens = this._modifiedTextModel.tokenization.getLineTokens(i2.modifiedRange.startLineNumber);
                for (const { text: text2, extraClasses, offsetRange } of textSegments) {
                  originalDecorations.push({
                    range: Range$2.fromPositions(i2.originalRange.getEndPosition()),
                    options: {
                      description: "inserted-text",
                      before: {
                        tokens: lineTokens.getTokensInRange(offsetRange),
                        content: text2,
                        inlineClassName: classNames(
                          "inlineCompletions-char-insert",
                          i2.modifiedRange.isSingleLine() && diff.mode === "insertionInline" && "single-line-inline",
                          ...extraClasses
                          // include extraClasses for additional styling if provided
                        ),
                        cursorStops: InjectedTextCursorStops$1.None,
                        attachedData: new InlineEditAttachedData(this)
                      },
                      zIndex: 2,
                      showIfCollapsed: true
                    }
                  });
                }
              }
            }
          }
        }
        if (diff.isInDiffEditor) {
          for (const m of diff.diff) {
            if (!m.original.isEmpty) {
              originalDecorations.push({
                range: m.original.toExclusiveRange(),
                options: NESOriginalBackground
              });
            }
          }
        }
        return { originalDecorations, modifiedDecorations };
      });
      this._register(observableCodeEditor(this._originalEditor).setDecorations(this._decorations.map((d) => d?.originalDecorations ?? [])));
      const modifiedCodeEditor = this._state.map((s) => s?.modifiedCodeEditor);
      this._register(autorunWithStore((reader, store) => {
        const e = modifiedCodeEditor.read(reader);
        if (e) {
          store.add(observableCodeEditor(e).setDecorations(this._decorations.map((d) => d?.modifiedDecorations ?? [])));
        }
      }));
      this._register(this._originalEditor.onMouseUp((e) => {
        if (e.target.type !== 6) {
          return;
        }
        const a = e.target.detail.injectedText?.options.attachedData;
        if (a instanceof InlineEditAttachedData && a.owner === this) {
          this._onDidClick.fire(e.event);
        }
      }));
    }
  }
  class InlineEditAttachedData {
    constructor(owner) {
      this.owner = owner;
    }
  }
  function allowsTrueInlineDiffRendering(mapping) {
    if (!mapping.innerChanges) {
      return false;
    }
    return mapping.innerChanges.every((c) => rangeIsSingleLine(c.modifiedRange) && rangeIsSingleLine(c.originalRange));
  }
  let i = 0;
  function modelTokenizationFinished(model) {
    return observableFromEvent(model.onDidChangeTokens, () => i++);
  }
  var __decorate$17 = 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$16 = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  let InlineEditsView = class InlineEditsView extends Disposable {
    constructor(_editor, _host, _model, _ghostTextIndicator, _focusIsInMenu, _instantiationService) {
      super();
      this._editor = _editor;
      this._host = _host;
      this._model = _model;
      this._ghostTextIndicator = _ghostTextIndicator;
      this._focusIsInMenu = _focusIsInMenu;
      this._instantiationService = _instantiationService;
      this._editorObs = observableCodeEditor(this._editor);
      this._tabAction = derived((reader) => this._model.read(reader)?.tabAction.read(reader) ?? InlineEditTabAction.Inactive);
      this._constructorDone = observableValue(this, false);
      this._uiState = derived(this, (reader) => {
        const model = this._model.read(reader);
        if (!model || !this._constructorDone.read(reader)) {
          return void 0;
        }
        const inlineEdit = model.inlineEdit;
        let mappings = RangeMapping.fromEdit(inlineEdit.edit);
        let newText = inlineEdit.edit.apply(inlineEdit.originalText);
        let diff = lineRangeMappingFromRangeMappings(mappings, inlineEdit.originalText, new StringText(newText));
        let state = this.determineRenderState(model, reader, diff, new StringText(newText));
        if (!state) {
          onUnexpectedError(new Error(`unable to determine view: tried to render ${this._previousView?.view}`));
          return void 0;
        }
        if (state.kind === InlineCompletionViewKind.SideBySide) {
          const indentationAdjustmentEdit = createReindentEdit(newText, inlineEdit.modifiedLineRange, textModel.getOptions().tabSize);
          newText = indentationAdjustmentEdit.applyToString(newText);
          mappings = applyEditToModifiedRangeMappings(mappings, indentationAdjustmentEdit);
          diff = lineRangeMappingFromRangeMappings(mappings, inlineEdit.originalText, new StringText(newText));
        }
        this._previewTextModel.setLanguage(this._editor.getModel().getLanguageId());
        const previousNewText = this._previewTextModel.getValue();
        if (previousNewText !== newText) {
          this._previewTextModel.setValue(newText);
        }
        if (model.showCollapsed.read(reader) && !this._indicator.read(reader)?.isHoverVisible.read(reader)) {
          state = { kind: InlineCompletionViewKind.Collapsed, viewData: state.viewData };
        }
        model.handleInlineEditShown(state.kind, state.viewData);
        return {
          state,
          diff,
          edit: inlineEdit,
          newText,
          newTextLineCount: inlineEdit.modifiedLineRange.length,
          isInDiffEditor: model.isInDiffEditor
        };
      });
      this._previewTextModel = this._register(this._instantiationService.createInstance(TextModel, "", this._editor.getModel().getLanguageId(), { ...TextModel.DEFAULT_CREATION_OPTIONS, bracketPairColorizationOptions: { enabled: true, independentColorPoolPerBracketType: false } }, null));
      this._indicatorCyclicDependencyCircuitBreaker = observableValue(this, false);
      this._indicator = derived(this, (reader) => {
        if (!this._indicatorCyclicDependencyCircuitBreaker.read(reader)) {
          return void 0;
        }
        const indicatorDisplayRange = derivedOpts({ owner: this, equalsFn: equalsIfDefined(itemEquals()) }, (reader2) => {
          const ghostTextIndicator = this._ghostTextIndicator.read(reader2);
          if (ghostTextIndicator) {
            return ghostTextIndicator.lineRange;
          }
          const state = this._uiState.read(reader2);
          if (!state) {
            return void 0;
          }
          if (state.state?.kind === "custom") {
            const range2 = state.state.displayLocation?.range;
            if (!range2) {
              throw new BugIndicatingError("custom view should have a range");
            }
            return new LineRange(range2.startLineNumber, range2.endLineNumber);
          }
          if (state.state?.kind === "insertionMultiLine") {
            return this._insertion.originalLines.read(reader2);
          }
          return state.edit.displayRange;
        });
        const modelWithGhostTextSupport = derived(this, (reader2) => {
          const model = this._model.read(reader2);
          if (model) {
            return model;
          }
          const ghostTextIndicator = this._ghostTextIndicator.read(reader2);
          if (ghostTextIndicator) {
            return ghostTextIndicator.model;
          }
          return model;
        });
        return reader.store.add(this._instantiationService.createInstance(InlineEditsGutterIndicator, this._editorObs, indicatorDisplayRange, this._gutterIndicatorOffset, modelWithGhostTextSupport, this._inlineEditsIsHovered, this._focusIsInMenu));
      });
      this._inlineEditsIsHovered = derived(this, (reader) => {
        return this._sideBySide.isHovered.read(reader) || this._wordReplacementViews.read(reader).some((v) => v.isHovered.read(reader)) || this._deletion.isHovered.read(reader) || this._inlineDiffView.isHovered.read(reader) || this._lineReplacementView.isHovered.read(reader) || this._insertion.isHovered.read(reader) || this._customView.isHovered.read(reader);
      });
      this._gutterIndicatorOffset = derived(this, (reader) => {
        if (this._uiState.read(reader)?.state?.kind === "insertionMultiLine") {
          return this._insertion.startLineOffset.read(reader);
        }
        const ghostTextIndicator = this._ghostTextIndicator.read(reader);
        if (ghostTextIndicator) {
          return getGhostTextTopOffset(ghostTextIndicator, this._editor);
        }
        return 0;
      });
      this._sideBySide = this._register(this._instantiationService.createInstance(InlineEditsSideBySideView, this._editor, this._model.map((m) => m?.inlineEdit), this._previewTextModel, this._uiState.map((s) => s && s.state?.kind === InlineCompletionViewKind.SideBySide ? {
        newTextLineCount: s.newTextLineCount,
        isInDiffEditor: s.isInDiffEditor
      } : void 0), this._tabAction));
      this._deletion = this._register(this._instantiationService.createInstance(InlineEditsDeletionView, this._editor, this._model.map((m) => m?.inlineEdit), this._uiState.map((s) => s && s.state?.kind === InlineCompletionViewKind.Deletion ? {
        originalRange: s.state.originalRange,
        deletions: s.state.deletions,
        inDiffEditor: s.isInDiffEditor
      } : void 0), this._tabAction));
      this._insertion = this._register(this._instantiationService.createInstance(InlineEditsInsertionView, this._editor, this._uiState.map((s) => s && s.state?.kind === InlineCompletionViewKind.InsertionMultiLine ? {
        lineNumber: s.state.lineNumber,
        startColumn: s.state.column,
        text: s.state.text,
        inDiffEditor: s.isInDiffEditor
      } : void 0), this._tabAction));
      this._inlineDiffViewState = derived(this, (reader) => {
        const e = this._uiState.read(reader);
        if (!e || !e.state) {
          return void 0;
        }
        if (e.state.kind === "wordReplacements" || e.state.kind === "insertionMultiLine" || e.state.kind === "collapsed" || e.state.kind === "custom") {
          return void 0;
        }
        return {
          modifiedText: new StringText(e.newText),
          diff: e.diff,
          mode: e.state.kind,
          modifiedCodeEditor: this._sideBySide.previewEditor,
          isInDiffEditor: e.isInDiffEditor
        };
      });
      this._inlineCollapsedView = this._register(this._instantiationService.createInstance(InlineEditsCollapsedView, this._editor, this._model.map((m, reader) => this._uiState.read(reader)?.state?.kind === "collapsed" ? m?.inlineEdit : void 0)));
      this._customView = this._register(this._instantiationService.createInstance(InlineEditsCustomView, this._editor, this._model.map((m, reader) => this._uiState.read(reader)?.state?.kind === "custom" ? m?.displayLocation : void 0), this._tabAction));
      this._inlineDiffView = this._register(new OriginalEditorInlineDiffView(this._editor, this._inlineDiffViewState, this._previewTextModel));
      this._wordReplacementViews = mapObservableArrayCached(this, this._uiState.map((s) => s?.state?.kind === "wordReplacements" ? s.state.replacements : []), (e, store) => {
        return store.add(this._instantiationService.createInstance(InlineEditsWordReplacementView, this._editorObs, e, this._tabAction));
      });
      this._lineReplacementView = this._register(this._instantiationService.createInstance(InlineEditsLineReplacementView, this._editorObs, this._uiState.map((s) => s?.state?.kind === InlineCompletionViewKind.LineReplacement ? {
        originalRange: s.state.originalRange,
        modifiedRange: s.state.modifiedRange,
        modifiedLines: s.state.modifiedLines,
        replacements: s.state.replacements
      } : void 0), this._uiState.map((s) => s?.isInDiffEditor ?? false), this._tabAction));
      this._useCodeShifting = this._editorObs.getOption(
        71
        /* EditorOption.inlineSuggest */
      ).map((s) => s.edits.allowCodeShifting);
      this._renderSideBySide = this._editorObs.getOption(
        71
        /* EditorOption.inlineSuggest */
      ).map((s) => s.edits.renderSideBySide);
      this._register(autorunWithStore((reader, store) => {
        const model = this._model.read(reader);
        if (!model) {
          return;
        }
        store.add(Event.any(this._sideBySide.onDidClick, this._deletion.onDidClick, this._lineReplacementView.onDidClick, this._insertion.onDidClick, ...this._wordReplacementViews.read(reader).map((w) => w.onDidClick), this._inlineDiffView.onDidClick, this._customView.onDidClick)((e) => {
          if (this._viewHasBeenShownLongerThan(350)) {
            e.preventDefault();
            model.accept();
          }
        }));
      }));
      this._indicator.recomputeInitiallyAndOnChange(this._store);
      this._wordReplacementViews.recomputeInitiallyAndOnChange(this._store);
      this._indicatorCyclicDependencyCircuitBreaker.set(true, void 0);
      this._register(this._instantiationService.createInstance(InlineEditsOnboardingExperience, this._host, this._model, this._indicator, this._inlineCollapsedView));
      const minEditorScrollHeight = derived(this, (reader) => {
        return Math.max(...this._wordReplacementViews.read(reader).map((v) => v.minEditorScrollHeight.read(reader)), this._lineReplacementView.minEditorScrollHeight.read(reader), this._customView.minEditorScrollHeight.read(reader));
      }).recomputeInitiallyAndOnChange(this._store);
      const textModel = this._editor.getModel();
      let viewZoneId;
      this._register(autorun((reader) => {
        const minScrollHeight = minEditorScrollHeight.read(reader);
        this._editor.changeViewZones((accessor) => {
          const scrollHeight = this._editor.getScrollHeight();
          const viewZoneHeight = minScrollHeight - scrollHeight + 1;
          if (viewZoneHeight !== 0 && viewZoneId) {
            accessor.removeZone(viewZoneId);
            viewZoneId = void 0;
          }
          if (viewZoneHeight <= 0) {
            return;
          }
          viewZoneId = accessor.addZone({
            afterLineNumber: textModel.getLineCount(),
            heightInPx: viewZoneHeight,
            domNode: $$l("div.minScrollHeightViewZone")
          });
        });
      }));
      this._constructorDone.set(true, void 0);
    }
    getCacheId(model) {
      return model.inlineEdit.inlineCompletion.identity.id;
    }
    determineView(model, reader, diff, newText) {
      const inlineEdit = model.inlineEdit;
      const canUseCache = this._previousView?.id === this.getCacheId(model) && !model.displayLocation?.jumpToEdit;
      const reconsiderViewEditorWidthChange = this._previousView?.editorWidth !== this._editorObs.layoutInfoWidth.read(reader) && (this._previousView?.view === InlineCompletionViewKind.SideBySide || this._previousView?.view === InlineCompletionViewKind.LineReplacement);
      if (canUseCache && !reconsiderViewEditorWidthChange) {
        return this._previousView.view;
      }
      if (model.inlineEdit.inlineCompletion instanceof InlineEditItem && model.inlineEdit.inlineCompletion.uri) {
        return InlineCompletionViewKind.Custom;
      }
      if (model.displayLocation && !model.inlineEdit.inlineCompletion.identity.jumpedTo.read(reader)) {
        return InlineCompletionViewKind.Custom;
      }
      const numOriginalLines = inlineEdit.originalLineRange.length;
      const numModifiedLines = inlineEdit.modifiedLineRange.length;
      const inner = diff.flatMap((d) => d.innerChanges ?? []);
      const isSingleInnerEdit = inner.length === 1;
      if (!model.isInDiffEditor) {
        if (isSingleInnerEdit && this._useCodeShifting.read(reader) !== "never" && isSingleLineInsertion(diff)) {
          if (isSingleLineInsertionAfterPosition(diff, inlineEdit.cursorPosition)) {
            return InlineCompletionViewKind.InsertionInline;
          }
          return InlineCompletionViewKind.LineReplacement;
        }
        if (isDeletion(inner, inlineEdit, newText)) {
          return InlineCompletionViewKind.Deletion;
        }
        if (isSingleMultiLineInsertion(diff) && this._useCodeShifting.read(reader) === "always") {
          return InlineCompletionViewKind.InsertionMultiLine;
        }
        const allInnerChangesNotTooLong = inner.every((m) => TextLength.ofRange(m.originalRange).columnCount < InlineEditsWordReplacementView.MAX_LENGTH && TextLength.ofRange(m.modifiedRange).columnCount < InlineEditsWordReplacementView.MAX_LENGTH);
        if (allInnerChangesNotTooLong && isSingleInnerEdit && numOriginalLines === 1 && numModifiedLines === 1) {
          const modifiedText = inner.map((m) => newText.getValueOfRange(m.modifiedRange));
          const originalText = inner.map((m) => model.inlineEdit.originalText.getValueOfRange(m.originalRange));
          if (!modifiedText.some((v) => v.includes("	")) && !originalText.some((v) => v.includes("	"))) {
            if (!inner.some((m) => m.originalRange.isEmpty()) || !growEditsUntilWhitespace(inner.map((m) => new TextReplacement(m.originalRange, "")), inlineEdit.originalText).some((e) => e.range.isEmpty() && TextLength.ofRange(e.range).columnCount < InlineEditsWordReplacementView.MAX_LENGTH)) {
              return InlineCompletionViewKind.WordReplacements;
            }
          }
        }
      }
      if (numOriginalLines > 0 && numModifiedLines > 0) {
        if (numOriginalLines === 1 && numModifiedLines === 1 && !model.isInDiffEditor) {
          return InlineCompletionViewKind.LineReplacement;
        }
        if (this._renderSideBySide.read(reader) !== "never" && InlineEditsSideBySideView.fitsInsideViewport(this._editor, this._previewTextModel, inlineEdit, reader)) {
          return InlineCompletionViewKind.SideBySide;
        }
        return InlineCompletionViewKind.LineReplacement;
      }
      if (model.isInDiffEditor) {
        if (isDeletion(inner, inlineEdit, newText)) {
          return InlineCompletionViewKind.Deletion;
        }
        if (isSingleMultiLineInsertion(diff) && this._useCodeShifting.read(reader) === "always") {
          return InlineCompletionViewKind.InsertionMultiLine;
        }
      }
      return InlineCompletionViewKind.SideBySide;
    }
    determineRenderState(model, reader, diff, newText) {
      const inlineEdit = model.inlineEdit;
      let view = this.determineView(model, reader, diff, newText);
      if (this._willRenderAboveCursor(reader, inlineEdit, view)) {
        switch (view) {
          case InlineCompletionViewKind.LineReplacement:
          case InlineCompletionViewKind.WordReplacements:
            view = InlineCompletionViewKind.SideBySide;
            break;
        }
      }
      this._previousView = { id: this.getCacheId(model), view, editorWidth: this._editor.getLayoutInfo().width, timestamp: Date.now() };
      const inner = diff.flatMap((d) => d.innerChanges ?? []);
      const textModel = this._editor.getModel();
      const stringChanges = inner.map((m) => ({
        originalRange: m.originalRange,
        modifiedRange: m.modifiedRange,
        original: textModel.getValueInRange(m.originalRange),
        modified: newText.getValueOfRange(m.modifiedRange)
      }));
      const cursorPosition = inlineEdit.cursorPosition;
      const startsWithEOL = stringChanges.length === 0 ? false : stringChanges[0].modified.startsWith(textModel.getEOL());
      const viewData = {
        cursorColumnDistance: inlineEdit.edit.replacements.length === 0 ? 0 : inlineEdit.edit.replacements[0].range.getStartPosition().column - cursorPosition.column,
        cursorLineDistance: inlineEdit.lineEdit.lineRange.startLineNumber - cursorPosition.lineNumber + (startsWithEOL && inlineEdit.lineEdit.lineRange.startLineNumber >= cursorPosition.lineNumber ? 1 : 0),
        lineCountOriginal: inlineEdit.lineEdit.lineRange.length,
        lineCountModified: inlineEdit.lineEdit.newLines.length,
        characterCountOriginal: stringChanges.reduce((acc, r) => acc + r.original.length, 0),
        characterCountModified: stringChanges.reduce((acc, r) => acc + r.modified.length, 0),
        disjointReplacements: stringChanges.length,
        sameShapeReplacements: stringChanges.every((r) => r.original === stringChanges[0].original && r.modified === stringChanges[0].modified)
      };
      switch (view) {
        case InlineCompletionViewKind.InsertionInline:
          return { kind: InlineCompletionViewKind.InsertionInline, viewData };
        case InlineCompletionViewKind.SideBySide:
          return { kind: InlineCompletionViewKind.SideBySide, viewData };
        case InlineCompletionViewKind.Collapsed:
          return { kind: InlineCompletionViewKind.Collapsed, viewData };
        case InlineCompletionViewKind.Custom:
          return { kind: InlineCompletionViewKind.Custom, displayLocation: model.displayLocation, viewData };
      }
      if (view === InlineCompletionViewKind.Deletion) {
        return {
          kind: InlineCompletionViewKind.Deletion,
          originalRange: inlineEdit.originalLineRange,
          deletions: inner.map((m) => m.originalRange),
          viewData
        };
      }
      if (view === InlineCompletionViewKind.InsertionMultiLine) {
        const change = inner[0];
        return {
          kind: InlineCompletionViewKind.InsertionMultiLine,
          lineNumber: change.originalRange.startLineNumber,
          column: change.originalRange.startColumn,
          text: newText.getValueOfRange(change.modifiedRange),
          viewData
        };
      }
      const replacements = stringChanges.map((m) => new TextReplacement(m.originalRange, m.modified));
      if (replacements.length === 0) {
        return void 0;
      }
      if (view === InlineCompletionViewKind.WordReplacements) {
        let grownEdits = growEditsToEntireWord(replacements, inlineEdit.originalText);
        if (grownEdits.some((e) => e.range.isEmpty())) {
          grownEdits = growEditsUntilWhitespace(replacements, inlineEdit.originalText);
        }
        return {
          kind: InlineCompletionViewKind.WordReplacements,
          replacements: grownEdits,
          viewData
        };
      }
      if (view === InlineCompletionViewKind.LineReplacement) {
        return {
          kind: InlineCompletionViewKind.LineReplacement,
          originalRange: inlineEdit.originalLineRange,
          modifiedRange: inlineEdit.modifiedLineRange,
          modifiedLines: inlineEdit.modifiedLineRange.mapToLineArray((line) => newText.getLineAt(line)),
          replacements: inner.map((m) => ({ originalRange: m.originalRange, modifiedRange: m.modifiedRange })),
          viewData
        };
      }
      return void 0;
    }
    _willRenderAboveCursor(reader, inlineEdit, view) {
      const useCodeShifting = this._useCodeShifting.read(reader);
      if (useCodeShifting === "always") {
        return false;
      }
      for (const cursorPosition of inlineEdit.multiCursorPositions) {
        if (view === InlineCompletionViewKind.WordReplacements && cursorPosition.lineNumber === inlineEdit.originalLineRange.startLineNumber + 1) {
          return true;
        }
        if (view === InlineCompletionViewKind.LineReplacement && cursorPosition.lineNumber >= inlineEdit.originalLineRange.endLineNumberExclusive && cursorPosition.lineNumber < inlineEdit.modifiedLineRange.endLineNumberExclusive + inlineEdit.modifiedLineRange.length) {
          return true;
        }
      }
      return false;
    }
    _viewHasBeenShownLongerThan(durationMs) {
      const viewCreationTime = this._previousView?.timestamp;
      if (!viewCreationTime) {
        throw new BugIndicatingError("viewHasBeenShownLongThan called before a view has been shown");
      }
      const currentTime = Date.now();
      return currentTime - viewCreationTime >= durationMs;
    }
  };
  InlineEditsView = __decorate$17([
    __param$16(5, IInstantiationService)
  ], InlineEditsView);
  function isSingleLineInsertion(diff) {
    return diff.every((m) => m.innerChanges.every((r) => isWordInsertion(r)));
    function isWordInsertion(r) {
      if (!r.originalRange.isEmpty()) {
        return false;
      }
      const isInsertionWithinLine = r.modifiedRange.startLineNumber === r.modifiedRange.endLineNumber;
      if (!isInsertionWithinLine) {
        return false;
      }
      return true;
    }
  }
  function isSingleLineInsertionAfterPosition(diff, position) {
    if (!position) {
      return false;
    }
    if (!isSingleLineInsertion(diff)) {
      return false;
    }
    const pos = position;
    return diff.every((m) => m.innerChanges.every((r) => isStableWordInsertion(r)));
    function isStableWordInsertion(r) {
      const insertPosition = r.originalRange.getStartPosition();
      if (pos.isBeforeOrEqual(insertPosition)) {
        return true;
      }
      if (insertPosition.lineNumber < pos.lineNumber) {
        return true;
      }
      return false;
    }
  }
  function isSingleMultiLineInsertion(diff) {
    const inner = diff.flatMap((d) => d.innerChanges ?? []);
    if (inner.length !== 1) {
      return false;
    }
    const change = inner[0];
    if (!change.originalRange.isEmpty()) {
      return false;
    }
    if (change.modifiedRange.startLineNumber === change.modifiedRange.endLineNumber) {
      return false;
    }
    return true;
  }
  function isDeletion(inner, inlineEdit, newText) {
    const innerValues = inner.map((m) => ({ original: inlineEdit.originalText.getValueOfRange(m.originalRange), modified: newText.getValueOfRange(m.modifiedRange) }));
    return innerValues.every(({ original, modified }) => modified.trim() === "" && original.length > 0 && (original.length > modified.length || original.trim() !== ""));
  }
  function growEditsToEntireWord(replacements, originalText) {
    return _growEdits(replacements, originalText, (char) => /^[a-zA-Z]$/.test(char));
  }
  function growEditsUntilWhitespace(replacements, originalText) {
    return _growEdits(replacements, originalText, (char) => !/^\s$/.test(char));
  }
  function _growEdits(replacements, originalText, fn) {
    const result = [];
    replacements.sort((a, b) => Range$2.compareRangesUsingStarts(a.range, b.range));
    for (const edit2 of replacements) {
      let startIndex = edit2.range.startColumn - 1;
      let endIndex = edit2.range.endColumn - 2;
      let prefix = "";
      let suffix = "";
      const startLineContent = originalText.getLineAt(edit2.range.startLineNumber);
      const endLineContent = originalText.getLineAt(edit2.range.endLineNumber);
      if (isIncluded(startLineContent[startIndex])) {
        while (isIncluded(startLineContent[startIndex - 1])) {
          prefix = startLineContent[startIndex - 1] + prefix;
          startIndex--;
        }
      }
      if (isIncluded(endLineContent[endIndex]) || endIndex < startIndex) {
        while (isIncluded(endLineContent[endIndex + 1])) {
          suffix += endLineContent[endIndex + 1];
          endIndex++;
        }
      }
      let newEdit = new TextReplacement(new Range$2(edit2.range.startLineNumber, startIndex + 1, edit2.range.endLineNumber, endIndex + 2), prefix + edit2.text + suffix);
      if (result.length > 0 && Range$2.areIntersectingOrTouching(result[result.length - 1].range, newEdit.range)) {
        newEdit = TextReplacement.joinReplacements([result.pop(), newEdit], originalText);
      }
      result.push(newEdit);
    }
    function isIncluded(c) {
      if (c === void 0) {
        return false;
      }
      return fn(c);
    }
    return result;
  }
  function getGhostTextTopOffset(ghostTextIndicator, editor2) {
    const replacements = ghostTextIndicator.model.inlineEdit.edit.replacements;
    if (replacements.length !== 1) {
      return 0;
    }
    const textModel = editor2.getModel();
    if (!textModel) {
      return 0;
    }
    const EOL = textModel.getEOL();
    const replacement = replacements[0];
    if (replacement.range.isEmpty() && replacement.text.startsWith(EOL)) {
      const lineHeight = editor2.getLineHeightForPosition(replacement.range.getStartPosition());
      return countPrefixRepeats(replacement.text, EOL) * lineHeight;
    }
    return 0;
  }
  function countPrefixRepeats(str, prefix) {
    if (!prefix.length) {
      return 0;
    }
    let count = 0;
    let i2 = 0;
    while (str.startsWith(prefix, i2)) {
      count++;
      i2 += prefix.length;
    }
    return count;
  }
  var __decorate$16 = 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$15 = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  let InlineEditsViewAndDiffProducer = (_ka = class extends Disposable {
    constructor(_editor, _edit, _model, _focusIsInMenu, instantiationService) {
      super();
      this._editor = _editor;
      this._edit = _edit;
      this._model = _model;
      this._focusIsInMenu = _focusIsInMenu;
      this._inlineEdit = derived(this, (reader) => {
        const model = this._model.read(reader);
        if (!model) {
          return void 0;
        }
        const inlineEdit = this._edit.read(reader);
        if (!inlineEdit) {
          return void 0;
        }
        const textModel = this._editor.getModel();
        if (!textModel) {
          return void 0;
        }
        const editOffset = model.inlineEditState.read(void 0)?.inlineCompletion.updatedEdit;
        if (!editOffset) {
          return void 0;
        }
        const edits = editOffset.replacements.map((e) => {
          const innerEditRange = Range$2.fromPositions(textModel.getPositionAt(e.replaceRange.start), textModel.getPositionAt(e.replaceRange.endExclusive));
          return new TextReplacement(innerEditRange, e.newText);
        });
        const diffEdits = new TextEdit(edits);
        const text2 = new TextModelText(textModel);
        return new InlineEditWithChanges(text2, diffEdits, model.primaryPosition.read(void 0), model.allPositions.read(void 0), inlineEdit.commands, inlineEdit.inlineCompletion);
      });
      this._inlineEditModel = derived(this, (reader) => {
        const model = this._model.read(reader);
        if (!model) {
          return void 0;
        }
        const edit2 = this._inlineEdit.read(reader);
        if (!edit2) {
          return void 0;
        }
        const tabAction = derived(this, (reader2) => {
          if (this._editorObs.isFocused.read(reader2)) {
            if (model.tabShouldJumpToInlineEdit.read(reader2)) {
              return InlineEditTabAction.Jump;
            }
            if (model.tabShouldAcceptInlineEdit.read(reader2)) {
              return InlineEditTabAction.Accept;
            }
          }
          return InlineEditTabAction.Inactive;
        });
        return new InlineEditModel(model, edit2, tabAction);
      });
      this._inlineEditHost = derived(this, (reader) => {
        const model = this._model.read(reader);
        if (!model) {
          return void 0;
        }
        return new InlineEditHost(model);
      });
      this._ghostTextIndicator = derived(this, (reader) => {
        const model = this._model.read(reader);
        if (!model) {
          return void 0;
        }
        const state = model.inlineCompletionState.read(reader);
        if (!state) {
          return void 0;
        }
        const inlineCompletion = state.inlineCompletion;
        if (!inlineCompletion) {
          return void 0;
        }
        if (!inlineCompletion.showInlineEditMenu) {
          return void 0;
        }
        const lineRange = LineRange.ofLength(state.primaryGhostText.lineNumber, 1);
        return new GhostTextIndicator(this._editor, model, lineRange, inlineCompletion);
      });
      this._editorObs = observableCodeEditor(this._editor);
      this._register(instantiationService.createInstance(InlineEditsView, this._editor, this._inlineEditHost, this._inlineEditModel, this._ghostTextIndicator, this._focusIsInMenu));
    }
  }, _ka.hot = createHotClass(_ka), _ka);
  InlineEditsViewAndDiffProducer = __decorate$16([
    __param$15(4, IInstantiationService)
  ], InlineEditsViewAndDiffProducer);
  var __decorate$15 = 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$14 = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  let InlineCompletionsView = class InlineCompletionsView extends Disposable {
    constructor(_editor, _model, _focusIsInMenu, _instantiationService) {
      super();
      this._editor = _editor;
      this._model = _model;
      this._focusIsInMenu = _focusIsInMenu;
      this._instantiationService = _instantiationService;
      this._ghostTexts = derived(this, (reader) => {
        const model = this._model.read(reader);
        return model?.ghostTexts.read(reader) ?? [];
      });
      this._stablizedGhostTexts = convertItemsToStableObservables(this._ghostTexts, this._store);
      this._editorObs = observableCodeEditor(this._editor);
      this._ghostTextWidgets = mapObservableArrayCached(this, this._stablizedGhostTexts, (ghostText, store) => derivedDisposable((reader) => this._instantiationService.createInstance(GhostTextView.hot.read(reader), this._editor, {
        ghostText,
        warning: this._model.map((m, reader2) => {
          const warning = m?.warning?.read(reader2);
          return warning ? { icon: warning.icon } : void 0;
        }),
        minReservedLineCount: constObservable(0),
        targetTextModel: this._model.map((v) => v?.textModel),
        handleInlineCompletionShown: this._model.map((model, reader2) => {
          const inlineCompletion = model?.inlineCompletionState.read(reader2)?.inlineCompletion;
          if (inlineCompletion) {
            return (viewData) => model.handleInlineSuggestionShown(inlineCompletion, InlineCompletionViewKind.GhostText, viewData);
          }
          return () => {
          };
        })
      }, this._editorObs.getOption(
        71
        /* EditorOption.inlineSuggest */
      ).map((v) => ({ syntaxHighlightingEnabled: v.syntaxHighlightingEnabled })), false, false)).recomputeInitiallyAndOnChange(store)).recomputeInitiallyAndOnChange(this._store);
      this._inlineEdit = derived(this, (reader) => this._model.read(reader)?.inlineEditState.read(reader)?.inlineEdit);
      this._everHadInlineEdit = derivedObservableWithCache(this, (reader, last) => last || !!this._inlineEdit.read(reader) || !!this._model.read(reader)?.inlineCompletionState.read(reader)?.inlineCompletion?.showInlineEditMenu);
      this._inlineEditWidget = derivedDisposable((reader) => {
        if (!this._everHadInlineEdit.read(reader)) {
          return void 0;
        }
        return this._instantiationService.createInstance(InlineEditsViewAndDiffProducer.hot.read(reader), this._editor, this._inlineEdit, this._model, this._focusIsInMenu);
      }).recomputeInitiallyAndOnChange(this._store);
      this._fontFamily = this._editorObs.getOption(
        71
        /* EditorOption.inlineSuggest */
      ).map((val) => val.fontFamily);
      this._register(createStyleSheetFromObservable(derived((reader) => {
        const fontFamily = this._fontFamily.read(reader);
        return `
.monaco-editor .ghost-text-decoration,
.monaco-editor .ghost-text-decoration-preview,
.monaco-editor .ghost-text {
	font-family: ${fontFamily};
}`;
      })));
      this._register(new InlineCompletionsHintsWidget(this._editor, this._model, this._instantiationService));
    }
    shouldShowHoverAtViewZone(viewZoneId) {
      return this._ghostTextWidgets.get()[0]?.get().ownsViewZone(viewZoneId) ?? false;
    }
  };
  InlineCompletionsView = __decorate$15([
    __param$14(3, IInstantiationService)
  ], InlineCompletionsView);
  var __decorate$14 = 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$13 = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  var InlineCompletionsController_1;
  let InlineCompletionsController = (_la = class extends Disposable {
    /**
     * Find the controller in the focused editor or in the outer editor (if applicable)
     */
    static getInFocusedEditorOrParent(accessor) {
      const outerEditor = getOuterEditor(accessor);
      if (!outerEditor) {
        return null;
      }
      return InlineCompletionsController_1.get(outerEditor);
    }
    static get(editor2) {
      return hotClassGetOriginalInstance(editor2.getContribution(InlineCompletionsController_1.ID));
    }
    constructor(editor2, _instantiationService, _contextKeyService, _configurationService, _commandService, _debounceService, _languageFeaturesService, _accessibilitySignalService, _keybindingService, _accessibilityService) {
      super();
      this.editor = editor2;
      this._instantiationService = _instantiationService;
      this._contextKeyService = _contextKeyService;
      this._configurationService = _configurationService;
      this._commandService = _commandService;
      this._debounceService = _debounceService;
      this._languageFeaturesService = _languageFeaturesService;
      this._accessibilitySignalService = _accessibilitySignalService;
      this._keybindingService = _keybindingService;
      this._accessibilityService = _accessibilityService;
      this._editorObs = observableCodeEditor(this.editor);
      this._positions = derived(this, (reader) => this._editorObs.selections.read(reader)?.map((s) => s.getEndPosition()) ?? [new Position$1(1, 1)]);
      this._suggestWidgetAdapter = this._register(new ObservableSuggestWidgetAdapter(this._editorObs, (item) => this.model.get()?.handleSuggestAccepted(item), () => this.model.get()?.selectedInlineCompletion.get()?.getSingleTextEdit()));
      this._enabledInConfig = observableFromEvent(this, this.editor.onDidChangeConfiguration, () => this.editor.getOption(
        71
        /* EditorOption.inlineSuggest */
      ).enabled);
      this._isScreenReaderEnabled = observableFromEvent(this, this._accessibilityService.onDidChangeScreenReaderOptimized, () => this._accessibilityService.isScreenReaderOptimized());
      this._editorDictationInProgress = observableFromEvent(this, this._contextKeyService.onDidChangeContext, () => this._contextKeyService.getContext(this.editor.getDomNode()).getValue("editorDictation.inProgress") === true);
      this._enabled = derived(this, (reader) => this._enabledInConfig.read(reader) && (!this._isScreenReaderEnabled.read(reader) || !this._editorDictationInProgress.read(reader)));
      this._debounceValue = this._debounceService.for(this._languageFeaturesService.inlineCompletionsProvider, "InlineCompletionsDebounce", { min: 50, max: 50 });
      this._focusIsInMenu = observableValue(this, false);
      this._focusIsInEditorOrMenu = derived(this, (reader) => {
        const editorHasFocus = this._editorObs.isFocused.read(reader);
        const menuHasFocus = this._focusIsInMenu.read(reader);
        return editorHasFocus || menuHasFocus;
      });
      this._cursorIsInIndentation = derived(this, (reader) => {
        const cursorPos = this._editorObs.cursorPosition.read(reader);
        if (cursorPos === null) {
          return false;
        }
        const model = this._editorObs.model.read(reader);
        if (!model) {
          return false;
        }
        this._editorObs.versionId.read(reader);
        const indentMaxColumn = model.getLineIndentColumn(cursorPos.lineNumber);
        return cursorPos.column <= indentMaxColumn;
      });
      this.model = derivedDisposable(this, (reader) => {
        if (this._editorObs.isReadonly.read(reader)) {
          return void 0;
        }
        const textModel = this._editorObs.model.read(reader);
        if (!textModel) {
          return void 0;
        }
        const model = this._instantiationService.createInstance(InlineCompletionsModel, textModel, this._suggestWidgetAdapter.selectedItem, this._editorObs.versionId, this._positions, this._debounceValue, this._enabled, this.editor);
        return model;
      }).recomputeInitiallyAndOnChange(this._store);
      this._playAccessibilitySignal = observableSignal(this);
      this._hideInlineEditOnSelectionChange = this._editorObs.getOption(
        71
        /* EditorOption.inlineSuggest */
      ).map((val) => true);
      this._view = this._register(this._instantiationService.createInstance(InlineCompletionsView, this.editor, this.model, this._focusIsInMenu));
      InlineCompletionsController_1._instances.add(this);
      this._register(toDisposable(() => InlineCompletionsController_1._instances.delete(this)));
      this._register(autorun((reader) => {
        const model = this.model.read(reader);
        if (!model) {
          return;
        }
        const state = model.state.read(reader);
        if (!state) {
          return;
        }
        if (!this._focusIsInEditorOrMenu.read(void 0)) {
          return;
        }
        const nextEditUri = state.kind === "inlineEdit" ? state.nextEditUri : void 0;
        for (const ctrl of InlineCompletionsController_1._instances) {
          if (ctrl === this) {
            continue;
          } else if (nextEditUri && isEqual(nextEditUri, ctrl.editor.getModel()?.uri)) {
            ctrl.model.read(void 0)?.trigger();
          } else {
            ctrl.reject();
          }
        }
      }));
      this._register(autorun((reader) => {
        const model = this.model.read(reader);
        const uri = this.editor.getModel()?.uri;
        if (!model || !uri) {
          return;
        }
        reader.store.add(model.onDidAccept(() => {
          for (const ctrl of InlineCompletionsController_1._instances) {
            if (ctrl === this) {
              continue;
            }
            const state = ctrl.model.read(void 0)?.state.read(void 0);
            if (state?.kind === "inlineEdit" && isEqual(state.nextEditUri, uri)) {
              ctrl.model.read(void 0)?.stop("automatic");
            }
          }
        }));
      }));
      this._register(runOnChange(this._editorObs.onDidType, (_value, _changes) => {
        if (this._enabled.get()) {
          this.model.get()?.trigger();
        }
      }));
      this._register(runOnChange(this._editorObs.onDidPaste, (_value, _changes) => {
        if (this._enabled.get()) {
          this.model.get()?.trigger();
        }
      }));
      const triggerCommands = /* @__PURE__ */ new Set([
        CoreEditingCommands.Tab.id,
        CoreEditingCommands.DeleteLeft.id,
        CoreEditingCommands.DeleteRight.id,
        inlineSuggestCommitId,
        "acceptSelectedSuggestion",
        InsertLineAfterAction.ID,
        InsertLineBeforeAction.ID,
        FIND_IDS.NextMatchFindAction,
        ...TriggerInlineEditCommandsRegistry.getRegisteredCommands()
      ]);
      this._register(this._commandService.onDidExecuteCommand((e) => {
        if (triggerCommands.has(e.commandId) && editor2.hasTextFocus() && this._enabled.get()) {
          let noDelay = false;
          if (e.commandId === inlineSuggestCommitId) {
            noDelay = true;
          }
          this._editorObs.forceUpdate((tx) => {
            this.model.get()?.trigger(tx, { noDelay });
          });
        }
      }));
      this._register(runOnChange(this._editorObs.selections, (_value, _, changes) => {
        if (changes.some((e) => e.reason === 3 || e.source === "api")) {
          if (!this._hideInlineEditOnSelectionChange.get() && this.model.get()?.state.get()?.kind === "inlineEdit") {
            return;
          }
          const m = this.model.get();
          if (!m) {
            return;
          }
          if (m.state.get()?.kind === "ghostText") {
            this.model.get()?.stop();
          }
        }
      }));
      this._register(autorun((reader) => {
        const isFocused = this._focusIsInEditorOrMenu.read(reader);
        const model = this.model.read(void 0);
        if (isFocused) {
          const state = model?.state.read(void 0);
          if (!state || state.kind !== "inlineEdit" || !state.nextEditUri) {
            transaction((tx) => {
              for (const ctrl of InlineCompletionsController_1._instances) {
                if (ctrl !== this) {
                  ctrl.model.read(void 0)?.stop("automatic", tx);
                }
              }
            });
          }
          return;
        }
        if (this._contextKeyService.getContextKeyValue("accessibleViewIsShown") || this._configurationService.getValue("editor.inlineSuggest.keepOnBlur") || editor2.getOption(
          71
          /* EditorOption.inlineSuggest */
        ).keepOnBlur || InlineSuggestionHintsContentWidget.dropDownVisible) {
          return;
        }
        if (!model) {
          return;
        }
        if (model.state.read(void 0)?.inlineCompletion?.isFromExplicitRequest && model.inlineEditAvailable.read(void 0)) {
          return;
        }
        transaction((tx) => {
          model.stop("automatic", tx);
        });
      }));
      this._register(autorun((reader) => {
        const state = this.model.read(reader)?.inlineCompletionState.read(reader);
        if (state?.suggestItem) {
          if (state.primaryGhostText.lineCount >= 2) {
            this._suggestWidgetAdapter.forceRenderingAbove();
          }
        } else {
          this._suggestWidgetAdapter.stopForceRenderingAbove();
        }
      }));
      this._register(toDisposable(() => {
        this._suggestWidgetAdapter.stopForceRenderingAbove();
      }));
      const currentInlineCompletionBySemanticId = derivedObservableWithCache(this, (reader, last) => {
        const model = this.model.read(reader);
        const state = model?.state.read(reader);
        if (this._suggestWidgetAdapter.selectedItem.get()) {
          return last;
        }
        return state?.inlineCompletion?.semanticId;
      });
      this._register(runOnChangeWithStore(derived((reader) => {
        this._playAccessibilitySignal.read(reader);
        currentInlineCompletionBySemanticId.read(reader);
        return {};
      }), async (_value, _, _deltas, store) => {
        let model = this.model.get();
        let state = model?.state.get();
        if (!state || !model) {
          return;
        }
        await timeout(50, cancelOnDispose(store));
        await waitForState(this._suggestWidgetAdapter.selectedItem, isUndefined, () => false, cancelOnDispose(store));
        model = this.model.get();
        state = model?.state.get();
        if (!state || !model) {
          return;
        }
        const lineText = state.kind === "ghostText" ? model.textModel.getLineContent(state.primaryGhostText.lineNumber) : "";
        this._accessibilitySignalService.playSignal(state.kind === "ghostText" ? AccessibilitySignal.inlineSuggestion : AccessibilitySignal.nextEditSuggestion);
        if (this.editor.getOption(
          12
          /* EditorOption.screenReaderAnnounceInlineSuggestion */
        )) {
          if (state.kind === "ghostText") {
            this._provideScreenReaderUpdate(state.primaryGhostText.renderForScreenReader(lineText));
          } else {
            this._provideScreenReaderUpdate("");
          }
        }
      }));
      this._register(this._configurationService.onDidChangeConfiguration((e) => {
        if (e.affectsConfiguration("accessibility.verbosity.inlineCompletions")) {
          this.editor.updateOptions({ inlineCompletionsAccessibilityVerbose: this._configurationService.getValue("accessibility.verbosity.inlineCompletions") });
        }
      }));
      this.editor.updateOptions({ inlineCompletionsAccessibilityVerbose: this._configurationService.getValue("accessibility.verbosity.inlineCompletions") });
      const contextKeySvcObs = new ObservableContextKeyService(this._contextKeyService);
      this._register(contextKeySvcObs.bind(InlineCompletionContextKeys.cursorInIndentation, this._cursorIsInIndentation));
      this._register(contextKeySvcObs.bind(InlineCompletionContextKeys.hasSelection, (reader) => !this._editorObs.cursorSelection.read(reader)?.isEmpty()));
      this._register(contextKeySvcObs.bind(InlineCompletionContextKeys.cursorAtInlineEdit, this.model.map((m, reader) => m?.inlineEditState?.read(reader)?.cursorAtInlineEdit.read(reader))));
      this._register(contextKeySvcObs.bind(InlineCompletionContextKeys.tabShouldAcceptInlineEdit, this.model.map((m, r) => !!m?.tabShouldAcceptInlineEdit.read(r))));
      this._register(contextKeySvcObs.bind(InlineCompletionContextKeys.tabShouldJumpToInlineEdit, this.model.map((m, r) => !!m?.tabShouldJumpToInlineEdit.read(r))));
      this._register(contextKeySvcObs.bind(InlineCompletionContextKeys.inlineEditVisible, (reader) => this.model.read(reader)?.inlineEditState.read(reader) !== void 0));
      this._register(contextKeySvcObs.bind(InlineCompletionContextKeys.inlineSuggestionHasIndentation, (reader) => this.model.read(reader)?.getIndentationInfo(reader)?.startsWithIndentation));
      this._register(contextKeySvcObs.bind(InlineCompletionContextKeys.inlineSuggestionHasIndentationLessThanTabSize, (reader) => this.model.read(reader)?.getIndentationInfo(reader)?.startsWithIndentationLessThanTabSize));
      this._register(contextKeySvcObs.bind(InlineCompletionContextKeys.suppressSuggestions, (reader) => {
        const model = this.model.read(reader);
        const state = model?.inlineCompletionState.read(reader);
        return state?.primaryGhostText && state?.inlineCompletion ? state.inlineCompletion.source.inlineSuggestions.suppressSuggestions : void 0;
      }));
      this._register(contextKeySvcObs.bind(InlineCompletionContextKeys.inlineSuggestionVisible, (reader) => {
        const model = this.model.read(reader);
        const state = model?.inlineCompletionState.read(reader);
        return !!state?.inlineCompletion && state?.primaryGhostText !== void 0 && !state?.primaryGhostText.isEmpty();
      }));
      const firstGhostTextPos = derived(this, (reader) => {
        const model = this.model.read(reader);
        const state = model?.inlineCompletionState.read(reader);
        const primaryGhostText = state?.primaryGhostText;
        if (!primaryGhostText || primaryGhostText.isEmpty()) {
          return void 0;
        }
        const firstPartPos = new Position$1(primaryGhostText.lineNumber, primaryGhostText.parts[0].column);
        return firstPartPos;
      });
      this._register(contextKeySvcObs.bind(InlineCompletionContextKeys.cursorBeforeGhostText, (reader) => {
        const firstPartPos = firstGhostTextPos.read(reader);
        if (!firstPartPos) {
          return false;
        }
        const cursorPos = this._editorObs.cursorPosition.read(reader);
        if (!cursorPos) {
          return false;
        }
        return firstPartPos.equals(cursorPos);
      }));
      this._register(this._instantiationService.createInstance(TextModelChangeRecorder, this.editor));
    }
    playAccessibilitySignal(tx) {
      this._playAccessibilitySignal.trigger(tx);
    }
    _provideScreenReaderUpdate(content) {
      const accessibleViewShowing = this._contextKeyService.getContextKeyValue("accessibleViewIsShown");
      const accessibleViewKeybinding = this._keybindingService.lookupKeybinding("editor.action.accessibleView");
      let hint;
      if (!accessibleViewShowing && accessibleViewKeybinding && this.editor.getOption(
        169
        /* EditorOption.inlineCompletionsAccessibilityVerbose */
      )) {
        hint = localize(1204, "Inspect this in the accessible view ({0})", accessibleViewKeybinding.getAriaLabel());
      }
      alert(hint ? content + ", " + hint : content);
    }
    shouldShowHoverAt(range2) {
      const ghostText = this.model.get()?.primaryGhostText.get();
      if (!ghostText) {
        return false;
      }
      return ghostText.parts.some((p) => range2.containsPosition(new Position$1(ghostText.lineNumber, p.column)));
    }
    shouldShowHoverAtViewZone(viewZoneId) {
      return this._view.shouldShowHoverAtViewZone(viewZoneId);
    }
    reject() {
      transaction((tx) => {
        const m = this.model.get();
        if (m) {
          m.stop("explicitCancel", tx);
          if (this._focusIsInEditorOrMenu.get()) {
            for (const ctrl of InlineCompletionsController_1._instances) {
              if (ctrl !== this) {
                ctrl.model.get()?.stop("automatic", tx);
              }
            }
          }
        }
      });
    }
    jump() {
      const m = this.model.get();
      if (m) {
        m.jump();
      }
    }
  }, InlineCompletionsController_1 = _la, _la._instances = /* @__PURE__ */ new Set(), _la.hot = createHotClass(_la), _la.ID = "editor.contrib.inlineCompletionsController", _la);
  InlineCompletionsController = InlineCompletionsController_1 = __decorate$14([
    __param$13(1, IInstantiationService),
    __param$13(2, IContextKeyService),
    __param$13(3, IConfigurationService),
    __param$13(4, ICommandService),
    __param$13(5, ILanguageFeatureDebounceService),
    __param$13(6, ILanguageFeaturesService),
    __param$13(7, IAccessibilitySignalService),
    __param$13(8, IKeybindingService),
    __param$13(9, IAccessibilityService)
  ], InlineCompletionsController);
  const _ShowNextInlineSuggestionAction = class _ShowNextInlineSuggestionAction extends EditorAction {
    constructor() {
      super({
        id: _ShowNextInlineSuggestionAction.ID,
        label: localize2(1183, "Show Next Inline Suggestion"),
        precondition: ContextKeyExpr.and(EditorContextKeys.writable, InlineCompletionContextKeys.inlineSuggestionVisible),
        kbOpts: {
          weight: 100,
          primary: 512 | 94
        }
      });
    }
    async run(accessor, editor2) {
      const controller = InlineCompletionsController.get(editor2);
      controller?.model.get()?.next();
    }
  };
  _ShowNextInlineSuggestionAction.ID = showNextInlineSuggestionActionId;
  let ShowNextInlineSuggestionAction = _ShowNextInlineSuggestionAction;
  const _ShowPreviousInlineSuggestionAction = class _ShowPreviousInlineSuggestionAction extends EditorAction {
    constructor() {
      super({
        id: _ShowPreviousInlineSuggestionAction.ID,
        label: localize2(1184, "Show Previous Inline Suggestion"),
        precondition: ContextKeyExpr.and(EditorContextKeys.writable, InlineCompletionContextKeys.inlineSuggestionVisible),
        kbOpts: {
          weight: 100,
          primary: 512 | 92
        }
      });
    }
    async run(accessor, editor2) {
      const controller = InlineCompletionsController.get(editor2);
      controller?.model.get()?.previous();
    }
  };
  _ShowPreviousInlineSuggestionAction.ID = showPreviousInlineSuggestionActionId;
  let ShowPreviousInlineSuggestionAction = _ShowPreviousInlineSuggestionAction;
  const providerIdSchemaUri = "vscode://schemas/inlineCompletionProviderIdArgs";
  function inlineCompletionProviderGetMatcher(provider) {
    const result = [];
    if (provider.providerId) {
      result.push(provider.providerId.toStringWithoutVersion());
      result.push(provider.providerId.extensionId + ":*");
    }
    return result;
  }
  const argsValidator = vUnion(vObj({
    showNoResultNotification: vOptionalProp(vBoolean()),
    providerId: vOptionalProp(vWithJsonSchemaRef(providerIdSchemaUri, vString())),
    explicit: vOptionalProp(vBoolean())
  }), vUndefined());
  class TriggerInlineSuggestionAction extends EditorAction {
    constructor() {
      super({
        id: "editor.action.inlineSuggest.trigger",
        label: localize2(1185, "Trigger Inline Suggestion"),
        precondition: EditorContextKeys.writable,
        metadata: {
          description: localize(1172, "Triggers an inline suggestion in the editor."),
          args: [{
            name: "args",
            description: localize(1173, "Options for triggering inline suggestions."),
            isOptional: true,
            schema: argsValidator.getJSONSchema()
          }]
        }
      });
    }
    async run(accessor, editor2, args) {
      const notificationService = accessor.get(INotificationService);
      const languageFeaturesService = accessor.get(ILanguageFeaturesService);
      const controller = InlineCompletionsController.get(editor2);
      const validatedArgs = argsValidator.validateOrThrow(args);
      const provider = validatedArgs?.providerId ? languageFeaturesService.inlineCompletionsProvider.all(editor2.getModel()).find((p) => inlineCompletionProviderGetMatcher(p).some((m) => m === validatedArgs.providerId)) : void 0;
      await asyncTransaction(async (tx) => {
        await controller?.model.get()?.trigger(tx, {
          provider,
          explicit: validatedArgs?.explicit ?? true
        });
        controller?.playAccessibilitySignal(tx);
      });
      if (validatedArgs?.showNoResultNotification) {
        if (!controller?.model.get()?.state.get()) {
          notificationService.notify({
            severity: Severity.Info,
            message: localize(1174, "No inline suggestion is available.")
          });
        }
      }
    }
  }
  class AcceptNextWordOfInlineCompletion extends EditorAction {
    constructor() {
      super({
        id: "editor.action.inlineSuggest.acceptNextWord",
        label: localize2(1186, "Accept Next Word Of Inline Suggestion"),
        precondition: ContextKeyExpr.and(EditorContextKeys.writable, InlineCompletionContextKeys.inlineSuggestionVisible),
        kbOpts: {
          weight: 100 + 1,
          primary: 2048 | 17,
          kbExpr: ContextKeyExpr.and(EditorContextKeys.writable, InlineCompletionContextKeys.inlineSuggestionVisible, InlineCompletionContextKeys.cursorBeforeGhostText, CONTEXT_ACCESSIBILITY_MODE_ENABLED.negate())
        },
        menuOpts: [{
          menuId: MenuId.InlineSuggestionToolbar,
          title: localize(1175, "Accept Word"),
          group: "primary",
          order: 2
        }]
      });
    }
    async run(accessor, editor2) {
      const controller = InlineCompletionsController.get(editor2);
      await controller?.model.get()?.acceptNextWord();
    }
  }
  class AcceptNextLineOfInlineCompletion extends EditorAction {
    constructor() {
      super({
        id: "editor.action.inlineSuggest.acceptNextLine",
        label: localize2(1187, "Accept Next Line Of Inline Suggestion"),
        precondition: ContextKeyExpr.and(EditorContextKeys.writable, InlineCompletionContextKeys.inlineSuggestionVisible),
        kbOpts: {
          weight: 100 + 1
        },
        menuOpts: [{
          menuId: MenuId.InlineSuggestionToolbar,
          title: localize(1176, "Accept Line"),
          group: "secondary",
          order: 2
        }]
      });
    }
    async run(accessor, editor2) {
      const controller = InlineCompletionsController.get(editor2);
      await controller?.model.get()?.acceptNextLine();
    }
  }
  class AcceptInlineCompletion extends EditorAction {
    constructor() {
      super({
        id: inlineSuggestCommitId,
        label: localize2(1188, "Accept Inline Suggestion"),
        precondition: ContextKeyExpr.or(InlineCompletionContextKeys.inlineSuggestionVisible, InlineCompletionContextKeys.inlineEditVisible),
        menuOpts: [{
          menuId: MenuId.InlineSuggestionToolbar,
          title: localize(1177, "Accept"),
          group: "primary",
          order: 2
        }, {
          menuId: MenuId.InlineEditsActions,
          title: localize(1178, "Accept"),
          group: "primary",
          order: 2
        }],
        kbOpts: [
          {
            primary: 2,
            weight: 200,
            kbExpr: ContextKeyExpr.or(ContextKeyExpr.and(InlineCompletionContextKeys.inlineSuggestionVisible, EditorContextKeys.tabMovesFocus.toNegated(), Context$2.Visible.toNegated(), EditorContextKeys.hoverFocused.toNegated(), InlineCompletionContextKeys.hasSelection.toNegated(), InlineCompletionContextKeys.inlineSuggestionHasIndentationLessThanTabSize), ContextKeyExpr.and(InlineCompletionContextKeys.inlineEditVisible, EditorContextKeys.tabMovesFocus.toNegated(), Context$2.Visible.toNegated(), EditorContextKeys.hoverFocused.toNegated(), InlineCompletionContextKeys.tabShouldAcceptInlineEdit))
          }
        ]
      });
    }
    async run(accessor, editor2) {
      const controller = InlineCompletionsController.getInFocusedEditorOrParent(accessor);
      if (controller) {
        controller.model.get()?.accept(controller.editor);
        controller.editor.focus();
      }
    }
  }
  KeybindingsRegistry.registerKeybindingRule({
    id: inlineSuggestCommitId,
    weight: 202,
    // greater than jump
    primary: 2,
    when: ContextKeyExpr.and(InlineCompletionContextKeys.inInlineEditsPreviewEditor)
  });
  class JumpToNextInlineEdit extends EditorAction {
    constructor() {
      super({
        id: jumpToNextInlineEditId,
        label: localize2(1189, "Jump to next inline edit"),
        precondition: InlineCompletionContextKeys.inlineEditVisible,
        menuOpts: [{
          menuId: MenuId.InlineEditsActions,
          title: localize(1179, "Jump"),
          group: "primary",
          order: 1,
          when: InlineCompletionContextKeys.cursorAtInlineEdit.toNegated()
        }],
        kbOpts: {
          primary: 2,
          weight: 201,
          kbExpr: ContextKeyExpr.and(InlineCompletionContextKeys.inlineEditVisible, EditorContextKeys.tabMovesFocus.toNegated(), Context$2.Visible.toNegated(), EditorContextKeys.hoverFocused.toNegated(), InlineCompletionContextKeys.tabShouldJumpToInlineEdit)
        }
      });
    }
    async run(accessor, editor2) {
      const controller = InlineCompletionsController.get(editor2);
      if (controller) {
        controller.jump();
      }
    }
  }
  const _HideInlineCompletion = class _HideInlineCompletion extends EditorAction {
    constructor() {
      super({
        id: _HideInlineCompletion.ID,
        label: localize2(1190, "Hide Inline Suggestion"),
        precondition: ContextKeyExpr.or(InlineCompletionContextKeys.inlineSuggestionVisible, InlineCompletionContextKeys.inlineEditVisible),
        kbOpts: {
          weight: 100 + 90,
          // same as hiding the suggest widget
          primary: 9
        },
        menuOpts: [{
          menuId: MenuId.InlineEditsActions,
          title: localize(1180, "Reject"),
          group: "primary",
          order: 3
        }]
      });
    }
    async run(accessor, editor2) {
      const controller = InlineCompletionsController.getInFocusedEditorOrParent(accessor);
      transaction((tx) => {
        controller?.model.get()?.stop("explicitCancel", tx);
      });
      controller?.editor.focus();
    }
  };
  _HideInlineCompletion.ID = hideInlineCompletionId;
  let HideInlineCompletion = _HideInlineCompletion;
  const _ToggleInlineCompletionShowCollapsed = class _ToggleInlineCompletionShowCollapsed extends EditorAction {
    constructor() {
      super({
        id: _ToggleInlineCompletionShowCollapsed.ID,
        label: localize2(1191, "Toggle Inline Suggestions Show Collapsed"),
        precondition: ContextKeyExpr.true()
      });
    }
    async run(accessor, editor2) {
      const configurationService = accessor.get(IConfigurationService);
      const showCollapsed = configurationService.getValue("editor.inlineSuggest.edits.showCollapsed");
      configurationService.updateValue("editor.inlineSuggest.edits.showCollapsed", !showCollapsed);
    }
  };
  _ToggleInlineCompletionShowCollapsed.ID = toggleShowCollapsedId;
  let ToggleInlineCompletionShowCollapsed = _ToggleInlineCompletionShowCollapsed;
  KeybindingsRegistry.registerKeybindingRule({
    id: HideInlineCompletion.ID,
    weight: -1,
    // very weak
    primary: 9,
    secondary: [
      1024 | 9
      /* KeyCode.Escape */
    ],
    when: ContextKeyExpr.and(InlineCompletionContextKeys.inInlineEditsPreviewEditor)
  });
  const _ToggleAlwaysShowInlineSuggestionToolbar = class _ToggleAlwaysShowInlineSuggestionToolbar extends Action2 {
    constructor() {
      super({
        id: _ToggleAlwaysShowInlineSuggestionToolbar.ID,
        title: localize(1181, "Always Show Toolbar"),
        f1: false,
        precondition: void 0,
        menu: [{
          id: MenuId.InlineSuggestionToolbar,
          group: "secondary",
          order: 10
        }],
        toggled: ContextKeyExpr.equals("config.editor.inlineSuggest.showToolbar", "always")
      });
    }
    async run(accessor) {
      const configService = accessor.get(IConfigurationService);
      const currentValue = configService.getValue("editor.inlineSuggest.showToolbar");
      const newValue = currentValue === "always" ? "onHover" : "always";
      configService.updateValue("editor.inlineSuggest.showToolbar", newValue);
    }
  };
  _ToggleAlwaysShowInlineSuggestionToolbar.ID = "editor.action.inlineSuggest.toggleAlwaysShowToolbar";
  let ToggleAlwaysShowInlineSuggestionToolbar = _ToggleAlwaysShowInlineSuggestionToolbar;
  class DevExtractReproSample extends EditorAction {
    constructor() {
      super({
        id: "editor.action.inlineSuggest.dev.extractRepro",
        label: localize(1182, "Developer: Extract Inline Suggest State"),
        alias: "Developer: Inline Suggest Extract Repro",
        precondition: ContextKeyExpr.or(InlineCompletionContextKeys.inlineEditVisible, InlineCompletionContextKeys.inlineSuggestionVisible)
      });
    }
    async run(accessor, editor2) {
      const clipboardService = accessor.get(IClipboardService);
      const controller = InlineCompletionsController.get(editor2);
      const m = controller?.model.get();
      if (!m) {
        return;
      }
      const repro = m.extractReproSample();
      const inlineCompletionLines = splitLines(JSON.stringify({ inlineCompletion: repro.inlineCompletion }, null, 4));
      const json = inlineCompletionLines.map((l) => "// " + l).join("\n");
      const reproStr = `${repro.documentValue}

// <json>
${json}
// </json>
`;
      await clipboardService.writeText(reproStr);
      return { reproCase: reproStr };
    }
  }
  var __decorate$13 = 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$12 = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  class InlineCompletionsHover {
    constructor(owner, range2, controller) {
      this.owner = owner;
      this.range = range2;
      this.controller = controller;
    }
    isValidForHoverAnchor(anchor) {
      return anchor.type === 1 && this.range.startColumn <= anchor.range.startColumn && this.range.endColumn >= anchor.range.endColumn;
    }
  }
  let InlineCompletionsHoverParticipant = class InlineCompletionsHoverParticipant {
    constructor(_editor, accessibilityService, _instantiationService, _telemetryService, _markdownRendererService) {
      this._editor = _editor;
      this.accessibilityService = accessibilityService;
      this._instantiationService = _instantiationService;
      this._telemetryService = _telemetryService;
      this._markdownRendererService = _markdownRendererService;
      this.hoverOrdinal = 4;
    }
    suggestHoverAnchor(mouseEvent) {
      const controller = InlineCompletionsController.get(this._editor);
      if (!controller) {
        return null;
      }
      const target = mouseEvent.target;
      if (target.type === 8) {
        const viewZoneData = target.detail;
        if (controller.shouldShowHoverAtViewZone(viewZoneData.viewZoneId)) {
          return new HoverForeignElementAnchor(1e3, this, Range$2.fromPositions(this._editor.getModel().validatePosition(viewZoneData.positionBefore || viewZoneData.position)), mouseEvent.event.posx, mouseEvent.event.posy, false);
        }
      }
      if (target.type === 7) {
        if (controller.shouldShowHoverAt(target.range)) {
          return new HoverForeignElementAnchor(1e3, this, target.range, mouseEvent.event.posx, mouseEvent.event.posy, false);
        }
      }
      if (target.type === 6) {
        const mightBeForeignElement = target.detail.mightBeForeignElement;
        if (mightBeForeignElement && controller.shouldShowHoverAt(target.range)) {
          return new HoverForeignElementAnchor(1e3, this, target.range, mouseEvent.event.posx, mouseEvent.event.posy, false);
        }
      }
      if (target.type === 9 && target.element) {
        const ctx = GhostTextView.getWarningWidgetContext(target.element);
        if (ctx && controller.shouldShowHoverAt(ctx.range)) {
          return new HoverForeignElementAnchor(1e3, this, ctx.range, mouseEvent.event.posx, mouseEvent.event.posy, false);
        }
      }
      return null;
    }
    computeSync(anchor, lineDecorations) {
      if (this._editor.getOption(
        71
        /* EditorOption.inlineSuggest */
      ).showToolbar !== "onHover") {
        return [];
      }
      const controller = InlineCompletionsController.get(this._editor);
      if (controller && controller.shouldShowHoverAt(anchor.range)) {
        return [new InlineCompletionsHover(this, anchor.range, controller)];
      }
      return [];
    }
    renderHoverParts(context, hoverParts) {
      const disposables = new DisposableStore();
      const part = hoverParts[0];
      this._telemetryService.publicLog2("inlineCompletionHover.shown");
      if (this.accessibilityService.isScreenReaderOptimized() && !this._editor.getOption(
        12
        /* EditorOption.screenReaderAnnounceInlineSuggestion */
      )) {
        disposables.add(this.renderScreenReaderText(context, part));
      }
      const model = part.controller.model.get();
      const widgetNode = document.createElement("div");
      context.fragment.appendChild(widgetNode);
      disposables.add(autorunWithStore((reader, store) => {
        const w = store.add(this._instantiationService.createInstance(InlineSuggestionHintsContentWidget.hot.read(reader), this._editor, false, constObservable(null), model.selectedInlineCompletionIndex, model.inlineCompletionsCount, model.activeCommands, model.warning, () => {
          context.onContentsChanged();
        }));
        widgetNode.replaceChildren(w.getDomNode());
      }));
      model.triggerExplicitly();
      const renderedHoverPart = {
        hoverPart: part,
        hoverElement: widgetNode,
        dispose() {
          disposables.dispose();
        }
      };
      return new RenderedHoverParts([renderedHoverPart]);
    }
    getAccessibleContent(hoverPart) {
      return localize(1205, "There are inline completions here");
    }
    renderScreenReaderText(context, part) {
      const disposables = new DisposableStore();
      const $2 = $$l;
      const markdownHoverElement = $2("div.hover-row.markdown-hover");
      const hoverContentsElement = append$2(markdownHoverElement, $2("div.hover-contents", { ["aria-live"]: "assertive" }));
      const render = (code) => {
        const inlineSuggestionAvailable = localize(1206, "Suggestion:");
        const renderedContents = disposables.add(this._markdownRendererService.render(new MarkdownString().appendText(inlineSuggestionAvailable).appendCodeblock("text", code), {
          context: this._editor,
          asyncRenderCallback: () => {
            hoverContentsElement.className = "hover-contents code-hover-contents";
            context.onContentsChanged();
          }
        }));
        hoverContentsElement.replaceChildren(renderedContents.element);
      };
      disposables.add(autorun((reader) => {
        const ghostText = part.controller.model.read(reader)?.primaryGhostText.read(reader);
        if (ghostText) {
          const lineText = this._editor.getModel().getLineContent(ghostText.lineNumber);
          render(ghostText.renderForScreenReader(lineText));
        } else {
          reset(hoverContentsElement);
        }
      }));
      context.fragment.appendChild(markdownHoverElement);
      return disposables;
    }
  };
  InlineCompletionsHoverParticipant = __decorate$13([
    __param$12(1, IAccessibilityService),
    __param$12(2, IInstantiationService),
    __param$12(3, ITelemetryService),
    __param$12(4, IMarkdownRendererService)
  ], InlineCompletionsHoverParticipant);
  class InlineCompletionsAccessibleView {
  }
  registerEditorContribution(
    InlineCompletionsController.ID,
    wrapInHotClass1(InlineCompletionsController.hot),
    3
    /* EditorContributionInstantiation.Eventually */
  );
  registerEditorAction(TriggerInlineSuggestionAction);
  registerEditorAction(ShowNextInlineSuggestionAction);
  registerEditorAction(ShowPreviousInlineSuggestionAction);
  registerEditorAction(AcceptNextWordOfInlineCompletion);
  registerEditorAction(AcceptNextLineOfInlineCompletion);
  registerEditorAction(AcceptInlineCompletion);
  registerEditorAction(ToggleInlineCompletionShowCollapsed);
  registerEditorAction(HideInlineCompletion);
  registerEditorAction(JumpToNextInlineEdit);
  registerAction2(ToggleAlwaysShowInlineSuggestionToolbar);
  registerEditorAction(DevExtractReproSample);
  registerAction2(SnoozeInlineCompletion);
  registerAction2(CancelSnoozeInlineCompletion);
  HoverParticipantRegistry.register(InlineCompletionsHoverParticipant);
  AccessibleViewRegistry.register(new InlineCompletionsAccessibleView());
  var __decorate$12 = 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$11 = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  var GotoDefinitionAtPositionEditorContribution_1;
  let GotoDefinitionAtPositionEditorContribution = (_ma = class {
    constructor(editor2, textModelResolverService, languageService, languageFeaturesService) {
      this.textModelResolverService = textModelResolverService;
      this.languageService = languageService;
      this.languageFeaturesService = languageFeaturesService;
      this.toUnhook = new DisposableStore();
      this.toUnhookForKeyboard = new DisposableStore();
      this.currentWordAtPosition = null;
      this.previousPromise = null;
      this.editor = editor2;
      this.linkDecorations = this.editor.createDecorationsCollection();
      const linkGesture = new ClickLinkGesture(editor2);
      this.toUnhook.add(linkGesture);
      this.toUnhook.add(linkGesture.onMouseMoveOrRelevantKeyDown(([mouseEvent, keyboardEvent]) => {
        this.startFindDefinitionFromMouse(mouseEvent, keyboardEvent ?? void 0);
      }));
      this.toUnhook.add(linkGesture.onExecute((mouseEvent) => {
        if (this.isEnabled(mouseEvent)) {
          this.gotoDefinition(mouseEvent.target.position, mouseEvent.hasSideBySideModifier).catch((error) => {
            onUnexpectedError(error);
          }).finally(() => {
            this.removeLinkDecorations();
          });
        }
      }));
      this.toUnhook.add(linkGesture.onCancel(() => {
        this.removeLinkDecorations();
        this.currentWordAtPosition = null;
      }));
    }
    static get(editor2) {
      return editor2.getContribution(GotoDefinitionAtPositionEditorContribution_1.ID);
    }
    async startFindDefinitionFromCursor(position) {
      await this.startFindDefinition(position);
      this.toUnhookForKeyboard.add(this.editor.onDidChangeCursorPosition(() => {
        this.currentWordAtPosition = null;
        this.removeLinkDecorations();
        this.toUnhookForKeyboard.clear();
      }));
      this.toUnhookForKeyboard.add(this.editor.onKeyDown((e) => {
        if (e) {
          this.currentWordAtPosition = null;
          this.removeLinkDecorations();
          this.toUnhookForKeyboard.clear();
        }
      }));
    }
    startFindDefinitionFromMouse(mouseEvent, withKey) {
      if (mouseEvent.target.type === 9 && this.linkDecorations.length > 0) {
        return;
      }
      if (!this.editor.hasModel() || !this.isEnabled(mouseEvent, withKey)) {
        this.currentWordAtPosition = null;
        this.removeLinkDecorations();
        return;
      }
      const position = mouseEvent.target.position;
      this.startFindDefinition(position);
    }
    async startFindDefinition(position) {
      this.toUnhookForKeyboard.clear();
      const word = position ? this.editor.getModel()?.getWordAtPosition(position) : null;
      if (!word) {
        this.currentWordAtPosition = null;
        this.removeLinkDecorations();
        return;
      }
      if (this.currentWordAtPosition && this.currentWordAtPosition.startColumn === word.startColumn && this.currentWordAtPosition.endColumn === word.endColumn && this.currentWordAtPosition.word === word.word) {
        return;
      }
      this.currentWordAtPosition = word;
      const state = new EditorState$1(
        this.editor,
        4 | 1 | 2 | 8
        /* CodeEditorStateFlag.Scroll */
      );
      if (this.previousPromise) {
        this.previousPromise.cancel();
        this.previousPromise = null;
      }
      this.previousPromise = createCancelablePromise((token) => this.findDefinition(position, token));
      let results;
      try {
        results = await this.previousPromise;
      } catch (error) {
        onUnexpectedError(error);
        return;
      }
      if (!results || !results.length || !state.validate(this.editor)) {
        this.removeLinkDecorations();
        return;
      }
      const linkRange = results[0].originSelectionRange ? Range$2.lift(results[0].originSelectionRange) : new Range$2(position.lineNumber, word.startColumn, position.lineNumber, word.endColumn);
      if (results.length > 1) {
        let combinedRange = linkRange;
        for (const { originSelectionRange } of results) {
          if (originSelectionRange) {
            combinedRange = Range$2.plusRange(combinedRange, originSelectionRange);
          }
        }
        this.addDecoration(combinedRange, new MarkdownString().appendText(localize(1077, "Click to show {0} definitions.", results.length)));
      } else {
        const result = results[0];
        if (!result.uri) {
          return;
        }
        return this.textModelResolverService.createModelReference(result.uri).then((ref) => {
          if (!ref.object || !ref.object.textEditorModel) {
            ref.dispose();
            return;
          }
          const { object: { textEditorModel } } = ref;
          const { startLineNumber } = result.range;
          if (startLineNumber < 1 || startLineNumber > textEditorModel.getLineCount()) {
            ref.dispose();
            return;
          }
          const previewValue = this.getPreviewValue(textEditorModel, startLineNumber, result);
          const languageId = this.languageService.guessLanguageIdByFilepathOrFirstLine(textEditorModel.uri);
          this.addDecoration(linkRange, previewValue ? new MarkdownString().appendCodeblock(languageId ? languageId : "", previewValue) : void 0);
          ref.dispose();
        });
      }
    }
    getPreviewValue(textEditorModel, startLineNumber, result) {
      let rangeToUse = result.range;
      const numberOfLinesInRange = rangeToUse.endLineNumber - rangeToUse.startLineNumber;
      if (numberOfLinesInRange >= GotoDefinitionAtPositionEditorContribution_1.MAX_SOURCE_PREVIEW_LINES) {
        rangeToUse = this.getPreviewRangeBasedOnIndentation(textEditorModel, startLineNumber);
      }
      rangeToUse = textEditorModel.validateRange(rangeToUse);
      const previewValue = this.stripIndentationFromPreviewRange(textEditorModel, startLineNumber, rangeToUse);
      return previewValue;
    }
    stripIndentationFromPreviewRange(textEditorModel, startLineNumber, previewRange) {
      const startIndent = textEditorModel.getLineFirstNonWhitespaceColumn(startLineNumber);
      let minIndent = startIndent;
      for (let endLineNumber = startLineNumber + 1; endLineNumber < previewRange.endLineNumber; endLineNumber++) {
        const endIndent = textEditorModel.getLineFirstNonWhitespaceColumn(endLineNumber);
        minIndent = Math.min(minIndent, endIndent);
      }
      const previewValue = textEditorModel.getValueInRange(previewRange).replace(new RegExp(`^\\s{${minIndent - 1}}`, "gm"), "").trim();
      return previewValue;
    }
    getPreviewRangeBasedOnIndentation(textEditorModel, startLineNumber) {
      const startIndent = textEditorModel.getLineFirstNonWhitespaceColumn(startLineNumber);
      const maxLineNumber = Math.min(textEditorModel.getLineCount(), startLineNumber + GotoDefinitionAtPositionEditorContribution_1.MAX_SOURCE_PREVIEW_LINES);
      let endLineNumber = startLineNumber + 1;
      for (; endLineNumber < maxLineNumber; endLineNumber++) {
        const endIndent = textEditorModel.getLineFirstNonWhitespaceColumn(endLineNumber);
        if (startIndent === endIndent) {
          break;
        }
      }
      return new Range$2(startLineNumber, 1, endLineNumber + 1, 1);
    }
    addDecoration(range2, hoverMessage) {
      const newDecorations = {
        range: range2,
        options: {
          description: "goto-definition-link",
          inlineClassName: "goto-definition-link",
          hoverMessage
        }
      };
      this.linkDecorations.set([newDecorations]);
    }
    removeLinkDecorations() {
      this.linkDecorations.clear();
    }
    isEnabled(mouseEvent, withKey) {
      return this.editor.hasModel() && mouseEvent.isLeftClick && mouseEvent.isNoneOrSingleMouseDown && mouseEvent.target.type === 6 && !(mouseEvent.target.detail.injectedText?.options instanceof ModelDecorationInjectedTextOptions) && (mouseEvent.hasTriggerModifier || (withKey ? withKey.keyCodeIsTriggerKey : false)) && this.languageFeaturesService.definitionProvider.has(this.editor.getModel());
    }
    findDefinition(position, token) {
      const model = this.editor.getModel();
      if (!model) {
        return Promise.resolve(null);
      }
      return getDefinitionsAtPosition(this.languageFeaturesService.definitionProvider, model, position, false, token);
    }
    async gotoDefinition(position, openToSide) {
      this.editor.setPosition(position);
      return this.editor.invokeWithinContext((accessor) => {
        const canPeek = !openToSide && this.editor.getOption(
          101
          /* EditorOption.definitionLinkOpensInPeek */
        ) && !this.isInPeekEditor(accessor);
        const action = new DefinitionAction({ openToSide, openInPeek: canPeek, muteMessage: true }, { title: { value: "", original: "" }, id: "", precondition: void 0 });
        return action.run(accessor);
      });
    }
    isInPeekEditor(accessor) {
      const contextKeyService = accessor.get(IContextKeyService);
      return PeekContext.inPeekEditor.getValue(contextKeyService);
    }
    dispose() {
      this.toUnhook.dispose();
      this.toUnhookForKeyboard.dispose();
    }
  }, GotoDefinitionAtPositionEditorContribution_1 = _ma, _ma.ID = "editor.contrib.gotodefinitionatposition", _ma.MAX_SOURCE_PREVIEW_LINES = 8, _ma);
  GotoDefinitionAtPositionEditorContribution = GotoDefinitionAtPositionEditorContribution_1 = __decorate$12([
    __param$11(1, ITextModelService),
    __param$11(2, ILanguageService),
    __param$11(3, ILanguageFeaturesService)
  ], GotoDefinitionAtPositionEditorContribution);
  registerEditorContribution(
    GotoDefinitionAtPositionEditorContribution.ID,
    GotoDefinitionAtPositionEditorContribution,
    2
    /* EditorContributionInstantiation.BeforeFirstInteraction */
  );
  class DebugEditorGpuRendererAction extends EditorAction {
    constructor() {
      super({
        id: "editor.action.debugEditorGpuRenderer",
        label: localize2(1101, "Developer: Debug Editor GPU Renderer"),
        // TODO: Why doesn't `ContextKeyExpr.equals('config:editor.experimentalGpuAcceleration', 'on')` work?
        precondition: ContextKeyExpr.true()
      });
    }
    async run(accessor, editor2) {
      const instantiationService = accessor.get(IInstantiationService);
      const quickInputService = accessor.get(IQuickInputService);
      const choice = await quickInputService.pick([
        {
          label: localize(1098, "Log Texture Atlas Stats"),
          id: "logTextureAtlasStats"
        },
        {
          label: localize(1099, "Save Texture Atlas"),
          id: "saveTextureAtlas"
        },
        {
          label: localize(1100, "Draw Glyph"),
          id: "drawGlyph"
        }
      ], { canPickMany: false });
      if (!choice) {
        return;
      }
      switch (choice.id) {
        case "logTextureAtlasStats":
          instantiationService.invokeFunction((accessor2) => {
            const logService = accessor2.get(ILogService);
            const atlas = ViewGpuContext.atlas;
            if (!ViewGpuContext.atlas) {
              logService.error("No texture atlas found");
              return;
            }
            const stats = atlas.getStats();
            logService.info(["Texture atlas stats", ...stats].join("\n\n"));
          });
          break;
        case "saveTextureAtlas":
          instantiationService.invokeFunction(async (accessor2) => {
            const workspaceContextService = accessor2.get(IWorkspaceContextService);
            const fileService = accessor2.get(IFileService);
            const folders = workspaceContextService.getWorkspace().folders;
            if (folders.length > 0) {
              const atlas = ViewGpuContext.atlas;
              const promises = [];
              for (const [layerIndex, page] of atlas.pages.entries()) {
                promises.push(...[
                  fileService.writeFile(URI.joinPath(folders[0].uri, `textureAtlasPage${layerIndex}_actual.png`), VSBuffer.wrap(new Uint8Array(await (await page.source.convertToBlob()).arrayBuffer()))),
                  fileService.writeFile(URI.joinPath(folders[0].uri, `textureAtlasPage${layerIndex}_usage.png`), VSBuffer.wrap(new Uint8Array(await (await page.getUsagePreview()).arrayBuffer())))
                ]);
              }
              await Promise.all(promises);
            }
          });
          break;
        case "drawGlyph":
          instantiationService.invokeFunction(async (accessor2) => {
            const configurationService = accessor2.get(IConfigurationService);
            const fileService = accessor2.get(IFileService);
            const quickInputService2 = accessor2.get(IQuickInputService);
            const workspaceContextService = accessor2.get(IWorkspaceContextService);
            const folders = workspaceContextService.getWorkspace().folders;
            if (folders.length === 0) {
              return;
            }
            const atlas = ViewGpuContext.atlas;
            const fontFamily = configurationService.getValue("editor.fontFamily");
            const fontSize = configurationService.getValue("editor.fontSize");
            const rasterizer = new GlyphRasterizer(fontSize, fontFamily, getActiveWindow().devicePixelRatio, ViewGpuContext.decorationStyleCache);
            let chars = await quickInputService2.input({
              prompt: "Enter a character to draw (prefix with 0x for code point))"
            });
            if (!chars) {
              return;
            }
            const codePoint = chars.match(/0x(?<codePoint>[0-9a-f]+)/i)?.groups?.codePoint;
            if (codePoint !== void 0) {
              chars = String.fromCodePoint(parseInt(codePoint, 16));
            }
            const tokenMetadata = 0;
            const charMetadata = 0;
            const rasterizedGlyph = atlas.getGlyph(rasterizer, chars, tokenMetadata, charMetadata, 0);
            if (!rasterizedGlyph) {
              return;
            }
            const imageData = atlas.pages[rasterizedGlyph.pageIndex].source.getContext("2d")?.getImageData(rasterizedGlyph.x, rasterizedGlyph.y, rasterizedGlyph.w, rasterizedGlyph.h);
            if (!imageData) {
              return;
            }
            const canvas = new OffscreenCanvas(imageData.width, imageData.height);
            const ctx = ensureNonNullable(canvas.getContext("2d"));
            ctx.putImageData(imageData, 0, 0);
            const blob = await canvas.convertToBlob({ type: "image/png" });
            const resource = URI.joinPath(folders[0].uri, `glyph_${chars}_${tokenMetadata}_${fontSize}px_${fontFamily.replaceAll(/[,\\\/\.'\s]/g, "_")}.png`);
            await fileService.writeFile(resource, VSBuffer.wrap(new Uint8Array(await blob.arrayBuffer())));
          });
          break;
      }
    }
  }
  registerEditorAction(DebugEditorGpuRendererAction);
  var HoverFocusBehavior;
  (function(HoverFocusBehavior2) {
    HoverFocusBehavior2["NoAutoFocus"] = "noAutoFocus";
    HoverFocusBehavior2["FocusIfVisible"] = "focusIfVisible";
    HoverFocusBehavior2["AutoFocusImmediately"] = "autoFocusImmediately";
  })(HoverFocusBehavior || (HoverFocusBehavior = {}));
  class ShowOrFocusHoverAction extends EditorAction {
    constructor() {
      super({
        id: SHOW_OR_FOCUS_HOVER_ACTION_ID,
        label: localize2(1107, "Show or Focus Hover"),
        metadata: {
          description: localize2(1108, "Show or focus the editor hover which shows documentation, references, and other content for a symbol at the current cursor position."),
          args: [{
            name: "args",
            schema: {
              type: "object",
              properties: {
                "focus": {
                  description: "Controls if and when the hover should take focus upon being triggered by this action.",
                  enum: [HoverFocusBehavior.NoAutoFocus, HoverFocusBehavior.FocusIfVisible, HoverFocusBehavior.AutoFocusImmediately],
                  enumDescriptions: [
                    localize(1104, "The hover will not automatically take focus."),
                    localize(1105, "The hover will take focus only if it is already visible."),
                    localize(1106, "The hover will automatically take focus when it appears.")
                  ],
                  default: HoverFocusBehavior.FocusIfVisible
                }
              }
            }
          }]
        },
        precondition: void 0,
        kbOpts: {
          kbExpr: EditorContextKeys.editorTextFocus,
          primary: KeyChord(
            2048 | 41,
            2048 | 39
            /* KeyCode.KeyI */
          ),
          weight: 100
          /* KeybindingWeight.EditorContrib */
        }
      });
    }
    run(accessor, editor2, args) {
      if (!editor2.hasModel()) {
        return;
      }
      const controller = ContentHoverController.get(editor2);
      if (!controller) {
        return;
      }
      const focusArgument = args?.focus;
      let focusOption = HoverFocusBehavior.FocusIfVisible;
      if (Object.values(HoverFocusBehavior).includes(focusArgument)) {
        focusOption = focusArgument;
      } else if (typeof focusArgument === "boolean" && focusArgument) {
        focusOption = HoverFocusBehavior.AutoFocusImmediately;
      }
      const showContentHover = (focus) => {
        const position = editor2.getPosition();
        const range2 = new Range$2(position.lineNumber, position.column, position.lineNumber, position.column);
        controller.showContentHover(range2, 1, 2, focus);
      };
      const accessibilitySupportEnabled = editor2.getOption(
        2
        /* EditorOption.accessibilitySupport */
      ) === 2;
      if (controller.isHoverVisible) {
        if (focusOption !== HoverFocusBehavior.NoAutoFocus) {
          controller.focus();
        } else {
          showContentHover(accessibilitySupportEnabled);
        }
      } else {
        showContentHover(accessibilitySupportEnabled || focusOption === HoverFocusBehavior.AutoFocusImmediately);
      }
    }
  }
  class ShowDefinitionPreviewHoverAction extends EditorAction {
    constructor() {
      super({
        id: SHOW_DEFINITION_PREVIEW_HOVER_ACTION_ID,
        label: localize2(1109, "Show Definition Preview Hover"),
        precondition: void 0,
        metadata: {
          description: localize2(1110, "Show the definition preview hover in the editor.")
        }
      });
    }
    run(accessor, editor2) {
      const controller = ContentHoverController.get(editor2);
      if (!controller) {
        return;
      }
      const position = editor2.getPosition();
      if (!position) {
        return;
      }
      const range2 = new Range$2(position.lineNumber, position.column, position.lineNumber, position.column);
      const goto = GotoDefinitionAtPositionEditorContribution.get(editor2);
      if (!goto) {
        return;
      }
      const promise = goto.startFindDefinitionFromCursor(position);
      promise.then(() => {
        controller.showContentHover(range2, 1, 2, true);
      });
    }
  }
  class HideContentHoverAction extends EditorAction {
    constructor() {
      super({
        id: HIDE_HOVER_ACTION_ID,
        label: localize2(1111, "Hide Hover"),
        alias: "Hide Content Hover",
        precondition: void 0
      });
    }
    run(accessor, editor2) {
      ContentHoverController.get(editor2)?.hideContentHover();
    }
  }
  class ScrollUpHoverAction extends EditorAction {
    constructor() {
      super({
        id: SCROLL_UP_HOVER_ACTION_ID,
        label: localize2(1112, "Scroll Up Hover"),
        precondition: EditorContextKeys.hoverFocused,
        kbOpts: {
          kbExpr: EditorContextKeys.hoverFocused,
          primary: 16,
          weight: 100
          /* KeybindingWeight.EditorContrib */
        },
        metadata: {
          description: localize2(1113, "Scroll up the editor hover.")
        }
      });
    }
    run(accessor, editor2) {
      const controller = ContentHoverController.get(editor2);
      if (!controller) {
        return;
      }
      controller.scrollUp();
    }
  }
  class ScrollDownHoverAction extends EditorAction {
    constructor() {
      super({
        id: SCROLL_DOWN_HOVER_ACTION_ID,
        label: localize2(1114, "Scroll Down Hover"),
        precondition: EditorContextKeys.hoverFocused,
        kbOpts: {
          kbExpr: EditorContextKeys.hoverFocused,
          primary: 18,
          weight: 100
          /* KeybindingWeight.EditorContrib */
        },
        metadata: {
          description: localize2(1115, "Scroll down the editor hover.")
        }
      });
    }
    run(accessor, editor2) {
      const controller = ContentHoverController.get(editor2);
      if (!controller) {
        return;
      }
      controller.scrollDown();
    }
  }
  class ScrollLeftHoverAction extends EditorAction {
    constructor() {
      super({
        id: SCROLL_LEFT_HOVER_ACTION_ID,
        label: localize2(1116, "Scroll Left Hover"),
        precondition: EditorContextKeys.hoverFocused,
        kbOpts: {
          kbExpr: EditorContextKeys.hoverFocused,
          primary: 15,
          weight: 100
          /* KeybindingWeight.EditorContrib */
        },
        metadata: {
          description: localize2(1117, "Scroll left the editor hover.")
        }
      });
    }
    run(accessor, editor2) {
      const controller = ContentHoverController.get(editor2);
      if (!controller) {
        return;
      }
      controller.scrollLeft();
    }
  }
  class ScrollRightHoverAction extends EditorAction {
    constructor() {
      super({
        id: SCROLL_RIGHT_HOVER_ACTION_ID,
        label: localize2(1118, "Scroll Right Hover"),
        precondition: EditorContextKeys.hoverFocused,
        kbOpts: {
          kbExpr: EditorContextKeys.hoverFocused,
          primary: 17,
          weight: 100
          /* KeybindingWeight.EditorContrib */
        },
        metadata: {
          description: localize2(1119, "Scroll right the editor hover.")
        }
      });
    }
    run(accessor, editor2) {
      const controller = ContentHoverController.get(editor2);
      if (!controller) {
        return;
      }
      controller.scrollRight();
    }
  }
  class PageUpHoverAction extends EditorAction {
    constructor() {
      super({
        id: PAGE_UP_HOVER_ACTION_ID,
        label: localize2(1120, "Page Up Hover"),
        precondition: EditorContextKeys.hoverFocused,
        kbOpts: {
          kbExpr: EditorContextKeys.hoverFocused,
          primary: 11,
          secondary: [
            512 | 16
            /* KeyCode.UpArrow */
          ],
          weight: 100
          /* KeybindingWeight.EditorContrib */
        },
        metadata: {
          description: localize2(1121, "Page up the editor hover.")
        }
      });
    }
    run(accessor, editor2) {
      const controller = ContentHoverController.get(editor2);
      if (!controller) {
        return;
      }
      controller.pageUp();
    }
  }
  class PageDownHoverAction extends EditorAction {
    constructor() {
      super({
        id: PAGE_DOWN_HOVER_ACTION_ID,
        label: localize2(1122, "Page Down Hover"),
        precondition: EditorContextKeys.hoverFocused,
        kbOpts: {
          kbExpr: EditorContextKeys.hoverFocused,
          primary: 12,
          secondary: [
            512 | 18
            /* KeyCode.DownArrow */
          ],
          weight: 100
          /* KeybindingWeight.EditorContrib */
        },
        metadata: {
          description: localize2(1123, "Page down the editor hover.")
        }
      });
    }
    run(accessor, editor2) {
      const controller = ContentHoverController.get(editor2);
      if (!controller) {
        return;
      }
      controller.pageDown();
    }
  }
  class GoToTopHoverAction extends EditorAction {
    constructor() {
      super({
        id: GO_TO_TOP_HOVER_ACTION_ID,
        label: localize2(1124, "Go To Top Hover"),
        precondition: EditorContextKeys.hoverFocused,
        kbOpts: {
          kbExpr: EditorContextKeys.hoverFocused,
          primary: 14,
          secondary: [
            2048 | 16
            /* KeyCode.UpArrow */
          ],
          weight: 100
          /* KeybindingWeight.EditorContrib */
        },
        metadata: {
          description: localize2(1125, "Go to the top of the editor hover.")
        }
      });
    }
    run(accessor, editor2) {
      const controller = ContentHoverController.get(editor2);
      if (!controller) {
        return;
      }
      controller.goToTop();
    }
  }
  class GoToBottomHoverAction extends EditorAction {
    constructor() {
      super({
        id: GO_TO_BOTTOM_HOVER_ACTION_ID,
        label: localize2(1126, "Go To Bottom Hover"),
        precondition: EditorContextKeys.hoverFocused,
        kbOpts: {
          kbExpr: EditorContextKeys.hoverFocused,
          primary: 13,
          secondary: [
            2048 | 18
            /* KeyCode.DownArrow */
          ],
          weight: 100
          /* KeybindingWeight.EditorContrib */
        },
        metadata: {
          description: localize2(1127, "Go to the bottom of the editor hover.")
        }
      });
    }
    run(accessor, editor2) {
      const controller = ContentHoverController.get(editor2);
      if (!controller) {
        return;
      }
      controller.goToBottom();
    }
  }
  class IncreaseHoverVerbosityLevel extends EditorAction {
    constructor() {
      super({
        id: INCREASE_HOVER_VERBOSITY_ACTION_ID,
        label: INCREASE_HOVER_VERBOSITY_ACTION_LABEL,
        alias: "Increase Hover Verbosity Level",
        precondition: EditorContextKeys.hoverVisible
      });
    }
    run(accessor, editor2, args) {
      const hoverController = ContentHoverController.get(editor2);
      if (!hoverController) {
        return;
      }
      const index = args?.index !== void 0 ? args.index : hoverController.focusedHoverPartIndex();
      hoverController.updateHoverVerbosityLevel(HoverVerbosityAction$1.Increase, index, args?.focus);
    }
  }
  class DecreaseHoverVerbosityLevel extends EditorAction {
    constructor() {
      super({
        id: DECREASE_HOVER_VERBOSITY_ACTION_ID,
        label: DECREASE_HOVER_VERBOSITY_ACTION_LABEL,
        alias: "Decrease Hover Verbosity Level",
        precondition: EditorContextKeys.hoverVisible
      });
    }
    run(accessor, editor2, args) {
      const hoverController = ContentHoverController.get(editor2);
      if (!hoverController) {
        return;
      }
      const index = args?.index !== void 0 ? args.index : hoverController.focusedHoverPartIndex();
      ContentHoverController.get(editor2)?.updateHoverVerbosityLevel(HoverVerbosityAction$1.Decrease, index, args?.focus);
    }
  }
  class GlyphHoverComputer {
    constructor(_editor) {
      this._editor = _editor;
    }
    computeSync(opts) {
      const toHoverMessage = (contents) => {
        return {
          value: contents
        };
      };
      const lineDecorations = this._editor.getLineDecorations(opts.lineNumber);
      const result = [];
      const isLineHover = opts.laneOrLine === "lineNo";
      if (!lineDecorations) {
        return result;
      }
      for (const d of lineDecorations) {
        const lane = d.options.glyphMargin?.position ?? GlyphMarginLane$1.Center;
        if (!isLineHover && lane !== opts.laneOrLine) {
          continue;
        }
        const hoverMessage = isLineHover ? d.options.lineNumberHoverMessage : d.options.glyphMarginHoverMessage;
        if (!hoverMessage || isEmptyMarkdownString(hoverMessage)) {
          continue;
        }
        result.push(...asArray(hoverMessage).map(toHoverMessage));
      }
      return result;
    }
  }
  var __decorate$11 = 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$10 = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  var GlyphHoverWidget_1;
  const $$7 = $$l;
  let GlyphHoverWidget = (_na = class extends Disposable {
    constructor(editor2, _markdownRendererService) {
      super();
      this._markdownRendererService = _markdownRendererService;
      this.allowEditorOverflow = true;
      this._renderDisposeables = this._register(new DisposableStore());
      this._editor = editor2;
      this._isVisible = false;
      this._messages = [];
      this._hover = this._register(new HoverWidget$1(true));
      this._hover.containerDomNode.classList.toggle("hidden", !this._isVisible);
      this._hoverOperation = this._register(new HoverOperation(this._editor, new GlyphHoverComputer(this._editor)));
      this._register(this._hoverOperation.onResult((result) => this._withResult(result)));
      this._register(this._editor.onDidChangeModelDecorations(() => this._onModelDecorationsChanged()));
      this._register(this._editor.onDidChangeConfiguration((e) => {
        if (e.hasChanged(
          59
          /* EditorOption.fontInfo */
        )) {
          this._updateFont();
        }
      }));
      this._register(addStandardDisposableListener(this._hover.containerDomNode, "mouseleave", (e) => {
        this._onMouseLeave(e);
      }));
      this._editor.addOverlayWidget(this);
    }
    dispose() {
      this._hoverComputerOptions = void 0;
      this._editor.removeOverlayWidget(this);
      super.dispose();
    }
    getId() {
      return GlyphHoverWidget_1.ID;
    }
    getDomNode() {
      return this._hover.containerDomNode;
    }
    getPosition() {
      return null;
    }
    _updateFont() {
      const codeClasses = Array.prototype.slice.call(this._hover.contentsDomNode.getElementsByClassName("code"));
      codeClasses.forEach((node) => this._editor.applyFontInfo(node));
    }
    _onModelDecorationsChanged() {
      if (this._isVisible && this._hoverComputerOptions) {
        this._hoverOperation.cancel();
        this._hoverOperation.start(0, this._hoverComputerOptions);
      }
    }
    showsOrWillShow(mouseEvent) {
      const target = mouseEvent.target;
      if (target.type === 2 && target.detail.glyphMarginLane) {
        this._startShowingAt(target.position.lineNumber, target.detail.glyphMarginLane);
        return true;
      }
      if (target.type === 3) {
        this._startShowingAt(target.position.lineNumber, "lineNo");
        return true;
      }
      return false;
    }
    _startShowingAt(lineNumber, laneOrLine) {
      if (this._hoverComputerOptions && this._hoverComputerOptions.lineNumber === lineNumber && this._hoverComputerOptions.laneOrLine === laneOrLine) {
        return;
      }
      this._hoverOperation.cancel();
      this.hide();
      this._hoverComputerOptions = { lineNumber, laneOrLine };
      this._hoverOperation.start(0, this._hoverComputerOptions);
    }
    hide() {
      this._hoverComputerOptions = void 0;
      this._hoverOperation.cancel();
      if (!this._isVisible) {
        return;
      }
      this._isVisible = false;
      this._hover.containerDomNode.classList.toggle("hidden", !this._isVisible);
    }
    _withResult(result) {
      this._messages = result.value;
      if (this._messages.length > 0) {
        this._renderMessages(result.options.lineNumber, result.options.laneOrLine, this._messages);
      } else {
        this.hide();
      }
    }
    _renderMessages(lineNumber, laneOrLine, messages) {
      this._renderDisposeables.clear();
      const fragment = document.createDocumentFragment();
      for (const msg of messages) {
        const markdownHoverElement = $$7("div.hover-row.markdown-hover");
        const hoverContentsElement = append$2(markdownHoverElement, $$7("div.hover-contents"));
        const renderedContents = this._renderDisposeables.add(this._markdownRendererService.render(msg.value, { context: this._editor }));
        hoverContentsElement.appendChild(renderedContents.element);
        fragment.appendChild(markdownHoverElement);
      }
      this._updateContents(fragment);
      this._showAt(lineNumber, laneOrLine);
    }
    _updateContents(node) {
      this._hover.contentsDomNode.textContent = "";
      this._hover.contentsDomNode.appendChild(node);
      this._updateFont();
    }
    _showAt(lineNumber, laneOrLine) {
      if (!this._isVisible) {
        this._isVisible = true;
        this._hover.containerDomNode.classList.toggle("hidden", !this._isVisible);
      }
      const editorLayout = this._editor.getLayoutInfo();
      const topForLineNumber = this._editor.getTopForLineNumber(lineNumber);
      const editorScrollTop = this._editor.getScrollTop();
      const lineHeight = this._editor.getOption(
        75
        /* EditorOption.lineHeight */
      );
      const nodeHeight = this._hover.containerDomNode.clientHeight;
      const top = topForLineNumber - editorScrollTop - (nodeHeight - lineHeight) / 2;
      const left = editorLayout.glyphMarginLeft + editorLayout.glyphMarginWidth + (laneOrLine === "lineNo" ? editorLayout.lineNumbersWidth : 0);
      const editorHeight = editorLayout.height;
      const maxTop = editorHeight - nodeHeight;
      const constrainedTop = Math.max(0, Math.min(Math.round(top), maxTop));
      const fixedOverflowWidgets = this._editor.getOption(
        51
        /* EditorOption.fixedOverflowWidgets */
      );
      if (fixedOverflowWidgets) {
        const editorDomNode = this._editor.getDomNode();
        if (editorDomNode) {
          const editorRect = getDomNodePagePosition(editorDomNode);
          this._hover.containerDomNode.style.position = "fixed";
          this._hover.containerDomNode.style.left = `${editorRect.left + left}px`;
          this._hover.containerDomNode.style.top = `${editorRect.top + constrainedTop}px`;
        }
      } else {
        this._hover.containerDomNode.style.position = "absolute";
        this._hover.containerDomNode.style.left = `${left}px`;
        this._hover.containerDomNode.style.top = `${constrainedTop}px`;
      }
      this._hover.containerDomNode.style.zIndex = "11";
    }
    _onMouseLeave(e) {
      const editorDomNode = this._editor.getDomNode();
      const isMousePositionOutsideOfEditor = !editorDomNode || !isMousePositionWithinElement(editorDomNode, e.x, e.y);
      if (isMousePositionOutsideOfEditor) {
        this.hide();
      }
    }
  }, GlyphHoverWidget_1 = _na, _na.ID = "editor.contrib.modesGlyphHoverWidget", _na);
  GlyphHoverWidget = GlyphHoverWidget_1 = __decorate$11([
    __param$10(1, IMarkdownRendererService)
  ], GlyphHoverWidget);
  var __decorate$10 = 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$$ = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  let GlyphHoverController = (_oa = class extends Disposable {
    constructor(_editor, _instantiationService) {
      super();
      this._editor = _editor;
      this._instantiationService = _instantiationService;
      this.shouldKeepOpenOnEditorMouseMoveOrLeave = false;
      this._listenersStore = new DisposableStore();
      this._hoverState = {
        mouseDown: false
      };
      this._reactToEditorMouseMoveRunner = this._register(new RunOnceScheduler(() => this._reactToEditorMouseMove(this._mouseMoveEvent), 0));
      this._hookListeners();
      this._register(this._editor.onDidChangeConfiguration((e) => {
        if (e.hasChanged(
          69
          /* EditorOption.hover */
        )) {
          this._unhookListeners();
          this._hookListeners();
        }
      }));
    }
    _hookListeners() {
      const hoverOpts = this._editor.getOption(
        69
        /* EditorOption.hover */
      );
      this._hoverSettings = {
        enabled: hoverOpts.enabled,
        sticky: hoverOpts.sticky,
        hidingDelay: hoverOpts.hidingDelay
      };
      if (hoverOpts.enabled) {
        this._listenersStore.add(this._editor.onMouseDown((e) => this._onEditorMouseDown(e)));
        this._listenersStore.add(this._editor.onMouseUp(() => this._onEditorMouseUp()));
        this._listenersStore.add(this._editor.onMouseMove((e) => this._onEditorMouseMove(e)));
        this._listenersStore.add(this._editor.onKeyDown((e) => this._onKeyDown(e)));
      } else {
        this._listenersStore.add(this._editor.onMouseMove((e) => this._onEditorMouseMove(e)));
        this._listenersStore.add(this._editor.onKeyDown((e) => this._onKeyDown(e)));
      }
      this._listenersStore.add(this._editor.onMouseLeave((e) => this._onEditorMouseLeave(e)));
      this._listenersStore.add(this._editor.onDidChangeModel(() => {
        this._cancelScheduler();
        this.hideGlyphHover();
      }));
      this._listenersStore.add(this._editor.onDidChangeModelContent(() => this._cancelScheduler()));
      this._listenersStore.add(this._editor.onDidScrollChange((e) => this._onEditorScrollChanged(e)));
    }
    _unhookListeners() {
      this._listenersStore.clear();
    }
    _cancelScheduler() {
      this._mouseMoveEvent = void 0;
      this._reactToEditorMouseMoveRunner.cancel();
    }
    _onEditorScrollChanged(e) {
      if (e.scrollTopChanged || e.scrollLeftChanged) {
        this.hideGlyphHover();
      }
    }
    _onEditorMouseDown(mouseEvent) {
      this._hoverState.mouseDown = true;
      const shouldNotHideCurrentHoverWidget = this._isMouseOnGlyphHoverWidget(mouseEvent);
      if (shouldNotHideCurrentHoverWidget) {
        return;
      }
      this.hideGlyphHover();
    }
    _isMouseOnGlyphHoverWidget(mouseEvent) {
      const glyphHoverWidgetNode = this._glyphWidget?.getDomNode();
      if (glyphHoverWidgetNode) {
        return isMousePositionWithinElement(glyphHoverWidgetNode, mouseEvent.event.posx, mouseEvent.event.posy);
      }
      return false;
    }
    _onEditorMouseUp() {
      this._hoverState.mouseDown = false;
    }
    _onEditorMouseLeave(mouseEvent) {
      if (this.shouldKeepOpenOnEditorMouseMoveOrLeave) {
        return;
      }
      this._cancelScheduler();
      const shouldNotHideCurrentHoverWidget = this._isMouseOnGlyphHoverWidget(mouseEvent);
      if (shouldNotHideCurrentHoverWidget) {
        return;
      }
      this.hideGlyphHover();
    }
    _shouldNotRecomputeCurrentHoverWidget(mouseEvent) {
      const isHoverSticky = this._hoverSettings.sticky;
      const isMouseOnGlyphHoverWidget = this._isMouseOnGlyphHoverWidget(mouseEvent);
      return isHoverSticky && isMouseOnGlyphHoverWidget;
    }
    _onEditorMouseMove(mouseEvent) {
      if (this.shouldKeepOpenOnEditorMouseMoveOrLeave) {
        return;
      }
      this._mouseMoveEvent = mouseEvent;
      const shouldNotRecomputeCurrentHoverWidget = this._shouldNotRecomputeCurrentHoverWidget(mouseEvent);
      if (shouldNotRecomputeCurrentHoverWidget) {
        this._reactToEditorMouseMoveRunner.cancel();
        return;
      }
      this._reactToEditorMouseMove(mouseEvent);
    }
    _reactToEditorMouseMove(mouseEvent) {
      if (!mouseEvent) {
        return;
      }
      const glyphWidgetShowsOrWillShow = this._tryShowHoverWidget(mouseEvent);
      if (glyphWidgetShowsOrWillShow) {
        return;
      }
      this.hideGlyphHover();
    }
    _tryShowHoverWidget(mouseEvent) {
      const glyphWidget = this._getOrCreateGlyphWidget();
      return glyphWidget.showsOrWillShow(mouseEvent);
    }
    _onKeyDown(e) {
      if (!this._editor.hasModel()) {
        return;
      }
      if (e.keyCode === 5 || e.keyCode === 6 || e.keyCode === 57 || e.keyCode === 4) {
        return;
      }
      this.hideGlyphHover();
    }
    hideGlyphHover() {
      this._glyphWidget?.hide();
    }
    _getOrCreateGlyphWidget() {
      if (!this._glyphWidget) {
        this._glyphWidget = this._instantiationService.createInstance(GlyphHoverWidget, this._editor);
      }
      return this._glyphWidget;
    }
    dispose() {
      super.dispose();
      this._unhookListeners();
      this._listenersStore.dispose();
      this._glyphWidget?.dispose();
    }
  }, _oa.ID = "editor.contrib.marginHover", _oa);
  GlyphHoverController = __decorate$10([
    __param$$(1, IInstantiationService)
  ], GlyphHoverController);
  class HoverAccessibleView {
  }
  class HoverAccessibilityHelp {
  }
  class ExtHoverAccessibleView {
  }
  registerEditorContribution(
    ContentHoverController.ID,
    ContentHoverController,
    2
    /* EditorContributionInstantiation.BeforeFirstInteraction */
  );
  registerEditorContribution(
    GlyphHoverController.ID,
    GlyphHoverController,
    2
    /* EditorContributionInstantiation.BeforeFirstInteraction */
  );
  registerEditorAction(ShowOrFocusHoverAction);
  registerEditorAction(ShowDefinitionPreviewHoverAction);
  registerEditorAction(HideContentHoverAction);
  registerEditorAction(ScrollUpHoverAction);
  registerEditorAction(ScrollDownHoverAction);
  registerEditorAction(ScrollLeftHoverAction);
  registerEditorAction(ScrollRightHoverAction);
  registerEditorAction(PageUpHoverAction);
  registerEditorAction(PageDownHoverAction);
  registerEditorAction(GoToTopHoverAction);
  registerEditorAction(GoToBottomHoverAction);
  registerEditorAction(IncreaseHoverVerbosityLevel);
  registerEditorAction(DecreaseHoverVerbosityLevel);
  HoverParticipantRegistry.register(MarkdownHoverParticipant);
  HoverParticipantRegistry.register(MarkerHoverParticipant);
  registerThemingParticipant((theme, collector) => {
    const hoverBorder = theme.getColor(editorHoverBorder);
    if (hoverBorder) {
      collector.addRule(`.monaco-editor .monaco-hover .hover-row:not(:first-child):not(:empty) { border-top: 1px solid ${hoverBorder.transparent(0.5)}; }`);
      collector.addRule(`.monaco-editor .monaco-hover hr { border-top: 1px solid ${hoverBorder.transparent(0.5)}; }`);
      collector.addRule(`.monaco-editor .monaco-hover hr { border-bottom: 0px solid ${hoverBorder.transparent(0.5)}; }`);
    }
  });
  AccessibleViewRegistry.register(new HoverAccessibleView());
  AccessibleViewRegistry.register(new HoverAccessibilityHelp());
  AccessibleViewRegistry.register(new ExtHoverAccessibleView());
  function getReindentEditOperations(model, languageConfigurationService, startLineNumber, endLineNumber) {
    if (model.getLineCount() === 1 && model.getLineMaxColumn(1) === 1) {
      return [];
    }
    const indentationRulesSupport = languageConfigurationService.getLanguageConfiguration(model.getLanguageId()).indentRulesSupport;
    if (!indentationRulesSupport) {
      return [];
    }
    const processedIndentRulesSupport = new ProcessedIndentRulesSupport(model, indentationRulesSupport, languageConfigurationService);
    endLineNumber = Math.min(endLineNumber, model.getLineCount());
    while (startLineNumber <= endLineNumber) {
      if (!processedIndentRulesSupport.shouldIgnore(startLineNumber)) {
        break;
      }
      startLineNumber++;
    }
    if (startLineNumber > endLineNumber - 1) {
      return [];
    }
    const { tabSize, indentSize, insertSpaces } = model.getOptions();
    const shiftIndent2 = (indentation, count) => {
      count = count || 1;
      return ShiftCommand.shiftIndent(indentation, indentation.length + count, tabSize, indentSize, insertSpaces);
    };
    const unshiftIndent2 = (indentation, count) => {
      count = count || 1;
      return ShiftCommand.unshiftIndent(indentation, indentation.length + count, tabSize, indentSize, insertSpaces);
    };
    const indentEdits = [];
    const currentLineText = model.getLineContent(startLineNumber);
    let globalIndent = getLeadingWhitespace(currentLineText);
    let idealIndentForNextLine = globalIndent;
    if (processedIndentRulesSupport.shouldIncrease(startLineNumber)) {
      idealIndentForNextLine = shiftIndent2(idealIndentForNextLine);
      globalIndent = shiftIndent2(globalIndent);
    } else if (processedIndentRulesSupport.shouldIndentNextLine(startLineNumber)) {
      idealIndentForNextLine = shiftIndent2(idealIndentForNextLine);
    }
    startLineNumber++;
    for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
      if (doesLineStartWithString(model, lineNumber)) {
        continue;
      }
      const text2 = model.getLineContent(lineNumber);
      const oldIndentation = getLeadingWhitespace(text2);
      const currentIdealIndent = idealIndentForNextLine;
      if (processedIndentRulesSupport.shouldDecrease(lineNumber, currentIdealIndent)) {
        idealIndentForNextLine = unshiftIndent2(idealIndentForNextLine);
        globalIndent = unshiftIndent2(globalIndent);
      }
      if (oldIndentation !== idealIndentForNextLine) {
        indentEdits.push(EditOperation.replaceMove(new Selection$1(lineNumber, 1, lineNumber, oldIndentation.length + 1), normalizeIndentation(idealIndentForNextLine, indentSize, insertSpaces)));
      }
      if (processedIndentRulesSupport.shouldIgnore(lineNumber)) {
        continue;
      } else if (processedIndentRulesSupport.shouldIncrease(lineNumber, currentIdealIndent)) {
        globalIndent = shiftIndent2(globalIndent);
        idealIndentForNextLine = globalIndent;
      } else if (processedIndentRulesSupport.shouldIndentNextLine(lineNumber, currentIdealIndent)) {
        idealIndentForNextLine = shiftIndent2(idealIndentForNextLine);
      } else {
        idealIndentForNextLine = globalIndent;
      }
    }
    return indentEdits;
  }
  function doesLineStartWithString(model, lineNumber) {
    if (!model.tokenization.isCheapToTokenize(lineNumber)) {
      return false;
    }
    const lineTokens = model.tokenization.getLineTokens(lineNumber);
    return lineTokens.getStandardTokenType(0) === 2;
  }
  var __decorate$$ = 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$_ = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  const _IndentationToSpacesAction = class _IndentationToSpacesAction extends EditorAction {
    constructor() {
      super({
        id: _IndentationToSpacesAction.ID,
        label: localize2(1148, "Convert Indentation to Spaces"),
        precondition: EditorContextKeys.writable,
        metadata: {
          description: localize2(1149, "Convert the tab indentation to spaces.")
        }
      });
    }
    run(accessor, editor2) {
      const model = editor2.getModel();
      if (!model) {
        return;
      }
      const modelOpts = model.getOptions();
      const selection = editor2.getSelection();
      if (!selection) {
        return;
      }
      const command = new IndentationToSpacesCommand(selection, modelOpts.tabSize);
      editor2.pushUndoStop();
      editor2.executeCommands(this.id, [command]);
      editor2.pushUndoStop();
      model.updateOptions({
        insertSpaces: true
      });
    }
  };
  _IndentationToSpacesAction.ID = "editor.action.indentationToSpaces";
  let IndentationToSpacesAction = _IndentationToSpacesAction;
  const _IndentationToTabsAction = class _IndentationToTabsAction extends EditorAction {
    constructor() {
      super({
        id: _IndentationToTabsAction.ID,
        label: localize2(1150, "Convert Indentation to Tabs"),
        precondition: EditorContextKeys.writable,
        metadata: {
          description: localize2(1151, "Convert the spaces indentation to tabs.")
        }
      });
    }
    run(accessor, editor2) {
      const model = editor2.getModel();
      if (!model) {
        return;
      }
      const modelOpts = model.getOptions();
      const selection = editor2.getSelection();
      if (!selection) {
        return;
      }
      const command = new IndentationToTabsCommand(selection, modelOpts.tabSize);
      editor2.pushUndoStop();
      editor2.executeCommands(this.id, [command]);
      editor2.pushUndoStop();
      model.updateOptions({
        insertSpaces: false
      });
    }
  };
  _IndentationToTabsAction.ID = "editor.action.indentationToTabs";
  let IndentationToTabsAction = _IndentationToTabsAction;
  class ChangeIndentationSizeAction extends EditorAction {
    constructor(insertSpaces, displaySizeOnly, opts) {
      super(opts);
      this.insertSpaces = insertSpaces;
      this.displaySizeOnly = displaySizeOnly;
    }
    run(accessor, editor2) {
      const quickInputService = accessor.get(IQuickInputService);
      const modelService = accessor.get(IModelService);
      const model = editor2.getModel();
      if (!model) {
        return;
      }
      const creationOpts = modelService.getCreationOptions(model.getLanguageId(), model.uri, model.isForSimpleWidget);
      const modelOpts = model.getOptions();
      const picks = [1, 2, 3, 4, 5, 6, 7, 8].map((n2) => ({
        id: n2.toString(),
        label: n2.toString(),
        // add description for tabSize value set in the configuration
        description: n2 === creationOpts.tabSize && n2 === modelOpts.tabSize ? localize(1144, "Configured Tab Size") : n2 === creationOpts.tabSize ? localize(1145, "Default Tab Size") : n2 === modelOpts.tabSize ? localize(1146, "Current Tab Size") : void 0
      }));
      const autoFocusIndex = Math.min(model.getOptions().tabSize - 1, 7);
      setTimeout(
        () => {
          quickInputService.pick(picks, { placeHolder: localize(1147, "Select Tab Size for Current File"), activeItem: picks[autoFocusIndex] }).then((pick) => {
            if (pick) {
              if (model && !model.isDisposed()) {
                const pickedVal = parseInt(pick.label, 10);
                if (this.displaySizeOnly) {
                  model.updateOptions({
                    tabSize: pickedVal
                  });
                } else {
                  model.updateOptions({
                    tabSize: pickedVal,
                    indentSize: pickedVal,
                    insertSpaces: this.insertSpaces
                  });
                }
              }
            }
          });
        },
        50
        /* quick input is sensitive to being opened so soon after another */
      );
    }
  }
  const _IndentUsingTabs = class _IndentUsingTabs extends ChangeIndentationSizeAction {
    constructor() {
      super(false, false, {
        id: _IndentUsingTabs.ID,
        label: localize2(1152, "Indent Using Tabs"),
        precondition: void 0,
        metadata: {
          description: localize2(1153, "Use indentation with tabs.")
        }
      });
    }
  };
  _IndentUsingTabs.ID = "editor.action.indentUsingTabs";
  let IndentUsingTabs = _IndentUsingTabs;
  const _IndentUsingSpaces = class _IndentUsingSpaces extends ChangeIndentationSizeAction {
    constructor() {
      super(true, false, {
        id: _IndentUsingSpaces.ID,
        label: localize2(1154, "Indent Using Spaces"),
        precondition: void 0,
        metadata: {
          description: localize2(1155, "Use indentation with spaces.")
        }
      });
    }
  };
  _IndentUsingSpaces.ID = "editor.action.indentUsingSpaces";
  let IndentUsingSpaces = _IndentUsingSpaces;
  const _ChangeTabDisplaySize = class _ChangeTabDisplaySize extends ChangeIndentationSizeAction {
    constructor() {
      super(true, true, {
        id: _ChangeTabDisplaySize.ID,
        label: localize2(1156, "Change Tab Display Size"),
        precondition: void 0,
        metadata: {
          description: localize2(1157, "Change the space size equivalent of the tab.")
        }
      });
    }
  };
  _ChangeTabDisplaySize.ID = "editor.action.changeTabDisplaySize";
  let ChangeTabDisplaySize = _ChangeTabDisplaySize;
  const _DetectIndentation = class _DetectIndentation extends EditorAction {
    constructor() {
      super({
        id: _DetectIndentation.ID,
        label: localize2(1158, "Detect Indentation from Content"),
        precondition: void 0,
        metadata: {
          description: localize2(1159, "Detect the indentation from content.")
        }
      });
    }
    run(accessor, editor2) {
      const modelService = accessor.get(IModelService);
      const model = editor2.getModel();
      if (!model) {
        return;
      }
      const creationOpts = modelService.getCreationOptions(model.getLanguageId(), model.uri, model.isForSimpleWidget);
      model.detectIndentation(creationOpts.insertSpaces, creationOpts.tabSize);
    }
  };
  _DetectIndentation.ID = "editor.action.detectIndentation";
  let DetectIndentation = _DetectIndentation;
  class ReindentLinesAction extends EditorAction {
    constructor() {
      super({
        id: "editor.action.reindentlines",
        label: localize2(1160, "Reindent Lines"),
        precondition: EditorContextKeys.writable,
        metadata: {
          description: localize2(1161, "Reindent the lines of the editor.")
        },
        canTriggerInlineEdits: true
      });
    }
    run(accessor, editor2) {
      const languageConfigurationService = accessor.get(ILanguageConfigurationService);
      const model = editor2.getModel();
      if (!model) {
        return;
      }
      const edits = getReindentEditOperations(model, languageConfigurationService, 1, model.getLineCount());
      if (edits.length > 0) {
        editor2.pushUndoStop();
        editor2.executeEdits(this.id, edits);
        editor2.pushUndoStop();
      }
    }
  }
  class ReindentSelectedLinesAction extends EditorAction {
    constructor() {
      super({
        id: "editor.action.reindentselectedlines",
        label: localize2(1162, "Reindent Selected Lines"),
        precondition: EditorContextKeys.writable,
        metadata: {
          description: localize2(1163, "Reindent the selected lines of the editor.")
        },
        canTriggerInlineEdits: true
      });
    }
    run(accessor, editor2) {
      const languageConfigurationService = accessor.get(ILanguageConfigurationService);
      const model = editor2.getModel();
      if (!model) {
        return;
      }
      const selections = editor2.getSelections();
      if (selections === null) {
        return;
      }
      const edits = [];
      for (const selection of selections) {
        let startLineNumber = selection.startLineNumber;
        let endLineNumber = selection.endLineNumber;
        if (startLineNumber !== endLineNumber && selection.endColumn === 1) {
          endLineNumber--;
        }
        if (startLineNumber === 1) {
          if (startLineNumber === endLineNumber) {
            continue;
          }
        } else {
          startLineNumber--;
        }
        const editOperations = getReindentEditOperations(model, languageConfigurationService, startLineNumber, endLineNumber);
        edits.push(...editOperations);
      }
      if (edits.length > 0) {
        editor2.pushUndoStop();
        editor2.executeEdits(this.id, edits);
        editor2.pushUndoStop();
      }
    }
  }
  class AutoIndentOnPasteCommand {
    constructor(edits, initialSelection) {
      this._initialSelection = initialSelection;
      this._edits = [];
      this._selectionId = null;
      for (const edit2 of edits) {
        if (edit2.range && typeof edit2.text === "string") {
          this._edits.push(edit2);
        }
      }
    }
    getEditOperations(model, builder) {
      for (const edit2 of this._edits) {
        builder.addEditOperation(Range$2.lift(edit2.range), edit2.text);
      }
      let selectionIsSet = false;
      if (Array.isArray(this._edits) && this._edits.length === 1 && this._initialSelection.isEmpty()) {
        if (this._edits[0].range.startColumn === this._initialSelection.endColumn && this._edits[0].range.startLineNumber === this._initialSelection.endLineNumber) {
          selectionIsSet = true;
          this._selectionId = builder.trackSelection(this._initialSelection, true);
        } else if (this._edits[0].range.endColumn === this._initialSelection.startColumn && this._edits[0].range.endLineNumber === this._initialSelection.startLineNumber) {
          selectionIsSet = true;
          this._selectionId = builder.trackSelection(this._initialSelection, false);
        }
      }
      if (!selectionIsSet) {
        this._selectionId = builder.trackSelection(this._initialSelection);
      }
    }
    computeCursorState(model, helper) {
      return helper.getTrackedSelection(this._selectionId);
    }
  }
  let AutoIndentOnPaste = (_pa = class {
    constructor(editor2, _languageConfigurationService) {
      this.editor = editor2;
      this._languageConfigurationService = _languageConfigurationService;
      this.callOnDispose = new DisposableStore();
      this.callOnModel = new DisposableStore();
      this.callOnDispose.add(editor2.onDidChangeConfiguration(() => this.update()));
      this.callOnDispose.add(editor2.onDidChangeModel(() => this.update()));
      this.callOnDispose.add(editor2.onDidChangeModelLanguage(() => this.update()));
    }
    update() {
      this.callOnModel.clear();
      if (!this.editor.getOption(
        17
        /* EditorOption.autoIndentOnPaste */
      ) || this.editor.getOption(
        16
        /* EditorOption.autoIndent */
      ) < 4) {
        return;
      }
      if (!this.editor.hasModel()) {
        return;
      }
      this.callOnModel.add(this.editor.onDidPaste(({ range: range2 }) => {
        this.trigger(range2);
      }));
    }
    trigger(range2) {
      const selections = this.editor.getSelections();
      if (selections === null || selections.length > 1) {
        return;
      }
      const model = this.editor.getModel();
      if (!model) {
        return;
      }
      const containsOnlyWhitespace = this.rangeContainsOnlyWhitespaceCharacters(model, range2);
      if (containsOnlyWhitespace) {
        return;
      }
      if (!this.editor.getOption(
        18
        /* EditorOption.autoIndentOnPasteWithinString */
      ) && isStartOrEndInString(model, range2)) {
        return;
      }
      if (!model.tokenization.isCheapToTokenize(range2.getStartPosition().lineNumber)) {
        return;
      }
      const autoIndent = this.editor.getOption(
        16
        /* EditorOption.autoIndent */
      );
      const { tabSize, indentSize, insertSpaces } = model.getOptions();
      const textEdits = [];
      const indentConverter = {
        shiftIndent: (indentation) => {
          return ShiftCommand.shiftIndent(indentation, indentation.length + 1, tabSize, indentSize, insertSpaces);
        },
        unshiftIndent: (indentation) => {
          return ShiftCommand.unshiftIndent(indentation, indentation.length + 1, tabSize, indentSize, insertSpaces);
        }
      };
      let startLineNumber = range2.startLineNumber;
      let firstLineText = model.getLineContent(startLineNumber);
      if (!/\S/.test(firstLineText.substring(0, range2.startColumn - 1))) {
        const indentOfFirstLine = getGoodIndentForLine(autoIndent, model, model.getLanguageId(), startLineNumber, indentConverter, this._languageConfigurationService);
        if (indentOfFirstLine !== null) {
          const oldIndentation = getLeadingWhitespace(firstLineText);
          const newSpaceCnt = getSpaceCnt(indentOfFirstLine, tabSize);
          const oldSpaceCnt = getSpaceCnt(oldIndentation, tabSize);
          if (newSpaceCnt !== oldSpaceCnt) {
            const newIndent = generateIndent(newSpaceCnt, tabSize, insertSpaces);
            textEdits.push({
              range: new Range$2(startLineNumber, 1, startLineNumber, oldIndentation.length + 1),
              text: newIndent
            });
            firstLineText = newIndent + firstLineText.substring(oldIndentation.length);
          } else {
            const indentMetadata = getIndentMetadata(model, startLineNumber, this._languageConfigurationService);
            if (indentMetadata === 0 || indentMetadata === 8) {
              return;
            }
          }
        }
      }
      const firstLineNumber = startLineNumber;
      while (startLineNumber < range2.endLineNumber) {
        if (!/\S/.test(model.getLineContent(startLineNumber + 1))) {
          startLineNumber++;
          continue;
        }
        break;
      }
      if (startLineNumber !== range2.endLineNumber) {
        const virtualModel = {
          tokenization: {
            getLineTokens: (lineNumber) => {
              return model.tokenization.getLineTokens(lineNumber);
            },
            getLanguageId: () => {
              return model.getLanguageId();
            },
            getLanguageIdAtPosition: (lineNumber, column) => {
              return model.getLanguageIdAtPosition(lineNumber, column);
            }
          },
          getLineContent: (lineNumber) => {
            if (lineNumber === firstLineNumber) {
              return firstLineText;
            } else {
              return model.getLineContent(lineNumber);
            }
          }
        };
        const indentOfSecondLine = getGoodIndentForLine(autoIndent, virtualModel, model.getLanguageId(), startLineNumber + 1, indentConverter, this._languageConfigurationService);
        if (indentOfSecondLine !== null) {
          const newSpaceCntOfSecondLine = getSpaceCnt(indentOfSecondLine, tabSize);
          const oldSpaceCntOfSecondLine = getSpaceCnt(getLeadingWhitespace(model.getLineContent(startLineNumber + 1)), tabSize);
          if (newSpaceCntOfSecondLine !== oldSpaceCntOfSecondLine) {
            const spaceCntOffset = newSpaceCntOfSecondLine - oldSpaceCntOfSecondLine;
            for (let i2 = startLineNumber + 1; i2 <= range2.endLineNumber; i2++) {
              const lineContent = model.getLineContent(i2);
              const originalIndent = getLeadingWhitespace(lineContent);
              const originalSpacesCnt = getSpaceCnt(originalIndent, tabSize);
              const newSpacesCnt = originalSpacesCnt + spaceCntOffset;
              const newIndent = generateIndent(newSpacesCnt, tabSize, insertSpaces);
              if (newIndent !== originalIndent) {
                textEdits.push({
                  range: new Range$2(i2, 1, i2, originalIndent.length + 1),
                  text: newIndent
                });
              }
            }
          }
        }
      }
      if (textEdits.length > 0) {
        this.editor.pushUndoStop();
        const cmd = new AutoIndentOnPasteCommand(textEdits, this.editor.getSelection());
        this.editor.executeCommand("autoIndentOnPaste", cmd);
        this.editor.pushUndoStop();
      }
    }
    rangeContainsOnlyWhitespaceCharacters(model, range2) {
      const lineContainsOnlyWhitespace = (content) => {
        return content.trim().length === 0;
      };
      let containsOnlyWhitespace = true;
      if (range2.startLineNumber === range2.endLineNumber) {
        const lineContent = model.getLineContent(range2.startLineNumber);
        const linePart = lineContent.substring(range2.startColumn - 1, range2.endColumn - 1);
        containsOnlyWhitespace = lineContainsOnlyWhitespace(linePart);
      } else {
        for (let i2 = range2.startLineNumber; i2 <= range2.endLineNumber; i2++) {
          const lineContent = model.getLineContent(i2);
          if (i2 === range2.startLineNumber) {
            const linePart = lineContent.substring(range2.startColumn - 1);
            containsOnlyWhitespace = lineContainsOnlyWhitespace(linePart);
          } else if (i2 === range2.endLineNumber) {
            const linePart = lineContent.substring(0, range2.endColumn - 1);
            containsOnlyWhitespace = lineContainsOnlyWhitespace(linePart);
          } else {
            containsOnlyWhitespace = model.getLineFirstNonWhitespaceColumn(i2) === 0;
          }
          if (!containsOnlyWhitespace) {
            break;
          }
        }
      }
      return containsOnlyWhitespace;
    }
    dispose() {
      this.callOnDispose.dispose();
      this.callOnModel.dispose();
    }
  }, _pa.ID = "editor.contrib.autoIndentOnPaste", _pa);
  AutoIndentOnPaste = __decorate$$([
    __param$_(1, ILanguageConfigurationService)
  ], AutoIndentOnPaste);
  function isStartOrEndInString(model, range2) {
    const isPositionInString = (position) => {
      const tokenType = getStandardTokenTypeAtPosition(model, position);
      return tokenType === 2;
    };
    return isPositionInString(range2.getStartPosition()) || isPositionInString(range2.getEndPosition());
  }
  function getIndentationEditOperations(model, builder, tabSize, tabsToSpaces) {
    if (model.getLineCount() === 1 && model.getLineMaxColumn(1) === 1) {
      return;
    }
    let spaces2 = "";
    for (let i2 = 0; i2 < tabSize; i2++) {
      spaces2 += " ";
    }
    const spacesRegExp = new RegExp(spaces2, "gi");
    for (let lineNumber = 1, lineCount = model.getLineCount(); lineNumber <= lineCount; lineNumber++) {
      let lastIndentationColumn = model.getLineFirstNonWhitespaceColumn(lineNumber);
      if (lastIndentationColumn === 0) {
        lastIndentationColumn = model.getLineMaxColumn(lineNumber);
      }
      if (lastIndentationColumn === 1) {
        continue;
      }
      const originalIndentationRange = new Range$2(lineNumber, 1, lineNumber, lastIndentationColumn);
      const originalIndentation = model.getValueInRange(originalIndentationRange);
      const newIndentation = tabsToSpaces ? originalIndentation.replace(/\t/ig, spaces2) : originalIndentation.replace(spacesRegExp, "	");
      builder.addEditOperation(originalIndentationRange, newIndentation);
    }
  }
  class IndentationToSpacesCommand {
    constructor(selection, tabSize) {
      this.selection = selection;
      this.tabSize = tabSize;
      this.selectionId = null;
    }
    getEditOperations(model, builder) {
      this.selectionId = builder.trackSelection(this.selection);
      getIndentationEditOperations(model, builder, this.tabSize, true);
    }
    computeCursorState(model, helper) {
      return helper.getTrackedSelection(this.selectionId);
    }
  }
  class IndentationToTabsCommand {
    constructor(selection, tabSize) {
      this.selection = selection;
      this.tabSize = tabSize;
      this.selectionId = null;
    }
    getEditOperations(model, builder) {
      this.selectionId = builder.trackSelection(this.selection);
      getIndentationEditOperations(model, builder, this.tabSize, false);
    }
    computeCursorState(model, helper) {
      return helper.getTrackedSelection(this.selectionId);
    }
  }
  registerEditorContribution(
    AutoIndentOnPaste.ID,
    AutoIndentOnPaste,
    2
    /* EditorContributionInstantiation.BeforeFirstInteraction */
  );
  registerEditorAction(IndentationToSpacesAction);
  registerEditorAction(IndentationToTabsAction);
  registerEditorAction(IndentUsingTabs);
  registerEditorAction(IndentUsingSpaces);
  registerEditorAction(ChangeTabDisplaySize);
  registerEditorAction(DetectIndentation);
  registerEditorAction(ReindentLinesAction);
  registerEditorAction(ReindentSelectedLinesAction);
  registerEditorContribution(
    InlayHintsController.ID,
    InlayHintsController,
    1
    /* EditorContributionInstantiation.AfterFirstRender */
  );
  HoverParticipantRegistry.register(InlayHintsHover);
  class InPlaceReplaceCommand {
    constructor(editRange, originalSelection, text2) {
      this._editRange = editRange;
      this._originalSelection = originalSelection;
      this._text = text2;
    }
    getEditOperations(model, builder) {
      builder.addTrackedEditOperation(this._editRange, this._text);
    }
    computeCursorState(model, helper) {
      const inverseEditOperations = helper.getInverseEditOperations();
      const srcRange = inverseEditOperations[0].range;
      if (!this._originalSelection.isEmpty()) {
        return new Selection$1(srcRange.endLineNumber, srcRange.endColumn - this._text.length, srcRange.endLineNumber, srcRange.endColumn);
      }
      return new Selection$1(srcRange.endLineNumber, Math.min(this._originalSelection.positionColumn, srcRange.endColumn), srcRange.endLineNumber, Math.min(this._originalSelection.positionColumn, srcRange.endColumn));
    }
  }
  var __decorate$_ = 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$Z = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  var InPlaceReplaceController_1;
  let InPlaceReplaceController = (_qa = class {
    static get(editor2) {
      return editor2.getContribution(InPlaceReplaceController_1.ID);
    }
    constructor(editor2, editorWorkerService) {
      this.editor = editor2;
      this.editorWorkerService = editorWorkerService;
      this.decorations = this.editor.createDecorationsCollection();
    }
    dispose() {
    }
    run(source, up) {
      this.currentRequest?.cancel();
      const editorSelection = this.editor.getSelection();
      const model = this.editor.getModel();
      if (!model || !editorSelection) {
        return void 0;
      }
      let selection = editorSelection;
      if (selection.startLineNumber !== selection.endLineNumber) {
        return void 0;
      }
      const state = new EditorState$1(
        this.editor,
        1 | 4
        /* CodeEditorStateFlag.Position */
      );
      const modelURI = model.uri;
      if (!this.editorWorkerService.canNavigateValueSet(modelURI)) {
        return Promise.resolve(void 0);
      }
      this.currentRequest = createCancelablePromise((token) => this.editorWorkerService.navigateValueSet(modelURI, selection, up));
      return this.currentRequest.then((result) => {
        if (!result || !result.range || !result.value) {
          return;
        }
        if (!state.validate(this.editor)) {
          return;
        }
        const editRange = Range$2.lift(result.range);
        let highlightRange2 = result.range;
        const diff = result.value.length - (selection.endColumn - selection.startColumn);
        highlightRange2 = {
          startLineNumber: highlightRange2.startLineNumber,
          startColumn: highlightRange2.startColumn,
          endLineNumber: highlightRange2.endLineNumber,
          endColumn: highlightRange2.startColumn + result.value.length
        };
        if (diff > 1) {
          selection = new Selection$1(selection.startLineNumber, selection.startColumn, selection.endLineNumber, selection.endColumn + diff - 1);
        }
        const command = new InPlaceReplaceCommand(editRange, selection, result.value);
        this.editor.pushUndoStop();
        this.editor.executeCommand(source, command);
        this.editor.pushUndoStop();
        this.decorations.set([{
          range: highlightRange2,
          options: InPlaceReplaceController_1.DECORATION
        }]);
        this.decorationRemover?.cancel();
        this.decorationRemover = timeout(350);
        this.decorationRemover.then(() => this.decorations.clear()).catch(onUnexpectedError);
      }).catch(onUnexpectedError);
    }
  }, InPlaceReplaceController_1 = _qa, _qa.ID = "editor.contrib.inPlaceReplaceController", _qa.DECORATION = ModelDecorationOptions.register({
    description: "in-place-replace",
    className: "valueSetReplacement"
  }), _qa);
  InPlaceReplaceController = InPlaceReplaceController_1 = __decorate$_([
    __param$Z(1, IEditorWorkerService)
  ], InPlaceReplaceController);
  class InPlaceReplaceUp extends EditorAction {
    constructor() {
      super({
        id: "editor.action.inPlaceReplace.up",
        label: localize2(1240, "Replace with Previous Value"),
        precondition: EditorContextKeys.writable,
        kbOpts: {
          kbExpr: EditorContextKeys.editorTextFocus,
          primary: 2048 | 1024 | 87,
          weight: 100
          /* KeybindingWeight.EditorContrib */
        }
      });
    }
    run(accessor, editor2) {
      const controller = InPlaceReplaceController.get(editor2);
      if (!controller) {
        return Promise.resolve(void 0);
      }
      return controller.run(this.id, false);
    }
  }
  class InPlaceReplaceDown extends EditorAction {
    constructor() {
      super({
        id: "editor.action.inPlaceReplace.down",
        label: localize2(1241, "Replace with Next Value"),
        precondition: EditorContextKeys.writable,
        kbOpts: {
          kbExpr: EditorContextKeys.editorTextFocus,
          primary: 2048 | 1024 | 89,
          weight: 100
          /* KeybindingWeight.EditorContrib */
        }
      });
    }
    run(accessor, editor2) {
      const controller = InPlaceReplaceController.get(editor2);
      if (!controller) {
        return Promise.resolve(void 0);
      }
      return controller.run(this.id, true);
    }
  }
  registerEditorContribution(
    InPlaceReplaceController.ID,
    InPlaceReplaceController,
    4
    /* EditorContributionInstantiation.Lazy */
  );
  registerEditorAction(InPlaceReplaceUp);
  registerEditorAction(InPlaceReplaceDown);
  class InsertFinalNewLineCommand {
    constructor(selection) {
      this._selection = selection;
      this._selectionId = null;
    }
    getEditOperations(model, builder) {
      const op = insertFinalNewLine(model);
      if (op) {
        builder.addEditOperation(op.range, op.text);
      }
      this._selectionId = builder.trackSelection(this._selection);
    }
    computeCursorState(model, helper) {
      return helper.getTrackedSelection(this._selectionId);
    }
  }
  function insertFinalNewLine(model) {
    const lineCount = model.getLineCount();
    const lastLine = model.getLineContent(lineCount);
    const lastLineIsEmptyOrWhitespace = lastNonWhitespaceIndex(lastLine) === -1;
    if (!lineCount || lastLineIsEmptyOrWhitespace) {
      return;
    }
    return EditOperation.insert(new Position$1(lineCount, model.getLineMaxColumn(lineCount)), model.getEOL());
  }
  const _InsertFinalNewLineAction = class _InsertFinalNewLineAction extends EditorAction {
    constructor() {
      super({
        id: _InsertFinalNewLineAction.ID,
        label: localize2(1242, "Insert Final New Line"),
        precondition: EditorContextKeys.writable
      });
    }
    run(_accessor, editor2, args) {
      const selection = editor2.getSelection();
      if (selection === null) {
        return;
      }
      const command = new InsertFinalNewLineCommand(selection);
      editor2.pushUndoStop();
      editor2.executeCommands(this.id, [command]);
      editor2.pushUndoStop();
    }
  };
  _InsertFinalNewLineAction.ID = "editor.action.insertFinalNewLine";
  let InsertFinalNewLineAction = _InsertFinalNewLineAction;
  registerEditorAction(InsertFinalNewLineAction);
  class ExpandLineSelectionAction extends EditorAction {
    constructor() {
      super({
        id: "expandLineSelection",
        label: localize2(1243, "Expand Line Selection"),
        precondition: void 0,
        kbOpts: {
          weight: 0,
          kbExpr: EditorContextKeys.textInputFocus,
          primary: 2048 | 42
          /* KeyCode.KeyL */
        }
      });
    }
    run(_accessor, editor2, args) {
      args = args || {};
      if (!editor2.hasModel()) {
        return;
      }
      const viewModel = editor2._getViewModel();
      viewModel.model.pushStackElement();
      viewModel.setCursorStates(args.source, 3, CursorMoveCommands.expandLineSelection(viewModel, viewModel.getCursorStates()));
      viewModel.revealAllCursors(args.source, true);
    }
  }
  registerEditorAction(ExpandLineSelectionAction);
  var __decorate$Z = 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$Y = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  var LinkedEditingContribution_1;
  const CONTEXT_ONTYPE_RENAME_INPUT_VISIBLE = new RawContextKey("LinkedEditingInputVisible", false);
  const DECORATION_CLASS_NAME = "linked-editing-decoration";
  let LinkedEditingContribution = (_ra = class extends Disposable {
    static get(editor2) {
      return editor2.getContribution(LinkedEditingContribution_1.ID);
    }
    constructor(editor2, contextKeyService, languageFeaturesService, languageConfigurationService, languageFeatureDebounceService) {
      super();
      this.languageConfigurationService = languageConfigurationService;
      this._syncRangesToken = 0;
      this._localToDispose = this._register(new DisposableStore());
      this._editor = editor2;
      this._providers = languageFeaturesService.linkedEditingRangeProvider;
      this._enabled = false;
      this._visibleContextKey = CONTEXT_ONTYPE_RENAME_INPUT_VISIBLE.bindTo(contextKeyService);
      this._debounceInformation = languageFeatureDebounceService.for(this._providers, "Linked Editing", { max: 200 });
      this._currentDecorations = this._editor.createDecorationsCollection();
      this._languageWordPattern = null;
      this._currentWordPattern = null;
      this._ignoreChangeEvent = false;
      this._localToDispose = this._register(new DisposableStore());
      this._rangeUpdateTriggerPromise = null;
      this._rangeSyncTriggerPromise = null;
      this._currentRequestCts = null;
      this._currentRequestPosition = null;
      this._currentRequestModelVersion = null;
      this._register(this._editor.onDidChangeModel(() => this.reinitialize(true)));
      this._register(this._editor.onDidChangeConfiguration((e) => {
        if (e.hasChanged(
          78
          /* EditorOption.linkedEditing */
        ) || e.hasChanged(
          106
          /* EditorOption.renameOnType */
        )) {
          this.reinitialize(false);
        }
      }));
      this._register(this._providers.onDidChange(() => this.reinitialize(false)));
      this._register(this._editor.onDidChangeModelLanguage(() => this.reinitialize(true)));
      this.reinitialize(true);
    }
    reinitialize(forceRefresh) {
      const model = this._editor.getModel();
      const isEnabled = model !== null && (this._editor.getOption(
        78
        /* EditorOption.linkedEditing */
      ) || this._editor.getOption(
        106
        /* EditorOption.renameOnType */
      )) && this._providers.has(model);
      if (isEnabled === this._enabled && !forceRefresh) {
        return;
      }
      this._enabled = isEnabled;
      this.clearRanges();
      this._localToDispose.clear();
      if (!isEnabled || model === null) {
        return;
      }
      this._localToDispose.add(Event.runAndSubscribe(model.onDidChangeLanguageConfiguration, () => {
        this._languageWordPattern = this.languageConfigurationService.getLanguageConfiguration(model.getLanguageId()).getWordDefinition();
      }));
      const rangeUpdateScheduler = new Delayer(this._debounceInformation.get(model));
      const triggerRangeUpdate = () => {
        this._rangeUpdateTriggerPromise = rangeUpdateScheduler.trigger(() => this.updateRanges(), this._debounceDuration ?? this._debounceInformation.get(model));
      };
      const rangeSyncScheduler = new Delayer(0);
      const triggerRangeSync = (token) => {
        this._rangeSyncTriggerPromise = rangeSyncScheduler.trigger(() => this._syncRanges(token));
      };
      this._localToDispose.add(this._editor.onDidChangeCursorPosition(() => {
        triggerRangeUpdate();
      }));
      this._localToDispose.add(this._editor.onDidChangeModelContent((e) => {
        if (!this._ignoreChangeEvent) {
          if (this._currentDecorations.length > 0) {
            const referenceRange = this._currentDecorations.getRange(0);
            if (referenceRange && e.changes.every((c) => referenceRange.intersectRanges(c.range))) {
              triggerRangeSync(this._syncRangesToken);
              return;
            }
          }
        }
        triggerRangeUpdate();
      }));
      this._localToDispose.add({
        dispose: () => {
          rangeUpdateScheduler.dispose();
          rangeSyncScheduler.dispose();
        }
      });
      this.updateRanges();
    }
    _syncRanges(token) {
      if (!this._editor.hasModel() || token !== this._syncRangesToken || this._currentDecorations.length === 0) {
        return;
      }
      const model = this._editor.getModel();
      const referenceRange = this._currentDecorations.getRange(0);
      if (!referenceRange || referenceRange.startLineNumber !== referenceRange.endLineNumber) {
        return this.clearRanges();
      }
      const referenceValue = model.getValueInRange(referenceRange);
      if (this._currentWordPattern) {
        const match2 = referenceValue.match(this._currentWordPattern);
        const matchLength = match2 ? match2[0].length : 0;
        if (matchLength !== referenceValue.length) {
          return this.clearRanges();
        }
      }
      const edits = [];
      for (let i2 = 1, len = this._currentDecorations.length; i2 < len; i2++) {
        const mirrorRange = this._currentDecorations.getRange(i2);
        if (!mirrorRange) {
          continue;
        }
        if (mirrorRange.startLineNumber !== mirrorRange.endLineNumber) {
          edits.push({
            range: mirrorRange,
            text: referenceValue
          });
        } else {
          let oldValue = model.getValueInRange(mirrorRange);
          let newValue = referenceValue;
          let rangeStartColumn = mirrorRange.startColumn;
          let rangeEndColumn = mirrorRange.endColumn;
          const commonPrefixLength$1 = commonPrefixLength(oldValue, newValue);
          rangeStartColumn += commonPrefixLength$1;
          oldValue = oldValue.substr(commonPrefixLength$1);
          newValue = newValue.substr(commonPrefixLength$1);
          const commonSuffixLength$1 = commonSuffixLength(oldValue, newValue);
          rangeEndColumn -= commonSuffixLength$1;
          oldValue = oldValue.substr(0, oldValue.length - commonSuffixLength$1);
          newValue = newValue.substr(0, newValue.length - commonSuffixLength$1);
          if (rangeStartColumn !== rangeEndColumn || newValue.length !== 0) {
            edits.push({
              range: new Range$2(mirrorRange.startLineNumber, rangeStartColumn, mirrorRange.endLineNumber, rangeEndColumn),
              text: newValue
            });
          }
        }
      }
      if (edits.length === 0) {
        return;
      }
      try {
        this._editor.popUndoStop();
        this._ignoreChangeEvent = true;
        const prevEditOperationType = this._editor._getViewModel().getPrevEditOperationType();
        this._editor.executeEdits("linkedEditing", edits);
        this._editor._getViewModel().setPrevEditOperationType(prevEditOperationType);
      } finally {
        this._ignoreChangeEvent = false;
      }
    }
    dispose() {
      this.clearRanges();
      super.dispose();
    }
    clearRanges() {
      this._visibleContextKey.set(false);
      this._currentDecorations.clear();
      if (this._currentRequestCts) {
        this._currentRequestCts.cancel();
        this._currentRequestCts = null;
        this._currentRequestPosition = null;
      }
    }
    async updateRanges(force = false) {
      if (!this._editor.hasModel()) {
        this.clearRanges();
        return;
      }
      const position = this._editor.getPosition();
      if (!this._enabled && !force || this._editor.getSelections().length > 1) {
        this.clearRanges();
        return;
      }
      const model = this._editor.getModel();
      const modelVersionId = model.getVersionId();
      if (this._currentRequestPosition && this._currentRequestModelVersion === modelVersionId) {
        if (position.equals(this._currentRequestPosition)) {
          return;
        }
        if (this._currentDecorations.length > 0) {
          const range2 = this._currentDecorations.getRange(0);
          if (range2 && range2.containsPosition(position)) {
            return;
          }
        }
      }
      if (!this._currentRequestPosition?.equals(position)) {
        const currentRange = this._currentDecorations.getRange(0);
        if (!currentRange?.containsPosition(position)) {
          this.clearRanges();
        }
      }
      this._currentRequestPosition = position;
      this._currentRequestModelVersion = modelVersionId;
      const currentRequestCts = this._currentRequestCts = new CancellationTokenSource$1();
      try {
        const sw = new StopWatch(false);
        const response = await getLinkedEditingRanges(this._providers, model, position, currentRequestCts.token);
        this._debounceInformation.update(model, sw.elapsed());
        if (currentRequestCts !== this._currentRequestCts) {
          return;
        }
        this._currentRequestCts = null;
        if (modelVersionId !== model.getVersionId()) {
          return;
        }
        let ranges = [];
        if (response?.ranges) {
          ranges = response.ranges;
        }
        this._currentWordPattern = response?.wordPattern || this._languageWordPattern;
        let foundReferenceRange = false;
        for (let i2 = 0, len = ranges.length; i2 < len; i2++) {
          if (Range$2.containsPosition(ranges[i2], position)) {
            foundReferenceRange = true;
            if (i2 !== 0) {
              const referenceRange = ranges[i2];
              ranges.splice(i2, 1);
              ranges.unshift(referenceRange);
            }
            break;
          }
        }
        if (!foundReferenceRange) {
          this.clearRanges();
          return;
        }
        const decorations = ranges.map((range2) => ({ range: range2, options: LinkedEditingContribution_1.DECORATION }));
        this._visibleContextKey.set(true);
        this._currentDecorations.set(decorations);
        this._syncRangesToken++;
      } catch (err) {
        if (!isCancellationError(err)) {
          onUnexpectedError(err);
        }
        if (this._currentRequestCts === currentRequestCts || !this._currentRequestCts) {
          this.clearRanges();
        }
      }
    }
  }, LinkedEditingContribution_1 = _ra, _ra.ID = "editor.contrib.linkedEditing", _ra.DECORATION = ModelDecorationOptions.register({
    description: "linked-editing",
    stickiness: 0,
    className: DECORATION_CLASS_NAME
  }), _ra);
  LinkedEditingContribution = LinkedEditingContribution_1 = __decorate$Z([
    __param$Y(1, IContextKeyService),
    __param$Y(2, ILanguageFeaturesService),
    __param$Y(3, ILanguageConfigurationService),
    __param$Y(4, ILanguageFeatureDebounceService)
  ], LinkedEditingContribution);
  class LinkedEditingAction extends EditorAction {
    constructor() {
      super({
        id: "editor.action.linkedEditing",
        label: localize2(1276, "Start Linked Editing"),
        precondition: ContextKeyExpr.and(EditorContextKeys.writable, EditorContextKeys.hasRenameProvider),
        kbOpts: {
          kbExpr: EditorContextKeys.editorTextFocus,
          primary: 2048 | 1024 | 60,
          weight: 100
          /* KeybindingWeight.EditorContrib */
        }
      });
    }
    runCommand(accessor, args) {
      const editorService = accessor.get(ICodeEditorService);
      const [uri, pos] = Array.isArray(args) && args || [void 0, void 0];
      if (URI.isUri(uri) && Position$1.isIPosition(pos)) {
        return editorService.openCodeEditor({ resource: uri }, editorService.getActiveCodeEditor()).then((editor2) => {
          if (!editor2) {
            return;
          }
          editor2.setPosition(pos);
          editor2.invokeWithinContext((accessor2) => {
            this.reportTelemetry(accessor2, editor2);
            return this.run(accessor2, editor2);
          });
        }, onUnexpectedError);
      }
      return super.runCommand(accessor, args);
    }
    run(_accessor, editor2) {
      const controller = LinkedEditingContribution.get(editor2);
      if (controller) {
        return Promise.resolve(controller.updateRanges(true));
      }
      return Promise.resolve();
    }
  }
  const LinkedEditingCommand = EditorCommand.bindToContribution(LinkedEditingContribution.get);
  registerEditorCommand(new LinkedEditingCommand({
    id: "cancelLinkedEditingInput",
    precondition: CONTEXT_ONTYPE_RENAME_INPUT_VISIBLE,
    handler: (x) => x.clearRanges(),
    kbOpts: {
      kbExpr: EditorContextKeys.editorTextFocus,
      weight: 100 + 99,
      primary: 9,
      secondary: [
        1024 | 9
        /* KeyCode.Escape */
      ]
    }
  }));
  function getLinkedEditingRanges(providers, model, position, token) {
    const orderedByScore = providers.ordered(model);
    return first(orderedByScore.map((provider) => async () => {
      try {
        return await provider.provideLinkedEditingRanges(model, position, token);
      } catch (e) {
        onUnexpectedExternalError(e);
        return void 0;
      }
    }), (result) => !!result && isNonEmptyArray(result?.ranges));
  }
  registerColor("editor.linkedEditingBackground", { dark: Color.fromHex("#f00").transparent(0.3), light: Color.fromHex("#f00").transparent(0.3), hcDark: Color.fromHex("#f00").transparent(0.3), hcLight: Color.white }, localize(1275, "Background color when the editor auto renames on type."));
  registerModelAndPositionCommand("_executeLinkedEditingProvider", (_accessor, model, position) => {
    const { linkedEditingRangeProvider } = _accessor.get(ILanguageFeaturesService);
    return getLinkedEditingRanges(linkedEditingRangeProvider, model, position, CancellationToken.None);
  });
  registerEditorContribution(
    LinkedEditingContribution.ID,
    LinkedEditingContribution,
    1
    /* EditorContributionInstantiation.AfterFirstRender */
  );
  registerEditorAction(LinkedEditingAction);
  let Link$1 = class Link {
    constructor(link2, provider) {
      this._link = link2;
      this._provider = provider;
    }
    toJSON() {
      return {
        range: this.range,
        url: this.url,
        tooltip: this.tooltip
      };
    }
    get range() {
      return this._link.range;
    }
    get url() {
      return this._link.url;
    }
    get tooltip() {
      return this._link.tooltip;
    }
    async resolve(token) {
      if (this._link.url) {
        return this._link.url;
      }
      if (typeof this._provider.resolveLink === "function") {
        return Promise.resolve(this._provider.resolveLink(this._link, token)).then((value) => {
          this._link = value || this._link;
          if (this._link.url) {
            return this.resolve(token);
          }
          return Promise.reject(new Error("missing"));
        });
      }
      return Promise.reject(new Error("missing"));
    }
  };
  const _LinksList = class _LinksList {
    constructor(tuples) {
      this._disposables = new DisposableStore();
      let links = [];
      for (const [list2, provider] of tuples) {
        const newLinks = list2.links.map((link2) => new Link$1(link2, provider));
        links = _LinksList._union(links, newLinks);
        if (isDisposable(list2)) {
          this._disposables ??= new DisposableStore();
          this._disposables.add(list2);
        }
      }
      this.links = links;
    }
    dispose() {
      this._disposables?.dispose();
      this.links.length = 0;
    }
    static _union(oldLinks, newLinks) {
      const result = [];
      let oldIndex;
      let oldLen;
      let newIndex;
      let newLen;
      for (oldIndex = 0, newIndex = 0, oldLen = oldLinks.length, newLen = newLinks.length; oldIndex < oldLen && newIndex < newLen; ) {
        const oldLink = oldLinks[oldIndex];
        const newLink = newLinks[newIndex];
        if (Range$2.areIntersectingOrTouching(oldLink.range, newLink.range)) {
          oldIndex++;
          continue;
        }
        const comparisonResult = Range$2.compareRangesUsingStarts(oldLink.range, newLink.range);
        if (comparisonResult < 0) {
          result.push(oldLink);
          oldIndex++;
        } else {
          result.push(newLink);
          newIndex++;
        }
      }
      for (; oldIndex < oldLen; oldIndex++) {
        result.push(oldLinks[oldIndex]);
      }
      for (; newIndex < newLen; newIndex++) {
        result.push(newLinks[newIndex]);
      }
      return result;
    }
  };
  _LinksList.Empty = new _LinksList([]);
  let LinksList = _LinksList;
  async function getLinks(providers, model, token) {
    const lists = [];
    const promises = providers.ordered(model).reverse().map(async (provider, i2) => {
      try {
        const result = await provider.provideLinks(model, token);
        if (result) {
          lists[i2] = [result, provider];
        }
      } catch (err) {
        onUnexpectedExternalError(err);
      }
    });
    await Promise.all(promises);
    let res = new LinksList(coalesce(lists));
    if (token.isCancellationRequested) {
      res.dispose();
      res = LinksList.Empty;
    }
    return res;
  }
  CommandsRegistry.registerCommand("_executeLinkProvider", async (accessor, ...args) => {
    let [uri, resolveCount] = args;
    assertType(uri instanceof URI);
    if (typeof resolveCount !== "number") {
      resolveCount = 0;
    }
    const { linkProvider } = accessor.get(ILanguageFeaturesService);
    const model = accessor.get(IModelService).getModel(uri);
    if (!model) {
      return [];
    }
    const list2 = await getLinks(linkProvider, model, CancellationToken.None);
    if (!list2) {
      return [];
    }
    for (let i2 = 0; i2 < Math.min(resolveCount, list2.links.length); i2++) {
      await list2.links[i2].resolve(CancellationToken.None);
    }
    const result = list2.links.slice(0);
    list2.dispose();
    return result;
  });
  var __decorate$Y = 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$X = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  var LinkDetector_1;
  let LinkDetector = (_sa = class extends Disposable {
    static get(editor2) {
      return editor2.getContribution(LinkDetector_1.ID);
    }
    constructor(editor2, openerService, notificationService, languageFeaturesService, languageFeatureDebounceService) {
      super();
      this.editor = editor2;
      this.openerService = openerService;
      this.notificationService = notificationService;
      this.languageFeaturesService = languageFeaturesService;
      this.providers = this.languageFeaturesService.linkProvider;
      this.debounceInformation = languageFeatureDebounceService.for(this.providers, "Links", { min: 1e3, max: 4e3 });
      this.computeLinks = this._register(new RunOnceScheduler(() => this.computeLinksNow(), 1e3));
      this.computePromise = null;
      this.activeLinksList = null;
      this.currentOccurrences = {};
      this.activeLinkDecorationId = null;
      const clickLinkGesture = this._register(new ClickLinkGesture(editor2));
      this._register(clickLinkGesture.onMouseMoveOrRelevantKeyDown(([mouseEvent, keyboardEvent]) => {
        this._onEditorMouseMove(mouseEvent, keyboardEvent);
      }));
      this._register(clickLinkGesture.onExecute((e) => {
        this.onEditorMouseUp(e);
      }));
      this._register(clickLinkGesture.onCancel((e) => {
        this.cleanUpActiveLinkDecoration();
      }));
      this._register(editor2.onDidChangeConfiguration((e) => {
        if (!e.hasChanged(
          79
          /* EditorOption.links */
        )) {
          return;
        }
        this.updateDecorations([]);
        this.stop();
        this.computeLinks.schedule(0);
      }));
      this._register(editor2.onDidChangeModelContent((e) => {
        if (!this.editor.hasModel()) {
          return;
        }
        this.computeLinks.schedule(this.debounceInformation.get(this.editor.getModel()));
      }));
      this._register(editor2.onDidChangeModel((e) => {
        this.currentOccurrences = {};
        this.activeLinkDecorationId = null;
        this.stop();
        this.computeLinks.schedule(0);
      }));
      this._register(editor2.onDidChangeModelLanguage((e) => {
        this.stop();
        this.computeLinks.schedule(0);
      }));
      this._register(this.providers.onDidChange((e) => {
        this.stop();
        this.computeLinks.schedule(0);
      }));
      this.computeLinks.schedule(0);
    }
    async computeLinksNow() {
      if (!this.editor.hasModel() || !this.editor.getOption(
        79
        /* EditorOption.links */
      )) {
        return;
      }
      const model = this.editor.getModel();
      if (model.isTooLargeForSyncing()) {
        return;
      }
      if (!this.providers.has(model)) {
        return;
      }
      if (this.activeLinksList) {
        this.activeLinksList.dispose();
        this.activeLinksList = null;
      }
      this.computePromise = createCancelablePromise((token) => getLinks(this.providers, model, token));
      try {
        const sw = new StopWatch(false);
        this.activeLinksList = await this.computePromise;
        this.debounceInformation.update(model, sw.elapsed());
        if (model.isDisposed()) {
          return;
        }
        this.updateDecorations(this.activeLinksList.links);
      } catch (err) {
        onUnexpectedError(err);
      } finally {
        this.computePromise = null;
      }
    }
    updateDecorations(links) {
      const useMetaKey = this.editor.getOption(
        86
        /* EditorOption.multiCursorModifier */
      ) === "altKey";
      const oldDecorations = [];
      const keys = Object.keys(this.currentOccurrences);
      for (const decorationId of keys) {
        const occurence = this.currentOccurrences[decorationId];
        oldDecorations.push(occurence.decorationId);
      }
      const newDecorations = [];
      if (links) {
        for (const link2 of links) {
          newDecorations.push(LinkOccurrence.decoration(link2, useMetaKey));
        }
      }
      this.editor.changeDecorations((changeAccessor) => {
        const decorations = changeAccessor.deltaDecorations(oldDecorations, newDecorations);
        this.currentOccurrences = {};
        this.activeLinkDecorationId = null;
        for (let i2 = 0, len = decorations.length; i2 < len; i2++) {
          const occurence = new LinkOccurrence(links[i2], decorations[i2]);
          this.currentOccurrences[occurence.decorationId] = occurence;
        }
      });
    }
    _onEditorMouseMove(mouseEvent, withKey) {
      const useMetaKey = this.editor.getOption(
        86
        /* EditorOption.multiCursorModifier */
      ) === "altKey";
      if (this.isEnabled(mouseEvent, withKey)) {
        this.cleanUpActiveLinkDecoration();
        const occurrence = this.getLinkOccurrence(mouseEvent.target.position);
        if (occurrence) {
          this.editor.changeDecorations((changeAccessor) => {
            occurrence.activate(changeAccessor, useMetaKey);
            this.activeLinkDecorationId = occurrence.decorationId;
          });
        }
      } else {
        this.cleanUpActiveLinkDecoration();
      }
    }
    cleanUpActiveLinkDecoration() {
      const useMetaKey = this.editor.getOption(
        86
        /* EditorOption.multiCursorModifier */
      ) === "altKey";
      if (this.activeLinkDecorationId) {
        const occurrence = this.currentOccurrences[this.activeLinkDecorationId];
        if (occurrence) {
          this.editor.changeDecorations((changeAccessor) => {
            occurrence.deactivate(changeAccessor, useMetaKey);
          });
        }
        this.activeLinkDecorationId = null;
      }
    }
    onEditorMouseUp(mouseEvent) {
      if (!this.isEnabled(mouseEvent)) {
        return;
      }
      const occurrence = this.getLinkOccurrence(mouseEvent.target.position);
      if (!occurrence) {
        return;
      }
      this.openLinkOccurrence(
        occurrence,
        mouseEvent.hasSideBySideModifier,
        true
        /* from user gesture */
      );
    }
    openLinkOccurrence(occurrence, openToSide, fromUserGesture = false) {
      if (!this.openerService) {
        return;
      }
      const { link: link2 } = occurrence;
      link2.resolve(CancellationToken.None).then((uri) => {
        if (typeof uri === "string" && this.editor.hasModel()) {
          const modelUri = this.editor.getModel().uri;
          if (modelUri.scheme === Schemas.file && uri.startsWith(`${Schemas.file}:`)) {
            const parsedUri = URI.parse(uri);
            if (parsedUri.scheme === Schemas.file) {
              const fsPath = originalFSPath(parsedUri);
              let relativePath2 = null;
              if (fsPath.startsWith("/./") || fsPath.startsWith("\\.\\")) {
                relativePath2 = `.${fsPath.substr(1)}`;
              } else if (fsPath.startsWith("//./") || fsPath.startsWith("\\\\.\\")) {
                relativePath2 = `.${fsPath.substr(2)}`;
              }
              if (relativePath2) {
                uri = joinPath(modelUri, relativePath2);
              }
            }
          }
        }
        return this.openerService.open(uri, { openToSide, fromUserGesture, allowContributedOpeners: true, allowCommands: true, fromWorkspace: true });
      }, (err) => {
        const messageOrError = err instanceof Error ? err.message : err;
        if (messageOrError === "invalid") {
          this.notificationService.warn(localize(1277, "Failed to open this link because it is not well-formed: {0}", link2.url.toString()));
        } else if (messageOrError === "missing") {
          this.notificationService.warn(localize(1278, "Failed to open this link because its target is missing."));
        } else {
          onUnexpectedError(err);
        }
      });
    }
    getLinkOccurrence(position) {
      if (!this.editor.hasModel() || !position) {
        return null;
      }
      const decorations = this.editor.getModel().getDecorationsInRange({
        startLineNumber: position.lineNumber,
        startColumn: position.column,
        endLineNumber: position.lineNumber,
        endColumn: position.column
      }, 0, true);
      for (const decoration2 of decorations) {
        const currentOccurrence = this.currentOccurrences[decoration2.id];
        if (currentOccurrence) {
          return currentOccurrence;
        }
      }
      return null;
    }
    isEnabled(mouseEvent, withKey) {
      return Boolean(mouseEvent.target.type === 6 && (mouseEvent.hasTriggerModifier || withKey && withKey.keyCodeIsTriggerKey || mouseEvent.isMiddleClick && mouseEvent.mouseMiddleClickAction === "openLink"));
    }
    stop() {
      this.computeLinks.cancel();
      if (this.activeLinksList) {
        this.activeLinksList?.dispose();
        this.activeLinksList = null;
      }
      if (this.computePromise) {
        this.computePromise.cancel();
        this.computePromise = null;
      }
    }
    dispose() {
      super.dispose();
      this.stop();
    }
  }, LinkDetector_1 = _sa, _sa.ID = "editor.linkDetector", _sa);
  LinkDetector = LinkDetector_1 = __decorate$Y([
    __param$X(1, IOpenerService),
    __param$X(2, INotificationService),
    __param$X(3, ILanguageFeaturesService),
    __param$X(4, ILanguageFeatureDebounceService)
  ], LinkDetector);
  const decoration$1 = {
    general: ModelDecorationOptions.register({
      description: "detected-link",
      stickiness: 1,
      collapseOnReplaceEdit: true,
      inlineClassName: "detected-link"
    }),
    active: ModelDecorationOptions.register({
      description: "detected-link-active",
      stickiness: 1,
      collapseOnReplaceEdit: true,
      inlineClassName: "detected-link-active"
    })
  };
  class LinkOccurrence {
    static decoration(link2, useMetaKey) {
      return {
        range: link2.range,
        options: LinkOccurrence._getOptions(link2, useMetaKey, false)
      };
    }
    static _getOptions(link2, useMetaKey, isActive) {
      const options = { ...isActive ? decoration$1.active : decoration$1.general };
      options.hoverMessage = getHoverMessage(link2, useMetaKey);
      return options;
    }
    constructor(link2, decorationId) {
      this.link = link2;
      this.decorationId = decorationId;
    }
    activate(changeAccessor, useMetaKey) {
      changeAccessor.changeDecorationOptions(this.decorationId, LinkOccurrence._getOptions(this.link, useMetaKey, true));
    }
    deactivate(changeAccessor, useMetaKey) {
      changeAccessor.changeDecorationOptions(this.decorationId, LinkOccurrence._getOptions(this.link, useMetaKey, false));
    }
  }
  function getHoverMessage(link2, useMetaKey) {
    const executeCmd = link2.url && /^command:/i.test(link2.url.toString());
    const label = link2.tooltip ? link2.tooltip : executeCmd ? localize(1279, "Execute command") : localize(1280, "Follow link");
    const kb = useMetaKey ? isMacintosh ? localize(1281, "cmd + click") : localize(1282, "ctrl + click") : isMacintosh ? localize(1283, "option + click") : localize(1284, "alt + click");
    if (link2.url) {
      let nativeLabel = "";
      if (/^command:/i.test(link2.url.toString())) {
        const match2 = link2.url.toString().match(/^command:([^?#]+)/);
        if (match2) {
          const commandId = match2[1];
          nativeLabel = localize(1285, "Execute command {0}", commandId);
        }
      }
      const hoverMessage = new MarkdownString("", true).appendLink(link2.url.toString(true).replace(/ /g, "%20"), label, nativeLabel).appendMarkdown(` (${kb})`);
      return hoverMessage;
    } else {
      return new MarkdownString().appendText(`${label} (${kb})`);
    }
  }
  class OpenLinkAction extends EditorAction {
    constructor() {
      super({
        id: "editor.action.openLink",
        label: localize2(1286, "Open Link"),
        precondition: void 0
      });
    }
    run(accessor, editor2) {
      const linkDetector = LinkDetector.get(editor2);
      if (!linkDetector) {
        return;
      }
      if (!editor2.hasModel()) {
        return;
      }
      const selections = editor2.getSelections();
      for (const sel of selections) {
        const link2 = linkDetector.getLinkOccurrence(sel.getEndPosition());
        if (link2) {
          linkDetector.openLinkOccurrence(link2, false);
        }
      }
    }
  }
  registerEditorContribution(
    LinkDetector.ID,
    LinkDetector,
    1
    /* EditorContributionInstantiation.AfterFirstRender */
  );
  registerEditorAction(OpenLinkAction);
  const _LongLinesHelper = class _LongLinesHelper extends Disposable {
    constructor(_editor) {
      super();
      this._editor = _editor;
      this._register(this._editor.onMouseDown((e) => {
        const stopRenderingLineAfter = this._editor.getOption(
          133
          /* EditorOption.stopRenderingLineAfter */
        );
        if (stopRenderingLineAfter >= 0 && e.target.type === 6 && e.target.position.column >= stopRenderingLineAfter) {
          this._editor.updateOptions({
            stopRenderingLineAfter: -1
          });
        }
      }));
    }
  };
  _LongLinesHelper.ID = "editor.contrib.longLinesHelper";
  let LongLinesHelper = _LongLinesHelper;
  registerEditorContribution(
    LongLinesHelper.ID,
    LongLinesHelper,
    2
    /* EditorContributionInstantiation.BeforeFirstInteraction */
  );
  const _MiddleScrollController = class _MiddleScrollController extends Disposable {
    constructor(_editor) {
      super();
      this._editor = _editor;
      const obsEditor = observableCodeEditor(this._editor);
      const scrollOnMiddleClick = obsEditor.getOption(
        171
        /* EditorOption.scrollOnMiddleClick */
      );
      this._register(autorun((reader) => {
        if (!scrollOnMiddleClick.read(reader)) {
          return;
        }
        const editorDomNode = obsEditor.domNode.read(reader);
        if (!editorDomNode) {
          return;
        }
        const scrollingSession = reader.store.add(disposableObservableValue("scrollingSession", void 0));
        reader.store.add(this._editor.onMouseDown((e) => {
          const session = scrollingSession.read(void 0);
          if (session) {
            scrollingSession.set(void 0, void 0);
            return;
          }
          if (!e.event.middleButton) {
            return;
          }
          e.event.stopPropagation();
          e.event.preventDefault();
          const store = new DisposableStore();
          const initialPos = new Point(e.event.posx, e.event.posy);
          const mousePos = observeWindowMousePos(getWindow(editorDomNode), initialPos, store);
          const mouseDeltaAfterThreshold = mousePos.map((v) => v.subtract(initialPos).withThreshold(5));
          const editorDomNodeRect = editorDomNode.getBoundingClientRect();
          const initialMousePosInEditor = new Point(initialPos.x - editorDomNodeRect.left, initialPos.y - editorDomNodeRect.top);
          scrollingSession.set({
            mouseDeltaAfterThreshold,
            initialMousePosInEditor,
            didScroll: false,
            dispose: () => store.dispose()
          }, void 0);
          store.add(this._editor.onMouseUp((e2) => {
            const session2 = scrollingSession.read(void 0);
            if (session2 && session2.didScroll) {
              scrollingSession.set(void 0, void 0);
            }
          }));
          store.add(this._editor.onKeyDown((e2) => {
            scrollingSession.set(void 0, void 0);
          }));
        }));
        reader.store.add(autorun((reader2) => {
          const session = scrollingSession.read(reader2);
          if (!session) {
            return;
          }
          let lastTime = Date.now();
          reader2.store.add(autorun((reader3) => {
            AnimationFrameScheduler.instance.invalidateOnNextAnimationFrame(reader3);
            const curTime = Date.now();
            const frameDurationMs = curTime - lastTime;
            lastTime = curTime;
            const mouseDelta = session.mouseDeltaAfterThreshold.read(void 0);
            const factor2 = frameDurationMs / 32;
            const scrollDelta = mouseDelta.scale(factor2);
            const scrollPos = new Point(this._editor.getScrollLeft(), this._editor.getScrollTop());
            this._editor.setScrollPosition(toScrollPosition(scrollPos.add(scrollDelta)));
            if (!scrollDelta.isZero()) {
              session.didScroll = true;
            }
          }));
          const directionAttr = derived((reader3) => {
            const delta = session.mouseDeltaAfterThreshold.read(reader3);
            let direction = "";
            direction += delta.y < 0 ? "n" : delta.y > 0 ? "s" : "";
            direction += delta.x < 0 ? "w" : delta.x > 0 ? "e" : "";
            return direction;
          });
          reader2.store.add(autorun((reader3) => {
            editorDomNode.setAttribute("data-scroll-direction", directionAttr.read(reader3));
          }));
        }));
        const dotDomElem = reader.store.add(n.div({
          class: ["scroll-editor-on-middle-click-dot", scrollingSession.map((session) => session ? "" : "hidden")],
          style: {
            left: scrollingSession.map((session) => session ? session.initialMousePosInEditor.x : 0),
            top: scrollingSession.map((session) => session ? session.initialMousePosInEditor.y : 0)
          }
        }).toDisposableLiveElement());
        reader.store.add(appendRemoveOnDispose(editorDomNode, dotDomElem.element));
        reader.store.add(autorun((reader2) => {
          const session = scrollingSession.read(reader2);
          editorDomNode.classList.toggle("scroll-editor-on-middle-click-editor", !!session);
        }));
      }));
    }
  };
  _MiddleScrollController.ID = "editor.contrib.middleScroll";
  let MiddleScrollController = _MiddleScrollController;
  function observeWindowMousePos(window2, initialPos, store) {
    const val = observableValue("pos", initialPos);
    store.add(addDisposableListener(window2, "mousemove", (e) => {
      val.set(new Point(e.pageX, e.pageY), void 0);
    }));
    return val;
  }
  function toScrollPosition(p) {
    return {
      scrollLeft: p.x,
      scrollTop: p.y
    };
  }
  registerEditorContribution(
    MiddleScrollController.ID,
    MiddleScrollController,
    2
    /* EditorContributionInstantiation.BeforeFirstInteraction */
  );
  const wordHighlightBackground = registerColor("editor.wordHighlightBackground", { dark: "#575757B8", light: "#57575740", hcDark: null, hcLight: null }, localize(1563, "Background color of a symbol during read-access, like reading a variable. The color must not be opaque so as not to hide underlying decorations."), true);
  registerColor("editor.wordHighlightStrongBackground", { dark: "#004972B8", light: "#0e639c40", hcDark: null, hcLight: null }, localize(1564, "Background color of a symbol during write-access, like writing to a variable. The color must not be opaque so as not to hide underlying decorations."), true);
  registerColor("editor.wordHighlightTextBackground", wordHighlightBackground, localize(1565, "Background color of a textual occurrence for a symbol. The color must not be opaque so as not to hide underlying decorations."), true);
  const wordHighlightBorder = registerColor("editor.wordHighlightBorder", { light: null, dark: null, hcDark: activeContrastBorder, hcLight: activeContrastBorder }, localize(1566, "Border color of a symbol during read-access, like reading a variable."));
  registerColor("editor.wordHighlightStrongBorder", { light: null, dark: null, hcDark: activeContrastBorder, hcLight: activeContrastBorder }, localize(1567, "Border color of a symbol during write-access, like writing to a variable."));
  registerColor("editor.wordHighlightTextBorder", wordHighlightBorder, localize(1568, "Border color of a textual occurrence for a symbol."));
  const overviewRulerWordHighlightForeground = registerColor("editorOverviewRuler.wordHighlightForeground", "#A0A0A0CC", localize(1569, "Overview ruler marker color for symbol highlights. The color must not be opaque so as not to hide underlying decorations."), true);
  const overviewRulerWordHighlightStrongForeground = registerColor("editorOverviewRuler.wordHighlightStrongForeground", "#C0A0C0CC", localize(1570, "Overview ruler marker color for write-access symbol highlights. The color must not be opaque so as not to hide underlying decorations."), true);
  const overviewRulerWordHighlightTextForeground = registerColor("editorOverviewRuler.wordHighlightTextForeground", overviewRulerSelectionHighlightForeground, localize(1571, "Overview ruler marker color of a textual occurrence for a symbol. The color must not be opaque so as not to hide underlying decorations."), true);
  const _WRITE_OPTIONS = ModelDecorationOptions.register({
    description: "word-highlight-strong",
    stickiness: 1,
    className: "wordHighlightStrong",
    overviewRuler: {
      color: themeColorFromId(overviewRulerWordHighlightStrongForeground),
      position: OverviewRulerLane$1.Center
    },
    minimap: {
      color: themeColorFromId(minimapSelectionOccurrenceHighlight),
      position: 1
      /* MinimapPosition.Inline */
    }
  });
  const _TEXT_OPTIONS = ModelDecorationOptions.register({
    description: "word-highlight-text",
    stickiness: 1,
    className: "wordHighlightText",
    overviewRuler: {
      color: themeColorFromId(overviewRulerWordHighlightTextForeground),
      position: OverviewRulerLane$1.Center
    },
    minimap: {
      color: themeColorFromId(minimapSelectionOccurrenceHighlight),
      position: 1
      /* MinimapPosition.Inline */
    }
  });
  const _SELECTION_HIGHLIGHT_OPTIONS = ModelDecorationOptions.register({
    description: "selection-highlight-overview",
    stickiness: 1,
    className: "selectionHighlight",
    overviewRuler: {
      color: themeColorFromId(overviewRulerSelectionHighlightForeground),
      position: OverviewRulerLane$1.Center
    },
    minimap: {
      color: themeColorFromId(minimapSelectionOccurrenceHighlight),
      position: 1
      /* MinimapPosition.Inline */
    }
  });
  const _SELECTION_HIGHLIGHT_OPTIONS_NO_OVERVIEW = ModelDecorationOptions.register({
    description: "selection-highlight",
    stickiness: 1,
    className: "selectionHighlight"
  });
  const _REGULAR_OPTIONS = ModelDecorationOptions.register({
    description: "word-highlight",
    stickiness: 1,
    className: "wordHighlight",
    overviewRuler: {
      color: themeColorFromId(overviewRulerWordHighlightForeground),
      position: OverviewRulerLane$1.Center
    },
    minimap: {
      color: themeColorFromId(minimapSelectionOccurrenceHighlight),
      position: 1
      /* MinimapPosition.Inline */
    }
  });
  function getHighlightDecorationOptions(kind) {
    if (kind === DocumentHighlightKind$1.Write) {
      return _WRITE_OPTIONS;
    } else if (kind === DocumentHighlightKind$1.Text) {
      return _TEXT_OPTIONS;
    } else {
      return _REGULAR_OPTIONS;
    }
  }
  function getSelectionHighlightDecorationOptions(hasSemanticHighlights) {
    return hasSemanticHighlights ? _SELECTION_HIGHLIGHT_OPTIONS_NO_OVERVIEW : _SELECTION_HIGHLIGHT_OPTIONS;
  }
  registerThemingParticipant((theme, collector) => {
    const selectionHighlight = theme.getColor(editorSelectionHighlight);
    if (selectionHighlight) {
      collector.addRule(`.monaco-editor .selectionHighlight { background-color: ${selectionHighlight.transparent(0.5)}; }`);
    }
  });
  var __decorate$X = 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$W = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  var SelectionHighlighter_1;
  function announceCursorChange(previousCursorState, cursorState) {
    const cursorDiff = cursorState.filter((cs) => !previousCursorState.find((pcs) => pcs.equals(cs)));
    if (cursorDiff.length >= 1) {
      const cursorPositions = cursorDiff.map((cs) => `line ${cs.viewState.position.lineNumber} column ${cs.viewState.position.column}`).join(", ");
      const msg = cursorDiff.length === 1 ? localize(1288, "Cursor added: {0}", cursorPositions) : localize(1289, "Cursors added: {0}", cursorPositions);
      status(msg);
    }
  }
  class InsertCursorAbove extends EditorAction {
    constructor() {
      super({
        id: "editor.action.insertCursorAbove",
        label: localize2(1298, "Add Cursor Above"),
        precondition: void 0,
        kbOpts: {
          kbExpr: EditorContextKeys.editorTextFocus,
          primary: 2048 | 512 | 16,
          linux: {
            primary: 1024 | 512 | 16,
            secondary: [
              2048 | 1024 | 16
              /* KeyCode.UpArrow */
            ]
          },
          weight: 100
          /* KeybindingWeight.EditorContrib */
        },
        menuOpts: {
          menuId: MenuId.MenubarSelectionMenu,
          group: "3_multi",
          title: localize(1290, "&&Add Cursor Above"),
          order: 2
        }
      });
    }
    run(accessor, editor2, args) {
      if (!editor2.hasModel()) {
        return;
      }
      let useLogicalLine = true;
      if (args && args.logicalLine === false) {
        useLogicalLine = false;
      }
      const viewModel = editor2._getViewModel();
      if (viewModel.cursorConfig.readOnly) {
        return;
      }
      viewModel.model.pushStackElement();
      const previousCursorState = viewModel.getCursorStates();
      viewModel.setCursorStates(args.source, 3, CursorMoveCommands.addCursorUp(viewModel, previousCursorState, useLogicalLine));
      viewModel.revealTopMostCursor(args.source);
      announceCursorChange(previousCursorState, viewModel.getCursorStates());
    }
  }
  class InsertCursorBelow extends EditorAction {
    constructor() {
      super({
        id: "editor.action.insertCursorBelow",
        label: localize2(1299, "Add Cursor Below"),
        precondition: void 0,
        kbOpts: {
          kbExpr: EditorContextKeys.editorTextFocus,
          primary: 2048 | 512 | 18,
          linux: {
            primary: 1024 | 512 | 18,
            secondary: [
              2048 | 1024 | 18
              /* KeyCode.DownArrow */
            ]
          },
          weight: 100
          /* KeybindingWeight.EditorContrib */
        },
        menuOpts: {
          menuId: MenuId.MenubarSelectionMenu,
          group: "3_multi",
          title: localize(1291, "A&&dd Cursor Below"),
          order: 3
        }
      });
    }
    run(accessor, editor2, args) {
      if (!editor2.hasModel()) {
        return;
      }
      let useLogicalLine = true;
      if (args && args.logicalLine === false) {
        useLogicalLine = false;
      }
      const viewModel = editor2._getViewModel();
      if (viewModel.cursorConfig.readOnly) {
        return;
      }
      viewModel.model.pushStackElement();
      const previousCursorState = viewModel.getCursorStates();
      viewModel.setCursorStates(args.source, 3, CursorMoveCommands.addCursorDown(viewModel, previousCursorState, useLogicalLine));
      viewModel.revealBottomMostCursor(args.source);
      announceCursorChange(previousCursorState, viewModel.getCursorStates());
    }
  }
  class InsertCursorAtEndOfEachLineSelected extends EditorAction {
    constructor() {
      super({
        id: "editor.action.insertCursorAtEndOfEachLineSelected",
        label: localize2(1300, "Add Cursors to Line Ends"),
        precondition: void 0,
        kbOpts: {
          kbExpr: EditorContextKeys.editorTextFocus,
          primary: 1024 | 512 | 39,
          weight: 100
          /* KeybindingWeight.EditorContrib */
        },
        menuOpts: {
          menuId: MenuId.MenubarSelectionMenu,
          group: "3_multi",
          title: localize(1292, "Add C&&ursors to Line Ends"),
          order: 4
        }
      });
    }
    getCursorsForSelection(selection, model, result) {
      if (selection.isEmpty()) {
        return;
      }
      for (let i2 = selection.startLineNumber; i2 < selection.endLineNumber; i2++) {
        const currentLineMaxColumn = model.getLineMaxColumn(i2);
        result.push(new Selection$1(i2, currentLineMaxColumn, i2, currentLineMaxColumn));
      }
      if (selection.endColumn > 1) {
        result.push(new Selection$1(selection.endLineNumber, selection.endColumn, selection.endLineNumber, selection.endColumn));
      }
    }
    run(accessor, editor2) {
      if (!editor2.hasModel()) {
        return;
      }
      const model = editor2.getModel();
      const selections = editor2.getSelections();
      const viewModel = editor2._getViewModel();
      const previousCursorState = viewModel.getCursorStates();
      const newSelections = [];
      selections.forEach((sel) => this.getCursorsForSelection(sel, model, newSelections));
      if (newSelections.length > 0) {
        editor2.setSelections(newSelections);
      }
      announceCursorChange(previousCursorState, viewModel.getCursorStates());
    }
  }
  class InsertCursorAtEndOfLineSelected extends EditorAction {
    constructor() {
      super({
        id: "editor.action.addCursorsToBottom",
        label: localize2(1301, "Add Cursors to Bottom"),
        precondition: void 0
      });
    }
    run(accessor, editor2) {
      if (!editor2.hasModel()) {
        return;
      }
      const selections = editor2.getSelections();
      const lineCount = editor2.getModel().getLineCount();
      const newSelections = [];
      for (let i2 = selections[0].startLineNumber; i2 <= lineCount; i2++) {
        newSelections.push(new Selection$1(i2, selections[0].startColumn, i2, selections[0].endColumn));
      }
      const viewModel = editor2._getViewModel();
      const previousCursorState = viewModel.getCursorStates();
      if (newSelections.length > 0) {
        editor2.setSelections(newSelections);
      }
      announceCursorChange(previousCursorState, viewModel.getCursorStates());
    }
  }
  class InsertCursorAtTopOfLineSelected extends EditorAction {
    constructor() {
      super({
        id: "editor.action.addCursorsToTop",
        label: localize2(1302, "Add Cursors to Top"),
        precondition: void 0
      });
    }
    run(accessor, editor2) {
      if (!editor2.hasModel()) {
        return;
      }
      const selections = editor2.getSelections();
      const newSelections = [];
      for (let i2 = selections[0].startLineNumber; i2 >= 1; i2--) {
        newSelections.push(new Selection$1(i2, selections[0].startColumn, i2, selections[0].endColumn));
      }
      const viewModel = editor2._getViewModel();
      const previousCursorState = viewModel.getCursorStates();
      if (newSelections.length > 0) {
        editor2.setSelections(newSelections);
      }
      announceCursorChange(previousCursorState, viewModel.getCursorStates());
    }
  }
  class MultiCursorSessionResult {
    constructor(selections, revealRange, revealScrollType) {
      this.selections = selections;
      this.revealRange = revealRange;
      this.revealScrollType = revealScrollType;
    }
  }
  class MultiCursorSession {
    static create(editor2, findController) {
      if (!editor2.hasModel()) {
        return null;
      }
      const findState = findController.getState();
      if (!editor2.hasTextFocus() && findState.isRevealed && findState.searchString.length > 0) {
        return new MultiCursorSession(editor2, findController, false, findState.searchString, findState.wholeWord, findState.matchCase, null);
      }
      let isDisconnectedFromFindController = false;
      let wholeWord;
      let matchCase;
      const selections = editor2.getSelections();
      if (selections.length === 1 && selections[0].isEmpty()) {
        isDisconnectedFromFindController = true;
        wholeWord = true;
        matchCase = true;
      } else {
        wholeWord = findState.wholeWord;
        matchCase = findState.matchCase;
      }
      const s = editor2.getSelection();
      let searchText;
      let currentMatch = null;
      if (s.isEmpty()) {
        const word = editor2.getConfiguredWordAtPosition(s.getStartPosition());
        if (!word) {
          return null;
        }
        searchText = word.word;
        currentMatch = new Selection$1(s.startLineNumber, word.startColumn, s.startLineNumber, word.endColumn);
      } else {
        searchText = editor2.getModel().getValueInRange(s).replace(/\r\n/g, "\n");
      }
      return new MultiCursorSession(editor2, findController, isDisconnectedFromFindController, searchText, wholeWord, matchCase, currentMatch);
    }
    constructor(_editor, findController, isDisconnectedFromFindController, searchText, wholeWord, matchCase, currentMatch) {
      this._editor = _editor;
      this.findController = findController;
      this.isDisconnectedFromFindController = isDisconnectedFromFindController;
      this.searchText = searchText;
      this.wholeWord = wholeWord;
      this.matchCase = matchCase;
      this.currentMatch = currentMatch;
    }
    addSelectionToNextFindMatch() {
      if (!this._editor.hasModel()) {
        return null;
      }
      const nextMatch = this._getNextMatch();
      if (!nextMatch) {
        return null;
      }
      const allSelections = this._editor.getSelections();
      return new MultiCursorSessionResult(
        allSelections.concat(nextMatch),
        nextMatch,
        0
        /* ScrollType.Smooth */
      );
    }
    moveSelectionToNextFindMatch() {
      if (!this._editor.hasModel()) {
        return null;
      }
      const nextMatch = this._getNextMatch();
      if (!nextMatch) {
        return null;
      }
      const allSelections = this._editor.getSelections();
      return new MultiCursorSessionResult(
        allSelections.slice(0, allSelections.length - 1).concat(nextMatch),
        nextMatch,
        0
        /* ScrollType.Smooth */
      );
    }
    _getNextMatch() {
      if (!this._editor.hasModel()) {
        return null;
      }
      if (this.currentMatch) {
        const result = this.currentMatch;
        this.currentMatch = null;
        return result;
      }
      this.findController.highlightFindOptions();
      const allSelections = this._editor.getSelections();
      const lastAddedSelection = allSelections[allSelections.length - 1];
      const nextMatch = this._editor.getModel().findNextMatch(this.searchText, lastAddedSelection.getEndPosition(), false, this.matchCase, this.wholeWord ? this._editor.getOption(
        148
        /* EditorOption.wordSeparators */
      ) : null, false);
      if (!nextMatch) {
        return null;
      }
      return new Selection$1(nextMatch.range.startLineNumber, nextMatch.range.startColumn, nextMatch.range.endLineNumber, nextMatch.range.endColumn);
    }
    addSelectionToPreviousFindMatch() {
      if (!this._editor.hasModel()) {
        return null;
      }
      const previousMatch = this._getPreviousMatch();
      if (!previousMatch) {
        return null;
      }
      const allSelections = this._editor.getSelections();
      return new MultiCursorSessionResult(
        allSelections.concat(previousMatch),
        previousMatch,
        0
        /* ScrollType.Smooth */
      );
    }
    moveSelectionToPreviousFindMatch() {
      if (!this._editor.hasModel()) {
        return null;
      }
      const previousMatch = this._getPreviousMatch();
      if (!previousMatch) {
        return null;
      }
      const allSelections = this._editor.getSelections();
      return new MultiCursorSessionResult(
        allSelections.slice(0, allSelections.length - 1).concat(previousMatch),
        previousMatch,
        0
        /* ScrollType.Smooth */
      );
    }
    _getPreviousMatch() {
      if (!this._editor.hasModel()) {
        return null;
      }
      if (this.currentMatch) {
        const result = this.currentMatch;
        this.currentMatch = null;
        return result;
      }
      this.findController.highlightFindOptions();
      const allSelections = this._editor.getSelections();
      const lastAddedSelection = allSelections[allSelections.length - 1];
      const previousMatch = this._editor.getModel().findPreviousMatch(this.searchText, lastAddedSelection.getStartPosition(), false, this.matchCase, this.wholeWord ? this._editor.getOption(
        148
        /* EditorOption.wordSeparators */
      ) : null, false);
      if (!previousMatch) {
        return null;
      }
      return new Selection$1(previousMatch.range.startLineNumber, previousMatch.range.startColumn, previousMatch.range.endLineNumber, previousMatch.range.endColumn);
    }
    selectAll(searchScope) {
      if (!this._editor.hasModel()) {
        return [];
      }
      this.findController.highlightFindOptions();
      const editorModel = this._editor.getModel();
      if (searchScope) {
        return editorModel.findMatches(
          this.searchText,
          searchScope,
          false,
          this.matchCase,
          this.wholeWord ? this._editor.getOption(
            148
            /* EditorOption.wordSeparators */
          ) : null,
          false,
          1073741824
          /* Constants.MAX_SAFE_SMALL_INTEGER */
        );
      }
      return editorModel.findMatches(
        this.searchText,
        true,
        false,
        this.matchCase,
        this.wholeWord ? this._editor.getOption(
          148
          /* EditorOption.wordSeparators */
        ) : null,
        false,
        1073741824
        /* Constants.MAX_SAFE_SMALL_INTEGER */
      );
    }
  }
  const _MultiCursorSelectionController = class _MultiCursorSelectionController extends Disposable {
    static get(editor2) {
      return editor2.getContribution(_MultiCursorSelectionController.ID);
    }
    constructor(editor2) {
      super();
      this._sessionDispose = this._register(new DisposableStore());
      this._editor = editor2;
      this._ignoreSelectionChange = false;
      this._session = null;
    }
    dispose() {
      this._endSession();
      super.dispose();
    }
    _beginSessionIfNeeded(findController) {
      if (!this._session) {
        const session = MultiCursorSession.create(this._editor, findController);
        if (!session) {
          return;
        }
        this._session = session;
        const newState = { searchString: this._session.searchText };
        if (this._session.isDisconnectedFromFindController) {
          newState.wholeWordOverride = 1;
          newState.matchCaseOverride = 1;
          newState.isRegexOverride = 2;
        }
        findController.getState().change(newState, false);
        this._sessionDispose.add(this._editor.onDidChangeCursorSelection((e) => {
          if (this._ignoreSelectionChange) {
            return;
          }
          this._endSession();
        }));
        this._sessionDispose.add(this._editor.onDidBlurEditorText(() => {
          this._endSession();
        }));
        this._sessionDispose.add(findController.getState().onFindReplaceStateChange((e) => {
          if (e.matchCase || e.wholeWord) {
            this._endSession();
          }
        }));
      }
    }
    _endSession() {
      this._sessionDispose.clear();
      if (this._session && this._session.isDisconnectedFromFindController) {
        const newState = {
          wholeWordOverride: 0,
          matchCaseOverride: 0,
          isRegexOverride: 0
        };
        this._session.findController.getState().change(newState, false);
      }
      this._session = null;
    }
    _setSelections(selections) {
      this._ignoreSelectionChange = true;
      this._editor.setSelections(selections);
      this._ignoreSelectionChange = false;
    }
    _expandEmptyToWord(model, selection) {
      if (!selection.isEmpty()) {
        return selection;
      }
      const word = this._editor.getConfiguredWordAtPosition(selection.getStartPosition());
      if (!word) {
        return selection;
      }
      return new Selection$1(selection.startLineNumber, word.startColumn, selection.startLineNumber, word.endColumn);
    }
    _applySessionResult(result) {
      if (!result) {
        return;
      }
      this._setSelections(result.selections);
      if (result.revealRange) {
        this._editor.revealRangeInCenterIfOutsideViewport(result.revealRange, result.revealScrollType);
      }
    }
    getSession(findController) {
      return this._session;
    }
    addSelectionToNextFindMatch(findController) {
      if (!this._editor.hasModel()) {
        return;
      }
      if (!this._session) {
        const allSelections = this._editor.getSelections();
        if (allSelections.length > 1) {
          const findState = findController.getState();
          const matchCase = findState.matchCase;
          const selectionsContainSameText = modelRangesContainSameText(this._editor.getModel(), allSelections, matchCase);
          if (!selectionsContainSameText) {
            const model = this._editor.getModel();
            const resultingSelections = [];
            for (let i2 = 0, len = allSelections.length; i2 < len; i2++) {
              resultingSelections[i2] = this._expandEmptyToWord(model, allSelections[i2]);
            }
            this._editor.setSelections(resultingSelections);
            return;
          }
        }
      }
      this._beginSessionIfNeeded(findController);
      if (this._session) {
        this._applySessionResult(this._session.addSelectionToNextFindMatch());
      }
    }
    addSelectionToPreviousFindMatch(findController) {
      this._beginSessionIfNeeded(findController);
      if (this._session) {
        this._applySessionResult(this._session.addSelectionToPreviousFindMatch());
      }
    }
    moveSelectionToNextFindMatch(findController) {
      this._beginSessionIfNeeded(findController);
      if (this._session) {
        this._applySessionResult(this._session.moveSelectionToNextFindMatch());
      }
    }
    moveSelectionToPreviousFindMatch(findController) {
      this._beginSessionIfNeeded(findController);
      if (this._session) {
        this._applySessionResult(this._session.moveSelectionToPreviousFindMatch());
      }
    }
    selectAll(findController) {
      if (!this._editor.hasModel()) {
        return;
      }
      let matches = null;
      const findState = findController.getState();
      if (findState.isRevealed && findState.searchString.length > 0 && findState.isRegex) {
        const editorModel = this._editor.getModel();
        if (findState.searchScope) {
          matches = editorModel.findMatches(
            findState.searchString,
            findState.searchScope,
            findState.isRegex,
            findState.matchCase,
            findState.wholeWord ? this._editor.getOption(
              148
              /* EditorOption.wordSeparators */
            ) : null,
            false,
            1073741824
            /* Constants.MAX_SAFE_SMALL_INTEGER */
          );
        } else {
          matches = editorModel.findMatches(
            findState.searchString,
            true,
            findState.isRegex,
            findState.matchCase,
            findState.wholeWord ? this._editor.getOption(
              148
              /* EditorOption.wordSeparators */
            ) : null,
            false,
            1073741824
            /* Constants.MAX_SAFE_SMALL_INTEGER */
          );
        }
      } else {
        this._beginSessionIfNeeded(findController);
        if (!this._session) {
          return;
        }
        matches = this._session.selectAll(findState.searchScope);
      }
      if (matches.length > 0) {
        const editorSelection = this._editor.getSelection();
        for (let i2 = 0, len = matches.length; i2 < len; i2++) {
          const match2 = matches[i2];
          const intersection2 = match2.range.intersectRanges(editorSelection);
          if (intersection2) {
            matches[i2] = matches[0];
            matches[0] = match2;
            break;
          }
        }
        this._setSelections(matches.map((m) => new Selection$1(m.range.startLineNumber, m.range.startColumn, m.range.endLineNumber, m.range.endColumn)));
      }
    }
  };
  _MultiCursorSelectionController.ID = "editor.contrib.multiCursorController";
  let MultiCursorSelectionController = _MultiCursorSelectionController;
  class MultiCursorSelectionControllerAction extends EditorAction {
    run(accessor, editor2) {
      const multiCursorController = MultiCursorSelectionController.get(editor2);
      if (!multiCursorController) {
        return;
      }
      const viewModel = editor2._getViewModel();
      if (viewModel) {
        const previousCursorState = viewModel.getCursorStates();
        const findController = CommonFindController.get(editor2);
        if (findController) {
          this._run(multiCursorController, findController);
        } else {
          const newFindController = accessor.get(IInstantiationService).createInstance(CommonFindController, editor2);
          this._run(multiCursorController, newFindController);
          newFindController.dispose();
        }
        announceCursorChange(previousCursorState, viewModel.getCursorStates());
      }
    }
  }
  class AddSelectionToNextFindMatchAction extends MultiCursorSelectionControllerAction {
    constructor() {
      super({
        id: "editor.action.addSelectionToNextFindMatch",
        label: localize2(1303, "Add Selection to Next Find Match"),
        precondition: void 0,
        kbOpts: {
          kbExpr: EditorContextKeys.focus,
          primary: 2048 | 34,
          weight: 100
          /* KeybindingWeight.EditorContrib */
        },
        menuOpts: {
          menuId: MenuId.MenubarSelectionMenu,
          group: "3_multi",
          title: localize(1293, "Add &&Next Occurrence"),
          order: 5
        }
      });
    }
    _run(multiCursorController, findController) {
      multiCursorController.addSelectionToNextFindMatch(findController);
    }
  }
  class AddSelectionToPreviousFindMatchAction extends MultiCursorSelectionControllerAction {
    constructor() {
      super({
        id: "editor.action.addSelectionToPreviousFindMatch",
        label: localize2(1304, "Add Selection to Previous Find Match"),
        precondition: void 0,
        menuOpts: {
          menuId: MenuId.MenubarSelectionMenu,
          group: "3_multi",
          title: localize(1294, "Add P&&revious Occurrence"),
          order: 6
        }
      });
    }
    _run(multiCursorController, findController) {
      multiCursorController.addSelectionToPreviousFindMatch(findController);
    }
  }
  class MoveSelectionToNextFindMatchAction extends MultiCursorSelectionControllerAction {
    constructor() {
      super({
        id: "editor.action.moveSelectionToNextFindMatch",
        label: localize2(1305, "Move Last Selection to Next Find Match"),
        precondition: void 0,
        kbOpts: {
          kbExpr: EditorContextKeys.focus,
          primary: KeyChord(
            2048 | 41,
            2048 | 34
            /* KeyCode.KeyD */
          ),
          weight: 100
          /* KeybindingWeight.EditorContrib */
        }
      });
    }
    _run(multiCursorController, findController) {
      multiCursorController.moveSelectionToNextFindMatch(findController);
    }
  }
  class MoveSelectionToPreviousFindMatchAction extends MultiCursorSelectionControllerAction {
    constructor() {
      super({
        id: "editor.action.moveSelectionToPreviousFindMatch",
        label: localize2(1306, "Move Last Selection to Previous Find Match"),
        precondition: void 0
      });
    }
    _run(multiCursorController, findController) {
      multiCursorController.moveSelectionToPreviousFindMatch(findController);
    }
  }
  class SelectHighlightsAction extends MultiCursorSelectionControllerAction {
    constructor() {
      super({
        id: "editor.action.selectHighlights",
        label: localize2(1307, "Select All Occurrences of Find Match"),
        precondition: void 0,
        kbOpts: {
          kbExpr: EditorContextKeys.focus,
          primary: 2048 | 1024 | 42,
          weight: 100
          /* KeybindingWeight.EditorContrib */
        },
        menuOpts: {
          menuId: MenuId.MenubarSelectionMenu,
          group: "3_multi",
          title: localize(1295, "Select All &&Occurrences"),
          order: 7
        }
      });
    }
    _run(multiCursorController, findController) {
      multiCursorController.selectAll(findController);
    }
  }
  class CompatChangeAll extends MultiCursorSelectionControllerAction {
    constructor() {
      super({
        id: "editor.action.changeAll",
        label: localize2(1308, "Change All Occurrences"),
        precondition: ContextKeyExpr.and(EditorContextKeys.writable, EditorContextKeys.editorTextFocus),
        kbOpts: {
          kbExpr: EditorContextKeys.editorTextFocus,
          primary: 2048 | 60,
          weight: 100
          /* KeybindingWeight.EditorContrib */
        },
        contextMenuOpts: {
          group: "1_modification",
          order: 1.2
        }
      });
    }
    _run(multiCursorController, findController) {
      multiCursorController.selectAll(findController);
    }
  }
  class SelectionHighlighterState {
    constructor(_model, _searchText, _matchCase, _wordSeparators, prevState) {
      this._model = _model;
      this._searchText = _searchText;
      this._matchCase = _matchCase;
      this._wordSeparators = _wordSeparators;
      this._cachedFindMatches = null;
      this._modelVersionId = this._model.getVersionId();
      if (prevState && this._model === prevState._model && this._searchText === prevState._searchText && this._matchCase === prevState._matchCase && this._wordSeparators === prevState._wordSeparators && this._modelVersionId === prevState._modelVersionId) {
        this._cachedFindMatches = prevState._cachedFindMatches;
      }
    }
    findMatches() {
      if (this._cachedFindMatches === null) {
        this._cachedFindMatches = this._model.findMatches(this._searchText, true, false, this._matchCase, this._wordSeparators, false).map((m) => m.range);
        this._cachedFindMatches.sort(Range$2.compareRangesUsingStarts);
      }
      return this._cachedFindMatches;
    }
  }
  let SelectionHighlighter = (_ta = class extends Disposable {
    constructor(editor2, _languageFeaturesService) {
      super();
      this._languageFeaturesService = _languageFeaturesService;
      this.editor = editor2;
      this._isEnabled = editor2.getOption(
        122
        /* EditorOption.selectionHighlight */
      );
      this._isEnabledMultiline = editor2.getOption(
        124
        /* EditorOption.selectionHighlightMultiline */
      );
      this._maxLength = editor2.getOption(
        123
        /* EditorOption.selectionHighlightMaxLength */
      );
      this._decorations = editor2.createDecorationsCollection();
      this.updateSoon = this._register(new RunOnceScheduler(() => this._update(), 300));
      this.state = null;
      this._register(editor2.onDidChangeConfiguration((e) => {
        this._isEnabled = editor2.getOption(
          122
          /* EditorOption.selectionHighlight */
        );
        this._isEnabledMultiline = editor2.getOption(
          124
          /* EditorOption.selectionHighlightMultiline */
        );
        this._maxLength = editor2.getOption(
          123
          /* EditorOption.selectionHighlightMaxLength */
        );
      }));
      this._register(editor2.onDidChangeCursorSelection((e) => {
        if (!this._isEnabled) {
          return;
        }
        if (e.selection.isEmpty()) {
          if (e.reason === 3) {
            if (this.state) {
              this._setState(null);
            }
            this.updateSoon.schedule();
          } else {
            this._setState(null);
          }
        } else {
          this._update();
        }
      }));
      this._register(editor2.onDidChangeModel((e) => {
        this._setState(null);
      }));
      this._register(editor2.onDidChangeModelContent((e) => {
        if (this._isEnabled) {
          this.updateSoon.schedule();
        }
      }));
      const findController = CommonFindController.get(editor2);
      if (findController) {
        this._register(findController.getState().onFindReplaceStateChange((e) => {
          this._update();
        }));
      }
      this.updateSoon.schedule();
    }
    _update() {
      this._setState(SelectionHighlighter_1._createState(this.state, this._isEnabled, this._isEnabledMultiline, this._maxLength, this.editor));
    }
    static _createState(oldState, isEnabled, isEnabledMultiline, maxLength, editor2) {
      if (!isEnabled) {
        return null;
      }
      if (!editor2.hasModel()) {
        return null;
      }
      if (!isEnabledMultiline) {
        const s = editor2.getSelection();
        if (s.startLineNumber !== s.endLineNumber) {
          return null;
        }
      }
      const multiCursorController = MultiCursorSelectionController.get(editor2);
      if (!multiCursorController) {
        return null;
      }
      const findController = CommonFindController.get(editor2);
      if (!findController) {
        return null;
      }
      let r = multiCursorController.getSession(findController);
      if (!r) {
        const allSelections = editor2.getSelections();
        if (allSelections.length > 1) {
          const findState2 = findController.getState();
          const matchCase = findState2.matchCase;
          const selectionsContainSameText = modelRangesContainSameText(editor2.getModel(), allSelections, matchCase);
          if (!selectionsContainSameText) {
            return null;
          }
        }
        r = MultiCursorSession.create(editor2, findController);
      }
      if (!r) {
        return null;
      }
      if (r.currentMatch) {
        return null;
      }
      if (/^[ \t]+$/.test(r.searchText)) {
        return null;
      }
      if (maxLength > 0 && r.searchText.length > maxLength) {
        return null;
      }
      const findState = findController.getState();
      const caseSensitive = findState.matchCase;
      if (findState.isRevealed) {
        let findStateSearchString = findState.searchString;
        if (!caseSensitive) {
          findStateSearchString = findStateSearchString.toLowerCase();
        }
        let mySearchString = r.searchText;
        if (!caseSensitive) {
          mySearchString = mySearchString.toLowerCase();
        }
        if (findStateSearchString === mySearchString && r.matchCase === findState.matchCase && r.wholeWord === findState.wholeWord && !findState.isRegex) {
          return null;
        }
      }
      return new SelectionHighlighterState(editor2.getModel(), r.searchText, r.matchCase, r.wholeWord ? editor2.getOption(
        148
        /* EditorOption.wordSeparators */
      ) : null, oldState);
    }
    _setState(newState) {
      this.state = newState;
      if (!this.state) {
        this._decorations.clear();
        return;
      }
      if (!this.editor.hasModel()) {
        return;
      }
      const model = this.editor.getModel();
      if (model.isTooLargeForTokenization()) {
        return;
      }
      const allMatches = this.state.findMatches();
      const selections = this.editor.getSelections();
      selections.sort(Range$2.compareRangesUsingStarts);
      const matches = [];
      for (let i2 = 0, j = 0, len = allMatches.length, lenJ = selections.length; i2 < len; ) {
        const match2 = allMatches[i2];
        if (j >= lenJ) {
          matches.push(match2);
          i2++;
        } else {
          const cmp3 = Range$2.compareRangesUsingStarts(match2, selections[j]);
          if (cmp3 < 0) {
            if (selections[j].isEmpty() || !Range$2.areIntersecting(match2, selections[j])) {
              matches.push(match2);
            }
            i2++;
          } else if (cmp3 > 0) {
            j++;
          } else {
            i2++;
            j++;
          }
        }
      }
      const occurrenceHighlighting = this.editor.getOption(
        90
        /* EditorOption.occurrencesHighlight */
      ) !== "off";
      const hasSemanticHighlights = this._languageFeaturesService.documentHighlightProvider.has(model) && occurrenceHighlighting;
      const decorations = matches.map((r) => {
        return {
          range: r,
          options: getSelectionHighlightDecorationOptions(hasSemanticHighlights)
        };
      });
      this._decorations.set(decorations);
    }
    dispose() {
      this._setState(null);
      super.dispose();
    }
  }, SelectionHighlighter_1 = _ta, _ta.ID = "editor.contrib.selectionHighlighter", _ta);
  SelectionHighlighter = SelectionHighlighter_1 = __decorate$X([
    __param$W(1, ILanguageFeaturesService)
  ], SelectionHighlighter);
  function modelRangesContainSameText(model, ranges, matchCase) {
    const selectedText = getValueInRange(model, ranges[0], !matchCase);
    for (let i2 = 1, len = ranges.length; i2 < len; i2++) {
      const range2 = ranges[i2];
      if (range2.isEmpty()) {
        return false;
      }
      const thisSelectedText = getValueInRange(model, range2, !matchCase);
      if (selectedText !== thisSelectedText) {
        return false;
      }
    }
    return true;
  }
  function getValueInRange(model, range2, toLowerCase) {
    const text2 = model.getValueInRange(range2);
    return toLowerCase ? text2.toLowerCase() : text2;
  }
  class FocusNextCursor extends EditorAction {
    constructor() {
      super({
        id: "editor.action.focusNextCursor",
        label: localize2(1309, "Focus Next Cursor"),
        metadata: {
          description: localize(1296, "Focuses the next cursor"),
          args: []
        },
        precondition: void 0
      });
    }
    run(accessor, editor2, args) {
      if (!editor2.hasModel()) {
        return;
      }
      const viewModel = editor2._getViewModel();
      if (viewModel.cursorConfig.readOnly) {
        return;
      }
      viewModel.model.pushStackElement();
      const previousCursorState = Array.from(viewModel.getCursorStates());
      const firstCursor = previousCursorState.shift();
      if (!firstCursor) {
        return;
      }
      previousCursorState.push(firstCursor);
      viewModel.setCursorStates(args.source, 3, previousCursorState);
      viewModel.revealPrimaryCursor(args.source, true);
      announceCursorChange(previousCursorState, viewModel.getCursorStates());
    }
  }
  class FocusPreviousCursor extends EditorAction {
    constructor() {
      super({
        id: "editor.action.focusPreviousCursor",
        label: localize2(1310, "Focus Previous Cursor"),
        metadata: {
          description: localize(1297, "Focuses the previous cursor"),
          args: []
        },
        precondition: void 0
      });
    }
    run(accessor, editor2, args) {
      if (!editor2.hasModel()) {
        return;
      }
      const viewModel = editor2._getViewModel();
      if (viewModel.cursorConfig.readOnly) {
        return;
      }
      viewModel.model.pushStackElement();
      const previousCursorState = Array.from(viewModel.getCursorStates());
      const firstCursor = previousCursorState.pop();
      if (!firstCursor) {
        return;
      }
      previousCursorState.unshift(firstCursor);
      viewModel.setCursorStates(args.source, 3, previousCursorState);
      viewModel.revealPrimaryCursor(args.source, true);
      announceCursorChange(previousCursorState, viewModel.getCursorStates());
    }
  }
  registerEditorContribution(
    MultiCursorSelectionController.ID,
    MultiCursorSelectionController,
    4
    /* EditorContributionInstantiation.Lazy */
  );
  registerEditorContribution(
    SelectionHighlighter.ID,
    SelectionHighlighter,
    1
    /* EditorContributionInstantiation.AfterFirstRender */
  );
  registerEditorAction(InsertCursorAbove);
  registerEditorAction(InsertCursorBelow);
  registerEditorAction(InsertCursorAtEndOfEachLineSelected);
  registerEditorAction(AddSelectionToNextFindMatchAction);
  registerEditorAction(AddSelectionToPreviousFindMatchAction);
  registerEditorAction(MoveSelectionToNextFindMatchAction);
  registerEditorAction(MoveSelectionToPreviousFindMatchAction);
  registerEditorAction(SelectHighlightsAction);
  registerEditorAction(CompatChangeAll);
  registerEditorAction(InsertCursorAtEndOfLineSelected);
  registerEditorAction(InsertCursorAtTopOfLineSelected);
  registerEditorAction(FocusNextCursor);
  registerEditorAction(FocusPreviousCursor);
  const Context$1 = {
    Visible: new RawContextKey("parameterHintsVisible", false),
    MultipleSignatures: new RawContextKey("parameterHintsMultipleSignatures", false)
  };
  async function provideSignatureHelp(registry, model, position, context, token) {
    const supports = registry.ordered(model);
    for (const support of supports) {
      try {
        const result = await support.provideSignatureHelp(model, position, token, context);
        if (result) {
          return result;
        }
      } catch (err) {
        onUnexpectedExternalError(err);
      }
    }
    return void 0;
  }
  CommandsRegistry.registerCommand("_executeSignatureHelpProvider", async (accessor, ...args) => {
    const [uri, position, triggerCharacter] = args;
    assertType(URI.isUri(uri));
    assertType(Position$1.isIPosition(position));
    assertType(typeof triggerCharacter === "string" || !triggerCharacter);
    const languageFeaturesService = accessor.get(ILanguageFeaturesService);
    const ref = await accessor.get(ITextModelService).createModelReference(uri);
    try {
      const result = await provideSignatureHelp(languageFeaturesService.signatureHelpProvider, ref.object.textEditorModel, Position$1.lift(position), {
        triggerKind: SignatureHelpTriggerKind$1.Invoke,
        isRetrigger: false,
        triggerCharacter
      }, CancellationToken.None);
      if (!result) {
        return void 0;
      }
      setTimeout(() => result.dispose(), 0);
      return result.value;
    } finally {
      ref.dispose();
    }
  });
  var ParameterHintState;
  (function(ParameterHintState2) {
    ParameterHintState2.Default = {
      type: 0
      /* Type.Default */
    };
    class Pending {
      constructor(request, previouslyActiveHints) {
        this.request = request;
        this.previouslyActiveHints = previouslyActiveHints;
        this.type = 2;
      }
    }
    ParameterHintState2.Pending = Pending;
    class Active {
      constructor(hints) {
        this.hints = hints;
        this.type = 1;
      }
    }
    ParameterHintState2.Active = Active;
  })(ParameterHintState || (ParameterHintState = {}));
  const _ParameterHintsModel = class _ParameterHintsModel extends Disposable {
    // ms
    constructor(editor2, providers, delay = _ParameterHintsModel.DEFAULT_DELAY) {
      super();
      this._onChangedHints = this._register(new Emitter$1());
      this.onChangedHints = this._onChangedHints.event;
      this.triggerOnType = false;
      this._state = ParameterHintState.Default;
      this._pendingTriggers = [];
      this._lastSignatureHelpResult = this._register(new MutableDisposable());
      this.triggerChars = new CharacterSet();
      this.retriggerChars = new CharacterSet();
      this.triggerId = 0;
      this.editor = editor2;
      this.providers = providers;
      this.throttledDelayer = new Delayer(delay);
      this._register(this.editor.onDidBlurEditorWidget(() => this.cancel()));
      this._register(this.editor.onDidChangeConfiguration(() => this.onEditorConfigurationChange()));
      this._register(this.editor.onDidChangeModel((e) => this.onModelChanged()));
      this._register(this.editor.onDidChangeModelLanguage((_) => this.onModelChanged()));
      this._register(this.editor.onDidChangeCursorSelection((e) => this.onCursorChange(e)));
      this._register(this.editor.onDidChangeModelContent((e) => this.onModelContentChange()));
      this._register(this.providers.onDidChange(this.onModelChanged, this));
      this._register(this.editor.onDidType((text2) => this.onDidType(text2)));
      this.onEditorConfigurationChange();
      this.onModelChanged();
    }
    get state() {
      return this._state;
    }
    set state(value) {
      if (this._state.type === 2) {
        this._state.request.cancel();
      }
      this._state = value;
    }
    cancel(silent = false) {
      this.state = ParameterHintState.Default;
      this.throttledDelayer.cancel();
      if (!silent) {
        this._onChangedHints.fire(void 0);
      }
    }
    trigger(context, delay) {
      const model = this.editor.getModel();
      if (!model || !this.providers.has(model)) {
        return;
      }
      const triggerId = ++this.triggerId;
      this._pendingTriggers.push(context);
      this.throttledDelayer.trigger(() => {
        return this.doTrigger(triggerId);
      }, delay).catch(onUnexpectedError);
    }
    next() {
      if (this.state.type !== 1) {
        return;
      }
      const length = this.state.hints.signatures.length;
      const activeSignature = this.state.hints.activeSignature;
      const last = activeSignature % length === length - 1;
      const cycle = this.editor.getOption(
        98
        /* EditorOption.parameterHints */
      ).cycle;
      if ((length < 2 || last) && !cycle) {
        this.cancel();
        return;
      }
      this.updateActiveSignature(last && cycle ? 0 : activeSignature + 1);
    }
    previous() {
      if (this.state.type !== 1) {
        return;
      }
      const length = this.state.hints.signatures.length;
      const activeSignature = this.state.hints.activeSignature;
      const first2 = activeSignature === 0;
      const cycle = this.editor.getOption(
        98
        /* EditorOption.parameterHints */
      ).cycle;
      if ((length < 2 || first2) && !cycle) {
        this.cancel();
        return;
      }
      this.updateActiveSignature(first2 && cycle ? length - 1 : activeSignature - 1);
    }
    updateActiveSignature(activeSignature) {
      if (this.state.type !== 1) {
        return;
      }
      this.state = new ParameterHintState.Active({ ...this.state.hints, activeSignature });
      this._onChangedHints.fire(this.state.hints);
    }
    async doTrigger(triggerId) {
      const isRetrigger = this.state.type === 1 || this.state.type === 2;
      const activeSignatureHelp = this.getLastActiveHints();
      this.cancel(true);
      if (this._pendingTriggers.length === 0) {
        return false;
      }
      const context = this._pendingTriggers.reduce(mergeTriggerContexts);
      this._pendingTriggers = [];
      const triggerContext = {
        triggerKind: context.triggerKind,
        triggerCharacter: context.triggerCharacter,
        isRetrigger,
        activeSignatureHelp
      };
      if (!this.editor.hasModel()) {
        return false;
      }
      const model = this.editor.getModel();
      const position = this.editor.getPosition();
      this.state = new ParameterHintState.Pending(createCancelablePromise((token) => provideSignatureHelp(this.providers, model, position, triggerContext, token)), activeSignatureHelp);
      try {
        const result = await this.state.request;
        if (triggerId !== this.triggerId) {
          result?.dispose();
          return false;
        }
        if (!result || !result.value.signatures || result.value.signatures.length === 0) {
          result?.dispose();
          this._lastSignatureHelpResult.clear();
          this.cancel();
          return false;
        } else {
          this.state = new ParameterHintState.Active(result.value);
          this._lastSignatureHelpResult.value = result;
          this._onChangedHints.fire(this.state.hints);
          return true;
        }
      } catch (error) {
        if (triggerId === this.triggerId) {
          this.state = ParameterHintState.Default;
        }
        onUnexpectedError(error);
        return false;
      }
    }
    getLastActiveHints() {
      switch (this.state.type) {
        case 1:
          return this.state.hints;
        case 2:
          return this.state.previouslyActiveHints;
        default:
          return void 0;
      }
    }
    get isTriggered() {
      return this.state.type === 1 || this.state.type === 2 || this.throttledDelayer.isTriggered();
    }
    onModelChanged() {
      this.cancel();
      this.triggerChars.clear();
      this.retriggerChars.clear();
      const model = this.editor.getModel();
      if (!model) {
        return;
      }
      for (const support of this.providers.ordered(model)) {
        for (const ch of support.signatureHelpTriggerCharacters || []) {
          if (ch.length) {
            const charCode = ch.charCodeAt(0);
            this.triggerChars.add(charCode);
            this.retriggerChars.add(charCode);
          }
        }
        for (const ch of support.signatureHelpRetriggerCharacters || []) {
          if (ch.length) {
            this.retriggerChars.add(ch.charCodeAt(0));
          }
        }
      }
    }
    onDidType(text2) {
      if (!this.triggerOnType) {
        return;
      }
      const lastCharIndex = text2.length - 1;
      const triggerCharCode = text2.charCodeAt(lastCharIndex);
      if (this.triggerChars.has(triggerCharCode) || this.isTriggered && this.retriggerChars.has(triggerCharCode)) {
        this.trigger({
          triggerKind: SignatureHelpTriggerKind$1.TriggerCharacter,
          triggerCharacter: text2.charAt(lastCharIndex)
        });
      }
    }
    onCursorChange(e) {
      if (e.source === "mouse") {
        this.cancel();
      } else if (this.isTriggered) {
        this.trigger({ triggerKind: SignatureHelpTriggerKind$1.ContentChange });
      }
    }
    onModelContentChange() {
      if (this.isTriggered) {
        this.trigger({ triggerKind: SignatureHelpTriggerKind$1.ContentChange });
      }
    }
    onEditorConfigurationChange() {
      this.triggerOnType = this.editor.getOption(
        98
        /* EditorOption.parameterHints */
      ).enabled;
      if (!this.triggerOnType) {
        this.cancel();
      }
    }
    dispose() {
      this.cancel(true);
      super.dispose();
    }
  };
  _ParameterHintsModel.DEFAULT_DELAY = 120;
  let ParameterHintsModel = _ParameterHintsModel;
  function mergeTriggerContexts(previous, current) {
    switch (current.triggerKind) {
      case SignatureHelpTriggerKind$1.Invoke:
        return current;
      case SignatureHelpTriggerKind$1.ContentChange:
        return previous;
      case SignatureHelpTriggerKind$1.TriggerCharacter:
      default:
        return current;
    }
  }
  var __decorate$W = 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$V = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  var ParameterHintsWidget_1;
  const $$6 = $$l;
  const parameterHintsNextIcon = registerIcon("parameter-hints-next", Codicon.chevronDown, localize(1312, "Icon for show next parameter hint."));
  const parameterHintsPreviousIcon = registerIcon("parameter-hints-previous", Codicon.chevronUp, localize(1313, "Icon for show previous parameter hint."));
  let ParameterHintsWidget = (_ua = class extends Disposable {
    constructor(editor2, model, contextKeyService, markdownRendererService) {
      super();
      this.editor = editor2;
      this.model = model;
      this.markdownRendererService = markdownRendererService;
      this.renderDisposeables = this._register(new DisposableStore());
      this.visible = false;
      this.announcedLabel = null;
      this.allowEditorOverflow = true;
      this.keyVisible = Context$1.Visible.bindTo(contextKeyService);
      this.keyMultipleSignatures = Context$1.MultipleSignatures.bindTo(contextKeyService);
    }
    createParameterHintDOMNodes() {
      const element = $$6(".editor-widget.parameter-hints-widget");
      const wrapper = append$2(element, $$6(".phwrapper"));
      wrapper.tabIndex = -1;
      const controls = append$2(wrapper, $$6(".controls"));
      const previous = append$2(controls, $$6(".button" + ThemeIcon.asCSSSelector(parameterHintsPreviousIcon)));
      const overloads = append$2(controls, $$6(".overloads"));
      const next = append$2(controls, $$6(".button" + ThemeIcon.asCSSSelector(parameterHintsNextIcon)));
      this._register(addDisposableListener(previous, "click", (e) => {
        EventHelper.stop(e);
        this.previous();
      }));
      this._register(addDisposableListener(next, "click", (e) => {
        EventHelper.stop(e);
        this.next();
      }));
      const body = $$6(".body");
      const scrollbar = new DomScrollableElement(body, {
        alwaysConsumeMouseWheel: true
      });
      this._register(scrollbar);
      wrapper.appendChild(scrollbar.getDomNode());
      const signature = append$2(body, $$6(".signature"));
      const docs = append$2(body, $$6(".docs"));
      element.style.userSelect = "text";
      this.domNodes = {
        element,
        signature,
        overloads,
        docs,
        scrollbar
      };
      this.editor.addContentWidget(this);
      this.hide();
      this._register(this.editor.onDidChangeCursorSelection((e) => {
        if (this.visible) {
          this.editor.layoutContentWidget(this);
        }
      }));
      const updateFont = () => {
        if (!this.domNodes) {
          return;
        }
        const fontInfo = this.editor.getOption(
          59
          /* EditorOption.fontInfo */
        );
        const element2 = this.domNodes.element;
        element2.style.fontSize = `${fontInfo.fontSize}px`;
        element2.style.lineHeight = `${fontInfo.lineHeight / fontInfo.fontSize}`;
        element2.style.setProperty("--vscode-parameterHintsWidget-editorFontFamily", fontInfo.fontFamily);
        element2.style.setProperty("--vscode-parameterHintsWidget-editorFontFamilyDefault", EDITOR_FONT_DEFAULTS.fontFamily);
      };
      updateFont();
      this._register(Event.chain(this.editor.onDidChangeConfiguration.bind(this.editor), ($2) => $2.filter((e) => e.hasChanged(
        59
        /* EditorOption.fontInfo */
      )))(updateFont));
      this._register(this.editor.onDidLayoutChange((e) => this.updateMaxHeight()));
      this.updateMaxHeight();
    }
    show() {
      if (this.visible) {
        return;
      }
      if (!this.domNodes) {
        this.createParameterHintDOMNodes();
      }
      this.keyVisible.set(true);
      this.visible = true;
      setTimeout(() => {
        this.domNodes?.element.classList.add("visible");
      }, 100);
      this.editor.layoutContentWidget(this);
    }
    hide() {
      this.renderDisposeables.clear();
      if (!this.visible) {
        return;
      }
      this.keyVisible.reset();
      this.visible = false;
      this.announcedLabel = null;
      this.domNodes?.element.classList.remove("visible");
      this.editor.layoutContentWidget(this);
    }
    getPosition() {
      if (this.visible) {
        return {
          position: this.editor.getPosition(),
          preference: [
            1,
            2
            /* ContentWidgetPositionPreference.BELOW */
          ]
        };
      }
      return null;
    }
    render(hints) {
      this.renderDisposeables.clear();
      if (!this.domNodes) {
        return;
      }
      const multiple = hints.signatures.length > 1;
      this.domNodes.element.classList.toggle("multiple", multiple);
      this.keyMultipleSignatures.set(multiple);
      this.domNodes.signature.innerText = "";
      this.domNodes.docs.innerText = "";
      const signature = hints.signatures[hints.activeSignature];
      if (!signature) {
        return;
      }
      const code = append$2(this.domNodes.signature, $$6(".code"));
      const hasParameters = signature.parameters.length > 0;
      const activeParameterIndex = signature.activeParameter ?? hints.activeParameter;
      if (!hasParameters) {
        const label = append$2(code, $$6("span"));
        label.textContent = signature.label;
      } else {
        this.renderParameters(code, signature, activeParameterIndex);
      }
      const activeParameter = signature.parameters[activeParameterIndex];
      if (activeParameter?.documentation) {
        const documentation = $$6("span.documentation");
        if (typeof activeParameter.documentation === "string") {
          documentation.textContent = activeParameter.documentation;
        } else {
          const renderedContents = this.renderMarkdownDocs(activeParameter.documentation);
          documentation.appendChild(renderedContents.element);
        }
        append$2(this.domNodes.docs, $$6("p", {}, documentation));
      }
      if (signature.documentation === void 0) ;
      else if (typeof signature.documentation === "string") {
        append$2(this.domNodes.docs, $$6("p", {}, signature.documentation));
      } else {
        const renderedContents = this.renderMarkdownDocs(signature.documentation);
        append$2(this.domNodes.docs, renderedContents.element);
      }
      const hasDocs = this.hasDocs(signature, activeParameter);
      this.domNodes.signature.classList.toggle("has-docs", hasDocs);
      this.domNodes.docs.classList.toggle("empty", !hasDocs);
      this.domNodes.overloads.textContent = String(hints.activeSignature + 1).padStart(hints.signatures.length.toString().length, "0") + "/" + hints.signatures.length;
      if (activeParameter) {
        let labelToAnnounce = "";
        const param = signature.parameters[activeParameterIndex];
        if (Array.isArray(param.label)) {
          labelToAnnounce = signature.label.substring(param.label[0], param.label[1]);
        } else {
          labelToAnnounce = param.label;
        }
        if (param.documentation) {
          labelToAnnounce += typeof param.documentation === "string" ? `, ${param.documentation}` : `, ${param.documentation.value}`;
        }
        if (signature.documentation) {
          labelToAnnounce += typeof signature.documentation === "string" ? `, ${signature.documentation}` : `, ${signature.documentation.value}`;
        }
        if (this.announcedLabel !== labelToAnnounce) {
          alert(localize(1314, "{0}, hint", labelToAnnounce));
          this.announcedLabel = labelToAnnounce;
        }
      }
      this.editor.layoutContentWidget(this);
      this.domNodes.scrollbar.scanDomNode();
    }
    renderMarkdownDocs(markdown) {
      const renderedContents = this.renderDisposeables.add(this.markdownRendererService.render(markdown, {
        context: this.editor,
        asyncRenderCallback: () => {
          this.domNodes?.scrollbar.scanDomNode();
        }
      }));
      renderedContents.element.classList.add("markdown-docs");
      return renderedContents;
    }
    hasDocs(signature, activeParameter) {
      if (activeParameter && typeof activeParameter.documentation === "string" && assertReturnsDefined(activeParameter.documentation).length > 0) {
        return true;
      }
      if (activeParameter && typeof activeParameter.documentation === "object" && assertReturnsDefined(activeParameter.documentation).value.length > 0) {
        return true;
      }
      if (signature.documentation && typeof signature.documentation === "string" && assertReturnsDefined(signature.documentation).length > 0) {
        return true;
      }
      if (signature.documentation && typeof signature.documentation === "object" && assertReturnsDefined(signature.documentation.value).length > 0) {
        return true;
      }
      return false;
    }
    renderParameters(parent, signature, activeParameterIndex) {
      const [start, end] = this.getParameterLabelOffsets(signature, activeParameterIndex);
      const beforeSpan = document.createElement("span");
      beforeSpan.textContent = signature.label.substring(0, start);
      const paramSpan = document.createElement("span");
      paramSpan.textContent = signature.label.substring(start, end);
      paramSpan.className = "parameter active";
      const afterSpan = document.createElement("span");
      afterSpan.textContent = signature.label.substring(end);
      append$2(parent, beforeSpan, paramSpan, afterSpan);
    }
    getParameterLabelOffsets(signature, paramIdx) {
      const param = signature.parameters[paramIdx];
      if (!param) {
        return [0, 0];
      } else if (Array.isArray(param.label)) {
        return param.label;
      } else if (!param.label.length) {
        return [0, 0];
      } else {
        const regex = new RegExp(`(\\W|^)${escapeRegExpCharacters(param.label)}(?=\\W|$)`, "g");
        regex.test(signature.label);
        const idx = regex.lastIndex - param.label.length;
        return idx >= 0 ? [idx, regex.lastIndex] : [0, 0];
      }
    }
    next() {
      this.editor.focus();
      this.model.next();
    }
    previous() {
      this.editor.focus();
      this.model.previous();
    }
    getDomNode() {
      if (!this.domNodes) {
        this.createParameterHintDOMNodes();
      }
      return this.domNodes.element;
    }
    getId() {
      return ParameterHintsWidget_1.ID;
    }
    updateMaxHeight() {
      if (!this.domNodes) {
        return;
      }
      const height = Math.max(this.editor.getLayoutInfo().height / 4, 250);
      const maxHeight = `${height}px`;
      this.domNodes.element.style.maxHeight = maxHeight;
      const wrapper = this.domNodes.element.getElementsByClassName("phwrapper");
      if (wrapper.length) {
        wrapper[0].style.maxHeight = maxHeight;
      }
    }
  }, ParameterHintsWidget_1 = _ua, _ua.ID = "editor.widget.parameterHintsWidget", _ua);
  ParameterHintsWidget = ParameterHintsWidget_1 = __decorate$W([
    __param$V(2, IContextKeyService),
    __param$V(3, IMarkdownRendererService)
  ], ParameterHintsWidget);
  registerColor("editorHoverWidget.highlightForeground", listHighlightForeground, localize(1315, "Foreground color of the active item in the parameter hint."));
  var __decorate$V = 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$U = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  var ParameterHintsController_1;
  let ParameterHintsController = (_va = class extends Disposable {
    static get(editor2) {
      return editor2.getContribution(ParameterHintsController_1.ID);
    }
    constructor(editor2, instantiationService, languageFeaturesService) {
      super();
      this.editor = editor2;
      this.model = this._register(new ParameterHintsModel(editor2, languageFeaturesService.signatureHelpProvider));
      this._register(this.model.onChangedHints((newParameterHints) => {
        if (newParameterHints) {
          this.widget.value.show();
          this.widget.value.render(newParameterHints);
        } else {
          this.widget.rawValue?.hide();
        }
      }));
      this.widget = new Lazy(() => this._register(instantiationService.createInstance(ParameterHintsWidget, this.editor, this.model)));
    }
    cancel() {
      this.model.cancel();
    }
    previous() {
      this.widget.rawValue?.previous();
    }
    next() {
      this.widget.rawValue?.next();
    }
    trigger(context) {
      this.model.trigger(context, 0);
    }
  }, ParameterHintsController_1 = _va, _va.ID = "editor.controller.parameterHints", _va);
  ParameterHintsController = ParameterHintsController_1 = __decorate$V([
    __param$U(1, IInstantiationService),
    __param$U(2, ILanguageFeaturesService)
  ], ParameterHintsController);
  class TriggerParameterHintsAction extends EditorAction {
    constructor() {
      super({
        id: "editor.action.triggerParameterHints",
        label: localize2(1311, "Trigger Parameter Hints"),
        precondition: EditorContextKeys.hasSignatureHelpProvider,
        kbOpts: {
          kbExpr: EditorContextKeys.editorTextFocus,
          primary: 2048 | 1024 | 10,
          weight: 100
          /* KeybindingWeight.EditorContrib */
        }
      });
    }
    run(accessor, editor2) {
      const controller = ParameterHintsController.get(editor2);
      controller?.trigger({
        triggerKind: SignatureHelpTriggerKind$1.Invoke
      });
    }
  }
  registerEditorContribution(
    ParameterHintsController.ID,
    ParameterHintsController,
    2
    /* EditorContributionInstantiation.BeforeFirstInteraction */
  );
  registerEditorAction(TriggerParameterHintsAction);
  const weight$1 = 100 + 75;
  const ParameterHintsCommand = EditorCommand.bindToContribution(ParameterHintsController.get);
  registerEditorCommand(new ParameterHintsCommand({
    id: "closeParameterHints",
    precondition: Context$1.Visible,
    handler: (x) => x.cancel(),
    kbOpts: {
      weight: weight$1,
      kbExpr: EditorContextKeys.focus,
      primary: 9,
      secondary: [
        1024 | 9
        /* KeyCode.Escape */
      ]
    }
  }));
  registerEditorCommand(new ParameterHintsCommand({
    id: "showPrevParameterHint",
    precondition: ContextKeyExpr.and(Context$1.Visible, Context$1.MultipleSignatures),
    handler: (x) => x.previous(),
    kbOpts: {
      weight: weight$1,
      kbExpr: EditorContextKeys.focus,
      primary: 16,
      secondary: [
        512 | 16
        /* KeyCode.UpArrow */
      ],
      mac: { primary: 16, secondary: [
        512 | 16,
        256 | 46
        /* KeyCode.KeyP */
      ] }
    }
  }));
  registerEditorCommand(new ParameterHintsCommand({
    id: "showNextParameterHint",
    precondition: ContextKeyExpr.and(Context$1.Visible, Context$1.MultipleSignatures),
    handler: (x) => x.next(),
    kbOpts: {
      weight: weight$1,
      kbExpr: EditorContextKeys.focus,
      primary: 18,
      secondary: [
        512 | 18
        /* KeyCode.DownArrow */
      ],
      mac: { primary: 18, secondary: [
        512 | 18,
        256 | 44
        /* KeyCode.KeyN */
      ] }
    }
  }));
  const _PlaceholderTextContribution = class _PlaceholderTextContribution extends Disposable {
    constructor(_editor) {
      super();
      this._editor = _editor;
      this._editorObs = observableCodeEditor(this._editor);
      this._placeholderText = this._editorObs.getOption(
        100
        /* EditorOption.placeholder */
      );
      this._state = derivedOpts({ owner: this, equalsFn: structuralEquals }, (reader) => {
        const p = this._placeholderText.read(reader);
        if (!p) {
          return void 0;
        }
        if (!this._editorObs.valueIsEmpty.read(reader)) {
          return void 0;
        }
        return { placeholder: p };
      });
      this._shouldViewBeAlive = isOrWasTrue(this, (reader) => this._state.read(reader)?.placeholder !== void 0);
      this._view = derived((reader) => {
        if (!this._shouldViewBeAlive.read(reader)) {
          return;
        }
        const element = h("div.editorPlaceholder");
        reader.store.add(autorun((reader2) => {
          const data = this._state.read(reader2);
          const shouldBeVisibile = data?.placeholder !== void 0;
          element.root.style.display = shouldBeVisibile ? "block" : "none";
          element.root.innerText = data?.placeholder ?? "";
        }));
        reader.store.add(autorun((reader2) => {
          const info = this._editorObs.layoutInfo.read(reader2);
          element.root.style.left = `${info.contentLeft}px`;
          element.root.style.width = info.contentWidth - info.verticalScrollbarWidth + "px";
          element.root.style.top = `${this._editor.getTopForLineNumber(0)}px`;
        }));
        reader.store.add(autorun((reader2) => {
          element.root.style.fontFamily = this._editorObs.getOption(
            58
            /* EditorOption.fontFamily */
          ).read(reader2);
          element.root.style.fontSize = this._editorObs.getOption(
            61
            /* EditorOption.fontSize */
          ).read(reader2) + "px";
          element.root.style.lineHeight = this._editorObs.getOption(
            75
            /* EditorOption.lineHeight */
          ).read(reader2) + "px";
        }));
        reader.store.add(this._editorObs.createOverlayWidget({
          allowEditorOverflow: false,
          minContentWidthInPx: constObservable(0),
          position: constObservable(null),
          domNode: element.root
        }));
      });
      this._view.recomputeInitiallyAndOnChange(this._store);
    }
  };
  _PlaceholderTextContribution.ID = "editor.contrib.placeholderText";
  let PlaceholderTextContribution = _PlaceholderTextContribution;
  function isOrWasTrue(owner, fn) {
    return derivedObservableWithCache(owner, (reader, lastValue) => {
      if (lastValue === true) {
        return true;
      }
      return fn(reader);
    });
  }
  var __decorate$U = 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$T = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  class BaseClass {
    constructor(instantiationService) {
      this.instantiationService = instantiationService;
    }
    init(...params) {
    }
  }
  function wrapInReloadableClass1(getClass) {
    return getClass();
  }
  let BaseClass1 = class BaseClass1 extends BaseClass {
    constructor(param1, i2) {
      super(i2);
      this.init(param1);
    }
  };
  BaseClass1 = __decorate$U([
    __param$T(1, IInstantiationService)
  ], BaseClass1);
  registerEditorContribution(
    PlaceholderTextContribution.ID,
    wrapInReloadableClass1(() => PlaceholderTextContribution),
    0
    /* EditorContributionInstantiation.Eager */
  );
  registerColor("editor.placeholder.foreground", ghostTextForeground, localize(1334, "Foreground color of the placeholder text in the editor."));
  const ITextResourceConfigurationService = createDecorator("textResourceConfigurationService");
  const ITextResourcePropertiesService = createDecorator("textResourcePropertiesService");
  var __decorate$T = 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$S = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  const CONTEXT_RENAME_INPUT_VISIBLE = new RawContextKey("renameInputVisible", false, localize(1391, "Whether the rename input widget is visible"));
  new RawContextKey("renameInputFocused", false, localize(1392, "Whether the rename input widget is focused"));
  let RenameWidget = class RenameWidget {
    constructor(_editor, _acceptKeybindings, _themeService, _keybindingService, contextKeyService, _logService) {
      this._editor = _editor;
      this._acceptKeybindings = _acceptKeybindings;
      this._themeService = _themeService;
      this._keybindingService = _keybindingService;
      this._logService = _logService;
      this.allowEditorOverflow = true;
      this._disposables = new DisposableStore();
      this._visibleContextKey = CONTEXT_RENAME_INPUT_VISIBLE.bindTo(contextKeyService);
      this._isEditingRenameCandidate = false;
      this._nRenameSuggestionsInvocations = 0;
      this._hadAutomaticRenameSuggestionsInvocation = false;
      this._candidates = /* @__PURE__ */ new Set();
      this._beforeFirstInputFieldEditSW = new StopWatch();
      this._inputWithButton = new InputWithButton();
      this._disposables.add(this._inputWithButton);
      this._editor.addContentWidget(this);
      this._disposables.add(this._editor.onDidChangeConfiguration((e) => {
        if (e.hasChanged(
          59
          /* EditorOption.fontInfo */
        )) {
          this._updateFont();
        }
      }));
      this._disposables.add(_themeService.onDidColorThemeChange(this._updateStyles, this));
    }
    dispose() {
      this._disposables.dispose();
      this._editor.removeContentWidget(this);
    }
    getId() {
      return "__renameInputWidget";
    }
    getDomNode() {
      if (!this._domNode) {
        this._domNode = document.createElement("div");
        this._domNode.className = "monaco-editor rename-box";
        this._domNode.appendChild(this._inputWithButton.domNode);
        this._renameCandidateListView = this._disposables.add(new RenameCandidateListView(this._domNode, {
          fontInfo: this._editor.getOption(
            59
            /* EditorOption.fontInfo */
          ),
          onFocusChange: (newSymbolName) => {
            this._inputWithButton.input.value = newSymbolName;
            this._isEditingRenameCandidate = false;
          },
          onSelectionChange: () => {
            this._isEditingRenameCandidate = false;
            this.acceptInput(false);
          }
        }));
        this._disposables.add(this._inputWithButton.onDidInputChange(() => {
          if (this._renameCandidateListView?.focusedCandidate !== void 0) {
            this._isEditingRenameCandidate = true;
          }
          this._timeBeforeFirstInputFieldEdit ??= this._beforeFirstInputFieldEditSW.elapsed();
          if (this._renameCandidateProvidersCts?.token.isCancellationRequested === false) {
            this._renameCandidateProvidersCts.cancel();
          }
          this._renameCandidateListView?.clearFocus();
        }));
        this._label = document.createElement("div");
        this._label.className = "rename-label";
        this._domNode.appendChild(this._label);
        this._updateFont();
        this._updateStyles(this._themeService.getColorTheme());
      }
      return this._domNode;
    }
    _updateStyles(theme) {
      if (!this._domNode) {
        return;
      }
      const widgetShadowColor = theme.getColor(widgetShadow);
      const widgetBorderColor = theme.getColor(widgetBorder);
      this._domNode.style.backgroundColor = String(theme.getColor(editorWidgetBackground) ?? "");
      this._domNode.style.boxShadow = widgetShadowColor ? ` 0 0 8px 2px ${widgetShadowColor}` : "";
      this._domNode.style.border = widgetBorderColor ? `1px solid ${widgetBorderColor}` : "";
      this._domNode.style.color = String(theme.getColor(inputForeground) ?? "");
      const border = theme.getColor(inputBorder);
      this._inputWithButton.domNode.style.backgroundColor = String(theme.getColor(inputBackground) ?? "");
      this._inputWithButton.input.style.backgroundColor = String(theme.getColor(inputBackground) ?? "");
      this._inputWithButton.domNode.style.borderWidth = border ? "1px" : "0px";
      this._inputWithButton.domNode.style.borderStyle = border ? "solid" : "none";
      this._inputWithButton.domNode.style.borderColor = border?.toString() ?? "none";
    }
    _updateFont() {
      if (this._domNode === void 0) {
        return;
      }
      assertType(this._label !== void 0, "RenameWidget#_updateFont: _label must not be undefined given _domNode is defined");
      this._editor.applyFontInfo(this._inputWithButton.input);
      const fontInfo = this._editor.getOption(
        59
        /* EditorOption.fontInfo */
      );
      this._label.style.fontSize = `${this._computeLabelFontSize(fontInfo.fontSize)}px`;
    }
    _computeLabelFontSize(editorFontSize) {
      return editorFontSize * 0.8;
    }
    getPosition() {
      if (!this._visible) {
        return null;
      }
      if (!this._editor.hasModel() || // @ulugbekna: shouldn't happen
      !this._editor.getDomNode()) {
        return null;
      }
      const bodyBox = getClientArea(this.getDomNode().ownerDocument.body);
      const editorBox = getDomNodePagePosition(this._editor.getDomNode());
      const cursorBoxTop = this._getTopForPosition();
      this._nPxAvailableAbove = cursorBoxTop + editorBox.top;
      this._nPxAvailableBelow = bodyBox.height - this._nPxAvailableAbove;
      const lineHeight = this._editor.getOption(
        75
        /* EditorOption.lineHeight */
      );
      const { totalHeight: candidateViewHeight } = RenameCandidateView.getLayoutInfo({ lineHeight });
      const positionPreference = this._nPxAvailableBelow > candidateViewHeight * 6 ? [
        2,
        1
        /* ContentWidgetPositionPreference.ABOVE */
      ] : [
        1,
        2
        /* ContentWidgetPositionPreference.BELOW */
      ];
      return {
        position: this._position,
        preference: positionPreference
      };
    }
    beforeRender() {
      const [accept, preview] = this._acceptKeybindings;
      this._label.innerText = localize(1393, "{0} to Rename, {1} to Preview", this._keybindingService.lookupKeybinding(accept)?.getLabel(), this._keybindingService.lookupKeybinding(preview)?.getLabel());
      this._domNode.style.minWidth = `200px`;
      return null;
    }
    afterRender(position) {
      if (position === null) {
        this.cancelInput(true, "afterRender (because position is null)");
        return;
      }
      if (!this._editor.hasModel() || // shouldn't happen
      !this._editor.getDomNode()) {
        return;
      }
      assertType(this._renameCandidateListView);
      assertType(this._nPxAvailableAbove !== void 0);
      assertType(this._nPxAvailableBelow !== void 0);
      const inputBoxHeight = getTotalHeight(this._inputWithButton.domNode);
      const labelHeight = getTotalHeight(this._label);
      let totalHeightAvailable;
      if (position === 2) {
        totalHeightAvailable = this._nPxAvailableBelow;
      } else {
        totalHeightAvailable = this._nPxAvailableAbove;
      }
      this._renameCandidateListView.layout({
        height: totalHeightAvailable - labelHeight - inputBoxHeight,
        width: getTotalWidth(this._inputWithButton.domNode)
      });
    }
    acceptInput(wantsPreview) {
      this._trace(`invoking acceptInput`);
      this._currentAcceptInput?.(wantsPreview);
    }
    cancelInput(focusEditor, caller) {
      this._currentCancelInput?.(focusEditor);
    }
    focusNextRenameSuggestion() {
      if (!this._renameCandidateListView?.focusNext()) {
        this._inputWithButton.input.value = this._currentName;
      }
    }
    focusPreviousRenameSuggestion() {
      if (!this._renameCandidateListView?.focusPrevious()) {
        this._inputWithButton.input.value = this._currentName;
      }
    }
    /**
     * @param requestRenameCandidates is `undefined` when there are no rename suggestion providers
     */
    getInput(where, currentName, supportPreview, requestRenameCandidates, cts) {
      const { start: selectionStart, end: selectionEnd } = this._getSelection(where, currentName);
      this._renameCts = cts;
      const disposeOnDone = new DisposableStore();
      this._nRenameSuggestionsInvocations = 0;
      this._hadAutomaticRenameSuggestionsInvocation = false;
      if (requestRenameCandidates === void 0) {
        this._inputWithButton.button.style.display = "none";
      } else {
        this._inputWithButton.button.style.display = "flex";
        this._requestRenameCandidatesOnce = requestRenameCandidates;
        this._requestRenameCandidates(currentName, false);
        disposeOnDone.add(addDisposableListener(this._inputWithButton.button, "click", () => this._requestRenameCandidates(currentName, true)));
        disposeOnDone.add(addDisposableListener(this._inputWithButton.button, EventType$1.KEY_DOWN, (e) => {
          const keyEvent = new StandardKeyboardEvent(e);
          if (keyEvent.equals(
            3
            /* KeyCode.Enter */
          ) || keyEvent.equals(
            10
            /* KeyCode.Space */
          )) {
            keyEvent.stopPropagation();
            keyEvent.preventDefault();
            this._requestRenameCandidates(currentName, true);
          }
        }));
      }
      this._isEditingRenameCandidate = false;
      this._domNode.classList.toggle("preview", supportPreview);
      this._position = new Position$1(where.startLineNumber, where.startColumn);
      this._currentName = currentName;
      this._inputWithButton.input.value = currentName;
      this._inputWithButton.input.setAttribute("selectionStart", selectionStart.toString());
      this._inputWithButton.input.setAttribute("selectionEnd", selectionEnd.toString());
      this._inputWithButton.input.size = Math.max((where.endColumn - where.startColumn) * 1.1, 20);
      this._beforeFirstInputFieldEditSW.reset();
      disposeOnDone.add(toDisposable(() => {
        this._renameCts = void 0;
        cts.dispose(true);
      }));
      disposeOnDone.add(toDisposable(() => {
        if (this._renameCandidateProvidersCts !== void 0) {
          this._renameCandidateProvidersCts.dispose(true);
          this._renameCandidateProvidersCts = void 0;
        }
      }));
      disposeOnDone.add(toDisposable(() => this._candidates.clear()));
      const inputResult = new DeferredPromise();
      inputResult.p.finally(() => {
        disposeOnDone.dispose();
        this._hide();
      });
      this._currentCancelInput = (focusEditor) => {
        this._trace("invoking _currentCancelInput");
        this._currentAcceptInput = void 0;
        this._currentCancelInput = void 0;
        this._renameCandidateListView?.clearCandidates();
        inputResult.complete(focusEditor);
        return true;
      };
      this._currentAcceptInput = (wantsPreview) => {
        this._trace("invoking _currentAcceptInput");
        assertType(this._renameCandidateListView !== void 0);
        const nRenameSuggestions = this._renameCandidateListView.nCandidates;
        let newName;
        let source;
        const focusedCandidate = this._renameCandidateListView.focusedCandidate;
        if (focusedCandidate !== void 0) {
          this._trace("using new name from renameSuggestion");
          newName = focusedCandidate;
          source = { k: "renameSuggestion" };
        } else {
          this._trace("using new name from inputField");
          newName = this._inputWithButton.input.value;
          source = this._isEditingRenameCandidate ? { k: "userEditedRenameSuggestion" } : { k: "inputField" };
        }
        if (newName === currentName || newName.trim().length === 0) {
          this.cancelInput(true, "_currentAcceptInput (because newName === value || newName.trim().length === 0)");
          return;
        }
        this._currentAcceptInput = void 0;
        this._currentCancelInput = void 0;
        this._renameCandidateListView.clearCandidates();
        inputResult.complete({
          newName,
          wantsPreview: supportPreview && wantsPreview,
          stats: {
            source,
            nRenameSuggestions,
            timeBeforeFirstInputFieldEdit: this._timeBeforeFirstInputFieldEdit,
            nRenameSuggestionsInvocations: this._nRenameSuggestionsInvocations,
            hadAutomaticRenameSuggestionsInvocation: this._hadAutomaticRenameSuggestionsInvocation
          }
        });
      };
      disposeOnDone.add(cts.token.onCancellationRequested(() => this.cancelInput(true, "cts.token.onCancellationRequested")));
      {
        disposeOnDone.add(this._editor.onDidBlurEditorWidget(() => this.cancelInput(!this._domNode?.ownerDocument.hasFocus(), "editor.onDidBlurEditorWidget")));
      }
      this._show();
      return inputResult.p;
    }
    _requestRenameCandidates(currentName, isManuallyTriggered) {
      if (this._requestRenameCandidatesOnce === void 0) {
        return;
      }
      if (this._renameCandidateProvidersCts !== void 0) {
        this._renameCandidateProvidersCts.dispose(true);
      }
      assertType(this._renameCts);
      if (this._inputWithButton.buttonState !== "stop") {
        this._renameCandidateProvidersCts = new CancellationTokenSource$1();
        const triggerKind = isManuallyTriggered ? NewSymbolNameTriggerKind$1.Invoke : NewSymbolNameTriggerKind$1.Automatic;
        const candidates = this._requestRenameCandidatesOnce(triggerKind, this._renameCandidateProvidersCts.token);
        if (candidates.length === 0) {
          this._inputWithButton.setSparkleButton();
          return;
        }
        if (!isManuallyTriggered) {
          this._hadAutomaticRenameSuggestionsInvocation = true;
        }
        this._nRenameSuggestionsInvocations += 1;
        this._inputWithButton.setStopButton();
        this._updateRenameCandidates(candidates, currentName, this._renameCts.token);
      }
    }
    /**
     * This allows selecting only part of the symbol name in the input field based on the selection in the editor
     */
    _getSelection(where, currentName) {
      assertType(this._editor.hasModel());
      const selection = this._editor.getSelection();
      let start = 0;
      let end = currentName.length;
      if (!Range$2.isEmpty(selection) && !Range$2.spansMultipleLines(selection) && Range$2.containsRange(where, selection)) {
        start = Math.max(0, selection.startColumn - where.startColumn);
        end = Math.min(where.endColumn, selection.endColumn) - where.startColumn;
      }
      return { start, end };
    }
    _show() {
      this._trace("invoking _show");
      this._editor.revealLineInCenterIfOutsideViewport(
        this._position.lineNumber,
        0
        /* ScrollType.Smooth */
      );
      this._visible = true;
      this._visibleContextKey.set(true);
      this._editor.layoutContentWidget(this);
      setTimeout(() => {
        this._inputWithButton.input.focus();
        this._inputWithButton.input.setSelectionRange(parseInt(this._inputWithButton.input.getAttribute("selectionStart")), parseInt(this._inputWithButton.input.getAttribute("selectionEnd")));
      }, 100);
    }
    async _updateRenameCandidates(candidates, currentName, token) {
      const trace = (...args) => this._trace("_updateRenameCandidates", ...args);
      trace("start");
      const namesListResults = await raceCancellation(Promise.allSettled(candidates), token);
      this._inputWithButton.setSparkleButton();
      if (namesListResults === void 0) {
        trace("returning early - received updateRenameCandidates results - undefined");
        return;
      }
      const newNames = namesListResults.flatMap((namesListResult) => namesListResult.status === "fulfilled" && isDefined(namesListResult.value) ? namesListResult.value : []);
      trace(`received updateRenameCandidates results - total (unfiltered) ${newNames.length} candidates.`);
      const distinctNames = distinct(newNames, (v) => v.newSymbolName);
      trace(`distinct candidates - ${distinctNames.length} candidates.`);
      const validDistinctNames = distinctNames.filter(({ newSymbolName }) => newSymbolName.trim().length > 0 && newSymbolName !== this._inputWithButton.input.value && newSymbolName !== currentName && !this._candidates.has(newSymbolName));
      trace(`valid distinct candidates - ${newNames.length} candidates.`);
      validDistinctNames.forEach((n2) => this._candidates.add(n2.newSymbolName));
      if (validDistinctNames.length < 1) {
        trace("returning early - no valid distinct candidates");
        return;
      }
      trace("setting candidates");
      this._renameCandidateListView.setCandidates(validDistinctNames);
      trace("asking editor to re-layout");
      this._editor.layoutContentWidget(this);
    }
    _hide() {
      this._trace("invoked _hide");
      this._visible = false;
      this._visibleContextKey.reset();
      this._editor.layoutContentWidget(this);
    }
    _getTopForPosition() {
      const visibleRanges = this._editor.getVisibleRanges();
      let firstLineInViewport;
      if (visibleRanges.length > 0) {
        firstLineInViewport = visibleRanges[0].startLineNumber;
      } else {
        this._logService.warn("RenameWidget#_getTopForPosition: this should not happen - visibleRanges is empty");
        firstLineInViewport = Math.max(1, this._position.lineNumber - 5);
      }
      return this._editor.getTopForLineNumber(this._position.lineNumber) - this._editor.getTopForLineNumber(firstLineInViewport);
    }
    _trace(...args) {
      this._logService.trace("RenameWidget", ...args);
    }
  };
  RenameWidget = __decorate$T([
    __param$S(2, IThemeService),
    __param$S(3, IKeybindingService),
    __param$S(4, IContextKeyService),
    __param$S(5, ILogService)
  ], RenameWidget);
  class RenameCandidateListView {
    // FIXME@ulugbekna: rewrite using event emitters
    constructor(parent, opts) {
      this._disposables = new DisposableStore();
      this._availableHeight = 0;
      this._minimumWidth = 0;
      this._lineHeight = opts.fontInfo.lineHeight;
      this._typicalHalfwidthCharacterWidth = opts.fontInfo.typicalHalfwidthCharacterWidth;
      this._listContainer = document.createElement("div");
      this._listContainer.className = "rename-box rename-candidate-list-container";
      parent.appendChild(this._listContainer);
      this._listWidget = RenameCandidateListView._createListWidget(this._listContainer, this._candidateViewHeight, opts.fontInfo);
      this._disposables.add(this._listWidget.onDidChangeFocus((e) => {
        if (e.elements.length === 1) {
          opts.onFocusChange(e.elements[0].newSymbolName);
        }
      }, this._disposables));
      this._disposables.add(this._listWidget.onDidChangeSelection((e) => {
        if (e.elements.length === 1) {
          opts.onSelectionChange();
        }
      }, this._disposables));
      this._disposables.add(this._listWidget.onDidBlur((e) => {
        this._listWidget.setFocus([]);
      }));
      this._listWidget.style(getListStyles({
        listInactiveFocusForeground: quickInputListFocusForeground,
        listInactiveFocusBackground: quickInputListFocusBackground
      }));
    }
    dispose() {
      this._listWidget.dispose();
      this._disposables.dispose();
    }
    // height - max height allowed by parent element
    layout({ height, width: width2 }) {
      this._availableHeight = height;
      this._minimumWidth = width2;
    }
    setCandidates(candidates) {
      this._listWidget.splice(0, 0, candidates);
      const height = this._pickListHeight(this._listWidget.length);
      const width2 = this._pickListWidth(candidates);
      this._listWidget.layout(height, width2);
      this._listContainer.style.height = `${height}px`;
      this._listContainer.style.width = `${width2}px`;
      status(localize(1394, "Received {0} rename suggestions", candidates.length));
    }
    clearCandidates() {
      this._listContainer.style.height = "0px";
      this._listContainer.style.width = "0px";
      this._listWidget.splice(0, this._listWidget.length, []);
    }
    get nCandidates() {
      return this._listWidget.length;
    }
    get focusedCandidate() {
      if (this._listWidget.length === 0) {
        return;
      }
      const selectedElement = this._listWidget.getSelectedElements()[0];
      if (selectedElement !== void 0) {
        return selectedElement.newSymbolName;
      }
      const focusedElement = this._listWidget.getFocusedElements()[0];
      if (focusedElement !== void 0) {
        return focusedElement.newSymbolName;
      }
      return;
    }
    focusNext() {
      if (this._listWidget.length === 0) {
        return false;
      }
      const focusedIxs = this._listWidget.getFocus();
      if (focusedIxs.length === 0) {
        this._listWidget.focusFirst();
        this._listWidget.reveal(0);
        return true;
      } else {
        if (focusedIxs[0] === this._listWidget.length - 1) {
          this._listWidget.setFocus([]);
          this._listWidget.reveal(0);
          return false;
        } else {
          this._listWidget.focusNext();
          const focused = this._listWidget.getFocus()[0];
          this._listWidget.reveal(focused);
          return true;
        }
      }
    }
    /**
     * @returns true if focus is moved to previous element
     */
    focusPrevious() {
      if (this._listWidget.length === 0) {
        return false;
      }
      const focusedIxs = this._listWidget.getFocus();
      if (focusedIxs.length === 0) {
        this._listWidget.focusLast();
        const focused = this._listWidget.getFocus()[0];
        this._listWidget.reveal(focused);
        return true;
      } else {
        if (focusedIxs[0] === 0) {
          this._listWidget.setFocus([]);
          return false;
        } else {
          this._listWidget.focusPrevious();
          const focused = this._listWidget.getFocus()[0];
          this._listWidget.reveal(focused);
          return true;
        }
      }
    }
    clearFocus() {
      this._listWidget.setFocus([]);
    }
    get _candidateViewHeight() {
      const { totalHeight } = RenameCandidateView.getLayoutInfo({ lineHeight: this._lineHeight });
      return totalHeight;
    }
    _pickListHeight(nCandidates) {
      const heightToFitAllCandidates = this._candidateViewHeight * nCandidates;
      const MAX_N_CANDIDATES = 7;
      const height = Math.min(heightToFitAllCandidates, this._availableHeight, this._candidateViewHeight * MAX_N_CANDIDATES);
      return height;
    }
    _pickListWidth(candidates) {
      const longestCandidateWidth = Math.ceil(Math.max(...candidates.map((c) => c.newSymbolName.length)) * this._typicalHalfwidthCharacterWidth);
      const width2 = Math.max(
        this._minimumWidth,
        4 + 16 + 5 + longestCandidateWidth + 10
        /* (possibly visible) scrollbar width */
        // TODO@ulugbekna: approximate calc - clean this up
      );
      return width2;
    }
    static _createListWidget(container, candidateViewHeight, fontInfo) {
      const virtualDelegate = new class {
        getTemplateId(element) {
          return "candidate";
        }
        getHeight(element) {
          return candidateViewHeight;
        }
      }();
      const renderer = new class {
        constructor() {
          this.templateId = "candidate";
        }
        renderTemplate(container2) {
          return new RenameCandidateView(container2, fontInfo);
        }
        renderElement(candidate, index, templateData) {
          templateData.populate(candidate);
        }
        disposeTemplate(templateData) {
          templateData.dispose();
        }
      }();
      return new List("NewSymbolNameCandidates", container, virtualDelegate, [renderer], {
        keyboardSupport: false,
        // @ulugbekna: because we handle keyboard events through proper commands & keybinding service, see `rename.ts`
        mouseSupport: true,
        multipleSelectionSupport: false
      });
    }
  }
  class InputWithButton {
    constructor() {
      this._buttonHoverContent = "";
      this._onDidInputChange = new Emitter$1();
      this.onDidInputChange = this._onDidInputChange.event;
      this._disposables = new DisposableStore();
    }
    get domNode() {
      if (!this._domNode) {
        this._domNode = document.createElement("div");
        this._domNode.className = "rename-input-with-button";
        this._domNode.style.display = "flex";
        this._domNode.style.flexDirection = "row";
        this._domNode.style.alignItems = "center";
        this._inputNode = document.createElement("input");
        this._inputNode.className = "rename-input";
        this._inputNode.type = "text";
        this._inputNode.style.border = "none";
        this._inputNode.setAttribute("aria-label", localize(1395, "Rename input. Type new name and press Enter to commit."));
        this._domNode.appendChild(this._inputNode);
        this._buttonNode = document.createElement("div");
        this._buttonNode.className = "rename-suggestions-button";
        this._buttonNode.setAttribute("tabindex", "0");
        this._buttonGenHoverText = localize(1396, "Generate New Name Suggestions");
        this._buttonCancelHoverText = localize(1397, "Cancel");
        this._buttonHoverContent = this._buttonGenHoverText;
        this._disposables.add(getBaseLayerHoverDelegate().setupDelayedHover(this._buttonNode, () => ({
          content: this._buttonHoverContent,
          style: 1
        })));
        this._domNode.appendChild(this._buttonNode);
        this._disposables.add(addDisposableListener(this.input, EventType$1.INPUT, () => this._onDidInputChange.fire()));
        this._disposables.add(addDisposableListener(this.input, EventType$1.KEY_DOWN, (e) => {
          const keyEvent = new StandardKeyboardEvent(e);
          if (keyEvent.keyCode === 15 || keyEvent.keyCode === 17) {
            this._onDidInputChange.fire();
          }
        }));
        this._disposables.add(addDisposableListener(this.input, EventType$1.CLICK, () => this._onDidInputChange.fire()));
        this._disposables.add(addDisposableListener(this.input, EventType$1.FOCUS, () => {
          this.domNode.style.outlineWidth = "1px";
          this.domNode.style.outlineStyle = "solid";
          this.domNode.style.outlineOffset = "-1px";
          this.domNode.style.outlineColor = "var(--vscode-focusBorder)";
        }));
        this._disposables.add(addDisposableListener(this.input, EventType$1.BLUR, () => {
          this.domNode.style.outline = "none";
        }));
      }
      return this._domNode;
    }
    get input() {
      assertType(this._inputNode);
      return this._inputNode;
    }
    get button() {
      assertType(this._buttonNode);
      return this._buttonNode;
    }
    get buttonState() {
      return this._buttonState;
    }
    setSparkleButton() {
      this._buttonState = "sparkle";
      this._sparkleIcon ??= renderIcon(Codicon.sparkle);
      clearNode(this.button);
      this.button.appendChild(this._sparkleIcon);
      this.button.setAttribute("aria-label", "Generating new name suggestions");
      this._buttonHoverContent = this._buttonGenHoverText;
      this.input.focus();
    }
    setStopButton() {
      this._buttonState = "stop";
      this._stopIcon ??= renderIcon(Codicon.stopCircle);
      clearNode(this.button);
      this.button.appendChild(this._stopIcon);
      this.button.setAttribute("aria-label", "Cancel generating new name suggestions");
      this._buttonHoverContent = this._buttonCancelHoverText;
      this.input.focus();
    }
    dispose() {
      this._disposables.dispose();
    }
  }
  const _RenameCandidateView = class _RenameCandidateView {
    constructor(parent, fontInfo) {
      this._domNode = document.createElement("div");
      this._domNode.className = "rename-box rename-candidate";
      this._domNode.style.display = `flex`;
      this._domNode.style.columnGap = `5px`;
      this._domNode.style.alignItems = `center`;
      this._domNode.style.height = `${fontInfo.lineHeight}px`;
      this._domNode.style.padding = `${_RenameCandidateView._PADDING}px`;
      const iconContainer = document.createElement("div");
      iconContainer.style.display = `flex`;
      iconContainer.style.alignItems = `center`;
      iconContainer.style.width = iconContainer.style.height = `${fontInfo.lineHeight * 0.8}px`;
      this._domNode.appendChild(iconContainer);
      this._icon = renderIcon(Codicon.sparkle);
      this._icon.style.display = `none`;
      iconContainer.appendChild(this._icon);
      this._label = document.createElement("div");
      applyFontInfo(this._label, fontInfo);
      this._domNode.appendChild(this._label);
      parent.appendChild(this._domNode);
    }
    populate(value) {
      this._updateIcon(value);
      this._updateLabel(value);
    }
    _updateIcon(value) {
      const isAIGenerated = !!value.tags?.includes(NewSymbolNameTag$1.AIGenerated);
      this._icon.style.display = isAIGenerated ? "inherit" : "none";
    }
    _updateLabel(value) {
      this._label.innerText = value.newSymbolName;
    }
    static getLayoutInfo({ lineHeight }) {
      const totalHeight = lineHeight + _RenameCandidateView._PADDING * 2;
      return { totalHeight };
    }
    dispose() {
    }
  };
  _RenameCandidateView._PADDING = 2;
  let RenameCandidateView = _RenameCandidateView;
  var __decorate$S = 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$R = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  var RenameController_1;
  class RenameSkeleton {
    constructor(model, position, registry) {
      this.model = model;
      this.position = position;
      this._providerRenameIdx = 0;
      this._providers = registry.ordered(model);
    }
    hasProvider() {
      return this._providers.length > 0;
    }
    async resolveRenameLocation(token) {
      const rejects = [];
      for (this._providerRenameIdx = 0; this._providerRenameIdx < this._providers.length; this._providerRenameIdx++) {
        const provider = this._providers[this._providerRenameIdx];
        if (!provider.resolveRenameLocation) {
          break;
        }
        const res = await provider.resolveRenameLocation(this.model, this.position, token);
        if (!res) {
          continue;
        }
        if (res.rejectReason) {
          rejects.push(res.rejectReason);
          continue;
        }
        return res;
      }
      this._providerRenameIdx = 0;
      const word = this.model.getWordAtPosition(this.position);
      if (!word) {
        return {
          range: Range$2.fromPositions(this.position),
          text: "",
          rejectReason: rejects.length > 0 ? rejects.join("\n") : void 0
        };
      }
      return {
        range: new Range$2(this.position.lineNumber, word.startColumn, this.position.lineNumber, word.endColumn),
        text: word.word,
        rejectReason: rejects.length > 0 ? rejects.join("\n") : void 0
      };
    }
    async provideRenameEdits(newName, token) {
      return this._provideRenameEdits(newName, this._providerRenameIdx, [], token);
    }
    async _provideRenameEdits(newName, i2, rejects, token) {
      const provider = this._providers[i2];
      if (!provider) {
        return {
          edits: [],
          rejectReason: rejects.join("\n")
        };
      }
      const result = await provider.provideRenameEdits(this.model, this.position, newName, token);
      if (!result) {
        return this._provideRenameEdits(newName, i2 + 1, rejects.concat(localize(1380, "No result.")), token);
      } else if (result.rejectReason) {
        return this._provideRenameEdits(newName, i2 + 1, rejects.concat(result.rejectReason), token);
      }
      return result;
    }
  }
  async function rename(registry, model, position, newName) {
    const skeleton = new RenameSkeleton(model, position, registry);
    const loc = await skeleton.resolveRenameLocation(CancellationToken.None);
    if (loc?.rejectReason) {
      return { edits: [], rejectReason: loc.rejectReason };
    }
    return skeleton.provideRenameEdits(newName, CancellationToken.None);
  }
  let RenameController = (_wa = class {
    static get(editor2) {
      return editor2.getContribution(RenameController_1.ID);
    }
    constructor(editor2, _instaService, _notificationService, _bulkEditService, _progressService, _logService, _configService, _languageFeaturesService) {
      this.editor = editor2;
      this._instaService = _instaService;
      this._notificationService = _notificationService;
      this._bulkEditService = _bulkEditService;
      this._progressService = _progressService;
      this._logService = _logService;
      this._configService = _configService;
      this._languageFeaturesService = _languageFeaturesService;
      this._disposableStore = new DisposableStore();
      this._cts = new CancellationTokenSource$1();
      this._renameWidget = this._disposableStore.add(this._instaService.createInstance(RenameWidget, this.editor, ["acceptRenameInput", "acceptRenameInputWithPreview"]));
    }
    dispose() {
      this._disposableStore.dispose();
      this._cts.dispose(true);
    }
    async run() {
      const trace = this._logService.trace.bind(this._logService, "[rename]");
      this._cts.dispose(true);
      this._cts = new CancellationTokenSource$1();
      if (!this.editor.hasModel()) {
        trace("editor has no model");
        return void 0;
      }
      const position = this.editor.getPosition();
      const skeleton = new RenameSkeleton(this.editor.getModel(), position, this._languageFeaturesService.renameProvider);
      if (!skeleton.hasProvider()) {
        trace("skeleton has no provider");
        return void 0;
      }
      const cts1 = new EditorStateCancellationTokenSource(this.editor, 4 | 1, void 0, this._cts.token);
      let loc;
      try {
        trace("resolving rename location");
        const resolveLocationOperation = skeleton.resolveRenameLocation(cts1.token);
        this._progressService.showWhile(resolveLocationOperation, 250);
        loc = await resolveLocationOperation;
        trace("resolved rename location");
      } catch (e) {
        if (e instanceof CancellationError) {
          trace("resolve rename location cancelled", JSON.stringify(e, null, "	"));
        } else {
          trace("resolve rename location failed", e instanceof Error ? e : JSON.stringify(e, null, "	"));
          if (typeof e === "string" || isMarkdownString(e)) {
            MessageController.get(this.editor)?.showMessage(e || localize(1381, "An unknown error occurred while resolving rename location"), position);
          }
        }
        return void 0;
      } finally {
        cts1.dispose();
      }
      if (!loc) {
        trace("returning early - no loc");
        return void 0;
      }
      if (loc.rejectReason) {
        trace(`returning early - rejected with reason: ${loc.rejectReason}`, loc.rejectReason);
        MessageController.get(this.editor)?.showMessage(loc.rejectReason, position);
        return void 0;
      }
      if (cts1.token.isCancellationRequested) {
        trace("returning early - cts1 cancelled");
        return void 0;
      }
      const cts2 = new EditorStateCancellationTokenSource(this.editor, 4 | 1, loc.range, this._cts.token);
      const model = this.editor.getModel();
      const newSymbolNamesProviders = this._languageFeaturesService.newSymbolNamesProvider.all(model);
      const resolvedNewSymbolnamesProviders = await Promise.all(newSymbolNamesProviders.map(async (p) => [p, await p.supportsAutomaticNewSymbolNamesTriggerKind ?? false]));
      const requestRenameSuggestions = (triggerKind, cts) => {
        let providers = resolvedNewSymbolnamesProviders.slice();
        if (triggerKind === NewSymbolNameTriggerKind$1.Automatic) {
          providers = providers.filter(([_, supportsAutomatic]) => supportsAutomatic);
        }
        return providers.map(([p]) => p.provideNewSymbolNames(model, loc.range, triggerKind, cts));
      };
      trace("creating rename input field and awaiting its result");
      const supportPreview = this._bulkEditService.hasPreviewHandler() && this._configService.getValue(this.editor.getModel().uri, "editor.rename.enablePreview");
      const inputFieldResult = await this._renameWidget.getInput(loc.range, loc.text, supportPreview, newSymbolNamesProviders.length > 0 ? requestRenameSuggestions : void 0, cts2);
      trace("received response from rename input field");
      if (typeof inputFieldResult === "boolean") {
        trace(`returning early - rename input field response - ${inputFieldResult}`);
        if (inputFieldResult) {
          this.editor.focus();
        }
        cts2.dispose();
        return void 0;
      }
      this.editor.focus();
      trace("requesting rename edits");
      const renameOperation = raceCancellation(skeleton.provideRenameEdits(inputFieldResult.newName, cts2.token), cts2.token).then(async (renameResult) => {
        if (!renameResult) {
          trace("returning early - no rename edits result");
          return;
        }
        if (!this.editor.hasModel()) {
          trace("returning early - no model after rename edits are provided");
          return;
        }
        if (renameResult.rejectReason) {
          trace(`returning early - rejected with reason: ${renameResult.rejectReason}`);
          this._notificationService.info(renameResult.rejectReason);
          return;
        }
        this.editor.setSelection(Range$2.fromPositions(this.editor.getSelection().getPosition()));
        trace("applying edits");
        this._bulkEditService.apply(renameResult, {
          editor: this.editor,
          showPreview: inputFieldResult.wantsPreview,
          label: localize(1382, "Renaming '{0}' to '{1}'", loc?.text, inputFieldResult.newName),
          code: "undoredo.rename",
          quotableLabel: localize(1383, "Renaming {0} to {1}", loc?.text, inputFieldResult.newName),
          respectAutoSaveConfig: true,
          reason: EditSources.rename()
        }).then((result) => {
          trace("edits applied");
          if (result.ariaSummary) {
            alert(localize(1384, "Successfully renamed '{0}' to '{1}'. Summary: {2}", loc.text, inputFieldResult.newName, result.ariaSummary));
          }
        }).catch((err) => {
          trace(`error when applying edits ${JSON.stringify(err, null, "	")}`);
          this._notificationService.error(localize(1385, "Rename failed to apply edits"));
          this._logService.error(err);
        });
      }, (err) => {
        trace("error when providing rename edits", JSON.stringify(err, null, "	"));
        this._notificationService.error(localize(1386, "Rename failed to compute edits"));
        this._logService.error(err);
      }).finally(() => {
        cts2.dispose();
      });
      trace("returning rename operation");
      this._progressService.showWhile(renameOperation, 250);
      return renameOperation;
    }
    acceptRenameInput(wantsPreview) {
      this._renameWidget.acceptInput(wantsPreview);
    }
    cancelRenameInput() {
      this._renameWidget.cancelInput(true, "cancelRenameInput command");
    }
    focusNextRenameSuggestion() {
      this._renameWidget.focusNextRenameSuggestion();
    }
    focusPreviousRenameSuggestion() {
      this._renameWidget.focusPreviousRenameSuggestion();
    }
  }, RenameController_1 = _wa, _wa.ID = "editor.contrib.renameController", _wa);
  RenameController = RenameController_1 = __decorate$S([
    __param$R(1, IInstantiationService),
    __param$R(2, INotificationService),
    __param$R(3, IBulkEditService),
    __param$R(4, IEditorProgressService),
    __param$R(5, ILogService),
    __param$R(6, ITextResourceConfigurationService),
    __param$R(7, ILanguageFeaturesService)
  ], RenameController);
  class RenameAction extends EditorAction {
    constructor() {
      super({
        id: "editor.action.rename",
        label: localize2(1388, "Rename Symbol"),
        precondition: ContextKeyExpr.and(EditorContextKeys.writable, EditorContextKeys.hasRenameProvider),
        kbOpts: {
          kbExpr: EditorContextKeys.editorTextFocus,
          primary: 60,
          weight: 100
          /* KeybindingWeight.EditorContrib */
        },
        contextMenuOpts: {
          group: "1_modification",
          order: 1.1
        },
        canTriggerInlineEdits: true
      });
    }
    runCommand(accessor, args) {
      const editorService = accessor.get(ICodeEditorService);
      const [uri, pos] = Array.isArray(args) && args || [void 0, void 0];
      if (URI.isUri(uri) && Position$1.isIPosition(pos)) {
        return editorService.openCodeEditor({ resource: uri }, editorService.getActiveCodeEditor()).then((editor2) => {
          if (!editor2) {
            return;
          }
          editor2.setPosition(pos);
          editor2.invokeWithinContext((accessor2) => {
            this.reportTelemetry(accessor2, editor2);
            return this.run(accessor2, editor2);
          });
        }, onUnexpectedError);
      }
      return super.runCommand(accessor, args);
    }
    run(accessor, editor2) {
      const logService = accessor.get(ILogService);
      const controller = RenameController.get(editor2);
      if (controller) {
        logService.trace("[RenameAction] got controller, running...");
        return controller.run();
      }
      logService.trace("[RenameAction] returning early - controller missing");
      return Promise.resolve();
    }
  }
  registerEditorContribution(
    RenameController.ID,
    RenameController,
    4
    /* EditorContributionInstantiation.Lazy */
  );
  registerEditorAction(RenameAction);
  const RenameCommand = EditorCommand.bindToContribution(RenameController.get);
  registerEditorCommand(new RenameCommand({
    id: "acceptRenameInput",
    precondition: CONTEXT_RENAME_INPUT_VISIBLE,
    handler: (x) => x.acceptRenameInput(false),
    kbOpts: {
      weight: 100 + 99,
      kbExpr: ContextKeyExpr.and(EditorContextKeys.focus, ContextKeyExpr.not("isComposing")),
      primary: 3
      /* KeyCode.Enter */
    }
  }));
  registerEditorCommand(new RenameCommand({
    id: "acceptRenameInputWithPreview",
    precondition: ContextKeyExpr.and(CONTEXT_RENAME_INPUT_VISIBLE, ContextKeyExpr.has("config.editor.rename.enablePreview")),
    handler: (x) => x.acceptRenameInput(true),
    kbOpts: {
      weight: 100 + 99,
      kbExpr: ContextKeyExpr.and(EditorContextKeys.focus, ContextKeyExpr.not("isComposing")),
      primary: 2048 + 3
      /* KeyCode.Enter */
    }
  }));
  registerEditorCommand(new RenameCommand({
    id: "cancelRenameInput",
    precondition: CONTEXT_RENAME_INPUT_VISIBLE,
    handler: (x) => x.cancelRenameInput(),
    kbOpts: {
      weight: 100 + 99,
      kbExpr: EditorContextKeys.focus,
      primary: 9,
      secondary: [
        1024 | 9
        /* KeyCode.Escape */
      ]
    }
  }));
  registerAction2(class FocusNextRenameSuggestion extends Action2 {
    constructor() {
      super({
        id: "focusNextRenameSuggestion",
        title: {
          ...localize2(1389, "Focus Next Rename Suggestion")
        },
        precondition: CONTEXT_RENAME_INPUT_VISIBLE,
        keybinding: [
          {
            primary: 18,
            weight: 100 + 99
          }
        ]
      });
    }
    run(accessor) {
      const currentEditor = accessor.get(ICodeEditorService).getFocusedCodeEditor();
      if (!currentEditor) {
        return;
      }
      const controller = RenameController.get(currentEditor);
      if (!controller) {
        return;
      }
      controller.focusNextRenameSuggestion();
    }
  });
  registerAction2(class FocusPreviousRenameSuggestion extends Action2 {
    constructor() {
      super({
        id: "focusPreviousRenameSuggestion",
        title: {
          ...localize2(1390, "Focus Previous Rename Suggestion")
        },
        precondition: CONTEXT_RENAME_INPUT_VISIBLE,
        keybinding: [
          {
            primary: 16,
            weight: 100 + 99
          }
        ]
      });
    }
    run(accessor) {
      const currentEditor = accessor.get(ICodeEditorService).getFocusedCodeEditor();
      if (!currentEditor) {
        return;
      }
      const controller = RenameController.get(currentEditor);
      if (!controller) {
        return;
      }
      controller.focusPreviousRenameSuggestion();
    }
  });
  registerModelAndPositionCommand("_executeDocumentRenameProvider", function(accessor, model, position, ...args) {
    const [newName] = args;
    assertType(typeof newName === "string");
    const { renameProvider } = accessor.get(ILanguageFeaturesService);
    return rename(renameProvider, model, position, newName);
  });
  registerModelAndPositionCommand("_executePrepareRename", async function(accessor, model, position) {
    const { renameProvider } = accessor.get(ILanguageFeaturesService);
    const skeleton = new RenameSkeleton(model, position, renameProvider);
    const loc = await skeleton.resolveRenameLocation(CancellationToken.None);
    if (loc?.rejectReason) {
      throw new Error(loc.rejectReason);
    }
    return loc;
  });
  Registry.as(Extensions$6.Configuration).registerConfiguration({
    id: "editor",
    properties: {
      "editor.rename.enablePreview": {
        scope: 6,
        description: localize(1387, "Enable/disable the ability to preview changes before renaming"),
        default: true,
        type: "boolean"
      }
    }
  });
  var __decorate$R = 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$Q = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  let SectionHeaderDetector = (_xa = class extends Disposable {
    constructor(editor2, languageConfigurationService, editorWorkerService) {
      super();
      this.editor = editor2;
      this.languageConfigurationService = languageConfigurationService;
      this.editorWorkerService = editorWorkerService;
      this.decorations = this.editor.createDecorationsCollection();
      this.options = this.createOptions(editor2.getOption(
        81
        /* EditorOption.minimap */
      ));
      this.computePromise = null;
      this.currentOccurrences = {};
      this._register(editor2.onDidChangeModel((e) => {
        this.currentOccurrences = {};
        this.options = this.createOptions(editor2.getOption(
          81
          /* EditorOption.minimap */
        ));
        this.stop();
        this.computeSectionHeaders.schedule(0);
      }));
      this._register(editor2.onDidChangeModelLanguage((e) => {
        this.currentOccurrences = {};
        this.options = this.createOptions(editor2.getOption(
          81
          /* EditorOption.minimap */
        ));
        this.stop();
        this.computeSectionHeaders.schedule(0);
      }));
      this._register(languageConfigurationService.onDidChange((e) => {
        const editorLanguageId = this.editor.getModel()?.getLanguageId();
        if (editorLanguageId && e.affects(editorLanguageId)) {
          this.currentOccurrences = {};
          this.options = this.createOptions(editor2.getOption(
            81
            /* EditorOption.minimap */
          ));
          this.stop();
          this.computeSectionHeaders.schedule(0);
        }
      }));
      this._register(editor2.onDidChangeConfiguration((e) => {
        if (this.options && !e.hasChanged(
          81
          /* EditorOption.minimap */
        )) {
          return;
        }
        this.options = this.createOptions(editor2.getOption(
          81
          /* EditorOption.minimap */
        ));
        this.updateDecorations([]);
        this.stop();
        this.computeSectionHeaders.schedule(0);
      }));
      this._register(this.editor.onDidChangeModelContent((e) => {
        this.computeSectionHeaders.schedule();
      }));
      this._register(editor2.onDidChangeModelTokens((e) => {
        if (!this.computeSectionHeaders.isScheduled()) {
          this.computeSectionHeaders.schedule(1e3);
        }
      }));
      this.computeSectionHeaders = this._register(new RunOnceScheduler(() => {
        this.findSectionHeaders();
      }, 250));
      this.computeSectionHeaders.schedule(0);
    }
    createOptions(minimap) {
      if (!minimap || !this.editor.hasModel()) {
        return void 0;
      }
      const languageId = this.editor.getModel().getLanguageId();
      if (!languageId) {
        return void 0;
      }
      const commentsConfiguration = this.languageConfigurationService.getLanguageConfiguration(languageId).comments;
      const foldingRules = this.languageConfigurationService.getLanguageConfiguration(languageId).foldingRules;
      if (!commentsConfiguration && !foldingRules?.markers) {
        return void 0;
      }
      return {
        foldingRules,
        markSectionHeaderRegex: minimap.markSectionHeaderRegex,
        findMarkSectionHeaders: minimap.showMarkSectionHeaders,
        findRegionSectionHeaders: minimap.showRegionSectionHeaders
      };
    }
    findSectionHeaders() {
      if (!this.editor.hasModel() || !this.options?.findMarkSectionHeaders && !this.options?.findRegionSectionHeaders) {
        return;
      }
      const model = this.editor.getModel();
      if (model.isDisposed() || model.isTooLargeForSyncing()) {
        return;
      }
      const modelVersionId = model.getVersionId();
      this.editorWorkerService.findSectionHeaders(model.uri, this.options).then((sectionHeaders) => {
        if (model.isDisposed() || model.getVersionId() !== modelVersionId) {
          return;
        }
        this.updateDecorations(sectionHeaders);
      });
    }
    updateDecorations(sectionHeaders) {
      const model = this.editor.getModel();
      if (model) {
        sectionHeaders = sectionHeaders.filter((sectionHeader) => {
          if (!sectionHeader.shouldBeInComments) {
            return true;
          }
          const validRange = model.validateRange(sectionHeader.range);
          const tokens = model.tokenization.getLineTokens(validRange.startLineNumber);
          const idx = tokens.findTokenIndexAtOffset(validRange.startColumn - 1);
          const tokenType = tokens.getStandardTokenType(idx);
          const languageId = tokens.getLanguageId(idx);
          return languageId === model.getLanguageId() && tokenType === 1;
        });
      }
      const oldDecorations = Object.values(this.currentOccurrences).map((occurrence) => occurrence.decorationId);
      const newDecorations = sectionHeaders.map((sectionHeader) => decoration(sectionHeader));
      this.editor.changeDecorations((changeAccessor) => {
        const decorations = changeAccessor.deltaDecorations(oldDecorations, newDecorations);
        this.currentOccurrences = {};
        for (let i2 = 0, len = decorations.length; i2 < len; i2++) {
          const occurrence = { sectionHeader: sectionHeaders[i2], decorationId: decorations[i2] };
          this.currentOccurrences[occurrence.decorationId] = occurrence;
        }
      });
    }
    stop() {
      this.computeSectionHeaders.cancel();
      if (this.computePromise) {
        this.computePromise.cancel();
        this.computePromise = null;
      }
    }
    dispose() {
      super.dispose();
      this.stop();
      this.decorations.clear();
    }
  }, _xa.ID = "editor.sectionHeaderDetector", _xa);
  SectionHeaderDetector = __decorate$R([
    __param$Q(1, ILanguageConfigurationService),
    __param$Q(2, IEditorWorkerService)
  ], SectionHeaderDetector);
  function decoration(sectionHeader) {
    return {
      range: sectionHeader.range,
      options: ModelDecorationOptions.createDynamic({
        description: "section-header",
        stickiness: 3,
        collapseOnReplaceEdit: true,
        minimap: {
          color: void 0,
          position: 1,
          sectionHeaderStyle: sectionHeader.hasSeparatorLine ? 2 : 1,
          sectionHeaderText: sectionHeader.text
        }
      })
    };
  }
  registerEditorContribution(
    SectionHeaderDetector.ID,
    SectionHeaderDetector,
    1
    /* EditorContributionInstantiation.AfterFirstRender */
  );
  class RateLimiter {
    constructor(timesPerSecond = 5) {
      this.timesPerSecond = timesPerSecond;
      this._lastRun = 0;
      this._minimumTimeBetweenRuns = 1e3 / timesPerSecond;
    }
    runIfNotLimited(callback) {
      const now = Date.now();
      if (now - this._lastRun >= this._minimumTimeBetweenRuns) {
        this._lastRun = now;
        callback();
      }
    }
  }
  class SparseMultilineTokens {
    static create(startLineNumber, tokens) {
      return new SparseMultilineTokens(startLineNumber, new SparseMultilineTokensStorage(tokens));
    }
    /**
     * (Inclusive) start line number for these tokens.
     */
    get startLineNumber() {
      return this._startLineNumber;
    }
    /**
     * (Inclusive) end line number for these tokens.
     */
    get endLineNumber() {
      return this._endLineNumber;
    }
    constructor(startLineNumber, tokens) {
      this._startLineNumber = startLineNumber;
      this._tokens = tokens;
      this._endLineNumber = this._startLineNumber + this._tokens.getMaxDeltaLine();
    }
    toString() {
      return this._tokens.toString(this._startLineNumber);
    }
    _updateEndLineNumber() {
      this._endLineNumber = this._startLineNumber + this._tokens.getMaxDeltaLine();
    }
    isEmpty() {
      return this._tokens.isEmpty();
    }
    getLineTokens(lineNumber) {
      if (this._startLineNumber <= lineNumber && lineNumber <= this._endLineNumber) {
        return this._tokens.getLineTokens(lineNumber - this._startLineNumber);
      }
      return null;
    }
    getRange() {
      const deltaRange = this._tokens.getRange();
      if (!deltaRange) {
        return deltaRange;
      }
      return new Range$2(this._startLineNumber + deltaRange.startLineNumber, deltaRange.startColumn, this._startLineNumber + deltaRange.endLineNumber, deltaRange.endColumn);
    }
    removeTokens(range2) {
      const startLineIndex = range2.startLineNumber - this._startLineNumber;
      const endLineIndex = range2.endLineNumber - this._startLineNumber;
      this._startLineNumber += this._tokens.removeTokens(startLineIndex, range2.startColumn - 1, endLineIndex, range2.endColumn - 1);
      this._updateEndLineNumber();
    }
    split(range2) {
      const startLineIndex = range2.startLineNumber - this._startLineNumber;
      const endLineIndex = range2.endLineNumber - this._startLineNumber;
      const [a, b, bDeltaLine] = this._tokens.split(startLineIndex, range2.startColumn - 1, endLineIndex, range2.endColumn - 1);
      return [new SparseMultilineTokens(this._startLineNumber, a), new SparseMultilineTokens(this._startLineNumber + bDeltaLine, b)];
    }
    applyEdit(range2, text2) {
      const [eolCount, firstLineLength, lastLineLength] = countEOL(text2);
      this.acceptEdit(
        range2,
        eolCount,
        firstLineLength,
        lastLineLength,
        text2.length > 0 ? text2.charCodeAt(0) : 0
        /* CharCode.Null */
      );
    }
    acceptEdit(range2, eolCount, firstLineLength, lastLineLength, firstCharCode) {
      this._acceptDeleteRange(range2);
      this._acceptInsertText(new Position$1(range2.startLineNumber, range2.startColumn), eolCount, firstLineLength, lastLineLength, firstCharCode);
      this._updateEndLineNumber();
    }
    _acceptDeleteRange(range2) {
      if (range2.startLineNumber === range2.endLineNumber && range2.startColumn === range2.endColumn) {
        return;
      }
      const firstLineIndex = range2.startLineNumber - this._startLineNumber;
      const lastLineIndex = range2.endLineNumber - this._startLineNumber;
      if (lastLineIndex < 0) {
        const deletedLinesCount = lastLineIndex - firstLineIndex;
        this._startLineNumber -= deletedLinesCount;
        return;
      }
      const tokenMaxDeltaLine = this._tokens.getMaxDeltaLine();
      if (firstLineIndex >= tokenMaxDeltaLine + 1) {
        return;
      }
      if (firstLineIndex < 0 && lastLineIndex >= tokenMaxDeltaLine + 1) {
        this._startLineNumber = 0;
        this._tokens.clear();
        return;
      }
      if (firstLineIndex < 0) {
        const deletedBefore = -firstLineIndex;
        this._startLineNumber -= deletedBefore;
        this._tokens.acceptDeleteRange(range2.startColumn - 1, 0, 0, lastLineIndex, range2.endColumn - 1);
      } else {
        this._tokens.acceptDeleteRange(0, firstLineIndex, range2.startColumn - 1, lastLineIndex, range2.endColumn - 1);
      }
    }
    _acceptInsertText(position, eolCount, firstLineLength, lastLineLength, firstCharCode) {
      if (eolCount === 0 && firstLineLength === 0) {
        return;
      }
      const lineIndex = position.lineNumber - this._startLineNumber;
      if (lineIndex < 0) {
        this._startLineNumber += eolCount;
        return;
      }
      const tokenMaxDeltaLine = this._tokens.getMaxDeltaLine();
      if (lineIndex >= tokenMaxDeltaLine + 1) {
        return;
      }
      this._tokens.acceptInsertText(lineIndex, position.column - 1, eolCount, firstLineLength, lastLineLength, firstCharCode);
    }
    reportIfInvalid(model) {
      this._tokens.reportIfInvalid(model, this._startLineNumber);
    }
  }
  const _SparseMultilineTokensStorage = class _SparseMultilineTokensStorage {
    constructor(tokens) {
      this._tokens = tokens;
      this._tokenCount = tokens.length / 4;
    }
    toString(startLineNumber) {
      const pieces = [];
      for (let i2 = 0; i2 < this._tokenCount; i2++) {
        pieces.push(`(${this._getDeltaLine(i2) + startLineNumber},${this._getStartCharacter(i2)}-${this._getEndCharacter(i2)})`);
      }
      return `[${pieces.join(",")}]`;
    }
    getMaxDeltaLine() {
      const tokenCount = this._getTokenCount();
      if (tokenCount === 0) {
        return -1;
      }
      return this._getDeltaLine(tokenCount - 1);
    }
    getRange() {
      const tokenCount = this._getTokenCount();
      if (tokenCount === 0) {
        return null;
      }
      const startChar = this._getStartCharacter(0);
      const maxDeltaLine = this._getDeltaLine(tokenCount - 1);
      const endChar = this._getEndCharacter(tokenCount - 1);
      return new Range$2(0, startChar + 1, maxDeltaLine, endChar + 1);
    }
    _getTokenCount() {
      return this._tokenCount;
    }
    _getDeltaLine(tokenIndex) {
      return this._tokens[4 * tokenIndex];
    }
    _getStartCharacter(tokenIndex) {
      return this._tokens[4 * tokenIndex + 1];
    }
    _getEndCharacter(tokenIndex) {
      return this._tokens[4 * tokenIndex + 2];
    }
    isEmpty() {
      return this._getTokenCount() === 0;
    }
    getLineTokens(deltaLine) {
      let low = 0;
      let high = this._getTokenCount() - 1;
      while (low < high) {
        const mid = low + Math.floor((high - low) / 2);
        const midDeltaLine = this._getDeltaLine(mid);
        if (midDeltaLine < deltaLine) {
          low = mid + 1;
        } else if (midDeltaLine > deltaLine) {
          high = mid - 1;
        } else {
          let min = mid;
          while (min > low && this._getDeltaLine(min - 1) === deltaLine) {
            min--;
          }
          let max = mid;
          while (max < high && this._getDeltaLine(max + 1) === deltaLine) {
            max++;
          }
          return new SparseLineTokens(this._tokens.subarray(4 * min, 4 * max + 4));
        }
      }
      if (this._getDeltaLine(low) === deltaLine) {
        return new SparseLineTokens(this._tokens.subarray(4 * low, 4 * low + 4));
      }
      return null;
    }
    clear() {
      this._tokenCount = 0;
    }
    removeTokens(startDeltaLine, startChar, endDeltaLine, endChar) {
      const tokens = this._tokens;
      const tokenCount = this._tokenCount;
      let newTokenCount = 0;
      let hasDeletedTokens = false;
      let firstDeltaLine = 0;
      for (let i2 = 0; i2 < tokenCount; i2++) {
        const srcOffset = 4 * i2;
        const tokenDeltaLine = tokens[srcOffset];
        const tokenStartCharacter = tokens[srcOffset + 1];
        const tokenEndCharacter = tokens[srcOffset + 2];
        const tokenMetadata = tokens[srcOffset + 3];
        if ((tokenDeltaLine > startDeltaLine || tokenDeltaLine === startDeltaLine && tokenEndCharacter >= startChar) && (tokenDeltaLine < endDeltaLine || tokenDeltaLine === endDeltaLine && tokenStartCharacter <= endChar)) {
          hasDeletedTokens = true;
        } else {
          if (newTokenCount === 0) {
            firstDeltaLine = tokenDeltaLine;
          }
          if (hasDeletedTokens) {
            const destOffset = 4 * newTokenCount;
            tokens[destOffset] = tokenDeltaLine - firstDeltaLine;
            tokens[destOffset + 1] = tokenStartCharacter;
            tokens[destOffset + 2] = tokenEndCharacter;
            tokens[destOffset + 3] = tokenMetadata;
          } else if (firstDeltaLine !== 0) {
            tokens[srcOffset] = tokenDeltaLine - firstDeltaLine;
          }
          newTokenCount++;
        }
      }
      this._tokenCount = newTokenCount;
      return firstDeltaLine;
    }
    split(startDeltaLine, startChar, endDeltaLine, endChar) {
      const tokens = this._tokens;
      const tokenCount = this._tokenCount;
      const aTokens = [];
      const bTokens = [];
      let destTokens = aTokens;
      let destOffset = 0;
      let destFirstDeltaLine = 0;
      for (let i2 = 0; i2 < tokenCount; i2++) {
        const srcOffset = 4 * i2;
        const tokenDeltaLine = tokens[srcOffset];
        const tokenStartCharacter = tokens[srcOffset + 1];
        const tokenEndCharacter = tokens[srcOffset + 2];
        const tokenMetadata = tokens[srcOffset + 3];
        if (tokenDeltaLine > startDeltaLine || tokenDeltaLine === startDeltaLine && tokenEndCharacter >= startChar) {
          if (tokenDeltaLine < endDeltaLine || tokenDeltaLine === endDeltaLine && tokenStartCharacter <= endChar) {
            continue;
          } else {
            if (destTokens !== bTokens) {
              destTokens = bTokens;
              destOffset = 0;
              destFirstDeltaLine = tokenDeltaLine;
            }
          }
        }
        destTokens[destOffset++] = tokenDeltaLine - destFirstDeltaLine;
        destTokens[destOffset++] = tokenStartCharacter;
        destTokens[destOffset++] = tokenEndCharacter;
        destTokens[destOffset++] = tokenMetadata;
      }
      return [new _SparseMultilineTokensStorage(new Uint32Array(aTokens)), new _SparseMultilineTokensStorage(new Uint32Array(bTokens)), destFirstDeltaLine];
    }
    acceptDeleteRange(horizontalShiftForFirstLineTokens, startDeltaLine, startCharacter, endDeltaLine, endCharacter) {
      const tokens = this._tokens;
      const tokenCount = this._tokenCount;
      const deletedLineCount = endDeltaLine - startDeltaLine;
      let newTokenCount = 0;
      let hasDeletedTokens = false;
      for (let i2 = 0; i2 < tokenCount; i2++) {
        const srcOffset = 4 * i2;
        let tokenDeltaLine = tokens[srcOffset];
        let tokenStartCharacter = tokens[srcOffset + 1];
        let tokenEndCharacter = tokens[srcOffset + 2];
        const tokenMetadata = tokens[srcOffset + 3];
        if (tokenDeltaLine < startDeltaLine || tokenDeltaLine === startDeltaLine && tokenEndCharacter <= startCharacter) {
          newTokenCount++;
          continue;
        } else if (tokenDeltaLine === startDeltaLine && tokenStartCharacter < startCharacter) {
          if (tokenDeltaLine === endDeltaLine && tokenEndCharacter > endCharacter) {
            tokenEndCharacter -= endCharacter - startCharacter;
          } else {
            tokenEndCharacter = startCharacter;
          }
        } else if (tokenDeltaLine === startDeltaLine && tokenStartCharacter === startCharacter) {
          if (tokenDeltaLine === endDeltaLine && tokenEndCharacter > endCharacter) {
            tokenEndCharacter -= endCharacter - startCharacter;
          } else {
            hasDeletedTokens = true;
            continue;
          }
        } else if (tokenDeltaLine < endDeltaLine || tokenDeltaLine === endDeltaLine && tokenStartCharacter < endCharacter) {
          if (tokenDeltaLine === endDeltaLine && tokenEndCharacter > endCharacter) {
            tokenDeltaLine = startDeltaLine;
            tokenStartCharacter = startCharacter;
            tokenEndCharacter = tokenStartCharacter + (tokenEndCharacter - endCharacter);
          } else {
            hasDeletedTokens = true;
            continue;
          }
        } else if (tokenDeltaLine > endDeltaLine) {
          if (deletedLineCount === 0 && !hasDeletedTokens) {
            newTokenCount = tokenCount;
            break;
          }
          tokenDeltaLine -= deletedLineCount;
        } else if (tokenDeltaLine === endDeltaLine && tokenStartCharacter >= endCharacter) {
          if (horizontalShiftForFirstLineTokens && tokenDeltaLine === 0) {
            tokenStartCharacter += horizontalShiftForFirstLineTokens;
            tokenEndCharacter += horizontalShiftForFirstLineTokens;
          }
          tokenDeltaLine -= deletedLineCount;
          tokenStartCharacter -= endCharacter - startCharacter;
          tokenEndCharacter -= endCharacter - startCharacter;
        } else {
          throw new Error(`Not possible!`);
        }
        const destOffset = 4 * newTokenCount;
        tokens[destOffset] = tokenDeltaLine;
        tokens[destOffset + 1] = tokenStartCharacter;
        tokens[destOffset + 2] = tokenEndCharacter;
        tokens[destOffset + 3] = tokenMetadata;
        newTokenCount++;
      }
      this._tokenCount = newTokenCount;
    }
    acceptInsertText(deltaLine, character, eolCount, firstLineLength, lastLineLength, firstCharCode) {
      const isInsertingPreciselyOneWordCharacter = eolCount === 0 && firstLineLength === 1 && (firstCharCode >= 48 && firstCharCode <= 57 || firstCharCode >= 65 && firstCharCode <= 90 || firstCharCode >= 97 && firstCharCode <= 122);
      const tokens = this._tokens;
      const tokenCount = this._tokenCount;
      for (let i2 = 0; i2 < tokenCount; i2++) {
        const offset = 4 * i2;
        let tokenDeltaLine = tokens[offset];
        let tokenStartCharacter = tokens[offset + 1];
        let tokenEndCharacter = tokens[offset + 2];
        if (tokenDeltaLine < deltaLine || tokenDeltaLine === deltaLine && tokenEndCharacter < character) {
          continue;
        } else if (tokenDeltaLine === deltaLine && tokenEndCharacter === character) {
          if (isInsertingPreciselyOneWordCharacter) {
            tokenEndCharacter += 1;
          } else {
            continue;
          }
        } else if (tokenDeltaLine === deltaLine && tokenStartCharacter < character && character < tokenEndCharacter) {
          if (eolCount === 0) {
            tokenEndCharacter += firstLineLength;
          } else {
            tokenEndCharacter = character;
          }
        } else {
          if (tokenDeltaLine === deltaLine && tokenStartCharacter === character) {
            if (isInsertingPreciselyOneWordCharacter) {
              continue;
            }
          }
          if (tokenDeltaLine === deltaLine) {
            tokenDeltaLine += eolCount;
            if (eolCount === 0) {
              tokenStartCharacter += firstLineLength;
              tokenEndCharacter += firstLineLength;
            } else {
              const tokenLength = tokenEndCharacter - tokenStartCharacter;
              tokenStartCharacter = lastLineLength + (tokenStartCharacter - character);
              tokenEndCharacter = tokenStartCharacter + tokenLength;
            }
          } else {
            tokenDeltaLine += eolCount;
          }
        }
        tokens[offset] = tokenDeltaLine;
        tokens[offset + 1] = tokenStartCharacter;
        tokens[offset + 2] = tokenEndCharacter;
      }
    }
    // limit to 10 times per minute
    reportIfInvalid(model, startLineNumber) {
      for (let i2 = 0; i2 < this._tokenCount; i2++) {
        const lineNumber = this._getDeltaLine(i2) + startLineNumber;
        if (lineNumber < 1) {
          _SparseMultilineTokensStorage._rateLimiter.runIfNotLimited(() => {
            console.error("Invalid Semantic Tokens Data From Extension: lineNumber < 1");
          });
        } else if (lineNumber > model.getLineCount()) {
          _SparseMultilineTokensStorage._rateLimiter.runIfNotLimited(() => {
            console.error("Invalid Semantic Tokens Data From Extension: lineNumber > model.getLineCount()");
          });
        } else if (this._getEndCharacter(i2) > model.getLineLength(lineNumber)) {
          _SparseMultilineTokensStorage._rateLimiter.runIfNotLimited(() => {
            console.error("Invalid Semantic Tokens Data From Extension: end character > model.getLineLength(lineNumber)");
          });
        }
      }
    }
  };
  _SparseMultilineTokensStorage._rateLimiter = new RateLimiter(10 / 60);
  let SparseMultilineTokensStorage = _SparseMultilineTokensStorage;
  class SparseLineTokens {
    constructor(tokens) {
      this._tokens = tokens;
    }
    getCount() {
      return this._tokens.length / 4;
    }
    getStartCharacter(tokenIndex) {
      return this._tokens[4 * tokenIndex + 1];
    }
    getEndCharacter(tokenIndex) {
      return this._tokens[4 * tokenIndex + 2];
    }
    getMetadata(tokenIndex) {
      return this._tokens[4 * tokenIndex + 3];
    }
  }
  var __decorate$Q = 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$P = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  let SemanticTokensProviderStyling = class SemanticTokensProviderStyling {
    constructor(_legend, _themeService, _languageService, _logService) {
      this._legend = _legend;
      this._themeService = _themeService;
      this._languageService = _languageService;
      this._logService = _logService;
      this._hasWarnedOverlappingTokens = false;
      this._hasWarnedInvalidLengthTokens = false;
      this._hasWarnedInvalidEditStart = false;
      this._hashTable = new HashTable();
    }
    getMetadata(tokenTypeIndex, tokenModifierSet, languageId) {
      const encodedLanguageId = this._languageService.languageIdCodec.encodeLanguageId(languageId);
      const entry = this._hashTable.get(tokenTypeIndex, tokenModifierSet, encodedLanguageId);
      let metadata;
      if (entry) {
        metadata = entry.metadata;
      } else {
        let tokenType = this._legend.tokenTypes[tokenTypeIndex];
        const tokenModifiers = [];
        if (tokenType) {
          let modifierSet = tokenModifierSet;
          for (let modifierIndex = 0; modifierSet > 0 && modifierIndex < this._legend.tokenModifiers.length; modifierIndex++) {
            if (modifierSet & 1) {
              tokenModifiers.push(this._legend.tokenModifiers[modifierIndex]);
            }
            modifierSet = modifierSet >> 1;
          }
          const tokenStyle = this._themeService.getColorTheme().getTokenStyleMetadata(tokenType, tokenModifiers, languageId);
          if (typeof tokenStyle === "undefined") {
            metadata = 2147483647;
          } else {
            metadata = 0;
            if (typeof tokenStyle.italic !== "undefined") {
              const italicBit = (tokenStyle.italic ? 1 : 0) << 11;
              metadata |= italicBit | 1;
            }
            if (typeof tokenStyle.bold !== "undefined") {
              const boldBit = (tokenStyle.bold ? 2 : 0) << 11;
              metadata |= boldBit | 2;
            }
            if (typeof tokenStyle.underline !== "undefined") {
              const underlineBit = (tokenStyle.underline ? 4 : 0) << 11;
              metadata |= underlineBit | 4;
            }
            if (typeof tokenStyle.strikethrough !== "undefined") {
              const strikethroughBit = (tokenStyle.strikethrough ? 8 : 0) << 11;
              metadata |= strikethroughBit | 8;
            }
            if (tokenStyle.foreground) {
              const foregroundBits = tokenStyle.foreground << 15;
              metadata |= foregroundBits | 16;
            }
            if (metadata === 0) {
              metadata = 2147483647;
            }
          }
        } else {
          metadata = 2147483647;
          tokenType = "not-in-legend";
        }
        this._hashTable.add(tokenTypeIndex, tokenModifierSet, encodedLanguageId, metadata);
      }
      return metadata;
    }
    warnOverlappingSemanticTokens(lineNumber, startColumn) {
      if (!this._hasWarnedOverlappingTokens) {
        this._hasWarnedOverlappingTokens = true;
        this._logService.warn(`Overlapping semantic tokens detected at lineNumber ${lineNumber}, column ${startColumn}`);
      }
    }
    warnInvalidLengthSemanticTokens(lineNumber, startColumn) {
      if (!this._hasWarnedInvalidLengthTokens) {
        this._hasWarnedInvalidLengthTokens = true;
        this._logService.warn(`Semantic token with invalid length detected at lineNumber ${lineNumber}, column ${startColumn}`);
      }
    }
    warnInvalidEditStart(previousResultId, resultId, editIndex, editStart, maxExpectedStart) {
      if (!this._hasWarnedInvalidEditStart) {
        this._hasWarnedInvalidEditStart = true;
        this._logService.warn(`Invalid semantic tokens edit detected (previousResultId: ${previousResultId}, resultId: ${resultId}) at edit #${editIndex}: The provided start offset ${editStart} is outside the previous data (length ${maxExpectedStart}).`);
      }
    }
  };
  SemanticTokensProviderStyling = __decorate$Q([
    __param$P(1, IThemeService),
    __param$P(2, ILanguageService),
    __param$P(3, ILogService)
  ], SemanticTokensProviderStyling);
  function toMultilineTokens2(tokens, styling, languageId) {
    const srcData = tokens.data;
    const tokenCount = tokens.data.length / 5 | 0;
    const tokensPerArea = Math.max(
      Math.ceil(
        tokenCount / 1024
        /* SemanticColoringConstants.DesiredMaxAreas */
      ),
      400
      /* SemanticColoringConstants.DesiredTokensPerArea */
    );
    const result = [];
    let tokenIndex = 0;
    let lastLineNumber = 1;
    let lastStartCharacter = 0;
    while (tokenIndex < tokenCount) {
      const tokenStartIndex = tokenIndex;
      let tokenEndIndex = Math.min(tokenStartIndex + tokensPerArea, tokenCount);
      if (tokenEndIndex < tokenCount) {
        let smallTokenEndIndex = tokenEndIndex;
        while (smallTokenEndIndex - 1 > tokenStartIndex && srcData[5 * smallTokenEndIndex] === 0) {
          smallTokenEndIndex--;
        }
        if (smallTokenEndIndex - 1 === tokenStartIndex) {
          let bigTokenEndIndex = tokenEndIndex;
          while (bigTokenEndIndex + 1 < tokenCount && srcData[5 * bigTokenEndIndex] === 0) {
            bigTokenEndIndex++;
          }
          tokenEndIndex = bigTokenEndIndex;
        } else {
          tokenEndIndex = smallTokenEndIndex;
        }
      }
      let destData = new Uint32Array((tokenEndIndex - tokenStartIndex) * 4);
      let destOffset = 0;
      let areaLine = 0;
      let prevLineNumber = 0;
      let prevEndCharacter = 0;
      while (tokenIndex < tokenEndIndex) {
        const srcOffset = 5 * tokenIndex;
        const deltaLine = srcData[srcOffset];
        const deltaCharacter = srcData[srcOffset + 1];
        const lineNumber = lastLineNumber + deltaLine | 0;
        const startCharacter = deltaLine === 0 ? lastStartCharacter + deltaCharacter | 0 : deltaCharacter;
        const length = srcData[srcOffset + 2];
        const endCharacter = startCharacter + length | 0;
        const tokenTypeIndex = srcData[srcOffset + 3];
        const tokenModifierSet = srcData[srcOffset + 4];
        if (endCharacter <= startCharacter) {
          styling.warnInvalidLengthSemanticTokens(lineNumber, startCharacter + 1);
        } else if (prevLineNumber === lineNumber && prevEndCharacter > startCharacter) {
          styling.warnOverlappingSemanticTokens(lineNumber, startCharacter + 1);
        } else {
          const metadata = styling.getMetadata(tokenTypeIndex, tokenModifierSet, languageId);
          if (metadata !== 2147483647) {
            if (areaLine === 0) {
              areaLine = lineNumber;
            }
            destData[destOffset] = lineNumber - areaLine;
            destData[destOffset + 1] = startCharacter;
            destData[destOffset + 2] = endCharacter;
            destData[destOffset + 3] = metadata;
            destOffset += 4;
            prevLineNumber = lineNumber;
            prevEndCharacter = endCharacter;
          }
        }
        lastLineNumber = lineNumber;
        lastStartCharacter = startCharacter;
        tokenIndex++;
      }
      if (destOffset !== destData.length) {
        destData = destData.subarray(0, destOffset);
      }
      const tokens2 = SparseMultilineTokens.create(areaLine, destData);
      result.push(tokens2);
    }
    return result;
  }
  class HashTableEntry {
    constructor(tokenTypeIndex, tokenModifierSet, languageId, metadata) {
      this.tokenTypeIndex = tokenTypeIndex;
      this.tokenModifierSet = tokenModifierSet;
      this.languageId = languageId;
      this.metadata = metadata;
      this.next = null;
    }
  }
  const _HashTable = class _HashTable {
    constructor() {
      this._elementsCount = 0;
      this._currentLengthIndex = 0;
      this._currentLength = _HashTable._SIZES[this._currentLengthIndex];
      this._growCount = Math.round(this._currentLengthIndex + 1 < _HashTable._SIZES.length ? 2 / 3 * this._currentLength : 0);
      this._elements = [];
      _HashTable._nullOutEntries(this._elements, this._currentLength);
    }
    static _nullOutEntries(entries2, length) {
      for (let i2 = 0; i2 < length; i2++) {
        entries2[i2] = null;
      }
    }
    _hash2(n1, n2) {
      return (n1 << 5) - n1 + n2 | 0;
    }
    _hashFunc(tokenTypeIndex, tokenModifierSet, languageId) {
      return this._hash2(this._hash2(tokenTypeIndex, tokenModifierSet), languageId) % this._currentLength;
    }
    get(tokenTypeIndex, tokenModifierSet, languageId) {
      const hash2 = this._hashFunc(tokenTypeIndex, tokenModifierSet, languageId);
      let p = this._elements[hash2];
      while (p) {
        if (p.tokenTypeIndex === tokenTypeIndex && p.tokenModifierSet === tokenModifierSet && p.languageId === languageId) {
          return p;
        }
        p = p.next;
      }
      return null;
    }
    add(tokenTypeIndex, tokenModifierSet, languageId, metadata) {
      this._elementsCount++;
      if (this._growCount !== 0 && this._elementsCount >= this._growCount) {
        const oldElements = this._elements;
        this._currentLengthIndex++;
        this._currentLength = _HashTable._SIZES[this._currentLengthIndex];
        this._growCount = Math.round(this._currentLengthIndex + 1 < _HashTable._SIZES.length ? 2 / 3 * this._currentLength : 0);
        this._elements = [];
        _HashTable._nullOutEntries(this._elements, this._currentLength);
        for (const first2 of oldElements) {
          let p = first2;
          while (p) {
            const oldNext = p.next;
            p.next = null;
            this._add(p);
            p = oldNext;
          }
        }
      }
      this._add(new HashTableEntry(tokenTypeIndex, tokenModifierSet, languageId, metadata));
    }
    _add(element) {
      const hash2 = this._hashFunc(element.tokenTypeIndex, element.tokenModifierSet, element.languageId);
      element.next = this._elements[hash2];
      this._elements[hash2] = element;
    }
  };
  _HashTable._SIZES = [3, 7, 13, 31, 61, 127, 251, 509, 1021, 2039, 4093, 8191, 16381, 32749, 65521, 131071, 262139, 524287, 1048573, 2097143];
  let HashTable = _HashTable;
  const ISemanticTokensStylingService = createDecorator("semanticTokensStylingService");
  function reverseEndianness(arr) {
    for (let i2 = 0, len = arr.length; i2 < len; i2 += 4) {
      const b0 = arr[i2 + 0];
      const b1 = arr[i2 + 1];
      const b2 = arr[i2 + 2];
      const b3 = arr[i2 + 3];
      arr[i2 + 0] = b3;
      arr[i2 + 1] = b2;
      arr[i2 + 2] = b1;
      arr[i2 + 3] = b0;
    }
  }
  function toLittleEndianBuffer(arr) {
    const uint8Arr = new Uint8Array(arr.buffer, arr.byteOffset, arr.length * 4);
    if (!isLittleEndian()) {
      reverseEndianness(uint8Arr);
    }
    return VSBuffer.wrap(uint8Arr);
  }
  function encodeSemanticTokensDto(semanticTokens) {
    const dest = new Uint32Array(encodeSemanticTokensDtoSize(semanticTokens));
    let offset = 0;
    dest[offset++] = semanticTokens.id;
    if (semanticTokens.type === "full") {
      dest[offset++] = 1;
      dest[offset++] = semanticTokens.data.length;
      dest.set(semanticTokens.data, offset);
      offset += semanticTokens.data.length;
    } else {
      dest[offset++] = 2;
      dest[offset++] = semanticTokens.deltas.length;
      for (const delta of semanticTokens.deltas) {
        dest[offset++] = delta.start;
        dest[offset++] = delta.deleteCount;
        if (delta.data) {
          dest[offset++] = delta.data.length;
          dest.set(delta.data, offset);
          offset += delta.data.length;
        } else {
          dest[offset++] = 0;
        }
      }
    }
    return toLittleEndianBuffer(dest);
  }
  function encodeSemanticTokensDtoSize(semanticTokens) {
    let result = 0;
    result += 1 + 1;
    if (semanticTokens.type === "full") {
      result += 1 + semanticTokens.data.length;
    } else {
      result += 1;
      result += (1 + 1 + 1) * semanticTokens.deltas.length;
      for (const delta of semanticTokens.deltas) {
        if (delta.data) {
          result += delta.data.length;
        }
      }
    }
    return result;
  }
  function isSemanticTokens(v) {
    return v && !!v.data;
  }
  function isSemanticTokensEdits(v) {
    return v && Array.isArray(v.edits);
  }
  class DocumentSemanticTokensResult {
    constructor(provider, tokens, error) {
      this.provider = provider;
      this.tokens = tokens;
      this.error = error;
    }
  }
  function hasDocumentSemanticTokensProvider(registry, model) {
    return registry.has(model);
  }
  function getDocumentSemanticTokensProviders(registry, model) {
    const groups = registry.orderedGroups(model);
    return groups.length > 0 ? groups[0] : [];
  }
  async function getDocumentSemanticTokens(registry, model, lastProvider, lastResultId, token) {
    const providers = getDocumentSemanticTokensProviders(registry, model);
    const results = await Promise.all(providers.map(async (provider) => {
      let result;
      let error = null;
      try {
        result = await provider.provideDocumentSemanticTokens(model, provider === lastProvider ? lastResultId : null, token);
      } catch (err) {
        error = err;
        result = null;
      }
      if (!result || !isSemanticTokens(result) && !isSemanticTokensEdits(result)) {
        result = null;
      }
      return new DocumentSemanticTokensResult(provider, result, error);
    }));
    for (const result of results) {
      if (result.error) {
        throw result.error;
      }
      if (result.tokens) {
        return result;
      }
    }
    if (results.length > 0) {
      return results[0];
    }
    return null;
  }
  function _getDocumentSemanticTokensProviderHighestGroup(registry, model) {
    const result = registry.orderedGroups(model);
    return result.length > 0 ? result[0] : null;
  }
  class DocumentRangeSemanticTokensResult {
    constructor(provider, tokens) {
      this.provider = provider;
      this.tokens = tokens;
    }
  }
  function hasDocumentRangeSemanticTokensProvider(providers, model) {
    return providers.has(model);
  }
  function getDocumentRangeSemanticTokensProviders(providers, model) {
    const groups = providers.orderedGroups(model);
    return groups.length > 0 ? groups[0] : [];
  }
  async function getDocumentRangeSemanticTokens(registry, model, range2, token) {
    const providers = getDocumentRangeSemanticTokensProviders(registry, model);
    const results = await Promise.all(providers.map(async (provider) => {
      let result;
      try {
        result = await provider.provideDocumentRangeSemanticTokens(model, range2, token);
      } catch (err) {
        onUnexpectedExternalError(err);
        result = null;
      }
      if (!result || !isSemanticTokens(result)) {
        result = null;
      }
      return new DocumentRangeSemanticTokensResult(provider, result);
    }));
    for (const result of results) {
      if (result.tokens) {
        return result;
      }
    }
    if (results.length > 0) {
      return results[0];
    }
    return null;
  }
  CommandsRegistry.registerCommand("_provideDocumentSemanticTokensLegend", async (accessor, ...args) => {
    const [uri] = args;
    assertType(uri instanceof URI);
    const model = accessor.get(IModelService).getModel(uri);
    if (!model) {
      return void 0;
    }
    const { documentSemanticTokensProvider } = accessor.get(ILanguageFeaturesService);
    const providers = _getDocumentSemanticTokensProviderHighestGroup(documentSemanticTokensProvider, model);
    if (!providers) {
      return accessor.get(ICommandService).executeCommand("_provideDocumentRangeSemanticTokensLegend", uri);
    }
    return providers[0].getLegend();
  });
  CommandsRegistry.registerCommand("_provideDocumentSemanticTokens", async (accessor, ...args) => {
    const [uri] = args;
    assertType(uri instanceof URI);
    const model = accessor.get(IModelService).getModel(uri);
    if (!model) {
      return void 0;
    }
    const { documentSemanticTokensProvider } = accessor.get(ILanguageFeaturesService);
    if (!hasDocumentSemanticTokensProvider(documentSemanticTokensProvider, model)) {
      return accessor.get(ICommandService).executeCommand("_provideDocumentRangeSemanticTokens", uri, model.getFullModelRange());
    }
    const r = await getDocumentSemanticTokens(documentSemanticTokensProvider, model, null, null, CancellationToken.None);
    if (!r) {
      return void 0;
    }
    const { provider, tokens } = r;
    if (!tokens || !isSemanticTokens(tokens)) {
      return void 0;
    }
    const buff = encodeSemanticTokensDto({
      id: 0,
      type: "full",
      data: tokens.data
    });
    if (tokens.resultId) {
      provider.releaseDocumentSemanticTokens(tokens.resultId);
    }
    return buff;
  });
  CommandsRegistry.registerCommand("_provideDocumentRangeSemanticTokensLegend", async (accessor, ...args) => {
    const [uri, range2] = args;
    assertType(uri instanceof URI);
    const model = accessor.get(IModelService).getModel(uri);
    if (!model) {
      return void 0;
    }
    const { documentRangeSemanticTokensProvider } = accessor.get(ILanguageFeaturesService);
    const providers = getDocumentRangeSemanticTokensProviders(documentRangeSemanticTokensProvider, model);
    if (providers.length === 0) {
      return void 0;
    }
    if (providers.length === 1) {
      return providers[0].getLegend();
    }
    if (!range2 || !Range$2.isIRange(range2)) {
      console.warn(`provideDocumentRangeSemanticTokensLegend might be out-of-sync with provideDocumentRangeSemanticTokens unless a range argument is passed in`);
      return providers[0].getLegend();
    }
    const result = await getDocumentRangeSemanticTokens(documentRangeSemanticTokensProvider, model, Range$2.lift(range2), CancellationToken.None);
    if (!result) {
      return void 0;
    }
    return result.provider.getLegend();
  });
  CommandsRegistry.registerCommand("_provideDocumentRangeSemanticTokens", async (accessor, ...args) => {
    const [uri, range2] = args;
    assertType(uri instanceof URI);
    assertType(Range$2.isIRange(range2));
    const model = accessor.get(IModelService).getModel(uri);
    if (!model) {
      return void 0;
    }
    const { documentRangeSemanticTokensProvider } = accessor.get(ILanguageFeaturesService);
    const result = await getDocumentRangeSemanticTokens(documentRangeSemanticTokensProvider, model, Range$2.lift(range2), CancellationToken.None);
    if (!result || !result.tokens) {
      return void 0;
    }
    return encodeSemanticTokensDto({
      id: 0,
      type: "full",
      data: result.tokens.data
    });
  });
  const SEMANTIC_HIGHLIGHTING_SETTING_ID = "editor.semanticHighlighting";
  function isSemanticColoringEnabled(model, themeService, configurationService) {
    const setting = configurationService.getValue(SEMANTIC_HIGHLIGHTING_SETTING_ID, { overrideIdentifier: model.getLanguageId(), resource: model.uri })?.enabled;
    if (typeof setting === "boolean") {
      return setting;
    }
    return themeService.getColorTheme().semanticHighlighting;
  }
  var __decorate$P = 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$O = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  var ModelSemanticColoring_1;
  let DocumentSemanticTokensFeature = class DocumentSemanticTokensFeature extends Disposable {
    constructor(semanticTokensStylingService, modelService, themeService, configurationService, languageFeatureDebounceService, languageFeaturesService) {
      super();
      this._watchers = new ResourceMap();
      const register2 = (model) => {
        this._watchers.get(model.uri)?.dispose();
        this._watchers.set(model.uri, new ModelSemanticColoring(model, semanticTokensStylingService, themeService, languageFeatureDebounceService, languageFeaturesService));
      };
      const deregister = (model, modelSemanticColoring) => {
        modelSemanticColoring.dispose();
        this._watchers.delete(model.uri);
      };
      const handleSettingOrThemeChange = () => {
        for (const model of modelService.getModels()) {
          const curr = this._watchers.get(model.uri);
          if (isSemanticColoringEnabled(model, themeService, configurationService)) {
            if (!curr) {
              register2(model);
            }
          } else {
            if (curr) {
              deregister(model, curr);
            }
          }
        }
      };
      modelService.getModels().forEach((model) => {
        if (isSemanticColoringEnabled(model, themeService, configurationService)) {
          register2(model);
        }
      });
      this._register(modelService.onModelAdded((model) => {
        if (isSemanticColoringEnabled(model, themeService, configurationService)) {
          register2(model);
        }
      }));
      this._register(modelService.onModelRemoved((model) => {
        const curr = this._watchers.get(model.uri);
        if (curr) {
          deregister(model, curr);
        }
      }));
      this._register(configurationService.onDidChangeConfiguration((e) => {
        if (e.affectsConfiguration(SEMANTIC_HIGHLIGHTING_SETTING_ID)) {
          handleSettingOrThemeChange();
        }
      }));
      this._register(themeService.onDidColorThemeChange(handleSettingOrThemeChange));
    }
    dispose() {
      dispose(this._watchers.values());
      this._watchers.clear();
      super.dispose();
    }
  };
  DocumentSemanticTokensFeature = __decorate$P([
    __param$O(0, ISemanticTokensStylingService),
    __param$O(1, IModelService),
    __param$O(2, IThemeService),
    __param$O(3, IConfigurationService),
    __param$O(4, ILanguageFeatureDebounceService),
    __param$O(5, ILanguageFeaturesService)
  ], DocumentSemanticTokensFeature);
  let ModelSemanticColoring = (_ya = class extends Disposable {
    constructor(model, _semanticTokensStylingService, themeService, languageFeatureDebounceService, languageFeaturesService) {
      super();
      this._semanticTokensStylingService = _semanticTokensStylingService;
      this._isDisposed = false;
      this._model = model;
      this._provider = languageFeaturesService.documentSemanticTokensProvider;
      this._debounceInformation = languageFeatureDebounceService.for(this._provider, "DocumentSemanticTokens", { min: ModelSemanticColoring_1.REQUEST_MIN_DELAY, max: ModelSemanticColoring_1.REQUEST_MAX_DELAY });
      this._fetchDocumentSemanticTokens = this._register(new RunOnceScheduler(() => this._fetchDocumentSemanticTokensNow(), ModelSemanticColoring_1.REQUEST_MIN_DELAY));
      this._currentDocumentResponse = null;
      this._currentDocumentRequestCancellationTokenSource = null;
      this._documentProvidersChangeListeners = [];
      this._providersChangedDuringRequest = false;
      this._register(this._model.onDidChangeContent(() => {
        if (!this._fetchDocumentSemanticTokens.isScheduled()) {
          this._fetchDocumentSemanticTokens.schedule(this._debounceInformation.get(this._model));
        }
      }));
      this._register(this._model.onDidChangeAttached(() => {
        if (!this._fetchDocumentSemanticTokens.isScheduled()) {
          this._fetchDocumentSemanticTokens.schedule(this._debounceInformation.get(this._model));
        }
      }));
      this._register(this._model.onDidChangeLanguage(() => {
        if (this._currentDocumentResponse) {
          this._currentDocumentResponse.dispose();
          this._currentDocumentResponse = null;
        }
        if (this._currentDocumentRequestCancellationTokenSource) {
          this._currentDocumentRequestCancellationTokenSource.cancel();
          this._currentDocumentRequestCancellationTokenSource = null;
        }
        this._setDocumentSemanticTokens(null, null, null, []);
        this._fetchDocumentSemanticTokens.schedule(0);
      }));
      const bindDocumentChangeListeners = () => {
        dispose(this._documentProvidersChangeListeners);
        this._documentProvidersChangeListeners = [];
        for (const provider of this._provider.all(model)) {
          if (typeof provider.onDidChange === "function") {
            this._documentProvidersChangeListeners.push(provider.onDidChange(() => {
              if (this._currentDocumentRequestCancellationTokenSource) {
                this._providersChangedDuringRequest = true;
                return;
              }
              this._fetchDocumentSemanticTokens.schedule(0);
            }));
          }
        }
      };
      bindDocumentChangeListeners();
      this._register(this._provider.onDidChange(() => {
        bindDocumentChangeListeners();
        this._fetchDocumentSemanticTokens.schedule(this._debounceInformation.get(this._model));
      }));
      this._register(themeService.onDidColorThemeChange((_) => {
        this._setDocumentSemanticTokens(null, null, null, []);
        this._fetchDocumentSemanticTokens.schedule(this._debounceInformation.get(this._model));
      }));
      this._fetchDocumentSemanticTokens.schedule(0);
    }
    dispose() {
      if (this._currentDocumentResponse) {
        this._currentDocumentResponse.dispose();
        this._currentDocumentResponse = null;
      }
      if (this._currentDocumentRequestCancellationTokenSource) {
        this._currentDocumentRequestCancellationTokenSource.cancel();
        this._currentDocumentRequestCancellationTokenSource = null;
      }
      dispose(this._documentProvidersChangeListeners);
      this._documentProvidersChangeListeners = [];
      this._setDocumentSemanticTokens(null, null, null, []);
      this._isDisposed = true;
      super.dispose();
    }
    _fetchDocumentSemanticTokensNow() {
      if (this._currentDocumentRequestCancellationTokenSource) {
        return;
      }
      if (!hasDocumentSemanticTokensProvider(this._provider, this._model)) {
        if (this._currentDocumentResponse) {
          this._model.tokenization.setSemanticTokens(null, false);
        }
        return;
      }
      if (!this._model.isAttachedToEditor()) {
        return;
      }
      const cancellationTokenSource = new CancellationTokenSource$1();
      const lastProvider = this._currentDocumentResponse ? this._currentDocumentResponse.provider : null;
      const lastResultId = this._currentDocumentResponse ? this._currentDocumentResponse.resultId || null : null;
      const request = getDocumentSemanticTokens(this._provider, this._model, lastProvider, lastResultId, cancellationTokenSource.token);
      this._currentDocumentRequestCancellationTokenSource = cancellationTokenSource;
      this._providersChangedDuringRequest = false;
      const pendingChanges = [];
      const contentChangeListener = this._model.onDidChangeContent((e) => {
        pendingChanges.push(e);
      });
      const sw = new StopWatch(false);
      request.then((res) => {
        this._debounceInformation.update(this._model, sw.elapsed());
        this._currentDocumentRequestCancellationTokenSource = null;
        contentChangeListener.dispose();
        if (!res) {
          this._setDocumentSemanticTokens(null, null, null, pendingChanges);
        } else {
          const { provider, tokens } = res;
          const styling = this._semanticTokensStylingService.getStyling(provider);
          this._setDocumentSemanticTokens(provider, tokens || null, styling, pendingChanges);
        }
      }, (err) => {
        const isExpectedError = err && (isCancellationError(err) || typeof err.message === "string" && err.message.indexOf("busy") !== -1);
        if (!isExpectedError) {
          onUnexpectedError(err);
        }
        this._currentDocumentRequestCancellationTokenSource = null;
        contentChangeListener.dispose();
        if (pendingChanges.length > 0 || this._providersChangedDuringRequest) {
          if (!this._fetchDocumentSemanticTokens.isScheduled()) {
            this._fetchDocumentSemanticTokens.schedule(this._debounceInformation.get(this._model));
          }
        }
      });
    }
    static _copy(src, srcOffset, dest, destOffset, length) {
      length = Math.min(length, dest.length - destOffset, src.length - srcOffset);
      for (let i2 = 0; i2 < length; i2++) {
        dest[destOffset + i2] = src[srcOffset + i2];
      }
    }
    _setDocumentSemanticTokens(provider, tokens, styling, pendingChanges) {
      const currentResponse = this._currentDocumentResponse;
      const rescheduleIfNeeded = () => {
        if ((pendingChanges.length > 0 || this._providersChangedDuringRequest) && !this._fetchDocumentSemanticTokens.isScheduled()) {
          this._fetchDocumentSemanticTokens.schedule(this._debounceInformation.get(this._model));
        }
      };
      if (this._currentDocumentResponse) {
        this._currentDocumentResponse.dispose();
        this._currentDocumentResponse = null;
      }
      if (this._isDisposed) {
        if (provider && tokens) {
          provider.releaseDocumentSemanticTokens(tokens.resultId);
        }
        return;
      }
      if (!provider || !styling) {
        this._model.tokenization.setSemanticTokens(null, false);
        return;
      }
      if (!tokens) {
        this._model.tokenization.setSemanticTokens(null, true);
        rescheduleIfNeeded();
        return;
      }
      if (isSemanticTokensEdits(tokens)) {
        if (!currentResponse) {
          this._model.tokenization.setSemanticTokens(null, true);
          return;
        }
        if (tokens.edits.length === 0) {
          tokens = {
            resultId: tokens.resultId,
            data: currentResponse.data
          };
        } else {
          let deltaLength = 0;
          for (const edit2 of tokens.edits) {
            deltaLength += (edit2.data ? edit2.data.length : 0) - edit2.deleteCount;
          }
          const srcData = currentResponse.data;
          const destData = new Uint32Array(srcData.length + deltaLength);
          let srcLastStart = srcData.length;
          let destLastStart = destData.length;
          for (let i2 = tokens.edits.length - 1; i2 >= 0; i2--) {
            const edit2 = tokens.edits[i2];
            if (edit2.start > srcData.length) {
              styling.warnInvalidEditStart(currentResponse.resultId, tokens.resultId, i2, edit2.start, srcData.length);
              this._model.tokenization.setSemanticTokens(null, true);
              return;
            }
            const copyCount = srcLastStart - (edit2.start + edit2.deleteCount);
            if (copyCount > 0) {
              ModelSemanticColoring_1._copy(srcData, srcLastStart - copyCount, destData, destLastStart - copyCount, copyCount);
              destLastStart -= copyCount;
            }
            if (edit2.data) {
              ModelSemanticColoring_1._copy(edit2.data, 0, destData, destLastStart - edit2.data.length, edit2.data.length);
              destLastStart -= edit2.data.length;
            }
            srcLastStart = edit2.start;
          }
          if (srcLastStart > 0) {
            ModelSemanticColoring_1._copy(srcData, 0, destData, 0, srcLastStart);
          }
          tokens = {
            resultId: tokens.resultId,
            data: destData
          };
        }
      }
      if (isSemanticTokens(tokens)) {
        this._currentDocumentResponse = new SemanticTokensResponse(provider, tokens.resultId, tokens.data);
        const result = toMultilineTokens2(tokens, styling, this._model.getLanguageId());
        if (pendingChanges.length > 0) {
          for (const change of pendingChanges) {
            for (const area of result) {
              for (const singleChange of change.changes) {
                area.applyEdit(singleChange.range, singleChange.text);
              }
            }
          }
        }
        this._model.tokenization.setSemanticTokens(result, true);
      } else {
        this._model.tokenization.setSemanticTokens(null, true);
      }
      rescheduleIfNeeded();
    }
  }, ModelSemanticColoring_1 = _ya, _ya.REQUEST_MIN_DELAY = 300, _ya.REQUEST_MAX_DELAY = 2e3, _ya);
  ModelSemanticColoring = ModelSemanticColoring_1 = __decorate$P([
    __param$O(1, ISemanticTokensStylingService),
    __param$O(2, IThemeService),
    __param$O(3, ILanguageFeatureDebounceService),
    __param$O(4, ILanguageFeaturesService)
  ], ModelSemanticColoring);
  class SemanticTokensResponse {
    constructor(provider, resultId, data) {
      this.provider = provider;
      this.resultId = resultId;
      this.data = data;
    }
    dispose() {
      this.provider.releaseDocumentSemanticTokens(this.resultId);
    }
  }
  registerEditorFeature(DocumentSemanticTokensFeature);
  var __decorate$O = 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$N = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  let ViewportSemanticTokensContribution = (_za = class extends Disposable {
    constructor(editor2, _semanticTokensStylingService, _themeService, _configurationService, languageFeatureDebounceService, languageFeaturesService) {
      super();
      this._semanticTokensStylingService = _semanticTokensStylingService;
      this._themeService = _themeService;
      this._configurationService = _configurationService;
      this._editor = editor2;
      this._provider = languageFeaturesService.documentRangeSemanticTokensProvider;
      this._debounceInformation = languageFeatureDebounceService.for(this._provider, "DocumentRangeSemanticTokens", { min: 100, max: 500 });
      this._tokenizeViewport = this._register(new RunOnceScheduler(() => this._tokenizeViewportNow(), 100));
      this._outstandingRequests = [];
      this._rangeProvidersChangeListeners = [];
      const scheduleTokenizeViewport = () => {
        if (this._editor.hasModel()) {
          this._tokenizeViewport.schedule(this._debounceInformation.get(this._editor.getModel()));
        }
      };
      const bindRangeProvidersChangeListeners = () => {
        this._cleanupProviderListeners();
        if (this._editor.hasModel()) {
          const model = this._editor.getModel();
          for (const provider of this._provider.all(model)) {
            const disposable = provider.onDidChange?.(() => {
              this._cancelAll();
              scheduleTokenizeViewport();
            });
            if (disposable) {
              this._rangeProvidersChangeListeners.push(disposable);
            }
          }
        }
      };
      this._register(this._editor.onDidScrollChange(() => {
        scheduleTokenizeViewport();
      }));
      this._register(this._editor.onDidChangeModel(() => {
        bindRangeProvidersChangeListeners();
        this._cancelAll();
        scheduleTokenizeViewport();
      }));
      this._register(this._editor.onDidChangeModelLanguage(() => {
        bindRangeProvidersChangeListeners();
        this._cancelAll();
        scheduleTokenizeViewport();
      }));
      this._register(this._editor.onDidChangeModelContent((e) => {
        this._cancelAll();
        scheduleTokenizeViewport();
      }));
      bindRangeProvidersChangeListeners();
      this._register(this._provider.onDidChange(() => {
        bindRangeProvidersChangeListeners();
        this._cancelAll();
        scheduleTokenizeViewport();
      }));
      this._register(this._configurationService.onDidChangeConfiguration((e) => {
        if (e.affectsConfiguration(SEMANTIC_HIGHLIGHTING_SETTING_ID)) {
          this._cancelAll();
          scheduleTokenizeViewport();
        }
      }));
      this._register(this._themeService.onDidColorThemeChange(() => {
        this._cancelAll();
        scheduleTokenizeViewport();
      }));
      scheduleTokenizeViewport();
    }
    dispose() {
      this._cleanupProviderListeners();
      super.dispose();
    }
    _cleanupProviderListeners() {
      dispose(this._rangeProvidersChangeListeners);
      this._rangeProvidersChangeListeners = [];
    }
    _cancelAll() {
      for (const request of this._outstandingRequests) {
        request.cancel();
      }
      this._outstandingRequests = [];
    }
    _removeOutstandingRequest(req) {
      for (let i2 = 0, len = this._outstandingRequests.length; i2 < len; i2++) {
        if (this._outstandingRequests[i2] === req) {
          this._outstandingRequests.splice(i2, 1);
          return;
        }
      }
    }
    _tokenizeViewportNow() {
      if (!this._editor.hasModel()) {
        return;
      }
      const model = this._editor.getModel();
      if (model.tokenization.hasCompleteSemanticTokens()) {
        return;
      }
      if (!isSemanticColoringEnabled(model, this._themeService, this._configurationService)) {
        if (model.tokenization.hasSomeSemanticTokens()) {
          model.tokenization.setSemanticTokens(null, false);
        }
        return;
      }
      if (!hasDocumentRangeSemanticTokensProvider(this._provider, model)) {
        if (model.tokenization.hasSomeSemanticTokens()) {
          model.tokenization.setSemanticTokens(null, false);
        }
        return;
      }
      const visibleRanges = this._editor.getVisibleRangesPlusViewportAboveBelow();
      this._outstandingRequests = this._outstandingRequests.concat(visibleRanges.map((range2) => this._requestRange(model, range2)));
    }
    _requestRange(model, range2) {
      const requestVersionId = model.getVersionId();
      const request = createCancelablePromise((token) => Promise.resolve(getDocumentRangeSemanticTokens(this._provider, model, range2, token)));
      const sw = new StopWatch(false);
      request.then((r) => {
        this._debounceInformation.update(model, sw.elapsed());
        if (!r || !r.tokens || model.isDisposed() || model.getVersionId() !== requestVersionId) {
          return;
        }
        const { provider, tokens: result } = r;
        const styling = this._semanticTokensStylingService.getStyling(provider);
        model.tokenization.setPartialSemanticTokens(range2, toMultilineTokens2(result, styling, model.getLanguageId()));
      }).then(() => this._removeOutstandingRequest(request), () => this._removeOutstandingRequest(request));
      return request;
    }
  }, _za.ID = "editor.contrib.viewportSemanticTokens", _za);
  ViewportSemanticTokensContribution = __decorate$O([
    __param$N(1, ISemanticTokensStylingService),
    __param$N(2, IThemeService),
    __param$N(3, IConfigurationService),
    __param$N(4, ILanguageFeatureDebounceService),
    __param$N(5, ILanguageFeaturesService)
  ], ViewportSemanticTokensContribution);
  registerEditorContribution(
    ViewportSemanticTokensContribution.ID,
    ViewportSemanticTokensContribution,
    1
    /* EditorContributionInstantiation.AfterFirstRender */
  );
  class WordSelectionRangeProvider {
    constructor(selectSubwords = true) {
      this.selectSubwords = selectSubwords;
    }
    provideSelectionRanges(model, positions) {
      const result = [];
      for (const position of positions) {
        const bucket = [];
        result.push(bucket);
        if (this.selectSubwords) {
          this._addInWordRanges(bucket, model, position);
        }
        this._addWordRanges(bucket, model, position);
        this._addWhitespaceLine(bucket, model, position);
        bucket.push({ range: model.getFullModelRange() });
      }
      return result;
    }
    _addInWordRanges(bucket, model, pos) {
      const obj = model.getWordAtPosition(pos);
      if (!obj) {
        return;
      }
      const { word, startColumn } = obj;
      const offset = pos.column - startColumn;
      let start = offset;
      let end = offset;
      let lastCh = 0;
      for (; start >= 0; start--) {
        const ch = word.charCodeAt(start);
        if (start !== offset && (ch === 95 || ch === 45)) {
          break;
        } else if (isLowerAsciiLetter(ch) && isUpperAsciiLetter(lastCh)) {
          break;
        }
        lastCh = ch;
      }
      start += 1;
      for (; end < word.length; end++) {
        const ch = word.charCodeAt(end);
        if (isUpperAsciiLetter(ch) && isLowerAsciiLetter(lastCh)) {
          break;
        } else if (ch === 95 || ch === 45) {
          break;
        }
        lastCh = ch;
      }
      if (start < end) {
        bucket.push({ range: new Range$2(pos.lineNumber, startColumn + start, pos.lineNumber, startColumn + end) });
      }
    }
    _addWordRanges(bucket, model, pos) {
      const word = model.getWordAtPosition(pos);
      if (word) {
        bucket.push({ range: new Range$2(pos.lineNumber, word.startColumn, pos.lineNumber, word.endColumn) });
      }
    }
    _addWhitespaceLine(bucket, model, pos) {
      if (model.getLineLength(pos.lineNumber) > 0 && model.getLineFirstNonWhitespaceColumn(pos.lineNumber) === 0 && model.getLineLastNonWhitespaceColumn(pos.lineNumber) === 0) {
        bucket.push({ range: new Range$2(pos.lineNumber, 1, pos.lineNumber, model.getLineMaxColumn(pos.lineNumber)) });
      }
    }
  }
  var __decorate$N = 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$M = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  var SmartSelectController_1;
  class SelectionRanges {
    constructor(index, ranges) {
      this.index = index;
      this.ranges = ranges;
    }
    mov(fwd) {
      const index = this.index + (fwd ? 1 : -1);
      if (index < 0 || index >= this.ranges.length) {
        return this;
      }
      const res = new SelectionRanges(index, this.ranges);
      if (res.ranges[index].equalsRange(this.ranges[this.index])) {
        return res.mov(fwd);
      }
      return res;
    }
  }
  let SmartSelectController = (_Aa = class {
    static get(editor2) {
      return editor2.getContribution(SmartSelectController_1.ID);
    }
    constructor(_editor, _languageFeaturesService) {
      this._editor = _editor;
      this._languageFeaturesService = _languageFeaturesService;
      this._ignoreSelection = false;
    }
    dispose() {
      this._selectionListener?.dispose();
    }
    async run(forward) {
      if (!this._editor.hasModel()) {
        return;
      }
      const selections = this._editor.getSelections();
      const model = this._editor.getModel();
      if (!this._state) {
        await provideSelectionRanges(this._languageFeaturesService.selectionRangeProvider, model, selections.map((s) => s.getPosition()), this._editor.getOption(
          129
          /* EditorOption.smartSelect */
        ), CancellationToken.None).then((ranges) => {
          if (!isNonEmptyArray(ranges) || ranges.length !== selections.length) {
            return;
          }
          if (!this._editor.hasModel() || !equals$1(this._editor.getSelections(), selections, (a, b) => a.equalsSelection(b))) {
            return;
          }
          for (let i2 = 0; i2 < ranges.length; i2++) {
            ranges[i2] = ranges[i2].filter((range2) => {
              return range2.containsPosition(selections[i2].getStartPosition()) && range2.containsPosition(selections[i2].getEndPosition());
            });
            ranges[i2].unshift(selections[i2]);
          }
          this._state = ranges.map((ranges2) => new SelectionRanges(0, ranges2));
          this._selectionListener?.dispose();
          this._selectionListener = this._editor.onDidChangeCursorPosition(() => {
            if (!this._ignoreSelection) {
              this._selectionListener?.dispose();
              this._state = void 0;
            }
          });
        });
      }
      if (!this._state) {
        return;
      }
      this._state = this._state.map((state) => state.mov(forward));
      const newSelections = this._state.map((state) => Selection$1.fromPositions(state.ranges[state.index].getStartPosition(), state.ranges[state.index].getEndPosition()));
      this._ignoreSelection = true;
      try {
        this._editor.setSelections(newSelections);
      } finally {
        this._ignoreSelection = false;
      }
    }
  }, SmartSelectController_1 = _Aa, _Aa.ID = "editor.contrib.smartSelectController", _Aa);
  SmartSelectController = SmartSelectController_1 = __decorate$N([
    __param$M(1, ILanguageFeaturesService)
  ], SmartSelectController);
  class AbstractSmartSelect extends EditorAction {
    constructor(forward, opts) {
      super(opts);
      this._forward = forward;
    }
    async run(_accessor, editor2) {
      const controller = SmartSelectController.get(editor2);
      if (controller) {
        await controller.run(this._forward);
      }
    }
  }
  class GrowSelectionAction extends AbstractSmartSelect {
    constructor() {
      super(true, {
        id: "editor.action.smartSelect.expand",
        label: localize2(1400, "Expand Selection"),
        precondition: void 0,
        kbOpts: {
          kbExpr: EditorContextKeys.editorTextFocus,
          primary: 1024 | 512 | 17,
          mac: {
            primary: 2048 | 256 | 1024 | 17,
            secondary: [
              256 | 1024 | 17
              /* KeyCode.RightArrow */
            ]
          },
          weight: 100
          /* KeybindingWeight.EditorContrib */
        },
        menuOpts: {
          menuId: MenuId.MenubarSelectionMenu,
          group: "1_basic",
          title: localize(1398, "&&Expand Selection"),
          order: 2
        }
      });
    }
  }
  CommandsRegistry.registerCommandAlias("editor.action.smartSelect.grow", "editor.action.smartSelect.expand");
  class ShrinkSelectionAction extends AbstractSmartSelect {
    constructor() {
      super(false, {
        id: "editor.action.smartSelect.shrink",
        label: localize2(1401, "Shrink Selection"),
        precondition: void 0,
        kbOpts: {
          kbExpr: EditorContextKeys.editorTextFocus,
          primary: 1024 | 512 | 15,
          mac: {
            primary: 2048 | 256 | 1024 | 15,
            secondary: [
              256 | 1024 | 15
              /* KeyCode.LeftArrow */
            ]
          },
          weight: 100
          /* KeybindingWeight.EditorContrib */
        },
        menuOpts: {
          menuId: MenuId.MenubarSelectionMenu,
          group: "1_basic",
          title: localize(1399, "&&Shrink Selection"),
          order: 3
        }
      });
    }
  }
  registerEditorContribution(
    SmartSelectController.ID,
    SmartSelectController,
    4
    /* EditorContributionInstantiation.Lazy */
  );
  registerEditorAction(GrowSelectionAction);
  registerEditorAction(ShrinkSelectionAction);
  async function provideSelectionRanges(registry, model, positions, options, token) {
    const providers = registry.all(model).concat(new WordSelectionRangeProvider(options.selectSubwords));
    if (providers.length === 1) {
      providers.unshift(new BracketSelectionRangeProvider());
    }
    const work = [];
    const allRawRanges = [];
    for (const provider of providers) {
      work.push(Promise.resolve(provider.provideSelectionRanges(model, positions, token)).then((allProviderRanges) => {
        if (isNonEmptyArray(allProviderRanges) && allProviderRanges.length === positions.length) {
          for (let i2 = 0; i2 < positions.length; i2++) {
            if (!allRawRanges[i2]) {
              allRawRanges[i2] = [];
            }
            for (const oneProviderRanges of allProviderRanges[i2]) {
              if (Range$2.isIRange(oneProviderRanges.range) && Range$2.containsPosition(oneProviderRanges.range, positions[i2])) {
                allRawRanges[i2].push(Range$2.lift(oneProviderRanges.range));
              }
            }
          }
        }
      }, onUnexpectedExternalError));
    }
    await Promise.all(work);
    return allRawRanges.map((oneRawRanges) => {
      if (oneRawRanges.length === 0) {
        return [];
      }
      oneRawRanges.sort((a, b) => {
        if (Position$1.isBefore(a.getStartPosition(), b.getStartPosition())) {
          return 1;
        } else if (Position$1.isBefore(b.getStartPosition(), a.getStartPosition())) {
          return -1;
        } else if (Position$1.isBefore(a.getEndPosition(), b.getEndPosition())) {
          return -1;
        } else if (Position$1.isBefore(b.getEndPosition(), a.getEndPosition())) {
          return 1;
        } else {
          return 0;
        }
      });
      const oneRanges = [];
      let last;
      for (const range2 of oneRawRanges) {
        if (!last || Range$2.containsRange(range2, last) && !Range$2.equalsRange(range2, last)) {
          oneRanges.push(range2);
          last = range2;
        }
      }
      if (!options.selectLeadingAndTrailingWhitespace) {
        return oneRanges;
      }
      const oneRangesWithTrivia = [oneRanges[0]];
      for (let i2 = 1; i2 < oneRanges.length; i2++) {
        const prev = oneRanges[i2 - 1];
        const cur = oneRanges[i2];
        if (cur.startLineNumber !== prev.startLineNumber || cur.endLineNumber !== prev.endLineNumber) {
          const rangeNoWhitespace = new Range$2(prev.startLineNumber, model.getLineFirstNonWhitespaceColumn(prev.startLineNumber), prev.endLineNumber, model.getLineLastNonWhitespaceColumn(prev.endLineNumber));
          if (rangeNoWhitespace.containsRange(prev) && !rangeNoWhitespace.equalsRange(prev) && cur.containsRange(rangeNoWhitespace) && !cur.equalsRange(rangeNoWhitespace)) {
            oneRangesWithTrivia.push(rangeNoWhitespace);
          }
          const rangeFull = new Range$2(prev.startLineNumber, 1, prev.endLineNumber, model.getLineMaxColumn(prev.endLineNumber));
          if (rangeFull.containsRange(prev) && !rangeFull.equalsRange(rangeNoWhitespace) && cur.containsRange(rangeFull) && !cur.equalsRange(rangeFull)) {
            oneRangesWithTrivia.push(rangeFull);
          }
        }
        oneRangesWithTrivia.push(cur);
      }
      return oneRangesWithTrivia;
    });
  }
  CommandsRegistry.registerCommand("_executeSelectionRangeProvider", async function(accessor, ...args) {
    const [resource, positions] = args;
    assertType(URI.isUri(resource));
    assertType(isArrayOf$1(positions, (p) => Position$1.isIPosition(p)));
    const registry = accessor.get(ILanguageFeaturesService).selectionRangeProvider;
    const reference = await accessor.get(ITextModelService).createModelReference(resource);
    try {
      return provideSelectionRanges(registry, reference.object.textEditorModel, positions.map(Position$1.lift), { selectLeadingAndTrailingWhitespace: true, selectSubwords: true }, CancellationToken.None);
    } finally {
      reference.dispose();
    }
  });
  const Categories = Object.freeze({
    View: localize2(1638, "View"),
    Help: localize2(1639, "Help"),
    Test: localize2(1640, "Test"),
    File: localize2(1641, "File"),
    Preferences: localize2(1642, "Preferences"),
    Developer: localize2(1643, "Developer")
  });
  class ToggleStickyScroll extends EditorAction2 {
    constructor() {
      super({
        id: "editor.action.toggleStickyScroll",
        title: {
          ...localize2(1448, "Toggle Editor Sticky Scroll"),
          mnemonicTitle: localize(1444, "&&Toggle Editor Sticky Scroll")
        },
        metadata: {
          description: localize2(1449, "Toggle/enable the editor sticky scroll which shows the nested scopes at the top of the viewport")
        },
        category: Categories.View,
        toggled: {
          condition: ContextKeyExpr.equals("config.editor.stickyScroll.enabled", true),
          title: localize(1445, "Sticky Scroll"),
          mnemonicTitle: localize(1446, "&&Sticky Scroll")
        },
        menu: [
          { id: MenuId.CommandPalette },
          { id: MenuId.MenubarAppearanceMenu, group: "4_editor", order: 3 },
          { id: MenuId.StickyScrollContext }
        ]
      });
    }
    async runEditorCommand(accessor, editor2) {
      const configurationService = accessor.get(IConfigurationService);
      const newValue = !configurationService.getValue("editor.stickyScroll.enabled");
      const isFocused = StickyScrollController.get(editor2)?.isFocused();
      configurationService.updateValue("editor.stickyScroll.enabled", newValue);
      if (isFocused) {
        editor2.focus();
      }
    }
  }
  const weight = 100;
  class FocusStickyScroll extends EditorAction2 {
    constructor() {
      super({
        id: "editor.action.focusStickyScroll",
        title: {
          ...localize2(1450, "Focus Editor Sticky Scroll"),
          mnemonicTitle: localize(1447, "&&Focus Editor Sticky Scroll")
        },
        precondition: ContextKeyExpr.and(ContextKeyExpr.has("config.editor.stickyScroll.enabled"), EditorContextKeys.stickyScrollVisible),
        menu: [
          { id: MenuId.CommandPalette }
        ]
      });
    }
    runEditorCommand(_accessor, editor2) {
      StickyScrollController.get(editor2)?.focus();
    }
  }
  class SelectNextStickyScrollLine extends EditorAction2 {
    constructor() {
      super({
        id: "editor.action.selectNextStickyScrollLine",
        title: localize2(1451, "Select the next editor sticky scroll line"),
        precondition: EditorContextKeys.stickyScrollFocused.isEqualTo(true),
        keybinding: {
          weight,
          primary: 18
          /* KeyCode.DownArrow */
        }
      });
    }
    runEditorCommand(_accessor, editor2) {
      StickyScrollController.get(editor2)?.focusNext();
    }
  }
  class SelectPreviousStickyScrollLine extends EditorAction2 {
    constructor() {
      super({
        id: "editor.action.selectPreviousStickyScrollLine",
        title: localize2(1452, "Select the previous sticky scroll line"),
        precondition: EditorContextKeys.stickyScrollFocused.isEqualTo(true),
        keybinding: {
          weight,
          primary: 16
          /* KeyCode.UpArrow */
        }
      });
    }
    runEditorCommand(_accessor, editor2) {
      StickyScrollController.get(editor2)?.focusPrevious();
    }
  }
  class GoToStickyScrollLine extends EditorAction2 {
    constructor() {
      super({
        id: "editor.action.goToFocusedStickyScrollLine",
        title: localize2(1453, "Go to the focused sticky scroll line"),
        precondition: EditorContextKeys.stickyScrollFocused.isEqualTo(true),
        keybinding: {
          weight,
          primary: 3
          /* KeyCode.Enter */
        }
      });
    }
    runEditorCommand(_accessor, editor2) {
      StickyScrollController.get(editor2)?.goToFocused();
    }
  }
  class SelectEditor extends EditorAction2 {
    constructor() {
      super({
        id: "editor.action.selectEditor",
        title: localize2(1454, "Select Editor"),
        precondition: EditorContextKeys.stickyScrollFocused.isEqualTo(true),
        keybinding: {
          weight,
          primary: 9
          /* KeyCode.Escape */
        }
      });
    }
    runEditorCommand(_accessor, editor2) {
      StickyScrollController.get(editor2)?.selectEditor();
    }
  }
  registerEditorContribution(
    StickyScrollController.ID,
    StickyScrollController,
    1
    /* EditorContributionInstantiation.AfterFirstRender */
  );
  registerAction2(ToggleStickyScroll);
  registerAction2(FocusStickyScroll);
  registerAction2(SelectPreviousStickyScrollLine);
  registerAction2(SelectNextStickyScrollLine);
  registerAction2(GoToStickyScrollLine);
  registerAction2(SelectEditor);
  var __decorate$M = 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$L = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  class SuggestInlineCompletion {
    constructor(range2, insertText, filterText, additionalTextEdits, command, gutterMenuLinkAction, completion) {
      this.range = range2;
      this.insertText = insertText;
      this.filterText = filterText;
      this.additionalTextEdits = additionalTextEdits;
      this.command = command;
      this.gutterMenuLinkAction = gutterMenuLinkAction;
      this.completion = completion;
    }
  }
  let InlineCompletionResults = class InlineCompletionResults extends RefCountedDisposable {
    constructor(model, line, word, completionModel, completions, _suggestMemoryService) {
      super(completions.disposable);
      this.model = model;
      this.line = line;
      this.word = word;
      this.completionModel = completionModel;
      this._suggestMemoryService = _suggestMemoryService;
    }
    canBeReused(model, line, word) {
      return this.model === model && this.line === line && this.word.word.length > 0 && this.word.startColumn === word.startColumn && this.word.endColumn < word.endColumn && this.completionModel.getIncompleteProvider().size === 0;
    }
    get items() {
      const result = [];
      const { items } = this.completionModel;
      const selectedIndex = this._suggestMemoryService.select(this.model, { lineNumber: this.line, column: this.word.endColumn + this.completionModel.lineContext.characterCountDelta }, items);
      const first2 = Iterable.slice(items, selectedIndex);
      const second = Iterable.slice(items, 0, selectedIndex);
      let resolveCount = 5;
      for (const item of Iterable.concat(first2, second)) {
        if (item.score === FuzzyScore.Default) {
          continue;
        }
        const range2 = new Range$2(
          item.editStart.lineNumber,
          item.editStart.column,
          item.editInsertEnd.lineNumber,
          item.editInsertEnd.column + this.completionModel.lineContext.characterCountDelta
          // end PLUS character delta
        );
        const insertText = item.completion.insertTextRules && item.completion.insertTextRules & 4 ? { snippet: item.completion.insertText } : item.completion.insertText;
        result.push(new SuggestInlineCompletion(range2, insertText, item.filterTextLow ?? item.labelLow, item.completion.additionalTextEdits, item.completion.command, item.completion.action, item));
        if (resolveCount-- >= 0) {
          item.resolve(CancellationToken.None);
        }
      }
      return result;
    }
  };
  InlineCompletionResults = __decorate$M([
    __param$L(5, ISuggestMemoryService)
  ], InlineCompletionResults);
  let SuggestInlineCompletions = class SuggestInlineCompletions extends Disposable {
    constructor(_languageFeatureService, _clipboardService, _suggestMemoryService, _editorService) {
      super();
      this._languageFeatureService = _languageFeatureService;
      this._clipboardService = _clipboardService;
      this._suggestMemoryService = _suggestMemoryService;
      this._editorService = _editorService;
      this._store.add(_languageFeatureService.inlineCompletionsProvider.register("*", this));
    }
    async provideInlineCompletions(model, position, context, token) {
      if (context.selectedSuggestionInfo) {
        return;
      }
      let editor2;
      for (const candidate of this._editorService.listCodeEditors()) {
        if (candidate.getModel() === model) {
          editor2 = candidate;
          break;
        }
      }
      if (!editor2) {
        return;
      }
      const config = editor2.getOption(
        102
        /* EditorOption.quickSuggestions */
      );
      if (QuickSuggestionsOptions.isAllOff(config)) {
        return;
      }
      model.tokenization.tokenizeIfCheap(position.lineNumber);
      const lineTokens = model.tokenization.getLineTokens(position.lineNumber);
      const tokenType = lineTokens.getStandardTokenType(lineTokens.findTokenIndexAtOffset(Math.max(position.column - 1 - 1, 0)));
      if (QuickSuggestionsOptions.valueFor(config, tokenType) !== "inline") {
        return void 0;
      }
      let wordInfo = model.getWordAtPosition(position);
      let triggerCharacterInfo;
      if (!wordInfo?.word) {
        triggerCharacterInfo = this._getTriggerCharacterInfo(model, position);
      }
      if (!wordInfo?.word && !triggerCharacterInfo) {
        return;
      }
      if (!wordInfo) {
        wordInfo = model.getWordUntilPosition(position);
      }
      if (wordInfo.endColumn !== position.column) {
        return;
      }
      let result;
      const leadingLineContents = model.getValueInRange(new Range$2(position.lineNumber, 1, position.lineNumber, position.column));
      if (!triggerCharacterInfo && this._lastResult?.canBeReused(model, position.lineNumber, wordInfo)) {
        const newLineContext = new LineContext$1(leadingLineContents, position.column - this._lastResult.word.endColumn);
        this._lastResult.completionModel.lineContext = newLineContext;
        this._lastResult.acquire();
        result = this._lastResult;
      } else {
        const completions = await provideSuggestionItems(this._languageFeatureService.completionProvider, model, position, new CompletionOptions(void 0, SuggestModel.createSuggestFilter(editor2).itemKind, triggerCharacterInfo?.providers), triggerCharacterInfo && { triggerKind: 1, triggerCharacter: triggerCharacterInfo.ch }, token);
        let clipboardText;
        if (completions.needsClipboard) {
          clipboardText = await this._clipboardService.readText();
        }
        const completionModel = new CompletionModel(completions.items, position.column, new LineContext$1(leadingLineContents, 0), WordDistance.None, editor2.getOption(
          134
          /* EditorOption.suggest */
        ), editor2.getOption(
          128
          /* EditorOption.snippetSuggestions */
        ), { boostFullMatch: false, firstMatchCanBeWeak: false }, clipboardText);
        result = new InlineCompletionResults(model, position.lineNumber, wordInfo, completionModel, completions, this._suggestMemoryService);
      }
      this._lastResult = result;
      return result;
    }
    handleItemDidShow(_completions, item) {
      item.completion.resolve(CancellationToken.None);
    }
    disposeInlineCompletions(result) {
      result.release();
    }
    _getTriggerCharacterInfo(model, position) {
      const ch = model.getValueInRange(Range$2.fromPositions({ lineNumber: position.lineNumber, column: position.column - 1 }, position));
      const providers = /* @__PURE__ */ new Set();
      for (const provider of this._languageFeatureService.completionProvider.all(model)) {
        if (provider.triggerCharacters?.includes(ch)) {
          providers.add(provider);
        }
      }
      if (providers.size === 0) {
        return void 0;
      }
      return { providers, ch };
    }
  };
  SuggestInlineCompletions = __decorate$M([
    __param$L(0, ILanguageFeaturesService),
    __param$L(1, IClipboardService),
    __param$L(2, ISuggestMemoryService),
    __param$L(3, ICodeEditorService)
  ], SuggestInlineCompletions);
  registerEditorFeature(SuggestInlineCompletions);
  class ForceRetokenizeAction extends EditorAction {
    constructor() {
      super({
        id: "editor.action.forceRetokenize",
        label: localize2(1532, "Developer: Force Retokenize"),
        precondition: void 0
      });
    }
    run(accessor, editor2) {
      if (!editor2.hasModel()) {
        return;
      }
      const model = editor2.getModel();
      model.tokenization.resetTokenization();
      const sw = new StopWatch();
      model.tokenization.forceTokenization(model.getLineCount());
      sw.stop();
      console.log(`tokenization took ${sw.elapsed()}`);
    }
  }
  registerEditorAction(ForceRetokenizeAction);
  const _ToggleTabFocusModeAction = class _ToggleTabFocusModeAction extends Action2 {
    constructor() {
      super({
        id: _ToggleTabFocusModeAction.ID,
        title: localize2(1530, "Toggle Tab Key Moves Focus"),
        precondition: void 0,
        keybinding: {
          primary: 2048 | 43,
          mac: {
            primary: 256 | 1024 | 43
            /* KeyCode.KeyM */
          },
          weight: 100
          /* KeybindingWeight.EditorContrib */
        },
        metadata: {
          description: localize2(1531, "Determines whether the tab key moves focus around the workbench or inserts the tab character in the current editor. This is also called tab trapping, tab navigation, or tab focus mode.")
        },
        f1: true
      });
    }
    run() {
      const oldValue = TabFocus.getTabFocusMode();
      const newValue = !oldValue;
      TabFocus.setTabFocusMode(newValue);
      if (newValue) {
        alert(localize(1528, "Pressing Tab will now move focus to the next focusable element"));
      } else {
        alert(localize(1529, "Pressing Tab will now insert the tab character"));
      }
    }
  };
  _ToggleTabFocusModeAction.ID = "editor.action.toggleTabFocusMode";
  let ToggleTabFocusModeAction = _ToggleTabFocusModeAction;
  registerAction2(ToggleTabFocusModeAction);
  class UnicodeTextModelHighlighter {
    static computeUnicodeHighlights(model, options, range2) {
      const startLine = range2 ? range2.startLineNumber : 1;
      const endLine = range2 ? range2.endLineNumber : model.getLineCount();
      const codePointHighlighter = new CodePointHighlighter(options);
      const candidates = codePointHighlighter.getCandidateCodePoints();
      let regex;
      if (candidates === "allNonBasicAscii") {
        regex = new RegExp("[^\\t\\n\\r\\x20-\\x7E]", "g");
      } else {
        regex = new RegExp(`${buildRegExpCharClassExpr(Array.from(candidates))}`, "g");
      }
      const searcher = new Searcher(null, regex);
      const ranges = [];
      let hasMore = false;
      let m;
      let ambiguousCharacterCount = 0;
      let invisibleCharacterCount = 0;
      let nonBasicAsciiCharacterCount = 0;
      forLoop: for (let lineNumber = startLine, lineCount = endLine; lineNumber <= lineCount; lineNumber++) {
        const lineContent = model.getLineContent(lineNumber);
        const lineLength = lineContent.length;
        searcher.reset(0);
        do {
          m = searcher.next(lineContent);
          if (m) {
            let startIndex = m.index;
            let endIndex = m.index + m[0].length;
            if (startIndex > 0) {
              const charCodeBefore = lineContent.charCodeAt(startIndex - 1);
              if (isHighSurrogate(charCodeBefore)) {
                startIndex--;
              }
            }
            if (endIndex + 1 < lineLength) {
              const charCodeBefore = lineContent.charCodeAt(endIndex - 1);
              if (isHighSurrogate(charCodeBefore)) {
                endIndex++;
              }
            }
            const str = lineContent.substring(startIndex, endIndex);
            let word = getWordAtText(startIndex + 1, DEFAULT_WORD_REGEXP, lineContent, 0);
            if (word && word.endColumn <= startIndex + 1) {
              word = null;
            }
            const highlightReason = codePointHighlighter.shouldHighlightNonBasicASCII(str, word ? word.word : null);
            if (highlightReason !== 0) {
              if (highlightReason === 3) {
                ambiguousCharacterCount++;
              } else if (highlightReason === 2) {
                invisibleCharacterCount++;
              } else if (highlightReason === 1) {
                nonBasicAsciiCharacterCount++;
              } else {
                assertNever();
              }
              const MAX_RESULT_LENGTH = 1e3;
              if (ranges.length >= MAX_RESULT_LENGTH) {
                hasMore = true;
                break forLoop;
              }
              ranges.push(new Range$2(lineNumber, startIndex + 1, lineNumber, endIndex + 1));
            }
          }
        } while (m);
      }
      return {
        ranges,
        hasMore,
        ambiguousCharacterCount,
        invisibleCharacterCount,
        nonBasicAsciiCharacterCount
      };
    }
    static computeUnicodeHighlightReason(char, options) {
      const codePointHighlighter = new CodePointHighlighter(options);
      const reason = codePointHighlighter.shouldHighlightNonBasicASCII(char, null);
      switch (reason) {
        case 0:
          return null;
        case 2:
          return {
            kind: 1
            /* UnicodeHighlighterReasonKind.Invisible */
          };
        case 3: {
          const codePoint = char.codePointAt(0);
          const primaryConfusable = codePointHighlighter.ambiguousCharacters.getPrimaryConfusable(codePoint);
          const notAmbiguousInLocales = AmbiguousCharacters.getLocales().filter((l) => !AmbiguousCharacters.getInstance(/* @__PURE__ */ new Set([...options.allowedLocales, l])).isAmbiguous(codePoint));
          return { kind: 0, confusableWith: String.fromCodePoint(primaryConfusable), notAmbiguousInLocales };
        }
        case 1:
          return {
            kind: 2
            /* UnicodeHighlighterReasonKind.NonBasicAscii */
          };
      }
    }
  }
  function buildRegExpCharClassExpr(codePoints, flags) {
    const src = `[${escapeRegExpCharacters(codePoints.map((i2) => String.fromCodePoint(i2)).join(""))}]`;
    return src;
  }
  class CodePointHighlighter {
    constructor(options) {
      this.options = options;
      this.allowedCodePoints = new Set(options.allowedCodePoints);
      this.ambiguousCharacters = AmbiguousCharacters.getInstance(new Set(options.allowedLocales));
    }
    getCandidateCodePoints() {
      if (this.options.nonBasicASCII) {
        return "allNonBasicAscii";
      }
      const set = /* @__PURE__ */ new Set();
      if (this.options.invisibleCharacters) {
        for (const cp of InvisibleCharacters.codePoints) {
          if (!isAllowedInvisibleCharacter(String.fromCodePoint(cp))) {
            set.add(cp);
          }
        }
      }
      if (this.options.ambiguousCharacters) {
        for (const cp of this.ambiguousCharacters.getConfusableCodePoints()) {
          set.add(cp);
        }
      }
      for (const cp of this.allowedCodePoints) {
        set.delete(cp);
      }
      return set;
    }
    shouldHighlightNonBasicASCII(character, wordContext) {
      const codePoint = character.codePointAt(0);
      if (this.allowedCodePoints.has(codePoint)) {
        return 0;
      }
      if (this.options.nonBasicASCII) {
        return 1;
      }
      let hasBasicASCIICharacters = false;
      let hasNonConfusableNonBasicAsciiCharacter = false;
      if (wordContext) {
        for (const char of wordContext) {
          const codePoint2 = char.codePointAt(0);
          const isBasicASCII$1 = isBasicASCII(char);
          hasBasicASCIICharacters = hasBasicASCIICharacters || isBasicASCII$1;
          if (!isBasicASCII$1 && !this.ambiguousCharacters.isAmbiguous(codePoint2) && !InvisibleCharacters.isInvisibleCharacter(codePoint2)) {
            hasNonConfusableNonBasicAsciiCharacter = true;
          }
        }
      }
      if (
        /* Don't allow mixing weird looking characters with ASCII */
        !hasBasicASCIICharacters && /* Is there an obviously weird looking character? */
        hasNonConfusableNonBasicAsciiCharacter
      ) {
        return 0;
      }
      if (this.options.invisibleCharacters) {
        if (!isAllowedInvisibleCharacter(character) && InvisibleCharacters.isInvisibleCharacter(codePoint)) {
          return 2;
        }
      }
      if (this.options.ambiguousCharacters) {
        if (this.ambiguousCharacters.isAmbiguous(codePoint)) {
          return 3;
        }
      }
      return 0;
    }
  }
  function isAllowedInvisibleCharacter(character) {
    return character === " " || character === "\n" || character === "	";
  }
  var __decorate$L = 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$K = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  let Link = class Link extends Disposable {
    get enabled() {
      return this._enabled;
    }
    set enabled(enabled) {
      if (enabled) {
        this.el.setAttribute("aria-disabled", "false");
        this.el.tabIndex = 0;
        this.el.style.pointerEvents = "auto";
        this.el.style.opacity = "1";
        this.el.style.cursor = "pointer";
        this._enabled = false;
      } else {
        this.el.setAttribute("aria-disabled", "true");
        this.el.tabIndex = -1;
        this.el.style.pointerEvents = "none";
        this.el.style.opacity = "0.4";
        this.el.style.cursor = "default";
        this._enabled = true;
      }
      this._enabled = enabled;
    }
    constructor(container, _link, options = {}, _hoverService, openerService) {
      super();
      this._link = _link;
      this._hoverService = _hoverService;
      this._enabled = true;
      this.el = append$2(container, $$l("a.monaco-link", {
        tabIndex: _link.tabIndex ?? 0,
        href: _link.href
      }, _link.label));
      this.hoverDelegate = options.hoverDelegate ?? getDefaultHoverDelegate("mouse");
      this.setTooltip(_link.title);
      this.el.setAttribute("role", "button");
      const onClickEmitter = this._register(new DomEmitter(this.el, "click"));
      const onKeyPress = this._register(new DomEmitter(this.el, "keypress"));
      const onEnterPress = Event.chain(onKeyPress.event, ($2) => $2.map((e) => new StandardKeyboardEvent(e)).filter(
        (e) => e.keyCode === 3
        /* KeyCode.Enter */
      ));
      const onTap = this._register(new DomEmitter(this.el, EventType.Tap)).event;
      this._register(Gesture.addTarget(this.el));
      const onOpen = Event.any(onClickEmitter.event, onEnterPress, onTap);
      this._register(onOpen((e) => {
        if (!this.enabled) {
          return;
        }
        EventHelper.stop(e, true);
        if (options?.opener) {
          options.opener(this._link.href);
        } else {
          openerService.open(this._link.href, { allowCommands: true });
        }
      }));
      this.enabled = true;
    }
    setTooltip(title) {
      if (!this.hover && title) {
        this.hover = this._register(this._hoverService.setupManagedHover(this.hoverDelegate, this.el, title));
      } else if (this.hover) {
        this.hover.update(title);
      }
    }
  };
  Link = __decorate$L([
    __param$K(3, IHoverService),
    __param$K(4, IOpenerService)
  ], Link);
  var __decorate$K = 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$J = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  const BANNER_ELEMENT_HEIGHT = 26;
  let BannerController = class BannerController extends Disposable {
    constructor(_editor, instantiationService) {
      super();
      this._editor = _editor;
      this.instantiationService = instantiationService;
      this.banner = this._register(this.instantiationService.createInstance(Banner));
    }
    hide() {
      this._editor.setBanner(null, 0);
      this.banner.clear();
    }
    show(item) {
      this.banner.show({
        ...item,
        onClose: () => {
          this.hide();
          item.onClose?.();
        }
      });
      this._editor.setBanner(this.banner.element, BANNER_ELEMENT_HEIGHT);
    }
  };
  BannerController = __decorate$K([
    __param$J(1, IInstantiationService)
  ], BannerController);
  let Banner = class Banner extends Disposable {
    constructor(instantiationService, markdownRendererService) {
      super();
      this.instantiationService = instantiationService;
      this.markdownRendererService = markdownRendererService;
      this.element = $$l("div.editor-banner");
      this.element.tabIndex = 0;
    }
    getAriaLabel(item) {
      if (item.ariaLabel) {
        return item.ariaLabel;
      }
      if (typeof item.message === "string") {
        return item.message;
      }
      return void 0;
    }
    getBannerMessage(message) {
      if (typeof message === "string") {
        const element = $$l("span");
        element.innerText = message;
        return element;
      }
      return this.markdownRendererService.render(message).element;
    }
    clear() {
      clearNode(this.element);
    }
    show(item) {
      clearNode(this.element);
      const ariaLabel = this.getAriaLabel(item);
      if (ariaLabel) {
        this.element.setAttribute("aria-label", ariaLabel);
      }
      const iconContainer = append$2(this.element, $$l("div.icon-container"));
      iconContainer.setAttribute("aria-hidden", "true");
      if (item.icon) {
        iconContainer.appendChild($$l(`div${ThemeIcon.asCSSSelector(item.icon)}`));
      }
      const messageContainer = append$2(this.element, $$l("div.message-container"));
      messageContainer.setAttribute("aria-hidden", "true");
      messageContainer.appendChild(this.getBannerMessage(item.message));
      this.messageActionsContainer = append$2(this.element, $$l("div.message-actions-container"));
      if (item.actions) {
        for (const action of item.actions) {
          this._register(this.instantiationService.createInstance(Link, this.messageActionsContainer, { ...action, tabIndex: -1 }, {}));
        }
      }
      const actionBarContainer = append$2(this.element, $$l("div.action-container"));
      this.actionBar = this._register(new ActionBar(actionBarContainer));
      this.actionBar.push(this._register(new Action("banner.close", localize(1533, "Close Banner"), ThemeIcon.asClassName(widgetClose), true, () => {
        if (typeof item.onClose === "function") {
          item.onClose();
        }
      })), { icon: true, label: false });
      this.actionBar.setFocusable(false);
    }
  };
  Banner = __decorate$K([
    __param$J(0, IInstantiationService),
    __param$J(1, IMarkdownRendererService)
  ], Banner);
  const IWorkspaceTrustManagementService = createDecorator("workspaceTrustManagementService");
  var __decorate$J = 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$I = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  const warningIcon = registerIcon("extensions-warning-message", Codicon.warning, localize(1534, "Icon shown with a warning message in the extensions editor."));
  let UnicodeHighlighter = (_Ba = class extends Disposable {
    constructor(_editor, _editorWorkerService, _workspaceTrustService, instantiationService) {
      super();
      this._editor = _editor;
      this._editorWorkerService = _editorWorkerService;
      this._workspaceTrustService = _workspaceTrustService;
      this._highlighter = null;
      this._bannerClosed = false;
      this._updateState = (state) => {
        if (state && state.hasMore) {
          if (this._bannerClosed) {
            return;
          }
          const max = Math.max(state.ambiguousCharacterCount, state.nonBasicAsciiCharacterCount, state.invisibleCharacterCount);
          let data;
          if (state.nonBasicAsciiCharacterCount >= max) {
            data = {
              message: localize(1535, "This document contains many non-basic ASCII unicode characters"),
              command: new DisableHighlightingOfNonBasicAsciiCharactersAction()
            };
          } else if (state.ambiguousCharacterCount >= max) {
            data = {
              message: localize(1536, "This document contains many ambiguous unicode characters"),
              command: new DisableHighlightingOfAmbiguousCharactersAction()
            };
          } else if (state.invisibleCharacterCount >= max) {
            data = {
              message: localize(1537, "This document contains many invisible unicode characters"),
              command: new DisableHighlightingOfInvisibleCharactersAction()
            };
          } else {
            throw new Error("Unreachable");
          }
          this._bannerController.show({
            id: "unicodeHighlightBanner",
            message: data.message,
            icon: warningIcon,
            actions: [
              {
                label: data.command.shortLabel,
                href: `command:${data.command.desc.id}`
              }
            ],
            onClose: () => {
              this._bannerClosed = true;
            }
          });
        } else {
          this._bannerController.hide();
        }
      };
      this._bannerController = this._register(instantiationService.createInstance(BannerController, _editor));
      this._register(this._editor.onDidChangeModel(() => {
        this._bannerClosed = false;
        this._updateHighlighter();
      }));
      this._options = _editor.getOption(
        142
        /* EditorOption.unicodeHighlighting */
      );
      this._register(_workspaceTrustService.onDidChangeTrust((e) => {
        this._updateHighlighter();
      }));
      this._register(_editor.onDidChangeConfiguration((e) => {
        if (e.hasChanged(
          142
          /* EditorOption.unicodeHighlighting */
        )) {
          this._options = _editor.getOption(
            142
            /* EditorOption.unicodeHighlighting */
          );
          this._updateHighlighter();
        }
      }));
      this._updateHighlighter();
    }
    dispose() {
      if (this._highlighter) {
        this._highlighter.dispose();
        this._highlighter = null;
      }
      super.dispose();
    }
    _updateHighlighter() {
      this._updateState(null);
      if (this._highlighter) {
        this._highlighter.dispose();
        this._highlighter = null;
      }
      if (!this._editor.hasModel()) {
        return;
      }
      const options = resolveOptions(this._workspaceTrustService.isWorkspaceTrusted(), this._options);
      if ([
        options.nonBasicASCII,
        options.ambiguousCharacters,
        options.invisibleCharacters
      ].every((option2) => option2 === false)) {
        return;
      }
      const highlightOptions = {
        nonBasicASCII: options.nonBasicASCII,
        ambiguousCharacters: options.ambiguousCharacters,
        invisibleCharacters: options.invisibleCharacters,
        includeComments: options.includeComments,
        includeStrings: options.includeStrings,
        allowedCodePoints: Object.keys(options.allowedCharacters).map((c) => c.codePointAt(0)),
        allowedLocales: Object.keys(options.allowedLocales).map((locale) => {
          if (locale === "_os") {
            const osLocale = safeIntl.NumberFormat().value.resolvedOptions().locale;
            return osLocale;
          } else if (locale === "_vscode") {
            return language;
          }
          return locale;
        })
      };
      if (this._editorWorkerService.canComputeUnicodeHighlights(this._editor.getModel().uri)) {
        this._highlighter = new DocumentUnicodeHighlighter(this._editor, highlightOptions, this._updateState, this._editorWorkerService);
      } else {
        this._highlighter = new ViewportUnicodeHighlighter(this._editor, highlightOptions, this._updateState);
      }
    }
    getDecorationInfo(decoration2) {
      if (this._highlighter) {
        return this._highlighter.getDecorationInfo(decoration2);
      }
      return null;
    }
  }, _Ba.ID = "editor.contrib.unicodeHighlighter", _Ba);
  UnicodeHighlighter = __decorate$J([
    __param$I(1, IEditorWorkerService),
    __param$I(2, IWorkspaceTrustManagementService),
    __param$I(3, IInstantiationService)
  ], UnicodeHighlighter);
  function resolveOptions(trusted, options) {
    return {
      nonBasicASCII: options.nonBasicASCII === inUntrustedWorkspace ? !trusted : options.nonBasicASCII,
      ambiguousCharacters: options.ambiguousCharacters,
      invisibleCharacters: options.invisibleCharacters,
      includeComments: options.includeComments === inUntrustedWorkspace ? !trusted : options.includeComments,
      includeStrings: options.includeStrings === inUntrustedWorkspace ? !trusted : options.includeStrings,
      allowedCharacters: options.allowedCharacters,
      allowedLocales: options.allowedLocales
    };
  }
  let DocumentUnicodeHighlighter = class DocumentUnicodeHighlighter extends Disposable {
    constructor(_editor, _options, _updateState, _editorWorkerService) {
      super();
      this._editor = _editor;
      this._options = _options;
      this._updateState = _updateState;
      this._editorWorkerService = _editorWorkerService;
      this._model = this._editor.getModel();
      this._decorations = this._editor.createDecorationsCollection();
      this._updateSoon = this._register(new RunOnceScheduler(() => this._update(), 250));
      this._register(this._editor.onDidChangeModelContent(() => {
        this._updateSoon.schedule();
      }));
      this._updateSoon.schedule();
    }
    dispose() {
      this._decorations.clear();
      super.dispose();
    }
    _update() {
      if (this._model.isDisposed()) {
        return;
      }
      if (!this._model.mightContainNonBasicASCII()) {
        this._decorations.clear();
        return;
      }
      const modelVersionId = this._model.getVersionId();
      this._editorWorkerService.computedUnicodeHighlights(this._model.uri, this._options).then((info) => {
        if (this._model.isDisposed()) {
          return;
        }
        if (this._model.getVersionId() !== modelVersionId) {
          return;
        }
        this._updateState(info);
        const decorations = [];
        if (!info.hasMore) {
          for (const range2 of info.ranges) {
            decorations.push({
              range: range2,
              options: Decorations.instance.getDecorationFromOptions(this._options)
            });
          }
        }
        this._decorations.set(decorations);
      });
    }
    getDecorationInfo(decoration2) {
      if (!this._decorations.has(decoration2)) {
        return null;
      }
      const model = this._editor.getModel();
      if (!isModelDecorationVisible(model, decoration2)) {
        return null;
      }
      const text2 = model.getValueInRange(decoration2.range);
      return {
        reason: computeReason(text2, this._options),
        inComment: isModelDecorationInComment(model, decoration2),
        inString: isModelDecorationInString(model, decoration2)
      };
    }
  };
  DocumentUnicodeHighlighter = __decorate$J([
    __param$I(3, IEditorWorkerService)
  ], DocumentUnicodeHighlighter);
  class ViewportUnicodeHighlighter extends Disposable {
    constructor(_editor, _options, _updateState) {
      super();
      this._editor = _editor;
      this._options = _options;
      this._updateState = _updateState;
      this._model = this._editor.getModel();
      this._decorations = this._editor.createDecorationsCollection();
      this._updateSoon = this._register(new RunOnceScheduler(() => this._update(), 250));
      this._register(this._editor.onDidLayoutChange(() => {
        this._updateSoon.schedule();
      }));
      this._register(this._editor.onDidScrollChange(() => {
        this._updateSoon.schedule();
      }));
      this._register(this._editor.onDidChangeHiddenAreas(() => {
        this._updateSoon.schedule();
      }));
      this._register(this._editor.onDidChangeModelContent(() => {
        this._updateSoon.schedule();
      }));
      this._updateSoon.schedule();
    }
    dispose() {
      this._decorations.clear();
      super.dispose();
    }
    _update() {
      if (this._model.isDisposed()) {
        return;
      }
      if (!this._model.mightContainNonBasicASCII()) {
        this._decorations.clear();
        return;
      }
      const ranges = this._editor.getVisibleRanges();
      const decorations = [];
      const totalResult = {
        ranges: [],
        ambiguousCharacterCount: 0,
        invisibleCharacterCount: 0,
        nonBasicAsciiCharacterCount: 0,
        hasMore: false
      };
      for (const range2 of ranges) {
        const result = UnicodeTextModelHighlighter.computeUnicodeHighlights(this._model, this._options, range2);
        for (const r of result.ranges) {
          totalResult.ranges.push(r);
        }
        totalResult.ambiguousCharacterCount += totalResult.ambiguousCharacterCount;
        totalResult.invisibleCharacterCount += totalResult.invisibleCharacterCount;
        totalResult.nonBasicAsciiCharacterCount += totalResult.nonBasicAsciiCharacterCount;
        totalResult.hasMore = totalResult.hasMore || result.hasMore;
      }
      if (!totalResult.hasMore) {
        for (const range2 of totalResult.ranges) {
          decorations.push({ range: range2, options: Decorations.instance.getDecorationFromOptions(this._options) });
        }
      }
      this._updateState(totalResult);
      this._decorations.set(decorations);
    }
    getDecorationInfo(decoration2) {
      if (!this._decorations.has(decoration2)) {
        return null;
      }
      const model = this._editor.getModel();
      const text2 = model.getValueInRange(decoration2.range);
      if (!isModelDecorationVisible(model, decoration2)) {
        return null;
      }
      return {
        reason: computeReason(text2, this._options),
        inComment: isModelDecorationInComment(model, decoration2),
        inString: isModelDecorationInString(model, decoration2)
      };
    }
  }
  const configureUnicodeHighlightOptionsStr = localize(1538, "Configure Unicode Highlight Options");
  let UnicodeHighlighterHoverParticipant = class UnicodeHighlighterHoverParticipant {
    constructor(_editor, _markdownRendererService) {
      this._editor = _editor;
      this._markdownRendererService = _markdownRendererService;
      this.hoverOrdinal = 5;
    }
    computeSync(anchor, lineDecorations) {
      if (!this._editor.hasModel() || anchor.type !== 1) {
        return [];
      }
      const model = this._editor.getModel();
      const unicodeHighlighter = this._editor.getContribution(UnicodeHighlighter.ID);
      if (!unicodeHighlighter) {
        return [];
      }
      const result = [];
      const existedReason = /* @__PURE__ */ new Set();
      let index = 300;
      for (const d of lineDecorations) {
        const highlightInfo = unicodeHighlighter.getDecorationInfo(d);
        if (!highlightInfo) {
          continue;
        }
        const char = model.getValueInRange(d.range);
        const codePoint = char.codePointAt(0);
        const codePointStr = formatCodePointMarkdown(codePoint);
        let reason;
        switch (highlightInfo.reason.kind) {
          case 0: {
            if (isBasicASCII(highlightInfo.reason.confusableWith)) {
              reason = localize(1539, "The character {0} could be confused with the ASCII character {1}, which is more common in source code.", codePointStr, formatCodePointMarkdown(highlightInfo.reason.confusableWith.codePointAt(0)));
            } else {
              reason = localize(1540, "The character {0} could be confused with the character {1}, which is more common in source code.", codePointStr, formatCodePointMarkdown(highlightInfo.reason.confusableWith.codePointAt(0)));
            }
            break;
          }
          case 1:
            reason = localize(1541, "The character {0} is invisible.", codePointStr);
            break;
          case 2:
            reason = localize(1542, "The character {0} is not a basic ASCII character.", codePointStr);
            break;
        }
        if (existedReason.has(reason)) {
          continue;
        }
        existedReason.add(reason);
        const adjustSettingsArgs = {
          codePoint,
          reason: highlightInfo.reason,
          inComment: highlightInfo.inComment,
          inString: highlightInfo.inString
        };
        const adjustSettings = localize(1543, "Adjust settings");
        const uri = createCommandUri(ShowExcludeOptions.ID, adjustSettingsArgs);
        const markdown = new MarkdownString("", true).appendMarkdown(reason).appendText(" ").appendLink(uri, adjustSettings, configureUnicodeHighlightOptionsStr);
        result.push(new MarkdownHover(this, d.range, [markdown], false, index++));
      }
      return result;
    }
    renderHoverParts(context, hoverParts) {
      return renderMarkdownHovers(context, hoverParts, this._editor, this._markdownRendererService);
    }
    getAccessibleContent(hoverPart) {
      return hoverPart.contents.map((c) => c.value).join("\n");
    }
  };
  UnicodeHighlighterHoverParticipant = __decorate$J([
    __param$I(1, IMarkdownRendererService)
  ], UnicodeHighlighterHoverParticipant);
  function codePointToHex(codePoint) {
    return `U+${codePoint.toString(16).padStart(4, "0")}`;
  }
  function formatCodePointMarkdown(codePoint) {
    let value = `\`${codePointToHex(codePoint)}\``;
    if (!InvisibleCharacters.isInvisibleCharacter(codePoint)) {
      value += ` "${`${renderCodePointAsInlineCode(codePoint)}`}"`;
    }
    return value;
  }
  function renderCodePointAsInlineCode(codePoint) {
    if (codePoint === 96) {
      return "`` ` ``";
    }
    return "`" + String.fromCodePoint(codePoint) + "`";
  }
  function computeReason(char, options) {
    return UnicodeTextModelHighlighter.computeUnicodeHighlightReason(char, options);
  }
  const _Decorations = class _Decorations {
    constructor() {
      this.map = /* @__PURE__ */ new Map();
    }
    getDecorationFromOptions(options) {
      return this.getDecoration(!options.includeComments, !options.includeStrings);
    }
    getDecoration(hideInComments, hideInStrings) {
      const key = `${hideInComments}${hideInStrings}`;
      let options = this.map.get(key);
      if (!options) {
        options = ModelDecorationOptions.createDynamic({
          description: "unicode-highlight",
          stickiness: 1,
          className: "unicode-highlight",
          showIfCollapsed: true,
          overviewRuler: null,
          minimap: null,
          hideInCommentTokens: hideInComments,
          hideInStringTokens: hideInStrings
        });
        this.map.set(key, options);
      }
      return options;
    }
  };
  _Decorations.instance = new _Decorations();
  let Decorations = _Decorations;
  class DisableHighlightingInCommentsAction extends EditorAction {
    constructor() {
      super({
        id: DisableHighlightingOfAmbiguousCharactersAction.ID,
        label: localize2(1552, "Disable highlighting of characters in comments"),
        precondition: void 0
      });
      this.shortLabel = localize(1544, "Disable Highlight In Comments");
    }
    async run(accessor, editor2, args) {
      const configurationService = accessor.get(IConfigurationService);
      if (configurationService) {
        this.runAction(configurationService);
      }
    }
    async runAction(configurationService) {
      await configurationService.updateValue(
        unicodeHighlightConfigKeys.includeComments,
        false,
        2
        /* ConfigurationTarget.USER */
      );
    }
  }
  class DisableHighlightingInStringsAction extends EditorAction {
    constructor() {
      super({
        id: DisableHighlightingOfAmbiguousCharactersAction.ID,
        label: localize2(1553, "Disable highlighting of characters in strings"),
        precondition: void 0
      });
      this.shortLabel = localize(1545, "Disable Highlight In Strings");
    }
    async run(accessor, editor2, args) {
      const configurationService = accessor.get(IConfigurationService);
      if (configurationService) {
        this.runAction(configurationService);
      }
    }
    async runAction(configurationService) {
      await configurationService.updateValue(
        unicodeHighlightConfigKeys.includeStrings,
        false,
        2
        /* ConfigurationTarget.USER */
      );
    }
  }
  const _DisableHighlightingOfAmbiguousCharactersAction = class _DisableHighlightingOfAmbiguousCharactersAction extends Action2 {
    constructor() {
      super({
        id: _DisableHighlightingOfAmbiguousCharactersAction.ID,
        title: localize2(1554, "Disable highlighting of ambiguous characters"),
        precondition: void 0,
        f1: false
      });
      this.shortLabel = localize(1546, "Disable Ambiguous Highlight");
    }
    async run(accessor, editor2, args) {
      const configurationService = accessor.get(IConfigurationService);
      if (configurationService) {
        this.runAction(configurationService);
      }
    }
    async runAction(configurationService) {
      await configurationService.updateValue(
        unicodeHighlightConfigKeys.ambiguousCharacters,
        false,
        2
        /* ConfigurationTarget.USER */
      );
    }
  };
  _DisableHighlightingOfAmbiguousCharactersAction.ID = "editor.action.unicodeHighlight.disableHighlightingOfAmbiguousCharacters";
  let DisableHighlightingOfAmbiguousCharactersAction = _DisableHighlightingOfAmbiguousCharactersAction;
  const _DisableHighlightingOfInvisibleCharactersAction = class _DisableHighlightingOfInvisibleCharactersAction extends Action2 {
    constructor() {
      super({
        id: _DisableHighlightingOfInvisibleCharactersAction.ID,
        title: localize2(1555, "Disable highlighting of invisible characters"),
        precondition: void 0,
        f1: false
      });
      this.shortLabel = localize(1547, "Disable Invisible Highlight");
    }
    async run(accessor, editor2, args) {
      const configurationService = accessor.get(IConfigurationService);
      if (configurationService) {
        this.runAction(configurationService);
      }
    }
    async runAction(configurationService) {
      await configurationService.updateValue(
        unicodeHighlightConfigKeys.invisibleCharacters,
        false,
        2
        /* ConfigurationTarget.USER */
      );
    }
  };
  _DisableHighlightingOfInvisibleCharactersAction.ID = "editor.action.unicodeHighlight.disableHighlightingOfInvisibleCharacters";
  let DisableHighlightingOfInvisibleCharactersAction = _DisableHighlightingOfInvisibleCharactersAction;
  const _DisableHighlightingOfNonBasicAsciiCharactersAction = class _DisableHighlightingOfNonBasicAsciiCharactersAction extends Action2 {
    constructor() {
      super({
        id: _DisableHighlightingOfNonBasicAsciiCharactersAction.ID,
        title: localize2(1556, "Disable highlighting of non basic ASCII characters"),
        precondition: void 0,
        f1: false
      });
      this.shortLabel = localize(1548, "Disable Non ASCII Highlight");
    }
    async run(accessor, editor2, args) {
      const configurationService = accessor.get(IConfigurationService);
      if (configurationService) {
        this.runAction(configurationService);
      }
    }
    async runAction(configurationService) {
      await configurationService.updateValue(
        unicodeHighlightConfigKeys.nonBasicASCII,
        false,
        2
        /* ConfigurationTarget.USER */
      );
    }
  };
  _DisableHighlightingOfNonBasicAsciiCharactersAction.ID = "editor.action.unicodeHighlight.disableHighlightingOfNonBasicAsciiCharacters";
  let DisableHighlightingOfNonBasicAsciiCharactersAction = _DisableHighlightingOfNonBasicAsciiCharactersAction;
  const _ShowExcludeOptions = class _ShowExcludeOptions extends Action2 {
    constructor() {
      super({
        id: _ShowExcludeOptions.ID,
        title: localize2(1557, "Show Exclude Options"),
        precondition: void 0,
        f1: false
      });
    }
    async run(accessor, args) {
      const { codePoint, reason, inString, inComment } = args;
      const char = String.fromCodePoint(codePoint);
      const quickPickService = accessor.get(IQuickInputService);
      const configurationService = accessor.get(IConfigurationService);
      function getExcludeCharFromBeingHighlightedLabel(codePoint2) {
        if (InvisibleCharacters.isInvisibleCharacter(codePoint2)) {
          return localize(1549, "Exclude {0} (invisible character) from being highlighted", codePointToHex(codePoint2));
        }
        return localize(1550, "Exclude {0} from being highlighted", `${codePointToHex(codePoint2)} "${char}"`);
      }
      const options = [];
      if (reason.kind === 0) {
        for (const locale of reason.notAmbiguousInLocales) {
          options.push({
            label: localize(1551, 'Allow unicode characters that are more common in the language "{0}".', locale),
            run: async () => {
              excludeLocaleFromBeingHighlighted(configurationService, [locale]);
            }
          });
        }
      }
      options.push({
        label: getExcludeCharFromBeingHighlightedLabel(codePoint),
        run: () => excludeCharFromBeingHighlighted(configurationService, [codePoint])
      });
      if (inComment) {
        const action = new DisableHighlightingInCommentsAction();
        options.push({ label: action.label, run: async () => action.runAction(configurationService) });
      } else if (inString) {
        const action = new DisableHighlightingInStringsAction();
        options.push({ label: action.label, run: async () => action.runAction(configurationService) });
      }
      function getTitle(options2) {
        return typeof options2.desc.title === "string" ? options2.desc.title : options2.desc.title.value;
      }
      if (reason.kind === 0) {
        const action = new DisableHighlightingOfAmbiguousCharactersAction();
        options.push({ label: getTitle(action), run: async () => action.runAction(configurationService) });
      } else if (reason.kind === 1) {
        const action = new DisableHighlightingOfInvisibleCharactersAction();
        options.push({ label: getTitle(action), run: async () => action.runAction(configurationService) });
      } else if (reason.kind === 2) {
        const action = new DisableHighlightingOfNonBasicAsciiCharactersAction();
        options.push({ label: getTitle(action), run: async () => action.runAction(configurationService) });
      } else {
        expectNever(reason);
      }
      const result = await quickPickService.pick(options, { title: configureUnicodeHighlightOptionsStr });
      if (result) {
        await result.run();
      }
    }
  };
  _ShowExcludeOptions.ID = "editor.action.unicodeHighlight.showExcludeOptions";
  let ShowExcludeOptions = _ShowExcludeOptions;
  async function excludeCharFromBeingHighlighted(configurationService, charCodes) {
    const existingValue = configurationService.getValue(unicodeHighlightConfigKeys.allowedCharacters);
    let value;
    if (typeof existingValue === "object" && existingValue) {
      value = existingValue;
    } else {
      value = {};
    }
    for (const charCode of charCodes) {
      value[String.fromCodePoint(charCode)] = true;
    }
    await configurationService.updateValue(
      unicodeHighlightConfigKeys.allowedCharacters,
      value,
      2
      /* ConfigurationTarget.USER */
    );
  }
  async function excludeLocaleFromBeingHighlighted(configurationService, locales) {
    const existingValue = configurationService.inspect(unicodeHighlightConfigKeys.allowedLocales).user?.value;
    let value;
    if (typeof existingValue === "object" && existingValue) {
      value = Object.assign({}, existingValue);
    } else {
      value = {};
    }
    for (const locale of locales) {
      value[locale] = true;
    }
    await configurationService.updateValue(
      unicodeHighlightConfigKeys.allowedLocales,
      value,
      2
      /* ConfigurationTarget.USER */
    );
  }
  function expectNever(value) {
    throw new Error(`Unexpected value: ${value}`);
  }
  registerAction2(DisableHighlightingOfAmbiguousCharactersAction);
  registerAction2(DisableHighlightingOfInvisibleCharactersAction);
  registerAction2(DisableHighlightingOfNonBasicAsciiCharactersAction);
  registerAction2(ShowExcludeOptions);
  registerEditorContribution(
    UnicodeHighlighter.ID,
    UnicodeHighlighter,
    1
    /* EditorContributionInstantiation.AfterFirstRender */
  );
  HoverParticipantRegistry.register(UnicodeHighlighterHoverParticipant);
  const IDialogService = createDecorator("dialogService");
  var __decorate$I = 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$H = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  const ignoreUnusualLineTerminators = "ignoreUnusualLineTerminators";
  function writeIgnoreState(codeEditorService, model, state) {
    codeEditorService.setModelProperty(model.uri, ignoreUnusualLineTerminators, state);
  }
  function readIgnoreState(codeEditorService, model) {
    return codeEditorService.getModelProperty(model.uri, ignoreUnusualLineTerminators);
  }
  let UnusualLineTerminatorsDetector = (_Ca = class extends Disposable {
    constructor(_editor, _dialogService, _codeEditorService) {
      super();
      this._editor = _editor;
      this._dialogService = _dialogService;
      this._codeEditorService = _codeEditorService;
      this._isPresentingDialog = false;
      this._config = this._editor.getOption(
        143
        /* EditorOption.unusualLineTerminators */
      );
      this._register(this._editor.onDidChangeConfiguration((e) => {
        if (e.hasChanged(
          143
          /* EditorOption.unusualLineTerminators */
        )) {
          this._config = this._editor.getOption(
            143
            /* EditorOption.unusualLineTerminators */
          );
          this._checkForUnusualLineTerminators();
        }
      }));
      this._register(this._editor.onDidChangeModel(() => {
        this._checkForUnusualLineTerminators();
      }));
      this._register(this._editor.onDidChangeModelContent((e) => {
        if (e.isUndoing) {
          return;
        }
        this._checkForUnusualLineTerminators();
      }));
      this._checkForUnusualLineTerminators();
    }
    async _checkForUnusualLineTerminators() {
      if (this._config === "off") {
        return;
      }
      if (!this._editor.hasModel()) {
        return;
      }
      const model = this._editor.getModel();
      if (!model.mightContainUnusualLineTerminators()) {
        return;
      }
      const ignoreState = readIgnoreState(this._codeEditorService, model);
      if (ignoreState === true) {
        return;
      }
      if (this._editor.getOption(
        104
        /* EditorOption.readOnly */
      )) {
        return;
      }
      if (this._config === "auto") {
        model.removeUnusualLineTerminators(this._editor.getSelections());
        return;
      }
      if (this._isPresentingDialog) {
        return;
      }
      let result;
      try {
        this._isPresentingDialog = true;
        result = await this._dialogService.confirm({
          title: localize(1558, "Unusual Line Terminators"),
          message: localize(1559, "Detected unusual line terminators"),
          detail: localize(1560, "The file '{0}' contains one or more unusual line terminator characters, like Line Separator (LS) or Paragraph Separator (PS).\n\nIt is recommended to remove them from the file. This can be configured via `editor.unusualLineTerminators`.", basename(model.uri)),
          primaryButton: localize(1561, "&&Remove Unusual Line Terminators"),
          cancelButton: localize(1562, "Ignore")
        });
      } finally {
        this._isPresentingDialog = false;
      }
      if (!result.confirmed) {
        writeIgnoreState(this._codeEditorService, model, true);
        return;
      }
      model.removeUnusualLineTerminators(this._editor.getSelections());
    }
  }, _Ca.ID = "editor.contrib.unusualLineTerminatorsDetector", _Ca);
  UnusualLineTerminatorsDetector = __decorate$I([
    __param$H(1, IDialogService),
    __param$H(2, ICodeEditorService)
  ], UnusualLineTerminatorsDetector);
  registerEditorContribution(
    UnusualLineTerminatorsDetector.ID,
    UnusualLineTerminatorsDetector,
    1
    /* EditorContributionInstantiation.AfterFirstRender */
  );
  const GLOBSTAR = "**";
  const GLOB_SPLIT = "/";
  const PATH_REGEX = "[/\\\\]";
  const NO_PATH_REGEX = "[^/\\\\]";
  const ALL_FORWARD_SLASHES = /\//g;
  function starsToRegExp(starCount, isLastPattern) {
    switch (starCount) {
      case 0:
        return "";
      case 1:
        return `${NO_PATH_REGEX}*?`;
      // 1 star matches any number of characters except path separator (/ and \) - non greedy (?)
      default:
        return `(?:${PATH_REGEX}|${NO_PATH_REGEX}+${PATH_REGEX}${isLastPattern ? `|${PATH_REGEX}${NO_PATH_REGEX}+` : ""})*?`;
    }
  }
  function splitGlobAware(pattern, splitChar) {
    if (!pattern) {
      return [];
    }
    const segments = [];
    let inBraces = false;
    let inBrackets = false;
    let curVal = "";
    for (const char of pattern) {
      switch (char) {
        case splitChar:
          if (!inBraces && !inBrackets) {
            segments.push(curVal);
            curVal = "";
            continue;
          }
          break;
        case "{":
          inBraces = true;
          break;
        case "}":
          inBraces = false;
          break;
        case "[":
          inBrackets = true;
          break;
        case "]":
          inBrackets = false;
          break;
      }
      curVal += char;
    }
    if (curVal) {
      segments.push(curVal);
    }
    return segments;
  }
  function parseRegExp(pattern) {
    if (!pattern) {
      return "";
    }
    let regEx = "";
    const segments = splitGlobAware(pattern, GLOB_SPLIT);
    if (segments.every((segment) => segment === GLOBSTAR)) {
      regEx = ".*";
    } else {
      let previousSegmentWasGlobStar = false;
      segments.forEach((segment, index) => {
        if (segment === GLOBSTAR) {
          if (previousSegmentWasGlobStar) {
            return;
          }
          regEx += starsToRegExp(2, index === segments.length - 1);
        } else {
          let inBraces = false;
          let braceVal = "";
          let inBrackets = false;
          let bracketVal = "";
          for (const char of segment) {
            if (char !== "}" && inBraces) {
              braceVal += char;
              continue;
            }
            if (inBrackets && (char !== "]" || !bracketVal)) {
              let res;
              if (char === "-") {
                res = char;
              } else if ((char === "^" || char === "!") && !bracketVal) {
                res = "^";
              } else if (char === GLOB_SPLIT) {
                res = "";
              } else {
                res = escapeRegExpCharacters(char);
              }
              bracketVal += res;
              continue;
            }
            switch (char) {
              case "{":
                inBraces = true;
                continue;
              case "[":
                inBrackets = true;
                continue;
              case "}": {
                const choices = splitGlobAware(braceVal, ",");
                const braceRegExp = `(?:${choices.map((choice) => parseRegExp(choice)).join("|")})`;
                regEx += braceRegExp;
                inBraces = false;
                braceVal = "";
                break;
              }
              case "]": {
                regEx += "[" + bracketVal + "]";
                inBrackets = false;
                bracketVal = "";
                break;
              }
              case "?":
                regEx += NO_PATH_REGEX;
                continue;
              case "*":
                regEx += starsToRegExp(1);
                continue;
              default:
                regEx += escapeRegExpCharacters(char);
            }
          }
          if (index < segments.length - 1 && // more segments to come after this
          (segments[index + 1] !== GLOBSTAR || // next segment is not **, or...
          index + 2 < segments.length)) {
            regEx += PATH_REGEX;
          }
        }
        previousSegmentWasGlobStar = segment === GLOBSTAR;
      });
    }
    return regEx;
  }
  const T1 = /^\*\*\/\*\.[\w\.-]+$/;
  const T2 = /^\*\*\/([\w\.-]+)\/?$/;
  const T3 = /^{\*\*\/\*?[\w\.-]+\/?(,\*\*\/\*?[\w\.-]+\/?)*}$/;
  const T3_2 = /^{\*\*\/\*?[\w\.-]+(\/(\*\*)?)?(,\*\*\/\*?[\w\.-]+(\/(\*\*)?)?)*}$/;
  const T4 = /^\*\*((\/[\w\.-]+)+)\/?$/;
  const T5 = /^([\w\.-]+(\/[\w\.-]+)*)\/?$/;
  const CACHE = new LRUCache(1e4);
  const FALSE = function() {
    return false;
  };
  const NULL = function() {
    return null;
  };
  function parsePattern(arg1, options) {
    if (!arg1) {
      return NULL;
    }
    let pattern;
    if (typeof arg1 !== "string") {
      pattern = arg1.pattern;
    } else {
      pattern = arg1;
    }
    pattern = pattern.trim();
    const ignoreCase = options.ignoreCase ?? false;
    const internalOptions = {
      ...options,
      equals: ignoreCase ? equalsIgnoreCase : (a, b) => a === b,
      endsWith: ignoreCase ? endsWithIgnoreCase : (str, candidate) => str.endsWith(candidate),
      // TODO: the '!isLinux' part below is to keep current behavior unchanged, but it should probably be removed
      // in favor of passing correct options from the caller.
      isEqualOrParent: (base, candidate) => isEqualOrParent(base, candidate, !isLinux || ignoreCase)
    };
    const patternKey = `${ignoreCase ? pattern.toLowerCase() : pattern}_${!!options.trimForExclusions}_${ignoreCase}`;
    let parsedPattern = CACHE.get(patternKey);
    if (parsedPattern) {
      return wrapRelativePattern(parsedPattern, arg1, internalOptions);
    }
    let match2;
    if (T1.test(pattern)) {
      parsedPattern = trivia1(pattern.substring(4), pattern, internalOptions);
    } else if (match2 = T2.exec(trimForExclusions(pattern, internalOptions))) {
      parsedPattern = trivia2(match2[1], pattern, internalOptions);
    } else if ((options.trimForExclusions ? T3_2 : T3).test(pattern)) {
      parsedPattern = trivia3(pattern, internalOptions);
    } else if (match2 = T4.exec(trimForExclusions(pattern, internalOptions))) {
      parsedPattern = trivia4and5(match2[1].substring(1), pattern, true, internalOptions);
    } else if (match2 = T5.exec(trimForExclusions(pattern, internalOptions))) {
      parsedPattern = trivia4and5(match2[1], pattern, false, internalOptions);
    } else {
      parsedPattern = toRegExp(pattern, internalOptions);
    }
    CACHE.set(patternKey, parsedPattern);
    return wrapRelativePattern(parsedPattern, arg1, internalOptions);
  }
  function wrapRelativePattern(parsedPattern, arg2, options) {
    if (typeof arg2 === "string") {
      return parsedPattern;
    }
    const wrappedPattern = function(path, basename2) {
      if (!options.isEqualOrParent(path, arg2.base)) {
        return null;
      }
      return parsedPattern(ltrim(path.substring(arg2.base.length), sep), basename2);
    };
    wrappedPattern.allBasenames = parsedPattern.allBasenames;
    wrappedPattern.allPaths = parsedPattern.allPaths;
    wrappedPattern.basenames = parsedPattern.basenames;
    wrappedPattern.patterns = parsedPattern.patterns;
    return wrappedPattern;
  }
  function trimForExclusions(pattern, options) {
    return options.trimForExclusions && pattern.endsWith("/**") ? pattern.substring(0, pattern.length - 2) : pattern;
  }
  function trivia1(base, pattern, options) {
    return function(path, basename2) {
      return typeof path === "string" && options.endsWith(path, base) ? pattern : null;
    };
  }
  function trivia2(base, pattern, options) {
    const slashBase = `/${base}`;
    const backslashBase = `\\${base}`;
    const parsedPattern = function(path, basename2) {
      if (typeof path !== "string") {
        return null;
      }
      if (basename2) {
        return options.equals(basename2, base) ? pattern : null;
      }
      return options.equals(path, base) || options.endsWith(path, slashBase) || options.endsWith(path, backslashBase) ? pattern : null;
    };
    const basenames = [base];
    parsedPattern.basenames = basenames;
    parsedPattern.patterns = [pattern];
    parsedPattern.allBasenames = basenames;
    return parsedPattern;
  }
  function trivia3(pattern, options) {
    const parsedPatterns = aggregateBasenameMatches(pattern.slice(1, -1).split(",").map((pattern2) => parsePattern(pattern2, options)).filter((pattern2) => pattern2 !== NULL), pattern);
    const patternsLength = parsedPatterns.length;
    if (!patternsLength) {
      return NULL;
    }
    if (patternsLength === 1) {
      return parsedPatterns[0];
    }
    const parsedPattern = function(path, basename2) {
      for (let i2 = 0, n2 = parsedPatterns.length; i2 < n2; i2++) {
        if (parsedPatterns[i2](path, basename2)) {
          return pattern;
        }
      }
      return null;
    };
    const withBasenames = parsedPatterns.find((pattern2) => !!pattern2.allBasenames);
    if (withBasenames) {
      parsedPattern.allBasenames = withBasenames.allBasenames;
    }
    const allPaths = parsedPatterns.reduce((all, current) => current.allPaths ? all.concat(current.allPaths) : all, []);
    if (allPaths.length) {
      parsedPattern.allPaths = allPaths;
    }
    return parsedPattern;
  }
  function trivia4and5(targetPath, pattern, matchPathEnds, options) {
    const usingPosixSep = sep === posix.sep;
    const nativePath = usingPosixSep ? targetPath : targetPath.replace(ALL_FORWARD_SLASHES, sep);
    const nativePathEnd = sep + nativePath;
    const targetPathEnd = posix.sep + targetPath;
    let parsedPattern;
    if (matchPathEnds) {
      parsedPattern = function(path, basename2) {
        return typeof path === "string" && (options.equals(path, nativePath) || options.endsWith(path, nativePathEnd) || !usingPosixSep && (options.equals(path, targetPath) || options.endsWith(path, targetPathEnd))) ? pattern : null;
      };
    } else {
      parsedPattern = function(path, basename2) {
        return typeof path === "string" && (options.equals(path, nativePath) || !usingPosixSep && options.equals(path, targetPath)) ? pattern : null;
      };
    }
    parsedPattern.allPaths = [(matchPathEnds ? "*/" : "./") + targetPath];
    return parsedPattern;
  }
  function toRegExp(pattern, options) {
    try {
      const regExp = new RegExp(`^${parseRegExp(pattern)}$`, options.ignoreCase ? "i" : void 0);
      return function(path) {
        regExp.lastIndex = 0;
        return typeof path === "string" && regExp.test(path) ? pattern : null;
      };
    } catch {
      return NULL;
    }
  }
  function match(arg1, path, options) {
    if (!arg1 || typeof path !== "string") {
      return false;
    }
    return parse(arg1, options)(path);
  }
  function parse(arg1, options = {}) {
    if (!arg1) {
      return FALSE;
    }
    if (typeof arg1 === "string" || isRelativePattern(arg1)) {
      const parsedPattern = parsePattern(arg1, options);
      if (parsedPattern === NULL) {
        return FALSE;
      }
      const resultPattern = function(path, basename2) {
        return !!parsedPattern(path, basename2);
      };
      if (parsedPattern.allBasenames) {
        resultPattern.allBasenames = parsedPattern.allBasenames;
      }
      if (parsedPattern.allPaths) {
        resultPattern.allPaths = parsedPattern.allPaths;
      }
      return resultPattern;
    }
    return parsedExpression(arg1, options);
  }
  function isRelativePattern(obj) {
    const rp = obj;
    if (!rp) {
      return false;
    }
    return typeof rp.base === "string" && typeof rp.pattern === "string";
  }
  function parsedExpression(expression, options) {
    const parsedPatterns = aggregateBasenameMatches(Object.getOwnPropertyNames(expression).map((pattern) => parseExpressionPattern(pattern, expression[pattern], options)).filter((pattern) => pattern !== NULL));
    const patternsLength = parsedPatterns.length;
    if (!patternsLength) {
      return NULL;
    }
    if (!parsedPatterns.some((parsedPattern) => !!parsedPattern.requiresSiblings)) {
      if (patternsLength === 1) {
        return parsedPatterns[0];
      }
      const resultExpression2 = function(path, basename2) {
        let resultPromises = void 0;
        for (let i2 = 0, n2 = parsedPatterns.length; i2 < n2; i2++) {
          const result = parsedPatterns[i2](path, basename2);
          if (typeof result === "string") {
            return result;
          }
          if (isThenable$1(result)) {
            if (!resultPromises) {
              resultPromises = [];
            }
            resultPromises.push(result);
          }
        }
        if (resultPromises) {
          return (async () => {
            for (const resultPromise of resultPromises) {
              const result = await resultPromise;
              if (typeof result === "string") {
                return result;
              }
            }
            return null;
          })();
        }
        return null;
      };
      const withBasenames2 = parsedPatterns.find((pattern) => !!pattern.allBasenames);
      if (withBasenames2) {
        resultExpression2.allBasenames = withBasenames2.allBasenames;
      }
      const allPaths2 = parsedPatterns.reduce((all, current) => current.allPaths ? all.concat(current.allPaths) : all, []);
      if (allPaths2.length) {
        resultExpression2.allPaths = allPaths2;
      }
      return resultExpression2;
    }
    const resultExpression = function(path, base, hasSibling) {
      let name = void 0;
      let resultPromises = void 0;
      for (let i2 = 0, n2 = parsedPatterns.length; i2 < n2; i2++) {
        const parsedPattern = parsedPatterns[i2];
        if (parsedPattern.requiresSiblings && hasSibling) {
          if (!base) {
            base = basename$1(path);
          }
          if (!name) {
            name = base.substring(0, base.length - extname$1(path).length);
          }
        }
        const result = parsedPattern(path, base, name, hasSibling);
        if (typeof result === "string") {
          return result;
        }
        if (isThenable$1(result)) {
          if (!resultPromises) {
            resultPromises = [];
          }
          resultPromises.push(result);
        }
      }
      if (resultPromises) {
        return (async () => {
          for (const resultPromise of resultPromises) {
            const result = await resultPromise;
            if (typeof result === "string") {
              return result;
            }
          }
          return null;
        })();
      }
      return null;
    };
    const withBasenames = parsedPatterns.find((pattern) => !!pattern.allBasenames);
    if (withBasenames) {
      resultExpression.allBasenames = withBasenames.allBasenames;
    }
    const allPaths = parsedPatterns.reduce((all, current) => current.allPaths ? all.concat(current.allPaths) : all, []);
    if (allPaths.length) {
      resultExpression.allPaths = allPaths;
    }
    return resultExpression;
  }
  function parseExpressionPattern(pattern, value, options) {
    if (value === false) {
      return NULL;
    }
    const parsedPattern = parsePattern(pattern, options);
    if (parsedPattern === NULL) {
      return NULL;
    }
    if (typeof value === "boolean") {
      return parsedPattern;
    }
    if (value) {
      const when = value.when;
      if (typeof when === "string") {
        const result = (path, basename2, name, hasSibling) => {
          if (!hasSibling || !parsedPattern(path, basename2)) {
            return null;
          }
          const clausePattern = when.replace("$(basename)", () => name);
          const matched = hasSibling(clausePattern);
          return isThenable$1(matched) ? matched.then((match2) => match2 ? pattern : null) : matched ? pattern : null;
        };
        result.requiresSiblings = true;
        return result;
      }
    }
    return parsedPattern;
  }
  function aggregateBasenameMatches(parsedPatterns, result) {
    const basenamePatterns = parsedPatterns.filter((parsedPattern) => !!parsedPattern.basenames);
    if (basenamePatterns.length < 2) {
      return parsedPatterns;
    }
    const basenames = basenamePatterns.reduce((all, current) => {
      const basenames2 = current.basenames;
      return basenames2 ? all.concat(basenames2) : all;
    }, []);
    let patterns;
    if (result) {
      patterns = [];
      for (let i2 = 0, n2 = basenames.length; i2 < n2; i2++) {
        patterns.push(result);
      }
    } else {
      patterns = basenamePatterns.reduce((all, current) => {
        const patterns2 = current.patterns;
        return patterns2 ? all.concat(patterns2) : all;
      }, []);
    }
    const aggregate = function(path, basename2) {
      if (typeof path !== "string") {
        return null;
      }
      if (!basename2) {
        let i2;
        for (i2 = path.length; i2 > 0; i2--) {
          const ch = path.charCodeAt(i2 - 1);
          if (ch === 47 || ch === 92) {
            break;
          }
        }
        basename2 = path.substring(i2);
      }
      const index = basenames.indexOf(basename2);
      return index !== -1 ? patterns[index] : null;
    };
    aggregate.basenames = basenames;
    aggregate.patterns = patterns;
    aggregate.allBasenames = basenames;
    const aggregatedPatterns = parsedPatterns.filter((parsedPattern) => !parsedPattern.basenames);
    aggregatedPatterns.push(aggregate);
    return aggregatedPatterns;
  }
  function score(selector, candidateUri, candidateLanguage, candidateIsSynchronized, candidateNotebookUri, candidateNotebookType) {
    if (Array.isArray(selector)) {
      let ret = 0;
      for (const filter of selector) {
        const value = score(filter, candidateUri, candidateLanguage, candidateIsSynchronized, candidateNotebookUri, candidateNotebookType);
        if (value === 10) {
          return value;
        }
        if (value > ret) {
          ret = value;
        }
      }
      return ret;
    } else if (typeof selector === "string") {
      if (!candidateIsSynchronized) {
        return 0;
      }
      if (selector === "*") {
        return 5;
      } else if (selector === candidateLanguage) {
        return 10;
      } else {
        return 0;
      }
    } else if (selector) {
      const { language: language2, pattern, scheme, hasAccessToAllModels, notebookType } = selector;
      if (!candidateIsSynchronized && !hasAccessToAllModels) {
        return 0;
      }
      if (notebookType && candidateNotebookUri) {
        candidateUri = candidateNotebookUri;
      }
      let ret = 0;
      if (scheme) {
        if (scheme === candidateUri.scheme) {
          ret = 10;
        } else if (scheme === "*") {
          ret = 5;
        } else {
          return 0;
        }
      }
      if (language2) {
        if (language2 === candidateLanguage) {
          ret = 10;
        } else if (language2 === "*") {
          ret = Math.max(ret, 5);
        } else {
          return 0;
        }
      }
      if (notebookType) {
        if (notebookType === candidateNotebookType) {
          ret = 10;
        } else if (notebookType === "*" && candidateNotebookType !== void 0) {
          ret = Math.max(ret, 5);
        } else {
          return 0;
        }
      }
      if (pattern) {
        let normalizedPattern;
        if (typeof pattern === "string") {
          normalizedPattern = pattern;
        } else {
          normalizedPattern = { ...pattern, base: normalize$1(pattern.base) };
        }
        if (normalizedPattern === candidateUri.fsPath || match(normalizedPattern, candidateUri.fsPath)) {
          ret = 10;
        } else {
          return 0;
        }
      }
      return ret;
    } else {
      return 0;
    }
  }
  var __decorate$H = 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$G = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  class TextualDocumentHighlightProvider {
    constructor() {
      this.selector = { language: "*" };
    }
    provideDocumentHighlights(model, position, token) {
      const result = [];
      const word = model.getWordAtPosition({
        lineNumber: position.lineNumber,
        column: position.column
      });
      if (!word) {
        return Promise.resolve(result);
      }
      if (model.isDisposed()) {
        return;
      }
      const matches = model.findMatches(word.word, true, false, true, USUAL_WORD_SEPARATORS, false);
      return matches.map((m) => ({
        range: m.range,
        kind: DocumentHighlightKind$1.Text
      }));
    }
    provideMultiDocumentHighlights(primaryModel, position, otherModels, token) {
      const result = new ResourceMap();
      const word = primaryModel.getWordAtPosition({
        lineNumber: position.lineNumber,
        column: position.column
      });
      if (!word) {
        return Promise.resolve(result);
      }
      for (const model of [primaryModel, ...otherModels]) {
        if (model.isDisposed()) {
          continue;
        }
        const matches = model.findMatches(word.word, true, false, true, USUAL_WORD_SEPARATORS, false);
        const highlights = matches.map((m) => ({
          range: m.range,
          kind: DocumentHighlightKind$1.Text
        }));
        if (highlights) {
          result.set(model.uri, highlights);
        }
      }
      return result;
    }
  }
  let TextualMultiDocumentHighlightFeature = class TextualMultiDocumentHighlightFeature extends Disposable {
    constructor(languageFeaturesService) {
      super();
      this._register(languageFeaturesService.documentHighlightProvider.register("*", new TextualDocumentHighlightProvider()));
      this._register(languageFeaturesService.multiDocumentHighlightProvider.register("*", new TextualDocumentHighlightProvider()));
    }
  };
  TextualMultiDocumentHighlightFeature = __decorate$H([
    __param$G(0, ILanguageFeaturesService)
  ], TextualMultiDocumentHighlightFeature);
  var __decorate$G = 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$F = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  var WordHighlighter_1, WordHighlighterContribution_1;
  const ctxHasWordHighlights = new RawContextKey("hasWordHighlights", false);
  function getOccurrencesAtPosition(registry, model, position, token) {
    const orderedByScore = registry.ordered(model);
    return first(orderedByScore.map((provider) => () => {
      return Promise.resolve(provider.provideDocumentHighlights(model, position, token)).then(void 0, onUnexpectedExternalError);
    }), (result) => result !== void 0 && result !== null).then((result) => {
      if (result) {
        const map = new ResourceMap();
        map.set(model.uri, result);
        return map;
      }
      return new ResourceMap();
    });
  }
  function getOccurrencesAcrossMultipleModels(registry, model, position, token, otherModels) {
    const orderedByScore = registry.ordered(model);
    return first(orderedByScore.map((provider) => () => {
      const filteredModels = otherModels.filter((otherModel) => {
        return shouldSynchronizeModel(otherModel);
      }).filter((otherModel) => {
        return score(provider.selector, otherModel.uri, otherModel.getLanguageId(), true, void 0, void 0) > 0;
      });
      return Promise.resolve(provider.provideMultiDocumentHighlights(model, position, filteredModels, token)).then(void 0, onUnexpectedExternalError);
    }), (result) => result !== void 0 && result !== null);
  }
  class OccurenceAtPositionRequest {
    constructor(_model, _selection, _wordSeparators) {
      this._model = _model;
      this._selection = _selection;
      this._wordSeparators = _wordSeparators;
      this._wordRange = this._getCurrentWordRange(_model, _selection);
      this._result = null;
    }
    get result() {
      if (!this._result) {
        this._result = createCancelablePromise((token) => this._compute(this._model, this._selection, this._wordSeparators, token));
      }
      return this._result;
    }
    _getCurrentWordRange(model, selection) {
      const word = model.getWordAtPosition(selection.getPosition());
      if (word) {
        return new Range$2(selection.startLineNumber, word.startColumn, selection.startLineNumber, word.endColumn);
      }
      return null;
    }
    cancel() {
      this.result.cancel();
    }
  }
  class SemanticOccurenceAtPositionRequest extends OccurenceAtPositionRequest {
    constructor(model, selection, wordSeparators2, providers) {
      super(model, selection, wordSeparators2);
      this._providers = providers;
    }
    _compute(model, selection, wordSeparators2, token) {
      return getOccurrencesAtPosition(this._providers, model, selection.getPosition(), token).then((value) => {
        if (!value) {
          return new ResourceMap();
        }
        return value;
      });
    }
  }
  class MultiModelOccurenceRequest extends OccurenceAtPositionRequest {
    constructor(model, selection, wordSeparators2, providers, otherModels) {
      super(model, selection, wordSeparators2);
      this._providers = providers;
      this._otherModels = otherModels;
    }
    _compute(model, selection, wordSeparators2, token) {
      return getOccurrencesAcrossMultipleModels(this._providers, model, selection.getPosition(), token, this._otherModels).then((value) => {
        if (!value) {
          return new ResourceMap();
        }
        return value;
      });
    }
  }
  function computeOccurencesAtPosition(registry, model, selection, wordSeparators2) {
    return new SemanticOccurenceAtPositionRequest(model, selection, wordSeparators2, registry);
  }
  function computeOccurencesMultiModel(registry, model, selection, wordSeparators2, otherModels) {
    return new MultiModelOccurenceRequest(model, selection, wordSeparators2, registry, otherModels);
  }
  registerModelAndPositionCommand("_executeDocumentHighlights", async (accessor, model, position) => {
    const languageFeaturesService = accessor.get(ILanguageFeaturesService);
    const map = await getOccurrencesAtPosition(languageFeaturesService.documentHighlightProvider, model, position, CancellationToken.None);
    return map?.get(model.uri);
  });
  let WordHighlighter = (_Da = class {
    constructor(editor2, providers, multiProviders, contextKeyService, textModelService, codeEditorService, configurationService, logService) {
      this.toUnhook = new DisposableStore();
      this.workerRequestTokenId = 0;
      this.workerRequestCompleted = false;
      this.workerRequestValue = new ResourceMap();
      this.lastCursorPositionChangeTime = 0;
      this.renderDecorationsTimer = void 0;
      this.runDelayer = this.toUnhook.add(new Delayer(50));
      this.editor = editor2;
      this.providers = providers;
      this.multiDocumentProviders = multiProviders;
      this.codeEditorService = codeEditorService;
      this.textModelService = textModelService;
      this.configurationService = configurationService;
      this.logService = logService;
      this._hasWordHighlights = ctxHasWordHighlights.bindTo(contextKeyService);
      this._ignorePositionChangeEvent = false;
      this.occurrencesHighlightEnablement = this.editor.getOption(
        90
        /* EditorOption.occurrencesHighlight */
      );
      this.occurrencesHighlightDelay = this.configurationService.getValue("editor.occurrencesHighlightDelay");
      this.model = this.editor.getModel();
      this.toUnhook.add(editor2.onDidChangeCursorPosition((e) => {
        if (this._ignorePositionChangeEvent) {
          return;
        }
        if (this.occurrencesHighlightEnablement === "off") {
          return;
        }
        this.runDelayer.trigger(() => {
          this._onPositionChanged(e);
        });
      }));
      this.toUnhook.add(editor2.onDidFocusEditorText((e) => {
        if (this.occurrencesHighlightEnablement === "off") {
          return;
        }
        if (!this.workerRequest) {
          this.runDelayer.trigger(() => {
            this._run();
          });
        }
      }));
      this.toUnhook.add(editor2.onDidChangeModelContent((e) => {
        if (!matchesScheme(this.model.uri, "output")) {
          this._stopAll();
        }
      }));
      this.toUnhook.add(editor2.onDidChangeModel((e) => {
        if (!e.newModelUrl && e.oldModelUrl) {
          this._stopSingular();
        } else if (WordHighlighter_1.query) {
          this._run();
        }
      }));
      this.toUnhook.add(editor2.onDidChangeConfiguration((e) => {
        const newEnablement = this.editor.getOption(
          90
          /* EditorOption.occurrencesHighlight */
        );
        if (this.occurrencesHighlightEnablement !== newEnablement) {
          this.occurrencesHighlightEnablement = newEnablement;
          switch (newEnablement) {
            case "off":
              this._stopAll();
              break;
            case "singleFile":
              this._stopAll(WordHighlighter_1.query?.modelInfo?.modelURI);
              break;
            case "multiFile":
              if (WordHighlighter_1.query) {
                this._run(true);
              }
              break;
            default:
              console.warn("Unknown occurrencesHighlight setting value:", newEnablement);
              break;
          }
        }
      }));
      this.toUnhook.add(this.configurationService.onDidChangeConfiguration((e) => {
        if (e.affectsConfiguration("editor.occurrencesHighlightDelay")) {
          const newDelay = configurationService.getValue("editor.occurrencesHighlightDelay");
          if (this.occurrencesHighlightDelay !== newDelay) {
            this.occurrencesHighlightDelay = newDelay;
          }
        }
      }));
      this.toUnhook.add(editor2.onDidBlurEditorWidget(() => {
        const activeEditor = this.codeEditorService.getFocusedCodeEditor();
        if (!activeEditor) {
          this._stopAll();
        } else if (activeEditor.getModel()?.uri.scheme === Schemas.vscodeNotebookCell && this.editor.getModel()?.uri.scheme !== Schemas.vscodeNotebookCell) {
          this._stopAll();
        }
      }));
      this.decorations = this.editor.createDecorationsCollection();
      this.workerRequestTokenId = 0;
      this.workerRequest = null;
      this.workerRequestCompleted = false;
      this.lastCursorPositionChangeTime = 0;
      this.renderDecorationsTimer = void 0;
      if (WordHighlighter_1.query) {
        this._run();
      }
    }
    hasDecorations() {
      return this.decorations.length > 0;
    }
    restore(delay) {
      if (this.occurrencesHighlightEnablement === "off") {
        return;
      }
      this.runDelayer.cancel();
      this.runDelayer.trigger(() => {
        this._run(false, delay);
      });
    }
    stop() {
      if (this.occurrencesHighlightEnablement === "off") {
        return;
      }
      this._stopAll();
    }
    _getSortedHighlights() {
      return this.decorations.getRanges().sort(Range$2.compareRangesUsingStarts);
    }
    moveNext() {
      const highlights = this._getSortedHighlights();
      const index = highlights.findIndex((range2) => range2.containsPosition(this.editor.getPosition()));
      const newIndex = (index + 1) % highlights.length;
      const dest = highlights[newIndex];
      try {
        this._ignorePositionChangeEvent = true;
        this.editor.setPosition(dest.getStartPosition());
        this.editor.revealRangeInCenterIfOutsideViewport(dest);
        const word = this._getWord();
        if (word) {
          const lineContent = this.editor.getModel().getLineContent(dest.startLineNumber);
          alert(`${lineContent}, ${newIndex + 1} of ${highlights.length} for '${word.word}'`);
        }
      } finally {
        this._ignorePositionChangeEvent = false;
      }
    }
    moveBack() {
      const highlights = this._getSortedHighlights();
      const index = highlights.findIndex((range2) => range2.containsPosition(this.editor.getPosition()));
      const newIndex = (index - 1 + highlights.length) % highlights.length;
      const dest = highlights[newIndex];
      try {
        this._ignorePositionChangeEvent = true;
        this.editor.setPosition(dest.getStartPosition());
        this.editor.revealRangeInCenterIfOutsideViewport(dest);
        const word = this._getWord();
        if (word) {
          const lineContent = this.editor.getModel().getLineContent(dest.startLineNumber);
          alert(`${lineContent}, ${newIndex + 1} of ${highlights.length} for '${word.word}'`);
        }
      } finally {
        this._ignorePositionChangeEvent = false;
      }
    }
    _removeSingleDecorations() {
      if (!this.editor.hasModel()) {
        return;
      }
      const currentDecorationIDs = WordHighlighter_1.storedDecorationIDs.get(this.editor.getModel().uri);
      if (!currentDecorationIDs) {
        return;
      }
      this.editor.removeDecorations(currentDecorationIDs);
      WordHighlighter_1.storedDecorationIDs.delete(this.editor.getModel().uri);
      if (this.decorations.length > 0) {
        this.decorations.clear();
        this._hasWordHighlights.set(false);
      }
    }
    _removeAllDecorations(preservedModel) {
      const currentEditors = this.codeEditorService.listCodeEditors();
      const deleteURI = [];
      for (const editor2 of currentEditors) {
        if (!editor2.hasModel() || isEqual(editor2.getModel().uri, preservedModel)) {
          continue;
        }
        const currentDecorationIDs = WordHighlighter_1.storedDecorationIDs.get(editor2.getModel().uri);
        if (!currentDecorationIDs) {
          continue;
        }
        editor2.removeDecorations(currentDecorationIDs);
        deleteURI.push(editor2.getModel().uri);
        const editorHighlighterContrib = WordHighlighterContribution.get(editor2);
        if (!editorHighlighterContrib?.wordHighlighter) {
          continue;
        }
        if (editorHighlighterContrib.wordHighlighter.decorations.length > 0) {
          editorHighlighterContrib.wordHighlighter.decorations.clear();
          editorHighlighterContrib.wordHighlighter.workerRequest = null;
          editorHighlighterContrib.wordHighlighter._hasWordHighlights.set(false);
        }
      }
      for (const uri of deleteURI) {
        WordHighlighter_1.storedDecorationIDs.delete(uri);
      }
    }
    _stopSingular() {
      this._removeSingleDecorations();
      if (this.editor.hasTextFocus()) {
        if (this.editor.getModel()?.uri.scheme !== Schemas.vscodeNotebookCell && WordHighlighter_1.query?.modelInfo?.modelURI.scheme !== Schemas.vscodeNotebookCell) {
          WordHighlighter_1.query = null;
          this._run();
        } else {
          if (WordHighlighter_1.query?.modelInfo) {
            WordHighlighter_1.query.modelInfo = null;
          }
        }
      }
      if (this.renderDecorationsTimer !== void 0) {
        clearTimeout(this.renderDecorationsTimer);
        this.renderDecorationsTimer = void 0;
      }
      if (this.workerRequest !== null) {
        this.workerRequest.cancel();
        this.workerRequest = null;
      }
      if (!this.workerRequestCompleted) {
        this.workerRequestTokenId++;
        this.workerRequestCompleted = true;
      }
    }
    _stopAll(preservedModel) {
      this._removeAllDecorations(preservedModel);
      if (this.renderDecorationsTimer !== void 0) {
        clearTimeout(this.renderDecorationsTimer);
        this.renderDecorationsTimer = void 0;
      }
      if (this.workerRequest !== null) {
        this.workerRequest.cancel();
        this.workerRequest = null;
      }
      if (!this.workerRequestCompleted) {
        this.workerRequestTokenId++;
        this.workerRequestCompleted = true;
      }
    }
    _onPositionChanged(e) {
      if (this.occurrencesHighlightEnablement === "off") {
        this._stopAll();
        return;
      }
      if (e.source !== "api" && e.reason !== 3) {
        this._stopAll();
        return;
      }
      this._run();
    }
    _getWord() {
      const editorSelection = this.editor.getSelection();
      const lineNumber = editorSelection.startLineNumber;
      const startColumn = editorSelection.startColumn;
      if (this.model.isDisposed()) {
        return null;
      }
      return this.model.getWordAtPosition({
        lineNumber,
        column: startColumn
      });
    }
    getOtherModelsToHighlight(model) {
      if (!model) {
        return [];
      }
      const isNotebookEditor = model.uri.scheme === Schemas.vscodeNotebookCell;
      if (isNotebookEditor) {
        const currentModels2 = [];
        const currentEditors2 = this.codeEditorService.listCodeEditors();
        for (const editor2 of currentEditors2) {
          const tempModel = editor2.getModel();
          if (tempModel && tempModel !== model && tempModel.uri.scheme === Schemas.vscodeNotebookCell) {
            currentModels2.push(tempModel);
          }
        }
        return currentModels2;
      }
      const currentModels = [];
      const currentEditors = this.codeEditorService.listCodeEditors();
      for (const editor2 of currentEditors) {
        if (!isDiffEditor(editor2)) {
          continue;
        }
        const diffModel = editor2.getModel();
        if (!diffModel) {
          continue;
        }
        if (model === diffModel.modified) {
          currentModels.push(diffModel.modified);
        }
      }
      if (currentModels.length) {
        return currentModels;
      }
      if (this.occurrencesHighlightEnablement === "singleFile") {
        return [];
      }
      for (const editor2 of currentEditors) {
        const tempModel = editor2.getModel();
        const isValidModel = tempModel && tempModel !== model;
        if (isValidModel) {
          currentModels.push(tempModel);
        }
      }
      return currentModels;
    }
    async _run(multiFileConfigChange, delay) {
      const hasTextFocus = this.editor.hasTextFocus();
      if (!hasTextFocus) {
        if (!WordHighlighter_1.query) {
          this._stopAll();
          return;
        }
      } else {
        const editorSelection = this.editor.getSelection();
        if (!editorSelection || editorSelection.startLineNumber !== editorSelection.endLineNumber) {
          WordHighlighter_1.query = null;
          this._stopAll();
          return;
        }
        const startColumn = editorSelection.startColumn;
        const endColumn = editorSelection.endColumn;
        const word = this._getWord();
        if (!word || word.startColumn > startColumn || word.endColumn < endColumn) {
          WordHighlighter_1.query = null;
          this._stopAll();
          return;
        }
        WordHighlighter_1.query = {
          modelInfo: {
            modelURI: this.model.uri,
            selection: editorSelection
          }
        };
      }
      this.lastCursorPositionChangeTime = (/* @__PURE__ */ new Date()).getTime();
      if (isEqual(this.editor.getModel().uri, WordHighlighter_1.query.modelInfo?.modelURI)) {
        if (!multiFileConfigChange) {
          const currentModelDecorationRanges = this.decorations.getRanges();
          for (const storedRange of currentModelDecorationRanges) {
            if (storedRange.containsPosition(this.editor.getPosition())) {
              return;
            }
          }
        }
        this._stopAll(multiFileConfigChange ? this.model.uri : void 0);
        const myRequestId = ++this.workerRequestTokenId;
        this.workerRequestCompleted = false;
        const otherModelsToHighlight = this.getOtherModelsToHighlight(this.editor.getModel());
        if (!WordHighlighter_1.query || !WordHighlighter_1.query.modelInfo) {
          return;
        }
        const queryModelRef = await this.textModelService.createModelReference(WordHighlighter_1.query.modelInfo.modelURI);
        try {
          this.workerRequest = this.computeWithModel(queryModelRef.object.textEditorModel, WordHighlighter_1.query.modelInfo.selection, otherModelsToHighlight);
          this.workerRequest?.result.then((data) => {
            if (myRequestId === this.workerRequestTokenId) {
              this.workerRequestCompleted = true;
              this.workerRequestValue = data || [];
              this._beginRenderDecorations(delay ?? this.occurrencesHighlightDelay);
            }
          }, onUnexpectedError);
        } catch (e) {
          this.logService.error("Unexpected error during occurrence request. Log: ", e);
        } finally {
          queryModelRef.dispose();
        }
      } else if (this.model.uri.scheme === Schemas.vscodeNotebookCell) {
        const myRequestId = ++this.workerRequestTokenId;
        this.workerRequestCompleted = false;
        if (!WordHighlighter_1.query || !WordHighlighter_1.query.modelInfo) {
          return;
        }
        const queryModelRef = await this.textModelService.createModelReference(WordHighlighter_1.query.modelInfo.modelURI);
        try {
          this.workerRequest = this.computeWithModel(queryModelRef.object.textEditorModel, WordHighlighter_1.query.modelInfo.selection, [this.model]);
          this.workerRequest?.result.then((data) => {
            if (myRequestId === this.workerRequestTokenId) {
              this.workerRequestCompleted = true;
              this.workerRequestValue = data || [];
              this._beginRenderDecorations(delay ?? this.occurrencesHighlightDelay);
            }
          }, onUnexpectedError);
        } catch (e) {
          this.logService.error("Unexpected error during occurrence request. Log: ", e);
        } finally {
          queryModelRef.dispose();
        }
      }
    }
    computeWithModel(model, selection, otherModels) {
      if (!otherModels.length) {
        return computeOccurencesAtPosition(this.providers, model, selection, this.editor.getOption(
          148
          /* EditorOption.wordSeparators */
        ));
      } else {
        return computeOccurencesMultiModel(this.multiDocumentProviders, model, selection, this.editor.getOption(
          148
          /* EditorOption.wordSeparators */
        ), otherModels);
      }
    }
    _beginRenderDecorations(delay) {
      const currentTime = (/* @__PURE__ */ new Date()).getTime();
      const minimumRenderTime = this.lastCursorPositionChangeTime + delay;
      if (currentTime >= minimumRenderTime) {
        this.renderDecorationsTimer = void 0;
        this.renderDecorations();
      } else {
        this.renderDecorationsTimer = setTimeout(() => {
          this.renderDecorations();
        }, minimumRenderTime - currentTime);
      }
    }
    renderDecorations() {
      this.renderDecorationsTimer = void 0;
      const currentEditors = this.codeEditorService.listCodeEditors();
      for (const editor2 of currentEditors) {
        const editorHighlighterContrib = WordHighlighterContribution.get(editor2);
        if (!editorHighlighterContrib) {
          continue;
        }
        const newDecorations = [];
        const uri = editor2.getModel()?.uri;
        if (uri && this.workerRequestValue.has(uri)) {
          const oldDecorationIDs = WordHighlighter_1.storedDecorationIDs.get(uri);
          const newDocumentHighlights = this.workerRequestValue.get(uri);
          if (newDocumentHighlights) {
            for (const highlight of newDocumentHighlights) {
              if (!highlight.range) {
                continue;
              }
              newDecorations.push({
                range: highlight.range,
                options: getHighlightDecorationOptions(highlight.kind)
              });
            }
          }
          let newDecorationIDs = [];
          editor2.changeDecorations((changeAccessor) => {
            newDecorationIDs = changeAccessor.deltaDecorations(oldDecorationIDs ?? [], newDecorations);
          });
          WordHighlighter_1.storedDecorationIDs = WordHighlighter_1.storedDecorationIDs.set(uri, newDecorationIDs);
          if (newDecorations.length > 0) {
            editorHighlighterContrib.wordHighlighter?.decorations.set(newDecorations);
            editorHighlighterContrib.wordHighlighter?._hasWordHighlights.set(true);
          }
        }
      }
      this.workerRequest = null;
    }
    dispose() {
      this._stopSingular();
      this.toUnhook.dispose();
    }
  }, WordHighlighter_1 = _Da, _Da.storedDecorationIDs = new ResourceMap(), _Da.query = null, _Da);
  WordHighlighter = WordHighlighter_1 = __decorate$G([
    __param$F(4, ITextModelService),
    __param$F(5, ICodeEditorService),
    __param$F(6, IConfigurationService),
    __param$F(7, ILogService)
  ], WordHighlighter);
  let WordHighlighterContribution = (_Ea = class extends Disposable {
    static get(editor2) {
      return editor2.getContribution(WordHighlighterContribution_1.ID);
    }
    constructor(editor2, contextKeyService, languageFeaturesService, codeEditorService, textModelService, configurationService, logService) {
      super();
      this._wordHighlighter = null;
      const createWordHighlighterIfPossible = () => {
        if (editor2.hasModel() && !editor2.getModel().isTooLargeForTokenization() && editor2.getModel().uri.scheme !== Schemas.accessibleView) {
          this._wordHighlighter = new WordHighlighter(editor2, languageFeaturesService.documentHighlightProvider, languageFeaturesService.multiDocumentHighlightProvider, contextKeyService, textModelService, codeEditorService, configurationService, logService);
        }
      };
      this._register(editor2.onDidChangeModel((e) => {
        if (this._wordHighlighter) {
          if (!e.newModelUrl && e.oldModelUrl?.scheme !== Schemas.vscodeNotebookCell) {
            this.wordHighlighter?.stop();
          }
          this._wordHighlighter.dispose();
          this._wordHighlighter = null;
        }
        createWordHighlighterIfPossible();
      }));
      createWordHighlighterIfPossible();
    }
    get wordHighlighter() {
      return this._wordHighlighter;
    }
    saveViewState() {
      if (this._wordHighlighter && this._wordHighlighter.hasDecorations()) {
        return true;
      }
      return false;
    }
    moveNext() {
      this._wordHighlighter?.moveNext();
    }
    moveBack() {
      this._wordHighlighter?.moveBack();
    }
    restoreViewState(state) {
      if (this._wordHighlighter && state) {
        this._wordHighlighter.restore(250);
      }
    }
    dispose() {
      if (this._wordHighlighter) {
        this._wordHighlighter.dispose();
        this._wordHighlighter = null;
      }
      super.dispose();
    }
  }, WordHighlighterContribution_1 = _Ea, _Ea.ID = "editor.contrib.wordHighlighter", _Ea);
  WordHighlighterContribution = WordHighlighterContribution_1 = __decorate$G([
    __param$F(1, IContextKeyService),
    __param$F(2, ILanguageFeaturesService),
    __param$F(3, ICodeEditorService),
    __param$F(4, ITextModelService),
    __param$F(5, IConfigurationService),
    __param$F(6, ILogService)
  ], WordHighlighterContribution);
  class WordHighlightNavigationAction extends EditorAction {
    constructor(next, opts) {
      super(opts);
      this._isNext = next;
    }
    run(accessor, editor2) {
      const controller = WordHighlighterContribution.get(editor2);
      if (!controller) {
        return;
      }
      if (this._isNext) {
        controller.moveNext();
      } else {
        controller.moveBack();
      }
    }
  }
  class NextWordHighlightAction extends WordHighlightNavigationAction {
    constructor() {
      super(true, {
        id: "editor.action.wordHighlight.next",
        label: localize2(1572, "Go to Next Symbol Highlight"),
        precondition: ctxHasWordHighlights,
        kbOpts: {
          kbExpr: EditorContextKeys.editorTextFocus,
          primary: 65,
          weight: 100
          /* KeybindingWeight.EditorContrib */
        }
      });
    }
  }
  class PrevWordHighlightAction extends WordHighlightNavigationAction {
    constructor() {
      super(false, {
        id: "editor.action.wordHighlight.prev",
        label: localize2(1573, "Go to Previous Symbol Highlight"),
        precondition: ctxHasWordHighlights,
        kbOpts: {
          kbExpr: EditorContextKeys.editorTextFocus,
          primary: 1024 | 65,
          weight: 100
          /* KeybindingWeight.EditorContrib */
        }
      });
    }
  }
  class TriggerWordHighlightAction extends EditorAction {
    constructor() {
      super({
        id: "editor.action.wordHighlight.trigger",
        label: localize2(1574, "Trigger Symbol Highlight"),
        precondition: void 0,
        kbOpts: {
          kbExpr: EditorContextKeys.editorTextFocus,
          primary: 0,
          weight: 100
          /* KeybindingWeight.EditorContrib */
        }
      });
    }
    run(accessor, editor2, args) {
      const controller = WordHighlighterContribution.get(editor2);
      if (!controller) {
        return;
      }
      controller.restoreViewState(true);
    }
  }
  registerEditorContribution(
    WordHighlighterContribution.ID,
    WordHighlighterContribution,
    0
    /* EditorContributionInstantiation.Eager */
  );
  registerEditorAction(NextWordHighlightAction);
  registerEditorAction(PrevWordHighlightAction);
  registerEditorAction(TriggerWordHighlightAction);
  registerEditorFeature(TextualMultiDocumentHighlightFeature);
  class MoveWordCommand extends EditorCommand {
    constructor(opts) {
      super(opts);
      this._inSelectionMode = opts.inSelectionMode;
      this._wordNavigationType = opts.wordNavigationType;
    }
    runEditorCommand(accessor, editor2, args) {
      if (!editor2.hasModel()) {
        return;
      }
      const wordSeparators2 = getMapForWordSeparators(editor2.getOption(
        148
        /* EditorOption.wordSeparators */
      ), editor2.getOption(
        147
        /* EditorOption.wordSegmenterLocales */
      ));
      const model = editor2.getModel();
      const selections = editor2.getSelections();
      const hasMulticursor = selections.length > 1;
      const result = selections.map((sel) => {
        const inPosition = new Position$1(sel.positionLineNumber, sel.positionColumn);
        const outPosition = this._move(wordSeparators2, model, inPosition, this._wordNavigationType, hasMulticursor);
        return this._moveTo(sel, outPosition, this._inSelectionMode);
      });
      model.pushStackElement();
      editor2._getViewModel().setCursorStates("moveWordCommand", 3, result.map((r) => CursorState$1.fromModelSelection(r)));
      if (result.length === 1) {
        const pos = new Position$1(result[0].positionLineNumber, result[0].positionColumn);
        editor2.revealPosition(
          pos,
          0
          /* ScrollType.Smooth */
        );
      }
    }
    _moveTo(from, to, inSelectionMode) {
      if (inSelectionMode) {
        return new Selection$1(from.selectionStartLineNumber, from.selectionStartColumn, to.lineNumber, to.column);
      } else {
        return new Selection$1(to.lineNumber, to.column, to.lineNumber, to.column);
      }
    }
  }
  class WordLeftCommand extends MoveWordCommand {
    _move(wordSeparators2, model, position, wordNavigationType, hasMulticursor) {
      return WordOperations.moveWordLeft(wordSeparators2, model, position, wordNavigationType, hasMulticursor);
    }
  }
  class WordRightCommand extends MoveWordCommand {
    _move(wordSeparators2, model, position, wordNavigationType, hasMulticursor) {
      return WordOperations.moveWordRight(wordSeparators2, model, position, wordNavigationType);
    }
  }
  class CursorWordStartLeft extends WordLeftCommand {
    constructor() {
      super({
        inSelectionMode: false,
        wordNavigationType: 0,
        id: "cursorWordStartLeft",
        precondition: void 0
      });
    }
  }
  class CursorWordEndLeft extends WordLeftCommand {
    constructor() {
      super({
        inSelectionMode: false,
        wordNavigationType: 2,
        id: "cursorWordEndLeft",
        precondition: void 0
      });
    }
  }
  class CursorWordLeft extends WordLeftCommand {
    constructor() {
      super({
        inSelectionMode: false,
        wordNavigationType: 1,
        id: "cursorWordLeft",
        precondition: void 0,
        kbOpts: {
          kbExpr: ContextKeyExpr.and(EditorContextKeys.textInputFocus, ContextKeyExpr.and(CONTEXT_ACCESSIBILITY_MODE_ENABLED, IsWindowsContext)?.negate()),
          primary: 2048 | 15,
          mac: {
            primary: 512 | 15
            /* KeyCode.LeftArrow */
          },
          weight: 100
          /* KeybindingWeight.EditorContrib */
        }
      });
    }
  }
  class CursorWordStartLeftSelect extends WordLeftCommand {
    constructor() {
      super({
        inSelectionMode: true,
        wordNavigationType: 0,
        id: "cursorWordStartLeftSelect",
        precondition: void 0
      });
    }
  }
  class CursorWordEndLeftSelect extends WordLeftCommand {
    constructor() {
      super({
        inSelectionMode: true,
        wordNavigationType: 2,
        id: "cursorWordEndLeftSelect",
        precondition: void 0
      });
    }
  }
  class CursorWordLeftSelect extends WordLeftCommand {
    constructor() {
      super({
        inSelectionMode: true,
        wordNavigationType: 1,
        id: "cursorWordLeftSelect",
        precondition: void 0,
        kbOpts: {
          kbExpr: ContextKeyExpr.and(EditorContextKeys.textInputFocus, ContextKeyExpr.and(CONTEXT_ACCESSIBILITY_MODE_ENABLED, IsWindowsContext)?.negate()),
          primary: 2048 | 1024 | 15,
          mac: {
            primary: 512 | 1024 | 15
            /* KeyCode.LeftArrow */
          },
          weight: 100
          /* KeybindingWeight.EditorContrib */
        }
      });
    }
  }
  class CursorWordAccessibilityLeft extends WordLeftCommand {
    constructor() {
      super({
        inSelectionMode: false,
        wordNavigationType: 3,
        id: "cursorWordAccessibilityLeft",
        precondition: void 0
      });
    }
    _move(wordCharacterClassifier, model, position, wordNavigationType, hasMulticursor) {
      return super._move(getMapForWordSeparators(EditorOptions.wordSeparators.defaultValue, wordCharacterClassifier.intlSegmenterLocales), model, position, wordNavigationType, hasMulticursor);
    }
  }
  class CursorWordAccessibilityLeftSelect extends WordLeftCommand {
    constructor() {
      super({
        inSelectionMode: true,
        wordNavigationType: 3,
        id: "cursorWordAccessibilityLeftSelect",
        precondition: void 0
      });
    }
    _move(wordCharacterClassifier, model, position, wordNavigationType, hasMulticursor) {
      return super._move(getMapForWordSeparators(EditorOptions.wordSeparators.defaultValue, wordCharacterClassifier.intlSegmenterLocales), model, position, wordNavigationType, hasMulticursor);
    }
  }
  class CursorWordStartRight extends WordRightCommand {
    constructor() {
      super({
        inSelectionMode: false,
        wordNavigationType: 0,
        id: "cursorWordStartRight",
        precondition: void 0
      });
    }
  }
  class CursorWordEndRight extends WordRightCommand {
    constructor() {
      super({
        inSelectionMode: false,
        wordNavigationType: 2,
        id: "cursorWordEndRight",
        precondition: void 0,
        kbOpts: {
          kbExpr: ContextKeyExpr.and(EditorContextKeys.textInputFocus, ContextKeyExpr.and(CONTEXT_ACCESSIBILITY_MODE_ENABLED, IsWindowsContext)?.negate()),
          primary: 2048 | 17,
          mac: {
            primary: 512 | 17
            /* KeyCode.RightArrow */
          },
          weight: 100
          /* KeybindingWeight.EditorContrib */
        }
      });
    }
  }
  class CursorWordRight extends WordRightCommand {
    constructor() {
      super({
        inSelectionMode: false,
        wordNavigationType: 2,
        id: "cursorWordRight",
        precondition: void 0
      });
    }
  }
  class CursorWordStartRightSelect extends WordRightCommand {
    constructor() {
      super({
        inSelectionMode: true,
        wordNavigationType: 0,
        id: "cursorWordStartRightSelect",
        precondition: void 0
      });
    }
  }
  class CursorWordEndRightSelect extends WordRightCommand {
    constructor() {
      super({
        inSelectionMode: true,
        wordNavigationType: 2,
        id: "cursorWordEndRightSelect",
        precondition: void 0,
        kbOpts: {
          kbExpr: ContextKeyExpr.and(EditorContextKeys.textInputFocus, ContextKeyExpr.and(CONTEXT_ACCESSIBILITY_MODE_ENABLED, IsWindowsContext)?.negate()),
          primary: 2048 | 1024 | 17,
          mac: {
            primary: 512 | 1024 | 17
            /* KeyCode.RightArrow */
          },
          weight: 100
          /* KeybindingWeight.EditorContrib */
        }
      });
    }
  }
  class CursorWordRightSelect extends WordRightCommand {
    constructor() {
      super({
        inSelectionMode: true,
        wordNavigationType: 2,
        id: "cursorWordRightSelect",
        precondition: void 0
      });
    }
  }
  class CursorWordAccessibilityRight extends WordRightCommand {
    constructor() {
      super({
        inSelectionMode: false,
        wordNavigationType: 3,
        id: "cursorWordAccessibilityRight",
        precondition: void 0
      });
    }
    _move(wordCharacterClassifier, model, position, wordNavigationType, hasMulticursor) {
      return super._move(getMapForWordSeparators(EditorOptions.wordSeparators.defaultValue, wordCharacterClassifier.intlSegmenterLocales), model, position, wordNavigationType, hasMulticursor);
    }
  }
  class CursorWordAccessibilityRightSelect extends WordRightCommand {
    constructor() {
      super({
        inSelectionMode: true,
        wordNavigationType: 3,
        id: "cursorWordAccessibilityRightSelect",
        precondition: void 0
      });
    }
    _move(wordCharacterClassifier, model, position, wordNavigationType, hasMulticursor) {
      return super._move(getMapForWordSeparators(EditorOptions.wordSeparators.defaultValue, wordCharacterClassifier.intlSegmenterLocales), model, position, wordNavigationType, hasMulticursor);
    }
  }
  class DeleteWordCommand extends EditorCommand {
    constructor(opts) {
      super({ canTriggerInlineEdits: true, ...opts });
      this._whitespaceHeuristics = opts.whitespaceHeuristics;
      this._wordNavigationType = opts.wordNavigationType;
    }
    runEditorCommand(accessor, editor2, args) {
      const languageConfigurationService = accessor?.get(ILanguageConfigurationService);
      if (!editor2.hasModel() || !languageConfigurationService) {
        return;
      }
      const wordSeparators2 = getMapForWordSeparators(editor2.getOption(
        148
        /* EditorOption.wordSeparators */
      ), editor2.getOption(
        147
        /* EditorOption.wordSegmenterLocales */
      ));
      const model = editor2.getModel();
      const selections = editor2.getSelections();
      const autoClosingBrackets = editor2.getOption(
        10
        /* EditorOption.autoClosingBrackets */
      );
      const autoClosingQuotes = editor2.getOption(
        15
        /* EditorOption.autoClosingQuotes */
      );
      const autoClosingPairs = languageConfigurationService.getLanguageConfiguration(model.getLanguageId()).getAutoClosingPairs();
      const viewModel = editor2._getViewModel();
      const commands = selections.map((sel) => {
        const deleteRange = this._delete({
          wordSeparators: wordSeparators2,
          model,
          selection: sel,
          whitespaceHeuristics: this._whitespaceHeuristics,
          autoClosingDelete: editor2.getOption(
            13
            /* EditorOption.autoClosingDelete */
          ),
          autoClosingBrackets,
          autoClosingQuotes,
          autoClosingPairs,
          autoClosedCharacters: viewModel.getCursorAutoClosedCharacters()
        }, this._wordNavigationType);
        return new ReplaceCommand(deleteRange, "");
      });
      editor2.pushUndoStop();
      editor2.executeCommands(this.id, commands);
      editor2.pushUndoStop();
    }
  }
  class DeleteWordLeftCommand extends DeleteWordCommand {
    _delete(ctx, wordNavigationType) {
      const r = WordOperations.deleteWordLeft(ctx, wordNavigationType);
      if (r) {
        return r;
      }
      return new Range$2(1, 1, 1, 1);
    }
  }
  class DeleteWordRightCommand extends DeleteWordCommand {
    _delete(ctx, wordNavigationType) {
      const r = WordOperations.deleteWordRight(ctx, wordNavigationType);
      if (r) {
        return r;
      }
      const lineCount = ctx.model.getLineCount();
      const maxColumn = ctx.model.getLineMaxColumn(lineCount);
      return new Range$2(lineCount, maxColumn, lineCount, maxColumn);
    }
  }
  class DeleteWordStartLeft extends DeleteWordLeftCommand {
    constructor() {
      super({
        whitespaceHeuristics: false,
        wordNavigationType: 0,
        id: "deleteWordStartLeft",
        precondition: EditorContextKeys.writable
      });
    }
  }
  class DeleteWordEndLeft extends DeleteWordLeftCommand {
    constructor() {
      super({
        whitespaceHeuristics: false,
        wordNavigationType: 2,
        id: "deleteWordEndLeft",
        precondition: EditorContextKeys.writable
      });
    }
  }
  class DeleteWordLeft extends DeleteWordLeftCommand {
    constructor() {
      super({
        whitespaceHeuristics: true,
        wordNavigationType: 0,
        id: "deleteWordLeft",
        precondition: EditorContextKeys.writable,
        kbOpts: {
          kbExpr: EditorContextKeys.textInputFocus,
          primary: 2048 | 1,
          mac: {
            primary: 512 | 1
            /* KeyCode.Backspace */
          },
          weight: 100
          /* KeybindingWeight.EditorContrib */
        }
      });
    }
  }
  class DeleteWordStartRight extends DeleteWordRightCommand {
    constructor() {
      super({
        whitespaceHeuristics: false,
        wordNavigationType: 0,
        id: "deleteWordStartRight",
        precondition: EditorContextKeys.writable
      });
    }
  }
  class DeleteWordEndRight extends DeleteWordRightCommand {
    constructor() {
      super({
        whitespaceHeuristics: false,
        wordNavigationType: 2,
        id: "deleteWordEndRight",
        precondition: EditorContextKeys.writable
      });
    }
  }
  class DeleteWordRight extends DeleteWordRightCommand {
    constructor() {
      super({
        whitespaceHeuristics: true,
        wordNavigationType: 2,
        id: "deleteWordRight",
        precondition: EditorContextKeys.writable,
        kbOpts: {
          kbExpr: EditorContextKeys.textInputFocus,
          primary: 2048 | 20,
          mac: {
            primary: 512 | 20
            /* KeyCode.Delete */
          },
          weight: 100
          /* KeybindingWeight.EditorContrib */
        }
      });
    }
  }
  class DeleteInsideWord extends EditorAction {
    constructor() {
      super({
        id: "deleteInsideWord",
        precondition: EditorContextKeys.writable,
        label: localize2(1575, "Delete Word")
      });
    }
    run(accessor, editor2, args) {
      if (!editor2.hasModel()) {
        return;
      }
      const wordSeparators2 = getMapForWordSeparators(editor2.getOption(
        148
        /* EditorOption.wordSeparators */
      ), editor2.getOption(
        147
        /* EditorOption.wordSegmenterLocales */
      ));
      const model = editor2.getModel();
      const selections = editor2.getSelections();
      const commands = selections.map((sel) => {
        const deleteRange = WordOperations.deleteInsideWord(wordSeparators2, model, sel);
        return new ReplaceCommand(deleteRange, "");
      });
      editor2.pushUndoStop();
      editor2.executeCommands(this.id, commands);
      editor2.pushUndoStop();
    }
  }
  registerEditorCommand(new CursorWordStartLeft());
  registerEditorCommand(new CursorWordEndLeft());
  registerEditorCommand(new CursorWordLeft());
  registerEditorCommand(new CursorWordStartLeftSelect());
  registerEditorCommand(new CursorWordEndLeftSelect());
  registerEditorCommand(new CursorWordLeftSelect());
  registerEditorCommand(new CursorWordStartRight());
  registerEditorCommand(new CursorWordEndRight());
  registerEditorCommand(new CursorWordRight());
  registerEditorCommand(new CursorWordStartRightSelect());
  registerEditorCommand(new CursorWordEndRightSelect());
  registerEditorCommand(new CursorWordRightSelect());
  registerEditorCommand(new CursorWordAccessibilityLeft());
  registerEditorCommand(new CursorWordAccessibilityLeftSelect());
  registerEditorCommand(new CursorWordAccessibilityRight());
  registerEditorCommand(new CursorWordAccessibilityRightSelect());
  registerEditorCommand(new DeleteWordStartLeft());
  registerEditorCommand(new DeleteWordEndLeft());
  registerEditorCommand(new DeleteWordLeft());
  registerEditorCommand(new DeleteWordStartRight());
  registerEditorCommand(new DeleteWordEndRight());
  registerEditorCommand(new DeleteWordRight());
  registerEditorAction(DeleteInsideWord);
  class DeleteWordPartLeft extends DeleteWordCommand {
    constructor() {
      super({
        whitespaceHeuristics: true,
        wordNavigationType: 0,
        id: "deleteWordPartLeft",
        precondition: EditorContextKeys.writable,
        kbOpts: {
          kbExpr: EditorContextKeys.textInputFocus,
          primary: 0,
          mac: {
            primary: 256 | 512 | 1
            /* KeyCode.Backspace */
          },
          weight: 100
          /* KeybindingWeight.EditorContrib */
        }
      });
    }
    _delete(ctx, wordNavigationType) {
      const r = WordPartOperations.deleteWordPartLeft(ctx);
      if (r) {
        return r;
      }
      return new Range$2(1, 1, 1, 1);
    }
  }
  class DeleteWordPartRight extends DeleteWordCommand {
    constructor() {
      super({
        whitespaceHeuristics: true,
        wordNavigationType: 2,
        id: "deleteWordPartRight",
        precondition: EditorContextKeys.writable,
        kbOpts: {
          kbExpr: EditorContextKeys.textInputFocus,
          primary: 0,
          mac: {
            primary: 256 | 512 | 20
            /* KeyCode.Delete */
          },
          weight: 100
          /* KeybindingWeight.EditorContrib */
        }
      });
    }
    _delete(ctx, wordNavigationType) {
      const r = WordPartOperations.deleteWordPartRight(ctx);
      if (r) {
        return r;
      }
      const lineCount = ctx.model.getLineCount();
      const maxColumn = ctx.model.getLineMaxColumn(lineCount);
      return new Range$2(lineCount, maxColumn, lineCount, maxColumn);
    }
  }
  class WordPartLeftCommand extends MoveWordCommand {
    _move(wordSeparators2, model, position, wordNavigationType, hasMulticursor) {
      return WordPartOperations.moveWordPartLeft(wordSeparators2, model, position, hasMulticursor);
    }
  }
  class CursorWordPartLeft extends WordPartLeftCommand {
    constructor() {
      super({
        inSelectionMode: false,
        wordNavigationType: 0,
        id: "cursorWordPartLeft",
        precondition: void 0,
        kbOpts: {
          kbExpr: EditorContextKeys.textInputFocus,
          primary: 0,
          mac: {
            primary: 256 | 512 | 15
            /* KeyCode.LeftArrow */
          },
          weight: 100
          /* KeybindingWeight.EditorContrib */
        }
      });
    }
  }
  CommandsRegistry.registerCommandAlias("cursorWordPartStartLeft", "cursorWordPartLeft");
  class CursorWordPartLeftSelect extends WordPartLeftCommand {
    constructor() {
      super({
        inSelectionMode: true,
        wordNavigationType: 0,
        id: "cursorWordPartLeftSelect",
        precondition: void 0,
        kbOpts: {
          kbExpr: EditorContextKeys.textInputFocus,
          primary: 0,
          mac: {
            primary: 256 | 512 | 1024 | 15
            /* KeyCode.LeftArrow */
          },
          weight: 100
          /* KeybindingWeight.EditorContrib */
        }
      });
    }
  }
  CommandsRegistry.registerCommandAlias("cursorWordPartStartLeftSelect", "cursorWordPartLeftSelect");
  class WordPartRightCommand extends MoveWordCommand {
    _move(wordSeparators2, model, position, wordNavigationType, hasMulticursor) {
      return WordPartOperations.moveWordPartRight(wordSeparators2, model, position);
    }
  }
  class CursorWordPartRight extends WordPartRightCommand {
    constructor() {
      super({
        inSelectionMode: false,
        wordNavigationType: 2,
        id: "cursorWordPartRight",
        precondition: void 0,
        kbOpts: {
          kbExpr: EditorContextKeys.textInputFocus,
          primary: 0,
          mac: {
            primary: 256 | 512 | 17
            /* KeyCode.RightArrow */
          },
          weight: 100
          /* KeybindingWeight.EditorContrib */
        }
      });
    }
  }
  class CursorWordPartRightSelect extends WordPartRightCommand {
    constructor() {
      super({
        inSelectionMode: true,
        wordNavigationType: 2,
        id: "cursorWordPartRightSelect",
        precondition: void 0,
        kbOpts: {
          kbExpr: EditorContextKeys.textInputFocus,
          primary: 0,
          mac: {
            primary: 256 | 512 | 1024 | 17
            /* KeyCode.RightArrow */
          },
          weight: 100
          /* KeybindingWeight.EditorContrib */
        }
      });
    }
  }
  registerEditorCommand(new DeleteWordPartLeft());
  registerEditorCommand(new DeleteWordPartRight());
  registerEditorCommand(new CursorWordPartLeft());
  registerEditorCommand(new CursorWordPartLeftSelect());
  registerEditorCommand(new CursorWordPartRight());
  registerEditorCommand(new CursorWordPartRightSelect());
  const _ReadOnlyMessageController = class _ReadOnlyMessageController extends Disposable {
    constructor(editor2) {
      super();
      this.editor = editor2;
      this._register(this.editor.onDidAttemptReadOnlyEdit(() => this._onDidAttemptReadOnlyEdit()));
    }
    _onDidAttemptReadOnlyEdit() {
      const messageController = MessageController.get(this.editor);
      if (messageController && this.editor.hasModel()) {
        let message = this.editor.getOptions().get(
          105
          /* EditorOption.readOnlyMessage */
        );
        if (!message) {
          if (this.editor.isSimpleWidget) {
            message = new MarkdownString(localize(1378, "Cannot edit in read-only input"));
          } else {
            message = new MarkdownString(localize(1379, "Cannot edit in read-only editor"));
          }
        }
        messageController.showMessage(message, this.editor.getPosition());
      }
    }
  };
  _ReadOnlyMessageController.ID = "editor.contrib.readOnlyMessageController";
  let ReadOnlyMessageController = _ReadOnlyMessageController;
  registerEditorContribution(
    ReadOnlyMessageController.ID,
    ReadOnlyMessageController,
    2
    /* EditorContributionInstantiation.BeforeFirstInteraction */
  );
  var __decorate$F = 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$E = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  let DiffEditorBreadcrumbsSource = class DiffEditorBreadcrumbsSource extends Disposable {
    constructor(_textModel, _languageFeaturesService, _outlineModelService) {
      super();
      this._textModel = _textModel;
      this._languageFeaturesService = _languageFeaturesService;
      this._outlineModelService = _outlineModelService;
      this._currentModel = observableValue(this, void 0);
      const documentSymbolProviderChanged = observableSignalFromEvent("documentSymbolProvider.onDidChange", this._languageFeaturesService.documentSymbolProvider.onDidChange);
      const textModelChanged = observableSignalFromEvent("_textModel.onDidChangeContent", Event.debounce((e) => this._textModel.onDidChangeContent(e), () => void 0, 100));
      this._register(autorunWithStore(async (reader, store) => {
        documentSymbolProviderChanged.read(reader);
        textModelChanged.read(reader);
        const src = store.add(new DisposableCancellationTokenSource());
        const model = await this._outlineModelService.getOrCreate(this._textModel, src.token);
        if (store.isDisposed) {
          return;
        }
        this._currentModel.set(model, void 0);
      }));
    }
    getBreadcrumbItems(startRange, reader) {
      const m = this._currentModel.read(reader);
      if (!m) {
        return [];
      }
      const symbols = m.asListOfDocumentSymbols().filter((s) => startRange.contains(s.range.startLineNumber) && !startRange.contains(s.range.endLineNumber));
      symbols.sort(reverseOrder(compareBy((s) => s.range.endLineNumber - s.range.startLineNumber, numberComparator)));
      return symbols.map((s) => ({ name: s.name, kind: s.kind, startLineNumber: s.range.startLineNumber }));
    }
  };
  DiffEditorBreadcrumbsSource = __decorate$F([
    __param$E(1, ILanguageFeaturesService),
    __param$E(2, IOutlineModelService)
  ], DiffEditorBreadcrumbsSource);
  HideUnchangedRegionsFeature.setBreadcrumbsSourceFactory((textModel, instantiationService) => {
    return instantiationService.createInstance(DiffEditorBreadcrumbsSource, textModel);
  });
  var __decorate$E = 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$D = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  let FloatingEditorToolbar = (_Fa = class extends Disposable {
    constructor(editor2, instantiationService, keybindingService, menuService) {
      super();
      const editorObs = this._register(observableCodeEditor(editor2));
      const menu = this._register(menuService.createMenu(MenuId.EditorContent, editor2.contextKeyService));
      const menuIsEmptyObs = observableFromEvent(this, menu.onDidChange, () => menu.getActions().length === 0);
      this._register(autorun((reader) => {
        const menuIsEmpty = menuIsEmptyObs.read(reader);
        if (menuIsEmpty) {
          return;
        }
        const container = h("div.floating-menu-overlay-widget");
        container.root.style.height = "28px";
        const toolbar = instantiationService.createInstance(MenuWorkbenchToolBar, container.root, MenuId.EditorContent, {
          actionViewItemProvider: (action, options) => {
            if (!(action instanceof MenuItemAction)) {
              return void 0;
            }
            const keybinding = keybindingService.lookupKeybinding(action.id);
            if (!keybinding) {
              return void 0;
            }
            return instantiationService.createInstance(class extends MenuEntryActionViewItem {
              updateLabel() {
                if (this.options.label && this.label) {
                  this.label.textContent = `${this._commandAction.label} (${keybinding.getLabel()})`;
                }
              }
            }, action, { ...options, keybindingNotRenderedWithLabel: true });
          },
          hiddenItemStrategy: 0,
          menuOptions: {
            shouldForwardArgs: true
          },
          telemetrySource: "editor.overlayToolbar",
          toolbarOptions: {
            primaryGroup: () => true,
            useSeparatorsInPrimaryActions: true
          }
        });
        reader.store.add(toolbar);
        reader.store.add(autorun((reader2) => {
          const model = editorObs.model.read(reader2);
          toolbar.context = model?.uri;
        }));
        reader.store.add(editorObs.createOverlayWidget({
          allowEditorOverflow: false,
          domNode: container.root,
          minContentWidthInPx: constObservable(0),
          position: constObservable({
            preference: 1
            /* OverlayWidgetPositionPreference.BOTTOM_RIGHT_CORNER */
          })
        }));
      }));
    }
  }, _Fa.ID = "editor.contrib.floatingToolbar", _Fa);
  FloatingEditorToolbar = __decorate$E([
    __param$D(1, IInstantiationService),
    __param$D(2, IKeybindingService),
    __param$D(3, IMenuService)
  ], FloatingEditorToolbar);
  registerEditorContribution(
    FloatingEditorToolbar.ID,
    FloatingEditorToolbar,
    1
    /* EditorContributionInstantiation.AfterFirstRender */
  );
  var InspectTokensNLS;
  (function(InspectTokensNLS2) {
    InspectTokensNLS2.inspectTokensAction = localize(786, "Developer: Inspect Tokens");
  })(InspectTokensNLS || (InspectTokensNLS = {}));
  var GoToLineNLS;
  (function(GoToLineNLS2) {
    GoToLineNLS2.gotoLineActionLabel = localize(787, "Go to Line/Column...");
  })(GoToLineNLS || (GoToLineNLS = {}));
  var QuickHelpNLS;
  (function(QuickHelpNLS2) {
    QuickHelpNLS2.helpQuickAccessActionLabel = localize(788, "Show all Quick Access Providers");
  })(QuickHelpNLS || (QuickHelpNLS = {}));
  var QuickCommandNLS;
  (function(QuickCommandNLS2) {
    QuickCommandNLS2.quickCommandActionLabel = localize(789, "Command Palette");
    QuickCommandNLS2.quickCommandHelp = localize(790, "Show And Run Commands");
  })(QuickCommandNLS || (QuickCommandNLS = {}));
  var QuickOutlineNLS;
  (function(QuickOutlineNLS2) {
    QuickOutlineNLS2.quickOutlineActionLabel = localize(791, "Go to Symbol...");
    QuickOutlineNLS2.quickOutlineByCategoryActionLabel = localize(792, "Go to Symbol by Category...");
  })(QuickOutlineNLS || (QuickOutlineNLS = {}));
  var StandaloneCodeEditorNLS;
  (function(StandaloneCodeEditorNLS2) {
    StandaloneCodeEditorNLS2.editorViewAccessibleLabel = localize(793, "Editor content");
  })(StandaloneCodeEditorNLS || (StandaloneCodeEditorNLS = {}));
  var ToggleHighContrastNLS;
  (function(ToggleHighContrastNLS2) {
    ToggleHighContrastNLS2.toggleHighContrast = localize(794, "Toggle High Contrast Theme");
  })(ToggleHighContrastNLS || (ToggleHighContrastNLS = {}));
  var StandaloneServicesNLS;
  (function(StandaloneServicesNLS2) {
    StandaloneServicesNLS2.bulkEditServiceSummary = localize(795, "Made {0} edits in {1} files");
  })(StandaloneServicesNLS || (StandaloneServicesNLS = {}));
  const _IPadShowKeyboard = class _IPadShowKeyboard extends Disposable {
    constructor(editor2) {
      super();
      this.editor = editor2;
      this.widget = null;
      if (isIOS) {
        this._register(editor2.onDidChangeConfiguration(() => this.update()));
        this.update();
      }
    }
    update() {
      const shouldHaveWidget = !this.editor.getOption(
        104
        /* EditorOption.readOnly */
      );
      if (!this.widget && shouldHaveWidget) {
        this.widget = new ShowKeyboardWidget(this.editor);
      } else if (this.widget && !shouldHaveWidget) {
        this.widget.dispose();
        this.widget = null;
      }
    }
    dispose() {
      super.dispose();
      if (this.widget) {
        this.widget.dispose();
        this.widget = null;
      }
    }
  };
  _IPadShowKeyboard.ID = "editor.contrib.iPadShowKeyboard";
  let IPadShowKeyboard = _IPadShowKeyboard;
  const _ShowKeyboardWidget = class _ShowKeyboardWidget extends Disposable {
    constructor(editor2) {
      super();
      this.editor = editor2;
      this._domNode = document.createElement("textarea");
      this._domNode.className = "iPadShowKeyboard";
      this._register(addDisposableListener(this._domNode, "touchstart", (e) => {
        this.editor.focus();
      }));
      this._register(addDisposableListener(this._domNode, "focus", (e) => {
        this.editor.focus();
      }));
      this.editor.addOverlayWidget(this);
    }
    dispose() {
      this.editor.removeOverlayWidget(this);
      super.dispose();
    }
    // ----- IOverlayWidget API
    getId() {
      return _ShowKeyboardWidget.ID;
    }
    getDomNode() {
      return this._domNode;
    }
    getPosition() {
      return {
        preference: 1
        /* OverlayWidgetPositionPreference.BOTTOM_RIGHT_CORNER */
      };
    }
  };
  _ShowKeyboardWidget.ID = "editor.contrib.ShowKeyboardWidget";
  let ShowKeyboardWidget = _ShowKeyboardWidget;
  registerEditorContribution(
    IPadShowKeyboard.ID,
    IPadShowKeyboard,
    3
    /* EditorContributionInstantiation.Eventually */
  );
  const IStandaloneThemeService = createDecorator("themeService");
  var __decorate$D = 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$C = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  var InspectTokensController_1;
  let InspectTokensController = (_Ga = class extends Disposable {
    static get(editor2) {
      return editor2.getContribution(InspectTokensController_1.ID);
    }
    constructor(editor2, standaloneColorService, languageService) {
      super();
      this._editor = editor2;
      this._languageService = languageService;
      this._widget = null;
      this._register(this._editor.onDidChangeModel((e) => this.stop()));
      this._register(this._editor.onDidChangeModelLanguage((e) => this.stop()));
      this._register(TokenizationRegistry.onDidChange((e) => this.stop()));
      this._register(this._editor.onKeyUp((e) => e.keyCode === 9 && this.stop()));
    }
    dispose() {
      this.stop();
      super.dispose();
    }
    launch() {
      if (this._widget) {
        return;
      }
      if (!this._editor.hasModel()) {
        return;
      }
      this._widget = new InspectTokensWidget(this._editor, this._languageService);
    }
    stop() {
      if (this._widget) {
        this._widget.dispose();
        this._widget = null;
      }
    }
  }, InspectTokensController_1 = _Ga, _Ga.ID = "editor.contrib.inspectTokens", _Ga);
  InspectTokensController = InspectTokensController_1 = __decorate$D([
    __param$C(1, IStandaloneThemeService),
    __param$C(2, ILanguageService)
  ], InspectTokensController);
  class InspectTokens extends EditorAction {
    constructor() {
      super({
        id: "editor.action.inspectTokens",
        label: InspectTokensNLS.inspectTokensAction,
        alias: "Developer: Inspect Tokens",
        precondition: void 0
      });
    }
    run(accessor, editor2) {
      const controller = InspectTokensController.get(editor2);
      controller?.launch();
    }
  }
  function renderTokenText(tokenText) {
    let result = "";
    for (let charIndex = 0, len = tokenText.length; charIndex < len; charIndex++) {
      const charCode = tokenText.charCodeAt(charIndex);
      switch (charCode) {
        case 9:
          result += "→";
          break;
        case 32:
          result += "·";
          break;
        default:
          result += String.fromCharCode(charCode);
      }
    }
    return result;
  }
  function getSafeTokenizationSupport$1(languageIdCodec, languageId) {
    const tokenizationSupport = TokenizationRegistry.get(languageId);
    if (tokenizationSupport) {
      return tokenizationSupport;
    }
    const encodedLanguageId = languageIdCodec.encodeLanguageId(languageId);
    return {
      getInitialState: () => NullState,
      tokenize: (line, hasEOL, state) => nullTokenize(languageId, state),
      tokenizeEncoded: (line, hasEOL, state) => nullTokenizeEncoded(encodedLanguageId, state)
    };
  }
  const _InspectTokensWidget = class _InspectTokensWidget extends Disposable {
    constructor(editor2, languageService) {
      super();
      this.allowEditorOverflow = true;
      this._editor = editor2;
      this._languageService = languageService;
      this._model = this._editor.getModel();
      this._domNode = document.createElement("div");
      this._domNode.className = "tokens-inspect-widget";
      this._tokenizationSupport = getSafeTokenizationSupport$1(this._languageService.languageIdCodec, this._model.getLanguageId());
      this._compute(this._editor.getPosition());
      this._register(this._editor.onDidChangeCursorPosition((e) => this._compute(this._editor.getPosition())));
      this._editor.addContentWidget(this);
    }
    dispose() {
      this._editor.removeContentWidget(this);
      super.dispose();
    }
    getId() {
      return _InspectTokensWidget._ID;
    }
    _compute(position) {
      const data = this._getTokensAtLine(position.lineNumber);
      let token1Index = 0;
      for (let i2 = data.tokens1.length - 1; i2 >= 0; i2--) {
        const t = data.tokens1[i2];
        if (position.column - 1 >= t.offset) {
          token1Index = i2;
          break;
        }
      }
      let token2Index = 0;
      for (let i2 = data.tokens2.length >>> 1; i2 >= 0; i2--) {
        if (position.column - 1 >= data.tokens2[i2 << 1]) {
          token2Index = i2;
          break;
        }
      }
      const lineContent = this._model.getLineContent(position.lineNumber);
      let tokenText = "";
      if (token1Index < data.tokens1.length) {
        const tokenStartIndex = data.tokens1[token1Index].offset;
        const tokenEndIndex = token1Index + 1 < data.tokens1.length ? data.tokens1[token1Index + 1].offset : lineContent.length;
        tokenText = lineContent.substring(tokenStartIndex, tokenEndIndex);
      }
      reset(this._domNode, $$l("h2.tm-token", void 0, renderTokenText(tokenText), $$l("span.tm-token-length", void 0, `${tokenText.length} ${tokenText.length === 1 ? "char" : "chars"}`)));
      append$2(this._domNode, $$l("hr.tokens-inspect-separator", { "style": "clear:both" }));
      const metadata = (token2Index << 1) + 1 < data.tokens2.length ? this._decodeMetadata(data.tokens2[(token2Index << 1) + 1]) : null;
      append$2(this._domNode, $$l("table.tm-metadata-table", void 0, $$l("tbody", void 0, $$l("tr", void 0, $$l("td.tm-metadata-key", void 0, "language"), $$l("td.tm-metadata-value", void 0, `${metadata ? metadata.languageId : "-?-"}`)), $$l("tr", void 0, $$l("td.tm-metadata-key", void 0, "token type"), $$l("td.tm-metadata-value", void 0, `${metadata ? this._tokenTypeToString(metadata.tokenType) : "-?-"}`)), $$l("tr", void 0, $$l("td.tm-metadata-key", void 0, "font style"), $$l("td.tm-metadata-value", void 0, `${metadata ? this._fontStyleToString(metadata.fontStyle) : "-?-"}`)), $$l("tr", void 0, $$l("td.tm-metadata-key", void 0, "foreground"), $$l("td.tm-metadata-value", void 0, `${metadata ? Color.Format.CSS.formatHex(metadata.foreground) : "-?-"}`)), $$l("tr", void 0, $$l("td.tm-metadata-key", void 0, "background"), $$l("td.tm-metadata-value", void 0, `${metadata ? Color.Format.CSS.formatHex(metadata.background) : "-?-"}`)))));
      append$2(this._domNode, $$l("hr.tokens-inspect-separator"));
      if (token1Index < data.tokens1.length) {
        append$2(this._domNode, $$l("span.tm-token-type", void 0, data.tokens1[token1Index].type));
      }
      this._editor.layoutContentWidget(this);
    }
    _decodeMetadata(metadata) {
      const colorMap = TokenizationRegistry.getColorMap();
      const languageId = TokenMetadata.getLanguageId(metadata);
      const tokenType = TokenMetadata.getTokenType(metadata);
      const fontStyle = TokenMetadata.getFontStyle(metadata);
      const foreground2 = TokenMetadata.getForeground(metadata);
      const background = TokenMetadata.getBackground(metadata);
      return {
        languageId: this._languageService.languageIdCodec.decodeLanguageId(languageId),
        tokenType,
        fontStyle,
        foreground: colorMap[foreground2],
        background: colorMap[background]
      };
    }
    _tokenTypeToString(tokenType) {
      switch (tokenType) {
        case 0:
          return "Other";
        case 1:
          return "Comment";
        case 2:
          return "String";
        case 3:
          return "RegEx";
        default:
          return "??";
      }
    }
    _fontStyleToString(fontStyle) {
      let r = "";
      if (fontStyle & 1) {
        r += "italic ";
      }
      if (fontStyle & 2) {
        r += "bold ";
      }
      if (fontStyle & 4) {
        r += "underline ";
      }
      if (fontStyle & 8) {
        r += "strikethrough ";
      }
      if (r.length === 0) {
        r = "---";
      }
      return r;
    }
    _getTokensAtLine(lineNumber) {
      const stateBeforeLine = this._getStateBeforeLine(lineNumber);
      const tokenizationResult1 = this._tokenizationSupport.tokenize(this._model.getLineContent(lineNumber), true, stateBeforeLine);
      const tokenizationResult2 = this._tokenizationSupport.tokenizeEncoded(this._model.getLineContent(lineNumber), true, stateBeforeLine);
      return {
        startState: stateBeforeLine,
        tokens1: tokenizationResult1.tokens,
        tokens2: tokenizationResult2.tokens,
        endState: tokenizationResult1.endState
      };
    }
    _getStateBeforeLine(lineNumber) {
      let state = this._tokenizationSupport.getInitialState();
      for (let i2 = 1; i2 < lineNumber; i2++) {
        const tokenizationResult = this._tokenizationSupport.tokenize(this._model.getLineContent(i2), true, state);
        state = tokenizationResult.endState;
      }
      return state;
    }
    getDomNode() {
      return this._domNode;
    }
    getPosition() {
      return {
        position: this._editor.getPosition(),
        preference: [
          2,
          1
          /* ContentWidgetPositionPreference.ABOVE */
        ]
      };
    }
  };
  _InspectTokensWidget._ID = "editor.contrib.inspectTokensWidget";
  let InspectTokensWidget = _InspectTokensWidget;
  registerEditorContribution(
    InspectTokensController.ID,
    InspectTokensController,
    4
    /* EditorContributionInstantiation.Lazy */
  );
  registerEditorAction(InspectTokens);
  var DefaultQuickAccessFilterValue;
  (function(DefaultQuickAccessFilterValue2) {
    DefaultQuickAccessFilterValue2[DefaultQuickAccessFilterValue2["PRESERVE"] = 0] = "PRESERVE";
    DefaultQuickAccessFilterValue2[DefaultQuickAccessFilterValue2["LAST"] = 1] = "LAST";
  })(DefaultQuickAccessFilterValue || (DefaultQuickAccessFilterValue = {}));
  const Extensions = {
    Quickaccess: "workbench.contributions.quickaccess"
  };
  class QuickAccessRegistry {
    constructor() {
      this.providers = [];
      this.defaultProvider = void 0;
    }
    registerQuickAccessProvider(provider) {
      if (provider.prefix.length === 0) {
        this.defaultProvider = provider;
      } else {
        this.providers.push(provider);
      }
      this.providers.sort((providerA, providerB) => providerB.prefix.length - providerA.prefix.length);
      return toDisposable(() => {
        this.providers.splice(this.providers.indexOf(provider), 1);
        if (this.defaultProvider === provider) {
          this.defaultProvider = void 0;
        }
      });
    }
    getQuickAccessProviders() {
      return coalesce([this.defaultProvider, ...this.providers]);
    }
    getQuickAccessProvider(prefix) {
      const result = prefix ? this.providers.find((provider) => prefix.startsWith(provider.prefix)) || void 0 : void 0;
      return result || this.defaultProvider;
    }
  }
  Registry.add(Extensions.Quickaccess, new QuickAccessRegistry());
  var __decorate$C = 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$B = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  var HelpQuickAccessProvider_1;
  let HelpQuickAccessProvider = (_Ha = class {
    constructor(quickInputService, keybindingService) {
      this.quickInputService = quickInputService;
      this.keybindingService = keybindingService;
      this.registry = Registry.as(Extensions.Quickaccess);
    }
    provide(picker) {
      const disposables = new DisposableStore();
      disposables.add(picker.onDidAccept(() => {
        const [item] = picker.selectedItems;
        if (item) {
          this.quickInputService.quickAccess.show(item.prefix, { preserveValue: true });
        }
      }));
      disposables.add(picker.onDidChangeValue((value) => {
        const providerDescriptor = this.registry.getQuickAccessProvider(value.substr(HelpQuickAccessProvider_1.PREFIX.length));
        if (providerDescriptor && providerDescriptor.prefix && providerDescriptor.prefix !== HelpQuickAccessProvider_1.PREFIX) {
          this.quickInputService.quickAccess.show(providerDescriptor.prefix, { preserveValue: true });
        }
      }));
      picker.items = this.getQuickAccessProviders().filter((p) => p.prefix !== HelpQuickAccessProvider_1.PREFIX);
      return disposables;
    }
    getQuickAccessProviders() {
      const providers = this.registry.getQuickAccessProviders().sort((providerA, providerB) => providerA.prefix.localeCompare(providerB.prefix)).flatMap((provider) => this.createPicks(provider));
      return providers;
    }
    createPicks(provider) {
      return provider.helpEntries.map((helpEntry) => {
        const prefix = helpEntry.prefix || provider.prefix;
        const label = prefix || "…";
        return {
          prefix,
          label,
          keybinding: helpEntry.commandId ? this.keybindingService.lookupKeybinding(helpEntry.commandId) : void 0,
          ariaLabel: localize(1747, "{0}, {1}", label, helpEntry.description),
          description: helpEntry.description
        };
      });
    }
  }, HelpQuickAccessProvider_1 = _Ha, _Ha.PREFIX = "?", _Ha);
  HelpQuickAccessProvider = HelpQuickAccessProvider_1 = __decorate$C([
    __param$B(0, IQuickInputService),
    __param$B(1, IKeybindingService)
  ], HelpQuickAccessProvider);
  Registry.as(Extensions.Quickaccess).registerQuickAccessProvider({
    ctor: HelpQuickAccessProvider,
    prefix: "",
    helpEntries: [{ description: QuickHelpNLS.helpQuickAccessActionLabel }]
  });
  class AbstractEditorNavigationQuickAccessProvider {
    constructor(options) {
      this.options = options;
      this.rangeHighlightDecorationId = void 0;
    }
    //#region Provider methods
    provide(picker, token, runOptions) {
      const disposables = new DisposableStore();
      picker.canAcceptInBackground = !!this.options?.canAcceptInBackground;
      picker.matchOnLabel = picker.matchOnDescription = picker.matchOnDetail = picker.sortByLabel = false;
      const pickerDisposable = disposables.add(new MutableDisposable());
      pickerDisposable.value = this.doProvide(picker, token, runOptions);
      disposables.add(this.onDidActiveTextEditorControlChange(() => {
        pickerDisposable.value = void 0;
        pickerDisposable.value = this.doProvide(picker, token);
      }));
      return disposables;
    }
    doProvide(picker, token, runOptions) {
      const disposables = new DisposableStore();
      const editor2 = this.activeTextEditorControl;
      if (editor2 && this.canProvideWithTextEditor(editor2)) {
        const context = { editor: editor2 };
        const codeEditor = getCodeEditor(editor2);
        if (codeEditor) {
          let lastKnownEditorViewState = editor2.saveViewState() ?? void 0;
          disposables.add(codeEditor.onDidChangeCursorPosition(() => {
            lastKnownEditorViewState = editor2.saveViewState() ?? void 0;
          }));
          context.restoreViewState = () => {
            if (lastKnownEditorViewState && editor2 === this.activeTextEditorControl) {
              editor2.restoreViewState(lastKnownEditorViewState);
            }
          };
          disposables.add(createSingleCallFunction(token.onCancellationRequested)(() => context.restoreViewState?.()));
        }
        disposables.add(toDisposable(() => this.clearDecorations(editor2)));
        disposables.add(this.provideWithTextEditor(context, picker, token, runOptions));
      } else {
        disposables.add(this.provideWithoutTextEditor(picker, token));
      }
      return disposables;
    }
    /**
     * Subclasses to implement if they can operate on the text editor.
     */
    canProvideWithTextEditor(editor2) {
      return true;
    }
    gotoLocation({ editor: editor2 }, options) {
      editor2.setSelection(
        options.range,
        "code.jump"
        /* TextEditorSelectionSource.JUMP */
      );
      editor2.revealRangeInCenter(
        options.range,
        0
        /* ScrollType.Smooth */
      );
      if (!options.preserveFocus) {
        editor2.focus();
      }
      const model = editor2.getModel();
      if (model && "getLineContent" in model) {
        status(`${model.getLineContent(options.range.startLineNumber)}`);
      }
    }
    getModel(editor2) {
      return isDiffEditor(editor2) ? editor2.getModel()?.modified : editor2.getModel();
    }
    addDecorations(editor2, range2) {
      editor2.changeDecorations((changeAccessor) => {
        const deleteDecorations = [];
        if (this.rangeHighlightDecorationId) {
          deleteDecorations.push(this.rangeHighlightDecorationId.overviewRulerDecorationId);
          deleteDecorations.push(this.rangeHighlightDecorationId.rangeHighlightId);
          this.rangeHighlightDecorationId = void 0;
        }
        const newDecorations = [
          // highlight the entire line on the range
          {
            range: range2,
            options: {
              description: "quick-access-range-highlight",
              className: "rangeHighlight",
              isWholeLine: true
            }
          },
          // also add overview ruler highlight
          {
            range: range2,
            options: {
              description: "quick-access-range-highlight-overview",
              overviewRuler: {
                color: themeColorFromId(overviewRulerRangeHighlight),
                position: OverviewRulerLane$1.Full
              }
            }
          }
        ];
        const [rangeHighlightId, overviewRulerDecorationId] = changeAccessor.deltaDecorations(deleteDecorations, newDecorations);
        this.rangeHighlightDecorationId = { rangeHighlightId, overviewRulerDecorationId };
      });
    }
    clearDecorations(editor2) {
      const rangeHighlightDecorationId = this.rangeHighlightDecorationId;
      if (rangeHighlightDecorationId) {
        editor2.changeDecorations((changeAccessor) => {
          changeAccessor.deltaDecorations([
            rangeHighlightDecorationId.overviewRulerDecorationId,
            rangeHighlightDecorationId.rangeHighlightId
          ], []);
        });
        this.rangeHighlightDecorationId = void 0;
      }
    }
  }
  const _AbstractGotoLineQuickAccessProvider = class _AbstractGotoLineQuickAccessProvider extends AbstractEditorNavigationQuickAccessProvider {
    constructor() {
      super({ canAcceptInBackground: true });
    }
    get useZeroBasedOffset() {
      return this.storageService.getBoolean(_AbstractGotoLineQuickAccessProvider.ZERO_BASED_OFFSET_STORAGE_KEY, -1, false);
    }
    set useZeroBasedOffset(value) {
      this.storageService.store(
        _AbstractGotoLineQuickAccessProvider.ZERO_BASED_OFFSET_STORAGE_KEY,
        value,
        -1,
        0
        /* StorageTarget.USER */
      );
    }
    provideWithoutTextEditor(picker) {
      const label = localize(1335, "Open a text editor first to go to a line.");
      picker.items = [{ label }];
      picker.ariaLabel = label;
      return Disposable.None;
    }
    provideWithTextEditor(context, picker, token) {
      const editor2 = context.editor;
      const disposables = new DisposableStore();
      disposables.add(picker.onDidAccept((event) => {
        const [item] = picker.selectedItems;
        if (item) {
          if (!item.lineNumber) {
            return;
          }
          this.gotoLocation(context, { range: this.toRange(item.lineNumber, item.column), keyMods: picker.keyMods, preserveFocus: event.inBackground });
          if (!event.inBackground) {
            picker.hide();
          }
        }
      }));
      const updatePickerAndEditor = () => {
        const inputText = picker.value.trim().substring(_AbstractGotoLineQuickAccessProvider.PREFIX.length);
        const { inOffsetMode, lineNumber, column, label } = this.parsePosition(editor2, inputText);
        toggle.visible = !!inOffsetMode;
        picker.items = [{
          lineNumber,
          column,
          label
        }];
        picker.ariaLabel = label;
        if (!lineNumber) {
          this.clearDecorations(editor2);
          return;
        }
        const range2 = this.toRange(lineNumber, column);
        editor2.revealRangeInCenter(
          range2,
          0
          /* ScrollType.Smooth */
        );
        this.addDecorations(editor2, range2);
      };
      const toggle = new Toggle({
        title: localize(1336, "Use Zero-Based Offset"),
        icon: Codicon.indexZero,
        isChecked: this.useZeroBasedOffset,
        inputActiveOptionBorder: asCssVariable(inputActiveOptionBorder),
        inputActiveOptionForeground: asCssVariable(inputActiveOptionForeground),
        inputActiveOptionBackground: asCssVariable(inputActiveOptionBackground)
      });
      disposables.add(toggle.onChange(() => {
        this.useZeroBasedOffset = !this.useZeroBasedOffset;
        updatePickerAndEditor();
      }));
      picker.toggles = [toggle];
      updatePickerAndEditor();
      disposables.add(picker.onDidChangeValue(() => updatePickerAndEditor()));
      const codeEditor = getCodeEditor(editor2);
      if (codeEditor) {
        const options = codeEditor.getOptions();
        const lineNumbers = options.get(
          76
          /* EditorOption.lineNumbers */
        );
        if (lineNumbers.renderType === 2) {
          codeEditor.updateOptions({ lineNumbers: "on" });
          disposables.add(toDisposable(() => codeEditor.updateOptions({ lineNumbers: "relative" })));
        }
      }
      return disposables;
    }
    toRange(lineNumber = 1, column = 1) {
      return {
        startLineNumber: lineNumber,
        startColumn: column,
        endLineNumber: lineNumber,
        endColumn: column
      };
    }
    parsePosition(editor2, value) {
      const model = this.getModel(editor2);
      if (!model) {
        return {
          label: localize(1337, "Open a text editor first to go to a line.")
        };
      }
      if (value.startsWith(":")) {
        let offset = parseInt(value.substring(1), 10);
        const maxOffset = model.getValueLength();
        if (isNaN(offset)) {
          return {
            inOffsetMode: true,
            label: this.useZeroBasedOffset ? localize(1338, "Type a character position to go to (from 0 to {0}).", maxOffset - 1) : localize(1339, "Type a character position to go to (from 1 to {0}).", maxOffset)
          };
        } else {
          const reverse = offset < 0;
          if (!this.useZeroBasedOffset) {
            offset -= Math.sign(offset);
          }
          if (reverse) {
            offset += maxOffset;
          }
          const pos = model.getPositionAt(offset);
          return {
            ...pos,
            inOffsetMode: true,
            label: localize(1340, "Press 'Enter' to go to line {0} at column {1}.", pos.lineNumber, pos.column)
          };
        }
      } else {
        const parts = value.split(/,|:|#/);
        const maxLine = model.getLineCount();
        let lineNumber = parseInt(parts[0]?.trim(), 10);
        if (parts.length < 1 || isNaN(lineNumber)) {
          return {
            label: localize(1341, "Type a line number to go to (from 1 to {0}).", maxLine)
          };
        }
        lineNumber = lineNumber >= 0 ? lineNumber : maxLine + 1 + lineNumber;
        lineNumber = Math.min(Math.max(1, lineNumber), maxLine);
        const maxColumn = model.getLineMaxColumn(lineNumber);
        let column = parseInt(parts[1]?.trim(), 10);
        if (parts.length < 2 || isNaN(column)) {
          return {
            lineNumber,
            column: 1,
            label: parts.length < 2 ? localize(1342, "Press 'Enter' to go to line {0} or enter : to add a column number.", lineNumber) : localize(1343, "Press 'Enter' to go to line {0} or enter a column number (from 1 to {1}).", lineNumber, maxColumn)
          };
        }
        column = column >= 0 ? column : maxColumn + column;
        column = Math.min(Math.max(1, column), maxColumn);
        return {
          lineNumber,
          column,
          label: localize(1344, "Press 'Enter' to go to line {0} at column {1}.", lineNumber, column)
        };
      }
    }
  };
  _AbstractGotoLineQuickAccessProvider.PREFIX = ":";
  _AbstractGotoLineQuickAccessProvider.ZERO_BASED_OFFSET_STORAGE_KEY = "gotoLine.useZeroBasedOffset";
  let AbstractGotoLineQuickAccessProvider = _AbstractGotoLineQuickAccessProvider;
  var __decorate$B = 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$A = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  let StandaloneGotoLineQuickAccessProvider = class StandaloneGotoLineQuickAccessProvider extends AbstractGotoLineQuickAccessProvider {
    constructor(editorService, storageService) {
      super();
      this.editorService = editorService;
      this.storageService = storageService;
      this.onDidActiveTextEditorControlChange = Event.None;
    }
    get activeTextEditorControl() {
      return this.editorService.getFocusedCodeEditor() ?? void 0;
    }
  };
  StandaloneGotoLineQuickAccessProvider = __decorate$B([
    __param$A(0, ICodeEditorService),
    __param$A(1, IStorageService)
  ], StandaloneGotoLineQuickAccessProvider);
  let GotoLineAction$1 = (_Ia = class extends EditorAction {
    constructor() {
      super({
        id: _Ia.ID,
        label: GoToLineNLS.gotoLineActionLabel,
        alias: "Go to Line/Column...",
        precondition: void 0,
        kbOpts: {
          kbExpr: EditorContextKeys.focus,
          primary: 2048 | 37,
          mac: {
            primary: 256 | 37
            /* KeyCode.KeyG */
          },
          weight: 100
          /* KeybindingWeight.EditorContrib */
        }
      });
    }
    run(accessor) {
      accessor.get(IQuickInputService).quickAccess.show(StandaloneGotoLineQuickAccessProvider.PREFIX);
    }
  }, _Ia.ID = "editor.action.gotoLine", _Ia);
  registerEditorAction(GotoLineAction$1);
  Registry.as(Extensions.Quickaccess).registerQuickAccessProvider({
    ctor: StandaloneGotoLineQuickAccessProvider,
    prefix: StandaloneGotoLineQuickAccessProvider.PREFIX,
    helpEntries: [{ description: GoToLineNLS.gotoLineActionLabel, commandId: GotoLineAction$1.ID }]
  });
  const NO_SCORE2 = [void 0, []];
  function scoreFuzzy2(target, query, patternStart = 0, wordStart = 0) {
    const preparedQuery = query;
    if (preparedQuery.values && preparedQuery.values.length > 1) {
      return doScoreFuzzy2Multiple(target, preparedQuery.values, patternStart, wordStart);
    }
    return doScoreFuzzy2Single(target, query, patternStart, wordStart);
  }
  function doScoreFuzzy2Multiple(target, query, patternStart, wordStart) {
    let totalScore = 0;
    const totalMatches = [];
    for (const queryPiece of query) {
      const [score2, matches] = doScoreFuzzy2Single(target, queryPiece, patternStart, wordStart);
      if (typeof score2 !== "number") {
        return NO_SCORE2;
      }
      totalScore += score2;
      totalMatches.push(...matches);
    }
    return [totalScore, normalizeMatches(totalMatches)];
  }
  function doScoreFuzzy2Single(target, query, patternStart, wordStart) {
    const score2 = fuzzyScore(query.original, query.originalLowercase, patternStart, target, target.toLowerCase(), wordStart, { firstMatchCanBeWeak: true, boostFullMatch: true });
    if (!score2) {
      return NO_SCORE2;
    }
    return [score2[0], createMatches(score2)];
  }
  function normalizeMatches(matches) {
    const sortedMatches = matches.sort((matchA, matchB) => {
      return matchA.start - matchB.start;
    });
    const normalizedMatches = [];
    let currentMatch = void 0;
    for (const match2 of sortedMatches) {
      if (!currentMatch || !matchOverlaps(currentMatch, match2)) {
        currentMatch = match2;
        normalizedMatches.push(match2);
      } else {
        currentMatch.start = Math.min(currentMatch.start, match2.start);
        currentMatch.end = Math.max(currentMatch.end, match2.end);
      }
    }
    return normalizedMatches;
  }
  function matchOverlaps(matchA, matchB) {
    if (matchA.end < matchB.start) {
      return false;
    }
    if (matchB.end < matchA.start) {
      return false;
    }
    return true;
  }
  function queryExpectsExactMatch(query) {
    return query.startsWith('"') && query.endsWith('"');
  }
  const MULTIPLE_QUERY_VALUES_SEPARATOR = " ";
  function prepareQuery(original) {
    if (typeof original !== "string") {
      original = "";
    }
    const originalLowercase = original.toLowerCase();
    const { pathNormalized, normalized, normalizedLowercase } = normalizeQuery(original);
    const containsPathSeparator = pathNormalized.indexOf(sep) >= 0;
    const expectExactMatch = queryExpectsExactMatch(original);
    let values = void 0;
    const originalSplit = original.split(MULTIPLE_QUERY_VALUES_SEPARATOR);
    if (originalSplit.length > 1) {
      for (const originalPiece of originalSplit) {
        const expectExactMatchPiece = queryExpectsExactMatch(originalPiece);
        const { pathNormalized: pathNormalizedPiece, normalized: normalizedPiece, normalizedLowercase: normalizedLowercasePiece } = normalizeQuery(originalPiece);
        if (normalizedPiece) {
          if (!values) {
            values = [];
          }
          values.push({
            original: originalPiece,
            originalLowercase: originalPiece.toLowerCase(),
            pathNormalized: pathNormalizedPiece,
            normalized: normalizedPiece,
            normalizedLowercase: normalizedLowercasePiece,
            expectContiguousMatch: expectExactMatchPiece
          });
        }
      }
    }
    return { original, originalLowercase, pathNormalized, normalized, normalizedLowercase, values, containsPathSeparator, expectContiguousMatch: expectExactMatch };
  }
  function normalizeQuery(original) {
    let pathNormalized;
    if (isWindows) {
      pathNormalized = original.replace(/\//g, sep);
    } else {
      pathNormalized = original.replace(/\\/g, sep);
    }
    const normalized = pathNormalized.replace(/[\*\u2026\s"]/g, "");
    return {
      pathNormalized,
      normalized,
      normalizedLowercase: normalized.toLowerCase()
    };
  }
  function pieceToQuery(arg1) {
    if (Array.isArray(arg1)) {
      return prepareQuery(arg1.map((piece) => piece.original).join(MULTIPLE_QUERY_VALUES_SEPARATOR));
    }
    return prepareQuery(arg1.original);
  }
  var __decorate$A = 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$z = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  var AbstractGotoSymbolQuickAccessProvider_1;
  let AbstractGotoSymbolQuickAccessProvider = (_Ja = class extends AbstractEditorNavigationQuickAccessProvider {
    constructor(_languageFeaturesService, _outlineModelService, options = /* @__PURE__ */ Object.create(null)) {
      super(options);
      this._languageFeaturesService = _languageFeaturesService;
      this._outlineModelService = _outlineModelService;
      this.options = options;
      this.options.canAcceptInBackground = true;
    }
    provideWithoutTextEditor(picker) {
      this.provideLabelPick(picker, localize(1345, "To go to a symbol, first open a text editor with symbol information."));
      return Disposable.None;
    }
    provideWithTextEditor(context, picker, token, runOptions) {
      const editor2 = context.editor;
      const model = this.getModel(editor2);
      if (!model) {
        return Disposable.None;
      }
      if (this._languageFeaturesService.documentSymbolProvider.has(model)) {
        return this.doProvideWithEditorSymbols(context, model, picker, token, runOptions);
      }
      return this.doProvideWithoutEditorSymbols(context, model, picker, token);
    }
    doProvideWithoutEditorSymbols(context, model, picker, token) {
      const disposables = new DisposableStore();
      this.provideLabelPick(picker, localize(1346, "The active text editor does not provide symbol information."));
      (async () => {
        const result = await this.waitForLanguageSymbolRegistry(model, disposables);
        if (!result || token.isCancellationRequested) {
          return;
        }
        disposables.add(this.doProvideWithEditorSymbols(context, model, picker, token));
      })();
      return disposables;
    }
    provideLabelPick(picker, label) {
      picker.items = [{
        label,
        index: 0,
        kind: 14
        /* SymbolKind.String */
      }];
      picker.ariaLabel = label;
    }
    async waitForLanguageSymbolRegistry(model, disposables) {
      if (this._languageFeaturesService.documentSymbolProvider.has(model)) {
        return true;
      }
      const symbolProviderRegistryPromise = new DeferredPromise();
      const symbolProviderListener = disposables.add(this._languageFeaturesService.documentSymbolProvider.onDidChange(() => {
        if (this._languageFeaturesService.documentSymbolProvider.has(model)) {
          symbolProviderListener.dispose();
          symbolProviderRegistryPromise.complete(true);
        }
      }));
      disposables.add(toDisposable(() => symbolProviderRegistryPromise.complete(false)));
      return symbolProviderRegistryPromise.p;
    }
    doProvideWithEditorSymbols(context, model, picker, token, runOptions) {
      const editor2 = context.editor;
      const disposables = new DisposableStore();
      disposables.add(picker.onDidAccept((event) => {
        const [item] = picker.selectedItems;
        if (item && item.range) {
          this.gotoLocation(context, { range: item.range.selection, keyMods: picker.keyMods, preserveFocus: event.inBackground });
          runOptions?.handleAccept?.(item, event.inBackground);
          if (!event.inBackground) {
            picker.hide();
          }
        }
      }));
      disposables.add(picker.onDidTriggerItemButton(({ item }) => {
        if (item && item.range) {
          this.gotoLocation(context, { range: item.range.selection, keyMods: picker.keyMods, forceSideBySide: true });
          picker.hide();
        }
      }));
      const symbolsPromise = this.getDocumentSymbols(model, token);
      const picksCts = disposables.add(new MutableDisposable());
      const updatePickerItems = async (positionToEnclose) => {
        picksCts?.value?.cancel();
        picker.busy = false;
        picksCts.value = new CancellationTokenSource$1();
        picker.busy = true;
        try {
          const query = prepareQuery(picker.value.substr(AbstractGotoSymbolQuickAccessProvider_1.PREFIX.length).trim());
          const items = await this.doGetSymbolPicks(symbolsPromise, query, void 0, picksCts.value.token, model);
          if (token.isCancellationRequested) {
            return;
          }
          if (items.length > 0) {
            picker.items = items;
            if (positionToEnclose && query.original.length === 0) {
              const candidate = findLast(items, (item) => Boolean(item.type !== "separator" && item.range && Range$2.containsPosition(item.range.decoration, positionToEnclose)));
              if (candidate) {
                picker.activeItems = [candidate];
              }
            }
          } else {
            if (query.original.length > 0) {
              this.provideLabelPick(picker, localize(1347, "No matching editor symbols"));
            } else {
              this.provideLabelPick(picker, localize(1348, "No editor symbols"));
            }
          }
        } finally {
          if (!token.isCancellationRequested) {
            picker.busy = false;
          }
        }
      };
      disposables.add(picker.onDidChangeValue(() => updatePickerItems(void 0)));
      updatePickerItems(editor2.getSelection()?.getPosition());
      disposables.add(picker.onDidChangeActive(() => {
        const [item] = picker.activeItems;
        if (item && item.range) {
          editor2.revealRangeInCenter(
            item.range.selection,
            0
            /* ScrollType.Smooth */
          );
          this.addDecorations(editor2, item.range.decoration);
        }
      }));
      return disposables;
    }
    async doGetSymbolPicks(symbolsPromise, query, options, token, model) {
      const symbols = await symbolsPromise;
      if (token.isCancellationRequested) {
        return [];
      }
      const filterBySymbolKind = query.original.indexOf(AbstractGotoSymbolQuickAccessProvider_1.SCOPE_PREFIX) === 0;
      const filterPos = filterBySymbolKind ? 1 : 0;
      let symbolQuery;
      let containerQuery;
      if (query.values && query.values.length > 1) {
        symbolQuery = pieceToQuery(query.values[0]);
        containerQuery = pieceToQuery(query.values.slice(1));
      } else {
        symbolQuery = query;
      }
      let buttons;
      const openSideBySideDirection = this.options?.openSideBySideDirection?.();
      if (openSideBySideDirection) {
        buttons = [{
          iconClass: openSideBySideDirection === "right" ? ThemeIcon.asClassName(Codicon.splitHorizontal) : ThemeIcon.asClassName(Codicon.splitVertical),
          tooltip: openSideBySideDirection === "right" ? localize(1349, "Open to the Side") : localize(1350, "Open to the Bottom")
        }];
      }
      const filteredSymbolPicks = [];
      for (let index = 0; index < symbols.length; index++) {
        const symbol = symbols[index];
        const symbolLabel = trim(symbol.name);
        const symbolLabelWithIcon = `$(${SymbolKinds.toIcon(symbol.kind).id}) ${symbolLabel}`;
        const symbolLabelIconOffset = symbolLabelWithIcon.length - symbolLabel.length;
        let containerLabel = symbol.containerName;
        if (options?.extraContainerLabel) {
          if (containerLabel) {
            containerLabel = `${options.extraContainerLabel} • ${containerLabel}`;
          } else {
            containerLabel = options.extraContainerLabel;
          }
        }
        let symbolScore = void 0;
        let symbolMatches = void 0;
        let containerScore = void 0;
        let containerMatches = void 0;
        if (query.original.length > filterPos) {
          let skipContainerQuery = false;
          if (symbolQuery !== query) {
            [symbolScore, symbolMatches] = scoreFuzzy2(symbolLabelWithIcon, {
              ...query,
              values: void 0
              /* disable multi-query support */
            }, filterPos, symbolLabelIconOffset);
            if (typeof symbolScore === "number") {
              skipContainerQuery = true;
            }
          }
          if (typeof symbolScore !== "number") {
            [symbolScore, symbolMatches] = scoreFuzzy2(symbolLabelWithIcon, symbolQuery, filterPos, symbolLabelIconOffset);
            if (typeof symbolScore !== "number") {
              continue;
            }
          }
          if (!skipContainerQuery && containerQuery) {
            if (containerLabel && containerQuery.original.length > 0) {
              [containerScore, containerMatches] = scoreFuzzy2(containerLabel, containerQuery);
            }
            if (typeof containerScore !== "number") {
              continue;
            }
            if (typeof symbolScore === "number") {
              symbolScore += containerScore;
            }
          }
        }
        const deprecated = symbol.tags && symbol.tags.indexOf(
          1
          /* SymbolTag.Deprecated */
        ) >= 0;
        filteredSymbolPicks.push({
          index,
          kind: symbol.kind,
          score: symbolScore,
          label: symbolLabelWithIcon,
          ariaLabel: getAriaLabelForSymbol(symbol.name, symbol.kind),
          description: containerLabel,
          highlights: deprecated ? void 0 : {
            label: symbolMatches,
            description: containerMatches
          },
          range: {
            selection: Range$2.collapseToStart(symbol.selectionRange),
            decoration: symbol.range
          },
          uri: model.uri,
          symbolName: symbolLabel,
          strikethrough: deprecated,
          buttons
        });
      }
      const sortedFilteredSymbolPicks = filteredSymbolPicks.sort((symbolA, symbolB) => filterBySymbolKind ? this.compareByKindAndScore(symbolA, symbolB) : this.compareByScore(symbolA, symbolB));
      let symbolPicks = [];
      if (filterBySymbolKind) {
        let updateLastSeparatorLabel = function() {
          if (lastSeparator && typeof lastSymbolKind === "number" && lastSymbolKindCounter > 0) {
            lastSeparator.label = format(NLS_SYMBOL_KIND_CACHE[lastSymbolKind] || FALLBACK_NLS_SYMBOL_KIND, lastSymbolKindCounter);
          }
        };
        let lastSymbolKind = void 0;
        let lastSeparator = void 0;
        let lastSymbolKindCounter = 0;
        for (const symbolPick of sortedFilteredSymbolPicks) {
          if (lastSymbolKind !== symbolPick.kind) {
            updateLastSeparatorLabel();
            lastSymbolKind = symbolPick.kind;
            lastSymbolKindCounter = 1;
            lastSeparator = { type: "separator" };
            symbolPicks.push(lastSeparator);
          } else {
            lastSymbolKindCounter++;
          }
          symbolPicks.push(symbolPick);
        }
        updateLastSeparatorLabel();
      } else if (sortedFilteredSymbolPicks.length > 0) {
        symbolPicks = [
          { label: localize(1351, "symbols ({0})", filteredSymbolPicks.length), type: "separator" },
          ...sortedFilteredSymbolPicks
        ];
      }
      return symbolPicks;
    }
    compareByScore(symbolA, symbolB) {
      if (typeof symbolA.score !== "number" && typeof symbolB.score === "number") {
        return 1;
      } else if (typeof symbolA.score === "number" && typeof symbolB.score !== "number") {
        return -1;
      }
      if (typeof symbolA.score === "number" && typeof symbolB.score === "number") {
        if (symbolA.score > symbolB.score) {
          return -1;
        } else if (symbolA.score < symbolB.score) {
          return 1;
        }
      }
      if (symbolA.index < symbolB.index) {
        return -1;
      } else if (symbolA.index > symbolB.index) {
        return 1;
      }
      return 0;
    }
    compareByKindAndScore(symbolA, symbolB) {
      const kindA = NLS_SYMBOL_KIND_CACHE[symbolA.kind] || FALLBACK_NLS_SYMBOL_KIND;
      const kindB = NLS_SYMBOL_KIND_CACHE[symbolB.kind] || FALLBACK_NLS_SYMBOL_KIND;
      const result = kindA.localeCompare(kindB);
      if (result === 0) {
        return this.compareByScore(symbolA, symbolB);
      }
      return result;
    }
    async getDocumentSymbols(document2, token) {
      const model = await this._outlineModelService.getOrCreate(document2, token);
      return token.isCancellationRequested ? [] : model.asListOfDocumentSymbols();
    }
  }, AbstractGotoSymbolQuickAccessProvider_1 = _Ja, _Ja.PREFIX = "@", _Ja.SCOPE_PREFIX = ":", _Ja.PREFIX_BY_CATEGORY = `${_Ja.PREFIX}${_Ja.SCOPE_PREFIX}`, _Ja);
  AbstractGotoSymbolQuickAccessProvider = AbstractGotoSymbolQuickAccessProvider_1 = __decorate$A([
    __param$z(0, ILanguageFeaturesService),
    __param$z(1, IOutlineModelService)
  ], AbstractGotoSymbolQuickAccessProvider);
  const FALLBACK_NLS_SYMBOL_KIND = localize(1352, "properties ({0})");
  const NLS_SYMBOL_KIND_CACHE = {
    [
      5
      /* SymbolKind.Method */
    ]: localize(1353, "methods ({0})"),
    [
      11
      /* SymbolKind.Function */
    ]: localize(1354, "functions ({0})"),
    [
      8
      /* SymbolKind.Constructor */
    ]: localize(1355, "constructors ({0})"),
    [
      12
      /* SymbolKind.Variable */
    ]: localize(1356, "variables ({0})"),
    [
      4
      /* SymbolKind.Class */
    ]: localize(1357, "classes ({0})"),
    [
      22
      /* SymbolKind.Struct */
    ]: localize(1358, "structs ({0})"),
    [
      23
      /* SymbolKind.Event */
    ]: localize(1359, "events ({0})"),
    [
      24
      /* SymbolKind.Operator */
    ]: localize(1360, "operators ({0})"),
    [
      10
      /* SymbolKind.Interface */
    ]: localize(1361, "interfaces ({0})"),
    [
      2
      /* SymbolKind.Namespace */
    ]: localize(1362, "namespaces ({0})"),
    [
      3
      /* SymbolKind.Package */
    ]: localize(1363, "packages ({0})"),
    [
      25
      /* SymbolKind.TypeParameter */
    ]: localize(1364, "type parameters ({0})"),
    [
      1
      /* SymbolKind.Module */
    ]: localize(1365, "modules ({0})"),
    [
      6
      /* SymbolKind.Property */
    ]: localize(1366, "properties ({0})"),
    [
      9
      /* SymbolKind.Enum */
    ]: localize(1367, "enumerations ({0})"),
    [
      21
      /* SymbolKind.EnumMember */
    ]: localize(1368, "enumeration members ({0})"),
    [
      14
      /* SymbolKind.String */
    ]: localize(1369, "strings ({0})"),
    [
      0
      /* SymbolKind.File */
    ]: localize(1370, "files ({0})"),
    [
      17
      /* SymbolKind.Array */
    ]: localize(1371, "arrays ({0})"),
    [
      15
      /* SymbolKind.Number */
    ]: localize(1372, "numbers ({0})"),
    [
      16
      /* SymbolKind.Boolean */
    ]: localize(1373, "booleans ({0})"),
    [
      18
      /* SymbolKind.Object */
    ]: localize(1374, "objects ({0})"),
    [
      19
      /* SymbolKind.Key */
    ]: localize(1375, "keys ({0})"),
    [
      7
      /* SymbolKind.Field */
    ]: localize(1376, "fields ({0})"),
    [
      13
      /* SymbolKind.Constant */
    ]: localize(1377, "constants ({0})")
  };
  var __decorate$z = 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$y = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  let StandaloneGotoSymbolQuickAccessProvider = class StandaloneGotoSymbolQuickAccessProvider extends AbstractGotoSymbolQuickAccessProvider {
    constructor(editorService, languageFeaturesService, outlineModelService) {
      super(languageFeaturesService, outlineModelService);
      this.editorService = editorService;
      this.onDidActiveTextEditorControlChange = Event.None;
    }
    get activeTextEditorControl() {
      return this.editorService.getFocusedCodeEditor() ?? void 0;
    }
  };
  StandaloneGotoSymbolQuickAccessProvider = __decorate$z([
    __param$y(0, ICodeEditorService),
    __param$y(1, ILanguageFeaturesService),
    __param$y(2, IOutlineModelService)
  ], StandaloneGotoSymbolQuickAccessProvider);
  const _GotoSymbolAction = class _GotoSymbolAction extends EditorAction {
    constructor() {
      super({
        id: _GotoSymbolAction.ID,
        label: QuickOutlineNLS.quickOutlineActionLabel,
        alias: "Go to Symbol...",
        precondition: EditorContextKeys.hasDocumentSymbolProvider,
        kbOpts: {
          kbExpr: EditorContextKeys.focus,
          primary: 2048 | 1024 | 45,
          weight: 100
          /* KeybindingWeight.EditorContrib */
        },
        contextMenuOpts: {
          group: "navigation",
          order: 3
        }
      });
    }
    run(accessor) {
      accessor.get(IQuickInputService).quickAccess.show(AbstractGotoSymbolQuickAccessProvider.PREFIX, { itemActivation: ItemActivation.NONE });
    }
  };
  _GotoSymbolAction.ID = "editor.action.quickOutline";
  let GotoSymbolAction = _GotoSymbolAction;
  registerEditorAction(GotoSymbolAction);
  Registry.as(Extensions.Quickaccess).registerQuickAccessProvider({
    ctor: StandaloneGotoSymbolQuickAccessProvider,
    prefix: AbstractGotoSymbolQuickAccessProvider.PREFIX,
    helpEntries: [
      { description: QuickOutlineNLS.quickOutlineActionLabel, prefix: AbstractGotoSymbolQuickAccessProvider.PREFIX, commandId: GotoSymbolAction.ID },
      { description: QuickOutlineNLS.quickOutlineByCategoryActionLabel, prefix: AbstractGotoSymbolQuickAccessProvider.PREFIX_BY_CATEGORY }
    ]
  });
  function countMapFrom(values) {
    const map = /* @__PURE__ */ new Map();
    for (const value of values) {
      map.set(value, (map.get(value) ?? 0) + 1);
    }
    return map;
  }
  class TfIdfCalculator {
    constructor() {
      this.chunkCount = 0;
      this.chunkOccurrences = /* @__PURE__ */ new Map();
      this.documents = /* @__PURE__ */ new Map();
    }
    calculateScores(query, token) {
      const embedding = this.computeEmbedding(query);
      const idfCache = /* @__PURE__ */ new Map();
      const scores = [];
      for (const [key, doc] of this.documents) {
        if (token.isCancellationRequested) {
          return [];
        }
        for (const chunk of doc.chunks) {
          const score2 = this.computeSimilarityScore(chunk, embedding, idfCache);
          if (score2 > 0) {
            scores.push({ key, score: score2 });
          }
        }
      }
      return scores;
    }
    /**
     * Count how many times each term (word) appears in a string.
     */
    static termFrequencies(input) {
      return countMapFrom(TfIdfCalculator.splitTerms(input));
    }
    /**
     * Break a string into terms (words).
     */
    static *splitTerms(input) {
      const normalize2 = (word) => word.toLowerCase();
      for (const [word] of input.matchAll(new RegExp("\\b\\p{Letter}[\\p{Letter}\\d]{2,}\\b", "gu"))) {
        yield normalize2(word);
        const camelParts = word.replace(/([a-z])([A-Z])/g, "$1 $2").split(/\s+/g);
        if (camelParts.length > 1) {
          for (const part of camelParts) {
            if (part.length > 2 && new RegExp("\\p{Letter}{3,}", "gu").test(part)) {
              yield normalize2(part);
            }
          }
        }
      }
    }
    updateDocuments(documents) {
      for (const { key } of documents) {
        this.deleteDocument(key);
      }
      for (const doc of documents) {
        const chunks = [];
        for (const text2 of doc.textChunks) {
          const tf = TfIdfCalculator.termFrequencies(text2);
          for (const term of tf.keys()) {
            this.chunkOccurrences.set(term, (this.chunkOccurrences.get(term) ?? 0) + 1);
          }
          chunks.push({ text: text2, tf });
        }
        this.chunkCount += chunks.length;
        this.documents.set(doc.key, { chunks });
      }
      return this;
    }
    deleteDocument(key) {
      const doc = this.documents.get(key);
      if (!doc) {
        return;
      }
      this.documents.delete(key);
      this.chunkCount -= doc.chunks.length;
      for (const chunk of doc.chunks) {
        for (const term of chunk.tf.keys()) {
          const currentOccurrences = this.chunkOccurrences.get(term);
          if (typeof currentOccurrences === "number") {
            const newOccurrences = currentOccurrences - 1;
            if (newOccurrences <= 0) {
              this.chunkOccurrences.delete(term);
            } else {
              this.chunkOccurrences.set(term, newOccurrences);
            }
          }
        }
      }
    }
    computeSimilarityScore(chunk, queryEmbedding, idfCache) {
      let sum2 = 0;
      for (const [term, termTfidf] of Object.entries(queryEmbedding)) {
        const chunkTf = chunk.tf.get(term);
        if (!chunkTf) {
          continue;
        }
        let chunkIdf = idfCache.get(term);
        if (typeof chunkIdf !== "number") {
          chunkIdf = this.computeIdf(term);
          idfCache.set(term, chunkIdf);
        }
        const chunkTfidf = chunkTf * chunkIdf;
        sum2 += chunkTfidf * termTfidf;
      }
      return sum2;
    }
    computeEmbedding(input) {
      const tf = TfIdfCalculator.termFrequencies(input);
      return this.computeTfidf(tf);
    }
    computeIdf(term) {
      const chunkOccurrences = this.chunkOccurrences.get(term) ?? 0;
      return chunkOccurrences > 0 ? Math.log((this.chunkCount + 1) / chunkOccurrences) : 0;
    }
    computeTfidf(termFrequencies) {
      const embedding = /* @__PURE__ */ Object.create(null);
      for (const [word, occurrences] of termFrequencies) {
        const idf = this.computeIdf(word);
        if (idf > 0) {
          embedding[word] = occurrences * idf;
        }
      }
      return embedding;
    }
  }
  function normalizeTfIdfScores(scores) {
    const result = scores.slice(0);
    result.sort((a, b) => b.score - a.score);
    const max = result[0]?.score ?? 0;
    if (max > 0) {
      for (const score2 of result) {
        score2.score /= max;
      }
    }
    return result;
  }
  var TriggerAction;
  (function(TriggerAction2) {
    TriggerAction2[TriggerAction2["NO_ACTION"] = 0] = "NO_ACTION";
    TriggerAction2[TriggerAction2["CLOSE_PICKER"] = 1] = "CLOSE_PICKER";
    TriggerAction2[TriggerAction2["REFRESH_PICKER"] = 2] = "REFRESH_PICKER";
    TriggerAction2[TriggerAction2["REMOVE_ITEM"] = 3] = "REMOVE_ITEM";
  })(TriggerAction || (TriggerAction = {}));
  function isPicksWithActive(obj) {
    const candidate = obj;
    return Array.isArray(candidate.items);
  }
  function isFastAndSlowPicks(obj) {
    const candidate = obj;
    return !!candidate.picks && candidate.additionalPicks instanceof Promise;
  }
  class PickerQuickAccessProvider extends Disposable {
    constructor(prefix, options) {
      super();
      this.prefix = prefix;
      this.options = options;
    }
    provide(picker, token, runOptions) {
      const disposables = new DisposableStore();
      picker.canAcceptInBackground = !!this.options?.canAcceptInBackground;
      picker.matchOnLabel = picker.matchOnDescription = picker.matchOnDetail = picker.sortByLabel = false;
      let picksCts = void 0;
      const picksDisposable = disposables.add(new MutableDisposable());
      const updatePickerItems = async () => {
        picksCts?.dispose(true);
        picker.busy = false;
        const picksDisposables = picksDisposable.value = new DisposableStore();
        picksCts = picksDisposables.add(new CancellationTokenSource$1(token));
        const picksToken = picksCts.token;
        let picksFilter = picker.value.substring(this.prefix.length);
        if (!this.options?.shouldSkipTrimPickFilter) {
          picksFilter = picksFilter.trim();
        }
        const providedPicks = this._getPicks(picksFilter, picksDisposables, picksToken, runOptions);
        const applyPicks = (picks, skipEmpty) => {
          let items;
          let activeItem = void 0;
          if (isPicksWithActive(picks)) {
            items = picks.items;
            activeItem = picks.active;
          } else {
            items = picks;
          }
          if (items.length === 0) {
            if (skipEmpty) {
              return false;
            }
            if ((picksFilter.length > 0 || picker.hideInput) && this.options?.noResultsPick) {
              if (isFunction(this.options.noResultsPick)) {
                items = [this.options.noResultsPick(picksFilter)];
              } else {
                items = [this.options.noResultsPick];
              }
            }
          }
          picker.items = items;
          if (activeItem) {
            picker.activeItems = [activeItem];
          }
          return true;
        };
        const applyFastAndSlowPicks = async (fastAndSlowPicks) => {
          let fastPicksApplied = false;
          let slowPicksApplied = false;
          await Promise.all([
            // Fast Picks: if `mergeDelay` is configured, in order to reduce
            // amount of flicker, we race against the slow picks over some delay
            // and then set the fast picks.
            // If the slow picks are faster, we reduce the flicker by only
            // setting the items once.
            (async () => {
              if (typeof fastAndSlowPicks.mergeDelay === "number") {
                await timeout(fastAndSlowPicks.mergeDelay);
                if (picksToken.isCancellationRequested) {
                  return;
                }
              }
              if (!slowPicksApplied) {
                fastPicksApplied = applyPicks(
                  fastAndSlowPicks.picks,
                  true
                  /* skip over empty to reduce flicker */
                );
              }
            })(),
            // Slow Picks: we await the slow picks and then set them at
            // once together with the fast picks, but only if we actually
            // have additional results.
            (async () => {
              picker.busy = true;
              try {
                const awaitedAdditionalPicks = await fastAndSlowPicks.additionalPicks;
                if (picksToken.isCancellationRequested) {
                  return;
                }
                let picks;
                let activePick = void 0;
                if (isPicksWithActive(fastAndSlowPicks.picks)) {
                  picks = fastAndSlowPicks.picks.items;
                  activePick = fastAndSlowPicks.picks.active;
                } else {
                  picks = fastAndSlowPicks.picks;
                }
                let additionalPicks;
                let additionalActivePick = void 0;
                if (isPicksWithActive(awaitedAdditionalPicks)) {
                  additionalPicks = awaitedAdditionalPicks.items;
                  additionalActivePick = awaitedAdditionalPicks.active;
                } else {
                  additionalPicks = awaitedAdditionalPicks;
                }
                if (additionalPicks.length > 0 || !fastPicksApplied) {
                  let fallbackActivePick = void 0;
                  if (!activePick && !additionalActivePick) {
                    const fallbackActivePickCandidate = picker.activeItems[0];
                    if (fallbackActivePickCandidate && picks.indexOf(fallbackActivePickCandidate) !== -1) {
                      fallbackActivePick = fallbackActivePickCandidate;
                    }
                  }
                  applyPicks({
                    items: [...picks, ...additionalPicks],
                    active: activePick || additionalActivePick || fallbackActivePick
                  });
                }
              } finally {
                if (!picksToken.isCancellationRequested) {
                  picker.busy = false;
                }
                slowPicksApplied = true;
              }
            })()
          ]);
        };
        if (providedPicks === null) ;
        else if (isFastAndSlowPicks(providedPicks)) {
          await applyFastAndSlowPicks(providedPicks);
        } else if (!(providedPicks instanceof Promise)) {
          applyPicks(providedPicks);
        } else {
          picker.busy = true;
          try {
            const awaitedPicks = await providedPicks;
            if (picksToken.isCancellationRequested) {
              return;
            }
            if (isFastAndSlowPicks(awaitedPicks)) {
              await applyFastAndSlowPicks(awaitedPicks);
            } else {
              applyPicks(awaitedPicks);
            }
          } finally {
            if (!picksToken.isCancellationRequested) {
              picker.busy = false;
            }
          }
        }
      };
      disposables.add(picker.onDidChangeValue(() => updatePickerItems()));
      updatePickerItems();
      disposables.add(picker.onDidAccept((event) => {
        if (runOptions?.handleAccept) {
          if (!event.inBackground) {
            picker.hide();
          }
          runOptions.handleAccept?.(picker.activeItems[0], event.inBackground);
          return;
        }
        const [item] = picker.selectedItems;
        if (typeof item?.accept === "function") {
          if (!event.inBackground) {
            picker.hide();
          }
          item.accept(picker.keyMods, event);
        }
      }));
      const buttonTrigger = async (button, item) => {
        if (typeof item.trigger !== "function") {
          return;
        }
        const buttonIndex = item.buttons?.indexOf(button) ?? -1;
        if (buttonIndex >= 0) {
          const result = item.trigger(buttonIndex, picker.keyMods);
          const action = typeof result === "number" ? result : await result;
          if (token.isCancellationRequested) {
            return;
          }
          switch (action) {
            case TriggerAction.NO_ACTION:
              break;
            case TriggerAction.CLOSE_PICKER:
              picker.hide();
              break;
            case TriggerAction.REFRESH_PICKER:
              updatePickerItems();
              break;
            case TriggerAction.REMOVE_ITEM: {
              const index = picker.items.indexOf(item);
              if (index !== -1) {
                const items = picker.items.slice();
                const removed = items.splice(index, 1);
                const activeItems = picker.activeItems.filter((activeItem) => activeItem !== removed[0]);
                const keepScrollPositionBefore = picker.keepScrollPosition;
                picker.keepScrollPosition = true;
                picker.items = items;
                if (activeItems) {
                  picker.activeItems = activeItems;
                }
                picker.keepScrollPosition = keepScrollPositionBefore;
              }
              break;
            }
          }
        }
      };
      disposables.add(picker.onDidTriggerItemButton(({ button, item }) => buttonTrigger(button, item)));
      disposables.add(picker.onDidTriggerSeparatorButton(({ button, separator: separator2 }) => buttonTrigger(button, separator2)));
      return disposables;
    }
  }
  new LRUCache(1e4);
  const nfdCache = new LRUCache(1e4);
  function normalizeNFD(str) {
    return normalize(str, "NFD", nfdCache);
  }
  const nonAsciiCharactersPattern = /[^\u0000-\u0080]/;
  function normalize(str, form, normalizedCache) {
    if (!str) {
      return str;
    }
    const cached = normalizedCache.get(str);
    if (cached) {
      return cached;
    }
    let res;
    if (nonAsciiCharactersPattern.test(str)) {
      res = str.normalize(form);
    } else {
      res = str;
    }
    normalizedCache.set(str, res);
    return res;
  }
  const removeAccents = /* @__PURE__ */ (function() {
    const regex = /[\u0300-\u036f]/g;
    return function(str) {
      return normalizeNFD(str).replace(regex, "");
    };
  })();
  var __decorate$y = 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$x = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  var AbstractCommandsQuickAccessProvider_1, CommandsHistory_1;
  let AbstractCommandsQuickAccessProvider = (_Ka = class extends PickerQuickAccessProvider {
    constructor(options, instantiationService, keybindingService, commandService, telemetryService, dialogService) {
      super(AbstractCommandsQuickAccessProvider_1.PREFIX, options);
      this.keybindingService = keybindingService;
      this.commandService = commandService;
      this.telemetryService = telemetryService;
      this.dialogService = dialogService;
      this.commandsHistory = this._register(instantiationService.createInstance(CommandsHistory));
      this.options = options;
    }
    async _getPicks(filter, _disposables, token, runOptions) {
      const allCommandPicks = await this.getCommandPicks(token);
      if (token.isCancellationRequested) {
        return [];
      }
      const runTfidf = createSingleCallFunction(() => {
        const tfidf = new TfIdfCalculator();
        tfidf.updateDocuments(allCommandPicks.map((commandPick) => ({
          key: commandPick.commandId,
          textChunks: [this.getTfIdfChunk(commandPick)]
        })));
        const result = tfidf.calculateScores(filter, token);
        return normalizeTfIdfScores(result).filter((score2) => score2.score > AbstractCommandsQuickAccessProvider_1.TFIDF_THRESHOLD).slice(0, AbstractCommandsQuickAccessProvider_1.TFIDF_MAX_RESULTS);
      });
      const noAccentsFilter = this.normalizeForFiltering(filter);
      const filteredCommandPicks = [];
      for (const commandPick of allCommandPicks) {
        commandPick.labelNoAccents ??= this.normalizeForFiltering(commandPick.label);
        const labelHighlights = AbstractCommandsQuickAccessProvider_1.WORD_FILTER(noAccentsFilter, commandPick.labelNoAccents) ?? void 0;
        let aliasHighlights;
        if (commandPick.commandAlias) {
          commandPick.aliasNoAccents ??= this.normalizeForFiltering(commandPick.commandAlias);
          aliasHighlights = AbstractCommandsQuickAccessProvider_1.WORD_FILTER(noAccentsFilter, commandPick.aliasNoAccents) ?? void 0;
        }
        if (labelHighlights || aliasHighlights) {
          commandPick.highlights = {
            label: labelHighlights,
            detail: this.options.showAlias ? aliasHighlights : void 0
          };
          filteredCommandPicks.push(commandPick);
        } else if (filter === commandPick.commandId) {
          filteredCommandPicks.push(commandPick);
        } else if (filter.length >= 3) {
          const tfidf = runTfidf();
          if (token.isCancellationRequested) {
            return [];
          }
          const tfidfScore = tfidf.find((score2) => score2.key === commandPick.commandId);
          if (tfidfScore) {
            commandPick.tfIdfScore = tfidfScore.score;
            filteredCommandPicks.push(commandPick);
          }
        }
      }
      const mapLabelToCommand = /* @__PURE__ */ new Map();
      for (const commandPick of filteredCommandPicks) {
        const existingCommandForLabel = mapLabelToCommand.get(commandPick.label);
        if (existingCommandForLabel) {
          commandPick.description = commandPick.commandId;
          existingCommandForLabel.description = existingCommandForLabel.commandId;
        } else {
          mapLabelToCommand.set(commandPick.label, commandPick);
        }
      }
      filteredCommandPicks.sort((commandPickA, commandPickB) => {
        if (commandPickA.tfIdfScore && commandPickB.tfIdfScore) {
          if (commandPickA.tfIdfScore === commandPickB.tfIdfScore) {
            return commandPickA.label.localeCompare(commandPickB.label);
          }
          return commandPickB.tfIdfScore - commandPickA.tfIdfScore;
        } else if (commandPickA.tfIdfScore) {
          return 1;
        } else if (commandPickB.tfIdfScore) {
          return -1;
        }
        const commandACounter = this.commandsHistory.peek(commandPickA.commandId);
        const commandBCounter = this.commandsHistory.peek(commandPickB.commandId);
        if (commandACounter && commandBCounter) {
          return commandACounter > commandBCounter ? -1 : 1;
        }
        if (commandACounter) {
          return -1;
        }
        if (commandBCounter) {
          return 1;
        }
        if (this.options.suggestedCommandIds) {
          const commandASuggestion = this.options.suggestedCommandIds.has(commandPickA.commandId);
          const commandBSuggestion = this.options.suggestedCommandIds.has(commandPickB.commandId);
          if (commandASuggestion && commandBSuggestion) {
            return 0;
          }
          if (commandASuggestion) {
            return -1;
          }
          if (commandBSuggestion) {
            return 1;
          }
        }
        const isDeveloperA = commandPickA.commandCategory === Categories.Developer.value;
        const isDeveloperB = commandPickB.commandCategory === Categories.Developer.value;
        if (isDeveloperA && !isDeveloperB) {
          return 1;
        }
        if (!isDeveloperA && isDeveloperB) {
          return -1;
        }
        return commandPickA.label.localeCompare(commandPickB.label);
      });
      const commandPicks = [];
      let addOtherSeparator = false;
      let addSuggestedSeparator = true;
      let addCommonlyUsedSeparator = !!this.options.suggestedCommandIds;
      for (let i2 = 0; i2 < filteredCommandPicks.length; i2++) {
        const commandPick = filteredCommandPicks[i2];
        if (i2 === 0 && this.commandsHistory.peek(commandPick.commandId)) {
          commandPicks.push({ type: "separator", label: localize(1740, "recently used") });
          addOtherSeparator = true;
        }
        if (addSuggestedSeparator && commandPick.tfIdfScore !== void 0) {
          commandPicks.push({ type: "separator", label: localize(1741, "similar commands") });
          addSuggestedSeparator = false;
        }
        if (addCommonlyUsedSeparator && commandPick.tfIdfScore === void 0 && !this.commandsHistory.peek(commandPick.commandId) && this.options.suggestedCommandIds?.has(commandPick.commandId)) {
          commandPicks.push({ type: "separator", label: localize(1742, "commonly used") });
          addOtherSeparator = true;
          addCommonlyUsedSeparator = false;
        }
        if (addOtherSeparator && commandPick.tfIdfScore === void 0 && !this.commandsHistory.peek(commandPick.commandId) && !this.options.suggestedCommandIds?.has(commandPick.commandId)) {
          commandPicks.push({ type: "separator", label: localize(1743, "other commands") });
          addOtherSeparator = false;
        }
        commandPicks.push(this.toCommandPick(commandPick, runOptions));
      }
      if (!this.hasAdditionalCommandPicks(filter, token)) {
        return commandPicks;
      }
      return {
        picks: commandPicks,
        additionalPicks: (async () => {
          const additionalCommandPicks = await this.getAdditionalCommandPicks(allCommandPicks, filteredCommandPicks, filter, token);
          if (token.isCancellationRequested) {
            return [];
          }
          const commandPicks2 = additionalCommandPicks.map((commandPick) => this.toCommandPick(commandPick, runOptions));
          if (addSuggestedSeparator && commandPicks2[0]?.type !== "separator") {
            commandPicks2.unshift({ type: "separator", label: localize(1744, "similar commands") });
          }
          return commandPicks2;
        })()
      };
    }
    toCommandPick(commandPick, runOptions) {
      if (commandPick.type === "separator") {
        return commandPick;
      }
      const keybinding = this.keybindingService.lookupKeybinding(commandPick.commandId);
      const ariaLabel = keybinding ? localize(1745, "{0}, {1}", commandPick.label, keybinding.getAriaLabel()) : commandPick.label;
      return {
        ...commandPick,
        ariaLabel,
        detail: this.options.showAlias && commandPick.commandAlias !== commandPick.label ? commandPick.commandAlias : void 0,
        keybinding,
        accept: async () => {
          this.commandsHistory.push(commandPick.commandId);
          this.telemetryService.publicLog2("workbenchActionExecuted", {
            id: commandPick.commandId,
            from: runOptions?.from ?? "quick open"
          });
          try {
            commandPick.args?.length ? await this.commandService.executeCommand(commandPick.commandId, ...commandPick.args) : await this.commandService.executeCommand(commandPick.commandId);
          } catch (error) {
            if (!isCancellationError(error)) {
              this.dialogService.error(localize(1746, "Command '{0}' resulted in an error", commandPick.label), toErrorMessage(error));
            }
          }
        }
      };
    }
    // TF-IDF string to be indexed
    getTfIdfChunk({ label, commandAlias, commandDescription }) {
      let chunk = label;
      if (commandAlias && commandAlias !== label) {
        chunk += ` - ${commandAlias}`;
      }
      if (commandDescription && commandDescription.value !== label) {
        chunk += ` - ${commandDescription.value === commandDescription.original ? commandDescription.value : `${commandDescription.value} (${commandDescription.original})`}`;
      }
      return chunk;
    }
    /**
     * Normalizes a string for filtering by removing accents, but only if
     * the result has the same length, otherwise returns the original string.
     */
    normalizeForFiltering(value) {
      const withoutAccents = removeAccents(value);
      if (withoutAccents.length !== value.length) {
        this.telemetryService.publicLog2("QuickAccess:FilterLengthMismatch", {
          originalLength: value.length,
          normalizedLength: withoutAccents.length
        });
        return value;
      } else {
        return withoutAccents;
      }
    }
  }, AbstractCommandsQuickAccessProvider_1 = _Ka, _Ka.PREFIX = ">", _Ka.TFIDF_THRESHOLD = 0.5, _Ka.TFIDF_MAX_RESULTS = 5, _Ka.WORD_FILTER = or(matchesPrefix, matchesWords, matchesContiguousSubString), _Ka);
  AbstractCommandsQuickAccessProvider = AbstractCommandsQuickAccessProvider_1 = __decorate$y([
    __param$x(1, IInstantiationService),
    __param$x(2, IKeybindingService),
    __param$x(3, ICommandService),
    __param$x(4, ITelemetryService),
    __param$x(5, IDialogService)
  ], AbstractCommandsQuickAccessProvider);
  let CommandsHistory = (_La = class extends Disposable {
    constructor(storageService, configurationService, logService) {
      super();
      this.storageService = storageService;
      this.configurationService = configurationService;
      this.logService = logService;
      this.configuredCommandsHistoryLength = 0;
      this.updateConfiguration();
      this.load();
      this.registerListeners();
    }
    registerListeners() {
      this._register(this.configurationService.onDidChangeConfiguration((e) => this.updateConfiguration(e)));
      this._register(this.storageService.onWillSaveState((e) => {
        if (e.reason === WillSaveStateReason.SHUTDOWN) {
          this.saveState();
        }
      }));
    }
    updateConfiguration(e) {
      if (e && !e.affectsConfiguration("workbench.commandPalette.history")) {
        return;
      }
      this.configuredCommandsHistoryLength = CommandsHistory_1.getConfiguredCommandHistoryLength(this.configurationService);
      if (CommandsHistory_1.cache && CommandsHistory_1.cache.limit !== this.configuredCommandsHistoryLength) {
        CommandsHistory_1.cache.limit = this.configuredCommandsHistoryLength;
        CommandsHistory_1.hasChanges = true;
      }
    }
    load() {
      const raw = this.storageService.get(
        CommandsHistory_1.PREF_KEY_CACHE,
        0
        /* StorageScope.PROFILE */
      );
      let serializedCache;
      if (raw) {
        try {
          serializedCache = JSON.parse(raw);
        } catch (error) {
          this.logService.error(`[CommandsHistory] invalid data: ${error}`);
        }
      }
      const cache = CommandsHistory_1.cache = new LRUCache(this.configuredCommandsHistoryLength, 1);
      if (serializedCache) {
        let entries2;
        if (serializedCache.usesLRU) {
          entries2 = serializedCache.entries;
        } else {
          entries2 = serializedCache.entries.sort((a, b) => a.value - b.value);
        }
        entries2.forEach((entry) => cache.set(entry.key, entry.value));
      }
      CommandsHistory_1.counter = this.storageService.getNumber(CommandsHistory_1.PREF_KEY_COUNTER, 0, CommandsHistory_1.counter);
    }
    push(commandId) {
      if (!CommandsHistory_1.cache) {
        return;
      }
      CommandsHistory_1.cache.set(commandId, CommandsHistory_1.counter++);
      CommandsHistory_1.hasChanges = true;
    }
    peek(commandId) {
      return CommandsHistory_1.cache?.peek(commandId);
    }
    saveState() {
      if (!CommandsHistory_1.cache) {
        return;
      }
      if (!CommandsHistory_1.hasChanges) {
        return;
      }
      const serializedCache = { usesLRU: true, entries: [] };
      CommandsHistory_1.cache.forEach((value, key) => serializedCache.entries.push({ key, value }));
      this.storageService.store(
        CommandsHistory_1.PREF_KEY_CACHE,
        JSON.stringify(serializedCache),
        0,
        0
        /* StorageTarget.USER */
      );
      this.storageService.store(
        CommandsHistory_1.PREF_KEY_COUNTER,
        CommandsHistory_1.counter,
        0,
        0
        /* StorageTarget.USER */
      );
      CommandsHistory_1.hasChanges = false;
    }
    static getConfiguredCommandHistoryLength(configurationService) {
      const config = configurationService.getValue();
      const configuredCommandHistoryLength = config.workbench?.commandPalette?.history;
      if (typeof configuredCommandHistoryLength === "number") {
        return configuredCommandHistoryLength;
      }
      return CommandsHistory_1.DEFAULT_COMMANDS_HISTORY_LENGTH;
    }
  }, CommandsHistory_1 = _La, _La.DEFAULT_COMMANDS_HISTORY_LENGTH = 50, _La.PREF_KEY_CACHE = "commandPalette.mru.cache", _La.PREF_KEY_COUNTER = "commandPalette.mru.counter", _La.counter = 1, _La.hasChanges = false, _La);
  CommandsHistory = CommandsHistory_1 = __decorate$y([
    __param$x(0, IStorageService),
    __param$x(1, IConfigurationService),
    __param$x(2, ILogService)
  ], CommandsHistory);
  class AbstractEditorCommandsQuickAccessProvider extends AbstractCommandsQuickAccessProvider {
    constructor(options, instantiationService, keybindingService, commandService, telemetryService, dialogService) {
      super(options, instantiationService, keybindingService, commandService, telemetryService, dialogService);
    }
    getCodeEditorCommandPicks() {
      const activeTextEditorControl = this.activeTextEditorControl;
      if (!activeTextEditorControl) {
        return [];
      }
      const editorCommandPicks = [];
      for (const editorAction of activeTextEditorControl.getSupportedActions()) {
        let commandDescription;
        if (editorAction.metadata?.description) {
          if (isLocalizedString(editorAction.metadata.description)) {
            commandDescription = editorAction.metadata.description;
          } else {
            commandDescription = { original: editorAction.metadata.description, value: editorAction.metadata.description };
          }
        }
        editorCommandPicks.push({
          commandId: editorAction.id,
          commandAlias: editorAction.alias,
          commandDescription,
          label: stripIcons(editorAction.label) || editorAction.id
        });
      }
      return editorCommandPicks;
    }
  }
  var __decorate$x = 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$w = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  let StandaloneCommandsQuickAccessProvider = class StandaloneCommandsQuickAccessProvider extends AbstractEditorCommandsQuickAccessProvider {
    get activeTextEditorControl() {
      return this.codeEditorService.getFocusedCodeEditor() ?? void 0;
    }
    constructor(instantiationService, codeEditorService, keybindingService, commandService, telemetryService, dialogService) {
      super({ showAlias: false }, instantiationService, keybindingService, commandService, telemetryService, dialogService);
      this.codeEditorService = codeEditorService;
    }
    async getCommandPicks() {
      return this.getCodeEditorCommandPicks();
    }
    hasAdditionalCommandPicks() {
      return false;
    }
    async getAdditionalCommandPicks() {
      return [];
    }
  };
  StandaloneCommandsQuickAccessProvider = __decorate$x([
    __param$w(0, IInstantiationService),
    __param$w(1, ICodeEditorService),
    __param$w(2, IKeybindingService),
    __param$w(3, ICommandService),
    __param$w(4, ITelemetryService),
    __param$w(5, IDialogService)
  ], StandaloneCommandsQuickAccessProvider);
  const _GotoLineAction = class _GotoLineAction extends EditorAction {
    constructor() {
      super({
        id: _GotoLineAction.ID,
        label: QuickCommandNLS.quickCommandActionLabel,
        alias: "Command Palette",
        precondition: void 0,
        kbOpts: {
          kbExpr: EditorContextKeys.focus,
          primary: 59,
          weight: 100
          /* KeybindingWeight.EditorContrib */
        },
        contextMenuOpts: {
          group: "z_commands",
          order: 1
        }
      });
    }
    run(accessor) {
      accessor.get(IQuickInputService).quickAccess.show(StandaloneCommandsQuickAccessProvider.PREFIX);
    }
  };
  _GotoLineAction.ID = "editor.action.quickCommand";
  let GotoLineAction = _GotoLineAction;
  registerEditorAction(GotoLineAction);
  Registry.as(Extensions.Quickaccess).registerQuickAccessProvider({
    ctor: StandaloneCommandsQuickAccessProvider,
    prefix: StandaloneCommandsQuickAccessProvider.PREFIX,
    helpEntries: [{ description: QuickCommandNLS.quickCommandHelp, commandId: GotoLineAction.ID }]
  });
  var __decorate$w = 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$v = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  let StandaloneReferencesController = class StandaloneReferencesController extends ReferencesController {
    constructor(editor2, contextKeyService, editorService, notificationService, instantiationService, storageService, configurationService) {
      super(true, editor2, contextKeyService, editorService, notificationService, instantiationService, storageService, configurationService);
    }
  };
  StandaloneReferencesController = __decorate$w([
    __param$v(1, IContextKeyService),
    __param$v(2, ICodeEditorService),
    __param$v(3, INotificationService),
    __param$v(4, IInstantiationService),
    __param$v(5, IStorageService),
    __param$v(6, IConfigurationService)
  ], StandaloneReferencesController);
  registerEditorContribution(
    ReferencesController.ID,
    StandaloneReferencesController,
    4
    /* EditorContributionInstantiation.Lazy */
  );
  class ParsedTokenThemeRule {
    constructor(token, index, fontStyle, foreground2, background) {
      this._parsedThemeRuleBrand = void 0;
      this.token = token;
      this.index = index;
      this.fontStyle = fontStyle;
      this.foreground = foreground2;
      this.background = background;
    }
  }
  function parseTokenTheme(source) {
    if (!source || !Array.isArray(source)) {
      return [];
    }
    const result = [];
    let resultLen = 0;
    for (let i2 = 0, len = source.length; i2 < len; i2++) {
      const entry = source[i2];
      let fontStyle = -1;
      if (typeof entry.fontStyle === "string") {
        fontStyle = 0;
        const segments = entry.fontStyle.split(" ");
        for (let j = 0, lenJ = segments.length; j < lenJ; j++) {
          const segment = segments[j];
          switch (segment) {
            case "italic":
              fontStyle = fontStyle | 1;
              break;
            case "bold":
              fontStyle = fontStyle | 2;
              break;
            case "underline":
              fontStyle = fontStyle | 4;
              break;
            case "strikethrough":
              fontStyle = fontStyle | 8;
              break;
          }
        }
      }
      let foreground2 = null;
      if (typeof entry.foreground === "string") {
        foreground2 = entry.foreground;
      }
      let background = null;
      if (typeof entry.background === "string") {
        background = entry.background;
      }
      result[resultLen++] = new ParsedTokenThemeRule(entry.token || "", i2, fontStyle, foreground2, background);
    }
    return result;
  }
  function resolveParsedTokenThemeRules(parsedThemeRules, customTokenColors) {
    parsedThemeRules.sort((a, b) => {
      const r = strcmp(a.token, b.token);
      if (r !== 0) {
        return r;
      }
      return a.index - b.index;
    });
    let defaultFontStyle = 0;
    let defaultForeground = "000000";
    let defaultBackground = "ffffff";
    while (parsedThemeRules.length >= 1 && parsedThemeRules[0].token === "") {
      const incomingDefaults = parsedThemeRules.shift();
      if (incomingDefaults.fontStyle !== -1) {
        defaultFontStyle = incomingDefaults.fontStyle;
      }
      if (incomingDefaults.foreground !== null) {
        defaultForeground = incomingDefaults.foreground;
      }
      if (incomingDefaults.background !== null) {
        defaultBackground = incomingDefaults.background;
      }
    }
    const colorMap = new ColorMap();
    for (const color of customTokenColors) {
      colorMap.getId(color);
    }
    const foregroundColorId = colorMap.getId(defaultForeground);
    const backgroundColorId = colorMap.getId(defaultBackground);
    const defaults = new ThemeTrieElementRule(defaultFontStyle, foregroundColorId, backgroundColorId);
    const root = new ThemeTrieElement(defaults);
    for (let i2 = 0, len = parsedThemeRules.length; i2 < len; i2++) {
      const rule = parsedThemeRules[i2];
      root.insert(rule.token, rule.fontStyle, colorMap.getId(rule.foreground), colorMap.getId(rule.background));
    }
    return new TokenTheme(colorMap, root);
  }
  const colorRegExp = /^#?([0-9A-Fa-f]{6})([0-9A-Fa-f]{2})?$/;
  class ColorMap {
    constructor() {
      this._lastColorId = 0;
      this._id2color = [];
      this._color2id = /* @__PURE__ */ new Map();
    }
    getId(color) {
      if (color === null) {
        return 0;
      }
      const match2 = color.match(colorRegExp);
      if (!match2) {
        throw new Error("Illegal value for token color: " + color);
      }
      color = match2[1].toUpperCase();
      let value = this._color2id.get(color);
      if (value) {
        return value;
      }
      value = ++this._lastColorId;
      this._color2id.set(color, value);
      this._id2color[value] = Color.fromHex("#" + color);
      return value;
    }
    getColorMap() {
      return this._id2color.slice(0);
    }
  }
  class TokenTheme {
    static createFromRawTokenTheme(source, customTokenColors) {
      return this.createFromParsedTokenTheme(parseTokenTheme(source), customTokenColors);
    }
    static createFromParsedTokenTheme(source, customTokenColors) {
      return resolveParsedTokenThemeRules(source, customTokenColors);
    }
    constructor(colorMap, root) {
      this._colorMap = colorMap;
      this._root = root;
      this._cache = /* @__PURE__ */ new Map();
    }
    getColorMap() {
      return this._colorMap.getColorMap();
    }
    _match(token) {
      return this._root.match(token);
    }
    match(languageId, token) {
      let result = this._cache.get(token);
      if (typeof result === "undefined") {
        const rule = this._match(token);
        const standardToken = toStandardTokenType(token);
        result = (rule.metadata | standardToken << 8) >>> 0;
        this._cache.set(token, result);
      }
      return (result | languageId << 0) >>> 0;
    }
  }
  const STANDARD_TOKEN_TYPE_REGEXP = /\b(comment|string|regex|regexp)\b/;
  function toStandardTokenType(tokenType) {
    const m = tokenType.match(STANDARD_TOKEN_TYPE_REGEXP);
    if (!m) {
      return 0;
    }
    switch (m[1]) {
      case "comment":
        return 1;
      case "string":
        return 2;
      case "regex":
        return 3;
      case "regexp":
        return 3;
    }
    throw new Error("Unexpected match for standard token type!");
  }
  function strcmp(a, b) {
    if (a < b) {
      return -1;
    }
    if (a > b) {
      return 1;
    }
    return 0;
  }
  class ThemeTrieElementRule {
    constructor(fontStyle, foreground2, background) {
      this._themeTrieElementRuleBrand = void 0;
      this._fontStyle = fontStyle;
      this._foreground = foreground2;
      this._background = background;
      this.metadata = (this._fontStyle << 11 | this._foreground << 15 | this._background << 24) >>> 0;
    }
    clone() {
      return new ThemeTrieElementRule(this._fontStyle, this._foreground, this._background);
    }
    acceptOverwrite(fontStyle, foreground2, background) {
      if (fontStyle !== -1) {
        this._fontStyle = fontStyle;
      }
      if (foreground2 !== 0) {
        this._foreground = foreground2;
      }
      if (background !== 0) {
        this._background = background;
      }
      this.metadata = (this._fontStyle << 11 | this._foreground << 15 | this._background << 24) >>> 0;
    }
  }
  class ThemeTrieElement {
    constructor(mainRule) {
      this._themeTrieElementBrand = void 0;
      this._mainRule = mainRule;
      this._children = /* @__PURE__ */ new Map();
    }
    match(token) {
      if (token === "") {
        return this._mainRule;
      }
      const dotIndex = token.indexOf(".");
      let head;
      let tail2;
      if (dotIndex === -1) {
        head = token;
        tail2 = "";
      } else {
        head = token.substring(0, dotIndex);
        tail2 = token.substring(dotIndex + 1);
      }
      const child = this._children.get(head);
      if (typeof child !== "undefined") {
        return child.match(tail2);
      }
      return this._mainRule;
    }
    insert(token, fontStyle, foreground2, background) {
      if (token === "") {
        this._mainRule.acceptOverwrite(fontStyle, foreground2, background);
        return;
      }
      const dotIndex = token.indexOf(".");
      let head;
      let tail2;
      if (dotIndex === -1) {
        head = token;
        tail2 = "";
      } else {
        head = token.substring(0, dotIndex);
        tail2 = token.substring(dotIndex + 1);
      }
      let child = this._children.get(head);
      if (typeof child === "undefined") {
        child = new ThemeTrieElement(this._mainRule.clone());
        this._children.set(head, child);
      }
      child.insert(tail2, fontStyle, foreground2, background);
    }
  }
  function generateTokensCSSForColorMap(colorMap) {
    const rules = [];
    for (let i2 = 1, len = colorMap.length; i2 < len; i2++) {
      const color = colorMap[i2];
      rules[i2] = `.mtk${i2} { color: ${color}; }`;
    }
    rules.push(".mtki { font-style: italic; }");
    rules.push(".mtkb { font-weight: bold; }");
    rules.push(".mtku { text-decoration: underline; text-underline-position: under; }");
    rules.push(".mtks { text-decoration: line-through; }");
    rules.push(".mtks.mtku { text-decoration: underline line-through; text-underline-position: under; }");
    return rules.join("\n");
  }
  const vs = {
    base: "vs",
    inherit: false,
    rules: [
      { token: "", foreground: "000000", background: "fffffe" },
      { token: "invalid", foreground: "cd3131" },
      { token: "emphasis", fontStyle: "italic" },
      { token: "strong", fontStyle: "bold" },
      { token: "variable", foreground: "001188" },
      { token: "variable.predefined", foreground: "4864AA" },
      { token: "constant", foreground: "dd0000" },
      { token: "comment", foreground: "008000" },
      { token: "number", foreground: "098658" },
      { token: "number.hex", foreground: "3030c0" },
      { token: "regexp", foreground: "800000" },
      { token: "annotation", foreground: "808080" },
      { token: "type", foreground: "008080" },
      { token: "delimiter", foreground: "000000" },
      { token: "delimiter.html", foreground: "383838" },
      { token: "delimiter.xml", foreground: "0000FF" },
      { token: "tag", foreground: "800000" },
      { token: "tag.id.pug", foreground: "4F76AC" },
      { token: "tag.class.pug", foreground: "4F76AC" },
      { token: "meta.scss", foreground: "800000" },
      { token: "metatag", foreground: "e00000" },
      { token: "metatag.content.html", foreground: "FF0000" },
      { token: "metatag.html", foreground: "808080" },
      { token: "metatag.xml", foreground: "808080" },
      { token: "metatag.php", fontStyle: "bold" },
      { token: "key", foreground: "863B00" },
      { token: "string.key.json", foreground: "A31515" },
      { token: "string.value.json", foreground: "0451A5" },
      { token: "attribute.name", foreground: "FF0000" },
      { token: "attribute.value", foreground: "0451A5" },
      { token: "attribute.value.number", foreground: "098658" },
      { token: "attribute.value.unit", foreground: "098658" },
      { token: "attribute.value.html", foreground: "0000FF" },
      { token: "attribute.value.xml", foreground: "0000FF" },
      { token: "string", foreground: "A31515" },
      { token: "string.html", foreground: "0000FF" },
      { token: "string.sql", foreground: "FF0000" },
      { token: "string.yaml", foreground: "0451A5" },
      { token: "keyword", foreground: "0000FF" },
      { token: "keyword.json", foreground: "0451A5" },
      { token: "keyword.flow", foreground: "AF00DB" },
      { token: "keyword.flow.scss", foreground: "0000FF" },
      { token: "operator.scss", foreground: "666666" },
      { token: "operator.sql", foreground: "778899" },
      { token: "operator.swift", foreground: "666666" },
      { token: "predefined.sql", foreground: "C700C7" }
    ],
    colors: {
      [editorBackground]: "#FFFFFE",
      [editorForeground]: "#000000",
      [editorInactiveSelection]: "#E5EBF1",
      [editorIndentGuide1]: "#D3D3D3",
      [editorActiveIndentGuide1]: "#939393",
      [editorSelectionHighlight]: "#ADD6FF4D"
    }
  };
  const vs_dark = {
    base: "vs-dark",
    inherit: false,
    rules: [
      { token: "", foreground: "D4D4D4", background: "1E1E1E" },
      { token: "invalid", foreground: "f44747" },
      { token: "emphasis", fontStyle: "italic" },
      { token: "strong", fontStyle: "bold" },
      { token: "variable", foreground: "74B0DF" },
      { token: "variable.predefined", foreground: "4864AA" },
      { token: "variable.parameter", foreground: "9CDCFE" },
      { token: "constant", foreground: "569CD6" },
      { token: "comment", foreground: "608B4E" },
      { token: "number", foreground: "B5CEA8" },
      { token: "number.hex", foreground: "5BB498" },
      { token: "regexp", foreground: "B46695" },
      { token: "annotation", foreground: "cc6666" },
      { token: "type", foreground: "3DC9B0" },
      { token: "delimiter", foreground: "DCDCDC" },
      { token: "delimiter.html", foreground: "808080" },
      { token: "delimiter.xml", foreground: "808080" },
      { token: "tag", foreground: "569CD6" },
      { token: "tag.id.pug", foreground: "4F76AC" },
      { token: "tag.class.pug", foreground: "4F76AC" },
      { token: "meta.scss", foreground: "A79873" },
      { token: "meta.tag", foreground: "CE9178" },
      { token: "metatag", foreground: "DD6A6F" },
      { token: "metatag.content.html", foreground: "9CDCFE" },
      { token: "metatag.html", foreground: "569CD6" },
      { token: "metatag.xml", foreground: "569CD6" },
      { token: "metatag.php", fontStyle: "bold" },
      { token: "key", foreground: "9CDCFE" },
      { token: "string.key.json", foreground: "9CDCFE" },
      { token: "string.value.json", foreground: "CE9178" },
      { token: "attribute.name", foreground: "9CDCFE" },
      { token: "attribute.value", foreground: "CE9178" },
      { token: "attribute.value.number.css", foreground: "B5CEA8" },
      { token: "attribute.value.unit.css", foreground: "B5CEA8" },
      { token: "attribute.value.hex.css", foreground: "D4D4D4" },
      { token: "string", foreground: "CE9178" },
      { token: "string.sql", foreground: "FF0000" },
      { token: "keyword", foreground: "569CD6" },
      { token: "keyword.flow", foreground: "C586C0" },
      { token: "keyword.json", foreground: "CE9178" },
      { token: "keyword.flow.scss", foreground: "569CD6" },
      { token: "operator.scss", foreground: "909090" },
      { token: "operator.sql", foreground: "778899" },
      { token: "operator.swift", foreground: "909090" },
      { token: "predefined.sql", foreground: "FF00FF" }
    ],
    colors: {
      [editorBackground]: "#1E1E1E",
      [editorForeground]: "#D4D4D4",
      [editorInactiveSelection]: "#3A3D41",
      [editorIndentGuide1]: "#404040",
      [editorActiveIndentGuide1]: "#707070",
      [editorSelectionHighlight]: "#ADD6FF26"
    }
  };
  const hc_black = {
    base: "hc-black",
    inherit: false,
    rules: [
      { token: "", foreground: "FFFFFF", background: "000000" },
      { token: "invalid", foreground: "f44747" },
      { token: "emphasis", fontStyle: "italic" },
      { token: "strong", fontStyle: "bold" },
      { token: "variable", foreground: "1AEBFF" },
      { token: "variable.parameter", foreground: "9CDCFE" },
      { token: "constant", foreground: "569CD6" },
      { token: "comment", foreground: "608B4E" },
      { token: "number", foreground: "FFFFFF" },
      { token: "regexp", foreground: "C0C0C0" },
      { token: "annotation", foreground: "569CD6" },
      { token: "type", foreground: "3DC9B0" },
      { token: "delimiter", foreground: "FFFF00" },
      { token: "delimiter.html", foreground: "FFFF00" },
      { token: "tag", foreground: "569CD6" },
      { token: "tag.id.pug", foreground: "4F76AC" },
      { token: "tag.class.pug", foreground: "4F76AC" },
      { token: "meta", foreground: "D4D4D4" },
      { token: "meta.tag", foreground: "CE9178" },
      { token: "metatag", foreground: "569CD6" },
      { token: "metatag.content.html", foreground: "1AEBFF" },
      { token: "metatag.html", foreground: "569CD6" },
      { token: "metatag.xml", foreground: "569CD6" },
      { token: "metatag.php", fontStyle: "bold" },
      { token: "key", foreground: "9CDCFE" },
      { token: "string.key", foreground: "9CDCFE" },
      { token: "string.value", foreground: "CE9178" },
      { token: "attribute.name", foreground: "569CD6" },
      { token: "attribute.value", foreground: "3FF23F" },
      { token: "string", foreground: "CE9178" },
      { token: "string.sql", foreground: "FF0000" },
      { token: "keyword", foreground: "569CD6" },
      { token: "keyword.flow", foreground: "C586C0" },
      { token: "operator.sql", foreground: "778899" },
      { token: "operator.swift", foreground: "909090" },
      { token: "predefined.sql", foreground: "FF00FF" }
    ],
    colors: {
      [editorBackground]: "#000000",
      [editorForeground]: "#FFFFFF",
      [editorIndentGuide1]: "#FFFFFF",
      [editorActiveIndentGuide1]: "#FFFFFF"
    }
  };
  const hc_light = {
    base: "hc-light",
    inherit: false,
    rules: [
      { token: "", foreground: "292929", background: "FFFFFF" },
      { token: "invalid", foreground: "B5200D" },
      { token: "emphasis", fontStyle: "italic" },
      { token: "strong", fontStyle: "bold" },
      { token: "variable", foreground: "264F70" },
      { token: "variable.predefined", foreground: "4864AA" },
      { token: "constant", foreground: "dd0000" },
      { token: "comment", foreground: "008000" },
      { token: "number", foreground: "098658" },
      { token: "number.hex", foreground: "3030c0" },
      { token: "regexp", foreground: "800000" },
      { token: "annotation", foreground: "808080" },
      { token: "type", foreground: "008080" },
      { token: "delimiter", foreground: "000000" },
      { token: "delimiter.html", foreground: "383838" },
      { token: "tag", foreground: "800000" },
      { token: "tag.id.pug", foreground: "4F76AC" },
      { token: "tag.class.pug", foreground: "4F76AC" },
      { token: "meta.scss", foreground: "800000" },
      { token: "metatag", foreground: "e00000" },
      { token: "metatag.content.html", foreground: "B5200D" },
      { token: "metatag.html", foreground: "808080" },
      { token: "metatag.xml", foreground: "808080" },
      { token: "metatag.php", fontStyle: "bold" },
      { token: "key", foreground: "863B00" },
      { token: "string.key.json", foreground: "A31515" },
      { token: "string.value.json", foreground: "0451A5" },
      { token: "attribute.name", foreground: "264F78" },
      { token: "attribute.value", foreground: "0451A5" },
      { token: "string", foreground: "A31515" },
      { token: "string.sql", foreground: "B5200D" },
      { token: "keyword", foreground: "0000FF" },
      { token: "keyword.flow", foreground: "AF00DB" },
      { token: "operator.sql", foreground: "778899" },
      { token: "operator.swift", foreground: "666666" },
      { token: "predefined.sql", foreground: "C700C7" }
    ],
    colors: {
      [editorBackground]: "#FFFFFF",
      [editorForeground]: "#292929",
      [editorIndentGuide1]: "#292929",
      [editorActiveIndentGuide1]: "#292929"
    }
  };
  function getIconsStyleSheet(themeService) {
    const disposable = new DisposableStore();
    const onDidChangeEmmiter = disposable.add(new Emitter$1());
    const iconRegistry2 = getIconRegistry();
    disposable.add(iconRegistry2.onDidChange(() => onDidChangeEmmiter.fire()));
    if (themeService) {
      disposable.add(themeService.onDidProductIconThemeChange(() => onDidChangeEmmiter.fire()));
    }
    return {
      dispose: () => disposable.dispose(),
      onDidChange: onDidChangeEmmiter.event,
      getCSS() {
        const productIconTheme = themeService ? themeService.getProductIconTheme() : new UnthemedProductIconTheme();
        const usedFontIds = {};
        const rules = new Builder();
        const rootAttribs = new Builder();
        for (const contribution of iconRegistry2.getIcons()) {
          const definition = productIconTheme.getIcon(contribution);
          if (!definition) {
            continue;
          }
          const fontContribution = definition.font;
          const fontFamilyVar = inline$1`--vscode-icon-${className(contribution.id)}-font-family`;
          const contentVar = inline$1`--vscode-icon-${className(contribution.id)}-content`;
          if (fontContribution) {
            usedFontIds[fontContribution.id] = fontContribution.definition;
            rootAttribs.push(inline$1`${fontFamilyVar}: ${stringValue(fontContribution.id)};`, inline$1`${contentVar}: ${stringValue(definition.fontCharacter)};`);
            rules.push(inline$1`.codicon-${className(contribution.id)}:before { content: ${stringValue(definition.fontCharacter)}; font-family: ${stringValue(fontContribution.id)}; }`);
          } else {
            rootAttribs.push(inline$1`${contentVar}: ${stringValue(definition.fontCharacter)}; ${fontFamilyVar}: 'codicon';`);
            rules.push(inline$1`.codicon-${className(contribution.id)}:before { content: ${stringValue(definition.fontCharacter)}; }`);
          }
        }
        for (const id in usedFontIds) {
          const definition = usedFontIds[id];
          const fontWeight = definition.weight ? inline$1`font-weight: ${identValue(definition.weight)};` : inline$1``;
          const fontStyle = definition.style ? inline$1`font-style: ${identValue(definition.style)};` : inline$1``;
          const src = new Builder();
          for (const l of definition.src) {
            src.push(inline$1`${asCSSUrl(l.location)} format(${stringValue(l.format)})`);
          }
          rules.push(inline$1`@font-face { src: ${src.join(", ")}; font-family: ${stringValue(id)};${fontWeight}${fontStyle} font-display: block; }`);
        }
        rules.push(inline$1`:root { ${rootAttribs.join(" ")} }`);
        return rules.join("\n");
      }
    };
  }
  class UnthemedProductIconTheme {
    getIcon(contribution) {
      const iconRegistry2 = getIconRegistry();
      let definition = contribution.defaults;
      while (ThemeIcon.isThemeIcon(definition)) {
        const c = iconRegistry2.getIcon(definition.id);
        if (!c) {
          return void 0;
        }
        definition = c.defaults;
      }
      return definition;
    }
  }
  const VS_LIGHT_THEME_NAME = "vs";
  const VS_DARK_THEME_NAME = "vs-dark";
  const HC_BLACK_THEME_NAME = "hc-black";
  const HC_LIGHT_THEME_NAME = "hc-light";
  const colorRegistry = Registry.as(Extensions$4.ColorContribution);
  const themingRegistry = Registry.as(Extensions$3.ThemingContribution);
  class StandaloneTheme {
    constructor(name, standaloneThemeData) {
      this.semanticHighlighting = false;
      this.themeData = standaloneThemeData;
      const base = standaloneThemeData.base;
      if (name.length > 0) {
        if (isBuiltinTheme(name)) {
          this.id = name;
        } else {
          this.id = base + " " + name;
        }
        this.themeName = name;
      } else {
        this.id = base;
        this.themeName = base;
      }
      this.colors = null;
      this.defaultColors = /* @__PURE__ */ Object.create(null);
      this._tokenTheme = null;
    }
    get base() {
      return this.themeData.base;
    }
    notifyBaseUpdated() {
      if (this.themeData.inherit) {
        this.colors = null;
        this._tokenTheme = null;
      }
    }
    getColors() {
      if (!this.colors) {
        const colors = /* @__PURE__ */ new Map();
        for (const id in this.themeData.colors) {
          colors.set(id, Color.fromHex(this.themeData.colors[id]));
        }
        if (this.themeData.inherit) {
          const baseData = getBuiltinRules(this.themeData.base);
          for (const id in baseData.colors) {
            if (!colors.has(id)) {
              colors.set(id, Color.fromHex(baseData.colors[id]));
            }
          }
        }
        this.colors = colors;
      }
      return this.colors;
    }
    getColor(colorId, useDefault) {
      const color = this.getColors().get(colorId);
      if (color) {
        return color;
      }
      if (useDefault !== false) {
        return this.getDefault(colorId);
      }
      return void 0;
    }
    getDefault(colorId) {
      let color = this.defaultColors[colorId];
      if (color) {
        return color;
      }
      color = colorRegistry.resolveDefaultColor(colorId, this);
      this.defaultColors[colorId] = color;
      return color;
    }
    defines(colorId) {
      return this.getColors().has(colorId);
    }
    get type() {
      switch (this.base) {
        case VS_LIGHT_THEME_NAME:
          return ColorScheme.LIGHT;
        case HC_BLACK_THEME_NAME:
          return ColorScheme.HIGH_CONTRAST_DARK;
        case HC_LIGHT_THEME_NAME:
          return ColorScheme.HIGH_CONTRAST_LIGHT;
        default:
          return ColorScheme.DARK;
      }
    }
    get tokenTheme() {
      if (!this._tokenTheme) {
        let rules = [];
        let encodedTokensColors = [];
        if (this.themeData.inherit) {
          const baseData = getBuiltinRules(this.themeData.base);
          rules = baseData.rules;
          if (baseData.encodedTokensColors) {
            encodedTokensColors = baseData.encodedTokensColors;
          }
        }
        const editorForeground2 = this.themeData.colors["editor.foreground"];
        const editorBackground2 = this.themeData.colors["editor.background"];
        if (editorForeground2 || editorBackground2) {
          const rule = { token: "" };
          if (editorForeground2) {
            rule.foreground = editorForeground2;
          }
          if (editorBackground2) {
            rule.background = editorBackground2;
          }
          rules.push(rule);
        }
        rules = rules.concat(this.themeData.rules);
        if (this.themeData.encodedTokensColors) {
          encodedTokensColors = this.themeData.encodedTokensColors;
        }
        this._tokenTheme = TokenTheme.createFromRawTokenTheme(rules, encodedTokensColors);
      }
      return this._tokenTheme;
    }
    getTokenStyleMetadata(type, modifiers, modelLanguage) {
      const style = this.tokenTheme._match([type].concat(modifiers).join("."));
      const metadata = style.metadata;
      const foreground2 = TokenMetadata.getForeground(metadata);
      const fontStyle = TokenMetadata.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 */
        )
      };
    }
    get tokenColorMap() {
      return [];
    }
  }
  function isBuiltinTheme(themeName) {
    return themeName === VS_LIGHT_THEME_NAME || themeName === VS_DARK_THEME_NAME || themeName === HC_BLACK_THEME_NAME || themeName === HC_LIGHT_THEME_NAME;
  }
  function getBuiltinRules(builtinTheme) {
    switch (builtinTheme) {
      case VS_LIGHT_THEME_NAME:
        return vs;
      case VS_DARK_THEME_NAME:
        return vs_dark;
      case HC_BLACK_THEME_NAME:
        return hc_black;
      case HC_LIGHT_THEME_NAME:
        return hc_light;
    }
  }
  function newBuiltInTheme(builtinTheme) {
    const themeData = getBuiltinRules(builtinTheme);
    return new StandaloneTheme(builtinTheme, themeData);
  }
  class StandaloneThemeService extends Disposable {
    constructor() {
      super();
      this._onColorThemeChange = this._register(new Emitter$1());
      this.onDidColorThemeChange = this._onColorThemeChange.event;
      this._onProductIconThemeChange = this._register(new Emitter$1());
      this.onDidProductIconThemeChange = this._onProductIconThemeChange.event;
      this._environment = /* @__PURE__ */ Object.create(null);
      this._builtInProductIconTheme = new UnthemedProductIconTheme();
      this._autoDetectHighContrast = true;
      this._knownThemes = /* @__PURE__ */ new Map();
      this._knownThemes.set(VS_LIGHT_THEME_NAME, newBuiltInTheme(VS_LIGHT_THEME_NAME));
      this._knownThemes.set(VS_DARK_THEME_NAME, newBuiltInTheme(VS_DARK_THEME_NAME));
      this._knownThemes.set(HC_BLACK_THEME_NAME, newBuiltInTheme(HC_BLACK_THEME_NAME));
      this._knownThemes.set(HC_LIGHT_THEME_NAME, newBuiltInTheme(HC_LIGHT_THEME_NAME));
      const iconsStyleSheet = this._register(getIconsStyleSheet(this));
      this._codiconCSS = iconsStyleSheet.getCSS();
      this._themeCSS = "";
      this._allCSS = `${this._codiconCSS}
${this._themeCSS}`;
      this._globalStyleElement = null;
      this._styleElements = [];
      this._colorMapOverride = null;
      this.setTheme(VS_LIGHT_THEME_NAME);
      this._onOSSchemeChanged();
      this._register(iconsStyleSheet.onDidChange(() => {
        this._codiconCSS = iconsStyleSheet.getCSS();
        this._updateCSS();
      }));
      addMatchMediaChangeListener(mainWindow, "(forced-colors: active)", () => {
        this._onOSSchemeChanged();
      });
    }
    registerEditorContainer(domNode) {
      if (isInShadowDOM(domNode)) {
        return this._registerShadowDomContainer(domNode);
      }
      return this._registerRegularEditorContainer();
    }
    _registerRegularEditorContainer() {
      if (!this._globalStyleElement) {
        this._globalStyleElement = createStyleSheet(void 0, (style) => {
          style.className = "monaco-colors";
          style.textContent = this._allCSS;
        });
        this._styleElements.push(this._globalStyleElement);
      }
      return Disposable.None;
    }
    _registerShadowDomContainer(domNode) {
      const styleElement = createStyleSheet(domNode, (style) => {
        style.className = "monaco-colors";
        style.textContent = this._allCSS;
      });
      this._styleElements.push(styleElement);
      return {
        dispose: () => {
          for (let i2 = 0; i2 < this._styleElements.length; i2++) {
            if (this._styleElements[i2] === styleElement) {
              this._styleElements.splice(i2, 1);
              return;
            }
          }
        }
      };
    }
    defineTheme(themeName, themeData) {
      if (!/^[a-z0-9\-]+$/i.test(themeName)) {
        throw new Error("Illegal theme name!");
      }
      if (!isBuiltinTheme(themeData.base) && !isBuiltinTheme(themeName)) {
        throw new Error("Illegal theme base!");
      }
      this._knownThemes.set(themeName, new StandaloneTheme(themeName, themeData));
      if (isBuiltinTheme(themeName)) {
        this._knownThemes.forEach((theme) => {
          if (theme.base === themeName) {
            theme.notifyBaseUpdated();
          }
        });
      }
      if (this._theme.themeName === themeName) {
        this.setTheme(themeName);
      }
    }
    getColorTheme() {
      return this._theme;
    }
    setColorMapOverride(colorMapOverride) {
      this._colorMapOverride = colorMapOverride;
      this._updateThemeOrColorMap();
    }
    setTheme(themeName) {
      let theme;
      if (this._knownThemes.has(themeName)) {
        theme = this._knownThemes.get(themeName);
      } else {
        theme = this._knownThemes.get(VS_LIGHT_THEME_NAME);
      }
      this._updateActualTheme(theme);
    }
    _updateActualTheme(desiredTheme) {
      if (!desiredTheme || this._theme === desiredTheme) {
        return;
      }
      this._theme = desiredTheme;
      this._updateThemeOrColorMap();
    }
    _onOSSchemeChanged() {
      if (this._autoDetectHighContrast) {
        const wantsHighContrast = mainWindow.matchMedia(`(forced-colors: active)`).matches;
        if (wantsHighContrast !== isHighContrast(this._theme.type)) {
          let newThemeName;
          if (isDark(this._theme.type)) {
            newThemeName = wantsHighContrast ? HC_BLACK_THEME_NAME : VS_DARK_THEME_NAME;
          } else {
            newThemeName = wantsHighContrast ? HC_LIGHT_THEME_NAME : VS_LIGHT_THEME_NAME;
          }
          this._updateActualTheme(this._knownThemes.get(newThemeName));
        }
      }
    }
    setAutoDetectHighContrast(autoDetectHighContrast) {
      this._autoDetectHighContrast = autoDetectHighContrast;
      this._onOSSchemeChanged();
    }
    _updateThemeOrColorMap() {
      const cssRules = [];
      const hasRule = {};
      const ruleCollector = {
        addRule: (rule) => {
          if (!hasRule[rule]) {
            cssRules.push(rule);
            hasRule[rule] = true;
          }
        }
      };
      themingRegistry.getThemingParticipants().forEach((p) => p(this._theme, ruleCollector, this._environment));
      const colorVariables = [];
      for (const item of colorRegistry.getColors()) {
        const color = this._theme.getColor(item.id, true);
        if (color) {
          colorVariables.push(`${asCssVariableName(item.id)}: ${color.toString()};`);
        }
      }
      ruleCollector.addRule(`.monaco-editor, .monaco-diff-editor, .monaco-component { ${colorVariables.join("\n")} }`);
      const colorMap = this._colorMapOverride || this._theme.tokenTheme.getColorMap();
      ruleCollector.addRule(generateTokensCSSForColorMap(colorMap));
      ruleCollector.addRule(`.monaco-editor, .monaco-diff-editor, .monaco-component { forced-color-adjust: none; }`);
      this._themeCSS = cssRules.join("\n");
      this._updateCSS();
      TokenizationRegistry.setColorMap(colorMap);
      this._onColorThemeChange.fire(this._theme);
    }
    _updateCSS() {
      this._allCSS = `${this._codiconCSS}
${this._themeCSS}`;
      this._styleElements.forEach((styleElement) => styleElement.textContent = this._allCSS);
    }
    getFileIconTheme() {
      return {
        hasFileIcons: false,
        hasFolderIcons: false,
        hidesExplorerArrows: false
      };
    }
    getProductIconTheme() {
      return this._builtInProductIconTheme;
    }
  }
  class ToggleHighContrast extends EditorAction {
    constructor() {
      super({
        id: "editor.action.toggleHighContrast",
        label: ToggleHighContrastNLS.toggleHighContrast,
        alias: "Toggle High Contrast Theme",
        precondition: void 0
      });
      this._originalThemeName = null;
    }
    run(accessor, editor2) {
      const standaloneThemeService = accessor.get(IStandaloneThemeService);
      const currentTheme = standaloneThemeService.getColorTheme();
      if (isHighContrast(currentTheme.type)) {
        standaloneThemeService.setTheme(this._originalThemeName || (isDark(currentTheme.type) ? VS_DARK_THEME_NAME : VS_LIGHT_THEME_NAME));
        this._originalThemeName = null;
      } else {
        standaloneThemeService.setTheme(isDark(currentTheme.type) ? HC_BLACK_THEME_NAME : HC_LIGHT_THEME_NAME);
        this._originalThemeName = currentTheme.themeName;
      }
    }
  }
  registerEditorAction(ToggleHighContrast);
  var AccessibilitySupport;
  (function(AccessibilitySupport2) {
    AccessibilitySupport2[AccessibilitySupport2["Unknown"] = 0] = "Unknown";
    AccessibilitySupport2[AccessibilitySupport2["Disabled"] = 1] = "Disabled";
    AccessibilitySupport2[AccessibilitySupport2["Enabled"] = 2] = "Enabled";
  })(AccessibilitySupport || (AccessibilitySupport = {}));
  var CodeActionTriggerType;
  (function(CodeActionTriggerType2) {
    CodeActionTriggerType2[CodeActionTriggerType2["Invoke"] = 1] = "Invoke";
    CodeActionTriggerType2[CodeActionTriggerType2["Auto"] = 2] = "Auto";
  })(CodeActionTriggerType || (CodeActionTriggerType = {}));
  var CompletionItemInsertTextRule;
  (function(CompletionItemInsertTextRule2) {
    CompletionItemInsertTextRule2[CompletionItemInsertTextRule2["None"] = 0] = "None";
    CompletionItemInsertTextRule2[CompletionItemInsertTextRule2["KeepWhitespace"] = 1] = "KeepWhitespace";
    CompletionItemInsertTextRule2[CompletionItemInsertTextRule2["InsertAsSnippet"] = 4] = "InsertAsSnippet";
  })(CompletionItemInsertTextRule || (CompletionItemInsertTextRule = {}));
  var CompletionItemKind;
  (function(CompletionItemKind2) {
    CompletionItemKind2[CompletionItemKind2["Method"] = 0] = "Method";
    CompletionItemKind2[CompletionItemKind2["Function"] = 1] = "Function";
    CompletionItemKind2[CompletionItemKind2["Constructor"] = 2] = "Constructor";
    CompletionItemKind2[CompletionItemKind2["Field"] = 3] = "Field";
    CompletionItemKind2[CompletionItemKind2["Variable"] = 4] = "Variable";
    CompletionItemKind2[CompletionItemKind2["Class"] = 5] = "Class";
    CompletionItemKind2[CompletionItemKind2["Struct"] = 6] = "Struct";
    CompletionItemKind2[CompletionItemKind2["Interface"] = 7] = "Interface";
    CompletionItemKind2[CompletionItemKind2["Module"] = 8] = "Module";
    CompletionItemKind2[CompletionItemKind2["Property"] = 9] = "Property";
    CompletionItemKind2[CompletionItemKind2["Event"] = 10] = "Event";
    CompletionItemKind2[CompletionItemKind2["Operator"] = 11] = "Operator";
    CompletionItemKind2[CompletionItemKind2["Unit"] = 12] = "Unit";
    CompletionItemKind2[CompletionItemKind2["Value"] = 13] = "Value";
    CompletionItemKind2[CompletionItemKind2["Constant"] = 14] = "Constant";
    CompletionItemKind2[CompletionItemKind2["Enum"] = 15] = "Enum";
    CompletionItemKind2[CompletionItemKind2["EnumMember"] = 16] = "EnumMember";
    CompletionItemKind2[CompletionItemKind2["Keyword"] = 17] = "Keyword";
    CompletionItemKind2[CompletionItemKind2["Text"] = 18] = "Text";
    CompletionItemKind2[CompletionItemKind2["Color"] = 19] = "Color";
    CompletionItemKind2[CompletionItemKind2["File"] = 20] = "File";
    CompletionItemKind2[CompletionItemKind2["Reference"] = 21] = "Reference";
    CompletionItemKind2[CompletionItemKind2["Customcolor"] = 22] = "Customcolor";
    CompletionItemKind2[CompletionItemKind2["Folder"] = 23] = "Folder";
    CompletionItemKind2[CompletionItemKind2["TypeParameter"] = 24] = "TypeParameter";
    CompletionItemKind2[CompletionItemKind2["User"] = 25] = "User";
    CompletionItemKind2[CompletionItemKind2["Issue"] = 26] = "Issue";
    CompletionItemKind2[CompletionItemKind2["Tool"] = 27] = "Tool";
    CompletionItemKind2[CompletionItemKind2["Snippet"] = 28] = "Snippet";
  })(CompletionItemKind || (CompletionItemKind = {}));
  var CompletionItemTag;
  (function(CompletionItemTag2) {
    CompletionItemTag2[CompletionItemTag2["Deprecated"] = 1] = "Deprecated";
  })(CompletionItemTag || (CompletionItemTag = {}));
  var CompletionTriggerKind;
  (function(CompletionTriggerKind2) {
    CompletionTriggerKind2[CompletionTriggerKind2["Invoke"] = 0] = "Invoke";
    CompletionTriggerKind2[CompletionTriggerKind2["TriggerCharacter"] = 1] = "TriggerCharacter";
    CompletionTriggerKind2[CompletionTriggerKind2["TriggerForIncompleteCompletions"] = 2] = "TriggerForIncompleteCompletions";
  })(CompletionTriggerKind || (CompletionTriggerKind = {}));
  var ContentWidgetPositionPreference;
  (function(ContentWidgetPositionPreference2) {
    ContentWidgetPositionPreference2[ContentWidgetPositionPreference2["EXACT"] = 0] = "EXACT";
    ContentWidgetPositionPreference2[ContentWidgetPositionPreference2["ABOVE"] = 1] = "ABOVE";
    ContentWidgetPositionPreference2[ContentWidgetPositionPreference2["BELOW"] = 2] = "BELOW";
  })(ContentWidgetPositionPreference || (ContentWidgetPositionPreference = {}));
  var CursorChangeReason;
  (function(CursorChangeReason2) {
    CursorChangeReason2[CursorChangeReason2["NotSet"] = 0] = "NotSet";
    CursorChangeReason2[CursorChangeReason2["ContentFlush"] = 1] = "ContentFlush";
    CursorChangeReason2[CursorChangeReason2["RecoverFromMarkers"] = 2] = "RecoverFromMarkers";
    CursorChangeReason2[CursorChangeReason2["Explicit"] = 3] = "Explicit";
    CursorChangeReason2[CursorChangeReason2["Paste"] = 4] = "Paste";
    CursorChangeReason2[CursorChangeReason2["Undo"] = 5] = "Undo";
    CursorChangeReason2[CursorChangeReason2["Redo"] = 6] = "Redo";
  })(CursorChangeReason || (CursorChangeReason = {}));
  var DefaultEndOfLine;
  (function(DefaultEndOfLine2) {
    DefaultEndOfLine2[DefaultEndOfLine2["LF"] = 1] = "LF";
    DefaultEndOfLine2[DefaultEndOfLine2["CRLF"] = 2] = "CRLF";
  })(DefaultEndOfLine || (DefaultEndOfLine = {}));
  var DocumentHighlightKind;
  (function(DocumentHighlightKind2) {
    DocumentHighlightKind2[DocumentHighlightKind2["Text"] = 0] = "Text";
    DocumentHighlightKind2[DocumentHighlightKind2["Read"] = 1] = "Read";
    DocumentHighlightKind2[DocumentHighlightKind2["Write"] = 2] = "Write";
  })(DocumentHighlightKind || (DocumentHighlightKind = {}));
  var EditorAutoIndentStrategy;
  (function(EditorAutoIndentStrategy2) {
    EditorAutoIndentStrategy2[EditorAutoIndentStrategy2["None"] = 0] = "None";
    EditorAutoIndentStrategy2[EditorAutoIndentStrategy2["Keep"] = 1] = "Keep";
    EditorAutoIndentStrategy2[EditorAutoIndentStrategy2["Brackets"] = 2] = "Brackets";
    EditorAutoIndentStrategy2[EditorAutoIndentStrategy2["Advanced"] = 3] = "Advanced";
    EditorAutoIndentStrategy2[EditorAutoIndentStrategy2["Full"] = 4] = "Full";
  })(EditorAutoIndentStrategy || (EditorAutoIndentStrategy = {}));
  var EditorOption;
  (function(EditorOption2) {
    EditorOption2[EditorOption2["acceptSuggestionOnCommitCharacter"] = 0] = "acceptSuggestionOnCommitCharacter";
    EditorOption2[EditorOption2["acceptSuggestionOnEnter"] = 1] = "acceptSuggestionOnEnter";
    EditorOption2[EditorOption2["accessibilitySupport"] = 2] = "accessibilitySupport";
    EditorOption2[EditorOption2["accessibilityPageSize"] = 3] = "accessibilityPageSize";
    EditorOption2[EditorOption2["allowOverflow"] = 4] = "allowOverflow";
    EditorOption2[EditorOption2["allowVariableLineHeights"] = 5] = "allowVariableLineHeights";
    EditorOption2[EditorOption2["allowVariableFonts"] = 6] = "allowVariableFonts";
    EditorOption2[EditorOption2["allowVariableFontsInAccessibilityMode"] = 7] = "allowVariableFontsInAccessibilityMode";
    EditorOption2[EditorOption2["ariaLabel"] = 8] = "ariaLabel";
    EditorOption2[EditorOption2["ariaRequired"] = 9] = "ariaRequired";
    EditorOption2[EditorOption2["autoClosingBrackets"] = 10] = "autoClosingBrackets";
    EditorOption2[EditorOption2["autoClosingComments"] = 11] = "autoClosingComments";
    EditorOption2[EditorOption2["screenReaderAnnounceInlineSuggestion"] = 12] = "screenReaderAnnounceInlineSuggestion";
    EditorOption2[EditorOption2["autoClosingDelete"] = 13] = "autoClosingDelete";
    EditorOption2[EditorOption2["autoClosingOvertype"] = 14] = "autoClosingOvertype";
    EditorOption2[EditorOption2["autoClosingQuotes"] = 15] = "autoClosingQuotes";
    EditorOption2[EditorOption2["autoIndent"] = 16] = "autoIndent";
    EditorOption2[EditorOption2["autoIndentOnPaste"] = 17] = "autoIndentOnPaste";
    EditorOption2[EditorOption2["autoIndentOnPasteWithinString"] = 18] = "autoIndentOnPasteWithinString";
    EditorOption2[EditorOption2["automaticLayout"] = 19] = "automaticLayout";
    EditorOption2[EditorOption2["autoSurround"] = 20] = "autoSurround";
    EditorOption2[EditorOption2["bracketPairColorization"] = 21] = "bracketPairColorization";
    EditorOption2[EditorOption2["guides"] = 22] = "guides";
    EditorOption2[EditorOption2["codeLens"] = 23] = "codeLens";
    EditorOption2[EditorOption2["codeLensFontFamily"] = 24] = "codeLensFontFamily";
    EditorOption2[EditorOption2["codeLensFontSize"] = 25] = "codeLensFontSize";
    EditorOption2[EditorOption2["colorDecorators"] = 26] = "colorDecorators";
    EditorOption2[EditorOption2["colorDecoratorsLimit"] = 27] = "colorDecoratorsLimit";
    EditorOption2[EditorOption2["columnSelection"] = 28] = "columnSelection";
    EditorOption2[EditorOption2["comments"] = 29] = "comments";
    EditorOption2[EditorOption2["contextmenu"] = 30] = "contextmenu";
    EditorOption2[EditorOption2["copyWithSyntaxHighlighting"] = 31] = "copyWithSyntaxHighlighting";
    EditorOption2[EditorOption2["cursorBlinking"] = 32] = "cursorBlinking";
    EditorOption2[EditorOption2["cursorSmoothCaretAnimation"] = 33] = "cursorSmoothCaretAnimation";
    EditorOption2[EditorOption2["cursorStyle"] = 34] = "cursorStyle";
    EditorOption2[EditorOption2["cursorSurroundingLines"] = 35] = "cursorSurroundingLines";
    EditorOption2[EditorOption2["cursorSurroundingLinesStyle"] = 36] = "cursorSurroundingLinesStyle";
    EditorOption2[EditorOption2["cursorWidth"] = 37] = "cursorWidth";
    EditorOption2[EditorOption2["cursorHeight"] = 38] = "cursorHeight";
    EditorOption2[EditorOption2["disableLayerHinting"] = 39] = "disableLayerHinting";
    EditorOption2[EditorOption2["disableMonospaceOptimizations"] = 40] = "disableMonospaceOptimizations";
    EditorOption2[EditorOption2["domReadOnly"] = 41] = "domReadOnly";
    EditorOption2[EditorOption2["dragAndDrop"] = 42] = "dragAndDrop";
    EditorOption2[EditorOption2["dropIntoEditor"] = 43] = "dropIntoEditor";
    EditorOption2[EditorOption2["editContext"] = 44] = "editContext";
    EditorOption2[EditorOption2["emptySelectionClipboard"] = 45] = "emptySelectionClipboard";
    EditorOption2[EditorOption2["experimentalGpuAcceleration"] = 46] = "experimentalGpuAcceleration";
    EditorOption2[EditorOption2["experimentalWhitespaceRendering"] = 47] = "experimentalWhitespaceRendering";
    EditorOption2[EditorOption2["extraEditorClassName"] = 48] = "extraEditorClassName";
    EditorOption2[EditorOption2["fastScrollSensitivity"] = 49] = "fastScrollSensitivity";
    EditorOption2[EditorOption2["find"] = 50] = "find";
    EditorOption2[EditorOption2["fixedOverflowWidgets"] = 51] = "fixedOverflowWidgets";
    EditorOption2[EditorOption2["folding"] = 52] = "folding";
    EditorOption2[EditorOption2["foldingStrategy"] = 53] = "foldingStrategy";
    EditorOption2[EditorOption2["foldingHighlight"] = 54] = "foldingHighlight";
    EditorOption2[EditorOption2["foldingImportsByDefault"] = 55] = "foldingImportsByDefault";
    EditorOption2[EditorOption2["foldingMaximumRegions"] = 56] = "foldingMaximumRegions";
    EditorOption2[EditorOption2["unfoldOnClickAfterEndOfLine"] = 57] = "unfoldOnClickAfterEndOfLine";
    EditorOption2[EditorOption2["fontFamily"] = 58] = "fontFamily";
    EditorOption2[EditorOption2["fontInfo"] = 59] = "fontInfo";
    EditorOption2[EditorOption2["fontLigatures"] = 60] = "fontLigatures";
    EditorOption2[EditorOption2["fontSize"] = 61] = "fontSize";
    EditorOption2[EditorOption2["fontWeight"] = 62] = "fontWeight";
    EditorOption2[EditorOption2["fontVariations"] = 63] = "fontVariations";
    EditorOption2[EditorOption2["formatOnPaste"] = 64] = "formatOnPaste";
    EditorOption2[EditorOption2["formatOnType"] = 65] = "formatOnType";
    EditorOption2[EditorOption2["glyphMargin"] = 66] = "glyphMargin";
    EditorOption2[EditorOption2["gotoLocation"] = 67] = "gotoLocation";
    EditorOption2[EditorOption2["hideCursorInOverviewRuler"] = 68] = "hideCursorInOverviewRuler";
    EditorOption2[EditorOption2["hover"] = 69] = "hover";
    EditorOption2[EditorOption2["inDiffEditor"] = 70] = "inDiffEditor";
    EditorOption2[EditorOption2["inlineSuggest"] = 71] = "inlineSuggest";
    EditorOption2[EditorOption2["letterSpacing"] = 72] = "letterSpacing";
    EditorOption2[EditorOption2["lightbulb"] = 73] = "lightbulb";
    EditorOption2[EditorOption2["lineDecorationsWidth"] = 74] = "lineDecorationsWidth";
    EditorOption2[EditorOption2["lineHeight"] = 75] = "lineHeight";
    EditorOption2[EditorOption2["lineNumbers"] = 76] = "lineNumbers";
    EditorOption2[EditorOption2["lineNumbersMinChars"] = 77] = "lineNumbersMinChars";
    EditorOption2[EditorOption2["linkedEditing"] = 78] = "linkedEditing";
    EditorOption2[EditorOption2["links"] = 79] = "links";
    EditorOption2[EditorOption2["matchBrackets"] = 80] = "matchBrackets";
    EditorOption2[EditorOption2["minimap"] = 81] = "minimap";
    EditorOption2[EditorOption2["mouseStyle"] = 82] = "mouseStyle";
    EditorOption2[EditorOption2["mouseWheelScrollSensitivity"] = 83] = "mouseWheelScrollSensitivity";
    EditorOption2[EditorOption2["mouseWheelZoom"] = 84] = "mouseWheelZoom";
    EditorOption2[EditorOption2["multiCursorMergeOverlapping"] = 85] = "multiCursorMergeOverlapping";
    EditorOption2[EditorOption2["multiCursorModifier"] = 86] = "multiCursorModifier";
    EditorOption2[EditorOption2["mouseMiddleClickAction"] = 87] = "mouseMiddleClickAction";
    EditorOption2[EditorOption2["multiCursorPaste"] = 88] = "multiCursorPaste";
    EditorOption2[EditorOption2["multiCursorLimit"] = 89] = "multiCursorLimit";
    EditorOption2[EditorOption2["occurrencesHighlight"] = 90] = "occurrencesHighlight";
    EditorOption2[EditorOption2["occurrencesHighlightDelay"] = 91] = "occurrencesHighlightDelay";
    EditorOption2[EditorOption2["overtypeCursorStyle"] = 92] = "overtypeCursorStyle";
    EditorOption2[EditorOption2["overtypeOnPaste"] = 93] = "overtypeOnPaste";
    EditorOption2[EditorOption2["overviewRulerBorder"] = 94] = "overviewRulerBorder";
    EditorOption2[EditorOption2["overviewRulerLanes"] = 95] = "overviewRulerLanes";
    EditorOption2[EditorOption2["padding"] = 96] = "padding";
    EditorOption2[EditorOption2["pasteAs"] = 97] = "pasteAs";
    EditorOption2[EditorOption2["parameterHints"] = 98] = "parameterHints";
    EditorOption2[EditorOption2["peekWidgetDefaultFocus"] = 99] = "peekWidgetDefaultFocus";
    EditorOption2[EditorOption2["placeholder"] = 100] = "placeholder";
    EditorOption2[EditorOption2["definitionLinkOpensInPeek"] = 101] = "definitionLinkOpensInPeek";
    EditorOption2[EditorOption2["quickSuggestions"] = 102] = "quickSuggestions";
    EditorOption2[EditorOption2["quickSuggestionsDelay"] = 103] = "quickSuggestionsDelay";
    EditorOption2[EditorOption2["readOnly"] = 104] = "readOnly";
    EditorOption2[EditorOption2["readOnlyMessage"] = 105] = "readOnlyMessage";
    EditorOption2[EditorOption2["renameOnType"] = 106] = "renameOnType";
    EditorOption2[EditorOption2["renderRichScreenReaderContent"] = 107] = "renderRichScreenReaderContent";
    EditorOption2[EditorOption2["renderControlCharacters"] = 108] = "renderControlCharacters";
    EditorOption2[EditorOption2["renderFinalNewline"] = 109] = "renderFinalNewline";
    EditorOption2[EditorOption2["renderLineHighlight"] = 110] = "renderLineHighlight";
    EditorOption2[EditorOption2["renderLineHighlightOnlyWhenFocus"] = 111] = "renderLineHighlightOnlyWhenFocus";
    EditorOption2[EditorOption2["renderValidationDecorations"] = 112] = "renderValidationDecorations";
    EditorOption2[EditorOption2["renderWhitespace"] = 113] = "renderWhitespace";
    EditorOption2[EditorOption2["revealHorizontalRightPadding"] = 114] = "revealHorizontalRightPadding";
    EditorOption2[EditorOption2["roundedSelection"] = 115] = "roundedSelection";
    EditorOption2[EditorOption2["rulers"] = 116] = "rulers";
    EditorOption2[EditorOption2["scrollbar"] = 117] = "scrollbar";
    EditorOption2[EditorOption2["scrollBeyondLastColumn"] = 118] = "scrollBeyondLastColumn";
    EditorOption2[EditorOption2["scrollBeyondLastLine"] = 119] = "scrollBeyondLastLine";
    EditorOption2[EditorOption2["scrollPredominantAxis"] = 120] = "scrollPredominantAxis";
    EditorOption2[EditorOption2["selectionClipboard"] = 121] = "selectionClipboard";
    EditorOption2[EditorOption2["selectionHighlight"] = 122] = "selectionHighlight";
    EditorOption2[EditorOption2["selectionHighlightMaxLength"] = 123] = "selectionHighlightMaxLength";
    EditorOption2[EditorOption2["selectionHighlightMultiline"] = 124] = "selectionHighlightMultiline";
    EditorOption2[EditorOption2["selectOnLineNumbers"] = 125] = "selectOnLineNumbers";
    EditorOption2[EditorOption2["showFoldingControls"] = 126] = "showFoldingControls";
    EditorOption2[EditorOption2["showUnused"] = 127] = "showUnused";
    EditorOption2[EditorOption2["snippetSuggestions"] = 128] = "snippetSuggestions";
    EditorOption2[EditorOption2["smartSelect"] = 129] = "smartSelect";
    EditorOption2[EditorOption2["smoothScrolling"] = 130] = "smoothScrolling";
    EditorOption2[EditorOption2["stickyScroll"] = 131] = "stickyScroll";
    EditorOption2[EditorOption2["stickyTabStops"] = 132] = "stickyTabStops";
    EditorOption2[EditorOption2["stopRenderingLineAfter"] = 133] = "stopRenderingLineAfter";
    EditorOption2[EditorOption2["suggest"] = 134] = "suggest";
    EditorOption2[EditorOption2["suggestFontSize"] = 135] = "suggestFontSize";
    EditorOption2[EditorOption2["suggestLineHeight"] = 136] = "suggestLineHeight";
    EditorOption2[EditorOption2["suggestOnTriggerCharacters"] = 137] = "suggestOnTriggerCharacters";
    EditorOption2[EditorOption2["suggestSelection"] = 138] = "suggestSelection";
    EditorOption2[EditorOption2["tabCompletion"] = 139] = "tabCompletion";
    EditorOption2[EditorOption2["tabIndex"] = 140] = "tabIndex";
    EditorOption2[EditorOption2["trimWhitespaceOnDelete"] = 141] = "trimWhitespaceOnDelete";
    EditorOption2[EditorOption2["unicodeHighlighting"] = 142] = "unicodeHighlighting";
    EditorOption2[EditorOption2["unusualLineTerminators"] = 143] = "unusualLineTerminators";
    EditorOption2[EditorOption2["useShadowDOM"] = 144] = "useShadowDOM";
    EditorOption2[EditorOption2["useTabStops"] = 145] = "useTabStops";
    EditorOption2[EditorOption2["wordBreak"] = 146] = "wordBreak";
    EditorOption2[EditorOption2["wordSegmenterLocales"] = 147] = "wordSegmenterLocales";
    EditorOption2[EditorOption2["wordSeparators"] = 148] = "wordSeparators";
    EditorOption2[EditorOption2["wordWrap"] = 149] = "wordWrap";
    EditorOption2[EditorOption2["wordWrapBreakAfterCharacters"] = 150] = "wordWrapBreakAfterCharacters";
    EditorOption2[EditorOption2["wordWrapBreakBeforeCharacters"] = 151] = "wordWrapBreakBeforeCharacters";
    EditorOption2[EditorOption2["wordWrapColumn"] = 152] = "wordWrapColumn";
    EditorOption2[EditorOption2["wordWrapOverride1"] = 153] = "wordWrapOverride1";
    EditorOption2[EditorOption2["wordWrapOverride2"] = 154] = "wordWrapOverride2";
    EditorOption2[EditorOption2["wrappingIndent"] = 155] = "wrappingIndent";
    EditorOption2[EditorOption2["wrappingStrategy"] = 156] = "wrappingStrategy";
    EditorOption2[EditorOption2["showDeprecated"] = 157] = "showDeprecated";
    EditorOption2[EditorOption2["inertialScroll"] = 158] = "inertialScroll";
    EditorOption2[EditorOption2["inlayHints"] = 159] = "inlayHints";
    EditorOption2[EditorOption2["wrapOnEscapedLineFeeds"] = 160] = "wrapOnEscapedLineFeeds";
    EditorOption2[EditorOption2["effectiveCursorStyle"] = 161] = "effectiveCursorStyle";
    EditorOption2[EditorOption2["editorClassName"] = 162] = "editorClassName";
    EditorOption2[EditorOption2["pixelRatio"] = 163] = "pixelRatio";
    EditorOption2[EditorOption2["tabFocusMode"] = 164] = "tabFocusMode";
    EditorOption2[EditorOption2["layoutInfo"] = 165] = "layoutInfo";
    EditorOption2[EditorOption2["wrappingInfo"] = 166] = "wrappingInfo";
    EditorOption2[EditorOption2["defaultColorDecorators"] = 167] = "defaultColorDecorators";
    EditorOption2[EditorOption2["colorDecoratorsActivatedOn"] = 168] = "colorDecoratorsActivatedOn";
    EditorOption2[EditorOption2["inlineCompletionsAccessibilityVerbose"] = 169] = "inlineCompletionsAccessibilityVerbose";
    EditorOption2[EditorOption2["effectiveEditContext"] = 170] = "effectiveEditContext";
    EditorOption2[EditorOption2["scrollOnMiddleClick"] = 171] = "scrollOnMiddleClick";
    EditorOption2[EditorOption2["effectiveAllowVariableFonts"] = 172] = "effectiveAllowVariableFonts";
  })(EditorOption || (EditorOption = {}));
  var EndOfLinePreference;
  (function(EndOfLinePreference2) {
    EndOfLinePreference2[EndOfLinePreference2["TextDefined"] = 0] = "TextDefined";
    EndOfLinePreference2[EndOfLinePreference2["LF"] = 1] = "LF";
    EndOfLinePreference2[EndOfLinePreference2["CRLF"] = 2] = "CRLF";
  })(EndOfLinePreference || (EndOfLinePreference = {}));
  var EndOfLineSequence;
  (function(EndOfLineSequence2) {
    EndOfLineSequence2[EndOfLineSequence2["LF"] = 0] = "LF";
    EndOfLineSequence2[EndOfLineSequence2["CRLF"] = 1] = "CRLF";
  })(EndOfLineSequence || (EndOfLineSequence = {}));
  var GlyphMarginLane;
  (function(GlyphMarginLane2) {
    GlyphMarginLane2[GlyphMarginLane2["Left"] = 1] = "Left";
    GlyphMarginLane2[GlyphMarginLane2["Center"] = 2] = "Center";
    GlyphMarginLane2[GlyphMarginLane2["Right"] = 3] = "Right";
  })(GlyphMarginLane || (GlyphMarginLane = {}));
  var HoverVerbosityAction;
  (function(HoverVerbosityAction2) {
    HoverVerbosityAction2[HoverVerbosityAction2["Increase"] = 0] = "Increase";
    HoverVerbosityAction2[HoverVerbosityAction2["Decrease"] = 1] = "Decrease";
  })(HoverVerbosityAction || (HoverVerbosityAction = {}));
  var IndentAction;
  (function(IndentAction2) {
    IndentAction2[IndentAction2["None"] = 0] = "None";
    IndentAction2[IndentAction2["Indent"] = 1] = "Indent";
    IndentAction2[IndentAction2["IndentOutdent"] = 2] = "IndentOutdent";
    IndentAction2[IndentAction2["Outdent"] = 3] = "Outdent";
  })(IndentAction || (IndentAction = {}));
  var InjectedTextCursorStops;
  (function(InjectedTextCursorStops2) {
    InjectedTextCursorStops2[InjectedTextCursorStops2["Both"] = 0] = "Both";
    InjectedTextCursorStops2[InjectedTextCursorStops2["Right"] = 1] = "Right";
    InjectedTextCursorStops2[InjectedTextCursorStops2["Left"] = 2] = "Left";
    InjectedTextCursorStops2[InjectedTextCursorStops2["None"] = 3] = "None";
  })(InjectedTextCursorStops || (InjectedTextCursorStops = {}));
  var InlayHintKind;
  (function(InlayHintKind2) {
    InlayHintKind2[InlayHintKind2["Type"] = 1] = "Type";
    InlayHintKind2[InlayHintKind2["Parameter"] = 2] = "Parameter";
  })(InlayHintKind || (InlayHintKind = {}));
  var InlineCompletionEndOfLifeReasonKind;
  (function(InlineCompletionEndOfLifeReasonKind2) {
    InlineCompletionEndOfLifeReasonKind2[InlineCompletionEndOfLifeReasonKind2["Accepted"] = 0] = "Accepted";
    InlineCompletionEndOfLifeReasonKind2[InlineCompletionEndOfLifeReasonKind2["Rejected"] = 1] = "Rejected";
    InlineCompletionEndOfLifeReasonKind2[InlineCompletionEndOfLifeReasonKind2["Ignored"] = 2] = "Ignored";
  })(InlineCompletionEndOfLifeReasonKind || (InlineCompletionEndOfLifeReasonKind = {}));
  var InlineCompletionHintStyle;
  (function(InlineCompletionHintStyle2) {
    InlineCompletionHintStyle2[InlineCompletionHintStyle2["Code"] = 1] = "Code";
    InlineCompletionHintStyle2[InlineCompletionHintStyle2["Label"] = 2] = "Label";
  })(InlineCompletionHintStyle || (InlineCompletionHintStyle = {}));
  var InlineCompletionTriggerKind;
  (function(InlineCompletionTriggerKind2) {
    InlineCompletionTriggerKind2[InlineCompletionTriggerKind2["Automatic"] = 0] = "Automatic";
    InlineCompletionTriggerKind2[InlineCompletionTriggerKind2["Explicit"] = 1] = "Explicit";
  })(InlineCompletionTriggerKind || (InlineCompletionTriggerKind = {}));
  var KeyCode$1;
  (function(KeyCode2) {
    KeyCode2[KeyCode2["DependsOnKbLayout"] = -1] = "DependsOnKbLayout";
    KeyCode2[KeyCode2["Unknown"] = 0] = "Unknown";
    KeyCode2[KeyCode2["Backspace"] = 1] = "Backspace";
    KeyCode2[KeyCode2["Tab"] = 2] = "Tab";
    KeyCode2[KeyCode2["Enter"] = 3] = "Enter";
    KeyCode2[KeyCode2["Shift"] = 4] = "Shift";
    KeyCode2[KeyCode2["Ctrl"] = 5] = "Ctrl";
    KeyCode2[KeyCode2["Alt"] = 6] = "Alt";
    KeyCode2[KeyCode2["PauseBreak"] = 7] = "PauseBreak";
    KeyCode2[KeyCode2["CapsLock"] = 8] = "CapsLock";
    KeyCode2[KeyCode2["Escape"] = 9] = "Escape";
    KeyCode2[KeyCode2["Space"] = 10] = "Space";
    KeyCode2[KeyCode2["PageUp"] = 11] = "PageUp";
    KeyCode2[KeyCode2["PageDown"] = 12] = "PageDown";
    KeyCode2[KeyCode2["End"] = 13] = "End";
    KeyCode2[KeyCode2["Home"] = 14] = "Home";
    KeyCode2[KeyCode2["LeftArrow"] = 15] = "LeftArrow";
    KeyCode2[KeyCode2["UpArrow"] = 16] = "UpArrow";
    KeyCode2[KeyCode2["RightArrow"] = 17] = "RightArrow";
    KeyCode2[KeyCode2["DownArrow"] = 18] = "DownArrow";
    KeyCode2[KeyCode2["Insert"] = 19] = "Insert";
    KeyCode2[KeyCode2["Delete"] = 20] = "Delete";
    KeyCode2[KeyCode2["Digit0"] = 21] = "Digit0";
    KeyCode2[KeyCode2["Digit1"] = 22] = "Digit1";
    KeyCode2[KeyCode2["Digit2"] = 23] = "Digit2";
    KeyCode2[KeyCode2["Digit3"] = 24] = "Digit3";
    KeyCode2[KeyCode2["Digit4"] = 25] = "Digit4";
    KeyCode2[KeyCode2["Digit5"] = 26] = "Digit5";
    KeyCode2[KeyCode2["Digit6"] = 27] = "Digit6";
    KeyCode2[KeyCode2["Digit7"] = 28] = "Digit7";
    KeyCode2[KeyCode2["Digit8"] = 29] = "Digit8";
    KeyCode2[KeyCode2["Digit9"] = 30] = "Digit9";
    KeyCode2[KeyCode2["KeyA"] = 31] = "KeyA";
    KeyCode2[KeyCode2["KeyB"] = 32] = "KeyB";
    KeyCode2[KeyCode2["KeyC"] = 33] = "KeyC";
    KeyCode2[KeyCode2["KeyD"] = 34] = "KeyD";
    KeyCode2[KeyCode2["KeyE"] = 35] = "KeyE";
    KeyCode2[KeyCode2["KeyF"] = 36] = "KeyF";
    KeyCode2[KeyCode2["KeyG"] = 37] = "KeyG";
    KeyCode2[KeyCode2["KeyH"] = 38] = "KeyH";
    KeyCode2[KeyCode2["KeyI"] = 39] = "KeyI";
    KeyCode2[KeyCode2["KeyJ"] = 40] = "KeyJ";
    KeyCode2[KeyCode2["KeyK"] = 41] = "KeyK";
    KeyCode2[KeyCode2["KeyL"] = 42] = "KeyL";
    KeyCode2[KeyCode2["KeyM"] = 43] = "KeyM";
    KeyCode2[KeyCode2["KeyN"] = 44] = "KeyN";
    KeyCode2[KeyCode2["KeyO"] = 45] = "KeyO";
    KeyCode2[KeyCode2["KeyP"] = 46] = "KeyP";
    KeyCode2[KeyCode2["KeyQ"] = 47] = "KeyQ";
    KeyCode2[KeyCode2["KeyR"] = 48] = "KeyR";
    KeyCode2[KeyCode2["KeyS"] = 49] = "KeyS";
    KeyCode2[KeyCode2["KeyT"] = 50] = "KeyT";
    KeyCode2[KeyCode2["KeyU"] = 51] = "KeyU";
    KeyCode2[KeyCode2["KeyV"] = 52] = "KeyV";
    KeyCode2[KeyCode2["KeyW"] = 53] = "KeyW";
    KeyCode2[KeyCode2["KeyX"] = 54] = "KeyX";
    KeyCode2[KeyCode2["KeyY"] = 55] = "KeyY";
    KeyCode2[KeyCode2["KeyZ"] = 56] = "KeyZ";
    KeyCode2[KeyCode2["Meta"] = 57] = "Meta";
    KeyCode2[KeyCode2["ContextMenu"] = 58] = "ContextMenu";
    KeyCode2[KeyCode2["F1"] = 59] = "F1";
    KeyCode2[KeyCode2["F2"] = 60] = "F2";
    KeyCode2[KeyCode2["F3"] = 61] = "F3";
    KeyCode2[KeyCode2["F4"] = 62] = "F4";
    KeyCode2[KeyCode2["F5"] = 63] = "F5";
    KeyCode2[KeyCode2["F6"] = 64] = "F6";
    KeyCode2[KeyCode2["F7"] = 65] = "F7";
    KeyCode2[KeyCode2["F8"] = 66] = "F8";
    KeyCode2[KeyCode2["F9"] = 67] = "F9";
    KeyCode2[KeyCode2["F10"] = 68] = "F10";
    KeyCode2[KeyCode2["F11"] = 69] = "F11";
    KeyCode2[KeyCode2["F12"] = 70] = "F12";
    KeyCode2[KeyCode2["F13"] = 71] = "F13";
    KeyCode2[KeyCode2["F14"] = 72] = "F14";
    KeyCode2[KeyCode2["F15"] = 73] = "F15";
    KeyCode2[KeyCode2["F16"] = 74] = "F16";
    KeyCode2[KeyCode2["F17"] = 75] = "F17";
    KeyCode2[KeyCode2["F18"] = 76] = "F18";
    KeyCode2[KeyCode2["F19"] = 77] = "F19";
    KeyCode2[KeyCode2["F20"] = 78] = "F20";
    KeyCode2[KeyCode2["F21"] = 79] = "F21";
    KeyCode2[KeyCode2["F22"] = 80] = "F22";
    KeyCode2[KeyCode2["F23"] = 81] = "F23";
    KeyCode2[KeyCode2["F24"] = 82] = "F24";
    KeyCode2[KeyCode2["NumLock"] = 83] = "NumLock";
    KeyCode2[KeyCode2["ScrollLock"] = 84] = "ScrollLock";
    KeyCode2[KeyCode2["Semicolon"] = 85] = "Semicolon";
    KeyCode2[KeyCode2["Equal"] = 86] = "Equal";
    KeyCode2[KeyCode2["Comma"] = 87] = "Comma";
    KeyCode2[KeyCode2["Minus"] = 88] = "Minus";
    KeyCode2[KeyCode2["Period"] = 89] = "Period";
    KeyCode2[KeyCode2["Slash"] = 90] = "Slash";
    KeyCode2[KeyCode2["Backquote"] = 91] = "Backquote";
    KeyCode2[KeyCode2["BracketLeft"] = 92] = "BracketLeft";
    KeyCode2[KeyCode2["Backslash"] = 93] = "Backslash";
    KeyCode2[KeyCode2["BracketRight"] = 94] = "BracketRight";
    KeyCode2[KeyCode2["Quote"] = 95] = "Quote";
    KeyCode2[KeyCode2["OEM_8"] = 96] = "OEM_8";
    KeyCode2[KeyCode2["IntlBackslash"] = 97] = "IntlBackslash";
    KeyCode2[KeyCode2["Numpad0"] = 98] = "Numpad0";
    KeyCode2[KeyCode2["Numpad1"] = 99] = "Numpad1";
    KeyCode2[KeyCode2["Numpad2"] = 100] = "Numpad2";
    KeyCode2[KeyCode2["Numpad3"] = 101] = "Numpad3";
    KeyCode2[KeyCode2["Numpad4"] = 102] = "Numpad4";
    KeyCode2[KeyCode2["Numpad5"] = 103] = "Numpad5";
    KeyCode2[KeyCode2["Numpad6"] = 104] = "Numpad6";
    KeyCode2[KeyCode2["Numpad7"] = 105] = "Numpad7";
    KeyCode2[KeyCode2["Numpad8"] = 106] = "Numpad8";
    KeyCode2[KeyCode2["Numpad9"] = 107] = "Numpad9";
    KeyCode2[KeyCode2["NumpadMultiply"] = 108] = "NumpadMultiply";
    KeyCode2[KeyCode2["NumpadAdd"] = 109] = "NumpadAdd";
    KeyCode2[KeyCode2["NUMPAD_SEPARATOR"] = 110] = "NUMPAD_SEPARATOR";
    KeyCode2[KeyCode2["NumpadSubtract"] = 111] = "NumpadSubtract";
    KeyCode2[KeyCode2["NumpadDecimal"] = 112] = "NumpadDecimal";
    KeyCode2[KeyCode2["NumpadDivide"] = 113] = "NumpadDivide";
    KeyCode2[KeyCode2["KEY_IN_COMPOSITION"] = 114] = "KEY_IN_COMPOSITION";
    KeyCode2[KeyCode2["ABNT_C1"] = 115] = "ABNT_C1";
    KeyCode2[KeyCode2["ABNT_C2"] = 116] = "ABNT_C2";
    KeyCode2[KeyCode2["AudioVolumeMute"] = 117] = "AudioVolumeMute";
    KeyCode2[KeyCode2["AudioVolumeUp"] = 118] = "AudioVolumeUp";
    KeyCode2[KeyCode2["AudioVolumeDown"] = 119] = "AudioVolumeDown";
    KeyCode2[KeyCode2["BrowserSearch"] = 120] = "BrowserSearch";
    KeyCode2[KeyCode2["BrowserHome"] = 121] = "BrowserHome";
    KeyCode2[KeyCode2["BrowserBack"] = 122] = "BrowserBack";
    KeyCode2[KeyCode2["BrowserForward"] = 123] = "BrowserForward";
    KeyCode2[KeyCode2["MediaTrackNext"] = 124] = "MediaTrackNext";
    KeyCode2[KeyCode2["MediaTrackPrevious"] = 125] = "MediaTrackPrevious";
    KeyCode2[KeyCode2["MediaStop"] = 126] = "MediaStop";
    KeyCode2[KeyCode2["MediaPlayPause"] = 127] = "MediaPlayPause";
    KeyCode2[KeyCode2["LaunchMediaPlayer"] = 128] = "LaunchMediaPlayer";
    KeyCode2[KeyCode2["LaunchMail"] = 129] = "LaunchMail";
    KeyCode2[KeyCode2["LaunchApp2"] = 130] = "LaunchApp2";
    KeyCode2[KeyCode2["Clear"] = 131] = "Clear";
    KeyCode2[KeyCode2["MAX_VALUE"] = 132] = "MAX_VALUE";
  })(KeyCode$1 || (KeyCode$1 = {}));
  var MarkerSeverity$1;
  (function(MarkerSeverity2) {
    MarkerSeverity2[MarkerSeverity2["Hint"] = 1] = "Hint";
    MarkerSeverity2[MarkerSeverity2["Info"] = 2] = "Info";
    MarkerSeverity2[MarkerSeverity2["Warning"] = 4] = "Warning";
    MarkerSeverity2[MarkerSeverity2["Error"] = 8] = "Error";
  })(MarkerSeverity$1 || (MarkerSeverity$1 = {}));
  var MarkerTag$1;
  (function(MarkerTag2) {
    MarkerTag2[MarkerTag2["Unnecessary"] = 1] = "Unnecessary";
    MarkerTag2[MarkerTag2["Deprecated"] = 2] = "Deprecated";
  })(MarkerTag$1 || (MarkerTag$1 = {}));
  var MinimapPosition;
  (function(MinimapPosition2) {
    MinimapPosition2[MinimapPosition2["Inline"] = 1] = "Inline";
    MinimapPosition2[MinimapPosition2["Gutter"] = 2] = "Gutter";
  })(MinimapPosition || (MinimapPosition = {}));
  var MinimapSectionHeaderStyle;
  (function(MinimapSectionHeaderStyle2) {
    MinimapSectionHeaderStyle2[MinimapSectionHeaderStyle2["Normal"] = 1] = "Normal";
    MinimapSectionHeaderStyle2[MinimapSectionHeaderStyle2["Underlined"] = 2] = "Underlined";
  })(MinimapSectionHeaderStyle || (MinimapSectionHeaderStyle = {}));
  var MouseTargetType;
  (function(MouseTargetType2) {
    MouseTargetType2[MouseTargetType2["UNKNOWN"] = 0] = "UNKNOWN";
    MouseTargetType2[MouseTargetType2["TEXTAREA"] = 1] = "TEXTAREA";
    MouseTargetType2[MouseTargetType2["GUTTER_GLYPH_MARGIN"] = 2] = "GUTTER_GLYPH_MARGIN";
    MouseTargetType2[MouseTargetType2["GUTTER_LINE_NUMBERS"] = 3] = "GUTTER_LINE_NUMBERS";
    MouseTargetType2[MouseTargetType2["GUTTER_LINE_DECORATIONS"] = 4] = "GUTTER_LINE_DECORATIONS";
    MouseTargetType2[MouseTargetType2["GUTTER_VIEW_ZONE"] = 5] = "GUTTER_VIEW_ZONE";
    MouseTargetType2[MouseTargetType2["CONTENT_TEXT"] = 6] = "CONTENT_TEXT";
    MouseTargetType2[MouseTargetType2["CONTENT_EMPTY"] = 7] = "CONTENT_EMPTY";
    MouseTargetType2[MouseTargetType2["CONTENT_VIEW_ZONE"] = 8] = "CONTENT_VIEW_ZONE";
    MouseTargetType2[MouseTargetType2["CONTENT_WIDGET"] = 9] = "CONTENT_WIDGET";
    MouseTargetType2[MouseTargetType2["OVERVIEW_RULER"] = 10] = "OVERVIEW_RULER";
    MouseTargetType2[MouseTargetType2["SCROLLBAR"] = 11] = "SCROLLBAR";
    MouseTargetType2[MouseTargetType2["OVERLAY_WIDGET"] = 12] = "OVERLAY_WIDGET";
    MouseTargetType2[MouseTargetType2["OUTSIDE_EDITOR"] = 13] = "OUTSIDE_EDITOR";
  })(MouseTargetType || (MouseTargetType = {}));
  var NewSymbolNameTag;
  (function(NewSymbolNameTag2) {
    NewSymbolNameTag2[NewSymbolNameTag2["AIGenerated"] = 1] = "AIGenerated";
  })(NewSymbolNameTag || (NewSymbolNameTag = {}));
  var NewSymbolNameTriggerKind;
  (function(NewSymbolNameTriggerKind2) {
    NewSymbolNameTriggerKind2[NewSymbolNameTriggerKind2["Invoke"] = 0] = "Invoke";
    NewSymbolNameTriggerKind2[NewSymbolNameTriggerKind2["Automatic"] = 1] = "Automatic";
  })(NewSymbolNameTriggerKind || (NewSymbolNameTriggerKind = {}));
  var OverlayWidgetPositionPreference;
  (function(OverlayWidgetPositionPreference2) {
    OverlayWidgetPositionPreference2[OverlayWidgetPositionPreference2["TOP_RIGHT_CORNER"] = 0] = "TOP_RIGHT_CORNER";
    OverlayWidgetPositionPreference2[OverlayWidgetPositionPreference2["BOTTOM_RIGHT_CORNER"] = 1] = "BOTTOM_RIGHT_CORNER";
    OverlayWidgetPositionPreference2[OverlayWidgetPositionPreference2["TOP_CENTER"] = 2] = "TOP_CENTER";
  })(OverlayWidgetPositionPreference || (OverlayWidgetPositionPreference = {}));
  var OverviewRulerLane;
  (function(OverviewRulerLane2) {
    OverviewRulerLane2[OverviewRulerLane2["Left"] = 1] = "Left";
    OverviewRulerLane2[OverviewRulerLane2["Center"] = 2] = "Center";
    OverviewRulerLane2[OverviewRulerLane2["Right"] = 4] = "Right";
    OverviewRulerLane2[OverviewRulerLane2["Full"] = 7] = "Full";
  })(OverviewRulerLane || (OverviewRulerLane = {}));
  var PartialAcceptTriggerKind;
  (function(PartialAcceptTriggerKind2) {
    PartialAcceptTriggerKind2[PartialAcceptTriggerKind2["Word"] = 0] = "Word";
    PartialAcceptTriggerKind2[PartialAcceptTriggerKind2["Line"] = 1] = "Line";
    PartialAcceptTriggerKind2[PartialAcceptTriggerKind2["Suggest"] = 2] = "Suggest";
  })(PartialAcceptTriggerKind || (PartialAcceptTriggerKind = {}));
  var PositionAffinity;
  (function(PositionAffinity2) {
    PositionAffinity2[PositionAffinity2["Left"] = 0] = "Left";
    PositionAffinity2[PositionAffinity2["Right"] = 1] = "Right";
    PositionAffinity2[PositionAffinity2["None"] = 2] = "None";
    PositionAffinity2[PositionAffinity2["LeftOfInjectedText"] = 3] = "LeftOfInjectedText";
    PositionAffinity2[PositionAffinity2["RightOfInjectedText"] = 4] = "RightOfInjectedText";
  })(PositionAffinity || (PositionAffinity = {}));
  var RenderLineNumbersType;
  (function(RenderLineNumbersType2) {
    RenderLineNumbersType2[RenderLineNumbersType2["Off"] = 0] = "Off";
    RenderLineNumbersType2[RenderLineNumbersType2["On"] = 1] = "On";
    RenderLineNumbersType2[RenderLineNumbersType2["Relative"] = 2] = "Relative";
    RenderLineNumbersType2[RenderLineNumbersType2["Interval"] = 3] = "Interval";
    RenderLineNumbersType2[RenderLineNumbersType2["Custom"] = 4] = "Custom";
  })(RenderLineNumbersType || (RenderLineNumbersType = {}));
  var RenderMinimap;
  (function(RenderMinimap2) {
    RenderMinimap2[RenderMinimap2["None"] = 0] = "None";
    RenderMinimap2[RenderMinimap2["Text"] = 1] = "Text";
    RenderMinimap2[RenderMinimap2["Blocks"] = 2] = "Blocks";
  })(RenderMinimap || (RenderMinimap = {}));
  var ScrollType;
  (function(ScrollType2) {
    ScrollType2[ScrollType2["Smooth"] = 0] = "Smooth";
    ScrollType2[ScrollType2["Immediate"] = 1] = "Immediate";
  })(ScrollType || (ScrollType = {}));
  var ScrollbarVisibility;
  (function(ScrollbarVisibility2) {
    ScrollbarVisibility2[ScrollbarVisibility2["Auto"] = 1] = "Auto";
    ScrollbarVisibility2[ScrollbarVisibility2["Hidden"] = 2] = "Hidden";
    ScrollbarVisibility2[ScrollbarVisibility2["Visible"] = 3] = "Visible";
  })(ScrollbarVisibility || (ScrollbarVisibility = {}));
  var SelectionDirection$1;
  (function(SelectionDirection2) {
    SelectionDirection2[SelectionDirection2["LTR"] = 0] = "LTR";
    SelectionDirection2[SelectionDirection2["RTL"] = 1] = "RTL";
  })(SelectionDirection$1 || (SelectionDirection$1 = {}));
  var ShowLightbulbIconMode;
  (function(ShowLightbulbIconMode2) {
    ShowLightbulbIconMode2["Off"] = "off";
    ShowLightbulbIconMode2["OnCode"] = "onCode";
    ShowLightbulbIconMode2["On"] = "on";
  })(ShowLightbulbIconMode || (ShowLightbulbIconMode = {}));
  var SignatureHelpTriggerKind;
  (function(SignatureHelpTriggerKind2) {
    SignatureHelpTriggerKind2[SignatureHelpTriggerKind2["Invoke"] = 1] = "Invoke";
    SignatureHelpTriggerKind2[SignatureHelpTriggerKind2["TriggerCharacter"] = 2] = "TriggerCharacter";
    SignatureHelpTriggerKind2[SignatureHelpTriggerKind2["ContentChange"] = 3] = "ContentChange";
  })(SignatureHelpTriggerKind || (SignatureHelpTriggerKind = {}));
  var SymbolKind;
  (function(SymbolKind2) {
    SymbolKind2[SymbolKind2["File"] = 0] = "File";
    SymbolKind2[SymbolKind2["Module"] = 1] = "Module";
    SymbolKind2[SymbolKind2["Namespace"] = 2] = "Namespace";
    SymbolKind2[SymbolKind2["Package"] = 3] = "Package";
    SymbolKind2[SymbolKind2["Class"] = 4] = "Class";
    SymbolKind2[SymbolKind2["Method"] = 5] = "Method";
    SymbolKind2[SymbolKind2["Property"] = 6] = "Property";
    SymbolKind2[SymbolKind2["Field"] = 7] = "Field";
    SymbolKind2[SymbolKind2["Constructor"] = 8] = "Constructor";
    SymbolKind2[SymbolKind2["Enum"] = 9] = "Enum";
    SymbolKind2[SymbolKind2["Interface"] = 10] = "Interface";
    SymbolKind2[SymbolKind2["Function"] = 11] = "Function";
    SymbolKind2[SymbolKind2["Variable"] = 12] = "Variable";
    SymbolKind2[SymbolKind2["Constant"] = 13] = "Constant";
    SymbolKind2[SymbolKind2["String"] = 14] = "String";
    SymbolKind2[SymbolKind2["Number"] = 15] = "Number";
    SymbolKind2[SymbolKind2["Boolean"] = 16] = "Boolean";
    SymbolKind2[SymbolKind2["Array"] = 17] = "Array";
    SymbolKind2[SymbolKind2["Object"] = 18] = "Object";
    SymbolKind2[SymbolKind2["Key"] = 19] = "Key";
    SymbolKind2[SymbolKind2["Null"] = 20] = "Null";
    SymbolKind2[SymbolKind2["EnumMember"] = 21] = "EnumMember";
    SymbolKind2[SymbolKind2["Struct"] = 22] = "Struct";
    SymbolKind2[SymbolKind2["Event"] = 23] = "Event";
    SymbolKind2[SymbolKind2["Operator"] = 24] = "Operator";
    SymbolKind2[SymbolKind2["TypeParameter"] = 25] = "TypeParameter";
  })(SymbolKind || (SymbolKind = {}));
  var SymbolTag;
  (function(SymbolTag2) {
    SymbolTag2[SymbolTag2["Deprecated"] = 1] = "Deprecated";
  })(SymbolTag || (SymbolTag = {}));
  var TextDirection;
  (function(TextDirection2) {
    TextDirection2[TextDirection2["LTR"] = 0] = "LTR";
    TextDirection2[TextDirection2["RTL"] = 1] = "RTL";
  })(TextDirection || (TextDirection = {}));
  var TextEditorCursorBlinkingStyle;
  (function(TextEditorCursorBlinkingStyle2) {
    TextEditorCursorBlinkingStyle2[TextEditorCursorBlinkingStyle2["Hidden"] = 0] = "Hidden";
    TextEditorCursorBlinkingStyle2[TextEditorCursorBlinkingStyle2["Blink"] = 1] = "Blink";
    TextEditorCursorBlinkingStyle2[TextEditorCursorBlinkingStyle2["Smooth"] = 2] = "Smooth";
    TextEditorCursorBlinkingStyle2[TextEditorCursorBlinkingStyle2["Phase"] = 3] = "Phase";
    TextEditorCursorBlinkingStyle2[TextEditorCursorBlinkingStyle2["Expand"] = 4] = "Expand";
    TextEditorCursorBlinkingStyle2[TextEditorCursorBlinkingStyle2["Solid"] = 5] = "Solid";
  })(TextEditorCursorBlinkingStyle || (TextEditorCursorBlinkingStyle = {}));
  var TextEditorCursorStyle;
  (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 || (TextEditorCursorStyle = {}));
  var TrackedRangeStickiness;
  (function(TrackedRangeStickiness2) {
    TrackedRangeStickiness2[TrackedRangeStickiness2["AlwaysGrowsWhenTypingAtEdges"] = 0] = "AlwaysGrowsWhenTypingAtEdges";
    TrackedRangeStickiness2[TrackedRangeStickiness2["NeverGrowsWhenTypingAtEdges"] = 1] = "NeverGrowsWhenTypingAtEdges";
    TrackedRangeStickiness2[TrackedRangeStickiness2["GrowsOnlyWhenTypingBefore"] = 2] = "GrowsOnlyWhenTypingBefore";
    TrackedRangeStickiness2[TrackedRangeStickiness2["GrowsOnlyWhenTypingAfter"] = 3] = "GrowsOnlyWhenTypingAfter";
  })(TrackedRangeStickiness || (TrackedRangeStickiness = {}));
  var WrappingIndent;
  (function(WrappingIndent2) {
    WrappingIndent2[WrappingIndent2["None"] = 0] = "None";
    WrappingIndent2[WrappingIndent2["Same"] = 1] = "Same";
    WrappingIndent2[WrappingIndent2["Indent"] = 2] = "Indent";
    WrappingIndent2[WrappingIndent2["DeepIndent"] = 3] = "DeepIndent";
  })(WrappingIndent || (WrappingIndent = {}));
  let KeyMod$1 = (_Ma = class {
    static chord(firstPart, secondPart) {
      return KeyChord(firstPart, secondPart);
    }
  }, _Ma.CtrlCmd = 2048, _Ma.Shift = 1024, _Ma.Alt = 512, _Ma.WinCtrl = 256, _Ma);
  function createMonacoBaseAPI() {
    return {
      editor: void 0,
      // undefined override expected here
      languages: void 0,
      // undefined override expected here
      CancellationTokenSource: CancellationTokenSource$1,
      Emitter: Emitter$1,
      KeyCode: KeyCode$1,
      KeyMod: KeyMod$1,
      Position: Position$1,
      Range: Range$2,
      Selection: Selection$1,
      SelectionDirection: SelectionDirection$1,
      MarkerSeverity: MarkerSeverity$1,
      MarkerTag: MarkerTag$1,
      Uri: URI,
      Token: Token$2
    };
  }
  const DEFAULT_CHANNEL = "default";
  const INITIALIZE = "$initialize";
  let webWorkerWarningLogged = false;
  function logOnceWebWorkerWarning(err) {
    if (!isWeb) {
      return;
    }
    if (!webWorkerWarningLogged) {
      webWorkerWarningLogged = true;
      console.warn("Could not create web worker(s). Falling back to loading web worker code in main thread, which might cause UI freezes. Please see https://github.com/microsoft/monaco-editor#faq");
    }
    console.warn(err.message);
  }
  class RequestMessage {
    constructor(vsWorker, req, channel, method, args) {
      this.vsWorker = vsWorker;
      this.req = req;
      this.channel = channel;
      this.method = method;
      this.args = args;
      this.type = 0;
    }
  }
  class ReplyMessage {
    constructor(vsWorker, seq, res, err) {
      this.vsWorker = vsWorker;
      this.seq = seq;
      this.res = res;
      this.err = err;
      this.type = 1;
    }
  }
  class SubscribeEventMessage {
    constructor(vsWorker, req, channel, eventName, arg) {
      this.vsWorker = vsWorker;
      this.req = req;
      this.channel = channel;
      this.eventName = eventName;
      this.arg = arg;
      this.type = 2;
    }
  }
  class EventMessage {
    constructor(vsWorker, req, event) {
      this.vsWorker = vsWorker;
      this.req = req;
      this.event = event;
      this.type = 3;
    }
  }
  class UnsubscribeEventMessage {
    constructor(vsWorker, req) {
      this.vsWorker = vsWorker;
      this.req = req;
      this.type = 4;
    }
  }
  class WebWorkerProtocol {
    constructor(handler) {
      this._workerId = -1;
      this._handler = handler;
      this._lastSentReq = 0;
      this._pendingReplies = /* @__PURE__ */ Object.create(null);
      this._pendingEmitters = /* @__PURE__ */ new Map();
      this._pendingEvents = /* @__PURE__ */ new Map();
    }
    setWorkerId(workerId) {
      this._workerId = workerId;
    }
    async sendMessage(channel, method, args) {
      const req = String(++this._lastSentReq);
      return new Promise((resolve2, reject) => {
        this._pendingReplies[req] = {
          resolve: resolve2,
          reject
        };
        this._send(new RequestMessage(this._workerId, req, channel, method, args));
      });
    }
    listen(channel, eventName, arg) {
      let req = null;
      const emitter = new Emitter$1({
        onWillAddFirstListener: () => {
          req = String(++this._lastSentReq);
          this._pendingEmitters.set(req, emitter);
          this._send(new SubscribeEventMessage(this._workerId, req, channel, eventName, arg));
        },
        onDidRemoveLastListener: () => {
          this._pendingEmitters.delete(req);
          this._send(new UnsubscribeEventMessage(this._workerId, req));
          req = null;
        }
      });
      return emitter.event;
    }
    handleMessage(message) {
      if (!message || !message.vsWorker) {
        return;
      }
      if (this._workerId !== -1 && message.vsWorker !== this._workerId) {
        return;
      }
      this._handleMessage(message);
    }
    createProxyToRemoteChannel(channel, sendMessageBarrier) {
      const handler = {
        get: (target, name) => {
          if (typeof name === "string" && !target[name]) {
            if (propertyIsDynamicEvent(name)) {
              target[name] = (arg) => {
                return this.listen(channel, name, arg);
              };
            } else if (propertyIsEvent(name)) {
              target[name] = this.listen(channel, name, void 0);
            } else if (name.charCodeAt(0) === 36) {
              target[name] = async (...myArgs) => {
                await sendMessageBarrier?.();
                return this.sendMessage(channel, name, myArgs);
              };
            }
          }
          return target[name];
        }
      };
      return new Proxy(/* @__PURE__ */ Object.create(null), handler);
    }
    _handleMessage(msg) {
      switch (msg.type) {
        case 1:
          return this._handleReplyMessage(msg);
        case 0:
          return this._handleRequestMessage(msg);
        case 2:
          return this._handleSubscribeEventMessage(msg);
        case 3:
          return this._handleEventMessage(msg);
        case 4:
          return this._handleUnsubscribeEventMessage(msg);
      }
    }
    _handleReplyMessage(replyMessage) {
      if (!this._pendingReplies[replyMessage.seq]) {
        console.warn("Got reply to unknown seq");
        return;
      }
      const reply = this._pendingReplies[replyMessage.seq];
      delete this._pendingReplies[replyMessage.seq];
      if (replyMessage.err) {
        let err = replyMessage.err;
        if (replyMessage.err.$isError) {
          const newErr = new Error();
          newErr.name = replyMessage.err.name;
          newErr.message = replyMessage.err.message;
          newErr.stack = replyMessage.err.stack;
          err = newErr;
        }
        reply.reject(err);
        return;
      }
      reply.resolve(replyMessage.res);
    }
    _handleRequestMessage(requestMessage) {
      const req = requestMessage.req;
      const result = this._handler.handleMessage(requestMessage.channel, requestMessage.method, requestMessage.args);
      result.then((r) => {
        this._send(new ReplyMessage(this._workerId, req, r, void 0));
      }, (e) => {
        if (e.detail instanceof Error) {
          e.detail = transformErrorForSerialization(e.detail);
        }
        this._send(new ReplyMessage(this._workerId, req, void 0, transformErrorForSerialization(e)));
      });
    }
    _handleSubscribeEventMessage(msg) {
      const req = msg.req;
      const disposable = this._handler.handleEvent(msg.channel, msg.eventName, msg.arg)((event) => {
        this._send(new EventMessage(this._workerId, req, event));
      });
      this._pendingEvents.set(req, disposable);
    }
    _handleEventMessage(msg) {
      if (!this._pendingEmitters.has(msg.req)) {
        console.warn("Got event for unknown req");
        return;
      }
      this._pendingEmitters.get(msg.req).fire(msg.event);
    }
    _handleUnsubscribeEventMessage(msg) {
      if (!this._pendingEvents.has(msg.req)) {
        console.warn("Got unsubscribe for unknown req");
        return;
      }
      this._pendingEvents.get(msg.req).dispose();
      this._pendingEvents.delete(msg.req);
    }
    _send(msg) {
      const transfer = [];
      if (msg.type === 0) {
        for (let i2 = 0; i2 < msg.args.length; i2++) {
          const arg = msg.args[i2];
          if (arg instanceof ArrayBuffer) {
            transfer.push(arg);
          }
        }
      } else if (msg.type === 1) {
        if (msg.res instanceof ArrayBuffer) {
          transfer.push(msg.res);
        }
      }
      this._handler.sendMessage(msg, transfer);
    }
  }
  class WebWorkerClient extends Disposable {
    constructor(worker) {
      super();
      this._localChannels = /* @__PURE__ */ new Map();
      this._worker = this._register(worker);
      this._register(this._worker.onMessage((msg) => {
        this._protocol.handleMessage(msg);
      }));
      this._register(this._worker.onError((err) => {
        logOnceWebWorkerWarning(err);
        onUnexpectedError(err);
      }));
      this._protocol = new WebWorkerProtocol({
        sendMessage: (msg, transfer) => {
          this._worker.postMessage(msg, transfer);
        },
        handleMessage: (channel, method, args) => {
          return this._handleMessage(channel, method, args);
        },
        handleEvent: (channel, eventName, arg) => {
          return this._handleEvent(channel, eventName, arg);
        }
      });
      this._protocol.setWorkerId(this._worker.getId());
      this._onModuleLoaded = this._protocol.sendMessage(DEFAULT_CHANNEL, INITIALIZE, [
        this._worker.getId()
      ]).then(() => {
      });
      this.proxy = this._protocol.createProxyToRemoteChannel(DEFAULT_CHANNEL, async () => {
        await this._onModuleLoaded;
      });
      this._onModuleLoaded.catch((e) => {
        this._onError("Worker failed to load ", e);
      });
    }
    _handleMessage(channelName, method, args) {
      const channel = this._localChannels.get(channelName);
      if (!channel) {
        return Promise.reject(new Error(`Missing channel ${channelName} on main thread`));
      }
      const fn = channel[method];
      if (typeof fn !== "function") {
        return Promise.reject(new Error(`Missing method ${method} on main thread channel ${channelName}`));
      }
      try {
        return Promise.resolve(fn.apply(channel, args));
      } catch (e) {
        return Promise.reject(e);
      }
    }
    _handleEvent(channelName, eventName, arg) {
      const channel = this._localChannels.get(channelName);
      if (!channel) {
        throw new Error(`Missing channel ${channelName} on main thread`);
      }
      if (propertyIsDynamicEvent(eventName)) {
        const fn = channel[eventName];
        if (typeof fn !== "function") {
          throw new Error(`Missing dynamic event ${eventName} on main thread channel ${channelName}.`);
        }
        const event = fn.call(channel, arg);
        if (typeof event !== "function") {
          throw new Error(`Missing dynamic event ${eventName} on main thread channel ${channelName}.`);
        }
        return event;
      }
      if (propertyIsEvent(eventName)) {
        const event = channel[eventName];
        if (typeof event !== "function") {
          throw new Error(`Missing event ${eventName} on main thread channel ${channelName}.`);
        }
        return event;
      }
      throw new Error(`Malformed event name ${eventName}`);
    }
    setChannel(channel, handler) {
      this._localChannels.set(channel, handler);
    }
    _onError(message, error) {
      console.error(message);
      console.info(error);
    }
  }
  function propertyIsEvent(name) {
    return name[0] === "o" && name[1] === "n" && isUpperAsciiLetter(name.charCodeAt(2));
  }
  function propertyIsDynamicEvent(name) {
    return /^onDynamic/.test(name) && isUpperAsciiLetter(name.charCodeAt(9));
  }
  let ttPolicy$1;
  if (typeof self === "object" && self.constructor && self.constructor.name === "DedicatedWorkerGlobalScope" && globalThis.workerttPolicy !== void 0) {
    ttPolicy$1 = globalThis.workerttPolicy;
  } else {
    ttPolicy$1 = createTrustedTypesPolicy("defaultWorkerFactory", { createScriptURL: (value) => value });
  }
  function getWorker(descriptor, id) {
    const label = descriptor.label || "anonymous" + id;
    const monacoEnvironment2 = getMonacoEnvironment();
    if (monacoEnvironment2) {
      if (typeof monacoEnvironment2.getWorker === "function") {
        return monacoEnvironment2.getWorker("workerMain.js", label);
      }
      if (typeof monacoEnvironment2.getWorkerUrl === "function") {
        const workerUrl = monacoEnvironment2.getWorkerUrl("workerMain.js", label);
        return new Worker(ttPolicy$1 ? ttPolicy$1.createScriptURL(workerUrl) : workerUrl, { name: label, type: "module" });
      }
    }
    const esmWorkerLocation = descriptor.esmModuleLocation;
    if (esmWorkerLocation) {
      const workerUrl = getWorkerBootstrapUrl(label, esmWorkerLocation.toString(true));
      const worker = new Worker(ttPolicy$1 ? ttPolicy$1.createScriptURL(workerUrl) : workerUrl, { name: label, type: "module" });
      return whenESMWorkerReady(worker);
    }
    throw new Error(`You must define a function MonacoEnvironment.getWorkerUrl or MonacoEnvironment.getWorker`);
  }
  function getWorkerBootstrapUrl(label, workerScriptUrl) {
    if (/^((http:)|(https:)|(file:))/.test(workerScriptUrl) && workerScriptUrl.substring(0, globalThis.origin.length) !== globalThis.origin) ;
    else {
      const start = workerScriptUrl.lastIndexOf("?");
      const end = workerScriptUrl.lastIndexOf("#", start);
      const params = start > 0 ? new URLSearchParams(workerScriptUrl.substring(start + 1, ~end ? end : void 0)) : new URLSearchParams();
      COI.addSearchParam(params, true, true);
      const search2 = params.toString();
      if (!search2) {
        workerScriptUrl = `${workerScriptUrl}#${label}`;
      } else {
        workerScriptUrl = `${workerScriptUrl}?${params.toString()}#${label}`;
      }
    }
    const blob = new Blob([coalesce([
      `/*${label}*/`,
      `globalThis._VSCODE_NLS_MESSAGES = ${JSON.stringify(getNLSMessages())};`,
      `globalThis._VSCODE_NLS_LANGUAGE = ${JSON.stringify(getNLSLanguage())};`,
      `globalThis._VSCODE_FILE_ROOT = ${JSON.stringify(globalThis._VSCODE_FILE_ROOT)};`,
      `const ttPolicy = globalThis.trustedTypes?.createPolicy('defaultWorkerFactory', { createScriptURL: value => value });`,
      `globalThis.workerttPolicy = ttPolicy;`,
      `await import(ttPolicy?.createScriptURL(${JSON.stringify(workerScriptUrl)}) ?? ${JSON.stringify(workerScriptUrl)});`,
      `globalThis.postMessage({ type: 'vscode-worker-ready' });`,
      `/*${label}*/`
    ]).join("")], { type: "application/javascript" });
    return URL.createObjectURL(blob);
  }
  function whenESMWorkerReady(worker) {
    return new Promise((resolve2, reject) => {
      worker.onmessage = function(e) {
        if (e.data.type === "vscode-worker-ready") {
          worker.onmessage = null;
          resolve2(worker);
        }
      };
      worker.onerror = reject;
    });
  }
  function isPromiseLike(obj) {
    return !!obj && typeof obj.then === "function";
  }
  const _WebWorker = class _WebWorker extends Disposable {
    constructor(descriptorOrWorker) {
      super();
      this._onMessage = this._register(new Emitter$1());
      this.onMessage = this._onMessage.event;
      this._onError = this._register(new Emitter$1());
      this.onError = this._onError.event;
      this.id = ++_WebWorker.LAST_WORKER_ID;
      const workerOrPromise = descriptorOrWorker instanceof Worker ? descriptorOrWorker : "then" in descriptorOrWorker ? descriptorOrWorker : getWorker(descriptorOrWorker, this.id);
      if (isPromiseLike(workerOrPromise)) {
        this.worker = workerOrPromise;
      } else {
        this.worker = Promise.resolve(workerOrPromise);
      }
      this.postMessage("-please-ignore-", []);
      const errorHandler2 = (ev) => {
        this._onError.fire(ev);
      };
      this.worker.then((w) => {
        w.onmessage = (ev) => {
          this._onMessage.fire(ev.data);
        };
        w.onmessageerror = (ev) => {
          this._onError.fire(ev);
        };
        if (typeof w.addEventListener === "function") {
          w.addEventListener("error", errorHandler2);
        }
      });
      this._register(toDisposable(() => {
        this.worker?.then((w) => {
          w.onmessage = null;
          w.onmessageerror = null;
          w.removeEventListener("error", errorHandler2);
          w.terminate();
        });
        this.worker = null;
      }));
    }
    getId() {
      return this.id;
    }
    postMessage(message, transfer) {
      this.worker?.then((w) => {
        try {
          w.postMessage(message, transfer);
        } catch (err) {
          onUnexpectedError(err);
          onUnexpectedError(new Error(`FAILED to post message to worker`, { cause: err }));
        }
      });
    }
  };
  _WebWorker.LAST_WORKER_ID = 0;
  let WebWorker = _WebWorker;
  class WebWorkerDescriptor {
    constructor(esmModuleLocation, label) {
      this.esmModuleLocation = esmModuleLocation;
      this.label = label;
    }
  }
  function createWebWorker$2(arg0, arg1) {
    const workerDescriptorOrWorker = URI.isUri(arg0) ? new WebWorkerDescriptor(arg0, arg1) : arg0;
    return new WebWorkerClient(new WebWorker(workerDescriptorOrWorker));
  }
  class Uint8Matrix {
    constructor(rows, cols, defaultValue) {
      const data = new Uint8Array(rows * cols);
      for (let i2 = 0, len = rows * cols; i2 < len; i2++) {
        data[i2] = defaultValue;
      }
      this._data = data;
      this.rows = rows;
      this.cols = cols;
    }
    get(row, col) {
      return this._data[row * this.cols + col];
    }
    set(row, col, value) {
      this._data[row * this.cols + col] = value;
    }
  }
  class StateMachine {
    constructor(edges) {
      let maxCharCode = 0;
      let maxState = 0;
      for (let i2 = 0, len = edges.length; i2 < len; i2++) {
        const [from, chCode, to] = edges[i2];
        if (chCode > maxCharCode) {
          maxCharCode = chCode;
        }
        if (from > maxState) {
          maxState = from;
        }
        if (to > maxState) {
          maxState = to;
        }
      }
      maxCharCode++;
      maxState++;
      const states = new Uint8Matrix(
        maxState,
        maxCharCode,
        0
        /* State.Invalid */
      );
      for (let i2 = 0, len = edges.length; i2 < len; i2++) {
        const [from, chCode, to] = edges[i2];
        states.set(from, chCode, to);
      }
      this._states = states;
      this._maxCharCode = maxCharCode;
    }
    nextState(currentState, chCode) {
      if (chCode < 0 || chCode >= this._maxCharCode) {
        return 0;
      }
      return this._states.get(currentState, chCode);
    }
  }
  let _stateMachine = null;
  function getStateMachine() {
    if (_stateMachine === null) {
      _stateMachine = new StateMachine([
        [
          1,
          104,
          2
          /* State.H */
        ],
        [
          1,
          72,
          2
          /* State.H */
        ],
        [
          1,
          102,
          6
          /* State.F */
        ],
        [
          1,
          70,
          6
          /* State.F */
        ],
        [
          2,
          116,
          3
          /* State.HT */
        ],
        [
          2,
          84,
          3
          /* State.HT */
        ],
        [
          3,
          116,
          4
          /* State.HTT */
        ],
        [
          3,
          84,
          4
          /* State.HTT */
        ],
        [
          4,
          112,
          5
          /* State.HTTP */
        ],
        [
          4,
          80,
          5
          /* State.HTTP */
        ],
        [
          5,
          115,
          9
          /* State.BeforeColon */
        ],
        [
          5,
          83,
          9
          /* State.BeforeColon */
        ],
        [
          5,
          58,
          10
          /* State.AfterColon */
        ],
        [
          6,
          105,
          7
          /* State.FI */
        ],
        [
          6,
          73,
          7
          /* State.FI */
        ],
        [
          7,
          108,
          8
          /* State.FIL */
        ],
        [
          7,
          76,
          8
          /* State.FIL */
        ],
        [
          8,
          101,
          9
          /* State.BeforeColon */
        ],
        [
          8,
          69,
          9
          /* State.BeforeColon */
        ],
        [
          9,
          58,
          10
          /* State.AfterColon */
        ],
        [
          10,
          47,
          11
          /* State.AlmostThere */
        ],
        [
          11,
          47,
          12
          /* State.End */
        ]
      ]);
    }
    return _stateMachine;
  }
  let _classifier = null;
  function getClassifier() {
    if (_classifier === null) {
      _classifier = new CharacterClassifier(
        0
        /* CharacterClass.None */
      );
      const FORCE_TERMINATION_CHARACTERS = ` 	<>'"、。｡､，．：；‘〈「『〔（［｛｢｣｝］）〕』」〉’｀～…|`;
      for (let i2 = 0; i2 < FORCE_TERMINATION_CHARACTERS.length; i2++) {
        _classifier.set(
          FORCE_TERMINATION_CHARACTERS.charCodeAt(i2),
          1
          /* CharacterClass.ForceTermination */
        );
      }
      const CANNOT_END_WITH_CHARACTERS = ".,;:";
      for (let i2 = 0; i2 < CANNOT_END_WITH_CHARACTERS.length; i2++) {
        _classifier.set(
          CANNOT_END_WITH_CHARACTERS.charCodeAt(i2),
          2
          /* CharacterClass.CannotEndIn */
        );
      }
    }
    return _classifier;
  }
  class LinkComputer {
    static _createLink(classifier, line, lineNumber, linkBeginIndex, linkEndIndex) {
      let lastIncludedCharIndex = linkEndIndex - 1;
      do {
        const chCode = line.charCodeAt(lastIncludedCharIndex);
        const chClass = classifier.get(chCode);
        if (chClass !== 2) {
          break;
        }
        lastIncludedCharIndex--;
      } while (lastIncludedCharIndex > linkBeginIndex);
      if (linkBeginIndex > 0) {
        const charCodeBeforeLink = line.charCodeAt(linkBeginIndex - 1);
        const lastCharCodeInLink = line.charCodeAt(lastIncludedCharIndex);
        if (charCodeBeforeLink === 40 && lastCharCodeInLink === 41 || charCodeBeforeLink === 91 && lastCharCodeInLink === 93 || charCodeBeforeLink === 123 && lastCharCodeInLink === 125) {
          lastIncludedCharIndex--;
        }
      }
      return {
        range: {
          startLineNumber: lineNumber,
          startColumn: linkBeginIndex + 1,
          endLineNumber: lineNumber,
          endColumn: lastIncludedCharIndex + 2
        },
        url: line.substring(linkBeginIndex, lastIncludedCharIndex + 1)
      };
    }
    static computeLinks(model, stateMachine = getStateMachine()) {
      const classifier = getClassifier();
      const result = [];
      for (let i2 = 1, lineCount = model.getLineCount(); i2 <= lineCount; i2++) {
        const line = model.getLineContent(i2);
        const len = line.length;
        let j = 0;
        let linkBeginIndex = 0;
        let linkBeginChCode = 0;
        let state = 1;
        let hasOpenParens = false;
        let hasOpenSquareBracket = false;
        let inSquareBrackets = false;
        let hasOpenCurlyBracket = false;
        while (j < len) {
          let resetStateMachine = false;
          const chCode = line.charCodeAt(j);
          if (state === 13) {
            let chClass;
            switch (chCode) {
              case 40:
                hasOpenParens = true;
                chClass = 0;
                break;
              case 41:
                chClass = hasOpenParens ? 0 : 1;
                break;
              case 91:
                inSquareBrackets = true;
                hasOpenSquareBracket = true;
                chClass = 0;
                break;
              case 93:
                inSquareBrackets = false;
                chClass = hasOpenSquareBracket ? 0 : 1;
                break;
              case 123:
                hasOpenCurlyBracket = true;
                chClass = 0;
                break;
              case 125:
                chClass = hasOpenCurlyBracket ? 0 : 1;
                break;
              // The following three rules make it that ' or " or ` are allowed inside links
              // only if the link is wrapped by some other quote character
              case 39:
              case 34:
              case 96:
                if (linkBeginChCode === chCode) {
                  chClass = 1;
                } else if (linkBeginChCode === 39 || linkBeginChCode === 34 || linkBeginChCode === 96) {
                  chClass = 0;
                } else {
                  chClass = 1;
                }
                break;
              case 42:
                chClass = linkBeginChCode === 42 ? 1 : 0;
                break;
              case 32:
                chClass = inSquareBrackets ? 0 : 1;
                break;
              default:
                chClass = classifier.get(chCode);
            }
            if (chClass === 1) {
              result.push(LinkComputer._createLink(classifier, line, i2, linkBeginIndex, j));
              resetStateMachine = true;
            }
          } else if (state === 12) {
            let chClass;
            if (chCode === 91) {
              hasOpenSquareBracket = true;
              chClass = 0;
            } else {
              chClass = classifier.get(chCode);
            }
            if (chClass === 1) {
              resetStateMachine = true;
            } else {
              state = 13;
            }
          } else {
            state = stateMachine.nextState(state, chCode);
            if (state === 0) {
              resetStateMachine = true;
            }
          }
          if (resetStateMachine) {
            state = 1;
            hasOpenParens = false;
            hasOpenSquareBracket = false;
            hasOpenCurlyBracket = false;
            linkBeginIndex = j + 1;
            linkBeginChCode = chCode;
          }
          j++;
        }
        if (state === 13) {
          result.push(LinkComputer._createLink(classifier, line, i2, linkBeginIndex, len));
        }
      }
      return result;
    }
  }
  function computeLinks(model) {
    if (!model || typeof model.getLineCount !== "function" || typeof model.getLineContent !== "function") {
      return [];
    }
    return LinkComputer.computeLinks(model);
  }
  const _BasicInplaceReplace = class _BasicInplaceReplace {
    constructor() {
      this._defaultValueSet = [
        ["true", "false"],
        ["True", "False"],
        ["Private", "Public", "Friend", "ReadOnly", "Partial", "Protected", "WriteOnly"],
        ["public", "protected", "private"]
      ];
    }
    navigateValueSet(range1, text1, range2, text2, up) {
      if (range1 && text1) {
        const result = this.doNavigateValueSet(text1, up);
        if (result) {
          return {
            range: range1,
            value: result
          };
        }
      }
      if (range2 && text2) {
        const result = this.doNavigateValueSet(text2, up);
        if (result) {
          return {
            range: range2,
            value: result
          };
        }
      }
      return null;
    }
    doNavigateValueSet(text2, up) {
      const numberResult = this.numberReplace(text2, up);
      if (numberResult !== null) {
        return numberResult;
      }
      return this.textReplace(text2, up);
    }
    numberReplace(value, up) {
      const precision = Math.pow(10, value.length - (value.lastIndexOf(".") + 1));
      let n1 = Number(value);
      const n2 = parseFloat(value);
      if (!isNaN(n1) && !isNaN(n2) && n1 === n2) {
        if (n1 === 0 && !up) {
          return null;
        } else {
          n1 = Math.floor(n1 * precision);
          n1 += up ? precision : -precision;
          return String(n1 / precision);
        }
      }
      return null;
    }
    textReplace(value, up) {
      return this.valueSetsReplace(this._defaultValueSet, value, up);
    }
    valueSetsReplace(valueSets, value, up) {
      let result = null;
      for (let i2 = 0, len = valueSets.length; result === null && i2 < len; i2++) {
        result = this.valueSetReplace(valueSets[i2], value, up);
      }
      return result;
    }
    valueSetReplace(valueSet, value, up) {
      let idx = valueSet.indexOf(value);
      if (idx >= 0) {
        idx += up ? 1 : -1;
        if (idx < 0) {
          idx = valueSet.length - 1;
        } else {
          idx %= valueSet.length;
        }
        return valueSet[idx];
      }
      return null;
    }
  };
  _BasicInplaceReplace.INSTANCE = new _BasicInplaceReplace();
  let BasicInplaceReplace = _BasicInplaceReplace;
  function _parseCaptureGroups(captureGroups) {
    const values = [];
    for (const captureGroup of captureGroups) {
      const parsedNumber = Number(captureGroup);
      if (parsedNumber || parsedNumber === 0 && captureGroup.replace(/\s/g, "") !== "") {
        values.push(parsedNumber);
      }
    }
    return values;
  }
  function _toIColor(r, g, b, a) {
    return {
      red: r / 255,
      blue: b / 255,
      green: g / 255,
      alpha: a
    };
  }
  function _findRange(model, match2) {
    const index = match2.index;
    const length = match2[0].length;
    if (index === void 0) {
      return;
    }
    const startPosition = model.positionAt(index);
    const range2 = {
      startLineNumber: startPosition.lineNumber,
      startColumn: startPosition.column,
      endLineNumber: startPosition.lineNumber,
      endColumn: startPosition.column + length
    };
    return range2;
  }
  function _findHexColorInformation(range2, hexValue) {
    if (!range2) {
      return;
    }
    const parsedHexColor = Color.Format.CSS.parseHex(hexValue);
    if (!parsedHexColor) {
      return;
    }
    return {
      range: range2,
      color: _toIColor(parsedHexColor.rgba.r, parsedHexColor.rgba.g, parsedHexColor.rgba.b, parsedHexColor.rgba.a)
    };
  }
  function _findRGBColorInformation(range2, matches, isAlpha) {
    if (!range2 || matches.length !== 1) {
      return;
    }
    const match2 = matches[0];
    const captureGroups = match2.values();
    const parsedRegex = _parseCaptureGroups(captureGroups);
    return {
      range: range2,
      color: _toIColor(parsedRegex[0], parsedRegex[1], parsedRegex[2], isAlpha ? parsedRegex[3] : 1)
    };
  }
  function _findHSLColorInformation(range2, matches, isAlpha) {
    if (!range2 || matches.length !== 1) {
      return;
    }
    const match2 = matches[0];
    const captureGroups = match2.values();
    const parsedRegex = _parseCaptureGroups(captureGroups);
    const colorEquivalent = new Color(new HSLA(parsedRegex[0], parsedRegex[1] / 100, parsedRegex[2] / 100, isAlpha ? parsedRegex[3] : 1));
    return {
      range: range2,
      color: _toIColor(colorEquivalent.rgba.r, colorEquivalent.rgba.g, colorEquivalent.rgba.b, colorEquivalent.rgba.a)
    };
  }
  function _findMatches(model, regex) {
    if (typeof model === "string") {
      return [...model.matchAll(regex)];
    } else {
      return model.findMatches(regex);
    }
  }
  function computeColors(model) {
    const result = [];
    const initialValidationRegex = new RegExp(`\\b(rgb|rgba|hsl|hsla)(\\([0-9\\s,.\\%]*\\))|^(#)([A-Fa-f0-9]{3})\\b|^(#)([A-Fa-f0-9]{4})\\b|^(#)([A-Fa-f0-9]{6})\\b|^(#)([A-Fa-f0-9]{8})\\b|(?<=['"\\s])(#)([A-Fa-f0-9]{3})\\b|(?<=['"\\s])(#)([A-Fa-f0-9]{4})\\b|(?<=['"\\s])(#)([A-Fa-f0-9]{6})\\b|(?<=['"\\s])(#)([A-Fa-f0-9]{8})\\b`, "gm");
    const initialValidationMatches = _findMatches(model, initialValidationRegex);
    if (initialValidationMatches.length > 0) {
      for (const initialMatch of initialValidationMatches) {
        const initialCaptureGroups = initialMatch.filter((captureGroup) => captureGroup !== void 0);
        const colorScheme = initialCaptureGroups[1];
        const colorParameters = initialCaptureGroups[2];
        if (!colorParameters) {
          continue;
        }
        let colorInformation;
        if (colorScheme === "rgb") {
          const regexParameters = /^\(\s*(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])\s*,\s*(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])\s*,\s*(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])\s*\)$/gm;
          colorInformation = _findRGBColorInformation(_findRange(model, initialMatch), _findMatches(colorParameters, regexParameters), false);
        } else if (colorScheme === "rgba") {
          const regexParameters = /^\(\s*(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])\s*,\s*(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])\s*,\s*(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])\s*,\s*(0[.][0-9]+|[.][0-9]+|[01][.]|[01])\s*\)$/gm;
          colorInformation = _findRGBColorInformation(_findRange(model, initialMatch), _findMatches(colorParameters, regexParameters), true);
        } else if (colorScheme === "hsl") {
          const regexParameters = /^\(\s*((?:360(?:\.0+)?|(?:36[0]|3[0-5][0-9]|[12][0-9][0-9]|[1-9]?[0-9])(?:\.\d+)?))\s*[\s,]\s*(100|\d{1,2}[.]\d*|\d{1,2})%\s*[\s,]\s*(100|\d{1,2}[.]\d*|\d{1,2})%\s*\)$/gm;
          colorInformation = _findHSLColorInformation(_findRange(model, initialMatch), _findMatches(colorParameters, regexParameters), false);
        } else if (colorScheme === "hsla") {
          const regexParameters = /^\(\s*((?:360(?:\.0+)?|(?:36[0]|3[0-5][0-9]|[12][0-9][0-9]|[1-9]?[0-9])(?:\.\d+)?))\s*[\s,]\s*(100|\d{1,2}[.]\d*|\d{1,2})%\s*[\s,]\s*(100|\d{1,2}[.]\d*|\d{1,2})%\s*[\s,]\s*(0[.][0-9]+|[.][0-9]+|[01][.]0*|[01])\s*\)$/gm;
          colorInformation = _findHSLColorInformation(_findRange(model, initialMatch), _findMatches(colorParameters, regexParameters), true);
        } else if (colorScheme === "#") {
          colorInformation = _findHexColorInformation(_findRange(model, initialMatch), colorScheme + colorParameters);
        }
        if (colorInformation) {
          result.push(colorInformation);
        }
      }
    }
    return result;
  }
  function computeDefaultDocumentColors(model) {
    if (!model || typeof model.getValue !== "function" || typeof model.positionAt !== "function") {
      return [];
    }
    return computeColors(model);
  }
  const trimDashesRegex = /^-+|-+$/g;
  const CHUNK_SIZE = 100;
  const MAX_SECTION_LINES = 5;
  function findSectionHeaders(model, options) {
    let headers = [];
    if (options.findRegionSectionHeaders && options.foldingRules?.markers) {
      const regionHeaders = collectRegionHeaders(model, options);
      headers = headers.concat(regionHeaders);
    }
    if (options.findMarkSectionHeaders) {
      const markHeaders = collectMarkHeaders(model, options);
      headers = headers.concat(markHeaders);
    }
    return headers;
  }
  function collectRegionHeaders(model, options) {
    const regionHeaders = [];
    const endLineNumber = model.getLineCount();
    for (let lineNumber = 1; lineNumber <= endLineNumber; lineNumber++) {
      const lineContent = model.getLineContent(lineNumber);
      const match2 = lineContent.match(options.foldingRules.markers.start);
      if (match2) {
        const range2 = { startLineNumber: lineNumber, startColumn: match2[0].length + 1, endLineNumber: lineNumber, endColumn: lineContent.length + 1 };
        if (range2.endColumn > range2.startColumn) {
          const sectionHeader = {
            range: range2,
            ...getHeaderText(lineContent.substring(match2[0].length)),
            shouldBeInComments: false
          };
          if (sectionHeader.text || sectionHeader.hasSeparatorLine) {
            regionHeaders.push(sectionHeader);
          }
        }
      }
    }
    return regionHeaders;
  }
  function collectMarkHeaders(model, options) {
    const markHeaders = [];
    const endLineNumber = model.getLineCount();
    if (!options.markSectionHeaderRegex || options.markSectionHeaderRegex.trim() === "") {
      return markHeaders;
    }
    const multiline = isMultilineRegexSource(options.markSectionHeaderRegex);
    const regex = new RegExp(options.markSectionHeaderRegex, `gdm${multiline ? "s" : ""}`);
    if (regExpLeadsToEndlessLoop(regex)) {
      return markHeaders;
    }
    for (let startLine = 1; startLine <= endLineNumber; startLine += CHUNK_SIZE - MAX_SECTION_LINES) {
      const endLine = Math.min(startLine + CHUNK_SIZE - 1, endLineNumber);
      const lines = [];
      for (let i2 = startLine; i2 <= endLine; i2++) {
        lines.push(model.getLineContent(i2));
      }
      const text2 = lines.join("\n");
      regex.lastIndex = 0;
      let match2;
      while ((match2 = regex.exec(text2)) !== null) {
        const precedingText = text2.substring(0, match2.index);
        const lineOffset = (precedingText.match(/\n/g) || []).length;
        const lineNumber = startLine + lineOffset;
        const matchLines = match2[0].split("\n");
        const matchHeight = matchLines.length;
        const matchEndLine = lineNumber + matchHeight - 1;
        const lineStartIndex = precedingText.lastIndexOf("\n") + 1;
        const startColumn = match2.index - lineStartIndex + 1;
        const lastMatchLine = matchLines[matchLines.length - 1];
        const endColumn = matchHeight === 1 ? startColumn + match2[0].length : lastMatchLine.length + 1;
        const range2 = {
          startLineNumber: lineNumber,
          startColumn,
          endLineNumber: matchEndLine,
          endColumn
        };
        const text22 = (match2.groups ?? {})["label"] ?? "";
        const hasSeparatorLine = ((match2.groups ?? {})["separator"] ?? "") !== "";
        const sectionHeader = {
          range: range2,
          text: text22,
          hasSeparatorLine,
          shouldBeInComments: true
        };
        if (sectionHeader.text || sectionHeader.hasSeparatorLine) {
          if (markHeaders.length === 0 || markHeaders[markHeaders.length - 1].range.endLineNumber < sectionHeader.range.startLineNumber) {
            markHeaders.push(sectionHeader);
          }
        }
        regex.lastIndex = match2.index + match2[0].length;
      }
    }
    return markHeaders;
  }
  function getHeaderText(text2) {
    text2 = text2.trim();
    const hasSeparatorLine = text2.startsWith("-");
    text2 = text2.replace(trimDashesRegex, "");
    return { text: text2, hasSeparatorLine };
  }
  class MirrorTextModel {
    constructor(uri, lines, eol, versionId) {
      this._uri = uri;
      this._lines = lines;
      this._eol = eol;
      this._versionId = versionId;
      this._lineStarts = null;
      this._cachedTextValue = null;
    }
    dispose() {
      this._lines.length = 0;
    }
    get version() {
      return this._versionId;
    }
    getText() {
      if (this._cachedTextValue === null) {
        this._cachedTextValue = this._lines.join(this._eol);
      }
      return this._cachedTextValue;
    }
    onEvents(e) {
      if (e.eol && e.eol !== this._eol) {
        this._eol = e.eol;
        this._lineStarts = null;
      }
      const changes = e.changes;
      for (const change of changes) {
        this._acceptDeleteRange(change.range);
        this._acceptInsertText(new Position$1(change.range.startLineNumber, change.range.startColumn), change.text);
      }
      this._versionId = e.versionId;
      this._cachedTextValue = null;
    }
    _ensureLineStarts() {
      if (!this._lineStarts) {
        const eolLength = this._eol.length;
        const linesLength = this._lines.length;
        const lineStartValues = new Uint32Array(linesLength);
        for (let i2 = 0; i2 < linesLength; i2++) {
          lineStartValues[i2] = this._lines[i2].length + eolLength;
        }
        this._lineStarts = new PrefixSumComputer(lineStartValues);
      }
    }
    /**
     * All changes to a line's text go through this method
     */
    _setLineText(lineIndex, newValue) {
      this._lines[lineIndex] = newValue;
      if (this._lineStarts) {
        this._lineStarts.setValue(lineIndex, this._lines[lineIndex].length + this._eol.length);
      }
    }
    _acceptDeleteRange(range2) {
      if (range2.startLineNumber === range2.endLineNumber) {
        if (range2.startColumn === range2.endColumn) {
          return;
        }
        this._setLineText(range2.startLineNumber - 1, this._lines[range2.startLineNumber - 1].substring(0, range2.startColumn - 1) + this._lines[range2.startLineNumber - 1].substring(range2.endColumn - 1));
        return;
      }
      this._setLineText(range2.startLineNumber - 1, this._lines[range2.startLineNumber - 1].substring(0, range2.startColumn - 1) + this._lines[range2.endLineNumber - 1].substring(range2.endColumn - 1));
      this._lines.splice(range2.startLineNumber, range2.endLineNumber - range2.startLineNumber);
      if (this._lineStarts) {
        this._lineStarts.removeValues(range2.startLineNumber, range2.endLineNumber - range2.startLineNumber);
      }
    }
    _acceptInsertText(position, insertText) {
      if (insertText.length === 0) {
        return;
      }
      const insertLines = splitLines(insertText);
      if (insertLines.length === 1) {
        this._setLineText(position.lineNumber - 1, this._lines[position.lineNumber - 1].substring(0, position.column - 1) + insertLines[0] + this._lines[position.lineNumber - 1].substring(position.column - 1));
        return;
      }
      insertLines[insertLines.length - 1] += this._lines[position.lineNumber - 1].substring(position.column - 1);
      this._setLineText(position.lineNumber - 1, this._lines[position.lineNumber - 1].substring(0, position.column - 1) + insertLines[0]);
      const newLengths = new Uint32Array(insertLines.length - 1);
      for (let i2 = 1; i2 < insertLines.length; i2++) {
        this._lines.splice(position.lineNumber + i2 - 1, 0, insertLines[i2]);
        newLengths[i2 - 1] = insertLines[i2].length + this._eol.length;
      }
      if (this._lineStarts) {
        this._lineStarts.insertValues(position.lineNumber, newLengths);
      }
    }
  }
  const STOP_SYNC_MODEL_DELTA_TIME_MS = 60 * 1e3;
  class WorkerTextModelSyncClient extends Disposable {
    constructor(proxy, modelService, keepIdleModels = false) {
      super();
      this._syncedModels = /* @__PURE__ */ Object.create(null);
      this._syncedModelsLastUsedTime = /* @__PURE__ */ Object.create(null);
      this._proxy = proxy;
      this._modelService = modelService;
      if (!keepIdleModels) {
        const timer = new IntervalTimer();
        timer.cancelAndSet(() => this._checkStopModelSync(), Math.round(STOP_SYNC_MODEL_DELTA_TIME_MS / 2));
        this._register(timer);
      }
    }
    dispose() {
      for (const modelUrl in this._syncedModels) {
        dispose(this._syncedModels[modelUrl]);
      }
      this._syncedModels = /* @__PURE__ */ Object.create(null);
      this._syncedModelsLastUsedTime = /* @__PURE__ */ Object.create(null);
      super.dispose();
    }
    ensureSyncedResources(resources, forceLargeModels = false) {
      for (const resource of resources) {
        const resourceStr = resource.toString();
        if (!this._syncedModels[resourceStr]) {
          this._beginModelSync(resource, forceLargeModels);
        }
        if (this._syncedModels[resourceStr]) {
          this._syncedModelsLastUsedTime[resourceStr] = (/* @__PURE__ */ new Date()).getTime();
        }
      }
    }
    _checkStopModelSync() {
      const currentTime = (/* @__PURE__ */ new Date()).getTime();
      const toRemove = [];
      for (const modelUrl in this._syncedModelsLastUsedTime) {
        const elapsedTime = currentTime - this._syncedModelsLastUsedTime[modelUrl];
        if (elapsedTime > STOP_SYNC_MODEL_DELTA_TIME_MS) {
          toRemove.push(modelUrl);
        }
      }
      for (const e of toRemove) {
        this._stopModelSync(e);
      }
    }
    _beginModelSync(resource, forceLargeModels) {
      const model = this._modelService.getModel(resource);
      if (!model) {
        return;
      }
      if (!forceLargeModels && model.isTooLargeForSyncing()) {
        return;
      }
      const modelUrl = resource.toString();
      this._proxy.$acceptNewModel({
        url: model.uri.toString(),
        lines: model.getLinesContent(),
        EOL: model.getEOL(),
        versionId: model.getVersionId()
      });
      const toDispose = new DisposableStore();
      toDispose.add(model.onDidChangeContent((e) => {
        this._proxy.$acceptModelChanged(modelUrl.toString(), e);
      }));
      toDispose.add(model.onWillDispose(() => {
        this._stopModelSync(modelUrl);
      }));
      toDispose.add(toDisposable(() => {
        this._proxy.$acceptRemovedModel(modelUrl);
      }));
      this._syncedModels[modelUrl] = toDispose;
    }
    _stopModelSync(modelUrl) {
      const toDispose = this._syncedModels[modelUrl];
      delete this._syncedModels[modelUrl];
      delete this._syncedModelsLastUsedTime[modelUrl];
      dispose(toDispose);
    }
  }
  class WorkerTextModelSyncServer {
    constructor() {
      this._models = /* @__PURE__ */ Object.create(null);
    }
    getModel(uri) {
      return this._models[uri];
    }
    getModels() {
      const all = [];
      Object.keys(this._models).forEach((key) => all.push(this._models[key]));
      return all;
    }
    $acceptNewModel(data) {
      this._models[data.url] = new MirrorModel(URI.parse(data.url), data.lines, data.EOL, data.versionId);
    }
    $acceptModelChanged(uri, e) {
      if (!this._models[uri]) {
        return;
      }
      const model = this._models[uri];
      model.onEvents(e);
    }
    $acceptRemovedModel(uri) {
      if (!this._models[uri]) {
        return;
      }
      delete this._models[uri];
    }
  }
  class MirrorModel extends MirrorTextModel {
    get uri() {
      return this._uri;
    }
    get eol() {
      return this._eol;
    }
    getValue() {
      return this.getText();
    }
    findMatches(regex) {
      const matches = [];
      for (let i2 = 0; i2 < this._lines.length; i2++) {
        const line = this._lines[i2];
        const offsetToAdd = this.offsetAt(new Position$1(i2 + 1, 1));
        const iteratorOverMatches = line.matchAll(regex);
        for (const match2 of iteratorOverMatches) {
          if (match2.index || match2.index === 0) {
            match2.index = match2.index + offsetToAdd;
          }
          matches.push(match2);
        }
      }
      return matches;
    }
    getLinesContent() {
      return this._lines.slice(0);
    }
    getLineCount() {
      return this._lines.length;
    }
    getLineContent(lineNumber) {
      return this._lines[lineNumber - 1];
    }
    getWordAtPosition(position, wordDefinition) {
      const wordAtText = getWordAtText(position.column, ensureValidWordDefinition(wordDefinition), this._lines[position.lineNumber - 1], 0);
      if (wordAtText) {
        return new Range$2(position.lineNumber, wordAtText.startColumn, position.lineNumber, wordAtText.endColumn);
      }
      return null;
    }
    words(wordDefinition) {
      const lines = this._lines;
      const wordenize = this._wordenize.bind(this);
      let lineNumber = 0;
      let lineText = "";
      let wordRangesIdx = 0;
      let wordRanges = [];
      return {
        *[Symbol.iterator]() {
          while (true) {
            if (wordRangesIdx < wordRanges.length) {
              const value = lineText.substring(wordRanges[wordRangesIdx].start, wordRanges[wordRangesIdx].end);
              wordRangesIdx += 1;
              yield value;
            } else {
              if (lineNumber < lines.length) {
                lineText = lines[lineNumber];
                wordRanges = wordenize(lineText, wordDefinition);
                wordRangesIdx = 0;
                lineNumber += 1;
              } else {
                break;
              }
            }
          }
        }
      };
    }
    getLineWords(lineNumber, wordDefinition) {
      const content = this._lines[lineNumber - 1];
      const ranges = this._wordenize(content, wordDefinition);
      const words = [];
      for (const range2 of ranges) {
        words.push({
          word: content.substring(range2.start, range2.end),
          startColumn: range2.start + 1,
          endColumn: range2.end + 1
        });
      }
      return words;
    }
    _wordenize(content, wordDefinition) {
      const result = [];
      let match2;
      wordDefinition.lastIndex = 0;
      while (match2 = wordDefinition.exec(content)) {
        if (match2[0].length === 0) {
          break;
        }
        result.push({ start: match2.index, end: match2.index + match2[0].length });
      }
      return result;
    }
    getValueInRange(range2) {
      range2 = this._validateRange(range2);
      if (range2.startLineNumber === range2.endLineNumber) {
        return this._lines[range2.startLineNumber - 1].substring(range2.startColumn - 1, range2.endColumn - 1);
      }
      const lineEnding = this._eol;
      const startLineIndex = range2.startLineNumber - 1;
      const endLineIndex = range2.endLineNumber - 1;
      const resultLines = [];
      resultLines.push(this._lines[startLineIndex].substring(range2.startColumn - 1));
      for (let i2 = startLineIndex + 1; i2 < endLineIndex; i2++) {
        resultLines.push(this._lines[i2]);
      }
      resultLines.push(this._lines[endLineIndex].substring(0, range2.endColumn - 1));
      return resultLines.join(lineEnding);
    }
    offsetAt(position) {
      position = this._validatePosition(position);
      this._ensureLineStarts();
      return this._lineStarts.getPrefixSum(position.lineNumber - 2) + (position.column - 1);
    }
    positionAt(offset) {
      offset = Math.floor(offset);
      offset = Math.max(0, offset);
      this._ensureLineStarts();
      const out = this._lineStarts.getIndexOf(offset);
      const lineLength = this._lines[out.index].length;
      return {
        lineNumber: 1 + out.index,
        column: 1 + Math.min(out.remainder, lineLength)
      };
    }
    _validateRange(range2) {
      const start = this._validatePosition({ lineNumber: range2.startLineNumber, column: range2.startColumn });
      const end = this._validatePosition({ lineNumber: range2.endLineNumber, column: range2.endColumn });
      if (start.lineNumber !== range2.startLineNumber || start.column !== range2.startColumn || end.lineNumber !== range2.endLineNumber || end.column !== range2.endColumn) {
        return {
          startLineNumber: start.lineNumber,
          startColumn: start.column,
          endLineNumber: end.lineNumber,
          endColumn: end.column
        };
      }
      return range2;
    }
    _validatePosition(position) {
      if (!Position$1.isIPosition(position)) {
        throw new Error("bad position");
      }
      let { lineNumber, column } = position;
      let hasChanged = false;
      if (lineNumber < 1) {
        lineNumber = 1;
        column = 1;
        hasChanged = true;
      } else if (lineNumber > this._lines.length) {
        lineNumber = this._lines.length;
        column = this._lines[lineNumber - 1].length + 1;
        hasChanged = true;
      } else {
        const maxCharacter = this._lines[lineNumber - 1].length + 1;
        if (column < 1) {
          column = 1;
          hasChanged = true;
        } else if (column > maxCharacter) {
          column = maxCharacter;
          hasChanged = true;
        }
      }
      if (!hasChanged) {
        return position;
      } else {
        return { lineNumber, column };
      }
    }
  }
  const _EditorWorker = class _EditorWorker {
    constructor(_foreignModule = null) {
      this._foreignModule = _foreignModule;
      this._requestHandlerBrand = void 0;
      this._workerTextModelSyncServer = new WorkerTextModelSyncServer();
    }
    dispose() {
    }
    async $ping() {
      return "pong";
    }
    _getModel(uri) {
      return this._workerTextModelSyncServer.getModel(uri);
    }
    getModels() {
      return this._workerTextModelSyncServer.getModels();
    }
    $acceptNewModel(data) {
      this._workerTextModelSyncServer.$acceptNewModel(data);
    }
    $acceptModelChanged(uri, e) {
      this._workerTextModelSyncServer.$acceptModelChanged(uri, e);
    }
    $acceptRemovedModel(uri) {
      this._workerTextModelSyncServer.$acceptRemovedModel(uri);
    }
    async $computeUnicodeHighlights(url, options, range2) {
      const model = this._getModel(url);
      if (!model) {
        return { ranges: [], hasMore: false, ambiguousCharacterCount: 0, invisibleCharacterCount: 0, nonBasicAsciiCharacterCount: 0 };
      }
      return UnicodeTextModelHighlighter.computeUnicodeHighlights(model, options, range2);
    }
    async $findSectionHeaders(url, options) {
      const model = this._getModel(url);
      if (!model) {
        return [];
      }
      return findSectionHeaders(model, options);
    }
    // ---- BEGIN diff --------------------------------------------------------------------------
    async $computeDiff(originalUrl, modifiedUrl, options, algorithm) {
      const original = this._getModel(originalUrl);
      const modified = this._getModel(modifiedUrl);
      if (!original || !modified) {
        return null;
      }
      const result = _EditorWorker.computeDiff(original, modified, options, algorithm);
      return result;
    }
    static computeDiff(originalTextModel, modifiedTextModel, options, algorithm) {
      const diffAlgorithm = algorithm === "advanced" ? linesDiffComputers.getDefault() : linesDiffComputers.getLegacy();
      const originalLines = originalTextModel.getLinesContent();
      const modifiedLines = modifiedTextModel.getLinesContent();
      const result = diffAlgorithm.computeDiff(originalLines, modifiedLines, options);
      const identical = result.changes.length > 0 ? false : this._modelsAreIdentical(originalTextModel, modifiedTextModel);
      function getLineChanges(changes) {
        return changes.map((m) => [m.original.startLineNumber, m.original.endLineNumberExclusive, m.modified.startLineNumber, m.modified.endLineNumberExclusive, m.innerChanges?.map((m2) => [
          m2.originalRange.startLineNumber,
          m2.originalRange.startColumn,
          m2.originalRange.endLineNumber,
          m2.originalRange.endColumn,
          m2.modifiedRange.startLineNumber,
          m2.modifiedRange.startColumn,
          m2.modifiedRange.endLineNumber,
          m2.modifiedRange.endColumn
        ])]);
      }
      return {
        identical,
        quitEarly: result.hitTimeout,
        changes: getLineChanges(result.changes),
        moves: result.moves.map((m) => [
          m.lineRangeMapping.original.startLineNumber,
          m.lineRangeMapping.original.endLineNumberExclusive,
          m.lineRangeMapping.modified.startLineNumber,
          m.lineRangeMapping.modified.endLineNumberExclusive,
          getLineChanges(m.changes)
        ])
      };
    }
    static _modelsAreIdentical(original, modified) {
      const originalLineCount = original.getLineCount();
      const modifiedLineCount = modified.getLineCount();
      if (originalLineCount !== modifiedLineCount) {
        return false;
      }
      for (let line = 1; line <= originalLineCount; line++) {
        const originalLine = original.getLineContent(line);
        const modifiedLine = modified.getLineContent(line);
        if (originalLine !== modifiedLine) {
          return false;
        }
      }
      return true;
    }
    async $computeMoreMinimalEdits(modelUrl, edits, pretty) {
      const model = this._getModel(modelUrl);
      if (!model) {
        return edits;
      }
      const result = [];
      let lastEol = void 0;
      edits = edits.slice(0).sort((a, b) => {
        if (a.range && b.range) {
          return Range$2.compareRangesUsingStarts(a.range, b.range);
        }
        const aRng = a.range ? 0 : 1;
        const bRng = b.range ? 0 : 1;
        return aRng - bRng;
      });
      let writeIndex = 0;
      for (let readIndex = 1; readIndex < edits.length; readIndex++) {
        if (Range$2.getEndPosition(edits[writeIndex].range).equals(Range$2.getStartPosition(edits[readIndex].range))) {
          edits[writeIndex].range = Range$2.fromPositions(Range$2.getStartPosition(edits[writeIndex].range), Range$2.getEndPosition(edits[readIndex].range));
          edits[writeIndex].text += edits[readIndex].text;
        } else {
          writeIndex++;
          edits[writeIndex] = edits[readIndex];
        }
      }
      edits.length = writeIndex + 1;
      for (let { range: range2, text: text2, eol } of edits) {
        if (typeof eol === "number") {
          lastEol = eol;
        }
        if (Range$2.isEmpty(range2) && !text2) {
          continue;
        }
        const original = model.getValueInRange(range2);
        text2 = text2.replace(/\r\n|\n|\r/g, model.eol);
        if (original === text2) {
          continue;
        }
        if (Math.max(text2.length, original.length) > _EditorWorker._diffLimit) {
          result.push({ range: range2, text: text2 });
          continue;
        }
        const changes = stringDiff(original, text2, pretty);
        const editOffset = model.offsetAt(Range$2.lift(range2).getStartPosition());
        for (const change of changes) {
          const start = model.positionAt(editOffset + change.originalStart);
          const end = model.positionAt(editOffset + change.originalStart + change.originalLength);
          const newEdit = {
            text: text2.substr(change.modifiedStart, change.modifiedLength),
            range: { startLineNumber: start.lineNumber, startColumn: start.column, endLineNumber: end.lineNumber, endColumn: end.column }
          };
          if (model.getValueInRange(newEdit.range) !== newEdit.text) {
            result.push(newEdit);
          }
        }
      }
      if (typeof lastEol === "number") {
        result.push({ eol: lastEol, text: "", range: { startLineNumber: 0, startColumn: 0, endLineNumber: 0, endColumn: 0 } });
      }
      return result;
    }
    // ---- END minimal edits ---------------------------------------------------------------
    async $computeLinks(modelUrl) {
      const model = this._getModel(modelUrl);
      if (!model) {
        return null;
      }
      return computeLinks(model);
    }
    // --- BEGIN default document colors -----------------------------------------------------------
    async $computeDefaultDocumentColors(modelUrl) {
      const model = this._getModel(modelUrl);
      if (!model) {
        return null;
      }
      return computeDefaultDocumentColors(model);
    }
    async $textualSuggest(modelUrls, leadingWord, wordDef, wordDefFlags) {
      const sw = new StopWatch();
      const wordDefRegExp = new RegExp(wordDef, wordDefFlags);
      const seen = /* @__PURE__ */ new Set();
      outer: for (const url of modelUrls) {
        const model = this._getModel(url);
        if (!model) {
          continue;
        }
        for (const word of model.words(wordDefRegExp)) {
          if (word === leadingWord || !isNaN(Number(word))) {
            continue;
          }
          seen.add(word);
          if (seen.size > _EditorWorker._suggestionsLimit) {
            break outer;
          }
        }
      }
      return { words: Array.from(seen), duration: sw.elapsed() };
    }
    // ---- END suggest --------------------------------------------------------------------------
    //#region -- word ranges --
    async $computeWordRanges(modelUrl, range2, wordDef, wordDefFlags) {
      const model = this._getModel(modelUrl);
      if (!model) {
        return /* @__PURE__ */ Object.create(null);
      }
      const wordDefRegExp = new RegExp(wordDef, wordDefFlags);
      const result = /* @__PURE__ */ Object.create(null);
      for (let line = range2.startLineNumber; line < range2.endLineNumber; line++) {
        const words = model.getLineWords(line, wordDefRegExp);
        for (const word of words) {
          if (!isNaN(Number(word.word))) {
            continue;
          }
          let array2 = result[word.word];
          if (!array2) {
            array2 = [];
            result[word.word] = array2;
          }
          array2.push({
            startLineNumber: line,
            startColumn: word.startColumn,
            endLineNumber: line,
            endColumn: word.endColumn
          });
        }
      }
      return result;
    }
    //#endregion
    async $navigateValueSet(modelUrl, range2, up, wordDef, wordDefFlags) {
      const model = this._getModel(modelUrl);
      if (!model) {
        return null;
      }
      const wordDefRegExp = new RegExp(wordDef, wordDefFlags);
      if (range2.startColumn === range2.endColumn) {
        range2 = {
          startLineNumber: range2.startLineNumber,
          startColumn: range2.startColumn,
          endLineNumber: range2.endLineNumber,
          endColumn: range2.endColumn + 1
        };
      }
      const selectionText = model.getValueInRange(range2);
      const wordRange = model.getWordAtPosition({ lineNumber: range2.startLineNumber, column: range2.startColumn }, wordDefRegExp);
      if (!wordRange) {
        return null;
      }
      const word = model.getValueInRange(wordRange);
      const result = BasicInplaceReplace.INSTANCE.navigateValueSet(range2, selectionText, wordRange, word, up);
      return result;
    }
    // ---- BEGIN foreign module support --------------------------------------------------------------------------
    // foreign method request
    $fmr(method, args) {
      if (!this._foreignModule || typeof this._foreignModule[method] !== "function") {
        return Promise.reject(new Error("Missing requestHandler or method: " + method));
      }
      try {
        return Promise.resolve(this._foreignModule[method].apply(this._foreignModule, args));
      } catch (e) {
        return Promise.reject(e);
      }
    }
  };
  _EditorWorker._diffLimit = 1e5;
  _EditorWorker._suggestionsLimit = 1e4;
  let EditorWorker = _EditorWorker;
  if (typeof importScripts === "function") {
    globalThis.monaco = createMonacoBaseAPI();
  }
  const _EditorWorkerHost = class _EditorWorkerHost {
    static getChannel(workerServer) {
      return workerServer.getChannel(_EditorWorkerHost.CHANNEL_NAME);
    }
    static setChannel(workerClient, obj) {
      workerClient.setChannel(_EditorWorkerHost.CHANNEL_NAME, obj);
    }
  };
  _EditorWorkerHost.CHANNEL_NAME = "editorWorkerHost";
  let EditorWorkerHost = _EditorWorkerHost;
  var __decorate$v = 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$u = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  const STOP_WORKER_DELTA_TIME_MS = 5 * 60 * 1e3;
  function canSyncModel(modelService, resource) {
    const model = modelService.getModel(resource);
    if (!model) {
      return false;
    }
    if (model.isTooLargeForSyncing()) {
      return false;
    }
    return true;
  }
  let EditorWorkerService = class EditorWorkerService extends Disposable {
    constructor(workerDescriptor, modelService, configurationService, logService, _languageConfigurationService, languageFeaturesService) {
      super();
      this._languageConfigurationService = _languageConfigurationService;
      this._modelService = modelService;
      this._workerManager = this._register(new WorkerManager(workerDescriptor, this._modelService));
      this._logService = logService;
      this._register(languageFeaturesService.linkProvider.register({ language: "*", hasAccessToAllModels: true }, {
        provideLinks: async (model, token) => {
          if (!canSyncModel(this._modelService, model.uri)) {
            return Promise.resolve({ links: [] });
          }
          const worker = await this._workerWithResources([model.uri]);
          const links = await worker.$computeLinks(model.uri.toString());
          return links && { links };
        }
      }));
      this._register(languageFeaturesService.completionProvider.register("*", new WordBasedCompletionItemProvider(this._workerManager, configurationService, this._modelService, this._languageConfigurationService, this._logService)));
    }
    dispose() {
      super.dispose();
    }
    canComputeUnicodeHighlights(uri) {
      return canSyncModel(this._modelService, uri);
    }
    async computedUnicodeHighlights(uri, options, range2) {
      const worker = await this._workerWithResources([uri]);
      return worker.$computeUnicodeHighlights(uri.toString(), options, range2);
    }
    async computeDiff(original, modified, options, algorithm) {
      const worker = await this._workerWithResources(
        [original, modified],
        /* forceLargeModels */
        true
      );
      const result = await worker.$computeDiff(original.toString(), modified.toString(), options, algorithm);
      if (!result) {
        return null;
      }
      const diff = {
        identical: result.identical,
        quitEarly: result.quitEarly,
        changes: toLineRangeMappings(result.changes),
        moves: result.moves.map((m) => new MovedText(new LineRangeMapping(new LineRange(m[0], m[1]), new LineRange(m[2], m[3])), toLineRangeMappings(m[4])))
      };
      return diff;
      function toLineRangeMappings(changes) {
        return changes.map((c) => new DetailedLineRangeMapping(new LineRange(c[0], c[1]), new LineRange(c[2], c[3]), c[4]?.map((c2) => new RangeMapping(new Range$2(c2[0], c2[1], c2[2], c2[3]), new Range$2(c2[4], c2[5], c2[6], c2[7])))));
      }
    }
    async computeMoreMinimalEdits(resource, edits, pretty = false) {
      if (isNonEmptyArray(edits)) {
        if (!canSyncModel(this._modelService, resource)) {
          return Promise.resolve(edits);
        }
        const sw = StopWatch.create();
        const result = this._workerWithResources([resource]).then((worker) => worker.$computeMoreMinimalEdits(resource.toString(), edits, pretty));
        result.finally(() => this._logService.trace("FORMAT#computeMoreMinimalEdits", resource.toString(true), sw.elapsed()));
        return Promise.race([result, timeout(1e3).then(() => edits)]);
      } else {
        return Promise.resolve(void 0);
      }
    }
    canNavigateValueSet(resource) {
      return canSyncModel(this._modelService, resource);
    }
    async navigateValueSet(resource, range2, up) {
      const model = this._modelService.getModel(resource);
      if (!model) {
        return null;
      }
      const wordDefRegExp = this._languageConfigurationService.getLanguageConfiguration(model.getLanguageId()).getWordDefinition();
      const wordDef = wordDefRegExp.source;
      const wordDefFlags = wordDefRegExp.flags;
      const worker = await this._workerWithResources([resource]);
      return worker.$navigateValueSet(resource.toString(), range2, up, wordDef, wordDefFlags);
    }
    canComputeWordRanges(resource) {
      return canSyncModel(this._modelService, resource);
    }
    async computeWordRanges(resource, range2) {
      const model = this._modelService.getModel(resource);
      if (!model) {
        return Promise.resolve(null);
      }
      const wordDefRegExp = this._languageConfigurationService.getLanguageConfiguration(model.getLanguageId()).getWordDefinition();
      const wordDef = wordDefRegExp.source;
      const wordDefFlags = wordDefRegExp.flags;
      const worker = await this._workerWithResources([resource]);
      return worker.$computeWordRanges(resource.toString(), range2, wordDef, wordDefFlags);
    }
    async findSectionHeaders(uri, options) {
      const worker = await this._workerWithResources([uri]);
      return worker.$findSectionHeaders(uri.toString(), options);
    }
    async computeDefaultDocumentColors(uri) {
      const worker = await this._workerWithResources([uri]);
      return worker.$computeDefaultDocumentColors(uri.toString());
    }
    async _workerWithResources(resources, forceLargeModels = false) {
      const worker = await this._workerManager.withWorker();
      return await worker.workerWithSyncedResources(resources, forceLargeModels);
    }
  };
  EditorWorkerService = __decorate$v([
    __param$u(1, IModelService),
    __param$u(2, ITextResourceConfigurationService),
    __param$u(3, ILogService),
    __param$u(4, ILanguageConfigurationService),
    __param$u(5, ILanguageFeaturesService)
  ], EditorWorkerService);
  class WordBasedCompletionItemProvider {
    constructor(workerManager, configurationService, modelService, languageConfigurationService, logService) {
      this.languageConfigurationService = languageConfigurationService;
      this.logService = logService;
      this._debugDisplayName = "wordbasedCompletions";
      this._workerManager = workerManager;
      this._configurationService = configurationService;
      this._modelService = modelService;
    }
    async provideCompletionItems(model, position) {
      const config = this._configurationService.getValue(model.uri, position, "editor");
      if (config.wordBasedSuggestions === "off") {
        return void 0;
      }
      const models = [];
      if (config.wordBasedSuggestions === "currentDocument") {
        if (canSyncModel(this._modelService, model.uri)) {
          models.push(model.uri);
        }
      } else {
        for (const candidate of this._modelService.getModels()) {
          if (!canSyncModel(this._modelService, candidate.uri)) {
            continue;
          }
          if (candidate === model) {
            models.unshift(candidate.uri);
          } else if (config.wordBasedSuggestions === "allDocuments" || candidate.getLanguageId() === model.getLanguageId()) {
            models.push(candidate.uri);
          }
        }
      }
      if (models.length === 0) {
        return void 0;
      }
      const wordDefRegExp = this.languageConfigurationService.getLanguageConfiguration(model.getLanguageId()).getWordDefinition();
      const word = model.getWordAtPosition(position);
      const replace = !word ? Range$2.fromPositions(position) : new Range$2(position.lineNumber, word.startColumn, position.lineNumber, word.endColumn);
      const insert = replace.setEndPosition(position.lineNumber, position.column);
      this.logService.trace("[WordBasedCompletionItemProvider]", `word: "${word?.word || ""}", wordDef: "${wordDefRegExp}", replace: [${replace.toString()}], insert: [${insert.toString()}]`);
      const client = await this._workerManager.withWorker();
      const data = await client.textualSuggest(models, word?.word, wordDefRegExp);
      if (!data) {
        return void 0;
      }
      return {
        duration: data.duration,
        suggestions: data.words.map((word2) => {
          return {
            kind: 18,
            label: word2,
            insertText: word2,
            range: { insert, replace }
          };
        })
      };
    }
  }
  let WorkerManager = class WorkerManager extends Disposable {
    constructor(_workerDescriptor, modelService) {
      super();
      this._workerDescriptor = _workerDescriptor;
      this._modelService = modelService;
      this._editorWorkerClient = null;
      this._lastWorkerUsedTime = (/* @__PURE__ */ new Date()).getTime();
      const stopWorkerInterval = this._register(new WindowIntervalTimer());
      stopWorkerInterval.cancelAndSet(() => this._checkStopIdleWorker(), Math.round(STOP_WORKER_DELTA_TIME_MS / 2), mainWindow);
      this._register(this._modelService.onModelRemoved((_) => this._checkStopEmptyWorker()));
    }
    dispose() {
      if (this._editorWorkerClient) {
        this._editorWorkerClient.dispose();
        this._editorWorkerClient = null;
      }
      super.dispose();
    }
    /**
     * Check if the model service has no more models and stop the worker if that is the case.
     */
    _checkStopEmptyWorker() {
      if (!this._editorWorkerClient) {
        return;
      }
      const models = this._modelService.getModels();
      if (models.length === 0) {
        this._editorWorkerClient.dispose();
        this._editorWorkerClient = null;
      }
    }
    /**
     * Check if the worker has been idle for a while and then stop it.
     */
    _checkStopIdleWorker() {
      if (!this._editorWorkerClient) {
        return;
      }
      const timeSinceLastWorkerUsedTime = (/* @__PURE__ */ new Date()).getTime() - this._lastWorkerUsedTime;
      if (timeSinceLastWorkerUsedTime > STOP_WORKER_DELTA_TIME_MS) {
        this._editorWorkerClient.dispose();
        this._editorWorkerClient = null;
      }
    }
    withWorker() {
      this._lastWorkerUsedTime = (/* @__PURE__ */ new Date()).getTime();
      if (!this._editorWorkerClient) {
        this._editorWorkerClient = new EditorWorkerClient(this._workerDescriptor, false, this._modelService);
      }
      return Promise.resolve(this._editorWorkerClient);
    }
  };
  WorkerManager = __decorate$v([
    __param$u(1, IModelService)
  ], WorkerManager);
  class SynchronousWorkerClient {
    constructor(instance) {
      this._instance = instance;
      this.proxy = this._instance;
    }
    dispose() {
      this._instance.dispose();
    }
    setChannel(channel, handler) {
      throw new Error(`Not supported`);
    }
  }
  let EditorWorkerClient = class EditorWorkerClient extends Disposable {
    constructor(_workerDescriptorOrWorker, keepIdleModels, modelService) {
      super();
      this._workerDescriptorOrWorker = _workerDescriptorOrWorker;
      this._disposed = false;
      this._modelService = modelService;
      this._keepIdleModels = keepIdleModels;
      this._worker = null;
      this._modelManager = null;
    }
    // foreign host request
    fhr(method, args) {
      throw new Error(`Not implemented!`);
    }
    _getOrCreateWorker() {
      if (!this._worker) {
        try {
          this._worker = this._register(createWebWorker$2(this._workerDescriptorOrWorker));
          EditorWorkerHost.setChannel(this._worker, this._createEditorWorkerHost());
        } catch (err) {
          logOnceWebWorkerWarning(err);
          this._worker = this._createFallbackLocalWorker();
        }
      }
      return this._worker;
    }
    async _getProxy() {
      try {
        const proxy = this._getOrCreateWorker().proxy;
        await proxy.$ping();
        return proxy;
      } catch (err) {
        logOnceWebWorkerWarning(err);
        this._worker = this._createFallbackLocalWorker();
        return this._worker.proxy;
      }
    }
    _createFallbackLocalWorker() {
      return new SynchronousWorkerClient(new EditorWorker(null));
    }
    _createEditorWorkerHost() {
      return {
        $fhr: (method, args) => this.fhr(method, args)
      };
    }
    _getOrCreateModelManager(proxy) {
      if (!this._modelManager) {
        this._modelManager = this._register(new WorkerTextModelSyncClient(proxy, this._modelService, this._keepIdleModels));
      }
      return this._modelManager;
    }
    async workerWithSyncedResources(resources, forceLargeModels = false) {
      if (this._disposed) {
        return Promise.reject(canceled());
      }
      const proxy = await this._getProxy();
      this._getOrCreateModelManager(proxy).ensureSyncedResources(resources, forceLargeModels);
      return proxy;
    }
    async textualSuggest(resources, leadingWord, wordDefRegExp) {
      const proxy = await this.workerWithSyncedResources(resources);
      const wordDef = wordDefRegExp.source;
      const wordDefFlags = wordDefRegExp.flags;
      return proxy.$textualSuggest(resources.map((r) => r.toString()), leadingWord, wordDef, wordDefFlags);
    }
    dispose() {
      super.dispose();
      this._disposed = true;
    }
  };
  EditorWorkerClient = __decorate$v([
    __param$u(2, IModelService)
  ], EditorWorkerClient);
  function createWebWorker$1(modelService, opts) {
    return new MonacoWebWorkerImpl(modelService, opts);
  }
  class MonacoWebWorkerImpl extends EditorWorkerClient {
    constructor(modelService, opts) {
      super(opts.worker, opts.keepIdleModels || false, modelService);
      this._foreignModuleHost = opts.host || null;
      this._foreignProxy = this._getProxy().then((proxy) => {
        return new Proxy({}, {
          get(target, prop, receiver) {
            if (prop === "then") {
              return void 0;
            }
            if (typeof prop !== "string") {
              throw new Error(`Not supported`);
            }
            return (...args) => {
              return proxy.$fmr(prop, args);
            };
          }
        });
      });
    }
    // foreign host request
    fhr(method, args) {
      if (!this._foreignModuleHost || typeof this._foreignModuleHost[method] !== "function") {
        return Promise.reject(new Error("Missing method " + method + " or missing main thread foreign host."));
      }
      try {
        return Promise.resolve(this._foreignModuleHost[method].apply(this._foreignModuleHost, args));
      } catch (e) {
        return Promise.reject(e);
      }
    }
    getProxy() {
      return this._foreignProxy;
    }
    withSyncedResources(resources) {
      return this.workerWithSyncedResources(resources).then((_) => this.getProxy());
    }
  }
  function isFuzzyActionArr(what) {
    return Array.isArray(what);
  }
  function isFuzzyAction(what) {
    return !isFuzzyActionArr(what);
  }
  function isString(what) {
    return typeof what === "string";
  }
  function isIAction(what) {
    return !isString(what);
  }
  function empty(s) {
    return s ? false : true;
  }
  function fixCase(lexer2, str) {
    return lexer2.ignoreCase && str ? str.toLowerCase() : str;
  }
  function sanitize(s) {
    return s.replace(/[&<>'"_]/g, "-");
  }
  function log(lexer2, msg) {
    console.log(`${lexer2.languageId}: ${msg}`);
  }
  function createError(lexer2, msg) {
    return new Error(`${lexer2.languageId}: ${msg}`);
  }
  function substituteMatches(lexer2, str, id, matches, state) {
    const re = /\$((\$)|(#)|(\d\d?)|[sS](\d\d?)|@(\w+))/g;
    let stateMatches = null;
    return str.replace(re, function(full, sub, dollar, hash2, n2, s, attr, ofs, total) {
      if (!empty(dollar)) {
        return "$";
      }
      if (!empty(hash2)) {
        return fixCase(lexer2, id);
      }
      if (!empty(n2) && n2 < matches.length) {
        return fixCase(lexer2, matches[n2]);
      }
      if (!empty(attr) && lexer2 && typeof lexer2[attr] === "string") {
        return lexer2[attr];
      }
      if (stateMatches === null) {
        stateMatches = state.split(".");
        stateMatches.unshift(state);
      }
      if (!empty(s) && s < stateMatches.length) {
        return fixCase(lexer2, stateMatches[s]);
      }
      return "";
    });
  }
  function substituteMatchesRe(lexer2, str, state) {
    const re = /\$[sS](\d\d?)/g;
    let stateMatches = null;
    return str.replace(re, function(full, s) {
      if (stateMatches === null) {
        stateMatches = state.split(".");
        stateMatches.unshift(state);
      }
      if (!empty(s) && s < stateMatches.length) {
        return escapeRegExpCharacters(fixCase(lexer2, stateMatches[s]));
      }
      return "";
    });
  }
  function findRules(lexer2, inState) {
    let state = inState;
    while (state && state.length > 0) {
      const rules = lexer2.tokenizer[state];
      if (rules) {
        return rules;
      }
      const idx = state.lastIndexOf(".");
      if (idx < 0) {
        state = null;
      } else {
        state = state.substr(0, idx);
      }
    }
    return null;
  }
  function stateExists(lexer2, inState) {
    let state = inState;
    while (state && state.length > 0) {
      const exist = lexer2.stateNames[state];
      if (exist) {
        return true;
      }
      const idx = state.lastIndexOf(".");
      if (idx < 0) {
        state = null;
      } else {
        state = state.substr(0, idx);
      }
    }
    return false;
  }
  var __decorate$u = 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$t = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  var MonarchTokenizer_1;
  const CACHE_STACK_DEPTH = 5;
  const _MonarchStackElementFactory = class _MonarchStackElementFactory {
    static create(parent, state) {
      return this._INSTANCE.create(parent, state);
    }
    constructor(maxCacheDepth) {
      this._maxCacheDepth = maxCacheDepth;
      this._entries = /* @__PURE__ */ Object.create(null);
    }
    create(parent, state) {
      if (parent !== null && parent.depth >= this._maxCacheDepth) {
        return new MonarchStackElement(parent, state);
      }
      let stackElementId = MonarchStackElement.getStackElementId(parent);
      if (stackElementId.length > 0) {
        stackElementId += "|";
      }
      stackElementId += state;
      let result = this._entries[stackElementId];
      if (result) {
        return result;
      }
      result = new MonarchStackElement(parent, state);
      this._entries[stackElementId] = result;
      return result;
    }
  };
  _MonarchStackElementFactory._INSTANCE = new _MonarchStackElementFactory(CACHE_STACK_DEPTH);
  let MonarchStackElementFactory = _MonarchStackElementFactory;
  class MonarchStackElement {
    constructor(parent, state) {
      this.parent = parent;
      this.state = state;
      this.depth = (this.parent ? this.parent.depth : 0) + 1;
    }
    static getStackElementId(element) {
      let result = "";
      while (element !== null) {
        if (result.length > 0) {
          result += "|";
        }
        result += element.state;
        element = element.parent;
      }
      return result;
    }
    static _equals(a, b) {
      while (a !== null && b !== null) {
        if (a === b) {
          return true;
        }
        if (a.state !== b.state) {
          return false;
        }
        a = a.parent;
        b = b.parent;
      }
      if (a === null && b === null) {
        return true;
      }
      return false;
    }
    equals(other) {
      return MonarchStackElement._equals(this, other);
    }
    push(state) {
      return MonarchStackElementFactory.create(this, state);
    }
    pop() {
      return this.parent;
    }
    popall() {
      let result = this;
      while (result.parent) {
        result = result.parent;
      }
      return result;
    }
    switchTo(state) {
      return MonarchStackElementFactory.create(this.parent, state);
    }
  }
  class EmbeddedLanguageData {
    constructor(languageId, state) {
      this.languageId = languageId;
      this.state = state;
    }
    equals(other) {
      return this.languageId === other.languageId && this.state.equals(other.state);
    }
    clone() {
      const stateClone = this.state.clone();
      if (stateClone === this.state) {
        return this;
      }
      return new EmbeddedLanguageData(this.languageId, this.state);
    }
  }
  const _MonarchLineStateFactory = class _MonarchLineStateFactory {
    static create(stack, embeddedLanguageData) {
      return this._INSTANCE.create(stack, embeddedLanguageData);
    }
    constructor(maxCacheDepth) {
      this._maxCacheDepth = maxCacheDepth;
      this._entries = /* @__PURE__ */ Object.create(null);
    }
    create(stack, embeddedLanguageData) {
      if (embeddedLanguageData !== null) {
        return new MonarchLineState(stack, embeddedLanguageData);
      }
      if (stack !== null && stack.depth >= this._maxCacheDepth) {
        return new MonarchLineState(stack, embeddedLanguageData);
      }
      const stackElementId = MonarchStackElement.getStackElementId(stack);
      let result = this._entries[stackElementId];
      if (result) {
        return result;
      }
      result = new MonarchLineState(stack, null);
      this._entries[stackElementId] = result;
      return result;
    }
  };
  _MonarchLineStateFactory._INSTANCE = new _MonarchLineStateFactory(CACHE_STACK_DEPTH);
  let MonarchLineStateFactory = _MonarchLineStateFactory;
  class MonarchLineState {
    constructor(stack, embeddedLanguageData) {
      this.stack = stack;
      this.embeddedLanguageData = embeddedLanguageData;
    }
    clone() {
      const embeddedlanguageDataClone = this.embeddedLanguageData ? this.embeddedLanguageData.clone() : null;
      if (embeddedlanguageDataClone === this.embeddedLanguageData) {
        return this;
      }
      return MonarchLineStateFactory.create(this.stack, this.embeddedLanguageData);
    }
    equals(other) {
      if (!(other instanceof MonarchLineState)) {
        return false;
      }
      if (!this.stack.equals(other.stack)) {
        return false;
      }
      if (this.embeddedLanguageData === null && other.embeddedLanguageData === null) {
        return true;
      }
      if (this.embeddedLanguageData === null || other.embeddedLanguageData === null) {
        return false;
      }
      return this.embeddedLanguageData.equals(other.embeddedLanguageData);
    }
  }
  class MonarchClassicTokensCollector {
    constructor() {
      this._tokens = [];
      this._languageId = null;
      this._lastTokenType = null;
      this._lastTokenLanguage = null;
    }
    enterLanguage(languageId) {
      this._languageId = languageId;
    }
    emit(startOffset, type) {
      if (this._lastTokenType === type && this._lastTokenLanguage === this._languageId) {
        return;
      }
      this._lastTokenType = type;
      this._lastTokenLanguage = this._languageId;
      this._tokens.push(new Token$2(startOffset, type, this._languageId));
    }
    nestedLanguageTokenize(embeddedLanguageLine, hasEOL, embeddedLanguageData, offsetDelta) {
      const nestedLanguageId = embeddedLanguageData.languageId;
      const embeddedModeState = embeddedLanguageData.state;
      const nestedLanguageTokenizationSupport = TokenizationRegistry.get(nestedLanguageId);
      if (!nestedLanguageTokenizationSupport) {
        this.enterLanguage(nestedLanguageId);
        this.emit(offsetDelta, "");
        return embeddedModeState;
      }
      const nestedResult = nestedLanguageTokenizationSupport.tokenize(embeddedLanguageLine, hasEOL, embeddedModeState);
      if (offsetDelta !== 0) {
        for (const token of nestedResult.tokens) {
          this._tokens.push(new Token$2(token.offset + offsetDelta, token.type, token.language));
        }
      } else {
        this._tokens = this._tokens.concat(nestedResult.tokens);
      }
      this._lastTokenType = null;
      this._lastTokenLanguage = null;
      this._languageId = null;
      return nestedResult.endState;
    }
    finalize(endState) {
      return new TokenizationResult(this._tokens, endState);
    }
  }
  class MonarchModernTokensCollector {
    constructor(languageService, theme) {
      this._languageService = languageService;
      this._theme = theme;
      this._prependTokens = null;
      this._tokens = [];
      this._currentLanguageId = 0;
      this._lastTokenMetadata = 0;
    }
    enterLanguage(languageId) {
      this._currentLanguageId = this._languageService.languageIdCodec.encodeLanguageId(languageId);
    }
    emit(startOffset, type) {
      const metadata = this._theme.match(this._currentLanguageId, type) | 1024;
      if (this._lastTokenMetadata === metadata) {
        return;
      }
      this._lastTokenMetadata = metadata;
      this._tokens.push(startOffset);
      this._tokens.push(metadata);
    }
    static _merge(a, b, c) {
      const aLen = a !== null ? a.length : 0;
      const bLen = b.length;
      const cLen = c !== null ? c.length : 0;
      if (aLen === 0 && bLen === 0 && cLen === 0) {
        return new Uint32Array(0);
      }
      if (aLen === 0 && bLen === 0) {
        return c;
      }
      if (bLen === 0 && cLen === 0) {
        return a;
      }
      const result = new Uint32Array(aLen + bLen + cLen);
      if (a !== null) {
        result.set(a);
      }
      for (let i2 = 0; i2 < bLen; i2++) {
        result[aLen + i2] = b[i2];
      }
      if (c !== null) {
        result.set(c, aLen + bLen);
      }
      return result;
    }
    nestedLanguageTokenize(embeddedLanguageLine, hasEOL, embeddedLanguageData, offsetDelta) {
      const nestedLanguageId = embeddedLanguageData.languageId;
      const embeddedModeState = embeddedLanguageData.state;
      const nestedLanguageTokenizationSupport = TokenizationRegistry.get(nestedLanguageId);
      if (!nestedLanguageTokenizationSupport) {
        this.enterLanguage(nestedLanguageId);
        this.emit(offsetDelta, "");
        return embeddedModeState;
      }
      const nestedResult = nestedLanguageTokenizationSupport.tokenizeEncoded(embeddedLanguageLine, hasEOL, embeddedModeState);
      if (offsetDelta !== 0) {
        for (let i2 = 0, len = nestedResult.tokens.length; i2 < len; i2 += 2) {
          nestedResult.tokens[i2] += offsetDelta;
        }
      }
      this._prependTokens = MonarchModernTokensCollector._merge(this._prependTokens, this._tokens, nestedResult.tokens);
      this._tokens = [];
      this._currentLanguageId = 0;
      this._lastTokenMetadata = 0;
      return nestedResult.endState;
    }
    finalize(endState) {
      return new EncodedTokenizationResult(MonarchModernTokensCollector._merge(this._prependTokens, this._tokens, null), endState);
    }
  }
  let MonarchTokenizer = MonarchTokenizer_1 = class MonarchTokenizer extends Disposable {
    constructor(languageService, standaloneThemeService, languageId, lexer2, _configurationService) {
      super();
      this._configurationService = _configurationService;
      this._languageService = languageService;
      this._standaloneThemeService = standaloneThemeService;
      this._languageId = languageId;
      this._lexer = lexer2;
      this._embeddedLanguages = /* @__PURE__ */ Object.create(null);
      this.embeddedLoaded = Promise.resolve(void 0);
      let emitting = false;
      this._register(TokenizationRegistry.onDidChange((e) => {
        if (emitting) {
          return;
        }
        let isOneOfMyEmbeddedModes = false;
        for (let i2 = 0, len = e.changedLanguages.length; i2 < len; i2++) {
          const language2 = e.changedLanguages[i2];
          if (this._embeddedLanguages[language2]) {
            isOneOfMyEmbeddedModes = true;
            break;
          }
        }
        if (isOneOfMyEmbeddedModes) {
          emitting = true;
          TokenizationRegistry.handleChange([this._languageId]);
          emitting = false;
        }
      }));
      this._maxTokenizationLineLength = this._configurationService.getValue("editor.maxTokenizationLineLength", {
        overrideIdentifier: this._languageId
      });
      this._register(this._configurationService.onDidChangeConfiguration((e) => {
        if (e.affectsConfiguration("editor.maxTokenizationLineLength")) {
          this._maxTokenizationLineLength = this._configurationService.getValue("editor.maxTokenizationLineLength", {
            overrideIdentifier: this._languageId
          });
        }
      }));
    }
    getLoadStatus() {
      const promises = [];
      for (const nestedLanguageId in this._embeddedLanguages) {
        const tokenizationSupport = TokenizationRegistry.get(nestedLanguageId);
        if (tokenizationSupport) {
          if (tokenizationSupport instanceof MonarchTokenizer_1) {
            const nestedModeStatus = tokenizationSupport.getLoadStatus();
            if (nestedModeStatus.loaded === false) {
              promises.push(nestedModeStatus.promise);
            }
          }
          continue;
        }
        if (!TokenizationRegistry.isResolved(nestedLanguageId)) {
          promises.push(TokenizationRegistry.getOrCreate(nestedLanguageId));
        }
      }
      if (promises.length === 0) {
        return {
          loaded: true
        };
      }
      return {
        loaded: false,
        promise: Promise.all(promises).then((_) => void 0)
      };
    }
    getInitialState() {
      const rootState = MonarchStackElementFactory.create(null, this._lexer.start);
      return MonarchLineStateFactory.create(rootState, null);
    }
    tokenize(line, hasEOL, lineState) {
      if (line.length >= this._maxTokenizationLineLength) {
        return nullTokenize(this._languageId, lineState);
      }
      const tokensCollector = new MonarchClassicTokensCollector();
      const endLineState = this._tokenize(line, hasEOL, lineState, tokensCollector);
      return tokensCollector.finalize(endLineState);
    }
    tokenizeEncoded(line, hasEOL, lineState) {
      if (line.length >= this._maxTokenizationLineLength) {
        return nullTokenizeEncoded(this._languageService.languageIdCodec.encodeLanguageId(this._languageId), lineState);
      }
      const tokensCollector = new MonarchModernTokensCollector(this._languageService, this._standaloneThemeService.getColorTheme().tokenTheme);
      const endLineState = this._tokenize(line, hasEOL, lineState, tokensCollector);
      return tokensCollector.finalize(endLineState);
    }
    _tokenize(line, hasEOL, lineState, collector) {
      if (lineState.embeddedLanguageData) {
        return this._nestedTokenize(line, hasEOL, lineState, 0, collector);
      } else {
        return this._myTokenize(line, hasEOL, lineState, 0, collector);
      }
    }
    _findLeavingNestedLanguageOffset(line, state) {
      let rules = this._lexer.tokenizer[state.stack.state];
      if (!rules) {
        rules = findRules(this._lexer, state.stack.state);
        if (!rules) {
          throw createError(this._lexer, "tokenizer state is not defined: " + state.stack.state);
        }
      }
      let popOffset = -1;
      let hasEmbeddedPopRule = false;
      for (const rule of rules) {
        if (!isIAction(rule.action) || !(rule.action.nextEmbedded === "@pop" || rule.action.hasEmbeddedEndInCases)) {
          continue;
        }
        hasEmbeddedPopRule = true;
        let regex = rule.resolveRegex(state.stack.state);
        const regexSource = regex.source;
        if (regexSource.substr(0, 4) === "^(?:" && regexSource.substr(regexSource.length - 1, 1) === ")") {
          const flags = (regex.ignoreCase ? "i" : "") + (regex.unicode ? "u" : "");
          regex = new RegExp(regexSource.substr(4, regexSource.length - 5), flags);
        }
        const result = line.search(regex);
        if (result === -1 || result !== 0 && rule.matchOnlyAtLineStart) {
          continue;
        }
        if (popOffset === -1 || result < popOffset) {
          popOffset = result;
        }
      }
      if (!hasEmbeddedPopRule) {
        throw createError(this._lexer, 'no rule containing nextEmbedded: "@pop" in tokenizer embedded state: ' + state.stack.state);
      }
      return popOffset;
    }
    _nestedTokenize(line, hasEOL, lineState, offsetDelta, tokensCollector) {
      const popOffset = this._findLeavingNestedLanguageOffset(line, lineState);
      if (popOffset === -1) {
        const nestedEndState = tokensCollector.nestedLanguageTokenize(line, hasEOL, lineState.embeddedLanguageData, offsetDelta);
        return MonarchLineStateFactory.create(lineState.stack, new EmbeddedLanguageData(lineState.embeddedLanguageData.languageId, nestedEndState));
      }
      const nestedLanguageLine = line.substring(0, popOffset);
      if (nestedLanguageLine.length > 0) {
        tokensCollector.nestedLanguageTokenize(nestedLanguageLine, false, lineState.embeddedLanguageData, offsetDelta);
      }
      const restOfTheLine = line.substring(popOffset);
      return this._myTokenize(restOfTheLine, hasEOL, lineState, offsetDelta + popOffset, tokensCollector);
    }
    _safeRuleName(rule) {
      if (rule) {
        return rule.name;
      }
      return "(unknown)";
    }
    _myTokenize(lineWithoutLF, hasEOL, lineState, offsetDelta, tokensCollector) {
      tokensCollector.enterLanguage(this._languageId);
      const lineWithoutLFLength = lineWithoutLF.length;
      const line = hasEOL && this._lexer.includeLF ? lineWithoutLF + "\n" : lineWithoutLF;
      const lineLength = line.length;
      let embeddedLanguageData = lineState.embeddedLanguageData;
      let stack = lineState.stack;
      let pos = 0;
      let groupMatching = null;
      let forceEvaluation = true;
      while (forceEvaluation || pos < lineLength) {
        const pos0 = pos;
        const stackLen0 = stack.depth;
        const groupLen0 = groupMatching ? groupMatching.groups.length : 0;
        const state = stack.state;
        let matches = null;
        let matched = null;
        let action = null;
        let rule = null;
        let enteringEmbeddedLanguage = null;
        if (groupMatching) {
          matches = groupMatching.matches;
          const groupEntry = groupMatching.groups.shift();
          matched = groupEntry.matched;
          action = groupEntry.action;
          rule = groupMatching.rule;
          if (groupMatching.groups.length === 0) {
            groupMatching = null;
          }
        } else {
          if (!forceEvaluation && pos >= lineLength) {
            break;
          }
          forceEvaluation = false;
          let rules = this._lexer.tokenizer[state];
          if (!rules) {
            rules = findRules(this._lexer, state);
            if (!rules) {
              throw createError(this._lexer, "tokenizer state is not defined: " + state);
            }
          }
          const restOfLine = line.substr(pos);
          for (const rule2 of rules) {
            if (pos === 0 || !rule2.matchOnlyAtLineStart) {
              matches = restOfLine.match(rule2.resolveRegex(state));
              if (matches) {
                matched = matches[0];
                action = rule2.action;
                break;
              }
            }
          }
        }
        if (!matches) {
          matches = [""];
          matched = "";
        }
        if (!action) {
          if (pos < lineLength) {
            matches = [line.charAt(pos)];
            matched = matches[0];
          }
          action = this._lexer.defaultToken;
        }
        if (matched === null) {
          break;
        }
        pos += matched.length;
        while (isFuzzyAction(action) && isIAction(action) && action.test) {
          action = action.test(matched, matches, state, pos === lineLength);
        }
        let result = null;
        if (typeof action === "string" || Array.isArray(action)) {
          result = action;
        } else if (action.group) {
          result = action.group;
        } else if (action.token !== null && action.token !== void 0) {
          if (action.tokenSubst) {
            result = substituteMatches(this._lexer, action.token, matched, matches, state);
          } else {
            result = action.token;
          }
          if (action.nextEmbedded) {
            if (action.nextEmbedded === "@pop") {
              if (!embeddedLanguageData) {
                throw createError(this._lexer, "cannot pop embedded language if not inside one");
              }
              embeddedLanguageData = null;
            } else if (embeddedLanguageData) {
              throw createError(this._lexer, "cannot enter embedded language from within an embedded language");
            } else {
              enteringEmbeddedLanguage = substituteMatches(this._lexer, action.nextEmbedded, matched, matches, state);
            }
          }
          if (action.goBack) {
            pos = Math.max(0, pos - action.goBack);
          }
          if (action.switchTo && typeof action.switchTo === "string") {
            let nextState = substituteMatches(this._lexer, action.switchTo, matched, matches, state);
            if (nextState[0] === "@") {
              nextState = nextState.substr(1);
            }
            if (!findRules(this._lexer, nextState)) {
              throw createError(this._lexer, "trying to switch to a state '" + nextState + "' that is undefined in rule: " + this._safeRuleName(rule));
            } else {
              stack = stack.switchTo(nextState);
            }
          } else if (action.transform && typeof action.transform === "function") {
            throw createError(this._lexer, "action.transform not supported");
          } else if (action.next) {
            if (action.next === "@push") {
              if (stack.depth >= this._lexer.maxStack) {
                throw createError(this._lexer, "maximum tokenizer stack size reached: [" + stack.state + "," + stack.parent.state + ",...]");
              } else {
                stack = stack.push(state);
              }
            } else if (action.next === "@pop") {
              if (stack.depth <= 1) {
                throw createError(this._lexer, "trying to pop an empty stack in rule: " + this._safeRuleName(rule));
              } else {
                stack = stack.pop();
              }
            } else if (action.next === "@popall") {
              stack = stack.popall();
            } else {
              let nextState = substituteMatches(this._lexer, action.next, matched, matches, state);
              if (nextState[0] === "@") {
                nextState = nextState.substr(1);
              }
              if (!findRules(this._lexer, nextState)) {
                throw createError(this._lexer, "trying to set a next state '" + nextState + "' that is undefined in rule: " + this._safeRuleName(rule));
              } else {
                stack = stack.push(nextState);
              }
            }
          }
          if (action.log && typeof action.log === "string") {
            log(this._lexer, this._lexer.languageId + ": " + substituteMatches(this._lexer, action.log, matched, matches, state));
          }
        }
        if (result === null) {
          throw createError(this._lexer, "lexer rule has no well-defined action in rule: " + this._safeRuleName(rule));
        }
        const computeNewStateForEmbeddedLanguage = (enteringEmbeddedLanguage2) => {
          const languageId = this._languageService.getLanguageIdByLanguageName(enteringEmbeddedLanguage2) || this._languageService.getLanguageIdByMimeType(enteringEmbeddedLanguage2) || enteringEmbeddedLanguage2;
          const embeddedLanguageData2 = this._getNestedEmbeddedLanguageData(languageId);
          if (pos < lineLength) {
            const restOfLine = lineWithoutLF.substr(pos);
            return this._nestedTokenize(restOfLine, hasEOL, MonarchLineStateFactory.create(stack, embeddedLanguageData2), offsetDelta + pos, tokensCollector);
          } else {
            return MonarchLineStateFactory.create(stack, embeddedLanguageData2);
          }
        };
        if (Array.isArray(result)) {
          if (groupMatching && groupMatching.groups.length > 0) {
            throw createError(this._lexer, "groups cannot be nested: " + this._safeRuleName(rule));
          }
          if (matches.length !== result.length + 1) {
            throw createError(this._lexer, "matched number of groups does not match the number of actions in rule: " + this._safeRuleName(rule));
          }
          let totalLen = 0;
          for (let i2 = 1; i2 < matches.length; i2++) {
            totalLen += matches[i2].length;
          }
          if (totalLen !== matched.length) {
            throw createError(this._lexer, "with groups, all characters should be matched in consecutive groups in rule: " + this._safeRuleName(rule));
          }
          groupMatching = {
            rule,
            matches,
            groups: []
          };
          for (let i2 = 0; i2 < result.length; i2++) {
            groupMatching.groups[i2] = {
              action: result[i2],
              matched: matches[i2 + 1]
            };
          }
          pos -= matched.length;
          continue;
        } else {
          if (result === "@rematch") {
            pos -= matched.length;
            matched = "";
            matches = null;
            result = "";
            if (enteringEmbeddedLanguage !== null) {
              return computeNewStateForEmbeddedLanguage(enteringEmbeddedLanguage);
            }
          }
          if (matched.length === 0) {
            if (lineLength === 0 || stackLen0 !== stack.depth || state !== stack.state || (!groupMatching ? 0 : groupMatching.groups.length) !== groupLen0) {
              continue;
            } else {
              throw createError(this._lexer, "no progress in tokenizer in rule: " + this._safeRuleName(rule));
            }
          }
          let tokenType = null;
          if (isString(result) && result.indexOf("@brackets") === 0) {
            const rest = result.substr("@brackets".length);
            const bracket = findBracket(this._lexer, matched);
            if (!bracket) {
              throw createError(this._lexer, "@brackets token returned but no bracket defined as: " + matched);
            }
            tokenType = sanitize(bracket.token + rest);
          } else {
            const token = result === "" ? "" : result + this._lexer.tokenPostfix;
            tokenType = sanitize(token);
          }
          if (pos0 < lineWithoutLFLength) {
            tokensCollector.emit(pos0 + offsetDelta, tokenType);
          }
        }
        if (enteringEmbeddedLanguage !== null) {
          return computeNewStateForEmbeddedLanguage(enteringEmbeddedLanguage);
        }
      }
      return MonarchLineStateFactory.create(stack, embeddedLanguageData);
    }
    _getNestedEmbeddedLanguageData(languageId) {
      if (!this._languageService.isRegisteredLanguageId(languageId)) {
        return new EmbeddedLanguageData(languageId, NullState);
      }
      if (languageId !== this._languageId) {
        this._languageService.requestBasicLanguageFeatures(languageId);
        TokenizationRegistry.getOrCreate(languageId);
        this._embeddedLanguages[languageId] = true;
      }
      const tokenizationSupport = TokenizationRegistry.get(languageId);
      if (tokenizationSupport) {
        return new EmbeddedLanguageData(languageId, tokenizationSupport.getInitialState());
      }
      return new EmbeddedLanguageData(languageId, NullState);
    }
  };
  MonarchTokenizer = MonarchTokenizer_1 = __decorate$u([
    __param$t(4, IConfigurationService)
  ], MonarchTokenizer);
  function findBracket(lexer2, matched) {
    if (!matched) {
      return null;
    }
    matched = fixCase(lexer2, matched);
    const brackets = lexer2.brackets;
    for (const bracket of brackets) {
      if (bracket.open === matched) {
        return {
          token: bracket.token,
          bracketType: 1
          /* monarchCommon.MonarchBracket.Open */
        };
      } else if (bracket.close === matched) {
        return {
          token: bracket.token,
          bracketType: -1
          /* monarchCommon.MonarchBracket.Close */
        };
      }
    }
    return null;
  }
  const ttPolicy = createTrustedTypesPolicy("standaloneColorizer", { createHTML: (value) => value });
  class Colorizer {
    static colorizeElement(themeService, languageService, domNode, options) {
      options = options || {};
      const theme = options.theme || "vs";
      const mimeType = options.mimeType || domNode.getAttribute("lang") || domNode.getAttribute("data-lang");
      if (!mimeType) {
        console.error("Mode not detected");
        return Promise.resolve();
      }
      const languageId = languageService.getLanguageIdByMimeType(mimeType) || mimeType;
      themeService.setTheme(theme);
      const text2 = domNode.firstChild ? domNode.firstChild.nodeValue : "";
      domNode.className += " " + theme;
      const render = (str) => {
        const trustedhtml = ttPolicy?.createHTML(str) ?? str;
        domNode.innerHTML = trustedhtml;
      };
      return this.colorize(languageService, text2 || "", languageId, options).then(render, (err) => console.error(err));
    }
    static async colorize(languageService, text2, languageId, options) {
      const languageIdCodec = languageService.languageIdCodec;
      let tabSize = 4;
      if (options && typeof options.tabSize === "number") {
        tabSize = options.tabSize;
      }
      if (startsWithUTF8BOM(text2)) {
        text2 = text2.substr(1);
      }
      const lines = splitLines(text2);
      if (!languageService.isRegisteredLanguageId(languageId)) {
        return _fakeColorize(lines, tabSize, languageIdCodec);
      }
      const tokenizationSupport = await TokenizationRegistry.getOrCreate(languageId);
      if (tokenizationSupport) {
        return _colorize(lines, tabSize, tokenizationSupport, languageIdCodec);
      }
      return _fakeColorize(lines, tabSize, languageIdCodec);
    }
    static colorizeLine(line, mightContainNonBasicASCII, mightContainRTL, tokens, tabSize = 4) {
      const isBasicASCII2 = ViewLineRenderingData.isBasicASCII(line, mightContainNonBasicASCII);
      const containsRTL2 = ViewLineRenderingData.containsRTL(line, isBasicASCII2, mightContainRTL);
      const renderResult = renderViewLine2(new RenderLineInput(false, true, line, false, isBasicASCII2, containsRTL2, 0, tokens, [], tabSize, 0, 0, 0, 0, -1, "none", false, false, null, null, 0));
      return renderResult.html;
    }
    static colorizeModelLine(model, lineNumber, tabSize = 4) {
      const content = model.getLineContent(lineNumber);
      model.tokenization.forceTokenization(lineNumber);
      const tokens = model.tokenization.getLineTokens(lineNumber);
      const inflatedTokens = tokens.inflate();
      return this.colorizeLine(content, model.mightContainNonBasicASCII(), model.mightContainRTL(), inflatedTokens, tabSize);
    }
  }
  function _colorize(lines, tabSize, tokenizationSupport, languageIdCodec) {
    return new Promise((c, e) => {
      const execute = () => {
        const result = _actualColorize(lines, tabSize, tokenizationSupport, languageIdCodec);
        if (tokenizationSupport instanceof MonarchTokenizer) {
          const status2 = tokenizationSupport.getLoadStatus();
          if (status2.loaded === false) {
            status2.promise.then(execute, e);
            return;
          }
        }
        c(result);
      };
      execute();
    });
  }
  function _fakeColorize(lines, tabSize, languageIdCodec) {
    let html2 = [];
    const defaultMetadata = (0 << 11 | 1 << 15 | 2 << 24) >>> 0;
    const tokens = new Uint32Array(2);
    tokens[0] = 0;
    tokens[1] = defaultMetadata;
    for (let i2 = 0, length = lines.length; i2 < length; i2++) {
      const line = lines[i2];
      tokens[0] = line.length;
      const lineTokens = new LineTokens(tokens, line, languageIdCodec);
      const isBasicASCII2 = ViewLineRenderingData.isBasicASCII(
        line,
        /* check for basic ASCII */
        true
      );
      const containsRTL2 = ViewLineRenderingData.containsRTL(
        line,
        isBasicASCII2,
        /* check for RTL */
        true
      );
      const renderResult = renderViewLine2(new RenderLineInput(false, true, line, false, isBasicASCII2, containsRTL2, 0, lineTokens, [], tabSize, 0, 0, 0, 0, -1, "none", false, false, null, null, 0));
      html2 = html2.concat(renderResult.html);
      html2.push("<br/>");
    }
    return html2.join("");
  }
  function _actualColorize(lines, tabSize, tokenizationSupport, languageIdCodec) {
    let html2 = [];
    let state = tokenizationSupport.getInitialState();
    for (let i2 = 0, length = lines.length; i2 < length; i2++) {
      const line = lines[i2];
      const tokenizeResult = tokenizationSupport.tokenizeEncoded(line, true, state);
      LineTokens.convertToEndOffset(tokenizeResult.tokens, line.length);
      const lineTokens = new LineTokens(tokenizeResult.tokens, line, languageIdCodec);
      const isBasicASCII2 = ViewLineRenderingData.isBasicASCII(
        line,
        /* check for basic ASCII */
        true
      );
      const containsRTL2 = ViewLineRenderingData.containsRTL(
        line,
        isBasicASCII2,
        /* check for RTL */
        true
      );
      const renderResult = renderViewLine2(new RenderLineInput(false, true, line, false, isBasicASCII2, containsRTL2, 0, lineTokens.inflate(), [], tabSize, 0, 0, 0, 0, -1, "none", false, false, null, null, 0));
      html2 = html2.concat(renderResult.html);
      html2.push("<br/>");
      state = tokenizeResult.endState;
    }
    return html2.join("");
  }
  var __decorate$t = 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$s = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  let AbstractCodeEditorService = class AbstractCodeEditorService extends Disposable {
    constructor(_themeService) {
      super();
      this._themeService = _themeService;
      this._onWillCreateCodeEditor = this._register(new Emitter$1());
      this._onCodeEditorAdd = this._register(new Emitter$1());
      this.onCodeEditorAdd = this._onCodeEditorAdd.event;
      this._onCodeEditorRemove = this._register(new Emitter$1());
      this.onCodeEditorRemove = this._onCodeEditorRemove.event;
      this._onWillCreateDiffEditor = this._register(new Emitter$1());
      this._onDiffEditorAdd = this._register(new Emitter$1());
      this.onDiffEditorAdd = this._onDiffEditorAdd.event;
      this._onDiffEditorRemove = this._register(new Emitter$1());
      this.onDiffEditorRemove = this._onDiffEditorRemove.event;
      this._decorationOptionProviders = /* @__PURE__ */ new Map();
      this._codeEditorOpenHandlers = new LinkedList();
      this._modelProperties = /* @__PURE__ */ new Map();
      this._codeEditors = /* @__PURE__ */ Object.create(null);
      this._diffEditors = /* @__PURE__ */ Object.create(null);
      this._globalStyleSheet = null;
    }
    willCreateCodeEditor() {
      this._onWillCreateCodeEditor.fire();
    }
    addCodeEditor(editor2) {
      this._codeEditors[editor2.getId()] = editor2;
      this._onCodeEditorAdd.fire(editor2);
    }
    removeCodeEditor(editor2) {
      if (delete this._codeEditors[editor2.getId()]) {
        this._onCodeEditorRemove.fire(editor2);
      }
    }
    listCodeEditors() {
      return Object.keys(this._codeEditors).map((id) => this._codeEditors[id]);
    }
    willCreateDiffEditor() {
      this._onWillCreateDiffEditor.fire();
    }
    addDiffEditor(editor2) {
      this._diffEditors[editor2.getId()] = editor2;
      this._onDiffEditorAdd.fire(editor2);
    }
    removeDiffEditor(editor2) {
      if (delete this._diffEditors[editor2.getId()]) {
        this._onDiffEditorRemove.fire(editor2);
      }
    }
    listDiffEditors() {
      return Object.keys(this._diffEditors).map((id) => this._diffEditors[id]);
    }
    getFocusedCodeEditor() {
      let editorWithWidgetFocus = null;
      const editors = this.listCodeEditors();
      for (const editor2 of editors) {
        if (editor2.hasTextFocus()) {
          return editor2;
        }
        if (editor2.hasWidgetFocus()) {
          editorWithWidgetFocus = editor2;
        }
      }
      return editorWithWidgetFocus;
    }
    removeDecorationType(key) {
      const provider = this._decorationOptionProviders.get(key);
      if (provider) {
        provider.refCount--;
        if (provider.refCount <= 0) {
          this._decorationOptionProviders.delete(key);
          provider.dispose();
          this.listCodeEditors().forEach((ed) => ed.removeDecorationsByType(key));
        }
      }
    }
    setModelProperty(resource, key, value) {
      const key1 = resource.toString();
      let dest;
      if (this._modelProperties.has(key1)) {
        dest = this._modelProperties.get(key1);
      } else {
        dest = /* @__PURE__ */ new Map();
        this._modelProperties.set(key1, dest);
      }
      dest.set(key, value);
    }
    getModelProperty(resource, key) {
      const key1 = resource.toString();
      if (this._modelProperties.has(key1)) {
        const innerMap = this._modelProperties.get(key1);
        return innerMap.get(key);
      }
      return void 0;
    }
    async openCodeEditor(input, source, sideBySide) {
      for (const handler of this._codeEditorOpenHandlers) {
        const candidate = await handler(input, source, sideBySide);
        if (candidate !== null) {
          return candidate;
        }
      }
      return null;
    }
    registerCodeEditorOpenHandler(handler) {
      const rm = this._codeEditorOpenHandlers.unshift(handler);
      return toDisposable(rm);
    }
  };
  AbstractCodeEditorService = __decorate$t([
    __param$s(0, IThemeService)
  ], AbstractCodeEditorService);
  var __decorate$s = 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$r = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  let StandaloneCodeEditorService = class StandaloneCodeEditorService extends AbstractCodeEditorService {
    constructor(contextKeyService, themeService) {
      super(themeService);
      this._register(this.onCodeEditorAdd(() => this._checkContextKey()));
      this._register(this.onCodeEditorRemove(() => this._checkContextKey()));
      this._editorIsOpen = contextKeyService.createKey("editorIsOpen", false);
      this._activeCodeEditor = null;
      this._register(this.registerCodeEditorOpenHandler(async (input, source, sideBySide) => {
        if (!source) {
          return null;
        }
        return this.doOpenEditor(source, input);
      }));
    }
    _checkContextKey() {
      let hasCodeEditor = false;
      for (const editor2 of this.listCodeEditors()) {
        if (!editor2.isSimpleWidget) {
          hasCodeEditor = true;
          break;
        }
      }
      this._editorIsOpen.set(hasCodeEditor);
    }
    setActiveCodeEditor(activeCodeEditor) {
      this._activeCodeEditor = activeCodeEditor;
    }
    getActiveCodeEditor() {
      return this._activeCodeEditor;
    }
    doOpenEditor(editor2, input) {
      const model = this.findModel(editor2, input.resource);
      if (!model) {
        if (input.resource) {
          const schema = input.resource.scheme;
          if (schema === Schemas.http || schema === Schemas.https) {
            windowOpenNoOpener(input.resource.toString());
            return editor2;
          }
        }
        return null;
      }
      const selection = input.options ? input.options.selection : null;
      if (selection) {
        if (typeof selection.endLineNumber === "number" && typeof selection.endColumn === "number") {
          editor2.setSelection(selection);
          editor2.revealRangeInCenter(
            selection,
            1
            /* ScrollType.Immediate */
          );
        } else {
          const pos = {
            lineNumber: selection.startLineNumber,
            column: selection.startColumn
          };
          editor2.setPosition(pos);
          editor2.revealPositionInCenter(
            pos,
            1
            /* ScrollType.Immediate */
          );
        }
      }
      return editor2;
    }
    findModel(editor2, resource) {
      const model = editor2.getModel();
      if (model && model.uri.toString() !== resource.toString()) {
        return null;
      }
      return model;
    }
  };
  StandaloneCodeEditorService = __decorate$s([
    __param$r(0, IContextKeyService),
    __param$r(1, IThemeService)
  ], StandaloneCodeEditorService);
  registerSingleton(
    ICodeEditorService,
    StandaloneCodeEditorService,
    0
    /* InstantiationType.Eager */
  );
  var __decorate$r = 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$q = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  let StandaloneLayoutService = class StandaloneLayoutService {
    get mainContainer() {
      return this._codeEditorService.listCodeEditors().at(0)?.getContainerDomNode() ?? mainWindow.document.body;
    }
    get activeContainer() {
      const activeCodeEditor = this._codeEditorService.getFocusedCodeEditor() ?? this._codeEditorService.getActiveCodeEditor();
      return activeCodeEditor?.getContainerDomNode() ?? this.mainContainer;
    }
    get mainContainerDimension() {
      return getClientArea(this.mainContainer);
    }
    get activeContainerDimension() {
      return getClientArea(this.activeContainer);
    }
    get containers() {
      return coalesce(this._codeEditorService.listCodeEditors().map((codeEditor) => codeEditor.getContainerDomNode()));
    }
    getContainer() {
      return this.activeContainer;
    }
    whenContainerStylesLoaded() {
      return void 0;
    }
    focus() {
      this._codeEditorService.getFocusedCodeEditor()?.focus();
    }
    constructor(_codeEditorService) {
      this._codeEditorService = _codeEditorService;
      this.onDidLayoutMainContainer = Event.None;
      this.onDidLayoutActiveContainer = Event.None;
      this.onDidLayoutContainer = Event.None;
      this.onDidChangeActiveContainer = Event.None;
      this.onDidAddContainer = Event.None;
      this.mainContainerOffset = { top: 0, quickPickTop: 0 };
      this.activeContainerOffset = { top: 0, quickPickTop: 0 };
    }
  };
  StandaloneLayoutService = __decorate$r([
    __param$q(0, ICodeEditorService)
  ], StandaloneLayoutService);
  let EditorScopedLayoutService = class EditorScopedLayoutService extends StandaloneLayoutService {
    get mainContainer() {
      return this._container;
    }
    constructor(_container, codeEditorService) {
      super(codeEditorService);
      this._container = _container;
    }
  };
  EditorScopedLayoutService = __decorate$r([
    __param$q(1, ICodeEditorService)
  ], EditorScopedLayoutService);
  registerSingleton(
    ILayoutService,
    StandaloneLayoutService,
    1
    /* InstantiationType.Delayed */
  );
  var __decorate$q = 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$p = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  function getResourceLabel(resource) {
    return resource.scheme === Schemas.file ? resource.fsPath : resource.path;
  }
  let stackElementCounter = 0;
  class ResourceStackElement {
    constructor(actual, resourceLabel, strResource, groupId, groupOrder, sourceId, sourceOrder) {
      this.id = ++stackElementCounter;
      this.type = 0;
      this.actual = actual;
      this.label = actual.label;
      this.confirmBeforeUndo = actual.confirmBeforeUndo || false;
      this.resourceLabel = resourceLabel;
      this.strResource = strResource;
      this.resourceLabels = [this.resourceLabel];
      this.strResources = [this.strResource];
      this.groupId = groupId;
      this.groupOrder = groupOrder;
      this.sourceId = sourceId;
      this.sourceOrder = sourceOrder;
      this.isValid = true;
    }
    setValid(isValid2) {
      this.isValid = isValid2;
    }
    toString() {
      return `[id:${this.id}] [group:${this.groupId}] [${this.isValid ? "  VALID" : "INVALID"}] ${this.actual.constructor.name} - ${this.actual}`;
    }
  }
  class ResourceReasonPair {
    constructor(resourceLabel, reason) {
      this.resourceLabel = resourceLabel;
      this.reason = reason;
    }
  }
  class RemovedResources {
    constructor() {
      this.elements = /* @__PURE__ */ new Map();
    }
    createMessage() {
      const externalRemoval = [];
      const noParallelUniverses = [];
      for (const [, element] of this.elements) {
        const dest = element.reason === 0 ? externalRemoval : noParallelUniverses;
        dest.push(element.resourceLabel);
      }
      const messages = [];
      if (externalRemoval.length > 0) {
        messages.push(localize(2030, "The following files have been closed and modified on disk: {0}.", externalRemoval.join(", ")));
      }
      if (noParallelUniverses.length > 0) {
        messages.push(localize(2031, "The following files have been modified in an incompatible way: {0}.", noParallelUniverses.join(", ")));
      }
      return messages.join("\n");
    }
    get size() {
      return this.elements.size;
    }
    has(strResource) {
      return this.elements.has(strResource);
    }
    set(strResource, value) {
      this.elements.set(strResource, value);
    }
    delete(strResource) {
      return this.elements.delete(strResource);
    }
  }
  class WorkspaceStackElement {
    constructor(actual, resourceLabels, strResources, groupId, groupOrder, sourceId, sourceOrder) {
      this.id = ++stackElementCounter;
      this.type = 1;
      this.actual = actual;
      this.label = actual.label;
      this.confirmBeforeUndo = actual.confirmBeforeUndo || false;
      this.resourceLabels = resourceLabels;
      this.strResources = strResources;
      this.groupId = groupId;
      this.groupOrder = groupOrder;
      this.sourceId = sourceId;
      this.sourceOrder = sourceOrder;
      this.removedResources = null;
      this.invalidatedResources = null;
    }
    canSplit() {
      return typeof this.actual.split === "function";
    }
    removeResource(resourceLabel, strResource, reason) {
      if (!this.removedResources) {
        this.removedResources = new RemovedResources();
      }
      if (!this.removedResources.has(strResource)) {
        this.removedResources.set(strResource, new ResourceReasonPair(resourceLabel, reason));
      }
    }
    setValid(resourceLabel, strResource, isValid2) {
      if (isValid2) {
        if (this.invalidatedResources) {
          this.invalidatedResources.delete(strResource);
          if (this.invalidatedResources.size === 0) {
            this.invalidatedResources = null;
          }
        }
      } else {
        if (!this.invalidatedResources) {
          this.invalidatedResources = new RemovedResources();
        }
        if (!this.invalidatedResources.has(strResource)) {
          this.invalidatedResources.set(strResource, new ResourceReasonPair(
            resourceLabel,
            0
            /* RemovedResourceReason.ExternalRemoval */
          ));
        }
      }
    }
    toString() {
      return `[id:${this.id}] [group:${this.groupId}] [${this.invalidatedResources ? "INVALID" : "  VALID"}] ${this.actual.constructor.name} - ${this.actual}`;
    }
  }
  class ResourceEditStack {
    constructor(resourceLabel, strResource) {
      this.resourceLabel = resourceLabel;
      this.strResource = strResource;
      this._past = [];
      this._future = [];
      this.locked = false;
      this.versionId = 1;
    }
    dispose() {
      for (const element of this._past) {
        if (element.type === 1) {
          element.removeResource(
            this.resourceLabel,
            this.strResource,
            0
            /* RemovedResourceReason.ExternalRemoval */
          );
        }
      }
      for (const element of this._future) {
        if (element.type === 1) {
          element.removeResource(
            this.resourceLabel,
            this.strResource,
            0
            /* RemovedResourceReason.ExternalRemoval */
          );
        }
      }
      this.versionId++;
    }
    toString() {
      const result = [];
      result.push(`* ${this.strResource}:`);
      for (let i2 = 0; i2 < this._past.length; i2++) {
        result.push(`   * [UNDO] ${this._past[i2]}`);
      }
      for (let i2 = this._future.length - 1; i2 >= 0; i2--) {
        result.push(`   * [REDO] ${this._future[i2]}`);
      }
      return result.join("\n");
    }
    flushAllElements() {
      this._past = [];
      this._future = [];
      this.versionId++;
    }
    _setElementValidFlag(element, isValid2) {
      if (element.type === 1) {
        element.setValid(this.resourceLabel, this.strResource, isValid2);
      } else {
        element.setValid(isValid2);
      }
    }
    setElementsValidFlag(isValid2, filter) {
      for (const element of this._past) {
        if (filter(element.actual)) {
          this._setElementValidFlag(element, isValid2);
        }
      }
      for (const element of this._future) {
        if (filter(element.actual)) {
          this._setElementValidFlag(element, isValid2);
        }
      }
    }
    pushElement(element) {
      for (const futureElement of this._future) {
        if (futureElement.type === 1) {
          futureElement.removeResource(
            this.resourceLabel,
            this.strResource,
            1
            /* RemovedResourceReason.NoParallelUniverses */
          );
        }
      }
      this._future = [];
      this._past.push(element);
      this.versionId++;
    }
    createSnapshot(resource) {
      const elements = [];
      for (let i2 = 0, len = this._past.length; i2 < len; i2++) {
        elements.push(this._past[i2].id);
      }
      for (let i2 = this._future.length - 1; i2 >= 0; i2--) {
        elements.push(this._future[i2].id);
      }
      return new ResourceEditStackSnapshot(resource, elements);
    }
    restoreSnapshot(snapshot) {
      const snapshotLength = snapshot.elements.length;
      let isOK = true;
      let snapshotIndex = 0;
      let removePastAfter = -1;
      for (let i2 = 0, len = this._past.length; i2 < len; i2++, snapshotIndex++) {
        const element = this._past[i2];
        if (isOK && (snapshotIndex >= snapshotLength || element.id !== snapshot.elements[snapshotIndex])) {
          isOK = false;
          removePastAfter = 0;
        }
        if (!isOK && element.type === 1) {
          element.removeResource(
            this.resourceLabel,
            this.strResource,
            0
            /* RemovedResourceReason.ExternalRemoval */
          );
        }
      }
      let removeFutureBefore = -1;
      for (let i2 = this._future.length - 1; i2 >= 0; i2--, snapshotIndex++) {
        const element = this._future[i2];
        if (isOK && (snapshotIndex >= snapshotLength || element.id !== snapshot.elements[snapshotIndex])) {
          isOK = false;
          removeFutureBefore = i2;
        }
        if (!isOK && element.type === 1) {
          element.removeResource(
            this.resourceLabel,
            this.strResource,
            0
            /* RemovedResourceReason.ExternalRemoval */
          );
        }
      }
      if (removePastAfter !== -1) {
        this._past = this._past.slice(0, removePastAfter);
      }
      if (removeFutureBefore !== -1) {
        this._future = this._future.slice(removeFutureBefore + 1);
      }
      this.versionId++;
    }
    getElements() {
      const past = [];
      const future = [];
      for (const element of this._past) {
        past.push(element.actual);
      }
      for (const element of this._future) {
        future.push(element.actual);
      }
      return { past, future };
    }
    getClosestPastElement() {
      if (this._past.length === 0) {
        return null;
      }
      return this._past[this._past.length - 1];
    }
    getSecondClosestPastElement() {
      if (this._past.length < 2) {
        return null;
      }
      return this._past[this._past.length - 2];
    }
    getClosestFutureElement() {
      if (this._future.length === 0) {
        return null;
      }
      return this._future[this._future.length - 1];
    }
    hasPastElements() {
      return this._past.length > 0;
    }
    hasFutureElements() {
      return this._future.length > 0;
    }
    splitPastWorkspaceElement(toRemove, individualMap) {
      for (let j = this._past.length - 1; j >= 0; j--) {
        if (this._past[j] === toRemove) {
          if (individualMap.has(this.strResource)) {
            this._past[j] = individualMap.get(this.strResource);
          } else {
            this._past.splice(j, 1);
          }
          break;
        }
      }
      this.versionId++;
    }
    splitFutureWorkspaceElement(toRemove, individualMap) {
      for (let j = this._future.length - 1; j >= 0; j--) {
        if (this._future[j] === toRemove) {
          if (individualMap.has(this.strResource)) {
            this._future[j] = individualMap.get(this.strResource);
          } else {
            this._future.splice(j, 1);
          }
          break;
        }
      }
      this.versionId++;
    }
    moveBackward(element) {
      this._past.pop();
      this._future.push(element);
      this.versionId++;
    }
    moveForward(element) {
      this._future.pop();
      this._past.push(element);
      this.versionId++;
    }
  }
  class EditStackSnapshot {
    constructor(editStacks) {
      this.editStacks = editStacks;
      this._versionIds = [];
      for (let i2 = 0, len = this.editStacks.length; i2 < len; i2++) {
        this._versionIds[i2] = this.editStacks[i2].versionId;
      }
    }
    isValid() {
      for (let i2 = 0, len = this.editStacks.length; i2 < len; i2++) {
        if (this._versionIds[i2] !== this.editStacks[i2].versionId) {
          return false;
        }
      }
      return true;
    }
  }
  const missingEditStack = new ResourceEditStack("", "");
  missingEditStack.locked = true;
  let UndoRedoService = class UndoRedoService {
    constructor(_dialogService, _notificationService) {
      this._dialogService = _dialogService;
      this._notificationService = _notificationService;
      this._editStacks = /* @__PURE__ */ new Map();
      this._uriComparisonKeyComputers = [];
    }
    getUriComparisonKey(resource) {
      for (const uriComparisonKeyComputer of this._uriComparisonKeyComputers) {
        if (uriComparisonKeyComputer[0] === resource.scheme) {
          return uriComparisonKeyComputer[1].getComparisonKey(resource);
        }
      }
      return resource.toString();
    }
    _print(label) {
      console.log(`------------------------------------`);
      console.log(`AFTER ${label}: `);
      const str = [];
      for (const element of this._editStacks) {
        str.push(element[1].toString());
      }
      console.log(str.join("\n"));
    }
    pushElement(element, group = UndoRedoGroup.None, source = UndoRedoSource.None) {
      if (element.type === 0) {
        const resourceLabel = getResourceLabel(element.resource);
        const strResource = this.getUriComparisonKey(element.resource);
        this._pushElement(new ResourceStackElement(element, resourceLabel, strResource, group.id, group.nextOrder(), source.id, source.nextOrder()));
      } else {
        const seen = /* @__PURE__ */ new Set();
        const resourceLabels = [];
        const strResources = [];
        for (const resource of element.resources) {
          const resourceLabel = getResourceLabel(resource);
          const strResource = this.getUriComparisonKey(resource);
          if (seen.has(strResource)) {
            continue;
          }
          seen.add(strResource);
          resourceLabels.push(resourceLabel);
          strResources.push(strResource);
        }
        if (resourceLabels.length === 1) {
          this._pushElement(new ResourceStackElement(element, resourceLabels[0], strResources[0], group.id, group.nextOrder(), source.id, source.nextOrder()));
        } else {
          this._pushElement(new WorkspaceStackElement(element, resourceLabels, strResources, group.id, group.nextOrder(), source.id, source.nextOrder()));
        }
      }
    }
    _pushElement(element) {
      for (let i2 = 0, len = element.strResources.length; i2 < len; i2++) {
        const resourceLabel = element.resourceLabels[i2];
        const strResource = element.strResources[i2];
        let editStack;
        if (this._editStacks.has(strResource)) {
          editStack = this._editStacks.get(strResource);
        } else {
          editStack = new ResourceEditStack(resourceLabel, strResource);
          this._editStacks.set(strResource, editStack);
        }
        editStack.pushElement(element);
      }
    }
    getLastElement(resource) {
      const strResource = this.getUriComparisonKey(resource);
      if (this._editStacks.has(strResource)) {
        const editStack = this._editStacks.get(strResource);
        if (editStack.hasFutureElements()) {
          return null;
        }
        const closestPastElement = editStack.getClosestPastElement();
        return closestPastElement ? closestPastElement.actual : null;
      }
      return null;
    }
    _splitPastWorkspaceElement(toRemove, ignoreResources) {
      const individualArr = toRemove.actual.split();
      const individualMap = /* @__PURE__ */ new Map();
      for (const _element of individualArr) {
        const resourceLabel = getResourceLabel(_element.resource);
        const strResource = this.getUriComparisonKey(_element.resource);
        const element = new ResourceStackElement(_element, resourceLabel, strResource, 0, 0, 0, 0);
        individualMap.set(element.strResource, element);
      }
      for (const strResource of toRemove.strResources) {
        if (ignoreResources && ignoreResources.has(strResource)) {
          continue;
        }
        const editStack = this._editStacks.get(strResource);
        editStack.splitPastWorkspaceElement(toRemove, individualMap);
      }
    }
    _splitFutureWorkspaceElement(toRemove, ignoreResources) {
      const individualArr = toRemove.actual.split();
      const individualMap = /* @__PURE__ */ new Map();
      for (const _element of individualArr) {
        const resourceLabel = getResourceLabel(_element.resource);
        const strResource = this.getUriComparisonKey(_element.resource);
        const element = new ResourceStackElement(_element, resourceLabel, strResource, 0, 0, 0, 0);
        individualMap.set(element.strResource, element);
      }
      for (const strResource of toRemove.strResources) {
        if (ignoreResources && ignoreResources.has(strResource)) {
          continue;
        }
        const editStack = this._editStacks.get(strResource);
        editStack.splitFutureWorkspaceElement(toRemove, individualMap);
      }
    }
    removeElements(resource) {
      const strResource = typeof resource === "string" ? resource : this.getUriComparisonKey(resource);
      if (this._editStacks.has(strResource)) {
        const editStack = this._editStacks.get(strResource);
        editStack.dispose();
        this._editStacks.delete(strResource);
      }
    }
    setElementsValidFlag(resource, isValid2, filter) {
      const strResource = this.getUriComparisonKey(resource);
      if (this._editStacks.has(strResource)) {
        const editStack = this._editStacks.get(strResource);
        editStack.setElementsValidFlag(isValid2, filter);
      }
    }
    createSnapshot(resource) {
      const strResource = this.getUriComparisonKey(resource);
      if (this._editStacks.has(strResource)) {
        const editStack = this._editStacks.get(strResource);
        return editStack.createSnapshot(resource);
      }
      return new ResourceEditStackSnapshot(resource, []);
    }
    restoreSnapshot(snapshot) {
      const strResource = this.getUriComparisonKey(snapshot.resource);
      if (this._editStacks.has(strResource)) {
        const editStack = this._editStacks.get(strResource);
        editStack.restoreSnapshot(snapshot);
        if (!editStack.hasPastElements() && !editStack.hasFutureElements()) {
          editStack.dispose();
          this._editStacks.delete(strResource);
        }
      }
    }
    getElements(resource) {
      const strResource = this.getUriComparisonKey(resource);
      if (this._editStacks.has(strResource)) {
        const editStack = this._editStacks.get(strResource);
        return editStack.getElements();
      }
      return { past: [], future: [] };
    }
    _findClosestUndoElementWithSource(sourceId) {
      if (!sourceId) {
        return [null, null];
      }
      let matchedElement = null;
      let matchedStrResource = null;
      for (const [strResource, editStack] of this._editStacks) {
        const candidate = editStack.getClosestPastElement();
        if (!candidate) {
          continue;
        }
        if (candidate.sourceId === sourceId) {
          if (!matchedElement || candidate.sourceOrder > matchedElement.sourceOrder) {
            matchedElement = candidate;
            matchedStrResource = strResource;
          }
        }
      }
      return [matchedElement, matchedStrResource];
    }
    canUndo(resourceOrSource) {
      if (resourceOrSource instanceof UndoRedoSource) {
        const [, matchedStrResource] = this._findClosestUndoElementWithSource(resourceOrSource.id);
        return matchedStrResource ? true : false;
      }
      const strResource = this.getUriComparisonKey(resourceOrSource);
      if (this._editStacks.has(strResource)) {
        const editStack = this._editStacks.get(strResource);
        return editStack.hasPastElements();
      }
      return false;
    }
    _onError(err, element) {
      onUnexpectedError(err);
      for (const strResource of element.strResources) {
        this.removeElements(strResource);
      }
      this._notificationService.error(err);
    }
    _acquireLocks(editStackSnapshot) {
      for (const editStack of editStackSnapshot.editStacks) {
        if (editStack.locked) {
          throw new Error("Cannot acquire edit stack lock");
        }
      }
      for (const editStack of editStackSnapshot.editStacks) {
        editStack.locked = true;
      }
      return () => {
        for (const editStack of editStackSnapshot.editStacks) {
          editStack.locked = false;
        }
      };
    }
    _safeInvokeWithLocks(element, invoke, editStackSnapshot, cleanup, continuation) {
      const releaseLocks = this._acquireLocks(editStackSnapshot);
      let result;
      try {
        result = invoke();
      } catch (err) {
        releaseLocks();
        cleanup.dispose();
        return this._onError(err, element);
      }
      if (result) {
        return result.then(() => {
          releaseLocks();
          cleanup.dispose();
          return continuation();
        }, (err) => {
          releaseLocks();
          cleanup.dispose();
          return this._onError(err, element);
        });
      } else {
        releaseLocks();
        cleanup.dispose();
        return continuation();
      }
    }
    async _invokeWorkspacePrepare(element) {
      if (typeof element.actual.prepareUndoRedo === "undefined") {
        return Disposable.None;
      }
      const result = element.actual.prepareUndoRedo();
      if (typeof result === "undefined") {
        return Disposable.None;
      }
      return result;
    }
    _invokeResourcePrepare(element, callback) {
      if (element.actual.type !== 1 || typeof element.actual.prepareUndoRedo === "undefined") {
        return callback(Disposable.None);
      }
      const r = element.actual.prepareUndoRedo();
      if (!r) {
        return callback(Disposable.None);
      }
      if (isDisposable(r)) {
        return callback(r);
      }
      return r.then((disposable) => {
        return callback(disposable);
      });
    }
    _getAffectedEditStacks(element) {
      const affectedEditStacks = [];
      for (const strResource of element.strResources) {
        affectedEditStacks.push(this._editStacks.get(strResource) || missingEditStack);
      }
      return new EditStackSnapshot(affectedEditStacks);
    }
    _tryToSplitAndUndo(strResource, element, ignoreResources, message) {
      if (element.canSplit()) {
        this._splitPastWorkspaceElement(element, ignoreResources);
        this._notificationService.warn(message);
        return new WorkspaceVerificationError(this._undo(strResource, 0, true));
      } else {
        for (const strResource2 of element.strResources) {
          this.removeElements(strResource2);
        }
        this._notificationService.warn(message);
        return new WorkspaceVerificationError();
      }
    }
    _checkWorkspaceUndo(strResource, element, editStackSnapshot, checkInvalidatedResources) {
      if (element.removedResources) {
        return this._tryToSplitAndUndo(strResource, element, element.removedResources, localize(2032, "Could not undo '{0}' across all files. {1}", element.label, element.removedResources.createMessage()));
      }
      if (checkInvalidatedResources && element.invalidatedResources) {
        return this._tryToSplitAndUndo(strResource, element, element.invalidatedResources, localize(2033, "Could not undo '{0}' across all files. {1}", element.label, element.invalidatedResources.createMessage()));
      }
      const cannotUndoDueToResources = [];
      for (const editStack of editStackSnapshot.editStacks) {
        if (editStack.getClosestPastElement() !== element) {
          cannotUndoDueToResources.push(editStack.resourceLabel);
        }
      }
      if (cannotUndoDueToResources.length > 0) {
        return this._tryToSplitAndUndo(strResource, element, null, localize(2034, "Could not undo '{0}' across all files because changes were made to {1}", element.label, cannotUndoDueToResources.join(", ")));
      }
      const cannotLockDueToResources = [];
      for (const editStack of editStackSnapshot.editStacks) {
        if (editStack.locked) {
          cannotLockDueToResources.push(editStack.resourceLabel);
        }
      }
      if (cannotLockDueToResources.length > 0) {
        return this._tryToSplitAndUndo(strResource, element, null, localize(2035, "Could not undo '{0}' across all files because there is already an undo or redo operation running on {1}", element.label, cannotLockDueToResources.join(", ")));
      }
      if (!editStackSnapshot.isValid()) {
        return this._tryToSplitAndUndo(strResource, element, null, localize(2036, "Could not undo '{0}' across all files because an undo or redo operation occurred in the meantime", element.label));
      }
      return null;
    }
    _workspaceUndo(strResource, element, undoConfirmed) {
      const affectedEditStacks = this._getAffectedEditStacks(element);
      const verificationError = this._checkWorkspaceUndo(
        strResource,
        element,
        affectedEditStacks,
        /*invalidated resources will be checked after the prepare call*/
        false
      );
      if (verificationError) {
        return verificationError.returnValue;
      }
      return this._confirmAndExecuteWorkspaceUndo(strResource, element, affectedEditStacks, undoConfirmed);
    }
    _isPartOfUndoGroup(element) {
      if (!element.groupId) {
        return false;
      }
      for (const [, editStack] of this._editStacks) {
        const pastElement = editStack.getClosestPastElement();
        if (!pastElement) {
          continue;
        }
        if (pastElement === element) {
          const secondPastElement = editStack.getSecondClosestPastElement();
          if (secondPastElement && secondPastElement.groupId === element.groupId) {
            return true;
          }
        }
        if (pastElement.groupId === element.groupId) {
          return true;
        }
      }
      return false;
    }
    async _confirmAndExecuteWorkspaceUndo(strResource, element, editStackSnapshot, undoConfirmed) {
      if (element.canSplit() && !this._isPartOfUndoGroup(element)) {
        let UndoChoice;
        (function(UndoChoice2) {
          UndoChoice2[UndoChoice2["All"] = 0] = "All";
          UndoChoice2[UndoChoice2["This"] = 1] = "This";
          UndoChoice2[UndoChoice2["Cancel"] = 2] = "Cancel";
        })(UndoChoice || (UndoChoice = {}));
        const { result } = await this._dialogService.prompt({
          type: Severity$2.Info,
          message: localize(2037, "Would you like to undo '{0}' across all files?", element.label),
          buttons: [
            {
              label: localize(2038, "&&Undo in {0} Files", editStackSnapshot.editStacks.length),
              run: () => UndoChoice.All
            },
            {
              label: localize(2039, "Undo this &&File"),
              run: () => UndoChoice.This
            }
          ],
          cancelButton: {
            run: () => UndoChoice.Cancel
          }
        });
        if (result === UndoChoice.Cancel) {
          return;
        }
        if (result === UndoChoice.This) {
          this._splitPastWorkspaceElement(element, null);
          return this._undo(strResource, 0, true);
        }
        const verificationError1 = this._checkWorkspaceUndo(
          strResource,
          element,
          editStackSnapshot,
          /*invalidated resources will be checked after the prepare call*/
          false
        );
        if (verificationError1) {
          return verificationError1.returnValue;
        }
        undoConfirmed = true;
      }
      let cleanup;
      try {
        cleanup = await this._invokeWorkspacePrepare(element);
      } catch (err) {
        return this._onError(err, element);
      }
      const verificationError2 = this._checkWorkspaceUndo(
        strResource,
        element,
        editStackSnapshot,
        /*now also check that there are no more invalidated resources*/
        true
      );
      if (verificationError2) {
        cleanup.dispose();
        return verificationError2.returnValue;
      }
      for (const editStack of editStackSnapshot.editStacks) {
        editStack.moveBackward(element);
      }
      return this._safeInvokeWithLocks(element, () => element.actual.undo(), editStackSnapshot, cleanup, () => this._continueUndoInGroup(element.groupId, undoConfirmed));
    }
    _resourceUndo(editStack, element, undoConfirmed) {
      if (!element.isValid) {
        editStack.flushAllElements();
        return;
      }
      if (editStack.locked) {
        const message = localize(2040, "Could not undo '{0}' because there is already an undo or redo operation running.", element.label);
        this._notificationService.warn(message);
        return;
      }
      return this._invokeResourcePrepare(element, (cleanup) => {
        editStack.moveBackward(element);
        return this._safeInvokeWithLocks(element, () => element.actual.undo(), new EditStackSnapshot([editStack]), cleanup, () => this._continueUndoInGroup(element.groupId, undoConfirmed));
      });
    }
    _findClosestUndoElementInGroup(groupId) {
      if (!groupId) {
        return [null, null];
      }
      let matchedElement = null;
      let matchedStrResource = null;
      for (const [strResource, editStack] of this._editStacks) {
        const candidate = editStack.getClosestPastElement();
        if (!candidate) {
          continue;
        }
        if (candidate.groupId === groupId) {
          if (!matchedElement || candidate.groupOrder > matchedElement.groupOrder) {
            matchedElement = candidate;
            matchedStrResource = strResource;
          }
        }
      }
      return [matchedElement, matchedStrResource];
    }
    _continueUndoInGroup(groupId, undoConfirmed) {
      if (!groupId) {
        return;
      }
      const [, matchedStrResource] = this._findClosestUndoElementInGroup(groupId);
      if (matchedStrResource) {
        return this._undo(matchedStrResource, 0, undoConfirmed);
      }
    }
    undo(resourceOrSource) {
      if (resourceOrSource instanceof UndoRedoSource) {
        const [, matchedStrResource] = this._findClosestUndoElementWithSource(resourceOrSource.id);
        return matchedStrResource ? this._undo(matchedStrResource, resourceOrSource.id, false) : void 0;
      }
      if (typeof resourceOrSource === "string") {
        return this._undo(resourceOrSource, 0, false);
      }
      return this._undo(this.getUriComparisonKey(resourceOrSource), 0, false);
    }
    _undo(strResource, sourceId = 0, undoConfirmed) {
      if (!this._editStacks.has(strResource)) {
        return;
      }
      const editStack = this._editStacks.get(strResource);
      const element = editStack.getClosestPastElement();
      if (!element) {
        return;
      }
      if (element.groupId) {
        const [matchedElement, matchedStrResource] = this._findClosestUndoElementInGroup(element.groupId);
        if (element !== matchedElement && matchedStrResource) {
          return this._undo(matchedStrResource, sourceId, undoConfirmed);
        }
      }
      const shouldPromptForConfirmation = element.sourceId !== sourceId || element.confirmBeforeUndo;
      if (shouldPromptForConfirmation && !undoConfirmed) {
        return this._confirmAndContinueUndo(strResource, sourceId, element);
      }
      try {
        if (element.type === 1) {
          return this._workspaceUndo(strResource, element, undoConfirmed);
        } else {
          return this._resourceUndo(editStack, element, undoConfirmed);
        }
      } finally {
      }
    }
    async _confirmAndContinueUndo(strResource, sourceId, element) {
      const result = await this._dialogService.confirm({
        message: localize(2041, "Would you like to undo '{0}'?", element.label),
        primaryButton: localize(2042, "&&Yes"),
        cancelButton: localize(2043, "No")
      });
      if (!result.confirmed) {
        return;
      }
      return this._undo(strResource, sourceId, true);
    }
    _findClosestRedoElementWithSource(sourceId) {
      if (!sourceId) {
        return [null, null];
      }
      let matchedElement = null;
      let matchedStrResource = null;
      for (const [strResource, editStack] of this._editStacks) {
        const candidate = editStack.getClosestFutureElement();
        if (!candidate) {
          continue;
        }
        if (candidate.sourceId === sourceId) {
          if (!matchedElement || candidate.sourceOrder < matchedElement.sourceOrder) {
            matchedElement = candidate;
            matchedStrResource = strResource;
          }
        }
      }
      return [matchedElement, matchedStrResource];
    }
    canRedo(resourceOrSource) {
      if (resourceOrSource instanceof UndoRedoSource) {
        const [, matchedStrResource] = this._findClosestRedoElementWithSource(resourceOrSource.id);
        return matchedStrResource ? true : false;
      }
      const strResource = this.getUriComparisonKey(resourceOrSource);
      if (this._editStacks.has(strResource)) {
        const editStack = this._editStacks.get(strResource);
        return editStack.hasFutureElements();
      }
      return false;
    }
    _tryToSplitAndRedo(strResource, element, ignoreResources, message) {
      if (element.canSplit()) {
        this._splitFutureWorkspaceElement(element, ignoreResources);
        this._notificationService.warn(message);
        return new WorkspaceVerificationError(this._redo(strResource));
      } else {
        for (const strResource2 of element.strResources) {
          this.removeElements(strResource2);
        }
        this._notificationService.warn(message);
        return new WorkspaceVerificationError();
      }
    }
    _checkWorkspaceRedo(strResource, element, editStackSnapshot, checkInvalidatedResources) {
      if (element.removedResources) {
        return this._tryToSplitAndRedo(strResource, element, element.removedResources, localize(2044, "Could not redo '{0}' across all files. {1}", element.label, element.removedResources.createMessage()));
      }
      if (checkInvalidatedResources && element.invalidatedResources) {
        return this._tryToSplitAndRedo(strResource, element, element.invalidatedResources, localize(2045, "Could not redo '{0}' across all files. {1}", element.label, element.invalidatedResources.createMessage()));
      }
      const cannotRedoDueToResources = [];
      for (const editStack of editStackSnapshot.editStacks) {
        if (editStack.getClosestFutureElement() !== element) {
          cannotRedoDueToResources.push(editStack.resourceLabel);
        }
      }
      if (cannotRedoDueToResources.length > 0) {
        return this._tryToSplitAndRedo(strResource, element, null, localize(2046, "Could not redo '{0}' across all files because changes were made to {1}", element.label, cannotRedoDueToResources.join(", ")));
      }
      const cannotLockDueToResources = [];
      for (const editStack of editStackSnapshot.editStacks) {
        if (editStack.locked) {
          cannotLockDueToResources.push(editStack.resourceLabel);
        }
      }
      if (cannotLockDueToResources.length > 0) {
        return this._tryToSplitAndRedo(strResource, element, null, localize(2047, "Could not redo '{0}' across all files because there is already an undo or redo operation running on {1}", element.label, cannotLockDueToResources.join(", ")));
      }
      if (!editStackSnapshot.isValid()) {
        return this._tryToSplitAndRedo(strResource, element, null, localize(2048, "Could not redo '{0}' across all files because an undo or redo operation occurred in the meantime", element.label));
      }
      return null;
    }
    _workspaceRedo(strResource, element) {
      const affectedEditStacks = this._getAffectedEditStacks(element);
      const verificationError = this._checkWorkspaceRedo(
        strResource,
        element,
        affectedEditStacks,
        /*invalidated resources will be checked after the prepare call*/
        false
      );
      if (verificationError) {
        return verificationError.returnValue;
      }
      return this._executeWorkspaceRedo(strResource, element, affectedEditStacks);
    }
    async _executeWorkspaceRedo(strResource, element, editStackSnapshot) {
      let cleanup;
      try {
        cleanup = await this._invokeWorkspacePrepare(element);
      } catch (err) {
        return this._onError(err, element);
      }
      const verificationError = this._checkWorkspaceRedo(
        strResource,
        element,
        editStackSnapshot,
        /*now also check that there are no more invalidated resources*/
        true
      );
      if (verificationError) {
        cleanup.dispose();
        return verificationError.returnValue;
      }
      for (const editStack of editStackSnapshot.editStacks) {
        editStack.moveForward(element);
      }
      return this._safeInvokeWithLocks(element, () => element.actual.redo(), editStackSnapshot, cleanup, () => this._continueRedoInGroup(element.groupId));
    }
    _resourceRedo(editStack, element) {
      if (!element.isValid) {
        editStack.flushAllElements();
        return;
      }
      if (editStack.locked) {
        const message = localize(2049, "Could not redo '{0}' because there is already an undo or redo operation running.", element.label);
        this._notificationService.warn(message);
        return;
      }
      return this._invokeResourcePrepare(element, (cleanup) => {
        editStack.moveForward(element);
        return this._safeInvokeWithLocks(element, () => element.actual.redo(), new EditStackSnapshot([editStack]), cleanup, () => this._continueRedoInGroup(element.groupId));
      });
    }
    _findClosestRedoElementInGroup(groupId) {
      if (!groupId) {
        return [null, null];
      }
      let matchedElement = null;
      let matchedStrResource = null;
      for (const [strResource, editStack] of this._editStacks) {
        const candidate = editStack.getClosestFutureElement();
        if (!candidate) {
          continue;
        }
        if (candidate.groupId === groupId) {
          if (!matchedElement || candidate.groupOrder < matchedElement.groupOrder) {
            matchedElement = candidate;
            matchedStrResource = strResource;
          }
        }
      }
      return [matchedElement, matchedStrResource];
    }
    _continueRedoInGroup(groupId) {
      if (!groupId) {
        return;
      }
      const [, matchedStrResource] = this._findClosestRedoElementInGroup(groupId);
      if (matchedStrResource) {
        return this._redo(matchedStrResource);
      }
    }
    redo(resourceOrSource) {
      if (resourceOrSource instanceof UndoRedoSource) {
        const [, matchedStrResource] = this._findClosestRedoElementWithSource(resourceOrSource.id);
        return matchedStrResource ? this._redo(matchedStrResource) : void 0;
      }
      if (typeof resourceOrSource === "string") {
        return this._redo(resourceOrSource);
      }
      return this._redo(this.getUriComparisonKey(resourceOrSource));
    }
    _redo(strResource) {
      if (!this._editStacks.has(strResource)) {
        return;
      }
      const editStack = this._editStacks.get(strResource);
      const element = editStack.getClosestFutureElement();
      if (!element) {
        return;
      }
      if (element.groupId) {
        const [matchedElement, matchedStrResource] = this._findClosestRedoElementInGroup(element.groupId);
        if (element !== matchedElement && matchedStrResource) {
          return this._redo(matchedStrResource);
        }
      }
      try {
        if (element.type === 1) {
          return this._workspaceRedo(strResource, element);
        } else {
          return this._resourceRedo(editStack, element);
        }
      } finally {
      }
    }
  };
  UndoRedoService = __decorate$q([
    __param$p(0, IDialogService),
    __param$p(1, INotificationService)
  ], UndoRedoService);
  class WorkspaceVerificationError {
    constructor(returnValue) {
      this.returnValue = returnValue;
    }
  }
  registerSingleton(
    IUndoRedoService,
    UndoRedoService,
    1
    /* InstantiationType.Delayed */
  );
  var __decorate$p = 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$o = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  let SemanticTokensStylingService = class SemanticTokensStylingService extends Disposable {
    constructor(_themeService, _logService, _languageService) {
      super();
      this._themeService = _themeService;
      this._logService = _logService;
      this._languageService = _languageService;
      this._caches = /* @__PURE__ */ new WeakMap();
      this._register(this._themeService.onDidColorThemeChange(() => {
        this._caches = /* @__PURE__ */ new WeakMap();
      }));
    }
    getStyling(provider) {
      if (!this._caches.has(provider)) {
        this._caches.set(provider, new SemanticTokensProviderStyling(provider.getLegend(), this._themeService, this._languageService, this._logService));
      }
      return this._caches.get(provider);
    }
  };
  SemanticTokensStylingService = __decorate$p([
    __param$o(0, IThemeService),
    __param$o(1, ILogService),
    __param$o(2, ILanguageService)
  ], SemanticTokensStylingService);
  registerSingleton(
    ISemanticTokensStylingService,
    SemanticTokensStylingService,
    1
    /* InstantiationType.Delayed */
  );
  function isExclusive(selector) {
    if (typeof selector === "string") {
      return false;
    } else if (Array.isArray(selector)) {
      return selector.every(isExclusive);
    } else {
      return !!selector.exclusive;
    }
  }
  class MatchCandidate {
    constructor(uri, languageId, notebookUri, notebookType, recursive) {
      this.uri = uri;
      this.languageId = languageId;
      this.notebookUri = notebookUri;
      this.notebookType = notebookType;
      this.recursive = recursive;
    }
    equals(other) {
      return this.notebookType === other.notebookType && this.languageId === other.languageId && this.uri.toString() === other.uri.toString() && this.notebookUri?.toString() === other.notebookUri?.toString() && this.recursive === other.recursive;
    }
  }
  class LanguageFeatureRegistry {
    get onDidChange() {
      return this._onDidChange.event;
    }
    constructor(_notebookInfoResolver) {
      this._notebookInfoResolver = _notebookInfoResolver;
      this._clock = 0;
      this._entries = [];
      this._onDidChange = new Emitter$1();
    }
    register(selector, provider) {
      let entry = {
        selector,
        provider,
        _score: -1,
        _time: this._clock++
      };
      this._entries.push(entry);
      this._lastCandidate = void 0;
      this._onDidChange.fire(this._entries.length);
      return toDisposable(() => {
        if (entry) {
          const idx = this._entries.indexOf(entry);
          if (idx >= 0) {
            this._entries.splice(idx, 1);
            this._lastCandidate = void 0;
            this._onDidChange.fire(this._entries.length);
            entry = void 0;
          }
        }
      });
    }
    has(model) {
      return this.all(model).length > 0;
    }
    all(model) {
      if (!model) {
        return [];
      }
      this._updateScores(model, false);
      const result = [];
      for (const entry of this._entries) {
        if (entry._score > 0) {
          result.push(entry.provider);
        }
      }
      return result;
    }
    ordered(model, recursive = false) {
      const result = [];
      this._orderedForEach(model, recursive, (entry) => result.push(entry.provider));
      return result;
    }
    orderedGroups(model) {
      const result = [];
      let lastBucket;
      let lastBucketScore;
      this._orderedForEach(model, false, (entry) => {
        if (lastBucket && lastBucketScore === entry._score) {
          lastBucket.push(entry.provider);
        } else {
          lastBucketScore = entry._score;
          lastBucket = [entry.provider];
          result.push(lastBucket);
        }
      });
      return result;
    }
    _orderedForEach(model, recursive, callback) {
      this._updateScores(model, recursive);
      for (const entry of this._entries) {
        if (entry._score > 0) {
          callback(entry);
        }
      }
    }
    _updateScores(model, recursive) {
      const notebookInfo = this._notebookInfoResolver?.(model.uri);
      const candidate = notebookInfo ? new MatchCandidate(model.uri, model.getLanguageId(), notebookInfo.uri, notebookInfo.type, recursive) : new MatchCandidate(model.uri, model.getLanguageId(), void 0, void 0, recursive);
      if (this._lastCandidate?.equals(candidate)) {
        return;
      }
      this._lastCandidate = candidate;
      for (const entry of this._entries) {
        entry._score = score(entry.selector, candidate.uri, candidate.languageId, shouldSynchronizeModel(model), candidate.notebookUri, candidate.notebookType);
        if (isExclusive(entry.selector) && entry._score > 0) {
          if (recursive) {
            entry._score = 0;
          } else {
            for (const entry2 of this._entries) {
              entry2._score = 0;
            }
            entry._score = 1e3;
            break;
          }
        }
      }
      this._entries.sort(LanguageFeatureRegistry._compareByScoreAndTime);
    }
    static _compareByScoreAndTime(a, b) {
      if (a._score < b._score) {
        return 1;
      } else if (a._score > b._score) {
        return -1;
      }
      if (isBuiltinSelector(a.selector) && !isBuiltinSelector(b.selector)) {
        return 1;
      } else if (!isBuiltinSelector(a.selector) && isBuiltinSelector(b.selector)) {
        return -1;
      }
      if (a._time < b._time) {
        return 1;
      } else if (a._time > b._time) {
        return -1;
      } else {
        return 0;
      }
    }
  }
  function isBuiltinSelector(selector) {
    if (typeof selector === "string") {
      return false;
    }
    if (Array.isArray(selector)) {
      return selector.some(isBuiltinSelector);
    }
    return Boolean(selector.isBuiltin);
  }
  class LanguageFeaturesService {
    constructor() {
      this.referenceProvider = new LanguageFeatureRegistry(this._score.bind(this));
      this.renameProvider = new LanguageFeatureRegistry(this._score.bind(this));
      this.newSymbolNamesProvider = new LanguageFeatureRegistry(this._score.bind(this));
      this.codeActionProvider = new LanguageFeatureRegistry(this._score.bind(this));
      this.definitionProvider = new LanguageFeatureRegistry(this._score.bind(this));
      this.typeDefinitionProvider = new LanguageFeatureRegistry(this._score.bind(this));
      this.declarationProvider = new LanguageFeatureRegistry(this._score.bind(this));
      this.implementationProvider = new LanguageFeatureRegistry(this._score.bind(this));
      this.documentSymbolProvider = new LanguageFeatureRegistry(this._score.bind(this));
      this.inlayHintsProvider = new LanguageFeatureRegistry(this._score.bind(this));
      this.colorProvider = new LanguageFeatureRegistry(this._score.bind(this));
      this.codeLensProvider = new LanguageFeatureRegistry(this._score.bind(this));
      this.documentFormattingEditProvider = new LanguageFeatureRegistry(this._score.bind(this));
      this.documentRangeFormattingEditProvider = new LanguageFeatureRegistry(this._score.bind(this));
      this.onTypeFormattingEditProvider = new LanguageFeatureRegistry(this._score.bind(this));
      this.signatureHelpProvider = new LanguageFeatureRegistry(this._score.bind(this));
      this.hoverProvider = new LanguageFeatureRegistry(this._score.bind(this));
      this.documentHighlightProvider = new LanguageFeatureRegistry(this._score.bind(this));
      this.multiDocumentHighlightProvider = new LanguageFeatureRegistry(this._score.bind(this));
      this.selectionRangeProvider = new LanguageFeatureRegistry(this._score.bind(this));
      this.foldingRangeProvider = new LanguageFeatureRegistry(this._score.bind(this));
      this.linkProvider = new LanguageFeatureRegistry(this._score.bind(this));
      this.inlineCompletionsProvider = new LanguageFeatureRegistry(this._score.bind(this));
      this.completionProvider = new LanguageFeatureRegistry(this._score.bind(this));
      this.linkedEditingRangeProvider = new LanguageFeatureRegistry(this._score.bind(this));
      this.documentRangeSemanticTokensProvider = new LanguageFeatureRegistry(this._score.bind(this));
      this.documentSemanticTokensProvider = new LanguageFeatureRegistry(this._score.bind(this));
      this.documentDropEditProvider = new LanguageFeatureRegistry(this._score.bind(this));
      this.documentPasteEditProvider = new LanguageFeatureRegistry(this._score.bind(this));
    }
    _score(uri) {
      return this._notebookTypeResolver?.(uri);
    }
  }
  registerSingleton(
    ILanguageFeaturesService,
    LanguageFeaturesService,
    1
    /* InstantiationType.Delayed */
  );
  var __decorate$o = 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$n = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  const $$5 = $$l;
  let HoverWidget = class HoverWidget extends Widget$1 {
    get _targetWindow() {
      return getWindow(this._target.targetElements[0]);
    }
    get _targetDocumentElement() {
      return getWindow(this._target.targetElements[0]).document.documentElement;
    }
    get isDisposed() {
      return this._isDisposed;
    }
    get isMouseIn() {
      return this._lockMouseTracker.isMouseIn;
    }
    get domNode() {
      return this._hover.containerDomNode;
    }
    get onDispose() {
      return this._onDispose.event;
    }
    get onRequestLayout() {
      return this._onRequestLayout.event;
    }
    get anchor() {
      return this._hoverPosition === 2 ? 0 : 1;
    }
    get x() {
      return this._x;
    }
    get y() {
      return this._y;
    }
    /**
     * Whether the hover is "locked" by holding the alt/option key. When locked, the hover will not
     * hide and can be hovered regardless of whether the `hideOnHover` hover option is set.
     */
    get isLocked() {
      return this._isLocked;
    }
    set isLocked(value) {
      if (this._isLocked === value) {
        return;
      }
      this._isLocked = value;
      this._hoverContainer.classList.toggle("locked", this._isLocked);
    }
    constructor(options, _keybindingService, _configurationService, _markdownRenderer, _accessibilityService) {
      super();
      this._keybindingService = _keybindingService;
      this._configurationService = _configurationService;
      this._markdownRenderer = _markdownRenderer;
      this._accessibilityService = _accessibilityService;
      this._messageListeners = new DisposableStore();
      this._isDisposed = false;
      this._forcePosition = false;
      this._x = 0;
      this._y = 0;
      this._isLocked = false;
      this._enableFocusTraps = false;
      this._addedFocusTrap = false;
      this._maxHeightRatioRelativeToWindow = 0.5;
      this._onDispose = this._register(new Emitter$1());
      this._onRequestLayout = this._register(new Emitter$1());
      this._linkHandler = options.linkHandler;
      this._target = "targetElements" in options.target ? options.target : new ElementHoverTarget(options.target);
      if (options.style) {
        switch (options.style) {
          case 1: {
            options.appearance ??= {};
            options.appearance.compact ??= true;
            options.appearance.showPointer ??= true;
            break;
          }
          case 2: {
            options.appearance ??= {};
            options.appearance.compact ??= true;
            break;
          }
        }
      }
      this._hoverPointer = options.appearance?.showPointer ? $$5("div.workbench-hover-pointer") : void 0;
      this._hover = this._register(new HoverWidget$1(!options.appearance?.skipFadeInAnimation));
      this._hover.containerDomNode.classList.add("workbench-hover");
      if (options.appearance?.compact) {
        this._hover.containerDomNode.classList.add("workbench-hover", "compact");
      }
      if (options.additionalClasses) {
        this._hover.containerDomNode.classList.add(...options.additionalClasses);
      }
      if (options.position?.forcePosition) {
        this._forcePosition = true;
      }
      if (options.trapFocus) {
        this._enableFocusTraps = true;
      }
      const maxHeightRatio = options.appearance?.maxHeightRatio;
      if (maxHeightRatio !== void 0 && maxHeightRatio > 0 && maxHeightRatio <= 1) {
        this._maxHeightRatioRelativeToWindow = maxHeightRatio;
      }
      this._hoverPosition = options.position?.hoverPosition === void 0 ? 3 : isNumber$1(options.position.hoverPosition) ? options.position.hoverPosition : 2;
      this.onmousedown(this._hover.containerDomNode, (e) => e.stopPropagation());
      this.onkeydown(this._hover.containerDomNode, (e) => {
        if (e.equals(
          9
          /* KeyCode.Escape */
        )) {
          this.dispose();
        }
      });
      this._register(addDisposableListener(this._targetWindow, "blur", () => this.dispose()));
      const rowElement = $$5("div.hover-row.markdown-hover");
      const contentsElement = $$5("div.hover-contents");
      if (typeof options.content === "string") {
        contentsElement.textContent = options.content;
        contentsElement.style.whiteSpace = "pre-wrap";
      } else if (isHTMLElement(options.content)) {
        contentsElement.appendChild(options.content);
        contentsElement.classList.add("html-hover-contents");
      } else {
        const markdown = options.content;
        const { element } = this._register(this._markdownRenderer.render(markdown, {
          actionHandler: this._linkHandler,
          asyncRenderCallback: () => {
            contentsElement.classList.add("code-hover-contents");
            this.layout();
            this._onRequestLayout.fire();
          }
        }));
        contentsElement.appendChild(element);
      }
      rowElement.appendChild(contentsElement);
      this._hover.contentsDomNode.appendChild(rowElement);
      if (options.actions && options.actions.length > 0) {
        const statusBarElement = $$5("div.hover-row.status-bar");
        const actionsElement = $$5("div.actions");
        options.actions.forEach((action) => {
          const keybinding = this._keybindingService.lookupKeybinding(action.commandId);
          const keybindingLabel = keybinding ? keybinding.getLabel() : null;
          this._register(HoverAction.render(actionsElement, {
            label: action.label,
            commandId: action.commandId,
            run: (e) => {
              action.run(e);
              this.dispose();
            },
            iconClass: action.iconClass
          }, keybindingLabel));
        });
        statusBarElement.appendChild(actionsElement);
        this._hover.containerDomNode.appendChild(statusBarElement);
      }
      this._hoverContainer = $$5("div.workbench-hover-container");
      if (this._hoverPointer) {
        this._hoverContainer.appendChild(this._hoverPointer);
      }
      this._hoverContainer.appendChild(this._hover.containerDomNode);
      let hideOnHover;
      if (options.actions && options.actions.length > 0) {
        hideOnHover = false;
      } else {
        if (options.persistence?.hideOnHover === void 0) {
          hideOnHover = typeof options.content === "string" || isMarkdownString(options.content) && !options.content.value.includes("](") && !options.content.value.includes("</a>");
        } else {
          hideOnHover = options.persistence.hideOnHover;
        }
      }
      if (options.appearance?.showHoverHint) {
        const statusBarElement = $$5("div.hover-row.status-bar");
        const infoElement = $$5("div.info");
        infoElement.textContent = localize(1699, "Hold {0} key to mouse over", isMacintosh ? "Option" : "Alt");
        statusBarElement.appendChild(infoElement);
        this._hover.containerDomNode.appendChild(statusBarElement);
      }
      const mouseTrackerTargets = [...this._target.targetElements];
      if (!hideOnHover) {
        mouseTrackerTargets.push(this._hoverContainer);
      }
      const mouseTracker = this._register(new CompositeMouseTracker(mouseTrackerTargets));
      this._register(mouseTracker.onMouseOut(() => {
        if (!this._isLocked) {
          this.dispose();
        }
      }));
      if (hideOnHover) {
        const mouseTracker2Targets = [...this._target.targetElements, this._hoverContainer];
        this._lockMouseTracker = this._register(new CompositeMouseTracker(mouseTracker2Targets));
        this._register(this._lockMouseTracker.onMouseOut(() => {
          if (!this._isLocked) {
            this.dispose();
          }
        }));
      } else {
        this._lockMouseTracker = mouseTracker;
      }
    }
    addFocusTrap() {
      if (!this._enableFocusTraps || this._addedFocusTrap) {
        return;
      }
      this._addedFocusTrap = true;
      const firstContainerFocusElement = this._hover.containerDomNode;
      const lastContainerFocusElement = this.findLastFocusableChild(this._hover.containerDomNode);
      if (lastContainerFocusElement) {
        const beforeContainerFocusElement = prepend$2(this._hoverContainer, $$5("div"));
        const afterContainerFocusElement = append$2(this._hoverContainer, $$5("div"));
        beforeContainerFocusElement.tabIndex = 0;
        afterContainerFocusElement.tabIndex = 0;
        this._register(addDisposableListener(afterContainerFocusElement, "focus", (e) => {
          firstContainerFocusElement.focus();
          e.preventDefault();
        }));
        this._register(addDisposableListener(beforeContainerFocusElement, "focus", (e) => {
          lastContainerFocusElement.focus();
          e.preventDefault();
        }));
      }
    }
    findLastFocusableChild(root) {
      if (root.hasChildNodes()) {
        for (let i2 = 0; i2 < root.childNodes.length; i2++) {
          const node = root.childNodes.item(root.childNodes.length - i2 - 1);
          if (node.nodeType === node.ELEMENT_NODE) {
            const parsedNode = node;
            if (typeof parsedNode.tabIndex === "number" && parsedNode.tabIndex >= 0) {
              return parsedNode;
            }
          }
          const recursivelyFoundElement = this.findLastFocusableChild(node);
          if (recursivelyFoundElement) {
            return recursivelyFoundElement;
          }
        }
      }
      return void 0;
    }
    render(container) {
      container.appendChild(this._hoverContainer);
      const hoverFocused = this._hoverContainer.contains(this._hoverContainer.ownerDocument.activeElement);
      const accessibleViewHint = hoverFocused && getHoverAccessibleViewHint(this._configurationService.getValue("accessibility.verbosity.hover") === true && this._accessibilityService.isScreenReaderOptimized(), this._keybindingService.lookupKeybinding("editor.action.accessibleView")?.getAriaLabel());
      if (accessibleViewHint) {
        status(accessibleViewHint);
      }
      this.layout();
      this.addFocusTrap();
    }
    layout() {
      this._hover.containerDomNode.classList.remove("right-aligned");
      this._hover.contentsDomNode.style.maxHeight = "";
      const getZoomAccountedBoundingClientRect = (e) => {
        const zoom = getDomNodeZoomLevel(e);
        const boundingRect = e.getBoundingClientRect();
        return {
          top: boundingRect.top * zoom,
          bottom: boundingRect.bottom * zoom,
          right: boundingRect.right * zoom,
          left: boundingRect.left * zoom
        };
      };
      const targetBounds = this._target.targetElements.map((e) => getZoomAccountedBoundingClientRect(e));
      const { top, right, bottom, left } = targetBounds[0];
      const width2 = right - left;
      const height = bottom - top;
      const targetRect = {
        top,
        right,
        bottom,
        left,
        width: width2,
        height,
        center: {
          x: left + width2 / 2,
          y: top + height / 2
        }
      };
      this.adjustHorizontalHoverPosition(targetRect);
      this.adjustVerticalHoverPosition(targetRect);
      this.adjustHoverMaxHeight(targetRect);
      this._hoverContainer.style.padding = "";
      this._hoverContainer.style.margin = "";
      if (this._hoverPointer) {
        switch (this._hoverPosition) {
          case 1:
            targetRect.left += 3;
            targetRect.right += 3;
            this._hoverContainer.style.paddingLeft = `${3}px`;
            this._hoverContainer.style.marginLeft = `${-3}px`;
            break;
          case 0:
            targetRect.left -= 3;
            targetRect.right -= 3;
            this._hoverContainer.style.paddingRight = `${3}px`;
            this._hoverContainer.style.marginRight = `${-3}px`;
            break;
          case 2:
            targetRect.top += 3;
            targetRect.bottom += 3;
            this._hoverContainer.style.paddingTop = `${3}px`;
            this._hoverContainer.style.marginTop = `${-3}px`;
            break;
          case 3:
            targetRect.top -= 3;
            targetRect.bottom -= 3;
            this._hoverContainer.style.paddingBottom = `${3}px`;
            this._hoverContainer.style.marginBottom = `${-3}px`;
            break;
        }
        targetRect.center.x = targetRect.left + width2 / 2;
        targetRect.center.y = targetRect.top + height / 2;
      }
      this.computeXCordinate(targetRect);
      this.computeYCordinate(targetRect);
      if (this._hoverPointer) {
        this._hoverPointer.classList.remove("top");
        this._hoverPointer.classList.remove("left");
        this._hoverPointer.classList.remove("right");
        this._hoverPointer.classList.remove("bottom");
        this.setHoverPointerPosition(targetRect);
      }
      this._hover.onContentsChanged();
    }
    computeXCordinate(target) {
      const hoverWidth = this._hover.containerDomNode.clientWidth + 2;
      if (this._target.x !== void 0) {
        this._x = this._target.x;
      } else if (this._hoverPosition === 1) {
        this._x = target.right;
      } else if (this._hoverPosition === 0) {
        this._x = target.left - hoverWidth;
      } else {
        if (this._hoverPointer) {
          this._x = target.center.x - this._hover.containerDomNode.clientWidth / 2;
        } else {
          this._x = target.left;
        }
        if (this._x + hoverWidth >= this._targetDocumentElement.clientWidth) {
          this._hover.containerDomNode.classList.add("right-aligned");
          this._x = Math.max(this._targetDocumentElement.clientWidth - hoverWidth - 2, this._targetDocumentElement.clientLeft);
        }
      }
      if (this._x < this._targetDocumentElement.clientLeft) {
        this._x = target.left + 2;
      }
    }
    computeYCordinate(target) {
      if (this._target.y !== void 0) {
        this._y = this._target.y;
      } else if (this._hoverPosition === 3) {
        this._y = target.top;
      } else if (this._hoverPosition === 2) {
        this._y = target.bottom - 2;
      } else {
        if (this._hoverPointer) {
          this._y = target.center.y + this._hover.containerDomNode.clientHeight / 2;
        } else {
          this._y = target.bottom;
        }
      }
      if (this._y > this._targetWindow.innerHeight) {
        this._y = target.bottom;
      }
    }
    adjustHorizontalHoverPosition(target) {
      if (this._target.x !== void 0) {
        return;
      }
      const hoverPointerOffset = this._hoverPointer ? 3 : 0;
      if (this._forcePosition) {
        const padding = hoverPointerOffset + 2;
        if (this._hoverPosition === 1) {
          this._hover.containerDomNode.style.maxWidth = `${this._targetDocumentElement.clientWidth - target.right - padding}px`;
        } else if (this._hoverPosition === 0) {
          this._hover.containerDomNode.style.maxWidth = `${target.left - padding}px`;
        }
        return;
      }
      if (this._hoverPosition === 1) {
        const roomOnRight = this._targetDocumentElement.clientWidth - target.right;
        if (roomOnRight < this._hover.containerDomNode.clientWidth + hoverPointerOffset) {
          const roomOnLeft = target.left;
          if (roomOnLeft >= this._hover.containerDomNode.clientWidth + hoverPointerOffset) {
            this._hoverPosition = 0;
          } else {
            this._hoverPosition = 2;
          }
        }
      } else if (this._hoverPosition === 0) {
        const roomOnLeft = target.left;
        if (roomOnLeft < this._hover.containerDomNode.clientWidth + hoverPointerOffset) {
          const roomOnRight = this._targetDocumentElement.clientWidth - target.right;
          if (roomOnRight >= this._hover.containerDomNode.clientWidth + hoverPointerOffset) {
            this._hoverPosition = 1;
          } else {
            this._hoverPosition = 2;
          }
        }
        if (target.left - this._hover.containerDomNode.clientWidth - hoverPointerOffset <= this._targetDocumentElement.clientLeft) {
          this._hoverPosition = 1;
        }
      }
    }
    adjustVerticalHoverPosition(target) {
      if (this._target.y !== void 0 || this._forcePosition) {
        return;
      }
      const hoverPointerOffset = this._hoverPointer ? 3 : 0;
      if (this._hoverPosition === 3) {
        if (target.top - this._hover.containerDomNode.clientHeight - hoverPointerOffset < 0) {
          this._hoverPosition = 2;
        }
      } else if (this._hoverPosition === 2) {
        if (target.bottom + this._hover.containerDomNode.offsetHeight + hoverPointerOffset > this._targetWindow.innerHeight) {
          this._hoverPosition = 3;
        }
      }
    }
    adjustHoverMaxHeight(target) {
      let maxHeight = this._targetWindow.innerHeight * this._maxHeightRatioRelativeToWindow;
      if (this._forcePosition) {
        const padding = (this._hoverPointer ? 3 : 0) + 2;
        if (this._hoverPosition === 3) {
          maxHeight = Math.min(maxHeight, target.top - padding);
        } else if (this._hoverPosition === 2) {
          maxHeight = Math.min(maxHeight, this._targetWindow.innerHeight - target.bottom - padding);
        }
      }
      this._hover.containerDomNode.style.maxHeight = `${maxHeight}px`;
      if (this._hover.contentsDomNode.clientHeight < this._hover.contentsDomNode.scrollHeight) {
        const extraRightPadding = `${this._hover.scrollbar.options.verticalScrollbarSize}px`;
        if (this._hover.contentsDomNode.style.paddingRight !== extraRightPadding) {
          this._hover.contentsDomNode.style.paddingRight = extraRightPadding;
        }
      }
    }
    setHoverPointerPosition(target) {
      if (!this._hoverPointer) {
        return;
      }
      switch (this._hoverPosition) {
        case 0:
        case 1: {
          this._hoverPointer.classList.add(this._hoverPosition === 0 ? "right" : "left");
          const hoverHeight = this._hover.containerDomNode.clientHeight;
          if (hoverHeight > target.height) {
            this._hoverPointer.style.top = `${target.center.y - (this._y - hoverHeight) - 3}px`;
          } else {
            this._hoverPointer.style.top = `${Math.round(hoverHeight / 2) - 3}px`;
          }
          break;
        }
        case 3:
        case 2: {
          this._hoverPointer.classList.add(this._hoverPosition === 3 ? "bottom" : "top");
          const hoverWidth = this._hover.containerDomNode.clientWidth;
          let pointerLeftPosition = Math.round(hoverWidth / 2) - 3;
          const pointerX = this._x + pointerLeftPosition;
          if (pointerX < target.left || pointerX > target.right) {
            pointerLeftPosition = target.center.x - this._x - 3;
          }
          this._hoverPointer.style.left = `${pointerLeftPosition}px`;
          break;
        }
      }
    }
    focus() {
      this._hover.containerDomNode.focus();
    }
    dispose() {
      if (!this._isDisposed) {
        this._onDispose.fire();
        this._target.dispose?.();
        this._hoverContainer.remove();
        this._messageListeners.dispose();
        super.dispose();
      }
      this._isDisposed = true;
    }
  };
  HoverWidget = __decorate$o([
    __param$n(1, IKeybindingService),
    __param$n(2, IConfigurationService),
    __param$n(3, IMarkdownRendererService),
    __param$n(4, IAccessibilityService)
  ], HoverWidget);
  class CompositeMouseTracker extends Widget$1 {
    get onMouseOut() {
      return this._onMouseOut.event;
    }
    get isMouseIn() {
      return this._isMouseIn;
    }
    /**
     * @param _elements The target elements to track mouse in/out events on.
     * @param _eventDebounceDelay The delay in ms to debounce the event firing. This is used to
     * allow a short period for the mouse to move into the hover or a nearby target element. For
     * example hovering a scroll bar will not hide the hover immediately.
     */
    constructor(_elements, _eventDebounceDelay = 200) {
      super();
      this._elements = _elements;
      this._eventDebounceDelay = _eventDebounceDelay;
      this._isMouseIn = true;
      this._mouseTimer = this._register(new MutableDisposable());
      this._onMouseOut = this._register(new Emitter$1());
      for (const element of this._elements) {
        this.onmouseover(element, () => this._onTargetMouseOver());
        this.onmouseleave(element, () => this._onTargetMouseLeave());
      }
    }
    _onTargetMouseOver() {
      this._isMouseIn = true;
      this._mouseTimer.clear();
    }
    _onTargetMouseLeave() {
      this._isMouseIn = false;
      this._mouseTimer.value = new TimeoutTimer(() => this._fireIfMouseOutside(), this._eventDebounceDelay);
    }
    _fireIfMouseOutside() {
      if (!this._isMouseIn) {
        this._onMouseOut.fire();
      }
    }
  }
  class ElementHoverTarget {
    constructor(_element) {
      this._element = _element;
      this.targetElements = [this._element];
    }
    dispose() {
    }
  }
  function isAnchor(obj) {
    const anchor = obj;
    return !!anchor && typeof anchor.x === "number" && typeof anchor.y === "number";
  }
  var LayoutAnchorMode;
  (function(LayoutAnchorMode2) {
    LayoutAnchorMode2[LayoutAnchorMode2["AVOID"] = 0] = "AVOID";
    LayoutAnchorMode2[LayoutAnchorMode2["ALIGN"] = 1] = "ALIGN";
  })(LayoutAnchorMode || (LayoutAnchorMode = {}));
  function layout(viewportSize, viewSize, anchor) {
    const layoutAfterAnchorBoundary = anchor.mode === LayoutAnchorMode.ALIGN ? anchor.offset : anchor.offset + anchor.size;
    const layoutBeforeAnchorBoundary = anchor.mode === LayoutAnchorMode.ALIGN ? anchor.offset + anchor.size : anchor.offset;
    if (anchor.position === 0) {
      if (viewSize <= viewportSize - layoutAfterAnchorBoundary) {
        return layoutAfterAnchorBoundary;
      }
      if (viewSize <= layoutBeforeAnchorBoundary) {
        return layoutBeforeAnchorBoundary - viewSize;
      }
      return Math.max(viewportSize - viewSize, 0);
    } else {
      if (viewSize <= layoutBeforeAnchorBoundary) {
        return layoutBeforeAnchorBoundary - viewSize;
      }
      if (viewSize <= viewportSize - layoutAfterAnchorBoundary) {
        return layoutAfterAnchorBoundary;
      }
      return 0;
    }
  }
  const _ContextView = class _ContextView extends Disposable {
    constructor(container, domPosition) {
      super();
      this.container = null;
      this.useFixedPosition = false;
      this.useShadowDOM = false;
      this.delegate = null;
      this.toDisposeOnClean = Disposable.None;
      this.toDisposeOnSetContainer = Disposable.None;
      this.shadowRoot = null;
      this.shadowRootHostElement = null;
      this.view = $$l(".context-view");
      hide(this.view);
      this.setContainer(container, domPosition);
      this._register(toDisposable(() => this.setContainer(
        null,
        1
        /* ContextViewDOMPosition.ABSOLUTE */
      )));
    }
    setContainer(container, domPosition) {
      this.useFixedPosition = domPosition !== 1;
      const usedShadowDOM = this.useShadowDOM;
      this.useShadowDOM = domPosition === 3;
      if (container === this.container && usedShadowDOM === this.useShadowDOM) {
        return;
      }
      if (this.container) {
        this.toDisposeOnSetContainer.dispose();
        this.view.remove();
        if (this.shadowRoot) {
          this.shadowRoot = null;
          this.shadowRootHostElement?.remove();
          this.shadowRootHostElement = null;
        }
        this.container = null;
      }
      if (container) {
        this.container = container;
        if (this.useShadowDOM) {
          this.shadowRootHostElement = $$l(".shadow-root-host");
          this.container.appendChild(this.shadowRootHostElement);
          this.shadowRoot = this.shadowRootHostElement.attachShadow({ mode: "open" });
          const style = document.createElement("style");
          style.textContent = SHADOW_ROOT_CSS;
          this.shadowRoot.appendChild(style);
          this.shadowRoot.appendChild(this.view);
          this.shadowRoot.appendChild($$l("slot"));
        } else {
          this.container.appendChild(this.view);
        }
        const toDisposeOnSetContainer = new DisposableStore();
        _ContextView.BUBBLE_UP_EVENTS.forEach((event) => {
          toDisposeOnSetContainer.add(addStandardDisposableListener(this.container, event, (e) => {
            this.onDOMEvent(e, false);
          }));
        });
        _ContextView.BUBBLE_DOWN_EVENTS.forEach((event) => {
          toDisposeOnSetContainer.add(addStandardDisposableListener(this.container, event, (e) => {
            this.onDOMEvent(e, true);
          }, true));
        });
        this.toDisposeOnSetContainer = toDisposeOnSetContainer;
      }
    }
    show(delegate) {
      if (this.isVisible()) {
        this.hide();
      }
      clearNode(this.view);
      this.view.className = "context-view monaco-component";
      this.view.style.top = "0px";
      this.view.style.left = "0px";
      this.view.style.zIndex = `${2575 + (delegate.layer ?? 0)}`;
      this.view.style.position = this.useFixedPosition ? "fixed" : "absolute";
      show(this.view);
      this.toDisposeOnClean = delegate.render(this.view) || Disposable.None;
      this.delegate = delegate;
      this.doLayout();
      this.delegate.focus?.();
    }
    getViewElement() {
      return this.view;
    }
    layout() {
      if (!this.isVisible()) {
        return;
      }
      if (this.delegate.canRelayout === false && !(isIOS && BrowserFeatures.pointerEvents)) {
        this.hide();
        return;
      }
      this.delegate?.layout?.();
      this.doLayout();
    }
    doLayout() {
      if (!this.isVisible()) {
        return;
      }
      const anchor = this.delegate.getAnchor();
      let around;
      if (isHTMLElement(anchor)) {
        const elementPosition = getDomNodePagePosition(anchor);
        const zoom = getDomNodeZoomLevel(anchor);
        around = {
          top: elementPosition.top * zoom,
          left: elementPosition.left * zoom,
          width: elementPosition.width * zoom,
          height: elementPosition.height * zoom
        };
      } else if (isAnchor(anchor)) {
        around = {
          top: anchor.y,
          left: anchor.x,
          width: anchor.width || 1,
          height: anchor.height || 2
        };
      } else {
        around = {
          top: anchor.posy,
          left: anchor.posx,
          // We are about to position the context view where the mouse
          // cursor is. To prevent the view being exactly under the mouse
          // when showing and thus potentially triggering an action within,
          // we treat the mouse location like a small sized block element.
          width: 2,
          height: 2
        };
      }
      const viewSizeWidth = getTotalWidth(this.view);
      const viewSizeHeight = getTotalHeight(this.view);
      const anchorPosition = this.delegate.anchorPosition ?? 0;
      const anchorAlignment = this.delegate.anchorAlignment ?? 0;
      const anchorAxisAlignment = this.delegate.anchorAxisAlignment ?? 0;
      let top;
      let left;
      const activeWindow = getActiveWindow();
      if (anchorAxisAlignment === 0) {
        const verticalAnchor = {
          offset: around.top - activeWindow.pageYOffset,
          size: around.height,
          position: anchorPosition === 0 ? 0 : 1
          /* LayoutAnchorPosition.After */
        };
        const horizontalAnchor = { offset: around.left, size: around.width, position: anchorAlignment === 0 ? 0 : 1, mode: LayoutAnchorMode.ALIGN };
        top = layout(activeWindow.innerHeight, viewSizeHeight, verticalAnchor) + activeWindow.pageYOffset;
        if (Range$1.intersects({ start: top, end: top + viewSizeHeight }, { start: verticalAnchor.offset, end: verticalAnchor.offset + verticalAnchor.size })) {
          horizontalAnchor.mode = LayoutAnchorMode.AVOID;
        }
        left = layout(activeWindow.innerWidth, viewSizeWidth, horizontalAnchor);
      } else {
        const horizontalAnchor = {
          offset: around.left,
          size: around.width,
          position: anchorAlignment === 0 ? 0 : 1
          /* LayoutAnchorPosition.After */
        };
        const verticalAnchor = { offset: around.top, size: around.height, position: anchorPosition === 0 ? 0 : 1, mode: LayoutAnchorMode.ALIGN };
        left = layout(activeWindow.innerWidth, viewSizeWidth, horizontalAnchor);
        if (Range$1.intersects({ start: left, end: left + viewSizeWidth }, { start: horizontalAnchor.offset, end: horizontalAnchor.offset + horizontalAnchor.size })) {
          verticalAnchor.mode = LayoutAnchorMode.AVOID;
        }
        top = layout(activeWindow.innerHeight, viewSizeHeight, verticalAnchor) + activeWindow.pageYOffset;
      }
      this.view.classList.remove("top", "bottom", "left", "right");
      this.view.classList.add(anchorPosition === 0 ? "bottom" : "top");
      this.view.classList.add(anchorAlignment === 0 ? "left" : "right");
      this.view.classList.toggle("fixed", this.useFixedPosition);
      const containerPosition = getDomNodePagePosition(this.container);
      const containerScrollTop = this.container.scrollTop || 0;
      const containerScrollLeft = this.container.scrollLeft || 0;
      this.view.style.top = `${top - (this.useFixedPosition ? getDomNodePagePosition(this.view).top : containerPosition.top) + containerScrollTop}px`;
      this.view.style.left = `${left - (this.useFixedPosition ? getDomNodePagePosition(this.view).left : containerPosition.left) + containerScrollLeft}px`;
      this.view.style.width = "initial";
    }
    hide(data) {
      const delegate = this.delegate;
      this.delegate = null;
      if (delegate?.onHide) {
        delegate.onHide(data);
      }
      this.toDisposeOnClean.dispose();
      hide(this.view);
    }
    isVisible() {
      return !!this.delegate;
    }
    onDOMEvent(e, onCapture) {
      if (this.delegate) {
        if (this.delegate.onDOMEvent) {
          this.delegate.onDOMEvent(e, getWindow(e).document.activeElement);
        } else if (onCapture && !isAncestor$1(e.target, this.container)) {
          this.hide();
        }
      }
    }
    dispose() {
      this.hide();
      super.dispose();
    }
  };
  _ContextView.BUBBLE_UP_EVENTS = ["click", "keydown", "focus", "blur"];
  _ContextView.BUBBLE_DOWN_EVENTS = ["click"];
  let ContextView = _ContextView;
  const SHADOW_ROOT_CSS = (
    /* css */
    `
	:host {
		all: initial; /* 1st rule so subsequent properties are reset. */
	}

	.codicon[class*='codicon-'] {
		font: normal normal normal 16px/1 codicon;
		display: inline-block;
		text-decoration: none;
		text-rendering: auto;
		text-align: center;
		-webkit-font-smoothing: antialiased;
		-moz-osx-font-smoothing: grayscale;
		user-select: none;
		-webkit-user-select: none;
		-ms-user-select: none;
	}

	:host {
		font-family: -apple-system, BlinkMacSystemFont, "Segoe WPC", "Segoe UI", "HelveticaNeue-Light", system-ui, "Ubuntu", "Droid Sans", sans-serif;
	}

	:host-context(.mac) { font-family: -apple-system, BlinkMacSystemFont, sans-serif; }
	:host-context(.mac:lang(zh-Hans)) { font-family: -apple-system, BlinkMacSystemFont, "PingFang SC", "Hiragino Sans GB", sans-serif; }
	:host-context(.mac:lang(zh-Hant)) { font-family: -apple-system, BlinkMacSystemFont, "PingFang TC", sans-serif; }
	:host-context(.mac:lang(ja)) { font-family: -apple-system, BlinkMacSystemFont, "Hiragino Kaku Gothic Pro", sans-serif; }
	:host-context(.mac:lang(ko)) { font-family: -apple-system, BlinkMacSystemFont, "Apple SD Gothic Neo", "Nanum Gothic", "AppleGothic", sans-serif; }

	:host-context(.windows) { font-family: "Segoe WPC", "Segoe UI", sans-serif; }
	:host-context(.windows:lang(zh-Hans)) { font-family: "Segoe WPC", "Segoe UI", "Microsoft YaHei", sans-serif; }
	:host-context(.windows:lang(zh-Hant)) { font-family: "Segoe WPC", "Segoe UI", "Microsoft Jhenghei", sans-serif; }
	:host-context(.windows:lang(ja)) { font-family: "Segoe WPC", "Segoe UI", "Yu Gothic UI", "Meiryo UI", sans-serif; }
	:host-context(.windows:lang(ko)) { font-family: "Segoe WPC", "Segoe UI", "Malgun Gothic", "Dotom", sans-serif; }

	:host-context(.linux) { font-family: system-ui, "Ubuntu", "Droid Sans", sans-serif; }
	:host-context(.linux:lang(zh-Hans)) { font-family: system-ui, "Ubuntu", "Droid Sans", "Source Han Sans SC", "Source Han Sans CN", "Source Han Sans", sans-serif; }
	:host-context(.linux:lang(zh-Hant)) { font-family: system-ui, "Ubuntu", "Droid Sans", "Source Han Sans TC", "Source Han Sans TW", "Source Han Sans", sans-serif; }
	:host-context(.linux:lang(ja)) { font-family: system-ui, "Ubuntu", "Droid Sans", "Source Han Sans J", "Source Han Sans JP", "Source Han Sans", sans-serif; }
	:host-context(.linux:lang(ko)) { font-family: system-ui, "Ubuntu", "Droid Sans", "Source Han Sans K", "Source Han Sans JR", "Source Han Sans", "UnDotum", "FBaekmuk Gulim", sans-serif; }
`
  );
  var __decorate$n = 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$m = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  let ContextViewHandler = class ContextViewHandler extends Disposable {
    constructor(layoutService) {
      super();
      this.layoutService = layoutService;
      this.contextView = this._register(new ContextView(
        this.layoutService.mainContainer,
        1
        /* ContextViewDOMPosition.ABSOLUTE */
      ));
      this.layout();
      this._register(layoutService.onDidLayoutContainer(() => this.layout()));
    }
    // ContextView
    showContextView(delegate, container, shadowRoot) {
      let domPosition;
      if (container) {
        if (container === this.layoutService.getContainer(getWindow(container))) {
          domPosition = 1;
        } else if (shadowRoot) {
          domPosition = 3;
        } else {
          domPosition = 2;
        }
      } else {
        domPosition = 1;
      }
      this.contextView.setContainer(container ?? this.layoutService.activeContainer, domPosition);
      this.contextView.show(delegate);
      const openContextView = {
        close: () => {
          if (this.openContextView === openContextView) {
            this.hideContextView();
          }
        }
      };
      this.openContextView = openContextView;
      return openContextView;
    }
    layout() {
      this.contextView.layout();
    }
    hideContextView(data) {
      this.contextView.hide(data);
      this.openContextView = void 0;
    }
  };
  ContextViewHandler = __decorate$n([
    __param$m(0, ILayoutService)
  ], ContextViewHandler);
  class ContextViewService extends ContextViewHandler {
    getContextViewElement() {
      return this.contextView.getViewElement();
    }
  }
  function isManagedHoverTooltipMarkdownString(obj) {
    const candidate = obj;
    return typeof candidate === "object" && "markdown" in candidate && "markdownNotSupportedFallback" in candidate;
  }
  class ManagedHoverWidget {
    constructor(hoverDelegate, target, fadeInAnimation) {
      this.hoverDelegate = hoverDelegate;
      this.target = target;
      this.fadeInAnimation = fadeInAnimation;
    }
    async update(content, focus, options) {
      if (this._cancellationTokenSource) {
        this._cancellationTokenSource.dispose(true);
        this._cancellationTokenSource = void 0;
      }
      if (this.isDisposed) {
        return;
      }
      let resolvedContent;
      if (isString$1(content) || isHTMLElement(content) || content === void 0) {
        resolvedContent = content;
      } else {
        this._cancellationTokenSource = new CancellationTokenSource$1();
        const token = this._cancellationTokenSource.token;
        let managedContent;
        if (isManagedHoverTooltipMarkdownString(content)) {
          if (isFunction(content.markdown)) {
            managedContent = content.markdown(token).then((resolvedContent2) => resolvedContent2 ?? content.markdownNotSupportedFallback);
          } else {
            managedContent = content.markdown ?? content.markdownNotSupportedFallback;
          }
        } else {
          managedContent = content.element(token);
        }
        if (managedContent instanceof Promise) {
          if (!this._hoverWidget) {
            this.show(localize(1700, "Loading..."), focus, options);
          }
          resolvedContent = await managedContent;
        } else {
          resolvedContent = managedContent;
        }
        if (this.isDisposed || token.isCancellationRequested) {
          return;
        }
      }
      this.show(resolvedContent, focus, options);
    }
    show(content, focus, options) {
      const oldHoverWidget = this._hoverWidget;
      if (this.hasContent(content)) {
        const hoverOptions = {
          content,
          target: this.target,
          actions: options?.actions,
          linkHandler: options?.linkHandler,
          trapFocus: options?.trapFocus,
          appearance: {
            showPointer: this.hoverDelegate.placement === "element",
            skipFadeInAnimation: !this.fadeInAnimation || !!oldHoverWidget,
            // do not fade in if the hover is already showing
            showHoverHint: options?.appearance?.showHoverHint
          },
          position: {
            hoverPosition: 2
          }
        };
        this._hoverWidget = this.hoverDelegate.showHover(hoverOptions, focus);
      }
      oldHoverWidget?.dispose();
    }
    hasContent(content) {
      if (!content) {
        return false;
      }
      if (isMarkdownString(content)) {
        return !!content.value;
      }
      return true;
    }
    get isDisposed() {
      return this._hoverWidget?.isDisposed;
    }
    dispose() {
      this._hoverWidget?.dispose();
      this._cancellationTokenSource?.dispose(true);
      this._cancellationTokenSource = void 0;
    }
  }
  var __decorate$m = 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$l = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  let HoverService = class HoverService extends Disposable {
    constructor(_instantiationService, _configurationService, contextMenuService, _keybindingService, _layoutService, _accessibilityService) {
      super();
      this._instantiationService = _instantiationService;
      this._configurationService = _configurationService;
      this._keybindingService = _keybindingService;
      this._layoutService = _layoutService;
      this._accessibilityService = _accessibilityService;
      this._currentDelayedHoverWasShown = false;
      this._delayedHovers = /* @__PURE__ */ new Map();
      this._managedHovers = /* @__PURE__ */ new Map();
      this._register(contextMenuService.onDidShowContextMenu(() => this.hideHover()));
      this._contextViewHandler = this._register(new ContextViewHandler(this._layoutService));
      this._register(KeybindingsRegistry.registerCommandAndKeybindingRule({
        id: "workbench.action.showHover",
        weight: 0,
        primary: KeyChord(
          2048 | 41,
          2048 | 39
          /* KeyCode.KeyI */
        ),
        handler: () => {
          this._showAndFocusHoverForActiveElement();
        }
      }));
    }
    showInstantHover(options, focus, skipLastFocusedUpdate, dontShow) {
      const hover = this._createHover(options, skipLastFocusedUpdate);
      if (!hover) {
        return void 0;
      }
      this._showHover(hover, options, focus);
      return hover;
    }
    showDelayedHover(options, lifecycleOptions) {
      if (options.id === void 0) {
        options.id = getHoverIdFromContent(options.content);
      }
      if (!this._currentDelayedHover || this._currentDelayedHoverWasShown) {
        if (this._currentHover?.isLocked) {
          return void 0;
        }
        if (getHoverOptionsIdentity(this._currentHoverOptions) === getHoverOptionsIdentity(options)) {
          return this._currentHover;
        }
        if (this._currentHover && !this._currentHover.isDisposed && this._currentDelayedHoverGroupId !== void 0 && this._currentDelayedHoverGroupId === lifecycleOptions?.groupId) {
          return this.showInstantHover({
            ...options,
            appearance: {
              ...options.appearance,
              skipFadeInAnimation: true
            }
          });
        }
      } else if (this._currentDelayedHover && getHoverOptionsIdentity(this._currentHoverOptions) === getHoverOptionsIdentity(options)) {
        return this._currentDelayedHover;
      }
      const hover = this._createHover(options, void 0);
      if (!hover) {
        this._currentDelayedHover = void 0;
        this._currentDelayedHoverWasShown = false;
        this._currentDelayedHoverGroupId = void 0;
        return void 0;
      }
      this._currentDelayedHover = hover;
      this._currentDelayedHoverWasShown = false;
      this._currentDelayedHoverGroupId = lifecycleOptions?.groupId;
      timeout(this._configurationService.getValue("workbench.hover.delay")).then(() => {
        if (hover && !hover.isDisposed) {
          this._currentDelayedHoverWasShown = true;
          this._showHover(hover, options);
        }
      });
      return hover;
    }
    setupDelayedHover(target, options, lifecycleOptions) {
      const resolveHoverOptions = () => ({
        ...typeof options === "function" ? options() : options,
        target
      });
      return this._setupDelayedHover(target, resolveHoverOptions, lifecycleOptions);
    }
    setupDelayedHoverAtMouse(target, options, lifecycleOptions) {
      const resolveHoverOptions = (e) => ({
        ...typeof options === "function" ? options() : options,
        target: {
          targetElements: [target],
          x: e !== void 0 ? e.x + 10 : void 0
        }
      });
      return this._setupDelayedHover(target, resolveHoverOptions, lifecycleOptions);
    }
    _setupDelayedHover(target, resolveHoverOptions, lifecycleOptions) {
      const store = new DisposableStore();
      store.add(addDisposableListener(target, EventType$1.MOUSE_OVER, (e) => {
        this.showDelayedHover(resolveHoverOptions(e), {
          groupId: lifecycleOptions?.groupId
        });
      }));
      if (lifecycleOptions?.setupKeyboardEvents) {
        store.add(addDisposableListener(target, EventType$1.KEY_DOWN, (e) => {
          const evt = new StandardKeyboardEvent(e);
          if (evt.equals(
            10
            /* KeyCode.Space */
          ) || evt.equals(
            3
            /* KeyCode.Enter */
          )) {
            this.showInstantHover(resolveHoverOptions(), true);
          }
        }));
      }
      this._delayedHovers.set(target, { show: (focus) => {
        this.showInstantHover(resolveHoverOptions(), focus);
      } });
      store.add(toDisposable(() => this._delayedHovers.delete(target)));
      return store;
    }
    _createHover(options, skipLastFocusedUpdate) {
      this._currentDelayedHover = void 0;
      if (options.content === "") {
        return void 0;
      }
      if (this._currentHover?.isLocked) {
        return void 0;
      }
      if (options.id === void 0) {
        options.id = getHoverIdFromContent(options.content);
      }
      if (getHoverOptionsIdentity(this._currentHoverOptions) === getHoverOptionsIdentity(options)) {
        return void 0;
      }
      this._currentHoverOptions = options;
      this._lastHoverOptions = options;
      const trapFocus = options.trapFocus || this._accessibilityService.isScreenReaderOptimized();
      const activeElement = getActiveElement();
      if (!skipLastFocusedUpdate) {
        if (trapFocus && activeElement) {
          if (!activeElement.classList.contains("monaco-hover")) {
            this._lastFocusedElementBeforeOpen = activeElement;
          }
        } else {
          this._lastFocusedElementBeforeOpen = void 0;
        }
      }
      const hoverDisposables = new DisposableStore();
      const hover = this._instantiationService.createInstance(HoverWidget, options);
      if (options.persistence?.sticky) {
        hover.isLocked = true;
      }
      if (options.position?.hoverPosition && !isNumber$1(options.position.hoverPosition)) {
        options.target = {
          targetElements: isHTMLElement(options.target) ? [options.target] : options.target.targetElements,
          x: options.position.hoverPosition.x + 10
        };
      }
      hover.onDispose(() => {
        const hoverWasFocused = this._currentHover?.domNode && isAncestorOfActiveElement(this._currentHover.domNode);
        if (hoverWasFocused) {
          this._lastFocusedElementBeforeOpen?.focus();
        }
        if (getHoverOptionsIdentity(this._currentHoverOptions) === getHoverOptionsIdentity(options)) {
          this.doHideHover();
        }
        hoverDisposables.dispose();
      }, void 0, hoverDisposables);
      if (!options.container) {
        const targetElement = isHTMLElement(options.target) ? options.target : options.target.targetElements[0];
        options.container = this._layoutService.getContainer(getWindow(targetElement));
      }
      hover.onRequestLayout(() => this._contextViewHandler.layout(), void 0, hoverDisposables);
      if (options.persistence?.sticky) {
        hoverDisposables.add(addDisposableListener(getWindow(options.container).document, EventType$1.MOUSE_DOWN, (e) => {
          if (!isAncestor$1(e.target, hover.domNode)) {
            this.doHideHover();
          }
        }));
      } else {
        if ("targetElements" in options.target) {
          for (const element of options.target.targetElements) {
            hoverDisposables.add(addDisposableListener(element, EventType$1.CLICK, () => this.hideHover()));
          }
        } else {
          hoverDisposables.add(addDisposableListener(options.target, EventType$1.CLICK, () => this.hideHover()));
        }
        const focusedElement = getActiveElement();
        if (focusedElement) {
          const focusedElementDocument = getWindow(focusedElement).document;
          hoverDisposables.add(addDisposableListener(focusedElement, EventType$1.KEY_DOWN, (e) => this._keyDown(e, hover, !!options.persistence?.hideOnKeyDown)));
          hoverDisposables.add(addDisposableListener(focusedElementDocument, EventType$1.KEY_DOWN, (e) => this._keyDown(e, hover, !!options.persistence?.hideOnKeyDown)));
          hoverDisposables.add(addDisposableListener(focusedElement, EventType$1.KEY_UP, (e) => this._keyUp(e, hover)));
          hoverDisposables.add(addDisposableListener(focusedElementDocument, EventType$1.KEY_UP, (e) => this._keyUp(e, hover)));
        }
      }
      if ("IntersectionObserver" in mainWindow) {
        const observer = new IntersectionObserver((e) => this._intersectionChange(e, hover), { threshold: 0 });
        const firstTargetElement = "targetElements" in options.target ? options.target.targetElements[0] : options.target;
        observer.observe(firstTargetElement);
        hoverDisposables.add(toDisposable(() => observer.disconnect()));
      }
      this._currentHover = hover;
      return hover;
    }
    _showHover(hover, options, focus) {
      this._contextViewHandler.showContextView(new HoverContextViewDelegate(hover, focus), options.container);
    }
    hideHover(force) {
      if (!force && this._currentHover?.isLocked || !this._currentHoverOptions) {
        return;
      }
      this.doHideHover();
    }
    doHideHover() {
      this._currentHover = void 0;
      this._currentHoverOptions = void 0;
      this._contextViewHandler.hideContextView();
    }
    _intersectionChange(entries2, hover) {
      const entry = entries2[entries2.length - 1];
      if (!entry.isIntersecting) {
        hover.dispose();
      }
    }
    showAndFocusLastHover() {
      if (!this._lastHoverOptions) {
        return;
      }
      this.showInstantHover(this._lastHoverOptions, true, true);
    }
    _showAndFocusHoverForActiveElement() {
      let activeElement = getActiveElement();
      while (activeElement) {
        const hover = this._delayedHovers.get(activeElement) ?? this._managedHovers.get(activeElement);
        if (hover) {
          hover.show(true);
          return;
        }
        activeElement = activeElement.parentElement;
      }
    }
    _keyDown(e, hover, hideOnKeyDown) {
      if (e.key === "Alt") {
        hover.isLocked = true;
        return;
      }
      const event = new StandardKeyboardEvent(e);
      const keybinding = this._keybindingService.resolveKeyboardEvent(event);
      if (keybinding.getSingleModifierDispatchChords().some((value) => !!value) || this._keybindingService.softDispatch(event, event.target).kind !== 0) {
        return;
      }
      if (hideOnKeyDown && (!this._currentHoverOptions?.trapFocus || e.key !== "Tab")) {
        this.hideHover();
        this._lastFocusedElementBeforeOpen?.focus();
      }
    }
    _keyUp(e, hover) {
      if (e.key === "Alt") {
        hover.isLocked = false;
        if (!hover.isMouseIn) {
          this.hideHover();
          this._lastFocusedElementBeforeOpen?.focus();
        }
      }
    }
    // TODO: Investigate performance of this function. There seems to be a lot of content created
    //       and thrown away on start up
    setupManagedHover(hoverDelegate, targetElement, content, options) {
      if (hoverDelegate.showNativeHover) {
        return setupNativeHover(targetElement, content);
      }
      targetElement.setAttribute("custom-hover", "true");
      if (targetElement.title !== "") {
        console.warn("HTML element already has a title attribute, which will conflict with the custom hover. Please remove the title attribute.");
        console.trace("Stack trace:", targetElement.title);
        targetElement.title = "";
      }
      let hoverPreparation;
      let hoverWidget;
      const hideHover = (disposeWidget, disposePreparation) => {
        const hadHover = hoverWidget !== void 0;
        if (disposeWidget) {
          hoverWidget?.dispose();
          hoverWidget = void 0;
        }
        if (disposePreparation) {
          hoverPreparation?.dispose();
          hoverPreparation = void 0;
        }
        if (hadHover) {
          hoverDelegate.onDidHideHover?.();
          hoverWidget = void 0;
        }
      };
      const triggerShowHover = (delay, focus, target, trapFocus) => {
        return new TimeoutTimer(async () => {
          if (!hoverWidget || hoverWidget.isDisposed) {
            hoverWidget = new ManagedHoverWidget(hoverDelegate, target || targetElement, delay > 0);
            await hoverWidget.update(typeof content === "function" ? content() : content, focus, { ...options, trapFocus });
          }
        }, delay);
      };
      const store = new DisposableStore();
      let isMouseDown = false;
      store.add(addDisposableListener(targetElement, EventType$1.MOUSE_DOWN, () => {
        isMouseDown = true;
        hideHover(true, true);
      }, true));
      store.add(addDisposableListener(targetElement, EventType$1.MOUSE_UP, () => {
        isMouseDown = false;
      }, true));
      store.add(addDisposableListener(targetElement, EventType$1.MOUSE_LEAVE, (e) => {
        isMouseDown = false;
        hideHover(false, e.fromElement === targetElement);
      }, true));
      store.add(addDisposableListener(targetElement, EventType$1.MOUSE_OVER, (e) => {
        if (hoverPreparation) {
          return;
        }
        const mouseOverStore = new DisposableStore();
        const target = {
          targetElements: [targetElement],
          dispose: () => {
          }
        };
        if (hoverDelegate.placement === void 0 || hoverDelegate.placement === "mouse") {
          const onMouseMove = (e2) => {
            target.x = e2.x + 10;
            if (!eventIsRelatedToTarget(e2, targetElement)) {
              hideHover(true, true);
            }
          };
          mouseOverStore.add(addDisposableListener(targetElement, EventType$1.MOUSE_MOVE, onMouseMove, true));
        }
        hoverPreparation = mouseOverStore;
        if (!eventIsRelatedToTarget(e, targetElement)) {
          return;
        }
        mouseOverStore.add(triggerShowHover(typeof hoverDelegate.delay === "function" ? hoverDelegate.delay(content) : hoverDelegate.delay, false, target));
      }, true));
      const onFocus = (e) => {
        if (isMouseDown || hoverPreparation) {
          return;
        }
        if (!eventIsRelatedToTarget(e, targetElement)) {
          return;
        }
        const target = {
          targetElements: [targetElement],
          dispose: () => {
          }
        };
        const toDispose = new DisposableStore();
        const onBlur = () => hideHover(true, true);
        toDispose.add(addDisposableListener(targetElement, EventType$1.BLUR, onBlur, true));
        toDispose.add(triggerShowHover(typeof hoverDelegate.delay === "function" ? hoverDelegate.delay(content) : hoverDelegate.delay, false, target));
        hoverPreparation = toDispose;
      };
      if (!isEditableElement(targetElement)) {
        store.add(addDisposableListener(targetElement, EventType$1.FOCUS, onFocus, true));
      }
      const hover = {
        show: (focus) => {
          hideHover(false, true);
          triggerShowHover(0, focus, void 0, focus);
        },
        hide: () => {
          hideHover(true, true);
        },
        update: async (newContent, hoverOptions) => {
          content = newContent;
          await hoverWidget?.update(content, void 0, hoverOptions);
        },
        dispose: () => {
          this._managedHovers.delete(targetElement);
          store.dispose();
          hideHover(true, true);
        }
      };
      this._managedHovers.set(targetElement, hover);
      return hover;
    }
    showManagedHover(target) {
      const hover = this._managedHovers.get(target);
      if (hover) {
        hover.show(true);
      }
    }
    dispose() {
      this._managedHovers.forEach((hover) => hover.dispose());
      super.dispose();
    }
  };
  HoverService = __decorate$m([
    __param$l(0, IInstantiationService),
    __param$l(1, IConfigurationService),
    __param$l(2, IContextMenuService),
    __param$l(3, IKeybindingService),
    __param$l(4, ILayoutService),
    __param$l(5, IAccessibilityService)
  ], HoverService);
  function getHoverOptionsIdentity(options) {
    if (options === void 0) {
      return void 0;
    }
    return options?.id ?? options;
  }
  function getHoverIdFromContent(content) {
    if (isHTMLElement(content)) {
      return void 0;
    }
    if (typeof content === "string") {
      return content.toString();
    }
    return content.value;
  }
  function getStringContent(contentOrFactory) {
    const content = typeof contentOrFactory === "function" ? contentOrFactory() : contentOrFactory;
    if (isString$1(content)) {
      return stripIcons(content);
    }
    if (isManagedHoverTooltipMarkdownString(content)) {
      return content.markdownNotSupportedFallback;
    }
    return void 0;
  }
  function setupNativeHover(targetElement, content) {
    function updateTitle(title) {
      if (title) {
        targetElement.setAttribute("title", title);
      } else {
        targetElement.removeAttribute("title");
      }
    }
    updateTitle(getStringContent(content));
    return {
      update: (content2) => updateTitle(getStringContent(content2)),
      show: () => {
      },
      hide: () => {
      },
      dispose: () => updateTitle(void 0)
    };
  }
  class HoverContextViewDelegate {
    get anchorPosition() {
      return this._hover.anchor;
    }
    constructor(_hover, _focus = false) {
      this._hover = _hover;
      this._focus = _focus;
      this.layer = 1;
    }
    render(container) {
      this._hover.render(container);
      if (this._focus) {
        this._hover.focus();
      }
      return this._hover;
    }
    getAnchor() {
      return {
        x: this._hover.x,
        y: this._hover.y
      };
    }
    layout() {
      this._hover.layout();
    }
  }
  function eventIsRelatedToTarget(event, target) {
    return isHTMLElement(event.target) && getHoverTargetElement(event.target, target) === target;
  }
  function getHoverTargetElement(element, stopElement) {
    stopElement = stopElement ?? getWindow(element).document.body;
    while (!element.hasAttribute("custom-hover") && element !== stopElement) {
      element = element.parentElement;
    }
    return element;
  }
  registerSingleton(
    IHoverService,
    HoverService,
    1
    /* InstantiationType.Delayed */
  );
  registerThemingParticipant((theme, collector) => {
    const hoverBorder = theme.getColor(editorHoverBorder);
    if (hoverBorder) {
      collector.addRule(`.monaco-hover.workbench-hover .hover-row:not(:first-child):not(:empty) { border-top: 1px solid ${hoverBorder.transparent(0.5)}; }`);
      collector.addRule(`.monaco-hover.workbench-hover hr { border-top: 1px solid ${hoverBorder.transparent(0.5)}; }`);
    }
  });
  function freeze(data) {
    return Object.isFrozen(data) ? data : deepFreeze(data);
  }
  class ConfigurationModel {
    static createEmptyModel(logService) {
      return new ConfigurationModel({}, [], [], void 0, logService);
    }
    constructor(_contents, _keys, _overrides, raw, logService) {
      this._contents = _contents;
      this._keys = _keys;
      this._overrides = _overrides;
      this.raw = raw;
      this.logService = logService;
      this.overrideConfigurations = /* @__PURE__ */ new Map();
    }
    get rawConfiguration() {
      if (!this._rawConfiguration) {
        if (this.raw) {
          const rawConfigurationModels = (Array.isArray(this.raw) ? this.raw : [this.raw]).map((raw) => {
            if (raw instanceof ConfigurationModel) {
              return raw;
            }
            const parser = new ConfigurationModelParser("", this.logService);
            parser.parseRaw(raw);
            return parser.configurationModel;
          });
          this._rawConfiguration = rawConfigurationModels.reduce((previous, current) => current === previous ? current : previous.merge(current), rawConfigurationModels[0]);
        } else {
          this._rawConfiguration = this;
        }
      }
      return this._rawConfiguration;
    }
    get contents() {
      return this._contents;
    }
    get overrides() {
      return this._overrides;
    }
    get keys() {
      return this._keys;
    }
    isEmpty() {
      return this._keys.length === 0 && Object.keys(this._contents).length === 0 && this._overrides.length === 0;
    }
    getValue(section) {
      return section ? getConfigurationValue(this.contents, section) : this.contents;
    }
    inspect(section, overrideIdentifier) {
      const that = this;
      return {
        get value() {
          return freeze(that.rawConfiguration.getValue(section));
        },
        get override() {
          return overrideIdentifier ? freeze(that.rawConfiguration.getOverrideValue(section, overrideIdentifier)) : void 0;
        },
        get merged() {
          return freeze(overrideIdentifier ? that.rawConfiguration.override(overrideIdentifier).getValue(section) : that.rawConfiguration.getValue(section));
        },
        get overrides() {
          const overrides = [];
          for (const { contents, identifiers, keys } of that.rawConfiguration.overrides) {
            const value = new ConfigurationModel(contents, keys, [], void 0, that.logService).getValue(section);
            if (value !== void 0) {
              overrides.push({ identifiers, value });
            }
          }
          return overrides.length ? freeze(overrides) : void 0;
        }
      };
    }
    getOverrideValue(section, overrideIdentifier) {
      const overrideContents = this.getContentsForOverrideIdentifer(overrideIdentifier);
      return overrideContents ? section ? getConfigurationValue(overrideContents, section) : overrideContents : void 0;
    }
    override(identifier) {
      let overrideConfigurationModel = this.overrideConfigurations.get(identifier);
      if (!overrideConfigurationModel) {
        overrideConfigurationModel = this.createOverrideConfigurationModel(identifier);
        this.overrideConfigurations.set(identifier, overrideConfigurationModel);
      }
      return overrideConfigurationModel;
    }
    merge(...others) {
      const contents = deepClone(this.contents);
      const overrides = deepClone(this.overrides);
      const keys = [...this.keys];
      const raws = this.raw ? Array.isArray(this.raw) ? [...this.raw] : [this.raw] : [this];
      for (const other of others) {
        raws.push(...other.raw ? Array.isArray(other.raw) ? other.raw : [other.raw] : [other]);
        if (other.isEmpty()) {
          continue;
        }
        this.mergeContents(contents, other.contents);
        for (const otherOverride of other.overrides) {
          const [override] = overrides.filter((o) => equals$1(o.identifiers, otherOverride.identifiers));
          if (override) {
            this.mergeContents(override.contents, otherOverride.contents);
            override.keys.push(...otherOverride.keys);
            override.keys = distinct(override.keys);
          } else {
            overrides.push(deepClone(otherOverride));
          }
        }
        for (const key of other.keys) {
          if (keys.indexOf(key) === -1) {
            keys.push(key);
          }
        }
      }
      return new ConfigurationModel(contents, keys, overrides, !raws.length || raws.every((raw) => raw instanceof ConfigurationModel) ? void 0 : raws, this.logService);
    }
    createOverrideConfigurationModel(identifier) {
      const overrideContents = this.getContentsForOverrideIdentifer(identifier);
      if (!overrideContents || typeof overrideContents !== "object" || !Object.keys(overrideContents).length) {
        return this;
      }
      const contents = {};
      for (const key of distinct([...Object.keys(this.contents), ...Object.keys(overrideContents)])) {
        let contentsForKey = this.contents[key];
        const overrideContentsForKey = overrideContents[key];
        if (overrideContentsForKey) {
          if (typeof contentsForKey === "object" && typeof overrideContentsForKey === "object") {
            contentsForKey = deepClone(contentsForKey);
            this.mergeContents(contentsForKey, overrideContentsForKey);
          } else {
            contentsForKey = overrideContentsForKey;
          }
        }
        contents[key] = contentsForKey;
      }
      return new ConfigurationModel(contents, this.keys, this.overrides, void 0, this.logService);
    }
    mergeContents(source, target) {
      for (const key of Object.keys(target)) {
        if (key in source) {
          if (isObject(source[key]) && isObject(target[key])) {
            this.mergeContents(source[key], target[key]);
            continue;
          }
        }
        source[key] = deepClone(target[key]);
      }
    }
    getContentsForOverrideIdentifer(identifier) {
      let contentsForIdentifierOnly = null;
      let contents = null;
      const mergeContents = (contentsToMerge) => {
        if (contentsToMerge) {
          if (contents) {
            this.mergeContents(contents, contentsToMerge);
          } else {
            contents = deepClone(contentsToMerge);
          }
        }
      };
      for (const override of this.overrides) {
        if (override.identifiers.length === 1 && override.identifiers[0] === identifier) {
          contentsForIdentifierOnly = override.contents;
        } else if (override.identifiers.includes(identifier)) {
          mergeContents(override.contents);
        }
      }
      mergeContents(contentsForIdentifierOnly);
      return contents;
    }
    toJSON() {
      return {
        contents: this.contents,
        overrides: this.overrides,
        keys: this.keys
      };
    }
    setValue(key, value) {
      this.updateValue(key, value, false);
    }
    removeValue(key) {
      const index = this.keys.indexOf(key);
      if (index === -1) {
        return;
      }
      this.keys.splice(index, 1);
      removeFromValueTree(this.contents, key);
      if (OVERRIDE_PROPERTY_REGEX.test(key)) {
        this.overrides.splice(this.overrides.findIndex((o) => equals$1(o.identifiers, overrideIdentifiersFromKey(key))), 1);
      }
    }
    updateValue(key, value, add) {
      addToValueTree(this.contents, key, value, (e) => this.logService.error(e));
      add = add || this.keys.indexOf(key) === -1;
      if (add) {
        this.keys.push(key);
      }
      if (OVERRIDE_PROPERTY_REGEX.test(key)) {
        const identifiers = overrideIdentifiersFromKey(key);
        const override = {
          identifiers,
          keys: Object.keys(this.contents[key]),
          contents: toValuesTree(this.contents[key], (message) => this.logService.error(message))
        };
        const index = this.overrides.findIndex((o) => equals$1(o.identifiers, identifiers));
        if (index !== -1) {
          this.overrides[index] = override;
        } else {
          this.overrides.push(override);
        }
      }
    }
  }
  class ConfigurationModelParser {
    constructor(_name, logService) {
      this._name = _name;
      this.logService = logService;
      this._raw = null;
      this._configurationModel = null;
      this._restrictedConfigurations = [];
    }
    get configurationModel() {
      return this._configurationModel || ConfigurationModel.createEmptyModel(this.logService);
    }
    parseRaw(raw, options) {
      this._raw = raw;
      const { contents, keys, overrides, restricted, hasExcludedProperties } = this.doParseRaw(raw, options);
      this._configurationModel = new ConfigurationModel(contents, keys, overrides, hasExcludedProperties ? [raw] : void 0, this.logService);
      this._restrictedConfigurations = restricted || [];
    }
    doParseRaw(raw, options) {
      const registry = Registry.as(Extensions$6.Configuration);
      const configurationProperties = registry.getConfigurationProperties();
      const excludedConfigurationProperties = registry.getExcludedConfigurationProperties();
      const filtered = this.filter(raw, configurationProperties, excludedConfigurationProperties, true, options);
      raw = filtered.raw;
      const contents = toValuesTree(raw, (message) => this.logService.error(`Conflict in settings file ${this._name}: ${message}`));
      const keys = Object.keys(raw);
      const overrides = this.toOverrides(raw, (message) => this.logService.error(`Conflict in settings file ${this._name}: ${message}`));
      return { contents, keys, overrides, restricted: filtered.restricted, hasExcludedProperties: filtered.hasExcludedProperties };
    }
    filter(properties, configurationProperties, excludedConfigurationProperties, filterOverriddenProperties, options) {
      let hasExcludedProperties = false;
      if (!options?.scopes && !options?.skipRestricted && !options?.skipUnregistered && !options?.exclude?.length) {
        return { raw: properties, restricted: [], hasExcludedProperties };
      }
      const raw = {};
      const restricted = [];
      for (const key in properties) {
        if (OVERRIDE_PROPERTY_REGEX.test(key) && filterOverriddenProperties) {
          const result = this.filter(properties[key], configurationProperties, excludedConfigurationProperties, false, options);
          raw[key] = result.raw;
          hasExcludedProperties = hasExcludedProperties || result.hasExcludedProperties;
          restricted.push(...result.restricted);
        } else {
          const propertySchema = configurationProperties[key];
          if (propertySchema?.restricted) {
            restricted.push(key);
          }
          if (this.shouldInclude(key, propertySchema, excludedConfigurationProperties, options)) {
            raw[key] = properties[key];
          } else {
            hasExcludedProperties = true;
          }
        }
      }
      return { raw, restricted, hasExcludedProperties };
    }
    shouldInclude(key, propertySchema, excludedConfigurationProperties, options) {
      if (options.exclude?.includes(key)) {
        return false;
      }
      if (options.include?.includes(key)) {
        return true;
      }
      if (options.skipRestricted && propertySchema?.restricted) {
        return false;
      }
      if (options.skipUnregistered && !propertySchema) {
        return false;
      }
      const schema = propertySchema ?? excludedConfigurationProperties[key];
      const scope = schema ? typeof schema.scope !== "undefined" ? schema.scope : 4 : void 0;
      if (scope === void 0 || options.scopes === void 0) {
        return true;
      }
      return options.scopes.includes(scope);
    }
    toOverrides(raw, conflictReporter) {
      const overrides = [];
      for (const key of Object.keys(raw)) {
        if (OVERRIDE_PROPERTY_REGEX.test(key)) {
          const overrideRaw = {};
          for (const keyInOverrideRaw in raw[key]) {
            overrideRaw[keyInOverrideRaw] = raw[key][keyInOverrideRaw];
          }
          overrides.push({
            identifiers: overrideIdentifiersFromKey(key),
            keys: Object.keys(overrideRaw),
            contents: toValuesTree(overrideRaw, conflictReporter)
          });
        }
      }
      return overrides;
    }
  }
  class ConfigurationInspectValue {
    constructor(key, overrides, _value, overrideIdentifiers, defaultConfiguration, policyConfiguration, applicationConfiguration, userConfiguration, localUserConfiguration, remoteUserConfiguration, workspaceConfiguration, folderConfigurationModel, memoryConfigurationModel) {
      this.key = key;
      this.overrides = overrides;
      this._value = _value;
      this.overrideIdentifiers = overrideIdentifiers;
      this.defaultConfiguration = defaultConfiguration;
      this.policyConfiguration = policyConfiguration;
      this.applicationConfiguration = applicationConfiguration;
      this.userConfiguration = userConfiguration;
      this.localUserConfiguration = localUserConfiguration;
      this.remoteUserConfiguration = remoteUserConfiguration;
      this.workspaceConfiguration = workspaceConfiguration;
      this.folderConfigurationModel = folderConfigurationModel;
      this.memoryConfigurationModel = memoryConfigurationModel;
    }
    toInspectValue(inspectValue) {
      return inspectValue?.value !== void 0 || inspectValue?.override !== void 0 || inspectValue?.overrides !== void 0 ? inspectValue : void 0;
    }
    get userInspectValue() {
      if (!this._userInspectValue) {
        this._userInspectValue = this.userConfiguration.inspect(this.key, this.overrides.overrideIdentifier);
      }
      return this._userInspectValue;
    }
    get user() {
      return this.toInspectValue(this.userInspectValue);
    }
  }
  class Configuration {
    constructor(_defaultConfiguration, _policyConfiguration, _applicationConfiguration, _localUserConfiguration, _remoteUserConfiguration, _workspaceConfiguration, _folderConfigurations, _memoryConfiguration, _memoryConfigurationByResource, logService) {
      this._defaultConfiguration = _defaultConfiguration;
      this._policyConfiguration = _policyConfiguration;
      this._applicationConfiguration = _applicationConfiguration;
      this._localUserConfiguration = _localUserConfiguration;
      this._remoteUserConfiguration = _remoteUserConfiguration;
      this._workspaceConfiguration = _workspaceConfiguration;
      this._folderConfigurations = _folderConfigurations;
      this._memoryConfiguration = _memoryConfiguration;
      this._memoryConfigurationByResource = _memoryConfigurationByResource;
      this.logService = logService;
      this._workspaceConsolidatedConfiguration = null;
      this._foldersConsolidatedConfigurations = new ResourceMap();
      this._userConfiguration = null;
    }
    getValue(section, overrides, workspace) {
      const consolidateConfigurationModel = this.getConsolidatedConfigurationModel(section, overrides, workspace);
      return consolidateConfigurationModel.getValue(section);
    }
    updateValue(key, value, overrides = {}) {
      let memoryConfiguration;
      if (overrides.resource) {
        memoryConfiguration = this._memoryConfigurationByResource.get(overrides.resource);
        if (!memoryConfiguration) {
          memoryConfiguration = ConfigurationModel.createEmptyModel(this.logService);
          this._memoryConfigurationByResource.set(overrides.resource, memoryConfiguration);
        }
      } else {
        memoryConfiguration = this._memoryConfiguration;
      }
      if (value === void 0) {
        memoryConfiguration.removeValue(key);
      } else {
        memoryConfiguration.setValue(key, value);
      }
      if (!overrides.resource) {
        this._workspaceConsolidatedConfiguration = null;
      }
    }
    inspect(key, overrides, workspace) {
      const consolidateConfigurationModel = this.getConsolidatedConfigurationModel(key, overrides, workspace);
      const folderConfigurationModel = this.getFolderConfigurationModelForResource(overrides.resource, workspace);
      const memoryConfigurationModel = overrides.resource ? this._memoryConfigurationByResource.get(overrides.resource) || this._memoryConfiguration : this._memoryConfiguration;
      const overrideIdentifiers = /* @__PURE__ */ new Set();
      for (const override of consolidateConfigurationModel.overrides) {
        for (const overrideIdentifier of override.identifiers) {
          if (consolidateConfigurationModel.getOverrideValue(key, overrideIdentifier) !== void 0) {
            overrideIdentifiers.add(overrideIdentifier);
          }
        }
      }
      return new ConfigurationInspectValue(key, overrides, consolidateConfigurationModel.getValue(key), overrideIdentifiers.size ? [...overrideIdentifiers] : void 0, this._defaultConfiguration, this._policyConfiguration.isEmpty() ? void 0 : this._policyConfiguration, this.applicationConfiguration.isEmpty() ? void 0 : this.applicationConfiguration, this.userConfiguration, this.localUserConfiguration, this.remoteUserConfiguration, workspace ? this._workspaceConfiguration : void 0, folderConfigurationModel ? folderConfigurationModel : void 0, memoryConfigurationModel);
    }
    get applicationConfiguration() {
      return this._applicationConfiguration;
    }
    get userConfiguration() {
      if (!this._userConfiguration) {
        if (this._remoteUserConfiguration.isEmpty()) {
          this._userConfiguration = this._localUserConfiguration;
        } else {
          const merged = this._localUserConfiguration.merge(this._remoteUserConfiguration);
          this._userConfiguration = new ConfigurationModel(merged.contents, merged.keys, merged.overrides, void 0, this.logService);
        }
      }
      return this._userConfiguration;
    }
    get localUserConfiguration() {
      return this._localUserConfiguration;
    }
    get remoteUserConfiguration() {
      return this._remoteUserConfiguration;
    }
    getConsolidatedConfigurationModel(section, overrides, workspace) {
      let configurationModel = this.getConsolidatedConfigurationModelForResource(overrides, workspace);
      if (overrides.overrideIdentifier) {
        configurationModel = configurationModel.override(overrides.overrideIdentifier);
      }
      if (!this._policyConfiguration.isEmpty() && this._policyConfiguration.getValue(section) !== void 0) {
        configurationModel = configurationModel.merge();
        for (const key of this._policyConfiguration.keys) {
          configurationModel.setValue(key, this._policyConfiguration.getValue(key));
        }
      }
      return configurationModel;
    }
    getConsolidatedConfigurationModelForResource({ resource }, workspace) {
      let consolidateConfiguration = this.getWorkspaceConsolidatedConfiguration();
      if (workspace && resource) {
        const root = workspace.getFolder(resource);
        if (root) {
          consolidateConfiguration = this.getFolderConsolidatedConfiguration(root.uri) || consolidateConfiguration;
        }
        const memoryConfigurationForResource = this._memoryConfigurationByResource.get(resource);
        if (memoryConfigurationForResource) {
          consolidateConfiguration = consolidateConfiguration.merge(memoryConfigurationForResource);
        }
      }
      return consolidateConfiguration;
    }
    getWorkspaceConsolidatedConfiguration() {
      if (!this._workspaceConsolidatedConfiguration) {
        this._workspaceConsolidatedConfiguration = this._defaultConfiguration.merge(this.applicationConfiguration, this.userConfiguration, this._workspaceConfiguration, this._memoryConfiguration);
      }
      return this._workspaceConsolidatedConfiguration;
    }
    getFolderConsolidatedConfiguration(folder) {
      let folderConsolidatedConfiguration = this._foldersConsolidatedConfigurations.get(folder);
      if (!folderConsolidatedConfiguration) {
        const workspaceConsolidateConfiguration = this.getWorkspaceConsolidatedConfiguration();
        const folderConfiguration = this._folderConfigurations.get(folder);
        if (folderConfiguration) {
          folderConsolidatedConfiguration = workspaceConsolidateConfiguration.merge(folderConfiguration);
          this._foldersConsolidatedConfigurations.set(folder, folderConsolidatedConfiguration);
        } else {
          folderConsolidatedConfiguration = workspaceConsolidateConfiguration;
        }
      }
      return folderConsolidatedConfiguration;
    }
    getFolderConfigurationModelForResource(resource, workspace) {
      if (workspace && resource) {
        const root = workspace.getFolder(resource);
        if (root) {
          return this._folderConfigurations.get(root.uri);
        }
      }
      return void 0;
    }
    toData() {
      return {
        defaults: {
          contents: this._defaultConfiguration.contents,
          overrides: this._defaultConfiguration.overrides,
          keys: this._defaultConfiguration.keys
        },
        policy: {
          contents: this._policyConfiguration.contents,
          overrides: this._policyConfiguration.overrides,
          keys: this._policyConfiguration.keys
        },
        application: {
          contents: this.applicationConfiguration.contents,
          overrides: this.applicationConfiguration.overrides,
          keys: this.applicationConfiguration.keys,
          raw: Array.isArray(this.applicationConfiguration.raw) ? void 0 : this.applicationConfiguration.raw
        },
        userLocal: {
          contents: this.localUserConfiguration.contents,
          overrides: this.localUserConfiguration.overrides,
          keys: this.localUserConfiguration.keys,
          raw: Array.isArray(this.localUserConfiguration.raw) ? void 0 : this.localUserConfiguration.raw
        },
        userRemote: {
          contents: this.remoteUserConfiguration.contents,
          overrides: this.remoteUserConfiguration.overrides,
          keys: this.remoteUserConfiguration.keys,
          raw: Array.isArray(this.remoteUserConfiguration.raw) ? void 0 : this.remoteUserConfiguration.raw
        },
        workspace: {
          contents: this._workspaceConfiguration.contents,
          overrides: this._workspaceConfiguration.overrides,
          keys: this._workspaceConfiguration.keys
        },
        folders: [...this._folderConfigurations.keys()].reduce((result, folder) => {
          const { contents, overrides, keys } = this._folderConfigurations.get(folder);
          result.push([folder, { contents, overrides, keys }]);
          return result;
        }, [])
      };
    }
    static parse(data, logService) {
      const defaultConfiguration = this.parseConfigurationModel(data.defaults, logService);
      const policyConfiguration = this.parseConfigurationModel(data.policy, logService);
      const applicationConfiguration = this.parseConfigurationModel(data.application, logService);
      const userLocalConfiguration = this.parseConfigurationModel(data.userLocal, logService);
      const userRemoteConfiguration = this.parseConfigurationModel(data.userRemote, logService);
      const workspaceConfiguration = this.parseConfigurationModel(data.workspace, logService);
      const folders = data.folders.reduce((result, value) => {
        result.set(URI.revive(value[0]), this.parseConfigurationModel(value[1], logService));
        return result;
      }, new ResourceMap());
      return new Configuration(defaultConfiguration, policyConfiguration, applicationConfiguration, userLocalConfiguration, userRemoteConfiguration, workspaceConfiguration, folders, ConfigurationModel.createEmptyModel(logService), new ResourceMap(), logService);
    }
    static parseConfigurationModel(model, logService) {
      return new ConfigurationModel(model.contents, model.keys, model.overrides, model.raw, logService);
    }
  }
  class ConfigurationChangeEvent {
    constructor(change, previous, currentConfiguraiton, currentWorkspace, logService) {
      this.change = change;
      this.previous = previous;
      this.currentConfiguraiton = currentConfiguraiton;
      this.currentWorkspace = currentWorkspace;
      this.logService = logService;
      this._marker = "\n";
      this._markerCode1 = this._marker.charCodeAt(0);
      this._markerCode2 = ".".charCodeAt(0);
      this.affectedKeys = /* @__PURE__ */ new Set();
      this._previousConfiguration = void 0;
      for (const key of change.keys) {
        this.affectedKeys.add(key);
      }
      for (const [, keys] of change.overrides) {
        for (const key of keys) {
          this.affectedKeys.add(key);
        }
      }
      this._affectsConfigStr = this._marker;
      for (const key of this.affectedKeys) {
        this._affectsConfigStr += key + this._marker;
      }
    }
    get previousConfiguration() {
      if (!this._previousConfiguration && this.previous) {
        this._previousConfiguration = Configuration.parse(this.previous.data, this.logService);
      }
      return this._previousConfiguration;
    }
    affectsConfiguration(section, overrides) {
      const needle = this._marker + section;
      const idx = this._affectsConfigStr.indexOf(needle);
      if (idx < 0) {
        return false;
      }
      const pos = idx + needle.length;
      if (pos >= this._affectsConfigStr.length) {
        return false;
      }
      const code = this._affectsConfigStr.charCodeAt(pos);
      if (code !== this._markerCode1 && code !== this._markerCode2) {
        return false;
      }
      if (overrides) {
        const value1 = this.previousConfiguration ? this.previousConfiguration.getValue(section, overrides, this.previous?.workspace) : void 0;
        const value2 = this.currentConfiguraiton.getValue(section, overrides, this.currentWorkspace);
        return !equals(value1, value2);
      }
      return true;
    }
  }
  const NoMatchingKb = {
    kind: 0
    /* ResultKind.NoMatchingKb */
  };
  const MoreChordsNeeded = {
    kind: 1
    /* ResultKind.MoreChordsNeeded */
  };
  function KbFound(commandId, commandArgs, isBubble) {
    return { kind: 2, commandId, commandArgs, isBubble };
  }
  class KeybindingResolver {
    constructor(defaultKeybindings, overrides, log2) {
      this._log = log2;
      this._defaultKeybindings = defaultKeybindings;
      this._defaultBoundCommands = /* @__PURE__ */ new Map();
      for (const defaultKeybinding of defaultKeybindings) {
        const command = defaultKeybinding.command;
        if (command && command.charAt(0) !== "-") {
          this._defaultBoundCommands.set(command, true);
        }
      }
      this._map = /* @__PURE__ */ new Map();
      this._lookupMap = /* @__PURE__ */ new Map();
      this._keybindings = KeybindingResolver.handleRemovals([].concat(defaultKeybindings).concat(overrides));
      for (let i2 = 0, len = this._keybindings.length; i2 < len; i2++) {
        const k = this._keybindings[i2];
        if (k.chords.length === 0) {
          continue;
        }
        const when = k.when?.substituteConstants();
        if (when && when.type === 0) {
          continue;
        }
        this._addKeyPress(k.chords[0], k);
      }
    }
    static _isTargetedForRemoval(defaultKb, keypress, when) {
      if (keypress) {
        for (let i2 = 0; i2 < keypress.length; i2++) {
          if (keypress[i2] !== defaultKb.chords[i2]) {
            return false;
          }
        }
      }
      if (when && when.type !== 1) {
        if (!defaultKb.when) {
          return false;
        }
        if (!expressionsAreEqualWithConstantSubstitution(when, defaultKb.when)) {
          return false;
        }
      }
      return true;
    }
    /**
     * Looks for rules containing "-commandId" and removes them.
     */
    static handleRemovals(rules) {
      const removals = /* @__PURE__ */ new Map();
      for (let i2 = 0, len = rules.length; i2 < len; i2++) {
        const rule = rules[i2];
        if (rule.command && rule.command.charAt(0) === "-") {
          const command = rule.command.substring(1);
          if (!removals.has(command)) {
            removals.set(command, [rule]);
          } else {
            removals.get(command).push(rule);
          }
        }
      }
      if (removals.size === 0) {
        return rules;
      }
      const result = [];
      for (let i2 = 0, len = rules.length; i2 < len; i2++) {
        const rule = rules[i2];
        if (!rule.command || rule.command.length === 0) {
          result.push(rule);
          continue;
        }
        if (rule.command.charAt(0) === "-") {
          continue;
        }
        const commandRemovals = removals.get(rule.command);
        if (!commandRemovals || !rule.isDefault) {
          result.push(rule);
          continue;
        }
        let isRemoved = false;
        for (const commandRemoval of commandRemovals) {
          const when = commandRemoval.when;
          if (this._isTargetedForRemoval(rule, commandRemoval.chords, when)) {
            isRemoved = true;
            break;
          }
        }
        if (!isRemoved) {
          result.push(rule);
          continue;
        }
      }
      return result;
    }
    _addKeyPress(keypress, item) {
      const conflicts = this._map.get(keypress);
      if (typeof conflicts === "undefined") {
        this._map.set(keypress, [item]);
        this._addToLookupMap(item);
        return;
      }
      for (let i2 = conflicts.length - 1; i2 >= 0; i2--) {
        const conflict = conflicts[i2];
        if (conflict.command === item.command) {
          continue;
        }
        let isShorterKbPrefix = true;
        for (let i3 = 1; i3 < conflict.chords.length && i3 < item.chords.length; i3++) {
          if (conflict.chords[i3] !== item.chords[i3]) {
            isShorterKbPrefix = false;
            break;
          }
        }
        if (!isShorterKbPrefix) {
          continue;
        }
        if (KeybindingResolver.whenIsEntirelyIncluded(conflict.when, item.when)) {
          this._removeFromLookupMap(conflict);
        }
      }
      conflicts.push(item);
      this._addToLookupMap(item);
    }
    _addToLookupMap(item) {
      if (!item.command) {
        return;
      }
      let arr = this._lookupMap.get(item.command);
      if (typeof arr === "undefined") {
        arr = [item];
        this._lookupMap.set(item.command, arr);
      } else {
        arr.push(item);
      }
    }
    _removeFromLookupMap(item) {
      if (!item.command) {
        return;
      }
      const arr = this._lookupMap.get(item.command);
      if (typeof arr === "undefined") {
        return;
      }
      for (let i2 = 0, len = arr.length; i2 < len; i2++) {
        if (arr[i2] === item) {
          arr.splice(i2, 1);
          return;
        }
      }
    }
    /**
     * Returns true if it is provable `a` implies `b`.
     */
    static whenIsEntirelyIncluded(a, b) {
      if (!b || b.type === 1) {
        return true;
      }
      if (!a || a.type === 1) {
        return false;
      }
      return implies(a, b);
    }
    getKeybindings() {
      return this._keybindings;
    }
    lookupPrimaryKeybinding(commandId, context, enforceContextCheck = false) {
      const items = this._lookupMap.get(commandId);
      if (typeof items === "undefined" || items.length === 0) {
        return null;
      }
      if (items.length === 1 && !enforceContextCheck) {
        return items[0];
      }
      for (let i2 = items.length - 1; i2 >= 0; i2--) {
        const item = items[i2];
        if (context.contextMatchesRules(item.when)) {
          return item;
        }
      }
      if (enforceContextCheck) {
        return null;
      }
      return items[items.length - 1];
    }
    /**
     * Looks up a keybinding trigged as a result of pressing a sequence of chords - `[...currentChords, keypress]`
     *
     * Example: resolving 3 chords pressed sequentially - `cmd+k cmd+p cmd+i`:
     * 	`currentChords = [ 'cmd+k' , 'cmd+p' ]` and `keypress = `cmd+i` - last pressed chord
     */
    resolve(context, currentChords, keypress) {
      const pressedChords = [...currentChords, keypress];
      this._log(`| Resolving ${pressedChords}`);
      const kbCandidates = this._map.get(pressedChords[0]);
      if (kbCandidates === void 0) {
        this._log(`\\ No keybinding entries.`);
        return NoMatchingKb;
      }
      let lookupMap = null;
      if (pressedChords.length < 2) {
        lookupMap = kbCandidates;
      } else {
        lookupMap = [];
        for (let i2 = 0, len = kbCandidates.length; i2 < len; i2++) {
          const candidate = kbCandidates[i2];
          if (pressedChords.length > candidate.chords.length) {
            continue;
          }
          let prefixMatches = true;
          for (let i3 = 1; i3 < pressedChords.length; i3++) {
            if (candidate.chords[i3] !== pressedChords[i3]) {
              prefixMatches = false;
              break;
            }
          }
          if (prefixMatches) {
            lookupMap.push(candidate);
          }
        }
      }
      const result = this._findCommand(context, lookupMap);
      if (!result) {
        this._log(`\\ From ${lookupMap.length} keybinding entries, no when clauses matched the context.`);
        return NoMatchingKb;
      }
      if (pressedChords.length < result.chords.length) {
        this._log(`\\ From ${lookupMap.length} keybinding entries, awaiting ${result.chords.length - pressedChords.length} more chord(s), when: ${printWhenExplanation(result.when)}, source: ${printSourceExplanation(result)}.`);
        return MoreChordsNeeded;
      }
      this._log(`\\ From ${lookupMap.length} keybinding entries, matched ${result.command}, when: ${printWhenExplanation(result.when)}, source: ${printSourceExplanation(result)}.`);
      return KbFound(result.command, result.commandArgs, result.bubble);
    }
    _findCommand(context, matches) {
      for (let i2 = matches.length - 1; i2 >= 0; i2--) {
        const k = matches[i2];
        if (!KeybindingResolver._contextMatchesRules(context, k.when)) {
          continue;
        }
        return k;
      }
      return null;
    }
    static _contextMatchesRules(context, rules) {
      if (!rules) {
        return true;
      }
      return rules.evaluate(context);
    }
  }
  function printWhenExplanation(when) {
    if (!when) {
      return `no when condition`;
    }
    return `${when.serialize()}`;
  }
  function printSourceExplanation(kb) {
    return kb.extensionId ? kb.isBuiltinExtension ? `built-in extension ${kb.extensionId}` : `user extension ${kb.extensionId}` : kb.isDefault ? `built-in` : `user`;
  }
  const HIGH_FREQ_COMMANDS = /^(cursor|delete|undo|redo|tab|editor\.action\.clipboard)/;
  class AbstractKeybindingService extends Disposable {
    get onDidUpdateKeybindings() {
      return this._onDidUpdateKeybindings ? this._onDidUpdateKeybindings.event : Event.None;
    }
    get inChordMode() {
      return this._currentChords.length > 0;
    }
    constructor(_contextKeyService, _commandService, _telemetryService, _notificationService, _logService) {
      super();
      this._contextKeyService = _contextKeyService;
      this._commandService = _commandService;
      this._telemetryService = _telemetryService;
      this._notificationService = _notificationService;
      this._logService = _logService;
      this._onDidUpdateKeybindings = this._register(new Emitter$1());
      this._currentChords = [];
      this._currentChordChecker = new IntervalTimer();
      this._currentChordStatusMessage = null;
      this._ignoreSingleModifiers = KeybindingModifierSet.EMPTY;
      this._currentSingleModifier = null;
      this._currentSingleModifierClearTimeout = new TimeoutTimer();
      this._currentlyDispatchingCommandId = null;
      this._logging = false;
    }
    dispose() {
      super.dispose();
    }
    _log(str) {
      if (this._logging) {
        this._logService.info(`[KeybindingService]: ${str}`);
      }
    }
    getKeybindings() {
      return this._getResolver().getKeybindings();
    }
    lookupKeybinding(commandId, context, enforceContextCheck = false) {
      const result = this._getResolver().lookupPrimaryKeybinding(commandId, context || this._contextKeyService, enforceContextCheck);
      if (!result) {
        return void 0;
      }
      return result.resolvedKeybinding;
    }
    dispatchEvent(e, target) {
      return this._dispatch(e, target);
    }
    // TODO@ulugbekna: update namings to align with `_doDispatch`
    // TODO@ulugbekna: this fn doesn't seem to take into account single-modifier keybindings, eg `shift shift`
    softDispatch(e, target) {
      this._log(`/ Soft dispatching keyboard event`);
      const keybinding = this.resolveKeyboardEvent(e);
      if (keybinding.hasMultipleChords()) {
        console.warn("keyboard event should not be mapped to multiple chords");
        return NoMatchingKb;
      }
      const [firstChord] = keybinding.getDispatchChords();
      if (firstChord === null) {
        this._log(`\\ Keyboard event cannot be dispatched`);
        return NoMatchingKb;
      }
      const contextValue = this._contextKeyService.getContext(target);
      const currentChords = this._currentChords.map((({ keypress }) => keypress));
      return this._getResolver().resolve(contextValue, currentChords, firstChord);
    }
    _scheduleLeaveChordMode() {
      const chordLastInteractedTime = Date.now();
      this._currentChordChecker.cancelAndSet(() => {
        if (!this._documentHasFocus()) {
          this._leaveChordMode();
          return;
        }
        if (Date.now() - chordLastInteractedTime > 5e3) {
          this._leaveChordMode();
        }
      }, 500);
    }
    _expectAnotherChord(firstChord, keypressLabel) {
      this._currentChords.push({ keypress: firstChord, label: keypressLabel });
      switch (this._currentChords.length) {
        case 0:
          throw illegalState("impossible");
        case 1:
          this._currentChordStatusMessage = this._notificationService.status(localize(1701, "({0}) was pressed. Waiting for second key of chord...", keypressLabel));
          break;
        default: {
          const fullKeypressLabel = this._currentChords.map(({ label }) => label).join(", ");
          this._currentChordStatusMessage = this._notificationService.status(localize(1702, "({0}) was pressed. Waiting for next key of chord...", fullKeypressLabel));
        }
      }
      this._scheduleLeaveChordMode();
      if (IME.enabled) {
        IME.disable();
      }
    }
    _leaveChordMode() {
      if (this._currentChordStatusMessage) {
        this._currentChordStatusMessage.close();
        this._currentChordStatusMessage = null;
      }
      this._currentChordChecker.cancel();
      this._currentChords = [];
      IME.enable();
    }
    _dispatch(e, target) {
      return this._doDispatch(
        this.resolveKeyboardEvent(e),
        target,
        /*isSingleModiferChord*/
        false
      );
    }
    _singleModifierDispatch(e, target) {
      const keybinding = this.resolveKeyboardEvent(e);
      const [singleModifier] = keybinding.getSingleModifierDispatchChords();
      if (singleModifier) {
        if (this._ignoreSingleModifiers.has(singleModifier)) {
          this._log(`+ Ignoring single modifier ${singleModifier} due to it being pressed together with other keys.`);
          this._ignoreSingleModifiers = KeybindingModifierSet.EMPTY;
          this._currentSingleModifierClearTimeout.cancel();
          this._currentSingleModifier = null;
          return false;
        }
        this._ignoreSingleModifiers = KeybindingModifierSet.EMPTY;
        if (this._currentSingleModifier === null) {
          this._log(`+ Storing single modifier for possible chord ${singleModifier}.`);
          this._currentSingleModifier = singleModifier;
          this._currentSingleModifierClearTimeout.cancelAndSet(() => {
            this._log(`+ Clearing single modifier due to 300ms elapsed.`);
            this._currentSingleModifier = null;
          }, 300);
          return false;
        }
        if (singleModifier === this._currentSingleModifier) {
          this._log(`/ Dispatching single modifier chord ${singleModifier} ${singleModifier}`);
          this._currentSingleModifierClearTimeout.cancel();
          this._currentSingleModifier = null;
          return this._doDispatch(
            keybinding,
            target,
            /*isSingleModiferChord*/
            true
          );
        }
        this._log(`+ Clearing single modifier due to modifier mismatch: ${this._currentSingleModifier} ${singleModifier}`);
        this._currentSingleModifierClearTimeout.cancel();
        this._currentSingleModifier = null;
        return false;
      }
      const [firstChord] = keybinding.getChords();
      this._ignoreSingleModifiers = new KeybindingModifierSet(firstChord);
      if (this._currentSingleModifier !== null) {
        this._log(`+ Clearing single modifier due to other key up.`);
      }
      this._currentSingleModifierClearTimeout.cancel();
      this._currentSingleModifier = null;
      return false;
    }
    _doDispatch(userKeypress, target, isSingleModiferChord = false) {
      let shouldPreventDefault = false;
      if (userKeypress.hasMultipleChords()) {
        console.warn("Unexpected keyboard event mapped to multiple chords");
        return false;
      }
      let userPressedChord = null;
      let currentChords = null;
      if (isSingleModiferChord) {
        const [dispatchKeyname] = userKeypress.getSingleModifierDispatchChords();
        userPressedChord = dispatchKeyname;
        currentChords = dispatchKeyname ? [dispatchKeyname] : [];
      } else {
        [userPressedChord] = userKeypress.getDispatchChords();
        currentChords = this._currentChords.map(({ keypress }) => keypress);
      }
      if (userPressedChord === null) {
        this._log(`\\ Keyboard event cannot be dispatched in keydown phase.`);
        return shouldPreventDefault;
      }
      const contextValue = this._contextKeyService.getContext(target);
      const keypressLabel = userKeypress.getLabel();
      const resolveResult = this._getResolver().resolve(contextValue, currentChords, userPressedChord);
      switch (resolveResult.kind) {
        case 0: {
          this._logService.trace("KeybindingService#dispatch", keypressLabel, `[ No matching keybinding ]`);
          if (this.inChordMode) {
            const currentChordsLabel = this._currentChords.map(({ label }) => label).join(", ");
            this._log(`+ Leaving multi-chord mode: Nothing bound to "${currentChordsLabel}, ${keypressLabel}".`);
            this._notificationService.status(localize(1703, "The key combination ({0}, {1}) is not a command.", currentChordsLabel, keypressLabel), {
              hideAfter: 10 * 1e3
              /* 10s */
            });
            this._leaveChordMode();
            shouldPreventDefault = true;
          }
          return shouldPreventDefault;
        }
        case 1: {
          this._logService.trace("KeybindingService#dispatch", keypressLabel, `[ Several keybindings match - more chords needed ]`);
          shouldPreventDefault = true;
          this._expectAnotherChord(userPressedChord, keypressLabel);
          this._log(this._currentChords.length === 1 ? `+ Entering multi-chord mode...` : `+ Continuing multi-chord mode...`);
          return shouldPreventDefault;
        }
        case 2: {
          this._logService.trace("KeybindingService#dispatch", keypressLabel, `[ Will dispatch command ${resolveResult.commandId} ]`);
          if (resolveResult.commandId === null || resolveResult.commandId === "") {
            if (this.inChordMode) {
              const currentChordsLabel = this._currentChords.map(({ label }) => label).join(", ");
              this._log(`+ Leaving chord mode: Nothing bound to "${currentChordsLabel}, ${keypressLabel}".`);
              this._notificationService.status(localize(1704, "The key combination ({0}, {1}) is not a command.", currentChordsLabel, keypressLabel), {
                hideAfter: 10 * 1e3
                /* 10s */
              });
              this._leaveChordMode();
              shouldPreventDefault = true;
            }
          } else {
            if (this.inChordMode) {
              this._leaveChordMode();
            }
            if (!resolveResult.isBubble) {
              shouldPreventDefault = true;
            }
            this._log(`+ Invoking command ${resolveResult.commandId}.`);
            this._currentlyDispatchingCommandId = resolveResult.commandId;
            try {
              if (typeof resolveResult.commandArgs === "undefined") {
                this._commandService.executeCommand(resolveResult.commandId).then(void 0, (err) => this._notificationService.warn(err));
              } else {
                this._commandService.executeCommand(resolveResult.commandId, resolveResult.commandArgs).then(void 0, (err) => this._notificationService.warn(err));
              }
            } finally {
              this._currentlyDispatchingCommandId = null;
            }
            if (!HIGH_FREQ_COMMANDS.test(resolveResult.commandId)) {
              this._telemetryService.publicLog2("workbenchActionExecuted", { id: resolveResult.commandId, from: "keybinding", detail: userKeypress.getUserSettingsLabel() ?? void 0 });
            }
          }
          return shouldPreventDefault;
        }
      }
    }
    mightProducePrintableCharacter(event) {
      if (event.ctrlKey || event.metaKey) {
        return false;
      }
      if (event.keyCode >= 31 && event.keyCode <= 56 || event.keyCode >= 21 && event.keyCode <= 30) {
        return true;
      }
      return false;
    }
  }
  const _KeybindingModifierSet = class _KeybindingModifierSet {
    constructor(source) {
      this._ctrlKey = source ? source.ctrlKey : false;
      this._shiftKey = source ? source.shiftKey : false;
      this._altKey = source ? source.altKey : false;
      this._metaKey = source ? source.metaKey : false;
    }
    has(modifier) {
      switch (modifier) {
        case "ctrl":
          return this._ctrlKey;
        case "shift":
          return this._shiftKey;
        case "alt":
          return this._altKey;
        case "meta":
          return this._metaKey;
      }
    }
  };
  _KeybindingModifierSet.EMPTY = new _KeybindingModifierSet(null);
  let KeybindingModifierSet = _KeybindingModifierSet;
  class ResolvedKeybindingItem {
    constructor(resolvedKeybinding, command, commandArgs, when, isDefault, extensionId, isBuiltinExtension) {
      this._resolvedKeybindingItemBrand = void 0;
      this.resolvedKeybinding = resolvedKeybinding;
      this.chords = resolvedKeybinding ? toEmptyArrayIfContainsNull(resolvedKeybinding.getDispatchChords()) : [];
      if (resolvedKeybinding && this.chords.length === 0) {
        this.chords = toEmptyArrayIfContainsNull(resolvedKeybinding.getSingleModifierDispatchChords());
      }
      this.bubble = command ? command.charCodeAt(0) === 94 : false;
      this.command = this.bubble ? command.substr(1) : command;
      this.commandArgs = commandArgs;
      this.when = when;
      this.isDefault = isDefault;
      this.extensionId = extensionId;
      this.isBuiltinExtension = isBuiltinExtension;
    }
  }
  function toEmptyArrayIfContainsNull(arr) {
    const result = [];
    for (let i2 = 0, len = arr.length; i2 < len; i2++) {
      const element = arr[i2];
      if (!element) {
        return [];
      }
      result.push(element);
    }
    return result;
  }
  class BaseResolvedKeybinding extends ResolvedKeybinding {
    constructor(os, chords) {
      super();
      if (chords.length === 0) {
        throw illegalArgument(`chords`);
      }
      this._os = os;
      this._chords = chords;
    }
    getLabel() {
      return UILabelProvider.toLabel(this._os, this._chords, (keybinding) => this._getLabel(keybinding));
    }
    getAriaLabel() {
      return AriaLabelProvider.toLabel(this._os, this._chords, (keybinding) => this._getAriaLabel(keybinding));
    }
    getElectronAccelerator() {
      if (this._chords.length > 1) {
        return null;
      }
      if (this._chords[0].isDuplicateModifierCase()) {
        return null;
      }
      return ElectronAcceleratorLabelProvider.toLabel(this._os, this._chords, (keybinding) => this._getElectronAccelerator(keybinding));
    }
    getUserSettingsLabel() {
      return UserSettingsLabelProvider.toLabel(this._os, this._chords, (keybinding) => this._getUserSettingsLabel(keybinding));
    }
    hasMultipleChords() {
      return this._chords.length > 1;
    }
    getChords() {
      return this._chords.map((keybinding) => this._getChord(keybinding));
    }
    _getChord(keybinding) {
      return new ResolvedChord(keybinding.ctrlKey, keybinding.shiftKey, keybinding.altKey, keybinding.metaKey, this._getLabel(keybinding), this._getAriaLabel(keybinding));
    }
    getDispatchChords() {
      return this._chords.map((keybinding) => this._getChordDispatch(keybinding));
    }
    getSingleModifierDispatchChords() {
      return this._chords.map((keybinding) => this._getSingleModifierChordDispatch(keybinding));
    }
  }
  class USLayoutResolvedKeybinding extends BaseResolvedKeybinding {
    constructor(chords, os) {
      super(os, chords);
    }
    _keyCodeToUILabel(keyCode) {
      if (this._os === 2) {
        switch (keyCode) {
          case 15:
            return "←";
          case 16:
            return "↑";
          case 17:
            return "→";
          case 18:
            return "↓";
        }
      }
      return KeyCodeUtils.toString(keyCode);
    }
    _getLabel(chord) {
      if (chord.isDuplicateModifierCase()) {
        return "";
      }
      return this._keyCodeToUILabel(chord.keyCode);
    }
    _getAriaLabel(chord) {
      if (chord.isDuplicateModifierCase()) {
        return "";
      }
      return KeyCodeUtils.toString(chord.keyCode);
    }
    _getElectronAccelerator(chord) {
      return KeyCodeUtils.toElectronAccelerator(chord.keyCode);
    }
    _getUserSettingsLabel(chord) {
      if (chord.isDuplicateModifierCase()) {
        return "";
      }
      const result = KeyCodeUtils.toUserSettingsUS(chord.keyCode);
      return result ? result.toLowerCase() : result;
    }
    _getChordDispatch(chord) {
      return USLayoutResolvedKeybinding.getDispatchStr(chord);
    }
    static getDispatchStr(chord) {
      if (chord.isModifierKey()) {
        return null;
      }
      let result = "";
      if (chord.ctrlKey) {
        result += "ctrl+";
      }
      if (chord.shiftKey) {
        result += "shift+";
      }
      if (chord.altKey) {
        result += "alt+";
      }
      if (chord.metaKey) {
        result += "meta+";
      }
      result += KeyCodeUtils.toString(chord.keyCode);
      return result;
    }
    _getSingleModifierChordDispatch(keybinding) {
      if (keybinding.keyCode === 5 && !keybinding.shiftKey && !keybinding.altKey && !keybinding.metaKey) {
        return "ctrl";
      }
      if (keybinding.keyCode === 4 && !keybinding.ctrlKey && !keybinding.altKey && !keybinding.metaKey) {
        return "shift";
      }
      if (keybinding.keyCode === 6 && !keybinding.ctrlKey && !keybinding.shiftKey && !keybinding.metaKey) {
        return "alt";
      }
      if (keybinding.keyCode === 57 && !keybinding.ctrlKey && !keybinding.shiftKey && !keybinding.altKey) {
        return "meta";
      }
      return null;
    }
    /**
     * *NOTE*: Check return value for `KeyCode.Unknown`.
     */
    static _scanCodeToKeyCode(scanCode) {
      const immutableKeyCode = IMMUTABLE_CODE_TO_KEY_CODE[scanCode];
      if (immutableKeyCode !== -1) {
        return immutableKeyCode;
      }
      switch (scanCode) {
        case 10:
          return 31;
        case 11:
          return 32;
        case 12:
          return 33;
        case 13:
          return 34;
        case 14:
          return 35;
        case 15:
          return 36;
        case 16:
          return 37;
        case 17:
          return 38;
        case 18:
          return 39;
        case 19:
          return 40;
        case 20:
          return 41;
        case 21:
          return 42;
        case 22:
          return 43;
        case 23:
          return 44;
        case 24:
          return 45;
        case 25:
          return 46;
        case 26:
          return 47;
        case 27:
          return 48;
        case 28:
          return 49;
        case 29:
          return 50;
        case 30:
          return 51;
        case 31:
          return 52;
        case 32:
          return 53;
        case 33:
          return 54;
        case 34:
          return 55;
        case 35:
          return 56;
        case 36:
          return 22;
        case 37:
          return 23;
        case 38:
          return 24;
        case 39:
          return 25;
        case 40:
          return 26;
        case 41:
          return 27;
        case 42:
          return 28;
        case 43:
          return 29;
        case 44:
          return 30;
        case 45:
          return 21;
        case 51:
          return 88;
        case 52:
          return 86;
        case 53:
          return 92;
        case 54:
          return 94;
        case 55:
          return 93;
        case 56:
          return 0;
        // missing
        case 57:
          return 85;
        case 58:
          return 95;
        case 59:
          return 91;
        case 60:
          return 87;
        case 61:
          return 89;
        case 62:
          return 90;
        case 106:
          return 97;
      }
      return 0;
    }
    static _toKeyCodeChord(chord) {
      if (!chord) {
        return null;
      }
      if (chord instanceof KeyCodeChord) {
        return chord;
      }
      const keyCode = this._scanCodeToKeyCode(chord.scanCode);
      if (keyCode === 0) {
        return null;
      }
      return new KeyCodeChord(chord.ctrlKey, chord.shiftKey, chord.altKey, chord.metaKey, keyCode);
    }
    static resolveKeybinding(keybinding, os) {
      const chords = toEmptyArrayIfContainsNull(keybinding.chords.map((chord) => this._toKeyCodeChord(chord)));
      if (chords.length > 0) {
        return [new USLayoutResolvedKeybinding(chords, os)];
      }
      return [];
    }
  }
  let registeredAssociations = [];
  let nonUserRegisteredAssociations = [];
  let userRegisteredAssociations = [];
  function registerPlatformLanguageAssociation(association, warnOnOverwrite = false) {
    _registerLanguageAssociation(association, false, warnOnOverwrite);
  }
  function _registerLanguageAssociation(association, userConfigured, warnOnOverwrite) {
    const associationItem = toLanguageAssociationItem(association, userConfigured);
    registeredAssociations.push(associationItem);
    if (!associationItem.userConfigured) {
      nonUserRegisteredAssociations.push(associationItem);
    } else {
      userRegisteredAssociations.push(associationItem);
    }
    if (warnOnOverwrite && !associationItem.userConfigured) {
      registeredAssociations.forEach((a) => {
        if (a.mime === associationItem.mime || a.userConfigured) {
          return;
        }
        if (associationItem.extension && a.extension === associationItem.extension) {
          console.warn(`Overwriting extension <<${associationItem.extension}>> to now point to mime <<${associationItem.mime}>>`);
        }
        if (associationItem.filename && a.filename === associationItem.filename) {
          console.warn(`Overwriting filename <<${associationItem.filename}>> to now point to mime <<${associationItem.mime}>>`);
        }
        if (associationItem.filepattern && a.filepattern === associationItem.filepattern) {
          console.warn(`Overwriting filepattern <<${associationItem.filepattern}>> to now point to mime <<${associationItem.mime}>>`);
        }
        if (associationItem.firstline && a.firstline === associationItem.firstline) {
          console.warn(`Overwriting firstline <<${associationItem.firstline}>> to now point to mime <<${associationItem.mime}>>`);
        }
      });
    }
  }
  function toLanguageAssociationItem(association, userConfigured) {
    return {
      id: association.id,
      mime: association.mime,
      filename: association.filename,
      extension: association.extension,
      filepattern: association.filepattern,
      firstline: association.firstline,
      userConfigured,
      filenameLowercase: association.filename ? association.filename.toLowerCase() : void 0,
      extensionLowercase: association.extension ? association.extension.toLowerCase() : void 0,
      filepatternLowercase: association.filepattern ? parse(association.filepattern.toLowerCase()) : void 0,
      filepatternOnPath: association.filepattern ? association.filepattern.indexOf(posix.sep) >= 0 : false
    };
  }
  function clearPlatformLanguageAssociations() {
    registeredAssociations = registeredAssociations.filter((a) => a.userConfigured);
    nonUserRegisteredAssociations = [];
  }
  function getLanguageIds(resource, firstLine) {
    return getAssociations(resource, firstLine).map((item) => item.id);
  }
  function getAssociations(resource, firstLine) {
    let path;
    if (resource) {
      switch (resource.scheme) {
        case Schemas.file:
          path = resource.fsPath;
          break;
        case Schemas.data: {
          const metadata = DataUri.parseMetaData(resource);
          path = metadata.get(DataUri.META_DATA_LABEL);
          break;
        }
        case Schemas.vscodeNotebookCell:
          path = void 0;
          break;
        default:
          path = resource.path;
      }
    }
    if (!path) {
      return [{ id: "unknown", mime: Mimes.unknown }];
    }
    path = path.toLowerCase();
    const filename = basename$1(path);
    const configuredLanguage = getAssociationByPath(path, filename, userRegisteredAssociations);
    if (configuredLanguage) {
      return [configuredLanguage, { id: PLAINTEXT_LANGUAGE_ID, mime: Mimes.text }];
    }
    const registeredLanguage = getAssociationByPath(path, filename, nonUserRegisteredAssociations);
    if (registeredLanguage) {
      return [registeredLanguage, { id: PLAINTEXT_LANGUAGE_ID, mime: Mimes.text }];
    }
    if (firstLine) {
      const firstlineLanguage = getAssociationByFirstline(firstLine);
      if (firstlineLanguage) {
        return [firstlineLanguage, { id: PLAINTEXT_LANGUAGE_ID, mime: Mimes.text }];
      }
    }
    return [{ id: "unknown", mime: Mimes.unknown }];
  }
  function getAssociationByPath(path, filename, associations) {
    let filenameMatch = void 0;
    let patternMatch = void 0;
    let extensionMatch = void 0;
    for (let i2 = associations.length - 1; i2 >= 0; i2--) {
      const association = associations[i2];
      if (filename === association.filenameLowercase) {
        filenameMatch = association;
        break;
      }
      if (association.filepattern) {
        if (!patternMatch || association.filepattern.length > patternMatch.filepattern.length) {
          const target = association.filepatternOnPath ? path : filename;
          if (association.filepatternLowercase?.(target)) {
            patternMatch = association;
          }
        }
      }
      if (association.extension) {
        if (!extensionMatch || association.extension.length > extensionMatch.extension.length) {
          if (filename.endsWith(association.extensionLowercase)) {
            extensionMatch = association;
          }
        }
      }
    }
    if (filenameMatch) {
      return filenameMatch;
    }
    if (patternMatch) {
      return patternMatch;
    }
    if (extensionMatch) {
      return extensionMatch;
    }
    return void 0;
  }
  function getAssociationByFirstline(firstLine) {
    if (startsWithUTF8BOM(firstLine)) {
      firstLine = firstLine.substr(1);
    }
    if (firstLine.length > 0) {
      for (let i2 = registeredAssociations.length - 1; i2 >= 0; i2--) {
        const association = registeredAssociations[i2];
        if (!association.firstline) {
          continue;
        }
        const matches = firstLine.match(association.firstline);
        if (matches && matches.length > 0) {
          return association;
        }
      }
    }
    return void 0;
  }
  const hasOwnProperty = Object.prototype.hasOwnProperty;
  const NULL_LANGUAGE_ID = "vs.editor.nullLanguage";
  class LanguageIdCodec {
    constructor() {
      this._languageIdToLanguage = [];
      this._languageToLanguageId = /* @__PURE__ */ new Map();
      this._register(
        NULL_LANGUAGE_ID,
        0
        /* LanguageId.Null */
      );
      this._register(
        PLAINTEXT_LANGUAGE_ID,
        1
        /* LanguageId.PlainText */
      );
      this._nextLanguageId = 2;
    }
    _register(language2, languageId) {
      this._languageIdToLanguage[languageId] = language2;
      this._languageToLanguageId.set(language2, languageId);
    }
    register(language2) {
      if (this._languageToLanguageId.has(language2)) {
        return;
      }
      const languageId = this._nextLanguageId++;
      this._register(language2, languageId);
    }
    encodeLanguageId(languageId) {
      return this._languageToLanguageId.get(languageId) || 0;
    }
    decodeLanguageId(languageId) {
      return this._languageIdToLanguage[languageId] || NULL_LANGUAGE_ID;
    }
  }
  const _LanguagesRegistry = class _LanguagesRegistry extends Disposable {
    constructor(useModesRegistry = true, warnOnOverwrite = false) {
      super();
      this._onDidChange = this._register(new Emitter$1());
      this.onDidChange = this._onDidChange.event;
      _LanguagesRegistry.instanceCount++;
      this._warnOnOverwrite = warnOnOverwrite;
      this.languageIdCodec = new LanguageIdCodec();
      this._dynamicLanguages = [];
      this._languages = {};
      this._mimeTypesMap = {};
      this._nameMap = {};
      this._lowercaseNameMap = {};
      if (useModesRegistry) {
        this._initializeFromRegistry();
        this._register(ModesRegistry.onDidChangeLanguages((m) => {
          this._initializeFromRegistry();
        }));
      }
    }
    dispose() {
      _LanguagesRegistry.instanceCount--;
      super.dispose();
    }
    _initializeFromRegistry() {
      this._languages = {};
      this._mimeTypesMap = {};
      this._nameMap = {};
      this._lowercaseNameMap = {};
      clearPlatformLanguageAssociations();
      const desc = [].concat(ModesRegistry.getLanguages()).concat(this._dynamicLanguages);
      this._registerLanguages(desc);
    }
    _registerLanguages(desc) {
      for (const d of desc) {
        this._registerLanguage(d);
      }
      this._mimeTypesMap = {};
      this._nameMap = {};
      this._lowercaseNameMap = {};
      Object.keys(this._languages).forEach((langId) => {
        const language2 = this._languages[langId];
        if (language2.name) {
          this._nameMap[language2.name] = language2.identifier;
        }
        language2.aliases.forEach((alias) => {
          this._lowercaseNameMap[alias.toLowerCase()] = language2.identifier;
        });
        language2.mimetypes.forEach((mimetype) => {
          this._mimeTypesMap[mimetype] = language2.identifier;
        });
      });
      Registry.as(Extensions$6.Configuration).registerOverrideIdentifiers(this.getRegisteredLanguageIds());
      this._onDidChange.fire();
    }
    _registerLanguage(lang) {
      const langId = lang.id;
      let resolvedLanguage;
      if (hasOwnProperty.call(this._languages, langId)) {
        resolvedLanguage = this._languages[langId];
      } else {
        this.languageIdCodec.register(langId);
        resolvedLanguage = {
          identifier: langId,
          name: null,
          mimetypes: [],
          aliases: [],
          extensions: [],
          filenames: [],
          configurationFiles: [],
          icons: []
        };
        this._languages[langId] = resolvedLanguage;
      }
      this._mergeLanguage(resolvedLanguage, lang);
    }
    _mergeLanguage(resolvedLanguage, lang) {
      const langId = lang.id;
      let primaryMime = null;
      if (Array.isArray(lang.mimetypes) && lang.mimetypes.length > 0) {
        resolvedLanguage.mimetypes.push(...lang.mimetypes);
        primaryMime = lang.mimetypes[0];
      }
      if (!primaryMime) {
        primaryMime = `text/x-${langId}`;
        resolvedLanguage.mimetypes.push(primaryMime);
      }
      if (Array.isArray(lang.extensions)) {
        if (lang.configuration) {
          resolvedLanguage.extensions = lang.extensions.concat(resolvedLanguage.extensions);
        } else {
          resolvedLanguage.extensions = resolvedLanguage.extensions.concat(lang.extensions);
        }
        for (const extension of lang.extensions) {
          registerPlatformLanguageAssociation({ id: langId, mime: primaryMime, extension }, this._warnOnOverwrite);
        }
      }
      if (Array.isArray(lang.filenames)) {
        for (const filename of lang.filenames) {
          registerPlatformLanguageAssociation({ id: langId, mime: primaryMime, filename }, this._warnOnOverwrite);
          resolvedLanguage.filenames.push(filename);
        }
      }
      if (Array.isArray(lang.filenamePatterns)) {
        for (const filenamePattern of lang.filenamePatterns) {
          registerPlatformLanguageAssociation({ id: langId, mime: primaryMime, filepattern: filenamePattern }, this._warnOnOverwrite);
        }
      }
      if (typeof lang.firstLine === "string" && lang.firstLine.length > 0) {
        let firstLineRegexStr = lang.firstLine;
        if (firstLineRegexStr.charAt(0) !== "^") {
          firstLineRegexStr = "^" + firstLineRegexStr;
        }
        try {
          const firstLineRegex = new RegExp(firstLineRegexStr);
          if (!regExpLeadsToEndlessLoop(firstLineRegex)) {
            registerPlatformLanguageAssociation({ id: langId, mime: primaryMime, firstline: firstLineRegex }, this._warnOnOverwrite);
          }
        } catch (err) {
          console.warn(`[${lang.id}]: Invalid regular expression \`${firstLineRegexStr}\`: `, err);
        }
      }
      resolvedLanguage.aliases.push(langId);
      let langAliases = null;
      if (typeof lang.aliases !== "undefined" && Array.isArray(lang.aliases)) {
        if (lang.aliases.length === 0) {
          langAliases = [null];
        } else {
          langAliases = lang.aliases;
        }
      }
      if (langAliases !== null) {
        for (const langAlias of langAliases) {
          if (!langAlias || langAlias.length === 0) {
            continue;
          }
          resolvedLanguage.aliases.push(langAlias);
        }
      }
      const containsAliases = langAliases !== null && langAliases.length > 0;
      if (containsAliases && langAliases[0] === null) ;
      else {
        const bestName = (containsAliases ? langAliases[0] : null) || langId;
        if (containsAliases || !resolvedLanguage.name) {
          resolvedLanguage.name = bestName;
        }
      }
      if (lang.configuration) {
        resolvedLanguage.configurationFiles.push(lang.configuration);
      }
      if (lang.icon) {
        resolvedLanguage.icons.push(lang.icon);
      }
    }
    isRegisteredLanguageId(languageId) {
      if (!languageId) {
        return false;
      }
      return hasOwnProperty.call(this._languages, languageId);
    }
    getRegisteredLanguageIds() {
      return Object.keys(this._languages);
    }
    getLanguageIdByLanguageName(languageName) {
      const languageNameLower = languageName.toLowerCase();
      if (!hasOwnProperty.call(this._lowercaseNameMap, languageNameLower)) {
        return null;
      }
      return this._lowercaseNameMap[languageNameLower];
    }
    getLanguageIdByMimeType(mimeType) {
      if (!mimeType) {
        return null;
      }
      if (hasOwnProperty.call(this._mimeTypesMap, mimeType)) {
        return this._mimeTypesMap[mimeType];
      }
      return null;
    }
    guessLanguageIdByFilepathOrFirstLine(resource, firstLine) {
      if (!resource && !firstLine) {
        return [];
      }
      return getLanguageIds(resource, firstLine);
    }
  };
  _LanguagesRegistry.instanceCount = 0;
  let LanguagesRegistry = _LanguagesRegistry;
  const _LanguageService = class _LanguageService extends Disposable {
    constructor(warnOnOverwrite = false) {
      super();
      this._onDidRequestBasicLanguageFeatures = this._register(new Emitter$1());
      this.onDidRequestBasicLanguageFeatures = this._onDidRequestBasicLanguageFeatures.event;
      this._onDidRequestRichLanguageFeatures = this._register(new Emitter$1());
      this.onDidRequestRichLanguageFeatures = this._onDidRequestRichLanguageFeatures.event;
      this._onDidChange = this._register(new Emitter$1({
        leakWarningThreshold: 200
        /* https://github.com/microsoft/vscode/issues/119968 */
      }));
      this.onDidChange = this._onDidChange.event;
      this._requestedBasicLanguages = /* @__PURE__ */ new Set();
      this._requestedRichLanguages = /* @__PURE__ */ new Set();
      _LanguageService.instanceCount++;
      this._registry = this._register(new LanguagesRegistry(true, warnOnOverwrite));
      this.languageIdCodec = this._registry.languageIdCodec;
      this._register(this._registry.onDidChange(() => this._onDidChange.fire()));
    }
    dispose() {
      _LanguageService.instanceCount--;
      super.dispose();
    }
    isRegisteredLanguageId(languageId) {
      return this._registry.isRegisteredLanguageId(languageId);
    }
    getLanguageIdByLanguageName(languageName) {
      return this._registry.getLanguageIdByLanguageName(languageName);
    }
    getLanguageIdByMimeType(mimeType) {
      return this._registry.getLanguageIdByMimeType(mimeType);
    }
    guessLanguageIdByFilepathOrFirstLine(resource, firstLine) {
      const languageIds = this._registry.guessLanguageIdByFilepathOrFirstLine(resource, firstLine);
      return languageIds.at(0) ?? null;
    }
    createById(languageId) {
      return new LanguageSelection(this.onDidChange, () => {
        return this._createAndGetLanguageIdentifier(languageId);
      });
    }
    createByFilepathOrFirstLine(resource, firstLine) {
      return new LanguageSelection(this.onDidChange, () => {
        const languageId = this.guessLanguageIdByFilepathOrFirstLine(resource, firstLine);
        return this._createAndGetLanguageIdentifier(languageId);
      });
    }
    _createAndGetLanguageIdentifier(languageId) {
      if (!languageId || !this.isRegisteredLanguageId(languageId)) {
        languageId = PLAINTEXT_LANGUAGE_ID;
      }
      return languageId;
    }
    requestBasicLanguageFeatures(languageId) {
      if (!this._requestedBasicLanguages.has(languageId)) {
        this._requestedBasicLanguages.add(languageId);
        this._onDidRequestBasicLanguageFeatures.fire(languageId);
      }
    }
    requestRichLanguageFeatures(languageId) {
      if (!this._requestedRichLanguages.has(languageId)) {
        this._requestedRichLanguages.add(languageId);
        this.requestBasicLanguageFeatures(languageId);
        TokenizationRegistry.getOrCreate(languageId);
        this._onDidRequestRichLanguageFeatures.fire(languageId);
      }
    }
  };
  _LanguageService.instanceCount = 0;
  let LanguageService = _LanguageService;
  class LanguageSelection {
    constructor(onDidChangeLanguages, selector) {
      this._value = observableFromEvent(this, onDidChangeLanguages, () => selector());
      this.onDidChange = Event.fromObservable(this._value);
    }
    get languageId() {
      return this._value.get();
    }
  }
  const MENU_MNEMONIC_REGEX = /\(&([^\s&])\)|(^|[^&])&([^\s&])/;
  const MENU_ESCAPED_MNEMONIC_REGEX = /(&amp;)?(&amp;)([^\s&])/g;
  var HorizontalDirection;
  (function(HorizontalDirection2) {
    HorizontalDirection2[HorizontalDirection2["Right"] = 0] = "Right";
    HorizontalDirection2[HorizontalDirection2["Left"] = 1] = "Left";
  })(HorizontalDirection || (HorizontalDirection = {}));
  var VerticalDirection;
  (function(VerticalDirection2) {
    VerticalDirection2[VerticalDirection2["Above"] = 0] = "Above";
    VerticalDirection2[VerticalDirection2["Below"] = 1] = "Below";
  })(VerticalDirection || (VerticalDirection = {}));
  class Menu extends ActionBar {
    constructor(container, actions, options, menuStyles) {
      container.classList.add("monaco-menu-container");
      container.setAttribute("role", "presentation");
      const menuElement = document.createElement("div");
      menuElement.classList.add("monaco-menu");
      menuElement.setAttribute("role", "presentation");
      super(menuElement, {
        orientation: 1,
        actionViewItemProvider: (action) => this.doGetActionViewItem(action, options, parentData),
        context: options.context,
        actionRunner: options.actionRunner,
        ariaLabel: options.ariaLabel,
        ariaRole: "menu",
        focusOnlyEnabledItems: true,
        triggerKeys: { keys: [3, ...isMacintosh || isLinux ? [
          10
          /* KeyCode.Space */
        ] : []], keyDown: true }
      });
      this.menuStyles = menuStyles;
      this.menuElement = menuElement;
      this.actionsList.tabIndex = 0;
      this.initializeOrUpdateStyleSheet(container, menuStyles);
      this._register(Gesture.addTarget(menuElement));
      this._register(addDisposableListener(menuElement, EventType$1.KEY_DOWN, (e) => {
        const event = new StandardKeyboardEvent(e);
        if (event.equals(
          2
          /* KeyCode.Tab */
        )) {
          e.preventDefault();
        }
      }));
      if (options.enableMnemonics) {
        this._register(addDisposableListener(menuElement, EventType$1.KEY_DOWN, (e) => {
          const key = e.key.toLocaleLowerCase();
          if (this.mnemonics.has(key)) {
            EventHelper.stop(e, true);
            const actions2 = this.mnemonics.get(key);
            if (actions2.length === 1) {
              if (actions2[0] instanceof SubmenuMenuActionViewItem && actions2[0].container) {
                this.focusItemByElement(actions2[0].container);
              }
              actions2[0].onClick(e);
            }
            if (actions2.length > 1) {
              const action = actions2.shift();
              if (action && action.container) {
                this.focusItemByElement(action.container);
                actions2.push(action);
              }
              this.mnemonics.set(key, actions2);
            }
          }
        }));
      }
      if (isLinux) {
        this._register(addDisposableListener(menuElement, EventType$1.KEY_DOWN, (e) => {
          const event = new StandardKeyboardEvent(e);
          if (event.equals(
            14
            /* KeyCode.Home */
          ) || event.equals(
            11
            /* KeyCode.PageUp */
          )) {
            this.focusedItem = this.viewItems.length - 1;
            this.focusNext();
            EventHelper.stop(e, true);
          } else if (event.equals(
            13
            /* KeyCode.End */
          ) || event.equals(
            12
            /* KeyCode.PageDown */
          )) {
            this.focusedItem = 0;
            this.focusPrevious();
            EventHelper.stop(e, true);
          }
        }));
      }
      this._register(addDisposableListener(this.domNode, EventType$1.MOUSE_OUT, (e) => {
        const relatedTarget = e.relatedTarget;
        if (!isAncestor$1(relatedTarget, this.domNode)) {
          this.focusedItem = void 0;
          this.updateFocus();
          e.stopPropagation();
        }
      }));
      this._register(addDisposableListener(this.actionsList, EventType$1.MOUSE_OVER, (e) => {
        let target = e.target;
        if (!target || !isAncestor$1(target, this.actionsList) || target === this.actionsList) {
          return;
        }
        while (target.parentElement !== this.actionsList && target.parentElement !== null) {
          target = target.parentElement;
        }
        if (target.classList.contains("action-item")) {
          const lastFocusedItem = this.focusedItem;
          this.setFocusedItem(target);
          if (lastFocusedItem !== this.focusedItem) {
            this.updateFocus();
          }
        }
      }));
      this._register(Gesture.addTarget(this.actionsList));
      this._register(addDisposableListener(this.actionsList, EventType.Tap, (e) => {
        let target = e.initialTarget;
        if (!target || !isAncestor$1(target, this.actionsList) || target === this.actionsList) {
          return;
        }
        while (target.parentElement !== this.actionsList && target.parentElement !== null) {
          target = target.parentElement;
        }
        if (target.classList.contains("action-item")) {
          const lastFocusedItem = this.focusedItem;
          this.setFocusedItem(target);
          if (lastFocusedItem !== this.focusedItem) {
            this.updateFocus();
          }
        }
      }));
      const parentData = {
        parent: this
      };
      this.mnemonics = /* @__PURE__ */ new Map();
      this.scrollableElement = this._register(new DomScrollableElement(menuElement, {
        alwaysConsumeMouseWheel: true,
        horizontal: 2,
        vertical: 3,
        verticalScrollbarSize: 7,
        handleMouseWheel: true,
        useShadows: true
      }));
      const scrollElement = this.scrollableElement.getDomNode();
      scrollElement.style.position = "";
      this.styleScrollElement(scrollElement, menuStyles);
      this._register(addDisposableListener(menuElement, EventType.Change, (e) => {
        EventHelper.stop(e, true);
        const scrollTop = this.scrollableElement.getScrollPosition().scrollTop;
        this.scrollableElement.setScrollPosition({ scrollTop: scrollTop - e.translationY });
      }));
      this._register(addDisposableListener(scrollElement, EventType$1.MOUSE_UP, (e) => {
        e.preventDefault();
      }));
      const window2 = getWindow(container);
      menuElement.style.maxHeight = `${Math.max(10, window2.innerHeight - container.getBoundingClientRect().top - 35)}px`;
      actions = actions.filter((a, idx) => {
        if (options.submenuIds?.has(a.id)) {
          console.warn(`Found submenu cycle: ${a.id}`);
          return false;
        }
        if (a instanceof Separator) {
          if (idx === actions.length - 1 || idx === 0) {
            return false;
          }
          const prevAction = actions[idx - 1];
          if (prevAction instanceof Separator) {
            return false;
          }
        }
        return true;
      });
      this.push(actions, { icon: true, label: true, isMenu: true });
      container.appendChild(this.scrollableElement.getDomNode());
      this.scrollableElement.scanDomNode();
      this.viewItems.filter((item) => !(item instanceof MenuSeparatorActionViewItem)).forEach((item, index, array2) => {
        item.updatePositionInSet(index + 1, array2.length);
      });
    }
    initializeOrUpdateStyleSheet(container, style) {
      if (!this.styleSheet) {
        if (isInShadowDOM(container)) {
          this.styleSheet = createStyleSheet(container);
        } else {
          if (!Menu.globalStyleSheet) {
            Menu.globalStyleSheet = createStyleSheet();
          }
          this.styleSheet = Menu.globalStyleSheet;
        }
      }
      this.styleSheet.textContent = getMenuWidgetCSS(style, isInShadowDOM(container));
    }
    styleScrollElement(scrollElement, style) {
      const fgColor = style.foregroundColor ?? "";
      const bgColor = style.backgroundColor ?? "";
      const border = style.borderColor ? `1px solid ${style.borderColor}` : "";
      const borderRadius = "5px";
      const shadow = style.shadowColor ? `0 2px 8px ${style.shadowColor}` : "";
      scrollElement.style.outline = border;
      scrollElement.style.borderRadius = borderRadius;
      scrollElement.style.color = fgColor;
      scrollElement.style.backgroundColor = bgColor;
      scrollElement.style.boxShadow = shadow;
    }
    getContainer() {
      return this.scrollableElement.getDomNode();
    }
    get onScroll() {
      return this.scrollableElement.onScroll;
    }
    focusItemByElement(element) {
      const lastFocusedItem = this.focusedItem;
      this.setFocusedItem(element);
      if (lastFocusedItem !== this.focusedItem) {
        this.updateFocus();
      }
    }
    setFocusedItem(element) {
      for (let i2 = 0; i2 < this.actionsList.children.length; i2++) {
        const elem = this.actionsList.children[i2];
        if (element === elem) {
          this.focusedItem = i2;
          break;
        }
      }
    }
    updateFocus(fromRight) {
      super.updateFocus(fromRight, true, true);
      if (typeof this.focusedItem !== "undefined") {
        this.scrollableElement.setScrollPosition({
          scrollTop: Math.round(this.menuElement.scrollTop)
        });
      }
    }
    doGetActionViewItem(action, options, parentData) {
      if (action instanceof Separator) {
        return new MenuSeparatorActionViewItem(options.context, action, { icon: true }, this.menuStyles);
      } else if (action instanceof SubmenuAction) {
        const menuActionViewItem = new SubmenuMenuActionViewItem(action, action.actions, parentData, { ...options, submenuIds: /* @__PURE__ */ new Set([...options.submenuIds || [], action.id]) }, this.menuStyles);
        if (options.enableMnemonics) {
          const mnemonic = menuActionViewItem.getMnemonic();
          if (mnemonic && menuActionViewItem.isEnabled()) {
            let actionViewItems = [];
            if (this.mnemonics.has(mnemonic)) {
              actionViewItems = this.mnemonics.get(mnemonic);
            }
            actionViewItems.push(menuActionViewItem);
            this.mnemonics.set(mnemonic, actionViewItems);
          }
        }
        return menuActionViewItem;
      } else {
        const keybindingLabel = options.getKeyBinding?.(action)?.getLabel();
        const menuItemOptions = {
          enableMnemonics: options.enableMnemonics,
          useEventAsContext: options.useEventAsContext,
          keybinding: keybindingLabel
        };
        const menuActionViewItem = new BaseMenuActionViewItem(options.context, action, menuItemOptions, this.menuStyles);
        if (options.enableMnemonics) {
          const mnemonic = menuActionViewItem.getMnemonic();
          if (mnemonic && menuActionViewItem.isEnabled()) {
            let actionViewItems = [];
            if (this.mnemonics.has(mnemonic)) {
              actionViewItems = this.mnemonics.get(mnemonic);
            }
            actionViewItems.push(menuActionViewItem);
            this.mnemonics.set(mnemonic, actionViewItems);
          }
        }
        return menuActionViewItem;
      }
    }
  }
  class BaseMenuActionViewItem extends BaseActionViewItem {
    constructor(ctx, action, options, menuStyle) {
      options = {
        ...options,
        isMenu: true,
        icon: options.icon !== void 0 ? options.icon : false,
        label: options.label !== void 0 ? options.label : true
      };
      super(action, action, options);
      this.menuStyle = menuStyle;
      this.options = options;
      this.cssClass = "";
      if (this.options.label && options.enableMnemonics) {
        const label = this.action.label;
        if (label) {
          const matches = MENU_MNEMONIC_REGEX.exec(label);
          if (matches) {
            this.mnemonic = (!!matches[1] ? matches[1] : matches[3]).toLocaleLowerCase();
          }
        }
      }
      this.runOnceToEnableMouseUp = new RunOnceScheduler(() => {
        if (!this.element) {
          return;
        }
        this._register(addDisposableListener(this.element, EventType$1.MOUSE_UP, (e) => {
          EventHelper.stop(e, true);
          if (isFirefox$1) {
            const mouseEvent = new StandardMouseEvent(getWindow(this.element), e);
            if (mouseEvent.rightButton) {
              return;
            }
            this.onClick(e);
          } else {
            setTimeout(() => {
              this.onClick(e);
            }, 0);
          }
        }));
        this._register(addDisposableListener(this.element, EventType$1.CONTEXT_MENU, (e) => {
          EventHelper.stop(e, true);
        }));
      }, 100);
      this._register(this.runOnceToEnableMouseUp);
    }
    render(container) {
      super.render(container);
      if (!this.element) {
        return;
      }
      this.container = container;
      this.item = append$2(this.element, $$l("a.action-menu-item"));
      if (this._action.id === Separator.ID) {
        this.item.setAttribute("role", "presentation");
      } else {
        this.item.setAttribute("role", "menuitem");
        if (this.mnemonic) {
          this.item.setAttribute("aria-keyshortcuts", `${this.mnemonic}`);
        }
      }
      this.check = append$2(this.item, $$l("span.menu-item-check" + ThemeIcon.asCSSSelector(Codicon.menuSelection)));
      this.check.setAttribute("role", "none");
      this.label = append$2(this.item, $$l("span.action-label"));
      if (this.options.label && this.options.keybinding) {
        append$2(this.item, $$l("span.keybinding")).textContent = this.options.keybinding;
      }
      this.runOnceToEnableMouseUp.schedule();
      this.updateClass();
      this.updateLabel();
      this.updateTooltip();
      this.updateEnabled();
      this.updateChecked();
      this.applyStyle();
    }
    blur() {
      super.blur();
      this.applyStyle();
    }
    focus() {
      super.focus();
      this.item?.focus();
      this.applyStyle();
    }
    updatePositionInSet(pos, setSize) {
      if (this.item) {
        this.item.setAttribute("aria-posinset", `${pos}`);
        this.item.setAttribute("aria-setsize", `${setSize}`);
      }
    }
    updateLabel() {
      if (!this.label) {
        return;
      }
      if (this.options.label) {
        clearNode(this.label);
        let label = stripIcons(this.action.label);
        if (label) {
          const cleanLabel = cleanMnemonic(label);
          if (!this.options.enableMnemonics) {
            label = cleanLabel;
          }
          this.label.setAttribute("aria-label", cleanLabel.replace(/&&/g, "&"));
          const matches = MENU_MNEMONIC_REGEX.exec(label);
          if (matches) {
            label = escape$2(label);
            MENU_ESCAPED_MNEMONIC_REGEX.lastIndex = 0;
            let escMatch = MENU_ESCAPED_MNEMONIC_REGEX.exec(label);
            while (escMatch && escMatch[1]) {
              escMatch = MENU_ESCAPED_MNEMONIC_REGEX.exec(label);
            }
            const replaceDoubleEscapes = (str) => str.replace(/&amp;&amp;/g, "&amp;");
            if (escMatch) {
              this.label.append(ltrim(replaceDoubleEscapes(label.substr(0, escMatch.index)), " "), $$l("u", { "aria-hidden": "true" }, escMatch[3]), rtrim$1(replaceDoubleEscapes(label.substr(escMatch.index + escMatch[0].length)), " "));
            } else {
              this.label.textContent = replaceDoubleEscapes(label).trim();
            }
            this.item?.setAttribute("aria-keyshortcuts", (!!matches[1] ? matches[1] : matches[3]).toLocaleLowerCase());
          } else {
            this.label.textContent = label.replace(/&&/g, "&").trim();
          }
        }
      }
    }
    updateTooltip() {
    }
    updateClass() {
      if (this.cssClass && this.item) {
        this.item.classList.remove(...this.cssClass.split(" "));
      }
      if (this.options.icon && this.label) {
        this.cssClass = this.action.class || "";
        this.label.classList.add("icon");
        if (this.cssClass) {
          this.label.classList.add(...this.cssClass.split(" "));
        }
        this.updateEnabled();
      } else if (this.label) {
        this.label.classList.remove("icon");
      }
    }
    updateEnabled() {
      if (this.action.enabled) {
        if (this.element) {
          this.element.classList.remove("disabled");
          this.element.removeAttribute("aria-disabled");
        }
        if (this.item) {
          this.item.classList.remove("disabled");
          this.item.removeAttribute("aria-disabled");
          this.item.tabIndex = 0;
        }
      } else {
        if (this.element) {
          this.element.classList.add("disabled");
          this.element.setAttribute("aria-disabled", "true");
        }
        if (this.item) {
          this.item.classList.add("disabled");
          this.item.setAttribute("aria-disabled", "true");
        }
      }
    }
    updateChecked() {
      if (!this.item) {
        return;
      }
      const checked = this.action.checked;
      this.item.classList.toggle("checked", !!checked);
      if (checked !== void 0) {
        this.item.setAttribute("role", "menuitemcheckbox");
        this.item.setAttribute("aria-checked", checked ? "true" : "false");
      } else {
        this.item.setAttribute("role", "menuitem");
        this.item.setAttribute("aria-checked", "");
      }
    }
    getMnemonic() {
      return this.mnemonic;
    }
    applyStyle() {
      const isSelected = this.element && this.element.classList.contains("focused");
      const fgColor = isSelected && this.menuStyle.selectionForegroundColor ? this.menuStyle.selectionForegroundColor : this.menuStyle.foregroundColor;
      const bgColor = isSelected && this.menuStyle.selectionBackgroundColor ? this.menuStyle.selectionBackgroundColor : void 0;
      const outline = isSelected && this.menuStyle.selectionBorderColor ? `1px solid ${this.menuStyle.selectionBorderColor}` : "";
      const outlineOffset = isSelected && this.menuStyle.selectionBorderColor ? `-1px` : "";
      if (this.item) {
        this.item.style.color = fgColor ?? "";
        this.item.style.backgroundColor = bgColor ?? "";
        this.item.style.outline = outline;
        this.item.style.outlineOffset = outlineOffset;
      }
      if (this.check) {
        this.check.style.color = fgColor ?? "";
      }
    }
  }
  class SubmenuMenuActionViewItem extends BaseMenuActionViewItem {
    constructor(action, submenuActions, parentData, submenuOptions, menuStyles) {
      super(action, action, submenuOptions, menuStyles);
      this.submenuActions = submenuActions;
      this.parentData = parentData;
      this.submenuOptions = submenuOptions;
      this.mysubmenu = null;
      this.submenuDisposables = this._register(new DisposableStore());
      this.mouseOver = false;
      this.expandDirection = submenuOptions && submenuOptions.expandDirection !== void 0 ? submenuOptions.expandDirection : { horizontal: HorizontalDirection.Right, vertical: VerticalDirection.Below };
      this.showScheduler = new RunOnceScheduler(() => {
        if (this.mouseOver) {
          this.cleanupExistingSubmenu(false);
          this.createSubmenu(false);
        }
      }, 250);
      this.hideScheduler = new RunOnceScheduler(() => {
        if (this.element && (!isAncestor$1(getActiveElement(), this.element) && this.parentData.submenu === this.mysubmenu)) {
          this.parentData.parent.focus(false);
          this.cleanupExistingSubmenu(true);
        }
      }, 750);
    }
    render(container) {
      super.render(container);
      if (!this.element) {
        return;
      }
      if (this.item) {
        this.item.classList.add("monaco-submenu-item");
        this.item.tabIndex = 0;
        this.item.setAttribute("aria-haspopup", "true");
        this.updateAriaExpanded("false");
        this.submenuIndicator = append$2(this.item, $$l("span.submenu-indicator" + ThemeIcon.asCSSSelector(Codicon.menuSubmenu)));
        this.submenuIndicator.setAttribute("aria-hidden", "true");
      }
      this._register(addDisposableListener(this.element, EventType$1.KEY_UP, (e) => {
        const event = new StandardKeyboardEvent(e);
        if (event.equals(
          17
          /* KeyCode.RightArrow */
        ) || event.equals(
          3
          /* KeyCode.Enter */
        )) {
          EventHelper.stop(e, true);
          this.createSubmenu(true);
        }
      }));
      this._register(addDisposableListener(this.element, EventType$1.KEY_DOWN, (e) => {
        const event = new StandardKeyboardEvent(e);
        if (getActiveElement() === this.item) {
          if (event.equals(
            17
            /* KeyCode.RightArrow */
          ) || event.equals(
            3
            /* KeyCode.Enter */
          )) {
            EventHelper.stop(e, true);
          }
        }
      }));
      this._register(addDisposableListener(this.element, EventType$1.MOUSE_OVER, (e) => {
        if (!this.mouseOver) {
          this.mouseOver = true;
          this.showScheduler.schedule();
        }
      }));
      this._register(addDisposableListener(this.element, EventType$1.MOUSE_LEAVE, (e) => {
        this.mouseOver = false;
      }));
      this._register(addDisposableListener(this.element, EventType$1.FOCUS_OUT, (e) => {
        if (this.element && !isAncestor$1(getActiveElement(), this.element)) {
          this.hideScheduler.schedule();
        }
      }));
      this._register(this.parentData.parent.onScroll(() => {
        if (this.parentData.submenu === this.mysubmenu) {
          this.parentData.parent.focus(false);
          this.cleanupExistingSubmenu(true);
        }
      }));
    }
    updateEnabled() {
    }
    onClick(e) {
      EventHelper.stop(e, true);
      this.cleanupExistingSubmenu(false);
      this.createSubmenu(true);
    }
    cleanupExistingSubmenu(force) {
      if (this.parentData.submenu && (force || this.parentData.submenu !== this.mysubmenu)) {
        try {
          this.parentData.submenu.dispose();
        } catch {
        }
        this.parentData.submenu = void 0;
        this.updateAriaExpanded("false");
        if (this.submenuContainer) {
          this.submenuDisposables.clear();
          this.submenuContainer = void 0;
        }
      }
    }
    calculateSubmenuMenuLayout(windowDimensions, submenu, entry, expandDirection) {
      const ret = { top: 0, left: 0 };
      ret.left = layout(windowDimensions.width, submenu.width, { position: expandDirection.horizontal === HorizontalDirection.Right ? 0 : 1, offset: entry.left, size: entry.width });
      if (ret.left >= entry.left && ret.left < entry.left + entry.width) {
        if (entry.left + 10 + submenu.width <= windowDimensions.width) {
          ret.left = entry.left + 10;
        }
        entry.top += 10;
        entry.height = 0;
      }
      ret.top = layout(windowDimensions.height, submenu.height, { position: 0, offset: entry.top, size: 0 });
      if (ret.top + submenu.height === entry.top && ret.top + entry.height + submenu.height <= windowDimensions.height) {
        ret.top += entry.height;
      }
      return ret;
    }
    createSubmenu(selectFirstItem = true) {
      if (!this.element) {
        return;
      }
      if (!this.parentData.submenu) {
        this.updateAriaExpanded("true");
        this.submenuContainer = append$2(this.element, $$l("div.monaco-submenu"));
        this.submenuContainer.classList.add("menubar-menu-items-holder", "context-view");
        const computedStyles = getWindow(this.parentData.parent.domNode).getComputedStyle(this.parentData.parent.domNode);
        const paddingTop = parseFloat(computedStyles.paddingTop || "0") || 0;
        this.submenuContainer.style.position = "fixed";
        this.submenuContainer.style.top = "0";
        this.submenuContainer.style.left = "0";
        this.submenuContainer.style.zIndex = "1";
        this.parentData.submenu = new Menu(this.submenuContainer, this.submenuActions.length ? this.submenuActions : [new EmptySubmenuAction()], this.submenuOptions, this.menuStyle);
        const entryBox = this.element.getBoundingClientRect();
        const entryBoxUpdated = {
          top: entryBox.top - paddingTop,
          left: entryBox.left,
          height: entryBox.height + 2 * paddingTop,
          width: entryBox.width
        };
        const viewBox = this.submenuContainer.getBoundingClientRect();
        const window2 = getWindow(this.element);
        const { top, left } = this.calculateSubmenuMenuLayout(new Dimension(window2.innerWidth, window2.innerHeight), Dimension.lift(viewBox), entryBoxUpdated, this.expandDirection);
        this.submenuContainer.style.left = `${left - viewBox.left}px`;
        this.submenuContainer.style.top = `${top - viewBox.top}px`;
        this.submenuDisposables.add(addDisposableListener(this.submenuContainer, EventType$1.KEY_UP, (e) => {
          const event = new StandardKeyboardEvent(e);
          if (event.equals(
            15
            /* KeyCode.LeftArrow */
          )) {
            EventHelper.stop(e, true);
            this.parentData.parent.focus();
            this.cleanupExistingSubmenu(true);
          }
        }));
        this.submenuDisposables.add(addDisposableListener(this.submenuContainer, EventType$1.KEY_DOWN, (e) => {
          const event = new StandardKeyboardEvent(e);
          if (event.equals(
            15
            /* KeyCode.LeftArrow */
          )) {
            EventHelper.stop(e, true);
          }
        }));
        this.submenuDisposables.add(this.parentData.submenu.onDidCancel(() => {
          this.parentData.parent.focus();
          this.cleanupExistingSubmenu(true);
        }));
        this.parentData.submenu.focus(selectFirstItem);
        this.mysubmenu = this.parentData.submenu;
      } else {
        this.parentData.submenu.focus(false);
      }
    }
    updateAriaExpanded(value) {
      if (this.item) {
        this.item?.setAttribute("aria-expanded", value);
      }
    }
    applyStyle() {
      super.applyStyle();
      const isSelected = this.element && this.element.classList.contains("focused");
      const fgColor = isSelected && this.menuStyle.selectionForegroundColor ? this.menuStyle.selectionForegroundColor : this.menuStyle.foregroundColor;
      if (this.submenuIndicator) {
        this.submenuIndicator.style.color = fgColor ?? "";
      }
    }
    dispose() {
      super.dispose();
      this.hideScheduler.dispose();
      if (this.mysubmenu) {
        this.mysubmenu.dispose();
        this.mysubmenu = null;
      }
      if (this.submenuContainer) {
        this.submenuContainer = void 0;
      }
    }
  }
  class MenuSeparatorActionViewItem extends ActionViewItem {
    constructor(context, action, options, menuStyles) {
      super(context, action, options);
      this.menuStyles = menuStyles;
    }
    render(container) {
      super.render(container);
      if (this.label) {
        this.label.style.borderBottomColor = this.menuStyles.separatorColor ? `${this.menuStyles.separatorColor}` : "";
      }
    }
  }
  function cleanMnemonic(label) {
    const regex = MENU_MNEMONIC_REGEX;
    const matches = regex.exec(label);
    if (!matches) {
      return label;
    }
    const mnemonicInText = !matches[1];
    return label.replace(regex, mnemonicInText ? "$2$3" : "").trim();
  }
  function formatRule(c) {
    const fontCharacter = getCodiconFontCharacters()[c.id];
    return `.codicon-${c.id}:before { content: '\\${fontCharacter.toString(16)}'; }`;
  }
  function getMenuWidgetCSS(style, isForShadowDom) {
    let result = (
      /* css */
      `
.monaco-menu {
	font-size: 13px;
	border-radius: 5px;
	min-width: 160px;
}

${formatRule(Codicon.menuSelection)}
${formatRule(Codicon.menuSubmenu)}

.monaco-menu .monaco-action-bar {
	text-align: right;
	overflow: hidden;
	white-space: nowrap;
}

.monaco-menu .monaco-action-bar .actions-container {
	display: flex;
	margin: 0 auto;
	padding: 0;
	width: 100%;
	justify-content: flex-end;
}

.monaco-menu .monaco-action-bar.vertical .actions-container {
	display: inline-block;
}

.monaco-menu .monaco-action-bar.reverse .actions-container {
	flex-direction: row-reverse;
}

.monaco-menu .monaco-action-bar .action-item {
	cursor: pointer;
	display: inline-block;
	transition: transform 50ms ease;
	position: relative;  /* DO NOT REMOVE - this is the key to preventing the ghosting icon bug in Chrome 42 */
}

.monaco-menu .monaco-action-bar .action-item.disabled {
	cursor: default;
}

.monaco-menu .monaco-action-bar .action-item .icon,
.monaco-menu .monaco-action-bar .action-item .codicon {
	display: inline-block;
}

.monaco-menu .monaco-action-bar .action-item .codicon {
	display: flex;
	align-items: center;
}

.monaco-menu .monaco-action-bar .action-label {
	font-size: 11px;
	margin-right: 4px;
}

.monaco-menu .monaco-action-bar .action-item.disabled .action-label,
.monaco-menu .monaco-action-bar .action-item.disabled .action-label:hover {
	color: var(--vscode-disabledForeground);
}

/* Vertical actions */

.monaco-menu .monaco-action-bar.vertical {
	text-align: left;
}

.monaco-menu .monaco-action-bar.vertical .action-item {
	display: block;
}

.monaco-menu .monaco-action-bar.vertical .action-label.separator {
	display: block;
	border-bottom: 1px solid var(--vscode-menu-separatorBackground);
	padding-top: 1px;
	padding: 30px;
}

.monaco-menu .secondary-actions .monaco-action-bar .action-label {
	margin-left: 6px;
}

/* Action Items */
.monaco-menu .monaco-action-bar .action-item.select-container {
	overflow: hidden; /* somehow the dropdown overflows its container, we prevent it here to not push */
	flex: 1;
	max-width: 170px;
	min-width: 60px;
	display: flex;
	align-items: center;
	justify-content: center;
	margin-right: 10px;
}

.monaco-menu .monaco-action-bar.vertical {
	margin-left: 0;
	overflow: visible;
}

.monaco-menu .monaco-action-bar.vertical .actions-container {
	display: block;
}

.monaco-menu .monaco-action-bar.vertical .action-item {
	padding: 0;
	transform: none;
	display: flex;
}

.monaco-menu .monaco-action-bar.vertical .action-item.active {
	transform: none;
}

.monaco-menu .monaco-action-bar.vertical .action-menu-item {
	flex: 1 1 auto;
	display: flex;
	height: 2em;
	align-items: center;
	position: relative;
	margin: 0 4px;
	border-radius: 4px;
}

.monaco-menu .monaco-action-bar.vertical .action-menu-item:hover .keybinding,
.monaco-menu .monaco-action-bar.vertical .action-menu-item:focus .keybinding {
	opacity: unset;
}

.monaco-menu .monaco-action-bar.vertical .action-label {
	flex: 1 1 auto;
	text-decoration: none;
	padding: 0 1em;
	background: none;
	font-size: 12px;
	line-height: 1;
}

.monaco-menu .monaco-action-bar.vertical .keybinding,
.monaco-menu .monaco-action-bar.vertical .submenu-indicator {
	display: inline-block;
	flex: 2 1 auto;
	padding: 0 1em;
	text-align: right;
	font-size: 12px;
	line-height: 1;
	opacity: 0.7;
}

.monaco-menu .monaco-action-bar.vertical .submenu-indicator {
	height: 100%;
}

.monaco-menu .monaco-action-bar.vertical .submenu-indicator.codicon {
	font-size: 16px !important;
	display: flex;
	align-items: center;
}

.monaco-menu .monaco-action-bar.vertical .submenu-indicator.codicon::before {
	margin-left: auto;
	margin-right: -20px;
}

.monaco-menu .monaco-action-bar.vertical .action-item.disabled .keybinding,
.monaco-menu .monaco-action-bar.vertical .action-item.disabled .submenu-indicator {
	opacity: 0.4;
}

.monaco-menu .monaco-action-bar.vertical .action-label:not(.separator) {
	display: inline-block;
	box-sizing: border-box;
	margin: 0;
}

.monaco-menu .monaco-action-bar.vertical .action-item {
	position: static;
	overflow: visible;
}

.monaco-menu .monaco-action-bar.vertical .action-item .monaco-submenu {
	position: absolute;
}

.monaco-menu .monaco-action-bar.vertical .action-label.separator {
	width: 100%;
	height: 0px !important;
	opacity: 1;
}

.monaco-menu .monaco-action-bar.vertical .action-label.separator.text {
	padding: 0.7em 1em 0.1em 1em;
	font-weight: bold;
	opacity: 1;
}

.monaco-menu .monaco-action-bar.vertical .action-label:hover {
	color: inherit;
}

.monaco-menu .monaco-action-bar.vertical .menu-item-check {
	position: absolute;
	visibility: hidden;
	width: 1em;
	height: 100%;
}

.monaco-menu .monaco-action-bar.vertical .action-menu-item.checked .menu-item-check {
	visibility: visible;
	display: flex;
	align-items: center;
	justify-content: center;
}

/* Context Menu */

.context-view.monaco-menu-container {
	outline: 0;
	border: none;
	animation: fadeIn 0.083s linear;
	-webkit-app-region: no-drag;
}

.context-view.monaco-menu-container :focus,
.context-view.monaco-menu-container .monaco-action-bar.vertical:focus,
.context-view.monaco-menu-container .monaco-action-bar.vertical :focus {
	outline: 0;
}

.hc-black .context-view.monaco-menu-container,
.hc-light .context-view.monaco-menu-container,
:host-context(.hc-black) .context-view.monaco-menu-container,
:host-context(.hc-light) .context-view.monaco-menu-container {
	box-shadow: none;
}

.hc-black .monaco-menu .monaco-action-bar.vertical .action-item.focused,
.hc-light .monaco-menu .monaco-action-bar.vertical .action-item.focused,
:host-context(.hc-black) .monaco-menu .monaco-action-bar.vertical .action-item.focused,
:host-context(.hc-light) .monaco-menu .monaco-action-bar.vertical .action-item.focused {
	background: none;
}

/* Vertical Action Bar Styles */

.monaco-menu .monaco-action-bar.vertical {
	padding: 4px 0;
}

.monaco-menu .monaco-action-bar.vertical .action-menu-item {
	height: 2em;
}

.monaco-menu .monaco-action-bar.vertical .action-label:not(.separator),
.monaco-menu .monaco-action-bar.vertical .keybinding {
	font-size: inherit;
	padding: 0 2em;
	max-height: 100%;
}

.monaco-menu .monaco-action-bar.vertical .menu-item-check {
	font-size: inherit;
	width: 2em;
}

.monaco-menu .monaco-action-bar.vertical .action-label.separator {
	font-size: inherit;
	margin: 5px 0 !important;
	padding: 0;
	border-radius: 0;
}

.linux .monaco-menu .monaco-action-bar.vertical .action-label.separator,
:host-context(.linux) .monaco-menu .monaco-action-bar.vertical .action-label.separator {
	margin-left: 0;
	margin-right: 0;
}

.monaco-menu .monaco-action-bar.vertical .submenu-indicator {
	font-size: 60%;
	padding: 0 1.8em;
}

.linux .monaco-menu .monaco-action-bar.vertical .submenu-indicator,
:host-context(.linux) .monaco-menu .monaco-action-bar.vertical .submenu-indicator {
	height: 100%;
	mask-size: 10px 10px;
	-webkit-mask-size: 10px 10px;
}

.monaco-menu .action-item {
	cursor: default;
}`
    );
    if (isForShadowDom) {
      result += `
			/* Arrows */
			.monaco-scrollable-element > .scrollbar > .scra {
				cursor: pointer;
				font-size: 11px !important;
			}

			.monaco-scrollable-element > .visible {
				opacity: 1;

				/* Background rule added for IE9 - to allow clicks on dom node */
				background:rgba(0,0,0,0);

				transition: opacity 100ms linear;
			}
			.monaco-scrollable-element > .invisible {
				opacity: 0;
				pointer-events: none;
			}
			.monaco-scrollable-element > .invisible.fade {
				transition: opacity 800ms linear;
			}

			/* Scrollable Content Inset Shadow */
			.monaco-scrollable-element > .shadow {
				position: absolute;
				display: none;
			}
			.monaco-scrollable-element > .shadow.top {
				display: block;
				top: 0;
				left: 3px;
				height: 3px;
				width: 100%;
			}
			.monaco-scrollable-element > .shadow.left {
				display: block;
				top: 3px;
				left: 0;
				height: 100%;
				width: 3px;
			}
			.monaco-scrollable-element > .shadow.top-left-corner {
				display: block;
				top: 0;
				left: 0;
				height: 3px;
				width: 3px;
			}
			/* Fix for https://github.com/microsoft/vscode/issues/103170 */
			.monaco-menu .action-item .monaco-submenu {
				z-index: 1;
			}
		`;
      const scrollbarShadowColor = style.scrollbarShadow;
      if (scrollbarShadowColor) {
        result += `
				.monaco-scrollable-element > .shadow.top {
					box-shadow: ${scrollbarShadowColor} 0 6px 6px -6px inset;
				}

				.monaco-scrollable-element > .shadow.left {
					box-shadow: ${scrollbarShadowColor} 6px 0 6px -6px inset;
				}

				.monaco-scrollable-element > .shadow.top.left {
					box-shadow: ${scrollbarShadowColor} 6px 6px 6px -6px inset;
				}
			`;
      }
      const scrollbarSliderBackgroundColor = style.scrollbarSliderBackground;
      if (scrollbarSliderBackgroundColor) {
        result += `
				.monaco-scrollable-element > .scrollbar > .slider {
					background: ${scrollbarSliderBackgroundColor};
				}
			`;
      }
      const scrollbarSliderHoverBackgroundColor = style.scrollbarSliderHoverBackground;
      if (scrollbarSliderHoverBackgroundColor) {
        result += `
				.monaco-scrollable-element > .scrollbar > .slider:hover {
					background: ${scrollbarSliderHoverBackgroundColor};
				}
			`;
      }
      const scrollbarSliderActiveBackgroundColor = style.scrollbarSliderActiveBackground;
      if (scrollbarSliderActiveBackgroundColor) {
        result += `
				.monaco-scrollable-element > .scrollbar > .slider.active {
					background: ${scrollbarSliderActiveBackgroundColor};
				}
			`;
      }
    }
    return result;
  }
  class ContextMenuHandler {
    constructor(contextViewService, telemetryService, notificationService, keybindingService) {
      this.contextViewService = contextViewService;
      this.telemetryService = telemetryService;
      this.notificationService = notificationService;
      this.keybindingService = keybindingService;
      this.focusToReturn = null;
      this.lastContainer = null;
      this.block = null;
      this.blockDisposable = null;
      this.options = { blockMouse: true };
    }
    configure(options) {
      this.options = options;
    }
    showContextMenu(delegate) {
      const actions = delegate.getActions();
      if (!actions.length) {
        return;
      }
      this.focusToReturn = getActiveElement();
      let menu;
      const shadowRootElement = isHTMLElement(delegate.domForShadowRoot) ? delegate.domForShadowRoot : void 0;
      this.contextViewService.showContextView({
        getAnchor: () => delegate.getAnchor(),
        canRelayout: false,
        anchorAlignment: delegate.anchorAlignment,
        anchorAxisAlignment: delegate.anchorAxisAlignment,
        layer: delegate.layer,
        render: (container) => {
          this.lastContainer = container;
          const className2 = delegate.getMenuClassName ? delegate.getMenuClassName() : "";
          if (className2) {
            container.className += " " + className2;
          }
          if (this.options.blockMouse) {
            this.block = container.appendChild($$l(".context-view-block"));
            this.block.style.position = "fixed";
            this.block.style.cursor = "initial";
            this.block.style.left = "0";
            this.block.style.top = "0";
            this.block.style.width = "100%";
            this.block.style.height = "100%";
            this.block.style.zIndex = "-1";
            this.blockDisposable?.dispose();
            this.blockDisposable = addDisposableListener(this.block, EventType$1.MOUSE_DOWN, (e) => e.stopPropagation());
          }
          const menuDisposables = new DisposableStore();
          const actionRunner = delegate.actionRunner || menuDisposables.add(new ActionRunner());
          actionRunner.onWillRun((evt) => this.onActionRun(evt, !delegate.skipTelemetry), this, menuDisposables);
          actionRunner.onDidRun(this.onDidActionRun, this, menuDisposables);
          menu = new Menu(container, actions, {
            actionViewItemProvider: delegate.getActionViewItem,
            context: delegate.getActionsContext ? delegate.getActionsContext() : null,
            actionRunner,
            getKeyBinding: delegate.getKeyBinding ? delegate.getKeyBinding : (action) => this.keybindingService.lookupKeybinding(action.id)
          }, defaultMenuStyles);
          menu.onDidCancel(() => this.contextViewService.hideContextView(true), null, menuDisposables);
          menu.onDidBlur(() => this.contextViewService.hideContextView(true), null, menuDisposables);
          const targetWindow = getWindow(container);
          menuDisposables.add(addDisposableListener(targetWindow, EventType$1.BLUR, () => this.contextViewService.hideContextView(true)));
          menuDisposables.add(addDisposableListener(targetWindow, EventType$1.MOUSE_DOWN, (e) => {
            if (e.defaultPrevented) {
              return;
            }
            const event = new StandardMouseEvent(targetWindow, e);
            let element = event.target;
            if (event.rightButton) {
              return;
            }
            while (element) {
              if (element === container) {
                return;
              }
              element = element.parentElement;
            }
            this.contextViewService.hideContextView(true);
          }));
          return combinedDisposable(menuDisposables, menu);
        },
        focus: () => {
          menu?.focus(!!delegate.autoSelectFirstItem);
        },
        onHide: (didCancel) => {
          delegate.onHide?.(!!didCancel);
          if (this.block) {
            this.block.remove();
            this.block = null;
          }
          this.blockDisposable?.dispose();
          this.blockDisposable = null;
          if (!!this.lastContainer && (getActiveElement() === this.lastContainer || isAncestor$1(getActiveElement(), this.lastContainer))) {
            this.focusToReturn?.focus();
          }
          this.lastContainer = null;
        }
      }, shadowRootElement, !!shadowRootElement);
    }
    onActionRun(e, logTelemetry) {
      if (logTelemetry) {
        this.telemetryService.publicLog2("workbenchActionExecuted", { id: e.action.id, from: "contextMenu" });
      }
      this.contextViewService.hideContextView(false);
    }
    onDidActionRun(e) {
      if (e.error && !isCancellationError(e.error)) {
        this.notificationService.error(e.error);
      }
    }
  }
  var __decorate$l = 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$k = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  let ContextMenuService = class ContextMenuService extends Disposable {
    get contextMenuHandler() {
      if (!this._contextMenuHandler) {
        this._contextMenuHandler = new ContextMenuHandler(this.contextViewService, this.telemetryService, this.notificationService, this.keybindingService);
      }
      return this._contextMenuHandler;
    }
    constructor(telemetryService, notificationService, contextViewService, keybindingService, menuService, contextKeyService) {
      super();
      this.telemetryService = telemetryService;
      this.notificationService = notificationService;
      this.contextViewService = contextViewService;
      this.keybindingService = keybindingService;
      this.menuService = menuService;
      this.contextKeyService = contextKeyService;
      this._contextMenuHandler = void 0;
      this._onDidShowContextMenu = this._store.add(new Emitter$1());
      this.onDidShowContextMenu = this._onDidShowContextMenu.event;
      this._onDidHideContextMenu = this._store.add(new Emitter$1());
      this.onDidHideContextMenu = this._onDidHideContextMenu.event;
    }
    configure(options) {
      this.contextMenuHandler.configure(options);
    }
    // ContextMenu
    showContextMenu(delegate) {
      delegate = ContextMenuMenuDelegate.transform(delegate, this.menuService, this.contextKeyService);
      this.contextMenuHandler.showContextMenu({
        ...delegate,
        onHide: (didCancel) => {
          delegate.onHide?.(didCancel);
          this._onDidHideContextMenu.fire();
        }
      });
      ModifierKeyEmitter.getInstance().resetKeyStatus();
      this._onDidShowContextMenu.fire();
    }
  };
  ContextMenuService = __decorate$l([
    __param$k(0, ITelemetryService),
    __param$k(1, INotificationService),
    __param$k(2, IContextViewService),
    __param$k(3, IKeybindingService),
    __param$k(4, IMenuService),
    __param$k(5, IContextKeyService)
  ], ContextMenuService);
  var ContextMenuMenuDelegate;
  (function(ContextMenuMenuDelegate2) {
    function is(thing) {
      return thing && thing.menuId instanceof MenuId;
    }
    function transform(delegate, menuService, globalContextKeyService) {
      if (!is(delegate)) {
        return delegate;
      }
      const { menuId, menuActionOptions, contextKeyService } = delegate;
      return {
        ...delegate,
        getActions: () => {
          let target = [];
          if (menuId) {
            const menu = menuService.getMenuActions(menuId, contextKeyService ?? globalContextKeyService, menuActionOptions);
            target = getFlatContextMenuActions(menu);
          }
          if (!delegate.getActions) {
            return target;
          } else {
            return Separator.join(delegate.getActions(), target);
          }
        }
      };
    }
    ContextMenuMenuDelegate2.transform = transform;
  })(ContextMenuMenuDelegate || (ContextMenuMenuDelegate = {}));
  var EditorOpenSource;
  (function(EditorOpenSource2) {
    EditorOpenSource2[EditorOpenSource2["API"] = 0] = "API";
    EditorOpenSource2[EditorOpenSource2["USER"] = 1] = "USER";
  })(EditorOpenSource || (EditorOpenSource = {}));
  var __decorate$k = 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$j = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  let CommandOpener = class CommandOpener {
    constructor(_commandService) {
      this._commandService = _commandService;
    }
    async open(target, options) {
      if (!matchesScheme(target, Schemas.command)) {
        return false;
      }
      if (!options?.allowCommands) {
        return true;
      }
      if (typeof target === "string") {
        target = URI.parse(target);
      }
      if (Array.isArray(options.allowCommands)) {
        if (!options.allowCommands.includes(target.path)) {
          return true;
        }
      }
      let args = [];
      try {
        args = parse$1(decodeURIComponent(target.query));
      } catch {
        try {
          args = parse$1(target.query);
        } catch {
        }
      }
      if (!Array.isArray(args)) {
        args = [args];
      }
      await this._commandService.executeCommand(target.path, ...args);
      return true;
    }
  };
  CommandOpener = __decorate$k([
    __param$j(0, ICommandService)
  ], CommandOpener);
  let EditorOpener = class EditorOpener {
    constructor(_editorService) {
      this._editorService = _editorService;
    }
    async open(target, options) {
      if (typeof target === "string") {
        target = URI.parse(target);
      }
      const { selection, uri } = extractSelection(target);
      target = uri;
      if (target.scheme === Schemas.file) {
        target = normalizePath(target);
      }
      await this._editorService.openCodeEditor({
        resource: target,
        options: {
          selection,
          source: options?.fromUserGesture ? EditorOpenSource.USER : EditorOpenSource.API,
          ...options?.editorOptions
        }
      }, this._editorService.getFocusedCodeEditor(), options?.openToSide);
      return true;
    }
  };
  EditorOpener = __decorate$k([
    __param$j(0, ICodeEditorService)
  ], EditorOpener);
  let OpenerService = class OpenerService {
    constructor(editorService, commandService) {
      this._openers = new LinkedList();
      this._validators = new LinkedList();
      this._resolvers = new LinkedList();
      this._resolvedUriTargets = new ResourceMap((uri) => uri.with({ path: null, fragment: null, query: null }).toString());
      this._externalOpeners = new LinkedList();
      this._defaultExternalOpener = {
        openExternal: async (href) => {
          if (matchesSomeScheme(href, Schemas.http, Schemas.https)) {
            windowOpenNoOpener(href);
          } else {
            mainWindow.location.href = href;
          }
          return true;
        }
      };
      this._openers.push({
        open: async (target, options) => {
          if (options?.openExternal || matchesSomeScheme(target, Schemas.mailto, Schemas.http, Schemas.https, Schemas.vsls)) {
            await this._doOpenExternal(target, options);
            return true;
          }
          return false;
        }
      });
      this._openers.push(new CommandOpener(commandService));
      this._openers.push(new EditorOpener(editorService));
    }
    registerOpener(opener) {
      const remove = this._openers.unshift(opener);
      return { dispose: remove };
    }
    async open(target, options) {
      if (!options?.skipValidation) {
        const targetURI = typeof target === "string" ? URI.parse(target) : target;
        const validationTarget = this._resolvedUriTargets.get(targetURI) ?? target;
        for (const validator of this._validators) {
          if (!await validator.shouldOpen(validationTarget, options)) {
            return false;
          }
        }
      }
      for (const opener of this._openers) {
        const handled = await opener.open(target, options);
        if (handled) {
          return true;
        }
      }
      return false;
    }
    async resolveExternalUri(resource, options) {
      for (const resolver of this._resolvers) {
        try {
          const result = await resolver.resolveExternalUri(resource, options);
          if (result) {
            if (!this._resolvedUriTargets.has(result.resolved)) {
              this._resolvedUriTargets.set(result.resolved, resource);
            }
            return result;
          }
        } catch {
        }
      }
      throw new Error("Could not resolve external URI: " + resource.toString());
    }
    async _doOpenExternal(resource, options) {
      const uri = typeof resource === "string" ? URI.parse(resource) : resource;
      let externalUri;
      try {
        externalUri = (await this.resolveExternalUri(uri, options)).resolved;
      } catch {
        externalUri = uri;
      }
      let href;
      if (typeof resource === "string" && uri.toString() === externalUri.toString()) {
        href = resource;
      } else {
        href = encodeURI(externalUri.toString(true));
      }
      if (options?.allowContributedOpeners) {
        const preferredOpenerId = typeof options?.allowContributedOpeners === "string" ? options?.allowContributedOpeners : void 0;
        for (const opener of this._externalOpeners) {
          const didOpen = await opener.openExternal(href, {
            sourceUri: uri,
            preferredOpenerId
          }, CancellationToken.None);
          if (didOpen) {
            return true;
          }
        }
      }
      return this._defaultExternalOpener.openExternal(href, { sourceUri: uri }, CancellationToken.None);
    }
    dispose() {
      this._validators.clear();
    }
  };
  OpenerService = __decorate$k([
    __param$j(0, ICodeEditorService),
    __param$j(1, ICommandService)
  ], OpenerService);
  var __decorate$j = 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$i = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  let MarkerDecorationsService = class MarkerDecorationsService extends Disposable {
    constructor(modelService, _markerService) {
      super();
      this._markerService = _markerService;
      this._onDidChangeMarker = this._register(new Emitter$1());
      this._suppressedRanges = new ResourceMap();
      this._markerDecorations = new ResourceMap();
      modelService.getModels().forEach((model) => this._onModelAdded(model));
      this._register(modelService.onModelAdded(this._onModelAdded, this));
      this._register(modelService.onModelRemoved(this._onModelRemoved, this));
      this._register(this._markerService.onMarkerChanged(this._handleMarkerChange, this));
    }
    dispose() {
      super.dispose();
      this._markerDecorations.forEach((value) => value.dispose());
      this._markerDecorations.clear();
    }
    getMarker(uri, decoration2) {
      const markerDecorations = this._markerDecorations.get(uri);
      return markerDecorations ? markerDecorations.getMarker(decoration2) || null : null;
    }
    _handleMarkerChange(changedResources) {
      changedResources.forEach((resource) => {
        const markerDecorations = this._markerDecorations.get(resource);
        if (markerDecorations) {
          this._updateDecorations(markerDecorations);
        }
      });
    }
    _onModelAdded(model) {
      const markerDecorations = new MarkerDecorations(model);
      this._markerDecorations.set(model.uri, markerDecorations);
      this._updateDecorations(markerDecorations);
    }
    _onModelRemoved(model) {
      const markerDecorations = this._markerDecorations.get(model.uri);
      if (markerDecorations) {
        markerDecorations.dispose();
        this._markerDecorations.delete(model.uri);
      }
      if (model.uri.scheme === Schemas.inMemory || model.uri.scheme === Schemas.internal || model.uri.scheme === Schemas.vscode) {
        this._markerService?.read({ resource: model.uri }).map((marker) => marker.owner).forEach((owner) => this._markerService.remove(owner, [model.uri]));
      }
    }
    _updateDecorations(markerDecorations) {
      let markers = this._markerService.read({ resource: markerDecorations.model.uri, take: 500 });
      const suppressedRanges = this._suppressedRanges.get(markerDecorations.model.uri);
      if (suppressedRanges) {
        markers = markers.filter((marker) => {
          return !Iterable.some(suppressedRanges, (candidate) => Range$2.areIntersectingOrTouching(candidate, marker));
        });
      }
      if (markerDecorations.update(markers)) {
        this._onDidChangeMarker.fire(markerDecorations.model);
      }
    }
  };
  MarkerDecorationsService = __decorate$j([
    __param$i(0, IModelService),
    __param$i(1, IMarkerService)
  ], MarkerDecorationsService);
  class MarkerDecorations extends Disposable {
    constructor(model) {
      super();
      this.model = model;
      this._map = new BidirectionalMap();
      this._register(toDisposable(() => {
        this.model.deltaDecorations([...this._map.values()], []);
        this._map.clear();
      }));
    }
    update(markers) {
      const { added, removed } = diffSets(new Set(this._map.keys()), new Set(markers));
      if (added.length === 0 && removed.length === 0) {
        return false;
      }
      const oldIds = removed.map((marker) => this._map.get(marker));
      const newDecorations = added.map((marker) => {
        return {
          range: this._createDecorationRange(this.model, marker),
          options: this._createDecorationOption(marker)
        };
      });
      const ids = this.model.deltaDecorations(oldIds, newDecorations);
      for (const removedMarker of removed) {
        this._map.delete(removedMarker);
      }
      for (let index = 0; index < ids.length; index++) {
        this._map.set(added[index], ids[index]);
      }
      return true;
    }
    getMarker(decoration2) {
      return this._map.getKey(decoration2.id);
    }
    _createDecorationRange(model, rawMarker) {
      let ret = Range$2.lift(rawMarker);
      if (rawMarker.severity === MarkerSeverity$2.Hint && !this._hasMarkerTag(
        rawMarker,
        1
        /* MarkerTag.Unnecessary */
      ) && !this._hasMarkerTag(
        rawMarker,
        2
        /* MarkerTag.Deprecated */
      )) {
        ret = ret.setEndPosition(ret.startLineNumber, ret.startColumn + 2);
      }
      ret = model.validateRange(ret);
      if (ret.isEmpty()) {
        const maxColumn = model.getLineLastNonWhitespaceColumn(ret.startLineNumber) || model.getLineMaxColumn(ret.startLineNumber);
        if (maxColumn === 1 || ret.endColumn >= maxColumn) {
          return ret;
        }
        const word = model.getWordAtPosition(ret.getStartPosition());
        if (word) {
          ret = new Range$2(ret.startLineNumber, word.startColumn, ret.endLineNumber, word.endColumn);
        }
      } else if (rawMarker.endColumn === Number.MAX_VALUE && rawMarker.startColumn === 1 && ret.startLineNumber === ret.endLineNumber) {
        const minColumn = model.getLineFirstNonWhitespaceColumn(rawMarker.startLineNumber);
        if (minColumn < ret.endColumn) {
          ret = new Range$2(ret.startLineNumber, minColumn, ret.endLineNumber, ret.endColumn);
          rawMarker.startColumn = minColumn;
        }
      }
      return ret;
    }
    _createDecorationOption(marker) {
      let className2;
      let color = void 0;
      let zIndex;
      let inlineClassName = void 0;
      let minimap;
      switch (marker.severity) {
        case MarkerSeverity$2.Hint:
          if (this._hasMarkerTag(
            marker,
            2
            /* MarkerTag.Deprecated */
          )) {
            className2 = void 0;
          } else if (this._hasMarkerTag(
            marker,
            1
            /* MarkerTag.Unnecessary */
          )) {
            className2 = "squiggly-unnecessary";
          } else {
            className2 = "squiggly-hint";
          }
          zIndex = 0;
          break;
        case MarkerSeverity$2.Info:
          className2 = "squiggly-info";
          color = themeColorFromId(overviewRulerInfo);
          zIndex = 10;
          minimap = {
            color: themeColorFromId(minimapInfo),
            position: 1
            /* MinimapPosition.Inline */
          };
          break;
        case MarkerSeverity$2.Warning:
          className2 = "squiggly-warning";
          color = themeColorFromId(overviewRulerWarning);
          zIndex = 20;
          minimap = {
            color: themeColorFromId(minimapWarning),
            position: 1
            /* MinimapPosition.Inline */
          };
          break;
        case MarkerSeverity$2.Error:
        default:
          className2 = "squiggly-error";
          color = themeColorFromId(overviewRulerError);
          zIndex = 30;
          minimap = {
            color: themeColorFromId(minimapError),
            position: 1
            /* MinimapPosition.Inline */
          };
          break;
      }
      if (marker.tags) {
        if (marker.tags.indexOf(
          1
          /* MarkerTag.Unnecessary */
        ) !== -1) {
          inlineClassName = "squiggly-inline-unnecessary";
        }
        if (marker.tags.indexOf(
          2
          /* MarkerTag.Deprecated */
        ) !== -1) {
          inlineClassName = "squiggly-inline-deprecated";
        }
      }
      return {
        description: "marker-decoration",
        stickiness: 1,
        className: className2,
        showIfCollapsed: true,
        overviewRuler: {
          color,
          position: OverviewRulerLane$1.Right
        },
        minimap,
        zIndex,
        inlineClassName
      };
    }
    _hasMarkerTag(marker, tag2) {
      if (marker.tags) {
        return marker.tags.indexOf(tag2) >= 0;
      }
      return false;
    }
  }
  var __decorate$i = 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$h = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  var ModelService_1;
  function MODEL_ID(resource) {
    return resource.toString();
  }
  class ModelData {
    constructor(model, onWillDispose, onDidChangeLanguage) {
      this.model = model;
      this._modelEventListeners = new DisposableStore();
      this.model = model;
      this._modelEventListeners.add(model.onWillDispose(() => onWillDispose(model)));
      this._modelEventListeners.add(model.onDidChangeLanguage((e) => onDidChangeLanguage(model, e)));
    }
    dispose() {
      this._modelEventListeners.dispose();
    }
  }
  const DEFAULT_EOL = isLinux || isMacintosh ? 1 : 2;
  class DisposedModelInfo {
    constructor(uri, initialUndoRedoSnapshot, time, sharesUndoRedoStack, heapSize, sha1, versionId, alternativeVersionId) {
      this.uri = uri;
      this.initialUndoRedoSnapshot = initialUndoRedoSnapshot;
      this.time = time;
      this.sharesUndoRedoStack = sharesUndoRedoStack;
      this.heapSize = heapSize;
      this.sha1 = sha1;
      this.versionId = versionId;
      this.alternativeVersionId = alternativeVersionId;
    }
  }
  let ModelService = (_Na = class extends Disposable {
    constructor(_configurationService, _resourcePropertiesService, _undoRedoService, _instantiationService) {
      super();
      this._configurationService = _configurationService;
      this._resourcePropertiesService = _resourcePropertiesService;
      this._undoRedoService = _undoRedoService;
      this._instantiationService = _instantiationService;
      this._onModelAdded = this._register(new Emitter$1());
      this.onModelAdded = this._onModelAdded.event;
      this._onModelRemoved = this._register(new Emitter$1());
      this.onModelRemoved = this._onModelRemoved.event;
      this._onModelModeChanged = this._register(new Emitter$1());
      this.onModelLanguageChanged = this._onModelModeChanged.event;
      this._modelCreationOptionsByLanguageAndResource = /* @__PURE__ */ Object.create(null);
      this._models = {};
      this._disposedModels = /* @__PURE__ */ new Map();
      this._disposedModelsHeapSize = 0;
      this._register(this._configurationService.onDidChangeConfiguration((e) => this._updateModelOptions(e)));
      this._updateModelOptions(void 0);
    }
    static _readModelOptions(config, isForSimpleWidget) {
      let tabSize = EDITOR_MODEL_DEFAULTS.tabSize;
      if (config.editor && typeof config.editor.tabSize !== "undefined") {
        tabSize = clampedInt(config.editor.tabSize, EDITOR_MODEL_DEFAULTS.tabSize, 1, 100);
      }
      let indentSize = "tabSize";
      if (config.editor && typeof config.editor.indentSize !== "undefined" && config.editor.indentSize !== "tabSize") {
        indentSize = clampedInt(config.editor.indentSize, "tabSize", 1, 100);
      }
      let insertSpaces = EDITOR_MODEL_DEFAULTS.insertSpaces;
      if (config.editor && typeof config.editor.insertSpaces !== "undefined") {
        insertSpaces = config.editor.insertSpaces === "false" ? false : Boolean(config.editor.insertSpaces);
      }
      let newDefaultEOL = DEFAULT_EOL;
      const eol = config.eol;
      if (eol === "\r\n") {
        newDefaultEOL = 2;
      } else if (eol === "\n") {
        newDefaultEOL = 1;
      }
      let trimAutoWhitespace = EDITOR_MODEL_DEFAULTS.trimAutoWhitespace;
      if (config.editor && typeof config.editor.trimAutoWhitespace !== "undefined") {
        trimAutoWhitespace = config.editor.trimAutoWhitespace === "false" ? false : Boolean(config.editor.trimAutoWhitespace);
      }
      let detectIndentation = EDITOR_MODEL_DEFAULTS.detectIndentation;
      if (config.editor && typeof config.editor.detectIndentation !== "undefined") {
        detectIndentation = config.editor.detectIndentation === "false" ? false : Boolean(config.editor.detectIndentation);
      }
      let largeFileOptimizations = EDITOR_MODEL_DEFAULTS.largeFileOptimizations;
      if (config.editor && typeof config.editor.largeFileOptimizations !== "undefined") {
        largeFileOptimizations = config.editor.largeFileOptimizations === "false" ? false : Boolean(config.editor.largeFileOptimizations);
      }
      let bracketPairColorizationOptions = EDITOR_MODEL_DEFAULTS.bracketPairColorizationOptions;
      if (config.editor?.bracketPairColorization && typeof config.editor.bracketPairColorization === "object") {
        const bpConfig = config.editor.bracketPairColorization;
        bracketPairColorizationOptions = {
          enabled: !!bpConfig.enabled,
          independentColorPoolPerBracketType: !!bpConfig.independentColorPoolPerBracketType
        };
      }
      return {
        isForSimpleWidget,
        tabSize,
        indentSize,
        insertSpaces,
        detectIndentation,
        defaultEOL: newDefaultEOL,
        trimAutoWhitespace,
        largeFileOptimizations,
        bracketPairColorizationOptions
      };
    }
    _getEOL(resource, language2) {
      if (resource) {
        return this._resourcePropertiesService.getEOL(resource, language2);
      }
      const eol = this._configurationService.getValue("files.eol", { overrideIdentifier: language2 });
      if (eol && typeof eol === "string" && eol !== "auto") {
        return eol;
      }
      return OS === 3 || OS === 2 ? "\n" : "\r\n";
    }
    _shouldRestoreUndoStack() {
      const result = this._configurationService.getValue("files.restoreUndoStack");
      if (typeof result === "boolean") {
        return result;
      }
      return true;
    }
    getCreationOptions(languageIdOrSelection, resource, isForSimpleWidget) {
      const language2 = typeof languageIdOrSelection === "string" ? languageIdOrSelection : languageIdOrSelection.languageId;
      let creationOptions = this._modelCreationOptionsByLanguageAndResource[language2 + resource];
      if (!creationOptions) {
        const editor2 = this._configurationService.getValue("editor", { overrideIdentifier: language2, resource });
        const eol = this._getEOL(resource, language2);
        creationOptions = ModelService_1._readModelOptions({ editor: editor2, eol }, isForSimpleWidget);
        this._modelCreationOptionsByLanguageAndResource[language2 + resource] = creationOptions;
      }
      return creationOptions;
    }
    _updateModelOptions(e) {
      const oldOptionsByLanguageAndResource = this._modelCreationOptionsByLanguageAndResource;
      this._modelCreationOptionsByLanguageAndResource = /* @__PURE__ */ Object.create(null);
      const keys = Object.keys(this._models);
      for (let i2 = 0, len = keys.length; i2 < len; i2++) {
        const modelId = keys[i2];
        const modelData = this._models[modelId];
        const language2 = modelData.model.getLanguageId();
        const uri = modelData.model.uri;
        if (e && !e.affectsConfiguration("editor", { overrideIdentifier: language2, resource: uri }) && !e.affectsConfiguration("files.eol", { overrideIdentifier: language2, resource: uri })) {
          continue;
        }
        const oldOptions = oldOptionsByLanguageAndResource[language2 + uri];
        const newOptions = this.getCreationOptions(language2, uri, modelData.model.isForSimpleWidget);
        ModelService_1._setModelOptionsForModel(modelData.model, newOptions, oldOptions);
      }
    }
    static _setModelOptionsForModel(model, newOptions, currentOptions) {
      if (currentOptions && currentOptions.defaultEOL !== newOptions.defaultEOL && model.getLineCount() === 1) {
        model.setEOL(
          newOptions.defaultEOL === 1 ? 0 : 1
          /* EndOfLineSequence.CRLF */
        );
      }
      if (currentOptions && currentOptions.detectIndentation === newOptions.detectIndentation && currentOptions.insertSpaces === newOptions.insertSpaces && currentOptions.tabSize === newOptions.tabSize && currentOptions.indentSize === newOptions.indentSize && currentOptions.trimAutoWhitespace === newOptions.trimAutoWhitespace && equals(currentOptions.bracketPairColorizationOptions, newOptions.bracketPairColorizationOptions)) {
        return;
      }
      if (newOptions.detectIndentation) {
        model.detectIndentation(newOptions.insertSpaces, newOptions.tabSize);
        model.updateOptions({
          trimAutoWhitespace: newOptions.trimAutoWhitespace,
          bracketColorizationOptions: newOptions.bracketPairColorizationOptions
        });
      } else {
        model.updateOptions({
          insertSpaces: newOptions.insertSpaces,
          tabSize: newOptions.tabSize,
          indentSize: newOptions.indentSize,
          trimAutoWhitespace: newOptions.trimAutoWhitespace,
          bracketColorizationOptions: newOptions.bracketPairColorizationOptions
        });
      }
    }
    // --- begin IModelService
    _insertDisposedModel(disposedModelData) {
      this._disposedModels.set(MODEL_ID(disposedModelData.uri), disposedModelData);
      this._disposedModelsHeapSize += disposedModelData.heapSize;
    }
    _removeDisposedModel(resource) {
      const disposedModelData = this._disposedModels.get(MODEL_ID(resource));
      if (disposedModelData) {
        this._disposedModelsHeapSize -= disposedModelData.heapSize;
      }
      this._disposedModels.delete(MODEL_ID(resource));
      return disposedModelData;
    }
    _ensureDisposedModelsHeapSize(maxModelsHeapSize) {
      if (this._disposedModelsHeapSize > maxModelsHeapSize) {
        const disposedModels = [];
        this._disposedModels.forEach((entry) => {
          if (!entry.sharesUndoRedoStack) {
            disposedModels.push(entry);
          }
        });
        disposedModels.sort((a, b) => a.time - b.time);
        while (disposedModels.length > 0 && this._disposedModelsHeapSize > maxModelsHeapSize) {
          const disposedModel = disposedModels.shift();
          this._removeDisposedModel(disposedModel.uri);
          if (disposedModel.initialUndoRedoSnapshot !== null) {
            this._undoRedoService.restoreSnapshot(disposedModel.initialUndoRedoSnapshot);
          }
        }
      }
    }
    _createModelData(value, languageIdOrSelection, resource, isForSimpleWidget) {
      const options = this.getCreationOptions(languageIdOrSelection, resource, isForSimpleWidget);
      const model = this._instantiationService.createInstance(TextModel, value, languageIdOrSelection, options, resource);
      if (resource && this._disposedModels.has(MODEL_ID(resource))) {
        const disposedModelData = this._removeDisposedModel(resource);
        const elements = this._undoRedoService.getElements(resource);
        const sha1Computer = this._getSHA1Computer();
        const sha1IsEqual = sha1Computer.canComputeSHA1(model) ? sha1Computer.computeSHA1(model) === disposedModelData.sha1 : false;
        if (sha1IsEqual || disposedModelData.sharesUndoRedoStack) {
          for (const element of elements.past) {
            if (isEditStackElement(element) && element.matchesResource(resource)) {
              element.setModel(model);
            }
          }
          for (const element of elements.future) {
            if (isEditStackElement(element) && element.matchesResource(resource)) {
              element.setModel(model);
            }
          }
          this._undoRedoService.setElementsValidFlag(resource, true, (element) => isEditStackElement(element) && element.matchesResource(resource));
          if (sha1IsEqual) {
            model._overwriteVersionId(disposedModelData.versionId);
            model._overwriteAlternativeVersionId(disposedModelData.alternativeVersionId);
            model._overwriteInitialUndoRedoSnapshot(disposedModelData.initialUndoRedoSnapshot);
          }
        } else {
          if (disposedModelData.initialUndoRedoSnapshot !== null) {
            this._undoRedoService.restoreSnapshot(disposedModelData.initialUndoRedoSnapshot);
          }
        }
      }
      const modelId = MODEL_ID(model.uri);
      if (this._models[modelId]) {
        throw new Error("ModelService: Cannot add model because it already exists!");
      }
      const modelData = new ModelData(model, (model2) => this._onWillDispose(model2), (model2, e) => this._onDidChangeLanguage(model2, e));
      this._models[modelId] = modelData;
      return modelData;
    }
    createModel(value, languageSelection, resource, isForSimpleWidget = false) {
      let modelData;
      if (languageSelection) {
        modelData = this._createModelData(value, languageSelection, resource, isForSimpleWidget);
      } else {
        modelData = this._createModelData(value, PLAINTEXT_LANGUAGE_ID, resource, isForSimpleWidget);
      }
      this._onModelAdded.fire(modelData.model);
      return modelData.model;
    }
    getModels() {
      const ret = [];
      const keys = Object.keys(this._models);
      for (let i2 = 0, len = keys.length; i2 < len; i2++) {
        const modelId = keys[i2];
        ret.push(this._models[modelId].model);
      }
      return ret;
    }
    getModel(resource) {
      const modelId = MODEL_ID(resource);
      const modelData = this._models[modelId];
      if (!modelData) {
        return null;
      }
      return modelData.model;
    }
    // --- end IModelService
    _schemaShouldMaintainUndoRedoElements(resource) {
      return resource.scheme === Schemas.file || resource.scheme === Schemas.vscodeRemote || resource.scheme === Schemas.vscodeUserData || resource.scheme === Schemas.vscodeNotebookCell || resource.scheme === "fake-fs";
    }
    _onWillDispose(model) {
      const modelId = MODEL_ID(model.uri);
      const modelData = this._models[modelId];
      const sharesUndoRedoStack = this._undoRedoService.getUriComparisonKey(model.uri) !== model.uri.toString();
      let maintainUndoRedoStack = false;
      let heapSize = 0;
      if (sharesUndoRedoStack || this._shouldRestoreUndoStack() && this._schemaShouldMaintainUndoRedoElements(model.uri)) {
        const elements = this._undoRedoService.getElements(model.uri);
        if (elements.past.length > 0 || elements.future.length > 0) {
          for (const element of elements.past) {
            if (isEditStackElement(element) && element.matchesResource(model.uri)) {
              maintainUndoRedoStack = true;
              heapSize += element.heapSize(model.uri);
              element.setModel(model.uri);
            }
          }
          for (const element of elements.future) {
            if (isEditStackElement(element) && element.matchesResource(model.uri)) {
              maintainUndoRedoStack = true;
              heapSize += element.heapSize(model.uri);
              element.setModel(model.uri);
            }
          }
        }
      }
      const maxMemory = ModelService_1.MAX_MEMORY_FOR_CLOSED_FILES_UNDO_STACK;
      const sha1Computer = this._getSHA1Computer();
      if (!maintainUndoRedoStack) {
        if (!sharesUndoRedoStack) {
          const initialUndoRedoSnapshot = modelData.model.getInitialUndoRedoSnapshot();
          if (initialUndoRedoSnapshot !== null) {
            this._undoRedoService.restoreSnapshot(initialUndoRedoSnapshot);
          }
        }
      } else if (!sharesUndoRedoStack && (heapSize > maxMemory || !sha1Computer.canComputeSHA1(model))) {
        const initialUndoRedoSnapshot = modelData.model.getInitialUndoRedoSnapshot();
        if (initialUndoRedoSnapshot !== null) {
          this._undoRedoService.restoreSnapshot(initialUndoRedoSnapshot);
        }
      } else {
        this._ensureDisposedModelsHeapSize(maxMemory - heapSize);
        this._undoRedoService.setElementsValidFlag(model.uri, false, (element) => isEditStackElement(element) && element.matchesResource(model.uri));
        this._insertDisposedModel(new DisposedModelInfo(model.uri, modelData.model.getInitialUndoRedoSnapshot(), Date.now(), sharesUndoRedoStack, heapSize, sha1Computer.computeSHA1(model), model.getVersionId(), model.getAlternativeVersionId()));
      }
      delete this._models[modelId];
      modelData.dispose();
      delete this._modelCreationOptionsByLanguageAndResource[model.getLanguageId() + model.uri];
      this._onModelRemoved.fire(model);
    }
    _onDidChangeLanguage(model, e) {
      const oldLanguageId = e.oldLanguage;
      const newLanguageId = model.getLanguageId();
      const oldOptions = this.getCreationOptions(oldLanguageId, model.uri, model.isForSimpleWidget);
      const newOptions = this.getCreationOptions(newLanguageId, model.uri, model.isForSimpleWidget);
      ModelService_1._setModelOptionsForModel(model, newOptions, oldOptions);
      this._onModelModeChanged.fire({ model, oldLanguageId });
    }
    _getSHA1Computer() {
      return new DefaultModelSHA1Computer();
    }
  }, ModelService_1 = _Na, _Na.MAX_MEMORY_FOR_CLOSED_FILES_UNDO_STACK = 20 * 1024 * 1024, _Na);
  ModelService = ModelService_1 = __decorate$i([
    __param$h(0, IConfigurationService),
    __param$h(1, ITextResourcePropertiesService),
    __param$h(2, IUndoRedoService),
    __param$h(3, IInstantiationService)
  ], ModelService);
  const _DefaultModelSHA1Computer = class _DefaultModelSHA1Computer {
    // takes 200ms to compute a sha1 on a 10MB model on a new machine
    canComputeSHA1(model) {
      return model.getValueLength() <= _DefaultModelSHA1Computer.MAX_MODEL_SIZE;
    }
    computeSHA1(model) {
      const shaComputer = new StringSHA1();
      const snapshot = model.createSnapshot();
      let text2;
      while (text2 = snapshot.read()) {
        shaComputer.update(text2);
      }
      return shaComputer.digest();
    }
  };
  _DefaultModelSHA1Computer.MAX_MODEL_SIZE = 10 * 1024 * 1024;
  let DefaultModelSHA1Computer = _DefaultModelSHA1Computer;
  var __decorate$h = 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$g = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  let QuickAccessController = class QuickAccessController extends Disposable {
    constructor(quickInputService, instantiationService) {
      super();
      this.quickInputService = quickInputService;
      this.instantiationService = instantiationService;
      this.registry = Registry.as(Extensions.Quickaccess);
      this.mapProviderToDescriptor = /* @__PURE__ */ new Map();
      this.lastAcceptedPickerValues = /* @__PURE__ */ new Map();
      this.visibleQuickAccess = void 0;
      this._register(toDisposable(() => {
        for (const provider of this.mapProviderToDescriptor.values()) {
          if (isDisposable(provider)) {
            provider.dispose();
          }
        }
        this.visibleQuickAccess?.picker.dispose();
      }));
    }
    show(value = "", options) {
      this.doShowOrPick(value, false, options);
    }
    doShowOrPick(value, pick, options) {
      const [provider, descriptor] = this.getOrInstantiateProvider(value, options?.enabledProviderPrefixes);
      const visibleQuickAccess = this.visibleQuickAccess;
      const visibleDescriptor = visibleQuickAccess?.descriptor;
      if (visibleQuickAccess && descriptor && visibleDescriptor === descriptor) {
        if (value !== descriptor.prefix && !options?.preserveValue) {
          visibleQuickAccess.picker.value = value;
        }
        this.adjustValueSelection(visibleQuickAccess.picker, descriptor, options);
        return;
      }
      if (descriptor && !options?.preserveValue) {
        let newValue = void 0;
        if (visibleQuickAccess && visibleDescriptor && visibleDescriptor !== descriptor) {
          const newValueCandidateWithoutPrefix = visibleQuickAccess.value.substr(visibleDescriptor.prefix.length);
          if (newValueCandidateWithoutPrefix) {
            newValue = `${descriptor.prefix}${newValueCandidateWithoutPrefix}`;
          }
        }
        if (!newValue) {
          const defaultFilterValue = provider?.defaultFilterValue;
          if (defaultFilterValue === DefaultQuickAccessFilterValue.LAST) {
            newValue = this.lastAcceptedPickerValues.get(descriptor);
          } else if (typeof defaultFilterValue === "string") {
            newValue = `${descriptor.prefix}${defaultFilterValue}`;
          }
        }
        if (typeof newValue === "string") {
          value = newValue;
        }
      }
      const visibleSelection = visibleQuickAccess?.picker?.valueSelection;
      const visibleValue = visibleQuickAccess?.picker?.value;
      const disposables = new DisposableStore();
      const picker = disposables.add(this.quickInputService.createQuickPick({ useSeparators: true }));
      picker.value = value;
      this.adjustValueSelection(picker, descriptor, options);
      picker.placeholder = options?.placeholder ?? descriptor?.placeholder;
      picker.quickNavigate = options?.quickNavigateConfiguration;
      picker.hideInput = !!picker.quickNavigate && !visibleQuickAccess;
      if (typeof options?.itemActivation === "number" || options?.quickNavigateConfiguration) {
        picker.itemActivation = options?.itemActivation ?? ItemActivation.SECOND;
      }
      picker.contextKey = descriptor?.contextKey;
      picker.filterValue = (value2) => value2.substring(descriptor ? descriptor.prefix.length : 0);
      let pickPromise = void 0;
      if (pick) {
        pickPromise = new DeferredPromise();
        disposables.add(Event.once(picker.onWillAccept)((e) => {
          e.veto();
          picker.hide();
        }));
      }
      disposables.add(this.registerPickerListeners(picker, provider, descriptor, value, options));
      const cts = disposables.add(new CancellationTokenSource$1());
      if (provider) {
        disposables.add(provider.provide(picker, cts.token, options?.providerOptions));
      }
      Event.once(picker.onDidHide)(() => {
        if (picker.selectedItems.length === 0) {
          cts.cancel();
        }
        disposables.dispose();
        pickPromise?.complete(picker.selectedItems.slice(0));
      });
      picker.show();
      if (visibleSelection && visibleValue === value) {
        picker.valueSelection = visibleSelection;
      }
      if (pick) {
        return pickPromise?.p;
      }
    }
    adjustValueSelection(picker, descriptor, options) {
      let valueSelection;
      if (options?.preserveValue) {
        valueSelection = [picker.value.length, picker.value.length];
      } else {
        valueSelection = [descriptor?.prefix.length ?? 0, picker.value.length];
      }
      picker.valueSelection = valueSelection;
    }
    registerPickerListeners(picker, provider, descriptor, value, options) {
      const disposables = new DisposableStore();
      const visibleQuickAccess = this.visibleQuickAccess = { picker, descriptor, value };
      disposables.add(toDisposable(() => {
        if (visibleQuickAccess === this.visibleQuickAccess) {
          this.visibleQuickAccess = void 0;
        }
      }));
      disposables.add(picker.onDidChangeValue((value2) => {
        const [providerForValue] = this.getOrInstantiateProvider(value2, options?.enabledProviderPrefixes);
        if (providerForValue !== provider) {
          this.show(value2, {
            enabledProviderPrefixes: options?.enabledProviderPrefixes,
            // do not rewrite value from user typing!
            preserveValue: true,
            // persist the value of the providerOptions from the original showing
            providerOptions: options?.providerOptions
          });
        } else {
          visibleQuickAccess.value = value2;
        }
      }));
      if (descriptor) {
        disposables.add(picker.onDidAccept(() => {
          this.lastAcceptedPickerValues.set(descriptor, picker.value);
        }));
      }
      return disposables;
    }
    getOrInstantiateProvider(value, enabledProviderPrefixes) {
      const providerDescriptor = this.registry.getQuickAccessProvider(value);
      if (!providerDescriptor || enabledProviderPrefixes && !enabledProviderPrefixes?.includes(providerDescriptor.prefix)) {
        return [void 0, void 0];
      }
      let provider = this.mapProviderToDescriptor.get(providerDescriptor);
      if (!provider) {
        provider = this.instantiationService.createInstance(providerDescriptor.ctor);
        this.mapProviderToDescriptor.set(providerDescriptor, provider);
      }
      return [provider, providerDescriptor];
    }
  };
  QuickAccessController = __decorate$h([
    __param$g(0, IQuickInputService),
    __param$g(1, IInstantiationService)
  ], QuickAccessController);
  var __decorate$g = 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;
  };
  class LinkedText {
    constructor(nodes) {
      this.nodes = nodes;
    }
    toString() {
      return this.nodes.map((node) => typeof node === "string" ? node : node.label).join("");
    }
  }
  __decorate$g([
    memoize
  ], LinkedText.prototype, "toString", null);
  const LINK_REGEX = /\[([^\]]+)\]\(((?:https?:\/\/|command:|file:)[^\)\s]+)(?: (["'])(.+?)(\3))?\)/gi;
  function parseLinkedText(text2) {
    const result = [];
    let index = 0;
    let match2;
    while (match2 = LINK_REGEX.exec(text2)) {
      if (match2.index - index > 0) {
        result.push(text2.substring(index, match2.index));
      }
      const [, label, href, , title] = match2;
      if (title) {
        result.push({ label, href, title });
      } else {
        result.push({ label, href });
      }
      index = match2.index + match2[0].length;
    }
    if (index < text2.length) {
      result.push(text2.substring(index));
    }
    return new LinkedText(result);
  }
  const iconPathToClass = {};
  const iconClassGenerator = new IdGenerator("quick-input-button-icon-");
  function getIconClass(iconPath) {
    if (!iconPath) {
      return void 0;
    }
    let iconClass;
    const key = iconPath.dark.toString();
    if (iconPathToClass[key]) {
      iconClass = iconPathToClass[key];
    } else {
      iconClass = iconClassGenerator.nextId();
      createCSSRule(`.${iconClass}, .hc-light .${iconClass}`, `background-image: ${asCSSUrl(iconPath.light || iconPath.dark)}`);
      createCSSRule(`.vs-dark .${iconClass}, .hc-black .${iconClass}`, `background-image: ${asCSSUrl(iconPath.dark)}`);
      iconPathToClass[key] = iconClass;
    }
    return iconClass;
  }
  function quickInputButtonToAction(button, id, run) {
    let cssClasses = button.iconClass || getIconClass(button.iconPath);
    if (button.alwaysVisible) {
      cssClasses = cssClasses ? `${cssClasses} always-visible` : "always-visible";
    }
    return {
      id,
      label: "",
      tooltip: button.tooltip || "",
      class: cssClasses,
      enabled: true,
      run
    };
  }
  function renderQuickInputDescription(description, container, actionHandler) {
    reset(container);
    const parsed = parseLinkedText(description);
    let tabIndex = 0;
    for (const node of parsed.nodes) {
      if (typeof node === "string") {
        container.append(...renderLabelWithIcons(node));
      } else {
        let title = node.title;
        if (!title && node.href.startsWith("command:")) {
          title = localize(1771, "Click to execute command '{0}'", node.href.substring("command:".length));
        } else if (!title) {
          title = node.href;
        }
        const anchor = $$l("a", { href: node.href, title, tabIndex: tabIndex++ }, node.label);
        anchor.style.textDecoration = "underline";
        const handleOpen = (e) => {
          if (isEventLike(e)) {
            EventHelper.stop(e, true);
          }
          actionHandler.callback(node.href);
        };
        const onClick = actionHandler.disposables.add(new DomEmitter(anchor, EventType$1.CLICK)).event;
        const onKeydown = actionHandler.disposables.add(new DomEmitter(anchor, EventType$1.KEY_DOWN)).event;
        const onSpaceOrEnter = Event.chain(onKeydown, ($2) => $2.filter((e) => {
          const event = new StandardKeyboardEvent(e);
          return event.equals(
            10
            /* KeyCode.Space */
          ) || event.equals(
            3
            /* KeyCode.Enter */
          );
        }));
        actionHandler.disposables.add(Gesture.addTarget(anchor));
        const onTap = actionHandler.disposables.add(new DomEmitter(anchor, EventType.Tap)).event;
        Event.any(onClick, onTap, onSpaceOrEnter)(handleOpen, null, actionHandler.disposables);
        container.appendChild(anchor);
      }
    }
  }
  var __decorate$f = 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$f = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  const inQuickInputContextKeyValue = "inQuickInput";
  const InQuickInputContextKey = new RawContextKey(inQuickInputContextKeyValue, false, localize(1748, "Whether keyboard focus is inside the quick input control"));
  const inQuickInputContext = ContextKeyExpr.has(inQuickInputContextKeyValue);
  const quickInputAlignmentContextKeyValue = "quickInputAlignment";
  const QuickInputAlignmentContextKey = new RawContextKey(quickInputAlignmentContextKeyValue, "top", localize(1749, "The alignment of the quick input"));
  const quickInputTypeContextKeyValue = "quickInputType";
  const QuickInputTypeContextKey = new RawContextKey(quickInputTypeContextKeyValue, void 0, localize(1750, "The type of the currently visible quick input"));
  const endOfQuickInputBoxContextKeyValue = "cursorAtEndOfQuickInputBox";
  const EndOfQuickInputBoxContextKey = new RawContextKey(endOfQuickInputBoxContextKeyValue, false, localize(1751, "Whether the cursor in the quick input is at the end of the input box"));
  const endOfQuickInputBoxContext = ContextKeyExpr.has(endOfQuickInputBoxContextKeyValue);
  const backButton = {
    iconClass: ThemeIcon.asClassName(Codicon.quickInputBack),
    tooltip: localize(1752, "Back")
  };
  const _QuickInput = class _QuickInput extends Disposable {
    constructor(ui) {
      super();
      this.ui = ui;
      this._visible = observableValue("visible", false);
      this._widgetUpdated = false;
      this._enabled = true;
      this._busy = false;
      this._ignoreFocusOut = false;
      this._leftButtons = [];
      this._rightButtons = [];
      this._inlineButtons = [];
      this.buttonsUpdated = false;
      this._toggles = [];
      this.togglesUpdated = false;
      this.noValidationMessage = _QuickInput.noPromptMessage;
      this._severity = Severity$2.Ignore;
      this.onDidTriggerButtonEmitter = this._register(new Emitter$1());
      this.onDidHideEmitter = this._register(new Emitter$1());
      this.onWillHideEmitter = this._register(new Emitter$1());
      this.onDisposeEmitter = this._register(new Emitter$1());
      this.visibleDisposables = this._register(new DisposableStore());
      this.onDidHide = this.onDidHideEmitter.event;
    }
    get visible() {
      return this._visible.get();
    }
    get title() {
      return this._title;
    }
    set title(title) {
      this._title = title;
      this.update();
    }
    get description() {
      return this._description;
    }
    set description(description) {
      this._description = description;
      this.update();
    }
    get step() {
      return this._steps;
    }
    set step(step) {
      this._steps = step;
      this.update();
    }
    get totalSteps() {
      return this._totalSteps;
    }
    set totalSteps(totalSteps) {
      this._totalSteps = totalSteps;
      this.update();
    }
    get enabled() {
      return this._enabled;
    }
    set enabled(enabled) {
      this._enabled = enabled;
      this.update();
    }
    get contextKey() {
      return this._contextKey;
    }
    set contextKey(contextKey) {
      this._contextKey = contextKey;
      this.update();
    }
    get busy() {
      return this._busy;
    }
    set busy(busy) {
      this._busy = busy;
      this.update();
    }
    get ignoreFocusOut() {
      return this._ignoreFocusOut;
    }
    set ignoreFocusOut(ignoreFocusOut) {
      const shouldUpdate = this._ignoreFocusOut !== ignoreFocusOut && !isIOS;
      this._ignoreFocusOut = ignoreFocusOut && !isIOS;
      if (shouldUpdate) {
        this.update();
      }
    }
    get titleButtons() {
      return this._leftButtons.length ? [...this._leftButtons, this._rightButtons] : this._rightButtons;
    }
    get buttons() {
      return [
        ...this._leftButtons,
        ...this._rightButtons,
        ...this._inlineButtons
      ];
    }
    set buttons(buttons) {
      this._leftButtons = buttons.filter((b) => b === backButton);
      this._rightButtons = buttons.filter((b) => b !== backButton && b.location !== QuickInputButtonLocation.Inline);
      this._inlineButtons = buttons.filter((b) => b.location === QuickInputButtonLocation.Inline);
      this.buttonsUpdated = true;
      this.update();
    }
    get toggles() {
      return this._toggles;
    }
    set toggles(toggles) {
      this._toggles = toggles ?? [];
      this.togglesUpdated = true;
      this.update();
    }
    get validationMessage() {
      return this._validationMessage;
    }
    set validationMessage(validationMessage) {
      this._validationMessage = validationMessage;
      this.update();
    }
    get severity() {
      return this._severity;
    }
    set severity(severity) {
      this._severity = severity;
      this.update();
    }
    show() {
      if (this.visible) {
        return;
      }
      this.visibleDisposables.add(this.ui.onDidTriggerButton((button) => {
        if (this.buttons.indexOf(button) !== -1) {
          this.onDidTriggerButtonEmitter.fire(button);
        }
      }));
      this.ui.show(this);
      this._visible.set(true, void 0);
      this._lastValidationMessage = void 0;
      this._lastSeverity = void 0;
      if (this.buttons.length) {
        this.buttonsUpdated = true;
      }
      if (this.toggles.length) {
        this.togglesUpdated = true;
      }
      this.update();
    }
    hide() {
      if (!this.visible) {
        return;
      }
      this.ui.hide();
    }
    didHide(reason = QuickInputHideReason.Other) {
      this._visible.set(false, void 0);
      this.visibleDisposables.clear();
      this.onDidHideEmitter.fire({ reason });
    }
    willHide(reason = QuickInputHideReason.Other) {
      this.onWillHideEmitter.fire({ reason });
    }
    update() {
      if (!this.visible) {
        return;
      }
      const title = this.getTitle();
      if (title && this.ui.title.textContent !== title) {
        this.ui.title.textContent = title;
      } else if (!title && this.ui.title.innerHTML !== "&nbsp;") {
        this.ui.title.innerText = " ";
      }
      const description = this.getDescription();
      if (this.ui.description1.textContent !== description) {
        this.ui.description1.textContent = description;
      }
      if (this.ui.description2.textContent !== description) {
        this.ui.description2.textContent = description;
      }
      if (this._widgetUpdated) {
        this._widgetUpdated = false;
        if (this._widget) {
          reset(this.ui.widget, this._widget);
        } else {
          reset(this.ui.widget);
        }
      }
      if (this.busy && !this.busyDelay) {
        this.busyDelay = new TimeoutTimer();
        this.busyDelay.setIfNotSet(() => {
          if (this.visible) {
            this.ui.progressBar.infinite();
            this.ui.progressBar.getContainer().removeAttribute("aria-hidden");
          }
        }, 800);
      }
      if (!this.busy && this.busyDelay) {
        this.ui.progressBar.stop();
        this.ui.progressBar.getContainer().setAttribute("aria-hidden", "true");
        this.busyDelay.cancel();
        this.busyDelay = void 0;
      }
      if (this.buttonsUpdated) {
        this.buttonsUpdated = false;
        this.ui.leftActionBar.clear();
        const leftButtons = this._leftButtons.map((button, index) => quickInputButtonToAction(button, `id-${index}`, async () => this.onDidTriggerButtonEmitter.fire(button)));
        this.ui.leftActionBar.push(leftButtons, { icon: true, label: false });
        this.ui.rightActionBar.clear();
        const rightButtons = this._rightButtons.map((button, index) => quickInputButtonToAction(button, `id-${index}`, async () => this.onDidTriggerButtonEmitter.fire(button)));
        this.ui.rightActionBar.push(rightButtons, { icon: true, label: false });
        this.ui.inlineActionBar.clear();
        const inlineButtons = this._inlineButtons.map((button, index) => quickInputButtonToAction(button, `id-${index}`, async () => this.onDidTriggerButtonEmitter.fire(button)));
        this.ui.inlineActionBar.push(inlineButtons, { icon: true, label: false });
      }
      if (this.togglesUpdated) {
        this.togglesUpdated = false;
        const concreteToggles = this.toggles?.filter((opts) => opts instanceof Toggle) ?? [];
        this.ui.inputBox.toggles = concreteToggles;
        const toggleOffset = concreteToggles.length * 22;
        this.ui.countContainer.style.right = toggleOffset > 0 ? `${4 + toggleOffset}px` : "4px";
        this.ui.visibleCountContainer.style.right = toggleOffset > 0 ? `${4 + toggleOffset}px` : "4px";
      }
      this.ui.ignoreFocusOut = this.ignoreFocusOut;
      this.ui.setEnabled(this.enabled);
      this.ui.setContextKey(this.contextKey);
      const validationMessage = this.validationMessage || this.noValidationMessage;
      if (this._lastValidationMessage !== validationMessage) {
        this._lastValidationMessage = validationMessage;
        reset(this.ui.message);
        if (validationMessage) {
          renderQuickInputDescription(validationMessage, this.ui.message, {
            callback: (content) => {
              this.ui.linkOpenerDelegate(content);
            },
            disposables: this.visibleDisposables
          });
        }
      }
      if (this._lastSeverity !== this.severity) {
        this._lastSeverity = this.severity;
        this.showMessageDecoration(this.severity);
      }
    }
    getTitle() {
      if (this.title && this.step) {
        return `${this.title} (${this.getSteps()})`;
      }
      if (this.title) {
        return this.title;
      }
      if (this.step) {
        return this.getSteps();
      }
      return "";
    }
    getDescription() {
      return this.description || "";
    }
    getSteps() {
      if (this.step && this.totalSteps) {
        return localize(1754, "{0}/{1}", this.step, this.totalSteps);
      }
      if (this.step) {
        return String(this.step);
      }
      return "";
    }
    showMessageDecoration(severity) {
      this.ui.inputBox.showDecoration(severity);
      if (severity !== Severity$2.Ignore) {
        const styles = this.ui.inputBox.stylesForType(severity);
        this.ui.message.style.color = styles.foreground ? `${styles.foreground}` : "";
        this.ui.message.style.backgroundColor = styles.background ? `${styles.background}` : "";
        this.ui.message.style.border = styles.border ? `1px solid ${styles.border}` : "";
        this.ui.message.style.marginBottom = "-2px";
      } else {
        this.ui.message.style.color = "";
        this.ui.message.style.backgroundColor = "";
        this.ui.message.style.border = "";
        this.ui.message.style.marginBottom = "";
      }
    }
    dispose() {
      this.hide();
      this.onDisposeEmitter.fire();
      super.dispose();
    }
  };
  _QuickInput.noPromptMessage = localize(1753, "Press 'Enter' to confirm your input or 'Escape' to cancel");
  let QuickInput = _QuickInput;
  const _QuickPick = class _QuickPick extends QuickInput {
    constructor(ui) {
      super(ui);
      this._value = "";
      this.onDidChangeValueEmitter = this._register(new Emitter$1());
      this.onWillAcceptEmitter = this._register(new Emitter$1());
      this.onDidAcceptEmitter = this._register(new Emitter$1());
      this.onDidCustomEmitter = this._register(new Emitter$1());
      this._items = [];
      this.itemsUpdated = false;
      this._canSelectMany = false;
      this._canAcceptInBackground = false;
      this._matchOnDescription = false;
      this._matchOnDetail = false;
      this._matchOnLabel = true;
      this._matchOnLabelMode = "fuzzy";
      this._sortByLabel = true;
      this._keepScrollPosition = false;
      this._itemActivation = ItemActivation.FIRST;
      this._activeItems = [];
      this.activeItemsUpdated = false;
      this.activeItemsToConfirm = [];
      this.onDidChangeActiveEmitter = this._register(new Emitter$1());
      this._selectedItems = [];
      this.selectedItemsUpdated = false;
      this.selectedItemsToConfirm = [];
      this.onDidChangeSelectionEmitter = this._register(new Emitter$1());
      this.onDidTriggerItemButtonEmitter = this._register(new Emitter$1());
      this.onDidTriggerSeparatorButtonEmitter = this._register(new Emitter$1());
      this.valueSelectionUpdated = true;
      this._ok = "default";
      this._customButton = false;
      this._focusEventBufferer = new EventBufferer();
      this.type = "quickPick";
      this.filterValue = (value) => value;
      this.onDidChangeValue = this.onDidChangeValueEmitter.event;
      this.onWillAccept = this.onWillAcceptEmitter.event;
      this.onDidAccept = this.onDidAcceptEmitter.event;
      this.onDidChangeActive = this.onDidChangeActiveEmitter.event;
      this.onDidChangeSelection = this.onDidChangeSelectionEmitter.event;
      this.onDidTriggerItemButton = this.onDidTriggerItemButtonEmitter.event;
      this.onDidTriggerSeparatorButton = this.onDidTriggerSeparatorButtonEmitter.event;
      this.noValidationMessage = void 0;
    }
    get quickNavigate() {
      return this._quickNavigate;
    }
    set quickNavigate(quickNavigate) {
      this._quickNavigate = quickNavigate;
      this.update();
    }
    get value() {
      return this._value;
    }
    set value(value) {
      this.doSetValue(value);
    }
    doSetValue(value, skipUpdate) {
      if (this._value !== value) {
        this._value = value;
        if (!skipUpdate) {
          this.update();
        }
        if (this.visible) {
          const didFilter = this.ui.list.filter(this.filterValue(this._value));
          if (didFilter) {
            this.trySelectFirst();
          }
        }
        this.onDidChangeValueEmitter.fire(this._value);
      }
    }
    set ariaLabel(ariaLabel) {
      this._ariaLabel = ariaLabel;
      this.update();
    }
    get ariaLabel() {
      return this._ariaLabel;
    }
    get placeholder() {
      return this._placeholder;
    }
    set placeholder(placeholder) {
      this._placeholder = placeholder;
      this.update();
    }
    get prompt() {
      return this.noValidationMessage;
    }
    set prompt(prompt) {
      this.noValidationMessage = prompt;
      this.update();
    }
    get items() {
      return this._items;
    }
    get scrollTop() {
      return this.ui.list.scrollTop;
    }
    set scrollTop(scrollTop) {
      this.ui.list.scrollTop = scrollTop;
    }
    set items(items) {
      this._items = items;
      this.itemsUpdated = true;
      this.update();
    }
    get canSelectMany() {
      return this._canSelectMany;
    }
    set canSelectMany(canSelectMany) {
      this._canSelectMany = canSelectMany;
      this.update();
    }
    get canAcceptInBackground() {
      return this._canAcceptInBackground;
    }
    set canAcceptInBackground(canAcceptInBackground) {
      this._canAcceptInBackground = canAcceptInBackground;
    }
    get matchOnDescription() {
      return this._matchOnDescription;
    }
    set matchOnDescription(matchOnDescription) {
      this._matchOnDescription = matchOnDescription;
      this.update();
    }
    get matchOnDetail() {
      return this._matchOnDetail;
    }
    set matchOnDetail(matchOnDetail) {
      this._matchOnDetail = matchOnDetail;
      this.update();
    }
    get matchOnLabel() {
      return this._matchOnLabel;
    }
    set matchOnLabel(matchOnLabel) {
      this._matchOnLabel = matchOnLabel;
      this.update();
    }
    get matchOnLabelMode() {
      return this._matchOnLabelMode;
    }
    set matchOnLabelMode(matchOnLabelMode) {
      this._matchOnLabelMode = matchOnLabelMode;
      this.update();
    }
    get sortByLabel() {
      return this._sortByLabel;
    }
    set sortByLabel(sortByLabel) {
      this._sortByLabel = sortByLabel;
      this.update();
    }
    get keepScrollPosition() {
      return this._keepScrollPosition;
    }
    set keepScrollPosition(keepScrollPosition) {
      this._keepScrollPosition = keepScrollPosition;
    }
    get itemActivation() {
      return this._itemActivation;
    }
    set itemActivation(itemActivation) {
      this._itemActivation = itemActivation;
    }
    get activeItems() {
      return this._activeItems;
    }
    set activeItems(activeItems) {
      this._activeItems = activeItems;
      this.activeItemsUpdated = true;
      this.update();
    }
    get selectedItems() {
      return this._selectedItems;
    }
    set selectedItems(selectedItems) {
      this._selectedItems = selectedItems;
      this.selectedItemsUpdated = true;
      this.update();
    }
    get keyMods() {
      if (this._quickNavigate) {
        return NO_KEY_MODS;
      }
      return this.ui.keyMods;
    }
    get valueSelection() {
      const selection = this.ui.inputBox.getSelection();
      if (!selection) {
        return void 0;
      }
      return [selection.start, selection.end];
    }
    set valueSelection(valueSelection) {
      this._valueSelection = valueSelection;
      this.valueSelectionUpdated = true;
      this.update();
    }
    get customButton() {
      return this._customButton;
    }
    set customButton(showCustomButton) {
      this._customButton = showCustomButton;
      this.update();
    }
    get customLabel() {
      return this._customButtonLabel;
    }
    set customLabel(label) {
      this._customButtonLabel = label;
      this.update();
    }
    get customHover() {
      return this._customButtonHover;
    }
    set customHover(hover) {
      this._customButtonHover = hover;
      this.update();
    }
    get ok() {
      return this._ok;
    }
    set ok(showOkButton) {
      this._ok = showOkButton;
      this.update();
    }
    get okLabel() {
      return this._okLabel ?? localize(1756, "OK");
    }
    set okLabel(okLabel) {
      this._okLabel = okLabel;
      this.update();
    }
    get hideInput() {
      return !!this._hideInput;
    }
    set hideInput(hideInput) {
      this._hideInput = hideInput;
      this.update();
    }
    trySelectFirst() {
      if (!this.canSelectMany) {
        this.ui.list.focus(QuickPickFocus.First);
      }
    }
    show() {
      if (!this.visible) {
        this.visibleDisposables.add(this.ui.inputBox.onDidChange((value) => {
          this.doSetValue(
            value,
            true
            /* skip update since this originates from the UI */
          );
        }));
        this.visibleDisposables.add(this.ui.onDidAccept(() => {
          if (this.canSelectMany) {
            if (!this.ui.list.getCheckedElements().length) {
              this._selectedItems = [];
              this.onDidChangeSelectionEmitter.fire(this.selectedItems);
            }
          } else if (this.activeItems[0]) {
            this._selectedItems = [this.activeItems[0]];
            this.onDidChangeSelectionEmitter.fire(this.selectedItems);
          }
          this.handleAccept(false);
        }));
        this.visibleDisposables.add(this.ui.onDidCustom(() => {
          this.onDidCustomEmitter.fire();
        }));
        this.visibleDisposables.add(this._focusEventBufferer.wrapEvent(
          this.ui.list.onDidChangeFocus,
          // Only fire the last event
          (_, e) => e
        )((focusedItems) => {
          if (this.activeItemsUpdated) {
            return;
          }
          if (this.activeItemsToConfirm !== this._activeItems && equals$1(focusedItems, this._activeItems, (a, b) => a === b)) {
            return;
          }
          this._activeItems = focusedItems;
          this.onDidChangeActiveEmitter.fire(focusedItems);
        }));
        this.visibleDisposables.add(this.ui.list.onDidChangeSelection(({ items: selectedItems, event }) => {
          if (this.canSelectMany && !selectedItems.some((i2) => i2.pickable === false)) {
            if (selectedItems.length) {
              this.ui.list.setSelectedElements([]);
            }
            return;
          }
          if (this.selectedItemsToConfirm !== this._selectedItems && equals$1(selectedItems, this._selectedItems, (a, b) => a === b)) {
            return;
          }
          this._selectedItems = selectedItems;
          this.onDidChangeSelectionEmitter.fire(selectedItems);
          if (selectedItems.length) {
            this.handleAccept(
              isMouseEvent(event) && event.button === 1
              /* mouse middle click */
            );
          }
        }));
        this.visibleDisposables.add(this.ui.list.onChangedCheckedElements((checkedItems) => {
          if (!this.canSelectMany || !this.visible) {
            return;
          }
          if (this.selectedItemsToConfirm !== this._selectedItems && equals$1(checkedItems, this._selectedItems, (a, b) => a === b)) {
            return;
          }
          this._selectedItems = checkedItems;
          this.onDidChangeSelectionEmitter.fire(checkedItems);
        }));
        this.visibleDisposables.add(this.ui.list.onButtonTriggered((event) => this.onDidTriggerItemButtonEmitter.fire(event)));
        this.visibleDisposables.add(this.ui.list.onSeparatorButtonTriggered((event) => this.onDidTriggerSeparatorButtonEmitter.fire(event)));
        this.visibleDisposables.add(this.registerQuickNavigation());
        this.valueSelectionUpdated = true;
      }
      super.show();
    }
    handleAccept(inBackground) {
      let veto = false;
      this.onWillAcceptEmitter.fire({ veto: () => veto = true });
      if (!veto) {
        this.onDidAcceptEmitter.fire({ inBackground });
      }
    }
    registerQuickNavigation() {
      return addDisposableListener(this.ui.container, EventType$1.KEY_UP, (e) => {
        if (this.canSelectMany || !this._quickNavigate) {
          return;
        }
        const keyboardEvent = new StandardKeyboardEvent(e);
        const keyCode = keyboardEvent.keyCode;
        const quickNavKeys = this._quickNavigate.keybindings;
        const wasTriggerKeyPressed = quickNavKeys.some((k) => {
          const chords = k.getChords();
          if (chords.length > 1) {
            return false;
          }
          if (chords[0].shiftKey && keyCode === 4) {
            if (keyboardEvent.ctrlKey || keyboardEvent.altKey || keyboardEvent.metaKey) {
              return false;
            }
            return true;
          }
          if (chords[0].altKey && keyCode === 6) {
            return true;
          }
          if (chords[0].ctrlKey && keyCode === 5) {
            return true;
          }
          if (chords[0].metaKey && keyCode === 57) {
            return true;
          }
          return false;
        });
        if (wasTriggerKeyPressed) {
          if (this.activeItems[0]) {
            this._selectedItems = [this.activeItems[0]];
            this.onDidChangeSelectionEmitter.fire(this.selectedItems);
            this.handleAccept(false);
          }
          this._quickNavigate = void 0;
        }
      });
    }
    update() {
      if (!this.visible) {
        return;
      }
      const scrollTopBefore = this.keepScrollPosition ? this.scrollTop : 0;
      const hasDescription = !!this.description;
      const visibilities = {
        title: !!this.title || !!this.step || !!this.titleButtons.length,
        description: hasDescription,
        checkAll: this.canSelectMany && !this._hideCheckAll,
        checkBox: this.canSelectMany,
        inputBox: !this._hideInput,
        progressBar: !this._hideInput || hasDescription,
        visibleCount: true,
        count: this.canSelectMany && !this._hideCountBadge,
        ok: this.ok === "default" ? this.canSelectMany : this.ok,
        list: true,
        message: !!this.validationMessage || !!this.prompt,
        customButton: this.customButton
      };
      this.ui.setVisibilities(visibilities);
      super.update();
      if (this.ui.inputBox.value !== this.value) {
        this.ui.inputBox.value = this.value;
      }
      if (this.valueSelectionUpdated) {
        this.valueSelectionUpdated = false;
        this.ui.inputBox.select(this._valueSelection && { start: this._valueSelection[0], end: this._valueSelection[1] });
      }
      if (this.ui.inputBox.placeholder !== (this.placeholder || "")) {
        this.ui.inputBox.placeholder = this.placeholder || "";
      }
      let ariaLabel = this.ariaLabel;
      if (!ariaLabel && visibilities.inputBox) {
        ariaLabel = this.placeholder;
        if (this.title) {
          ariaLabel = ariaLabel ? `${ariaLabel} - ${this.title}` : this.title;
        }
        if (!ariaLabel) {
          ariaLabel = _QuickPick.DEFAULT_ARIA_LABEL;
        }
      }
      if (this.ui.list.ariaLabel !== ariaLabel) {
        this.ui.list.ariaLabel = ariaLabel ?? null;
      }
      if (this.ui.inputBox.ariaLabel !== ariaLabel) {
        this.ui.inputBox.ariaLabel = ariaLabel ?? "input";
      }
      this.ui.list.matchOnDescription = this.matchOnDescription;
      this.ui.list.matchOnDetail = this.matchOnDetail;
      this.ui.list.matchOnLabel = this.matchOnLabel;
      this.ui.list.matchOnLabelMode = this.matchOnLabelMode;
      this.ui.list.sortByLabel = this.sortByLabel;
      if (this.itemsUpdated) {
        this.itemsUpdated = false;
        this._focusEventBufferer.bufferEvents(() => {
          this.ui.list.setElements(this.items);
          this.ui.list.shouldLoop = !this.canSelectMany;
          this.ui.list.filter(this.filterValue(this.ui.inputBox.value));
          switch (this._itemActivation) {
            case ItemActivation.NONE:
              this._itemActivation = ItemActivation.FIRST;
              break;
            case ItemActivation.SECOND:
              this.ui.list.focus(QuickPickFocus.Second);
              this._itemActivation = ItemActivation.FIRST;
              break;
            case ItemActivation.LAST:
              this.ui.list.focus(QuickPickFocus.Last);
              this._itemActivation = ItemActivation.FIRST;
              break;
            default:
              this.trySelectFirst();
              break;
          }
        });
      }
      if (this.ui.container.classList.contains("show-checkboxes") !== !!this.canSelectMany) {
        if (this.canSelectMany) {
          this.ui.list.clearFocus();
        } else {
          this.trySelectFirst();
        }
      }
      if (this.activeItemsUpdated) {
        this.activeItemsUpdated = false;
        this.activeItemsToConfirm = this._activeItems;
        this.ui.list.setFocusedElements(this.activeItems);
        if (this.activeItemsToConfirm === this._activeItems) {
          this.activeItemsToConfirm = null;
        }
      }
      if (this.selectedItemsUpdated) {
        this.selectedItemsUpdated = false;
        this.selectedItemsToConfirm = this._selectedItems;
        if (this.canSelectMany) {
          this.ui.list.setCheckedElements(this.selectedItems);
        } else {
          this.ui.list.setSelectedElements(this.selectedItems);
        }
        if (this.selectedItemsToConfirm === this._selectedItems) {
          this.selectedItemsToConfirm = null;
        }
      }
      this.ui.ok.label = this.okLabel || "";
      this.ui.customButton.label = this.customLabel || "";
      this.ui.customButton.element.title = this.customHover || "";
      if (!visibilities.inputBox) {
        this.ui.list.domFocus();
        if (this.canSelectMany) {
          this.ui.list.focus(QuickPickFocus.First);
        }
      }
      if (this.keepScrollPosition) {
        this.scrollTop = scrollTopBefore;
      }
    }
    focus(focus) {
      this.ui.list.focus(focus);
      if (this.canSelectMany) {
        this.ui.list.domFocus();
      }
    }
    accept(inBackground) {
      if (inBackground && !this._canAcceptInBackground) {
        return;
      }
      if (this.activeItems[0] && !this._canSelectMany) {
        this._selectedItems = [this.activeItems[0]];
        this.onDidChangeSelectionEmitter.fire(this.selectedItems);
      }
      this.handleAccept(inBackground ?? false);
    }
  };
  _QuickPick.DEFAULT_ARIA_LABEL = localize(1755, "Type to narrow down results.");
  let QuickPick = _QuickPick;
  class InputBox extends QuickInput {
    constructor() {
      super(...arguments);
      this._value = "";
      this.valueSelectionUpdated = true;
      this._password = false;
      this.onDidValueChangeEmitter = this._register(new Emitter$1());
      this.onDidAcceptEmitter = this._register(new Emitter$1());
      this.type = "inputBox";
      this.onDidChangeValue = this.onDidValueChangeEmitter.event;
      this.onDidAccept = this.onDidAcceptEmitter.event;
    }
    get value() {
      return this._value;
    }
    set value(value) {
      this._value = value || "";
      this.update();
    }
    get valueSelection() {
      const selection = this.ui.inputBox.getSelection();
      if (!selection) {
        return void 0;
      }
      return [selection.start, selection.end];
    }
    set valueSelection(valueSelection) {
      this._valueSelection = valueSelection;
      this.valueSelectionUpdated = true;
      this.update();
    }
    get placeholder() {
      return this._placeholder;
    }
    set placeholder(placeholder) {
      this._placeholder = placeholder;
      this.update();
    }
    get ariaLabel() {
      return this._ariaLabel;
    }
    set ariaLabel(ariaLabel) {
      this._ariaLabel = ariaLabel;
      this.update();
    }
    get password() {
      return this._password;
    }
    set password(password) {
      this._password = password;
      this.update();
    }
    get prompt() {
      return this._prompt;
    }
    set prompt(prompt) {
      this._prompt = prompt;
      this.noValidationMessage = prompt ? localize(1757, "{0} (Press 'Enter' to confirm or 'Escape' to cancel)", prompt) : QuickInput.noPromptMessage;
      this.update();
    }
    show() {
      if (!this.visible) {
        this.visibleDisposables.add(this.ui.inputBox.onDidChange((value) => {
          if (value === this.value) {
            return;
          }
          this._value = value;
          this.onDidValueChangeEmitter.fire(value);
        }));
        this.visibleDisposables.add(this.ui.onDidAccept(() => this.onDidAcceptEmitter.fire()));
        this.valueSelectionUpdated = true;
      }
      super.show();
    }
    accept() {
      this.onDidAcceptEmitter.fire();
    }
    update() {
      if (!this.visible) {
        return;
      }
      this.ui.container.classList.remove("hidden-input");
      const visibilities = {
        title: !!this.title || !!this.step || !!this.titleButtons.length,
        description: !!this.description || !!this.step,
        inputBox: true,
        message: true,
        progressBar: true
      };
      this.ui.setVisibilities(visibilities);
      super.update();
      if (this.ui.inputBox.value !== this.value) {
        this.ui.inputBox.value = this.value;
      }
      if (this.valueSelectionUpdated) {
        this.valueSelectionUpdated = false;
        this.ui.inputBox.select(this._valueSelection && { start: this._valueSelection[0], end: this._valueSelection[1] });
      }
      if (this.ui.inputBox.placeholder !== (this.placeholder || "")) {
        this.ui.inputBox.placeholder = this.placeholder || "";
      }
      if (this.ui.inputBox.password !== this.password) {
        this.ui.inputBox.password = this.password;
      }
      let ariaLabel = this.ariaLabel;
      if (!ariaLabel && visibilities.inputBox) {
        ariaLabel = this.placeholder ? this.title ? `${this.placeholder} - ${this.title}` : this.placeholder : this.title ? this.title : "input";
      }
      if (this.ui.inputBox.ariaLabel !== ariaLabel) {
        this.ui.inputBox.ariaLabel = ariaLabel || "input";
      }
    }
  }
  let QuickInputHoverDelegate = class QuickInputHoverDelegate extends WorkbenchHoverDelegate {
    constructor(configurationService, hoverService) {
      super("mouse", void 0, (options) => this.getOverrideOptions(options), configurationService, hoverService);
    }
    getOverrideOptions(options) {
      const showHoverHint = (isHTMLElement(options.content) ? options.content.textContent ?? "" : typeof options.content === "string" ? options.content : options.content.value).includes("\n");
      return {
        persistence: {
          hideOnKeyDown: false
        },
        appearance: {
          showHoverHint,
          skipFadeInAnimation: true
        }
      };
    }
  };
  QuickInputHoverDelegate = __decorate$f([
    __param$f(0, IConfigurationService),
    __param$f(1, IHoverService)
  ], QuickInputHoverDelegate);
  const CSS_DONE = "done";
  const CSS_ACTIVE = "active";
  const CSS_INFINITE = "infinite";
  const CSS_INFINITE_LONG_RUNNING = "infinite-long-running";
  const CSS_DISCRETE = "discrete";
  const _ProgressBar = class _ProgressBar extends Disposable {
    constructor(container, options) {
      super();
      this.progressSignal = this._register(new MutableDisposable());
      this.workedVal = 0;
      this.showDelayedScheduler = this._register(new RunOnceScheduler(() => show(this.element), 0));
      this.longRunningScheduler = this._register(new RunOnceScheduler(() => this.infiniteLongRunning(), _ProgressBar.LONG_RUNNING_INFINITE_THRESHOLD));
      this.create(container, options);
    }
    create(container, options) {
      this.element = document.createElement("div");
      this.element.classList.add("monaco-progress-container");
      this.element.setAttribute("role", "progressbar");
      this.element.setAttribute("aria-valuemin", "0");
      container.appendChild(this.element);
      this.bit = document.createElement("div");
      this.bit.classList.add("progress-bit");
      this.bit.style.backgroundColor = options?.progressBarBackground || "#0E70C0";
      this.element.appendChild(this.bit);
    }
    off() {
      this.bit.style.width = "inherit";
      this.bit.style.opacity = "1";
      this.element.classList.remove(CSS_ACTIVE, CSS_INFINITE, CSS_INFINITE_LONG_RUNNING, CSS_DISCRETE);
      this.workedVal = 0;
      this.totalWork = void 0;
      this.longRunningScheduler.cancel();
      this.progressSignal.clear();
    }
    /**
     * Stops the progressbar from showing any progress instantly without fading out.
     */
    stop() {
      return this.doDone(false);
    }
    doDone(delayed) {
      this.element.classList.add(CSS_DONE);
      if (!this.element.classList.contains(CSS_INFINITE)) {
        this.bit.style.width = "inherit";
        if (delayed) {
          setTimeout(() => this.off(), 200);
        } else {
          this.off();
        }
      } else {
        this.bit.style.opacity = "0";
        if (delayed) {
          setTimeout(() => this.off(), 200);
        } else {
          this.off();
        }
      }
      return this;
    }
    /**
     * Use this mode to indicate progress that has no total number of work units.
     */
    infinite() {
      this.bit.style.width = "2%";
      this.bit.style.opacity = "1";
      this.element.classList.remove(CSS_DISCRETE, CSS_DONE, CSS_INFINITE_LONG_RUNNING);
      this.element.classList.add(CSS_ACTIVE, CSS_INFINITE);
      this.longRunningScheduler.schedule();
      return this;
    }
    infiniteLongRunning() {
      this.element.classList.add(CSS_INFINITE_LONG_RUNNING);
    }
    getContainer() {
      return this.element;
    }
  };
  _ProgressBar.LONG_RUNNING_INFINITE_THRESHOLD = 1e4;
  let ProgressBar = _ProgressBar;
  const $$4 = $$l;
  class QuickInputBox extends Disposable {
    constructor(parent, inputBoxStyles, toggleStyles) {
      super();
      this.parent = parent;
      this.onDidChange = (handler) => {
        return this.findInput.onDidChange(handler);
      };
      this.container = append$2(this.parent, $$4(".quick-input-box"));
      this.findInput = this._register(new FindInput(this.container, void 0, { label: "", inputBoxStyles, toggleStyles }));
      const input = this.findInput.inputBox.inputElement;
      input.role = "textbox";
      input.ariaHasPopup = "menu";
      input.ariaAutoComplete = "list";
    }
    get onKeyDown() {
      return this.findInput.onKeyDown;
    }
    get value() {
      return this.findInput.getValue();
    }
    set value(value) {
      this.findInput.setValue(value);
    }
    select(range2 = null) {
      this.findInput.inputBox.select(range2);
    }
    getSelection() {
      return this.findInput.inputBox.getSelection();
    }
    isSelectionAtEnd() {
      return this.findInput.inputBox.isSelectionAtEnd();
    }
    get placeholder() {
      return this.findInput.inputBox.inputElement.getAttribute("placeholder") || "";
    }
    set placeholder(placeholder) {
      this.findInput.inputBox.setPlaceHolder(placeholder);
    }
    get password() {
      return this.findInput.inputBox.inputElement.type === "password";
    }
    set password(password) {
      this.findInput.inputBox.inputElement.type = password ? "password" : "text";
    }
    set enabled(enabled) {
      this.findInput.inputBox.inputElement.toggleAttribute("readonly", !enabled);
    }
    set toggles(toggles) {
      this.findInput.setAdditionalToggles(toggles);
    }
    get ariaLabel() {
      return this.findInput.inputBox.inputElement.getAttribute("aria-label") || "";
    }
    set ariaLabel(ariaLabel) {
      this.findInput.inputBox.inputElement.setAttribute("aria-label", ariaLabel);
    }
    hasFocus() {
      return this.findInput.inputBox.hasFocus();
    }
    setAttribute(name, value) {
      this.findInput.inputBox.inputElement.setAttribute(name, value);
    }
    removeAttribute(name) {
      this.findInput.inputBox.inputElement.removeAttribute(name);
    }
    showDecoration(decoration2) {
      if (decoration2 === Severity$2.Ignore) {
        this.findInput.clearMessage();
      } else {
        this.findInput.showMessage({ type: decoration2 === Severity$2.Info ? 1 : decoration2 === Severity$2.Warning ? 2 : 3, content: "" });
      }
    }
    stylesForType(decoration2) {
      return this.findInput.inputBox.stylesForType(
        decoration2 === Severity$2.Info ? 1 : decoration2 === Severity$2.Warning ? 2 : 3
        /* MessageType.ERROR */
      );
    }
    setFocus() {
      this.findInput.focus();
    }
    layout() {
      this.findInput.inputBox.layout();
    }
  }
  const intlFileNameCollatorBaseNumeric = new Lazy(() => {
    const collator = safeIntl.Collator(void 0, { numeric: true, sensitivity: "base" }).value;
    return {
      collator,
      collatorIsNumeric: collator.resolvedOptions().numeric
    };
  });
  new Lazy(() => {
    const collator = safeIntl.Collator(void 0, { numeric: true }).value;
    return {
      collator
    };
  });
  new Lazy(() => {
    const collator = safeIntl.Collator(void 0, { numeric: true, sensitivity: "accent" }).value;
    return {
      collator
    };
  });
  function compareFileNames(one, other, caseSensitive = false) {
    const a = one || "";
    const b = other || "";
    const result = intlFileNameCollatorBaseNumeric.value.collator.compare(a, b);
    if (intlFileNameCollatorBaseNumeric.value.collatorIsNumeric && result === 0 && a !== b) {
      return a < b ? -1 : 1;
    }
    return result;
  }
  function compareAnything(one, other, lookFor) {
    const elementAName = one.toLowerCase();
    const elementBName = other.toLowerCase();
    const prefixCompare = compareByPrefix(one, other, lookFor);
    if (prefixCompare) {
      return prefixCompare;
    }
    const elementASuffixMatch = elementAName.endsWith(lookFor);
    const elementBSuffixMatch = elementBName.endsWith(lookFor);
    if (elementASuffixMatch !== elementBSuffixMatch) {
      return elementASuffixMatch ? -1 : 1;
    }
    const r = compareFileNames(elementAName, elementBName);
    if (r !== 0) {
      return r;
    }
    return elementAName.localeCompare(elementBName);
  }
  function compareByPrefix(one, other, lookFor) {
    const elementAName = one.toLowerCase();
    const elementBName = other.toLowerCase();
    const elementAPrefixMatch = elementAName.startsWith(lookFor);
    const elementBPrefixMatch = elementBName.startsWith(lookFor);
    if (elementAPrefixMatch !== elementBPrefixMatch) {
      return elementAPrefixMatch ? -1 : 1;
    } else if (elementAPrefixMatch && elementBPrefixMatch) {
      if (elementAName.length < elementBName.length) {
        return -1;
      }
      if (elementAName.length > elementBName.length) {
        return 1;
      }
    }
    return 0;
  }
  var __decorate$e = 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$e = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  var QuickPickItemElementRenderer_1;
  const $$3 = $$l;
  class BaseQuickPickItemElement {
    constructor(index, hasCheckbox, mainItem) {
      this.index = index;
      this.hasCheckbox = hasCheckbox;
      this._hidden = false;
      this._init = new Lazy(() => {
        const saneLabel = mainItem.label ?? "";
        const saneSortLabel = parseLabelWithIcons(saneLabel).text.trim();
        const saneAriaLabel = mainItem.ariaLabel || [saneLabel, this.saneDescription, this.saneDetail].map((s) => getCodiconAriaLabel(s)).filter((s) => !!s).join(", ");
        return {
          saneLabel,
          saneSortLabel,
          saneAriaLabel
        };
      });
      this._saneDescription = mainItem.description;
      this._saneTooltip = mainItem.tooltip;
    }
    // #region Lazy Getters
    get saneLabel() {
      return this._init.value.saneLabel;
    }
    get saneSortLabel() {
      return this._init.value.saneSortLabel;
    }
    get saneAriaLabel() {
      return this._init.value.saneAriaLabel;
    }
    get element() {
      return this._element;
    }
    set element(value) {
      this._element = value;
    }
    get hidden() {
      return this._hidden;
    }
    set hidden(value) {
      this._hidden = value;
    }
    get saneDescription() {
      return this._saneDescription;
    }
    set saneDescription(value) {
      this._saneDescription = value;
    }
    get saneDetail() {
      return this._saneDetail;
    }
    set saneDetail(value) {
      this._saneDetail = value;
    }
    get saneTooltip() {
      return this._saneTooltip;
    }
    set saneTooltip(value) {
      this._saneTooltip = value;
    }
    get labelHighlights() {
      return this._labelHighlights;
    }
    set labelHighlights(value) {
      this._labelHighlights = value;
    }
    get descriptionHighlights() {
      return this._descriptionHighlights;
    }
    set descriptionHighlights(value) {
      this._descriptionHighlights = value;
    }
    get detailHighlights() {
      return this._detailHighlights;
    }
    set detailHighlights(value) {
      this._detailHighlights = value;
    }
  }
  class QuickPickItemElement extends BaseQuickPickItemElement {
    constructor(index, childIndex, hasCheckbox, fireButtonTriggered, _onChecked, item, _separator) {
      super(index, hasCheckbox, item);
      this.childIndex = childIndex;
      this.fireButtonTriggered = fireButtonTriggered;
      this._onChecked = _onChecked;
      this.item = item;
      this._separator = _separator;
      this._checked = false;
      this.onChecked = hasCheckbox ? Event.map(Event.filter(this._onChecked.event, (e) => e.element === this), (e) => e.checked) : Event.None;
      this._saneDetail = item.detail;
      this._labelHighlights = item.highlights?.label;
      this._descriptionHighlights = item.highlights?.description;
      this._detailHighlights = item.highlights?.detail;
    }
    get separator() {
      return this._separator;
    }
    set separator(value) {
      this._separator = value;
    }
    get checked() {
      return this._checked;
    }
    set checked(value) {
      if (value !== this._checked) {
        this._checked = value;
        this._onChecked.fire({ element: this, checked: value });
      }
    }
    get checkboxDisabled() {
      return !!this.item.disabled;
    }
  }
  var QuickPickSeparatorFocusReason;
  (function(QuickPickSeparatorFocusReason2) {
    QuickPickSeparatorFocusReason2[QuickPickSeparatorFocusReason2["NONE"] = 0] = "NONE";
    QuickPickSeparatorFocusReason2[QuickPickSeparatorFocusReason2["MOUSE_HOVER"] = 1] = "MOUSE_HOVER";
    QuickPickSeparatorFocusReason2[QuickPickSeparatorFocusReason2["ACTIVE_ITEM"] = 2] = "ACTIVE_ITEM";
  })(QuickPickSeparatorFocusReason || (QuickPickSeparatorFocusReason = {}));
  class QuickPickSeparatorElement extends BaseQuickPickItemElement {
    constructor(index, fireSeparatorButtonTriggered, separator2) {
      super(index, false, separator2);
      this.fireSeparatorButtonTriggered = fireSeparatorButtonTriggered;
      this.separator = separator2;
      this.children = new Array();
      this.focusInsideSeparator = QuickPickSeparatorFocusReason.NONE;
    }
  }
  class QuickInputItemDelegate {
    getHeight(element) {
      if (element instanceof QuickPickSeparatorElement) {
        return 30;
      }
      return element.saneDetail ? 44 : 22;
    }
    getTemplateId(element) {
      if (element instanceof QuickPickItemElement) {
        return QuickPickItemElementRenderer.ID;
      } else {
        return QuickPickSeparatorElementRenderer.ID;
      }
    }
  }
  class QuickInputAccessibilityProvider {
    getWidgetAriaLabel() {
      return localize(1770, "Quick Input");
    }
    getAriaLabel(element) {
      return element.separator?.label ? `${element.saneAriaLabel}, ${element.separator.label}` : element.saneAriaLabel;
    }
    getWidgetRole() {
      return "listbox";
    }
    getRole(element) {
      return element.hasCheckbox ? "checkbox" : "option";
    }
    isChecked(element) {
      if (!element.hasCheckbox || !(element instanceof QuickPickItemElement)) {
        return void 0;
      }
      return {
        get value() {
          return element.checked;
        },
        onDidChange: (e) => element.onChecked(() => e())
      };
    }
  }
  class BaseQuickInputListRenderer {
    constructor(hoverDelegate) {
      this.hoverDelegate = hoverDelegate;
    }
    // TODO: only do the common stuff here and have a subclass handle their specific stuff
    renderTemplate(container) {
      const data = /* @__PURE__ */ Object.create(null);
      data.toDisposeElement = new DisposableStore();
      data.toDisposeTemplate = new DisposableStore();
      data.entry = append$2(container, $$3(".quick-input-list-entry"));
      const label = append$2(data.entry, $$3("label.quick-input-list-label"));
      data.outerLabel = label;
      data.checkbox = data.toDisposeTemplate.add(new MutableDisposable());
      data.toDisposeTemplate.add(addStandardDisposableListener(label, EventType$1.CLICK, (e) => {
        if (data.checkbox.value && !e.defaultPrevented && data.checkbox.value.enabled) {
          const checked = !data.checkbox.value.checked;
          data.checkbox.value.checked = checked;
          data.element.checked = checked;
        }
      }));
      const rows = append$2(label, $$3(".quick-input-list-rows"));
      const row1 = append$2(rows, $$3(".quick-input-list-row"));
      const row2 = append$2(rows, $$3(".quick-input-list-row"));
      data.label = new IconLabel(row1, { supportHighlights: true, supportDescriptionHighlights: true, supportIcons: true, hoverDelegate: this.hoverDelegate });
      data.toDisposeTemplate.add(data.label);
      data.icon = prepend$2(data.label.element, $$3(".quick-input-list-icon"));
      const keybindingContainer = append$2(row1, $$3(".quick-input-list-entry-keybinding"));
      data.keybinding = new KeybindingLabel(keybindingContainer, OS);
      data.toDisposeTemplate.add(data.keybinding);
      const detailContainer = append$2(row2, $$3(".quick-input-list-label-meta"));
      data.detail = new IconLabel(detailContainer, { supportHighlights: true, supportIcons: true, hoverDelegate: this.hoverDelegate });
      data.toDisposeTemplate.add(data.detail);
      data.separator = append$2(data.entry, $$3(".quick-input-list-separator"));
      data.actionBar = new ActionBar(data.entry, this.hoverDelegate ? { hoverDelegate: this.hoverDelegate } : void 0);
      data.actionBar.domNode.classList.add("quick-input-list-entry-action-bar");
      data.toDisposeTemplate.add(data.actionBar);
      return data;
    }
    disposeTemplate(data) {
      data.toDisposeElement.dispose();
      data.toDisposeTemplate.dispose();
    }
    disposeElement(_element, _index, data) {
      data.toDisposeElement.clear();
      data.actionBar.clear();
    }
  }
  let QuickPickItemElementRenderer = (_Oa = class extends BaseQuickInputListRenderer {
    constructor(hoverDelegate, themeService) {
      super(hoverDelegate);
      this.themeService = themeService;
      this._itemsWithSeparatorsFrequency = /* @__PURE__ */ new Map();
    }
    get templateId() {
      return QuickPickItemElementRenderer_1.ID;
    }
    ensureCheckbox(element, data) {
      if (!element.hasCheckbox) {
        data.checkbox.value?.domNode.remove();
        data.checkbox.clear();
        return;
      }
      let checkbox = data.checkbox.value;
      if (!checkbox) {
        checkbox = new Checkbox(element.saneLabel, element.checked, { ...defaultCheckboxStyles, size: 15 });
        data.checkbox.value = checkbox;
        data.outerLabel.prepend(checkbox.domNode);
      } else {
        checkbox.setTitle(element.saneLabel);
      }
      if (element.checkboxDisabled) {
        checkbox.disable();
      } else {
        checkbox.enable();
      }
      checkbox.checked = element.checked;
      data.toDisposeElement.add(element.onChecked((checked) => checkbox.checked = checked));
      data.toDisposeElement.add(checkbox.onChange(() => element.checked = checkbox.checked));
    }
    renderElement(node, index, data) {
      const element = node.element;
      data.element = element;
      element.element = data.entry ?? void 0;
      const mainItem = element.item;
      element.element.classList.toggle("not-pickable", element.item.pickable === false);
      this.ensureCheckbox(element, data);
      const { labelHighlights, descriptionHighlights, detailHighlights } = element;
      if (mainItem.iconPath) {
        const icon = isDark(this.themeService.getColorTheme().type) ? mainItem.iconPath.dark : mainItem.iconPath.light ?? mainItem.iconPath.dark;
        const iconUrl = URI.revive(icon);
        data.icon.className = "quick-input-list-icon";
        data.icon.style.backgroundImage = asCSSUrl(iconUrl);
      } else {
        data.icon.style.backgroundImage = "";
        data.icon.className = mainItem.iconClass ? `quick-input-list-icon ${mainItem.iconClass}` : "";
      }
      let descriptionTitle;
      if (!element.saneTooltip && element.saneDescription) {
        descriptionTitle = {
          markdown: {
            value: escape$2(element.saneDescription),
            supportThemeIcons: true
          },
          markdownNotSupportedFallback: element.saneDescription
        };
      }
      const options = {
        matches: labelHighlights || [],
        // If we have a tooltip, we want that to be shown and not any other hover
        descriptionTitle,
        descriptionMatches: descriptionHighlights || [],
        labelEscapeNewLines: true
      };
      options.extraClasses = mainItem.iconClasses;
      options.italic = mainItem.italic;
      options.strikethrough = mainItem.strikethrough;
      data.entry.classList.remove("quick-input-list-separator-as-item");
      data.label.setLabel(element.saneLabel, element.saneDescription, options);
      data.keybinding.set(mainItem.keybinding);
      if (element.saneDetail) {
        let title;
        if (!element.saneTooltip) {
          title = {
            markdown: {
              value: escape$2(element.saneDetail),
              supportThemeIcons: true
            },
            markdownNotSupportedFallback: element.saneDetail
          };
        }
        data.detail.element.style.display = "";
        data.detail.setLabel(element.saneDetail, void 0, {
          matches: detailHighlights,
          title,
          labelEscapeNewLines: true
        });
      } else {
        data.detail.element.style.display = "none";
      }
      if (element.separator?.label) {
        data.separator.textContent = element.separator.label;
        data.separator.style.display = "";
        this.addItemWithSeparator(element);
      } else {
        data.separator.style.display = "none";
      }
      data.entry.classList.toggle("quick-input-list-separator-border", !!element.separator && element.childIndex !== 0);
      const buttons = mainItem.buttons;
      if (buttons && buttons.length) {
        data.actionBar.push(buttons.map((button, index2) => quickInputButtonToAction(button, `id-${index2}`, () => element.fireButtonTriggered({ button, item: element.item }))), { icon: true, label: false });
        data.entry.classList.add("has-actions");
      } else {
        data.entry.classList.remove("has-actions");
      }
    }
    disposeElement(element, _index, data) {
      this.removeItemWithSeparator(element.element);
      super.disposeElement(element, _index, data);
    }
    isItemWithSeparatorVisible(item) {
      return this._itemsWithSeparatorsFrequency.has(item);
    }
    addItemWithSeparator(item) {
      this._itemsWithSeparatorsFrequency.set(item, (this._itemsWithSeparatorsFrequency.get(item) || 0) + 1);
    }
    removeItemWithSeparator(item) {
      const frequency = this._itemsWithSeparatorsFrequency.get(item) || 0;
      if (frequency > 1) {
        this._itemsWithSeparatorsFrequency.set(item, frequency - 1);
      } else {
        this._itemsWithSeparatorsFrequency.delete(item);
      }
    }
  }, QuickPickItemElementRenderer_1 = _Oa, _Oa.ID = "quickpickitem", _Oa);
  QuickPickItemElementRenderer = QuickPickItemElementRenderer_1 = __decorate$e([
    __param$e(1, IThemeService)
  ], QuickPickItemElementRenderer);
  const _QuickPickSeparatorElementRenderer = class _QuickPickSeparatorElementRenderer extends BaseQuickInputListRenderer {
    constructor() {
      super(...arguments);
      this._visibleSeparatorsFrequency = /* @__PURE__ */ new Map();
    }
    get templateId() {
      return _QuickPickSeparatorElementRenderer.ID;
    }
    get visibleSeparators() {
      return [...this._visibleSeparatorsFrequency.keys()];
    }
    isSeparatorVisible(separator2) {
      return this._visibleSeparatorsFrequency.has(separator2);
    }
    renderElement(node, index, data) {
      const element = node.element;
      data.element = element;
      element.element = data.entry ?? void 0;
      element.element.classList.toggle("focus-inside", !!element.focusInsideSeparator);
      const mainItem = element.separator;
      const { labelHighlights, descriptionHighlights } = element;
      data.icon.style.backgroundImage = "";
      data.icon.className = "";
      let descriptionTitle;
      if (!element.saneTooltip && element.saneDescription) {
        descriptionTitle = {
          markdown: {
            value: escape$2(element.saneDescription),
            supportThemeIcons: true
          },
          markdownNotSupportedFallback: element.saneDescription
        };
      }
      const options = {
        matches: labelHighlights || [],
        // If we have a tooltip, we want that to be shown and not any other hover
        descriptionTitle,
        descriptionMatches: descriptionHighlights || [],
        labelEscapeNewLines: true
      };
      data.entry.classList.add("quick-input-list-separator-as-item");
      data.label.setLabel(element.saneLabel, element.saneDescription, options);
      data.separator.style.display = "none";
      data.entry.classList.add("quick-input-list-separator-border");
      const buttons = mainItem.buttons;
      if (buttons && buttons.length) {
        data.actionBar.push(buttons.map((button, index2) => quickInputButtonToAction(button, `id-${index2}`, () => element.fireSeparatorButtonTriggered({ button, separator: element.separator }))), { icon: true, label: false });
        data.entry.classList.add("has-actions");
      } else {
        data.entry.classList.remove("has-actions");
      }
      this.addSeparator(element);
    }
    disposeElement(element, _index, data) {
      this.removeSeparator(element.element);
      if (!this.isSeparatorVisible(element.element)) {
        element.element.element?.classList.remove("focus-inside");
      }
      super.disposeElement(element, _index, data);
    }
    addSeparator(separator2) {
      this._visibleSeparatorsFrequency.set(separator2, (this._visibleSeparatorsFrequency.get(separator2) || 0) + 1);
    }
    removeSeparator(separator2) {
      const frequency = this._visibleSeparatorsFrequency.get(separator2) || 0;
      if (frequency > 1) {
        this._visibleSeparatorsFrequency.set(separator2, frequency - 1);
      } else {
        this._visibleSeparatorsFrequency.delete(separator2);
      }
    }
  };
  _QuickPickSeparatorElementRenderer.ID = "quickpickseparator";
  let QuickPickSeparatorElementRenderer = _QuickPickSeparatorElementRenderer;
  let QuickInputList = class QuickInputList extends Disposable {
    constructor(parent, hoverDelegate, linkOpenerDelegate, id, instantiationService, accessibilityService) {
      super();
      this.parent = parent;
      this.hoverDelegate = hoverDelegate;
      this.linkOpenerDelegate = linkOpenerDelegate;
      this.accessibilityService = accessibilityService;
      this._onKeyDown = new Emitter$1();
      this._onLeave = new Emitter$1();
      this.onLeave = this._onLeave.event;
      this._visibleCountObservable = observableValue("VisibleCount", 0);
      this.onChangedVisibleCount = Event.fromObservable(this._visibleCountObservable, this._store);
      this._allVisibleCheckedObservable = observableValue("AllVisibleChecked", false);
      this.onChangedAllVisibleChecked = Event.fromObservable(this._allVisibleCheckedObservable, this._store);
      this._checkedCountObservable = observableValue("CheckedCount", 0);
      this.onChangedCheckedCount = Event.fromObservable(this._checkedCountObservable, this._store);
      this._checkedElementsObservable = observableValueOpts({ equalsFn: equals$1 }, new Array());
      this.onChangedCheckedElements = Event.fromObservable(this._checkedElementsObservable, this._store);
      this._onButtonTriggered = new Emitter$1();
      this.onButtonTriggered = this._onButtonTriggered.event;
      this._onSeparatorButtonTriggered = new Emitter$1();
      this.onSeparatorButtonTriggered = this._onSeparatorButtonTriggered.event;
      this._elementChecked = new Emitter$1();
      this._elementCheckedEventBufferer = new EventBufferer();
      this._hasCheckboxes = false;
      this._inputElements = new Array();
      this._elementTree = new Array();
      this._itemElements = new Array();
      this._elementDisposable = this._register(new DisposableStore());
      this._matchOnDescription = false;
      this._matchOnDetail = false;
      this._matchOnLabel = true;
      this._matchOnLabelMode = "fuzzy";
      this._sortByLabel = true;
      this._shouldLoop = true;
      this._container = append$2(this.parent, $$3(".quick-input-list"));
      this._separatorRenderer = new QuickPickSeparatorElementRenderer(hoverDelegate);
      this._itemRenderer = instantiationService.createInstance(QuickPickItemElementRenderer, hoverDelegate);
      this._tree = this._register(instantiationService.createInstance(WorkbenchObjectTree, "QuickInput", this._container, new QuickInputItemDelegate(), [this._itemRenderer, this._separatorRenderer], {
        filter: {
          filter(element) {
            return element.hidden ? 0 : element instanceof QuickPickSeparatorElement ? 2 : 1;
          }
        },
        sorter: {
          compare: (element, otherElement) => {
            if (!this.sortByLabel || !this._lastQueryString) {
              return 0;
            }
            const normalizedSearchValue = this._lastQueryString.toLowerCase();
            return compareEntries(element, otherElement, normalizedSearchValue);
          }
        },
        accessibilityProvider: new QuickInputAccessibilityProvider(),
        setRowLineHeight: false,
        multipleSelectionSupport: false,
        hideTwistiesOfChildlessElements: true,
        renderIndentGuides: RenderIndentGuides.None,
        findWidgetEnabled: false,
        indent: 0,
        horizontalScrolling: false,
        allowNonCollapsibleParents: true,
        alwaysConsumeMouseWheel: true
      }));
      this._tree.getHTMLElement().id = id;
      this._registerListeners();
    }
    //#region public getters/setters
    get onDidChangeFocus() {
      return Event.map(this._tree.onDidChangeFocus, (e) => e.elements.filter((e2) => e2 instanceof QuickPickItemElement).map((e2) => e2.item), this._store);
    }
    get onDidChangeSelection() {
      return Event.map(this._tree.onDidChangeSelection, (e) => ({
        items: e.elements.filter((e2) => e2 instanceof QuickPickItemElement).map((e2) => e2.item),
        event: e.browserEvent
      }), this._store);
    }
    get displayed() {
      return this._container.style.display !== "none";
    }
    set displayed(value) {
      this._container.style.display = value ? "" : "none";
    }
    get scrollTop() {
      return this._tree.scrollTop;
    }
    set scrollTop(scrollTop) {
      this._tree.scrollTop = scrollTop;
    }
    get ariaLabel() {
      return this._tree.ariaLabel;
    }
    set ariaLabel(label) {
      this._tree.ariaLabel = label ?? "";
    }
    set enabled(value) {
      this._tree.getHTMLElement().style.pointerEvents = value ? "" : "none";
    }
    get matchOnDescription() {
      return this._matchOnDescription;
    }
    set matchOnDescription(value) {
      this._matchOnDescription = value;
    }
    get matchOnDetail() {
      return this._matchOnDetail;
    }
    set matchOnDetail(value) {
      this._matchOnDetail = value;
    }
    get matchOnLabel() {
      return this._matchOnLabel;
    }
    set matchOnLabel(value) {
      this._matchOnLabel = value;
    }
    get matchOnLabelMode() {
      return this._matchOnLabelMode;
    }
    set matchOnLabelMode(value) {
      this._matchOnLabelMode = value;
    }
    get sortByLabel() {
      return this._sortByLabel;
    }
    set sortByLabel(value) {
      this._sortByLabel = value;
    }
    get shouldLoop() {
      return this._shouldLoop;
    }
    set shouldLoop(value) {
      this._shouldLoop = value;
    }
    //#endregion
    //#region register listeners
    _registerListeners() {
      this._registerOnKeyDown();
      this._registerOnContainerClick();
      this._registerOnMouseMiddleClick();
      this._registerOnTreeModelChanged();
      this._registerOnElementChecked();
      this._registerOnContextMenu();
      this._registerHoverListeners();
      this._registerSelectionChangeListener();
      this._registerSeparatorActionShowingListeners();
    }
    _registerOnKeyDown() {
      this._register(this._tree.onKeyDown((e) => {
        const event = new StandardKeyboardEvent(e);
        switch (event.keyCode) {
          case 10:
            this.toggleCheckbox();
            break;
        }
        this._onKeyDown.fire(event);
      }));
    }
    _registerOnContainerClick() {
      this._register(addDisposableListener(this._container, EventType$1.CLICK, (e) => {
        if (e.x || e.y) {
          this._onLeave.fire();
        }
      }));
    }
    _registerOnMouseMiddleClick() {
      this._register(addDisposableListener(this._container, EventType$1.AUXCLICK, (e) => {
        if (e.button === 1) {
          this._onLeave.fire();
        }
      }));
    }
    _registerOnTreeModelChanged() {
      this._register(this._tree.onDidChangeModel(() => {
        const visibleCount = this._itemElements.filter((e) => !e.hidden).length;
        this._visibleCountObservable.set(visibleCount, void 0);
        if (this._hasCheckboxes) {
          this._updateCheckedObservables();
        }
      }));
    }
    _registerOnElementChecked() {
      this._register(this._elementCheckedEventBufferer.wrapEvent(this._elementChecked.event, (_, e) => e)((_) => this._updateCheckedObservables()));
    }
    _registerOnContextMenu() {
      this._register(this._tree.onContextMenu((e) => {
        if (e.element) {
          e.browserEvent.preventDefault();
          this._tree.setSelection([e.element]);
        }
      }));
    }
    _registerHoverListeners() {
      const delayer2 = this._register(new ThrottledDelayer(typeof this.hoverDelegate.delay === "function" ? this.hoverDelegate.delay() : this.hoverDelegate.delay));
      this._register(this._tree.onMouseOver(async (e) => {
        if (isHTMLAnchorElement(e.browserEvent.target)) {
          delayer2.cancel();
          return;
        }
        if (
          // anchors are an exception as called out above so we skip them here
          !isHTMLAnchorElement(e.browserEvent.relatedTarget) && // check if the mouse is still over the same element
          isAncestor$1(e.browserEvent.relatedTarget, e.element?.element)
        ) {
          return;
        }
        try {
          await delayer2.trigger(async () => {
            if (e.element instanceof QuickPickItemElement) {
              this.showHover(e.element);
            }
          });
        } catch (e2) {
          if (!isCancellationError(e2)) {
            throw e2;
          }
        }
      }));
      this._register(this._tree.onMouseOut((e) => {
        if (isAncestor$1(e.browserEvent.relatedTarget, e.element?.element)) {
          return;
        }
        delayer2.cancel();
      }));
    }
    /**
     * Register's focus change and mouse events so that we can track when items inside of a
     * separator's section are focused or hovered so that we can display the separator's actions
     */
    _registerSeparatorActionShowingListeners() {
      this._register(this._tree.onDidChangeFocus((e) => {
        const parent = e.elements[0] ? this._tree.getParentElement(e.elements[0]) : null;
        for (const separator2 of this._separatorRenderer.visibleSeparators) {
          const value = separator2 === parent;
          const currentActive = !!(separator2.focusInsideSeparator & QuickPickSeparatorFocusReason.ACTIVE_ITEM);
          if (currentActive !== value) {
            if (value) {
              separator2.focusInsideSeparator |= QuickPickSeparatorFocusReason.ACTIVE_ITEM;
            } else {
              separator2.focusInsideSeparator &= ~QuickPickSeparatorFocusReason.ACTIVE_ITEM;
            }
            this._tree.rerender(separator2);
          }
        }
      }));
      this._register(this._tree.onMouseOver((e) => {
        const parent = e.element ? this._tree.getParentElement(e.element) : null;
        for (const separator2 of this._separatorRenderer.visibleSeparators) {
          if (separator2 !== parent) {
            continue;
          }
          const currentMouse = !!(separator2.focusInsideSeparator & QuickPickSeparatorFocusReason.MOUSE_HOVER);
          if (!currentMouse) {
            separator2.focusInsideSeparator |= QuickPickSeparatorFocusReason.MOUSE_HOVER;
            this._tree.rerender(separator2);
          }
        }
      }));
      this._register(this._tree.onMouseOut((e) => {
        const parent = e.element ? this._tree.getParentElement(e.element) : null;
        for (const separator2 of this._separatorRenderer.visibleSeparators) {
          if (separator2 !== parent) {
            continue;
          }
          const currentMouse = !!(separator2.focusInsideSeparator & QuickPickSeparatorFocusReason.MOUSE_HOVER);
          if (currentMouse) {
            separator2.focusInsideSeparator &= ~QuickPickSeparatorFocusReason.MOUSE_HOVER;
            this._tree.rerender(separator2);
          }
        }
      }));
    }
    _registerSelectionChangeListener() {
      this._register(this._tree.onDidChangeSelection((e) => {
        const elementsWithoutSeparators = e.elements.filter((e2) => e2 instanceof QuickPickItemElement);
        if (elementsWithoutSeparators.length !== e.elements.length) {
          if (e.elements.length === 1 && e.elements[0] instanceof QuickPickSeparatorElement) {
            this._tree.setFocus([e.elements[0].children[0]]);
            this._tree.reveal(e.elements[0], 0);
          }
          this._tree.setSelection(elementsWithoutSeparators);
        }
      }));
    }
    //#endregion
    //#region public methods
    setAllVisibleChecked(checked) {
      this._elementCheckedEventBufferer.bufferEvents(() => {
        this._itemElements.forEach((element) => {
          if (!element.hidden && !element.checkboxDisabled && element.item.pickable !== false) {
            element.checked = checked;
          }
        });
      });
    }
    setElements(inputElements) {
      this._elementDisposable.clear();
      this._lastQueryString = void 0;
      this._inputElements = inputElements;
      this._hasCheckboxes = this.parent.classList.contains("show-checkboxes");
      let currentSeparatorElement;
      this._itemElements = new Array();
      this._elementTree = inputElements.reduce((result, item, index) => {
        let element;
        if (item.type === "separator") {
          if (!item.buttons) {
            return result;
          }
          currentSeparatorElement = new QuickPickSeparatorElement(index, (e) => this._onSeparatorButtonTriggered.fire(e), item);
          element = currentSeparatorElement;
        } else {
          const previous = index > 0 ? inputElements[index - 1] : void 0;
          let separator2;
          if (previous && previous.type === "separator" && !previous.buttons) {
            separator2 = previous;
          }
          const qpi = new QuickPickItemElement(index, currentSeparatorElement?.children ? currentSeparatorElement.children.length : index, this._hasCheckboxes && item.pickable !== false, (e) => this._onButtonTriggered.fire(e), this._elementChecked, item, separator2);
          this._itemElements.push(qpi);
          if (currentSeparatorElement) {
            currentSeparatorElement.children.push(qpi);
            return result;
          }
          element = qpi;
        }
        result.push(element);
        return result;
      }, new Array());
      this._setElementsToTree(this._elementTree);
      if (this.accessibilityService.isScreenReaderOptimized()) {
        setTimeout(() => {
          const focusedElement = this._tree.getHTMLElement().querySelector(`.monaco-list-row.focused`);
          const parent = focusedElement?.parentNode;
          if (focusedElement && parent) {
            const nextSibling = focusedElement.nextSibling;
            focusedElement.remove();
            parent.insertBefore(focusedElement, nextSibling);
          }
        }, 0);
      }
    }
    setFocusedElements(items) {
      const elements = items.map((item) => this._itemElements.find((e) => e.item === item)).filter((e) => !!e).filter((e) => !e.hidden);
      this._tree.setFocus(elements);
      if (items.length > 0) {
        const focused = this._tree.getFocus()[0];
        if (focused) {
          this._tree.reveal(focused);
        }
      }
    }
    getActiveDescendant() {
      return this._tree.getHTMLElement().getAttribute("aria-activedescendant");
    }
    setSelectedElements(items) {
      const elements = items.map((item) => this._itemElements.find((e) => e.item === item)).filter((e) => !!e);
      this._tree.setSelection(elements);
    }
    getCheckedElements() {
      return this._itemElements.filter((e) => e.checked).map((e) => e.item);
    }
    setCheckedElements(items) {
      this._elementCheckedEventBufferer.bufferEvents(() => {
        const checked = /* @__PURE__ */ new Set();
        for (const item of items) {
          checked.add(item);
        }
        for (const element of this._itemElements) {
          element.checked = checked.has(element.item);
        }
      });
    }
    focus(what) {
      if (!this._itemElements.length) {
        return;
      }
      if (what === QuickPickFocus.Second && this._itemElements.length < 2) {
        what = QuickPickFocus.First;
      }
      switch (what) {
        case QuickPickFocus.First:
          this._tree.scrollTop = 0;
          this._tree.focusFirst(void 0, (e) => e.element instanceof QuickPickItemElement);
          break;
        case QuickPickFocus.Second: {
          this._tree.scrollTop = 0;
          let isSecondItem = false;
          this._tree.focusFirst(void 0, (e) => {
            if (!(e.element instanceof QuickPickItemElement)) {
              return false;
            }
            if (isSecondItem) {
              return true;
            }
            isSecondItem = !isSecondItem;
            return false;
          });
          break;
        }
        case QuickPickFocus.Last:
          this._tree.scrollTop = this._tree.scrollHeight;
          this._tree.focusLast(void 0, (e) => e.element instanceof QuickPickItemElement);
          break;
        case QuickPickFocus.Next: {
          const prevFocus = this._tree.getFocus();
          this._tree.focusNext(void 0, this._shouldLoop, void 0, (e) => {
            if (!(e.element instanceof QuickPickItemElement)) {
              return false;
            }
            this._tree.reveal(e.element);
            return true;
          });
          const currentFocus = this._tree.getFocus();
          if (prevFocus.length && prevFocus[0] === currentFocus[0]) {
            this._onLeave.fire();
          }
          break;
        }
        case QuickPickFocus.Previous: {
          const prevFocus = this._tree.getFocus();
          this._tree.focusPrevious(void 0, this._shouldLoop, void 0, (e) => {
            if (!(e.element instanceof QuickPickItemElement)) {
              return false;
            }
            const parent = this._tree.getParentElement(e.element);
            if (parent === null || parent.children[0] !== e.element) {
              this._tree.reveal(e.element);
            } else {
              this._tree.reveal(parent);
            }
            return true;
          });
          const currentFocus = this._tree.getFocus();
          if (prevFocus.length && prevFocus[0] === currentFocus[0]) {
            this._onLeave.fire();
          }
          break;
        }
        case QuickPickFocus.NextPage:
          this._tree.focusNextPage(void 0, (e) => {
            if (!(e.element instanceof QuickPickItemElement)) {
              return false;
            }
            this._tree.reveal(e.element);
            return true;
          });
          break;
        case QuickPickFocus.PreviousPage:
          this._tree.focusPreviousPage(void 0, (e) => {
            if (!(e.element instanceof QuickPickItemElement)) {
              return false;
            }
            const parent = this._tree.getParentElement(e.element);
            if (parent === null || parent.children[0] !== e.element) {
              this._tree.reveal(e.element);
            } else {
              this._tree.reveal(parent);
            }
            return true;
          });
          break;
        case QuickPickFocus.NextSeparator: {
          let foundSeparatorAsItem = false;
          const before = this._tree.getFocus()[0];
          this._tree.focusNext(void 0, true, void 0, (e) => {
            if (foundSeparatorAsItem) {
              return true;
            }
            if (e.element instanceof QuickPickSeparatorElement) {
              foundSeparatorAsItem = true;
              if (this._separatorRenderer.isSeparatorVisible(e.element)) {
                this._tree.reveal(e.element.children[0]);
              } else {
                this._tree.reveal(e.element, 0);
              }
            } else if (e.element instanceof QuickPickItemElement) {
              if (e.element.separator) {
                if (this._itemRenderer.isItemWithSeparatorVisible(e.element)) {
                  this._tree.reveal(e.element);
                } else {
                  this._tree.reveal(e.element, 0);
                }
                return true;
              } else if (e.element === this._elementTree[0]) {
                this._tree.reveal(e.element, 0);
                return true;
              }
            }
            return false;
          });
          const after2 = this._tree.getFocus()[0];
          if (before === after2) {
            this._tree.scrollTop = this._tree.scrollHeight;
            this._tree.focusLast(void 0, (e) => e.element instanceof QuickPickItemElement);
          }
          break;
        }
        case QuickPickFocus.PreviousSeparator: {
          let focusElement;
          let foundSeparator = !!this._tree.getFocus()[0]?.separator;
          this._tree.focusPrevious(void 0, true, void 0, (e) => {
            if (e.element instanceof QuickPickSeparatorElement) {
              if (foundSeparator) {
                if (!focusElement) {
                  if (this._separatorRenderer.isSeparatorVisible(e.element)) {
                    this._tree.reveal(e.element);
                  } else {
                    this._tree.reveal(e.element, 0);
                  }
                  focusElement = e.element.children[0];
                }
              } else {
                foundSeparator = true;
              }
            } else if (e.element instanceof QuickPickItemElement) {
              if (!focusElement) {
                if (e.element.separator) {
                  if (this._itemRenderer.isItemWithSeparatorVisible(e.element)) {
                    this._tree.reveal(e.element);
                  } else {
                    this._tree.reveal(e.element, 0);
                  }
                  focusElement = e.element;
                } else if (e.element === this._elementTree[0]) {
                  this._tree.reveal(e.element, 0);
                  return true;
                }
              }
            }
            return false;
          });
          if (focusElement) {
            this._tree.setFocus([focusElement]);
          }
          break;
        }
      }
    }
    clearFocus() {
      this._tree.setFocus([]);
    }
    domFocus() {
      this._tree.domFocus();
    }
    layout(maxHeight) {
      this._tree.getHTMLElement().style.maxHeight = maxHeight ? `${// Make sure height aligns with list item heights
      Math.floor(maxHeight / 44) * 44 + 6}px` : "";
      this._tree.layout();
    }
    filter(query) {
      this._lastQueryString = query;
      if (!(this._sortByLabel || this._matchOnLabel || this._matchOnDescription || this._matchOnDetail)) {
        this._tree.layout();
        return false;
      }
      const queryWithWhitespace = query;
      query = query.trim();
      if (!query || !(this.matchOnLabel || this.matchOnDescription || this.matchOnDetail)) {
        this._itemElements.forEach((element) => {
          element.labelHighlights = void 0;
          element.descriptionHighlights = void 0;
          element.detailHighlights = void 0;
          element.hidden = false;
          const previous = element.index && this._inputElements[element.index - 1];
          if (element.item) {
            element.separator = previous && previous.type === "separator" && !previous.buttons ? previous : void 0;
          }
        });
      } else {
        let currentSeparator;
        this._itemElements.forEach((element) => {
          let labelHighlights;
          if (this.matchOnLabelMode === "fuzzy") {
            labelHighlights = this.matchOnLabel ? matchesFuzzyIconAware(query, parseLabelWithIcons(element.saneLabel)) ?? void 0 : void 0;
          } else {
            labelHighlights = this.matchOnLabel ? matchesContiguousIconAware(queryWithWhitespace, parseLabelWithIcons(element.saneLabel)) ?? void 0 : void 0;
          }
          const descriptionHighlights = this.matchOnDescription ? matchesFuzzyIconAware(query, parseLabelWithIcons(element.saneDescription || "")) ?? void 0 : void 0;
          const detailHighlights = this.matchOnDetail ? matchesFuzzyIconAware(query, parseLabelWithIcons(element.saneDetail || "")) ?? void 0 : void 0;
          if (labelHighlights || descriptionHighlights || detailHighlights) {
            element.labelHighlights = labelHighlights;
            element.descriptionHighlights = descriptionHighlights;
            element.detailHighlights = detailHighlights;
            element.hidden = false;
          } else {
            element.labelHighlights = void 0;
            element.descriptionHighlights = void 0;
            element.detailHighlights = void 0;
            element.hidden = element.item ? !element.item.alwaysShow : true;
          }
          if (element.item) {
            element.separator = void 0;
          } else if (element.separator) {
            element.hidden = true;
          }
          if (!this.sortByLabel) {
            const previous = element.index && this._inputElements[element.index - 1] || void 0;
            if (previous?.type === "separator" && !previous.buttons) {
              currentSeparator = previous;
            }
            if (currentSeparator && !element.hidden) {
              element.separator = currentSeparator;
              currentSeparator = void 0;
            }
          }
        });
      }
      this._setElementsToTree(this._sortByLabel && query ? this._itemElements : this._elementTree);
      this._tree.layout();
      return true;
    }
    toggleCheckbox() {
      this._elementCheckedEventBufferer.bufferEvents(() => {
        const elements = this._tree.getFocus().filter((e) => e instanceof QuickPickItemElement);
        const allChecked = this._allVisibleChecked(elements);
        for (const element of elements) {
          if (!element.checkboxDisabled) {
            element.checked = !allChecked;
          }
        }
      });
    }
    style(styles) {
      this._tree.style(styles);
    }
    toggleHover() {
      const focused = this._tree.getFocus()[0];
      if (!focused?.saneTooltip || !(focused instanceof QuickPickItemElement)) {
        return;
      }
      if (this._lastHover && !this._lastHover.isDisposed) {
        this._lastHover.dispose();
        return;
      }
      this.showHover(focused);
      const store = new DisposableStore();
      store.add(this._tree.onDidChangeFocus((e) => {
        if (e.elements[0] instanceof QuickPickItemElement) {
          this.showHover(e.elements[0]);
        }
      }));
      if (this._lastHover) {
        store.add(this._lastHover);
      }
      this._elementDisposable.add(store);
    }
    //#endregion
    //#region private methods
    _setElementsToTree(elements) {
      const treeElements = new Array();
      for (const element of elements) {
        if (element instanceof QuickPickSeparatorElement) {
          treeElements.push({
            element,
            collapsible: false,
            collapsed: false,
            children: element.children.map((e) => ({
              element: e,
              collapsible: false,
              collapsed: false
            }))
          });
        } else {
          treeElements.push({
            element,
            collapsible: false,
            collapsed: false
          });
        }
      }
      this._tree.setChildren(null, treeElements);
    }
    _allVisibleChecked(elements, whenNoneVisible = true) {
      for (let i2 = 0, n2 = elements.length; i2 < n2; i2++) {
        const element = elements[i2];
        if (!element.hidden && element.item.pickable !== false) {
          if (!element.checked) {
            return false;
          } else {
            whenNoneVisible = true;
          }
        }
      }
      return whenNoneVisible;
    }
    _updateCheckedObservables() {
      transaction((tx) => {
        this._allVisibleCheckedObservable.set(this._allVisibleChecked(this._itemElements, false), tx);
        const checkedCount = this._itemElements.filter((element) => element.checked).length;
        this._checkedCountObservable.set(checkedCount, tx);
        this._checkedElementsObservable.set(this.getCheckedElements(), tx);
      });
    }
    /**
     * Disposes of the hover and shows a new one for the given index if it has a tooltip.
     * @param element The element to show the hover for
     */
    showHover(element) {
      if (this._lastHover && !this._lastHover.isDisposed) {
        this.hoverDelegate.onDidHideHover?.();
        this._lastHover?.dispose();
      }
      if (!element.element || !element.saneTooltip) {
        return;
      }
      this._lastHover = this.hoverDelegate.showHover({
        content: element.saneTooltip,
        target: element.element,
        linkHandler: (url) => {
          this.linkOpenerDelegate(url);
        },
        appearance: {
          showPointer: true
        },
        container: this._container,
        position: {
          hoverPosition: 1
          /* HoverPosition.RIGHT */
        }
      }, false);
    }
  };
  __decorate$e([
    memoize
  ], QuickInputList.prototype, "onDidChangeFocus", null);
  __decorate$e([
    memoize
  ], QuickInputList.prototype, "onDidChangeSelection", null);
  QuickInputList = __decorate$e([
    __param$e(4, IInstantiationService),
    __param$e(5, IAccessibilityService)
  ], QuickInputList);
  function matchesContiguousIconAware(query, target) {
    const { text: text2, iconOffsets } = target;
    if (!iconOffsets || iconOffsets.length === 0) {
      return matchesContiguous(query, text2);
    }
    const wordToMatchAgainstWithoutIconsTrimmed = ltrim(text2, " ");
    const leadingWhitespaceOffset = text2.length - wordToMatchAgainstWithoutIconsTrimmed.length;
    const matches = matchesContiguous(query, wordToMatchAgainstWithoutIconsTrimmed);
    if (matches) {
      for (const match2 of matches) {
        const iconOffset = iconOffsets[match2.start + leadingWhitespaceOffset] + leadingWhitespaceOffset;
        match2.start += iconOffset;
        match2.end += iconOffset;
      }
    }
    return matches;
  }
  function matchesContiguous(word, wordToMatchAgainst) {
    const matchIndex = wordToMatchAgainst.toLowerCase().indexOf(word.toLowerCase());
    if (matchIndex !== -1) {
      return [{ start: matchIndex, end: matchIndex + word.length }];
    }
    return null;
  }
  function compareEntries(elementA, elementB, lookFor) {
    const labelHighlightsA = elementA.labelHighlights || [];
    const labelHighlightsB = elementB.labelHighlights || [];
    if (labelHighlightsA.length && !labelHighlightsB.length) {
      return -1;
    }
    if (!labelHighlightsA.length && labelHighlightsB.length) {
      return 1;
    }
    if (labelHighlightsA.length === 0 && labelHighlightsB.length === 0) {
      return 0;
    }
    return compareAnything(elementA.saneSortLabel, elementB.saneSortLabel, lookFor);
  }
  function registerQuickInputCommandAndKeybindingRule(rule, options = {}) {
    KeybindingsRegistry.registerCommandAndKeybindingRule({
      weight: 200,
      when: inQuickInputContext,
      metadata: { description: localize(1758, "Used while in the context of any kind of quick input. If you change one keybinding for this command, you should change all of the other keybindings (modifier variants) of this command as well.") },
      ...rule,
      secondary: getSecondary(rule.primary, rule.secondary ?? [], options)
    });
  }
  function registerQuickPickCommandAndKeybindingRule(rule, options = {}) {
    KeybindingsRegistry.registerCommandAndKeybindingRule({
      weight: 200,
      when: ContextKeyExpr.and(ContextKeyExpr.or(
        // Only things that use Tree widgets
        ContextKeyExpr.equals(
          quickInputTypeContextKeyValue,
          "quickPick"
          /* QuickInputType.QuickPick */
        ),
        ContextKeyExpr.equals(
          quickInputTypeContextKeyValue,
          "quickTree"
          /* QuickInputType.QuickTree */
        )
      ), inQuickInputContext),
      metadata: { description: localize(1759, "Used while in the context of the quick pick. If you change one keybinding for this command, you should change all of the other keybindings (modifier variants) of this command as well.") },
      ...rule,
      secondary: getSecondary(rule.primary, rule.secondary ?? [], options)
    });
  }
  const ctrlKeyMod = isMacintosh ? 256 : 2048;
  function getSecondary(primary, secondary, options = {}) {
    if (options.withAltMod) {
      secondary.push(512 + primary);
    }
    if (options.withCtrlMod) {
      secondary.push(ctrlKeyMod + primary);
      if (options.withAltMod) {
        secondary.push(512 + ctrlKeyMod + primary);
      }
    }
    if (options.withCmdMod && isMacintosh) {
      secondary.push(2048 + primary);
      if (options.withCtrlMod) {
        secondary.push(2048 + 256 + primary);
      }
      if (options.withAltMod) {
        secondary.push(2048 + 512 + primary);
        if (options.withCtrlMod) {
          secondary.push(2048 + 512 + 256 + primary);
        }
      }
    }
    return secondary;
  }
  function focusHandler(focus, focusOnQuickNatigate) {
    return (accessor) => {
      const currentQuickPick = accessor.get(IQuickInputService).currentQuickInput;
      if (!currentQuickPick) {
        return;
      }
      if (focusOnQuickNatigate && currentQuickPick.quickNavigate) {
        return currentQuickPick.focus(focusOnQuickNatigate);
      }
      return currentQuickPick.focus(focus);
    };
  }
  registerQuickPickCommandAndKeybindingRule({ id: "quickInput.pageNext", primary: 12, handler: focusHandler(QuickPickFocus.NextPage) }, { withAltMod: true, withCtrlMod: true, withCmdMod: true });
  registerQuickPickCommandAndKeybindingRule({ id: "quickInput.pagePrevious", primary: 11, handler: focusHandler(QuickPickFocus.PreviousPage) }, { withAltMod: true, withCtrlMod: true, withCmdMod: true });
  registerQuickPickCommandAndKeybindingRule({ id: "quickInput.first", primary: ctrlKeyMod + 14, handler: focusHandler(QuickPickFocus.First) }, { withAltMod: true, withCmdMod: true });
  registerQuickPickCommandAndKeybindingRule({ id: "quickInput.last", primary: ctrlKeyMod + 13, handler: focusHandler(QuickPickFocus.Last) }, { withAltMod: true, withCmdMod: true });
  registerQuickPickCommandAndKeybindingRule({ id: "quickInput.next", primary: 18, handler: focusHandler(QuickPickFocus.Next) }, { withCtrlMod: true });
  registerQuickPickCommandAndKeybindingRule({ id: "quickInput.previous", primary: 16, handler: focusHandler(QuickPickFocus.Previous) }, { withCtrlMod: true });
  const nextSeparatorFallbackDesc = localize(1760, "If we're in quick access mode, this will navigate to the next item. If we are not in quick access mode, this will navigate to the next separator.");
  const prevSeparatorFallbackDesc = localize(1761, "If we're in quick access mode, this will navigate to the previous item. If we are not in quick access mode, this will navigate to the previous separator.");
  if (isMacintosh) {
    registerQuickPickCommandAndKeybindingRule({
      id: "quickInput.nextSeparatorWithQuickAccessFallback",
      primary: 2048 + 18,
      handler: focusHandler(QuickPickFocus.NextSeparator, QuickPickFocus.Next),
      metadata: { description: nextSeparatorFallbackDesc }
    });
    registerQuickPickCommandAndKeybindingRule({
      id: "quickInput.nextSeparator",
      primary: 2048 + 512 + 18,
      // Since macOS has the cmd key as the primary modifier, we need to add this additional
      // keybinding to capture cmd+ctrl+upArrow
      secondary: [
        2048 + 256 + 18
        /* KeyCode.DownArrow */
      ],
      handler: focusHandler(QuickPickFocus.NextSeparator)
    }, { withCtrlMod: true });
    registerQuickPickCommandAndKeybindingRule({
      id: "quickInput.previousSeparatorWithQuickAccessFallback",
      primary: 2048 + 16,
      handler: focusHandler(QuickPickFocus.PreviousSeparator, QuickPickFocus.Previous),
      metadata: { description: prevSeparatorFallbackDesc }
    });
    registerQuickPickCommandAndKeybindingRule({
      id: "quickInput.previousSeparator",
      primary: 2048 + 512 + 16,
      // Since macOS has the cmd key as the primary modifier, we need to add this additional
      // keybinding to capture cmd+ctrl+upArrow
      secondary: [
        2048 + 256 + 16
        /* KeyCode.UpArrow */
      ],
      handler: focusHandler(QuickPickFocus.PreviousSeparator)
    }, { withCtrlMod: true });
  } else {
    registerQuickPickCommandAndKeybindingRule({
      id: "quickInput.nextSeparatorWithQuickAccessFallback",
      primary: 512 + 18,
      handler: focusHandler(QuickPickFocus.NextSeparator, QuickPickFocus.Next),
      metadata: { description: nextSeparatorFallbackDesc }
    });
    registerQuickPickCommandAndKeybindingRule({
      id: "quickInput.nextSeparator",
      primary: 2048 + 512 + 18,
      handler: focusHandler(QuickPickFocus.NextSeparator)
    });
    registerQuickPickCommandAndKeybindingRule({
      id: "quickInput.previousSeparatorWithQuickAccessFallback",
      primary: 512 + 16,
      handler: focusHandler(QuickPickFocus.PreviousSeparator, QuickPickFocus.Previous),
      metadata: { description: prevSeparatorFallbackDesc }
    });
    registerQuickPickCommandAndKeybindingRule({
      id: "quickInput.previousSeparator",
      primary: 2048 + 512 + 16,
      handler: focusHandler(QuickPickFocus.PreviousSeparator)
    });
  }
  KeybindingsRegistry.registerCommandAndKeybindingRule({
    id: "quickInput.accept",
    primary: 3,
    weight: 200,
    when: ContextKeyExpr.and(
      // All other kinds of Quick things handle Accept, except Widget. In other words, Accepting is a detail on the things
      // that extend IQuickInput
      ContextKeyExpr.notEquals(
        quickInputTypeContextKeyValue,
        "quickWidget"
        /* QuickInputType.QuickWidget */
      ),
      inQuickInputContext,
      ContextKeyExpr.not("isComposing")
    ),
    metadata: { description: localize(1762, "Used while in the context of some quick input. If you change one keybinding for this command, you should change all of the other keybindings (modifier variants) of this command as well.") },
    handler: (accessor) => {
      const currentQuickPick = accessor.get(IQuickInputService).currentQuickInput;
      currentQuickPick?.accept();
    },
    secondary: getSecondary(3, [], { withAltMod: true, withCtrlMod: true, withCmdMod: true })
  });
  registerQuickPickCommandAndKeybindingRule({
    id: "quickInput.acceptInBackground",
    // If we are in the quick pick but the input box is not focused or our cursor is at the end of the input box
    when: ContextKeyExpr.and(inQuickInputContext, ContextKeyExpr.equals(
      quickInputTypeContextKeyValue,
      "quickPick"
      /* QuickInputType.QuickPick */
    ), ContextKeyExpr.or(InputFocusedContext.negate(), endOfQuickInputBoxContext)),
    primary: 17,
    // Need a little extra weight to ensure this keybinding is preferred over the default cmd+alt+right arrow keybinding
    // https://github.com/microsoft/vscode/blob/1451e4fbbbf074a4355cc537c35b547b80ce1c52/src/vs/workbench/browser/parts/editor/editorActions.ts#L1178-L1195
    weight: 200 + 50,
    handler: (accessor) => {
      const currentQuickPick = accessor.get(IQuickInputService).currentQuickInput;
      currentQuickPick?.accept(true);
    }
  }, { withAltMod: true, withCtrlMod: true, withCmdMod: true });
  registerQuickInputCommandAndKeybindingRule({
    id: "quickInput.hide",
    primary: 9,
    handler: (accessor) => {
      const currentQuickPick = accessor.get(IQuickInputService).currentQuickInput;
      currentQuickPick?.hide();
    }
  }, { withAltMod: true, withCtrlMod: true, withCmdMod: true });
  registerQuickPickCommandAndKeybindingRule({
    id: "quickInput.toggleHover",
    primary: ctrlKeyMod | 10,
    handler: (accessor) => {
      const quickInputService = accessor.get(IQuickInputService);
      quickInputService.toggleHover();
    }
  });
  var __decorate$d = 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$d = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  var QuickInputTreeRenderer_1;
  const $$2 = $$l;
  let QuickInputTreeRenderer = (_Pa = class extends Disposable {
    constructor(_hoverDelegate, _buttonTriggeredEmitter, onCheckedEvent, _themeService) {
      super();
      this._hoverDelegate = _hoverDelegate;
      this._buttonTriggeredEmitter = _buttonTriggeredEmitter;
      this.onCheckedEvent = onCheckedEvent;
      this._themeService = _themeService;
      this.templateId = QuickInputTreeRenderer_1.ID;
    }
    renderTemplate(container) {
      const store = new DisposableStore();
      const entry = append$2(container, $$2(".quick-input-tree-entry"));
      const checkbox = store.add(new TriStateCheckbox("", false, { ...defaultCheckboxStyles, size: 15 }));
      entry.appendChild(checkbox.domNode);
      const checkboxLabel = append$2(entry, $$2("label.quick-input-tree-label"));
      const rows = append$2(checkboxLabel, $$2(".quick-input-tree-rows"));
      const row1 = append$2(rows, $$2(".quick-input-tree-row"));
      const icon = prepend$2(row1, $$2(".quick-input-tree-icon"));
      const label = store.add(new IconLabel(row1, {
        supportHighlights: true,
        supportDescriptionHighlights: true,
        supportIcons: true,
        hoverDelegate: this._hoverDelegate
      }));
      const actionBar2 = store.add(new ActionBar(entry, this._hoverDelegate ? { hoverDelegate: this._hoverDelegate } : void 0));
      actionBar2.domNode.classList.add("quick-input-tree-entry-action-bar");
      return {
        toDisposeTemplate: store,
        entry,
        checkbox,
        icon,
        label,
        actionBar: actionBar2,
        toDisposeElement: new DisposableStore()
      };
    }
    renderElement(node, index, templateData, _details) {
      const store = templateData.toDisposeElement;
      const quickTreeItem = node.element;
      if (quickTreeItem.pickable === false) {
        templateData.checkbox.domNode.style.display = "none";
      } else {
        templateData.checkbox.domNode.style.display = "";
        templateData.checkbox.checked = quickTreeItem.checked ?? false;
        store.add(Event.filter(this.onCheckedEvent, (e) => e.item === quickTreeItem)((e) => templateData.checkbox.checked = e.checked));
        if (quickTreeItem.disabled) {
          templateData.checkbox.disable();
        }
      }
      if (quickTreeItem.iconPath) {
        const icon = isDark(this._themeService.getColorTheme().type) ? quickTreeItem.iconPath.dark : quickTreeItem.iconPath.light ?? quickTreeItem.iconPath.dark;
        const iconUrl = URI.revive(icon);
        templateData.icon.className = "quick-input-tree-icon";
        templateData.icon.style.backgroundImage = asCSSUrl(iconUrl);
      } else {
        templateData.icon.style.backgroundImage = "";
        templateData.icon.className = quickTreeItem.iconClass ? `quick-input-tree-icon ${quickTreeItem.iconClass}` : "";
      }
      const { labelHighlights: matches, descriptionHighlights: descriptionMatches } = node.filterData || {};
      let descriptionTitle;
      if (quickTreeItem.description) {
        descriptionTitle = {
          markdown: {
            value: escape$2(quickTreeItem.description),
            supportThemeIcons: true
          },
          markdownNotSupportedFallback: quickTreeItem.description
        };
      }
      templateData.label.setLabel(quickTreeItem.label, quickTreeItem.description, {
        matches,
        descriptionMatches,
        extraClasses: quickTreeItem.iconClasses,
        italic: quickTreeItem.italic,
        strikethrough: quickTreeItem.strikethrough,
        labelEscapeNewLines: true,
        descriptionTitle
      });
      const buttons = quickTreeItem.buttons;
      if (buttons && buttons.length) {
        templateData.actionBar.push(buttons.map((button, index2) => quickInputButtonToAction(button, `tree-${index2}`, () => this._buttonTriggeredEmitter.fire({ item: quickTreeItem, button }))), { icon: true, label: false });
        templateData.entry.classList.add("has-actions");
      } else {
        templateData.entry.classList.remove("has-actions");
      }
    }
    disposeElement(_element, _index, templateData, _details) {
      templateData.toDisposeElement.clear();
      templateData.actionBar.clear();
    }
    disposeTemplate(templateData) {
      templateData.toDisposeElement.dispose();
      templateData.toDisposeTemplate.dispose();
    }
  }, QuickInputTreeRenderer_1 = _Pa, _Pa.ID = "quickInputTreeElement", _Pa);
  QuickInputTreeRenderer = QuickInputTreeRenderer_1 = __decorate$d([
    __param$d(3, IThemeService)
  ], QuickInputTreeRenderer);
  class QuickInputTreeDelegate {
    getHeight(_element) {
      return 22;
    }
    getTemplateId(_element) {
      return QuickInputTreeRenderer.ID;
    }
  }
  function getParentNodeState(parentChildren) {
    let containsChecks = false;
    let containsUnchecks = false;
    let containsMixed = false;
    for (const element of parentChildren) {
      switch (element.element?.checked) {
        case "mixed":
          containsMixed = true;
          break;
        case true:
          containsChecks = true;
          break;
        default:
          containsUnchecks = true;
          break;
      }
      if (containsChecks && containsUnchecks && containsMixed) {
        break;
      }
    }
    const newState = containsUnchecks ? containsMixed ? "mixed" : containsChecks ? "mixed" : false : containsMixed ? "mixed" : containsChecks;
    return newState;
  }
  class QuickTreeAccessibilityProvider {
    constructor(onCheckedEvent) {
      this.onCheckedEvent = onCheckedEvent;
    }
    getWidgetAriaLabel() {
      return localize(1772, "Quick Tree");
    }
    getAriaLabel(element) {
      return element.ariaLabel || [element.label, element.description].map((s) => getCodiconAriaLabel(s)).filter((s) => !!s).join(", ");
    }
    getWidgetRole() {
      return "tree";
    }
    getRole(_element) {
      return "checkbox";
    }
    isChecked(element) {
      return {
        get value() {
          return element.checked === "mixed" ? "mixed" : !!element.checked;
        },
        onDidChange: (e) => Event.filter(this.onCheckedEvent, (e2) => e2.item === element)((_) => e())
      };
    }
  }
  class QuickInputTreeFilter {
    constructor() {
      this.filterValue = "";
      this.matchOnLabel = true;
      this.matchOnDescription = false;
    }
    filter(element, parentVisibility) {
      if (!this.filterValue || !(this.matchOnLabel || this.matchOnDescription)) {
        return element.children ? { visibility: 2, data: {} } : { visibility: 1, data: {} };
      }
      const labelHighlights = this.matchOnLabel ? matchesFuzzyIconAware(this.filterValue, parseLabelWithIcons(element.label)) ?? void 0 : void 0;
      const descriptionHighlights = this.matchOnDescription ? matchesFuzzyIconAware(this.filterValue, parseLabelWithIcons(element.description || "")) ?? void 0 : void 0;
      const visibility = parentVisibility === 1 ? 1 : labelHighlights || descriptionHighlights ? 1 : element.children ? 2 : 0;
      return {
        visibility,
        data: {
          labelHighlights,
          descriptionHighlights
        }
      };
    }
  }
  class QuickInputTreeSorter extends Disposable {
    constructor() {
      super(...arguments);
      this._sortByLabel = true;
    }
    get sortByLabel() {
      return this._sortByLabel;
    }
    set sortByLabel(value) {
      this._sortByLabel = value;
    }
    compare(a, b) {
      if (!this._sortByLabel) {
        return 0;
      }
      if (a.label < b.label) {
        return -1;
      } else if (a.label > b.label) {
        return 1;
      }
      if (a.description && b.description) {
        if (a.description < b.description) {
          return -1;
        } else if (a.description > b.description) {
          return 1;
        }
      } else if (a.description) {
        return -1;
      } else if (b.description) {
        return 1;
      }
      return 0;
    }
  }
  var __decorate$c = 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$c = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  const $$1 = $$l;
  let QuickInputTreeController = class QuickInputTreeController extends Disposable {
    constructor(container, hoverDelegate, instantiationService) {
      super();
      this.instantiationService = instantiationService;
      this._onDidTriggerButton = this._register(new Emitter$1());
      this._onDidChangeCheckboxState = this._register(new Emitter$1());
      this.onDidChangeCheckboxState = this._onDidChangeCheckboxState.event;
      this._onDidCheckedLeafItemsChange = this._register(new Emitter$1());
      this._onLeave = new Emitter$1();
      this.onLeave = this._onLeave.event;
      this._onDidAccept = this._register(new Emitter$1());
      this.onDidAccept = this._onDidAccept.event;
      this._container = append$2(container, $$1(".quick-input-tree"));
      this._renderer = this._register(this.instantiationService.createInstance(QuickInputTreeRenderer, hoverDelegate, this._onDidTriggerButton, this.onDidChangeCheckboxState));
      this._filter = this.instantiationService.createInstance(QuickInputTreeFilter);
      this._sorter = this._register(new QuickInputTreeSorter());
      this._tree = this._register(this.instantiationService.createInstance(WorkbenchObjectTree, "QuickInputTree", this._container, new QuickInputTreeDelegate(), [this._renderer], {
        accessibilityProvider: new QuickTreeAccessibilityProvider(this.onDidChangeCheckboxState),
        horizontalScrolling: false,
        multipleSelectionSupport: false,
        findWidgetEnabled: false,
        alwaysConsumeMouseWheel: true,
        hideTwistiesOfChildlessElements: true,
        renderIndentGuides: RenderIndentGuides.None,
        expandOnDoubleClick: true,
        expandOnlyOnTwistieClick: true,
        disableExpandOnSpacebar: true,
        sorter: this._sorter,
        filter: this._filter
      }));
      this.registerOnOpenListener();
    }
    get tree() {
      return this._tree;
    }
    get displayed() {
      return this._container.style.display !== "none";
    }
    set displayed(value) {
      this._container.style.display = value ? "" : "none";
    }
    get sortByLabel() {
      return this._sorter.sortByLabel;
    }
    set sortByLabel(value) {
      this._sorter.sortByLabel = value;
      this._tree.resort(null, true);
    }
    getActiveDescendant() {
      return this._tree.getHTMLElement().getAttribute("aria-activedescendant");
    }
    updateFilterOptions(options) {
      if (options.matchOnLabel !== void 0) {
        this._filter.matchOnLabel = options.matchOnLabel;
      }
      if (options.matchOnDescription !== void 0) {
        this._filter.matchOnDescription = options.matchOnDescription;
      }
      this._tree.refilter();
    }
    layout(maxHeight) {
      this._tree.getHTMLElement().style.maxHeight = maxHeight ? `${// Make sure height aligns with list item heights
      Math.floor(maxHeight / 44) * 44 + 6}px` : "";
      this._tree.layout();
    }
    registerOnOpenListener() {
      this._register(this._tree.onDidOpen((e) => {
        const item = e.element;
        if (!item) {
          return;
        }
        if (item.disabled) {
          return;
        }
        if (item.pickable === false) {
          this._tree.setFocus([item]);
          this._onDidAccept.fire();
          return;
        }
        const newState = item.checked !== true;
        if ((item.checked ?? false) === newState) {
          return;
        }
        item.checked = newState;
        this._tree.rerender(item);
        const updateSet = /* @__PURE__ */ new Set();
        const toUpdate = [...this._tree.getNode(item).children];
        while (toUpdate.length) {
          const pop = toUpdate.shift();
          if (pop?.element && !updateSet.has(pop.element)) {
            updateSet.add(pop.element);
            if ((pop.element.checked ?? false) !== item.checked) {
              pop.element.checked = item.checked;
              this._tree.rerender(pop.element);
            }
            toUpdate.push(...pop.children);
          }
        }
        let parent = this._tree.getParentElement(item);
        while (parent) {
          const parentChildren = [...this._tree.getNode(parent).children];
          const newState2 = getParentNodeState(parentChildren);
          if ((parent.checked ?? false) !== newState2) {
            parent.checked = newState2;
            this._tree.rerender(parent);
          }
          parent = this._tree.getParentElement(parent);
        }
        this._onDidChangeCheckboxState.fire({
          item,
          checked: item.checked ?? false
        });
        this._onDidCheckedLeafItemsChange.fire(this.getCheckedLeafItems());
      }));
    }
    getCheckedLeafItems() {
      const lookedAt = /* @__PURE__ */ new Set();
      const toLookAt = [...this._tree.getNode().children];
      const checkedItems = new Array();
      while (toLookAt.length) {
        const lookAt = toLookAt.shift();
        if (!lookAt?.element || lookedAt.has(lookAt.element)) {
          continue;
        }
        if (lookAt.element.checked) {
          lookedAt.add(lookAt.element);
          toLookAt.push(...lookAt.children);
          if (!lookAt.element.children) {
            checkedItems.push(lookAt.element);
          }
        }
      }
      return checkedItems;
    }
  };
  QuickInputTreeController = __decorate$c([
    __param$c(2, IInstantiationService)
  ], QuickInputTreeController);
  var __decorate$b = 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$b = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  var QuickInputController_1;
  const $ = $$l;
  const VIEWSTATE_STORAGE_KEY = "workbench.quickInput.viewState";
  let QuickInputController = (_Qa = class extends Disposable {
    // Max total width of quick input widget
    get currentQuickInput() {
      return this.controller ?? void 0;
    }
    get container() {
      return this._container;
    }
    constructor(options, layoutService, instantiationService, contextKeyService, storageService) {
      super();
      this.options = options;
      this.layoutService = layoutService;
      this.instantiationService = instantiationService;
      this.storageService = storageService;
      this.enabled = true;
      this.onDidAcceptEmitter = this._register(new Emitter$1());
      this.onDidCustomEmitter = this._register(new Emitter$1());
      this.onDidTriggerButtonEmitter = this._register(new Emitter$1());
      this.keyMods = { ctrlCmd: false, alt: false };
      this.controller = null;
      this.onShowEmitter = this._register(new Emitter$1());
      this.onShow = this.onShowEmitter.event;
      this.onHideEmitter = this._register(new Emitter$1());
      this.onHide = this.onHideEmitter.event;
      this.inQuickInputContext = InQuickInputContextKey.bindTo(contextKeyService);
      this.quickInputTypeContext = QuickInputTypeContextKey.bindTo(contextKeyService);
      this.endOfQuickInputBoxContext = EndOfQuickInputBoxContextKey.bindTo(contextKeyService);
      this.idPrefix = options.idPrefix;
      this._container = options.container;
      this.styles = options.styles;
      this._register(Event.runAndSubscribe(onDidRegisterWindow, ({ window: window2, disposables }) => this.registerKeyModsListeners(window2, disposables), { window: mainWindow, disposables: this._store }));
      this._register(onWillUnregisterWindow((window2) => {
        if (this.ui && getWindow(this.ui.container) === window2) {
          this.reparentUI(this.layoutService.mainContainer);
          this.layout(this.layoutService.mainContainerDimension, this.layoutService.mainContainerOffset.quickPickTop);
        }
      }));
      this.viewState = this.loadViewState();
    }
    registerKeyModsListeners(window2, disposables) {
      const listener = (e) => {
        this.keyMods.ctrlCmd = e.ctrlKey || e.metaKey;
        this.keyMods.alt = e.altKey;
      };
      for (const event of [EventType$1.KEY_DOWN, EventType$1.KEY_UP, EventType$1.MOUSE_DOWN]) {
        disposables.add(addDisposableListener(window2, event, listener, true));
      }
    }
    getUI(showInActiveContainer) {
      if (this.ui) {
        if (showInActiveContainer) {
          if (getWindow(this._container) !== getWindow(this.layoutService.activeContainer)) {
            this.reparentUI(this.layoutService.activeContainer);
            this.layout(this.layoutService.activeContainerDimension, this.layoutService.activeContainerOffset.quickPickTop);
          }
        }
        return this.ui;
      }
      const container = append$2(this._container, $(".quick-input-widget.show-file-icons"));
      container.tabIndex = -1;
      container.style.display = "none";
      const styleSheet = createStyleSheet(container);
      const titleBar = append$2(container, $(".quick-input-titlebar"));
      const leftActionBar = this._register(new ActionBar(titleBar, { hoverDelegate: this.options.hoverDelegate }));
      leftActionBar.domNode.classList.add("quick-input-left-action-bar");
      const title = append$2(titleBar, $(".quick-input-title"));
      const rightActionBar = this._register(new ActionBar(titleBar, { hoverDelegate: this.options.hoverDelegate }));
      rightActionBar.domNode.classList.add("quick-input-right-action-bar");
      const headerContainer = append$2(container, $(".quick-input-header"));
      const checkAll = this._register(new TriStateCheckbox(localize(1763, "Toggle all checkboxes"), false, { ...defaultCheckboxStyles, size: 15 }));
      append$2(headerContainer, checkAll.domNode);
      this._register(checkAll.onChange(() => {
        const checked = checkAll.checked;
        list2.setAllVisibleChecked(checked === true);
      }));
      this._register(addDisposableListener(checkAll.domNode, EventType$1.CLICK, (e) => {
        if (e.x || e.y) {
          inputBox.setFocus();
        }
      }));
      const description2 = append$2(headerContainer, $(".quick-input-description"));
      const inputContainer = append$2(headerContainer, $(".quick-input-and-message"));
      const filterContainer = append$2(inputContainer, $(".quick-input-filter"));
      const inputBox = this._register(new QuickInputBox(filterContainer, this.styles.inputBox, this.styles.toggle));
      inputBox.setAttribute("aria-describedby", `${this.idPrefix}message`);
      const visibleCountContainer = append$2(filterContainer, $(".quick-input-visible-count"));
      visibleCountContainer.setAttribute("aria-live", "polite");
      visibleCountContainer.setAttribute("aria-atomic", "true");
      const visibleCount = this._register(new CountBadge(visibleCountContainer, { countFormat: localize(1764, "{0} Results") }, this.styles.countBadge));
      const countContainer = append$2(filterContainer, $(".quick-input-count"));
      countContainer.setAttribute("aria-live", "polite");
      const count = this._register(new CountBadge(countContainer, { countFormat: localize(1765, "{0} Selected") }, this.styles.countBadge));
      const inlineActionBar = this._register(new ActionBar(headerContainer, { hoverDelegate: this.options.hoverDelegate }));
      inlineActionBar.domNode.classList.add("quick-input-inline-action-bar");
      const okContainer = append$2(headerContainer, $(".quick-input-action"));
      const ok2 = this._register(new Button(okContainer, this.styles.button));
      ok2.label = localize(1766, "OK");
      this._register(ok2.onDidClick((e) => {
        this.onDidAcceptEmitter.fire();
      }));
      const customButtonContainer = append$2(headerContainer, $(".quick-input-action"));
      const customButton = this._register(new Button(customButtonContainer, { ...this.styles.button, supportIcons: true }));
      customButton.label = localize(1767, "Custom");
      this._register(customButton.onDidClick((e) => {
        this.onDidCustomEmitter.fire();
      }));
      const message = append$2(inputContainer, $(`#${this.idPrefix}message.quick-input-message`));
      const progressBar = this._register(new ProgressBar(container, this.styles.progressBar));
      progressBar.getContainer().classList.add("quick-input-progress");
      const widget = append$2(container, $(".quick-input-html-widget"));
      widget.tabIndex = -1;
      const description1 = append$2(container, $(".quick-input-description"));
      const listId = this.idPrefix + "list";
      const list2 = this._register(this.instantiationService.createInstance(QuickInputList, container, this.options.hoverDelegate, this.options.linkOpenerDelegate, listId));
      inputBox.setAttribute("aria-controls", listId);
      this._register(list2.onDidChangeFocus(() => {
        if (inputBox.hasFocus()) {
          inputBox.setAttribute("aria-activedescendant", list2.getActiveDescendant() ?? "");
        }
      }));
      this._register(list2.onChangedAllVisibleChecked((checked) => {
        checkAll.checked = checked;
      }));
      this._register(list2.onChangedVisibleCount((c) => {
        visibleCount.setCount(c);
      }));
      this._register(list2.onChangedCheckedCount((c) => {
        setTimeout0(() => count.setCount(c));
      }));
      this._register(list2.onLeave(() => {
        setTimeout(() => {
          if (!this.controller) {
            return;
          }
          inputBox.setFocus();
          if (this.controller instanceof QuickPick && this.controller.canSelectMany) {
            list2.clearFocus();
          }
        }, 0);
      }));
      const tree = this._register(this.instantiationService.createInstance(QuickInputTreeController, container, this.options.hoverDelegate));
      this._register(tree.tree.onDidChangeFocus(() => {
        if (inputBox.hasFocus()) {
          inputBox.setAttribute("aria-activedescendant", tree.getActiveDescendant() ?? "");
        }
      }));
      this._register(tree.onLeave(() => {
        setTimeout(() => {
          if (!this.controller) {
            return;
          }
          inputBox.setFocus();
          tree.tree.setFocus([]);
        }, 0);
      }));
      this._register(tree.onDidAccept(() => {
        this.onDidAcceptEmitter.fire();
      }));
      this._register(tree.tree.onDidChangeContentHeight(() => this.updateLayout()));
      const focusTracker = trackFocus(container);
      this._register(focusTracker);
      this._register(addDisposableListener(container, EventType$1.FOCUS, (e) => {
        const ui = this.getUI();
        if (isAncestor$1(e.relatedTarget, ui.inputContainer)) {
          const value = ui.inputBox.isSelectionAtEnd();
          if (this.endOfQuickInputBoxContext.get() !== value) {
            this.endOfQuickInputBoxContext.set(value);
          }
        }
        if (isAncestor$1(e.relatedTarget, ui.container)) {
          return;
        }
        this.inQuickInputContext.set(true);
        this.previousFocusElement = isHTMLElement(e.relatedTarget) ? e.relatedTarget : void 0;
      }, true));
      this._register(focusTracker.onDidBlur(() => {
        if (!this.getUI().ignoreFocusOut && !this.options.ignoreFocusOut()) {
          this.hide(QuickInputHideReason.Blur);
        }
        this.inQuickInputContext.set(false);
        this.endOfQuickInputBoxContext.set(false);
        this.previousFocusElement = void 0;
      }));
      this._register(inputBox.onKeyDown((_) => {
        const value = this.getUI().inputBox.isSelectionAtEnd();
        if (this.endOfQuickInputBoxContext.get() !== value) {
          this.endOfQuickInputBoxContext.set(value);
        }
        inputBox.removeAttribute("aria-activedescendant");
      }));
      this._register(addDisposableListener(container, EventType$1.FOCUS, (e) => {
        inputBox.setFocus();
      }));
      this.dndController = this._register(this.instantiationService.createInstance(QuickInputDragAndDropController, this._container, container, [
        {
          node: titleBar,
          includeChildren: true
        },
        {
          node: headerContainer,
          includeChildren: false
        }
      ], this.viewState));
      this._register(autorun((reader) => {
        const dndViewState = this.dndController?.dndViewState.read(reader);
        if (!dndViewState) {
          return;
        }
        if (dndViewState.top !== void 0 && dndViewState.left !== void 0) {
          this.viewState = {
            ...this.viewState,
            top: dndViewState.top,
            left: dndViewState.left
          };
        } else {
          this.viewState = void 0;
        }
        this.updateLayout();
        if (dndViewState.done) {
          this.saveViewState(this.viewState);
        }
      }));
      this.ui = {
        container,
        styleSheet,
        leftActionBar,
        titleBar,
        title,
        description1,
        description2,
        widget,
        rightActionBar,
        inlineActionBar,
        checkAll,
        inputContainer,
        filterContainer,
        inputBox,
        visibleCountContainer,
        visibleCount,
        countContainer,
        count,
        okContainer,
        ok: ok2,
        message,
        customButtonContainer,
        customButton,
        list: list2,
        tree,
        progressBar,
        onDidAccept: this.onDidAcceptEmitter.event,
        onDidCustom: this.onDidCustomEmitter.event,
        onDidTriggerButton: this.onDidTriggerButtonEmitter.event,
        ignoreFocusOut: false,
        keyMods: this.keyMods,
        show: (controller) => this.show(controller),
        hide: () => this.hide(),
        setVisibilities: (visibilities) => this.setVisibilities(visibilities),
        setEnabled: (enabled) => this.setEnabled(enabled),
        setContextKey: (contextKey) => this.options.setContextKey(contextKey),
        linkOpenerDelegate: (content) => this.options.linkOpenerDelegate(content)
      };
      this.updateStyles();
      return this.ui;
    }
    reparentUI(container) {
      if (this.ui) {
        this._container = container;
        append$2(this._container, this.ui.container);
        this.dndController?.reparentUI(this._container);
      }
    }
    pick(picks, options = {}, token = CancellationToken.None) {
      return new Promise((doResolve, reject) => {
        let resolve2 = (result) => {
          resolve2 = doResolve;
          options.onKeyMods?.(input.keyMods);
          doResolve(result);
        };
        if (token.isCancellationRequested) {
          resolve2(void 0);
          return;
        }
        const input = this.createQuickPick({ useSeparators: true });
        let activeItem;
        const disposables = [
          input,
          input.onDidAccept(() => {
            if (input.canSelectMany) {
              resolve2(input.selectedItems.slice());
              input.hide();
            } else {
              const result = input.activeItems[0];
              if (result) {
                resolve2(result);
                input.hide();
              }
            }
          }),
          input.onDidChangeActive((items) => {
            const focused = items[0];
            if (focused && options.onDidFocus) {
              options.onDidFocus(focused);
            }
          }),
          input.onDidChangeSelection((items) => {
            if (!input.canSelectMany) {
              const result = items[0];
              if (result) {
                resolve2(result);
                input.hide();
              }
            }
          }),
          input.onDidTriggerItemButton((event) => options.onDidTriggerItemButton && options.onDidTriggerItemButton({
            ...event,
            removeItem: () => {
              const index = input.items.indexOf(event.item);
              if (index !== -1) {
                const items = input.items.slice();
                const removed = items.splice(index, 1);
                const activeItems = input.activeItems.filter((activeItem2) => activeItem2 !== removed[0]);
                const keepScrollPositionBefore = input.keepScrollPosition;
                input.keepScrollPosition = true;
                input.items = items;
                if (activeItems) {
                  input.activeItems = activeItems;
                }
                input.keepScrollPosition = keepScrollPositionBefore;
              }
            }
          })),
          input.onDidTriggerSeparatorButton((event) => options.onDidTriggerSeparatorButton?.(event)),
          input.onDidChangeValue((value) => {
            if (activeItem && !value && (input.activeItems.length !== 1 || input.activeItems[0] !== activeItem)) {
              input.activeItems = [activeItem];
            }
          }),
          token.onCancellationRequested(() => {
            input.hide();
          }),
          input.onDidHide(() => {
            dispose(disposables);
            resolve2(void 0);
          })
        ];
        input.title = options.title;
        if (options.value) {
          input.value = options.value;
        }
        input.canSelectMany = !!options.canPickMany;
        input.placeholder = options.placeHolder;
        input.prompt = options.prompt;
        input.ignoreFocusOut = !!options.ignoreFocusLost;
        input.matchOnDescription = !!options.matchOnDescription;
        input.matchOnDetail = !!options.matchOnDetail;
        if (options.sortByLabel !== void 0) {
          input.sortByLabel = options.sortByLabel;
        }
        input.matchOnLabel = options.matchOnLabel === void 0 || options.matchOnLabel;
        input.quickNavigate = options.quickNavigate;
        input.hideInput = !!options.hideInput;
        input.contextKey = options.contextKey;
        input.busy = true;
        Promise.all([picks, options.activeItem]).then(([items, _activeItem]) => {
          activeItem = _activeItem;
          input.busy = false;
          input.items = items;
          if (input.canSelectMany) {
            input.selectedItems = items.filter((item) => item.type !== "separator" && item.picked);
          }
          if (activeItem) {
            input.activeItems = [activeItem];
          }
        });
        input.show();
        Promise.resolve(picks).then(void 0, (err) => {
          reject(err);
          input.hide();
        });
      });
    }
    setValidationOnInput(input, validationResult) {
      if (validationResult && isString$1(validationResult)) {
        input.severity = Severity$2.Error;
        input.validationMessage = validationResult;
      } else if (validationResult && !isString$1(validationResult)) {
        input.severity = validationResult.severity;
        input.validationMessage = validationResult.content;
      } else {
        input.severity = Severity$2.Ignore;
        input.validationMessage = void 0;
      }
    }
    input(options = {}, token = CancellationToken.None) {
      return new Promise((resolve2) => {
        if (token.isCancellationRequested) {
          resolve2(void 0);
          return;
        }
        const input = this.createInputBox();
        const validateInput = options.validateInput || (() => Promise.resolve(void 0));
        const onDidValueChange = Event.debounce(input.onDidChangeValue, (last, cur) => cur, 100);
        let validationValue = options.value || "";
        let validation = Promise.resolve(validateInput(validationValue));
        const disposables = [
          input,
          onDidValueChange((value) => {
            if (value !== validationValue) {
              validation = Promise.resolve(validateInput(value));
              validationValue = value;
            }
            validation.then((result) => {
              if (value === validationValue) {
                this.setValidationOnInput(input, result);
              }
            });
          }),
          input.onDidAccept(() => {
            const value = input.value;
            if (value !== validationValue) {
              validation = Promise.resolve(validateInput(value));
              validationValue = value;
            }
            validation.then((result) => {
              if (!result || !isString$1(result) && result.severity !== Severity$2.Error) {
                resolve2(value);
                input.hide();
              } else if (value === validationValue) {
                this.setValidationOnInput(input, result);
              }
            });
          }),
          token.onCancellationRequested(() => {
            input.hide();
          }),
          input.onDidHide(() => {
            dispose(disposables);
            resolve2(void 0);
          })
        ];
        input.title = options.title;
        input.value = options.value || "";
        input.valueSelection = options.valueSelection;
        input.prompt = options.prompt;
        input.placeholder = options.placeHolder;
        input.password = !!options.password;
        input.ignoreFocusOut = !!options.ignoreFocusLost;
        input.show();
      });
    }
    createQuickPick(options = { useSeparators: false }) {
      const ui = this.getUI(true);
      return new QuickPick(ui);
    }
    createInputBox() {
      const ui = this.getUI(true);
      return new InputBox(ui);
    }
    show(controller) {
      const ui = this.getUI(true);
      this.onShowEmitter.fire();
      const oldController = this.controller;
      this.controller = controller;
      oldController?.didHide();
      this.setEnabled(true);
      ui.leftActionBar.clear();
      ui.title.textContent = "";
      ui.description1.textContent = "";
      ui.description2.textContent = "";
      reset(ui.widget);
      ui.rightActionBar.clear();
      ui.inlineActionBar.clear();
      ui.checkAll.checked = false;
      ui.inputBox.placeholder = "";
      ui.inputBox.password = false;
      ui.inputBox.showDecoration(Severity$2.Ignore);
      ui.visibleCount.setCount(0);
      ui.count.setCount(0);
      reset(ui.message);
      ui.progressBar.stop();
      ui.progressBar.getContainer().setAttribute("aria-hidden", "true");
      ui.list.setElements([]);
      ui.list.matchOnDescription = false;
      ui.list.matchOnDetail = false;
      ui.list.matchOnLabel = true;
      ui.list.sortByLabel = true;
      ui.tree.updateFilterOptions({
        matchOnDescription: false,
        matchOnLabel: true
      });
      ui.tree.sortByLabel = true;
      ui.ignoreFocusOut = false;
      ui.inputBox.toggles = void 0;
      const backKeybindingLabel = this.options.backKeybindingLabel();
      backButton.tooltip = backKeybindingLabel ? localize(1768, "Back ({0})", backKeybindingLabel) : localize(1769, "Back");
      ui.container.style.display = "";
      this.updateLayout();
      this.dndController?.layoutContainer();
      ui.inputBox.setFocus();
      this.quickInputTypeContext.set(controller.type);
    }
    isVisible() {
      return !!this.ui && this.ui.container.style.display !== "none";
    }
    setVisibilities(visibilities) {
      const ui = this.getUI();
      ui.title.style.display = visibilities.title ? "" : "none";
      ui.description1.style.display = visibilities.description && (visibilities.inputBox || visibilities.checkAll) ? "" : "none";
      ui.description2.style.display = visibilities.description && !(visibilities.inputBox || visibilities.checkAll) ? "" : "none";
      ui.checkAll.domNode.style.display = visibilities.checkAll ? "" : "none";
      ui.inputContainer.style.display = visibilities.inputBox ? "" : "none";
      ui.filterContainer.style.display = visibilities.inputBox ? "" : "none";
      ui.visibleCountContainer.style.display = visibilities.visibleCount ? "" : "none";
      ui.countContainer.style.display = visibilities.count ? "" : "none";
      ui.okContainer.style.display = visibilities.ok ? "" : "none";
      ui.customButtonContainer.style.display = visibilities.customButton ? "" : "none";
      ui.message.style.display = visibilities.message ? "" : "none";
      ui.progressBar.getContainer().style.display = visibilities.progressBar ? "" : "none";
      ui.list.displayed = !!visibilities.list;
      ui.tree.displayed = !!visibilities.tree;
      ui.container.classList.toggle("show-checkboxes", !!visibilities.checkBox);
      ui.container.classList.toggle("hidden-input", !visibilities.inputBox && !visibilities.description);
      this.updateLayout();
    }
    setEnabled(enabled) {
      if (enabled !== this.enabled) {
        this.enabled = enabled;
        const ui = this.getUI();
        for (const item of ui.leftActionBar.viewItems) {
          item.action.enabled = enabled;
        }
        for (const item of ui.rightActionBar.viewItems) {
          item.action.enabled = enabled;
        }
        if (enabled) {
          ui.checkAll.enable();
        } else {
          ui.checkAll.disable();
        }
        ui.inputBox.enabled = enabled;
        ui.ok.enabled = enabled;
        ui.list.enabled = enabled;
      }
    }
    hide(reason) {
      const controller = this.controller;
      if (!controller) {
        return;
      }
      controller.willHide(reason);
      const container = this.ui?.container;
      const focusChanged = container && !isAncestorOfActiveElement(container);
      this.controller = null;
      this.onHideEmitter.fire();
      if (container) {
        container.style.display = "none";
      }
      if (!focusChanged) {
        let currentElement = this.previousFocusElement;
        while (currentElement && !currentElement.offsetParent) {
          currentElement = currentElement.parentElement ?? void 0;
        }
        if (currentElement?.offsetParent) {
          currentElement.focus();
          this.previousFocusElement = void 0;
        } else {
          this.options.returnFocus();
        }
      }
      controller.didHide(reason);
    }
    toggleHover() {
      if (this.isVisible() && this.controller instanceof QuickPick) {
        this.getUI().list.toggleHover();
      }
    }
    layout(dimension, titleBarOffset) {
      this.dimension = dimension;
      this.titleBarOffset = titleBarOffset;
      this.updateLayout();
    }
    updateLayout() {
      if (this.ui && this.isVisible()) {
        const style = this.ui.container.style;
        const width2 = Math.min(this.dimension.width * 0.62, QuickInputController_1.MAX_WIDTH);
        style.width = width2 + "px";
        style.top = `${this.viewState?.top ? Math.round(this.dimension.height * this.viewState.top) : this.titleBarOffset}px`;
        style.left = `${Math.round(this.dimension.width * (this.viewState?.left ?? 0.5) - width2 / 2)}px`;
        this.ui.inputBox.layout();
        this.ui.list.layout(this.dimension && this.dimension.height * 0.4);
        this.ui.tree.layout(this.dimension && this.dimension.height * 0.4);
      }
    }
    applyStyles(styles) {
      this.styles = styles;
      this.updateStyles();
    }
    updateStyles() {
      if (this.ui) {
        const { quickInputTitleBackground: quickInputTitleBackground2, quickInputBackground: quickInputBackground2, quickInputForeground: quickInputForeground2, widgetBorder: widgetBorder2, widgetShadow: widgetShadow2 } = this.styles.widget;
        this.ui.titleBar.style.backgroundColor = quickInputTitleBackground2 ?? "";
        this.ui.container.style.backgroundColor = quickInputBackground2 ?? "";
        this.ui.container.style.color = quickInputForeground2 ?? "";
        this.ui.container.style.border = widgetBorder2 ? `1px solid ${widgetBorder2}` : "";
        this.ui.container.style.boxShadow = widgetShadow2 ? `0 0 8px 2px ${widgetShadow2}` : "";
        this.ui.list.style(this.styles.list);
        this.ui.tree.tree.style(this.styles.list);
        const content = [];
        if (this.styles.pickerGroup.pickerGroupBorder) {
          content.push(`.quick-input-list .quick-input-list-entry { border-top-color:  ${this.styles.pickerGroup.pickerGroupBorder}; }`);
        }
        if (this.styles.pickerGroup.pickerGroupForeground) {
          content.push(`.quick-input-list .quick-input-list-separator { color:  ${this.styles.pickerGroup.pickerGroupForeground}; }`);
        }
        if (this.styles.pickerGroup.pickerGroupForeground) {
          content.push(`.quick-input-list .quick-input-list-separator-as-item { color: var(--vscode-descriptionForeground); }`);
        }
        if (this.styles.keybindingLabel.keybindingLabelBackground || this.styles.keybindingLabel.keybindingLabelBorder || this.styles.keybindingLabel.keybindingLabelBottomBorder || this.styles.keybindingLabel.keybindingLabelShadow || this.styles.keybindingLabel.keybindingLabelForeground) {
          content.push(".quick-input-list .monaco-keybinding > .monaco-keybinding-key {");
          if (this.styles.keybindingLabel.keybindingLabelBackground) {
            content.push(`background-color: ${this.styles.keybindingLabel.keybindingLabelBackground};`);
          }
          if (this.styles.keybindingLabel.keybindingLabelBorder) {
            content.push(`border-color: ${this.styles.keybindingLabel.keybindingLabelBorder};`);
          }
          if (this.styles.keybindingLabel.keybindingLabelBottomBorder) {
            content.push(`border-bottom-color: ${this.styles.keybindingLabel.keybindingLabelBottomBorder};`);
          }
          if (this.styles.keybindingLabel.keybindingLabelShadow) {
            content.push(`box-shadow: inset 0 -1px 0 ${this.styles.keybindingLabel.keybindingLabelShadow};`);
          }
          if (this.styles.keybindingLabel.keybindingLabelForeground) {
            content.push(`color: ${this.styles.keybindingLabel.keybindingLabelForeground};`);
          }
          content.push("}");
        }
        const newStyles = content.join("\n");
        if (newStyles !== this.ui.styleSheet.textContent) {
          this.ui.styleSheet.textContent = newStyles;
        }
      }
    }
    loadViewState() {
      try {
        const data = JSON.parse(this.storageService.get(VIEWSTATE_STORAGE_KEY, -1, "{}"));
        if (data.top !== void 0 || data.left !== void 0) {
          return data;
        }
      } catch {
      }
      return void 0;
    }
    saveViewState(viewState) {
      const isMainWindow = this.layoutService.activeContainer === this.layoutService.mainContainer;
      if (!isMainWindow) {
        return;
      }
      if (viewState !== void 0) {
        this.storageService.store(
          VIEWSTATE_STORAGE_KEY,
          JSON.stringify(viewState),
          -1,
          1
          /* StorageTarget.MACHINE */
        );
      } else {
        this.storageService.remove(
          VIEWSTATE_STORAGE_KEY,
          -1
          /* StorageScope.APPLICATION */
        );
      }
    }
  }, QuickInputController_1 = _Qa, _Qa.MAX_WIDTH = 600, _Qa);
  QuickInputController = QuickInputController_1 = __decorate$b([
    __param$b(1, ILayoutService),
    __param$b(2, IInstantiationService),
    __param$b(3, IContextKeyService),
    __param$b(4, IStorageService)
  ], QuickInputController);
  let QuickInputDragAndDropController = class QuickInputDragAndDropController extends Disposable {
    constructor(_container, _quickInputContainer, _quickInputDragAreas, initialViewState, _layoutService, contextKeyService, configurationService) {
      super();
      this._container = _container;
      this._quickInputContainer = _quickInputContainer;
      this._quickInputDragAreas = _quickInputDragAreas;
      this._layoutService = _layoutService;
      this.configurationService = configurationService;
      this.dndViewState = observableValue(this, void 0);
      this._snapThreshold = 20;
      this._snapLineHorizontalRatio = 0.25;
      this._quickInputAlignmentContext = QuickInputAlignmentContextKey.bindTo(contextKeyService);
      const customWindowControls = getWindowControlsStyle(this.configurationService) === "custom";
      this._controlsOnLeft = customWindowControls && platform$1 === 1;
      this._controlsOnRight = customWindowControls && (platform$1 === 3 || platform$1 === 2);
      this._registerLayoutListener();
      this.registerMouseListeners();
      this.dndViewState.set({ ...initialViewState, done: true }, void 0);
    }
    reparentUI(container) {
      this._container = container;
    }
    layoutContainer(dimension = this._layoutService.activeContainerDimension) {
      const state = this.dndViewState.get();
      const dragAreaRect = this._quickInputContainer.getBoundingClientRect();
      if (state?.top && state?.left) {
        const a = Math.round(state.left * 100) / 100;
        const b = dimension.width;
        const c = dragAreaRect.width;
        const d = a * b - c / 2;
        this._layout(state.top * dimension.height, d);
      }
    }
    _registerLayoutListener() {
      this._register(Event.filter(this._layoutService.onDidLayoutContainer, (e) => e.container === this._container)((e) => this.layoutContainer(e.dimension)));
    }
    registerMouseListeners() {
      const dragArea = this._quickInputContainer;
      this._register(addDisposableGenericMouseUpListener(dragArea, (event) => {
        const originEvent = new StandardMouseEvent(getWindow(dragArea), event);
        if (originEvent.detail !== 2) {
          return;
        }
        if (!this._quickInputDragAreas.some(({ node, includeChildren }) => includeChildren ? isAncestor$1(originEvent.target, node) : originEvent.target === node)) {
          return;
        }
        this.dndViewState.set({ top: void 0, left: void 0, done: true }, void 0);
      }));
      this._register(addDisposableGenericMouseDownListener(dragArea, (e) => {
        const activeWindow = getWindow(this._layoutService.activeContainer);
        const originEvent = new StandardMouseEvent(activeWindow, e);
        if (!this._quickInputDragAreas.some(({ node, includeChildren }) => includeChildren ? isAncestor$1(originEvent.target, node) : originEvent.target === node)) {
          return;
        }
        const dragAreaRect = this._quickInputContainer.getBoundingClientRect();
        const dragOffsetX = originEvent.browserEvent.clientX - dragAreaRect.left;
        const dragOffsetY = originEvent.browserEvent.clientY - dragAreaRect.top;
        let isMovingQuickInput = false;
        const mouseMoveListener = addDisposableGenericMouseMoveListener(activeWindow, (e2) => {
          const mouseMoveEvent = new StandardMouseEvent(activeWindow, e2);
          mouseMoveEvent.preventDefault();
          if (!isMovingQuickInput) {
            isMovingQuickInput = true;
          }
          this._layout(e2.clientY - dragOffsetY, e2.clientX - dragOffsetX);
        });
        const mouseUpListener = addDisposableGenericMouseUpListener(activeWindow, (e2) => {
          if (isMovingQuickInput) {
            const state = this.dndViewState.get();
            this.dndViewState.set({ top: state?.top, left: state?.left, done: true }, void 0);
          }
          mouseMoveListener.dispose();
          mouseUpListener.dispose();
        });
      }));
    }
    _layout(topCoordinate, leftCoordinate) {
      const snapCoordinateYTop = this._getTopSnapValue();
      const snapCoordinateY = this._getCenterYSnapValue();
      const snapCoordinateX = this._getCenterXSnapValue();
      topCoordinate = Math.max(0, Math.min(topCoordinate, this._container.clientHeight - this._quickInputContainer.clientHeight));
      if (topCoordinate < this._layoutService.activeContainerOffset.top) {
        if (this._controlsOnLeft) {
          leftCoordinate = Math.max(leftCoordinate, 80 / getZoomFactor(getActiveWindow()));
        } else if (this._controlsOnRight) {
          leftCoordinate = Math.min(leftCoordinate, this._container.clientWidth - this._quickInputContainer.clientWidth - 140 / getZoomFactor(getActiveWindow()));
        }
      }
      const snappingToTop = Math.abs(topCoordinate - snapCoordinateYTop) < this._snapThreshold;
      topCoordinate = snappingToTop ? snapCoordinateYTop : topCoordinate;
      const snappingToCenter = Math.abs(topCoordinate - snapCoordinateY) < this._snapThreshold;
      topCoordinate = snappingToCenter ? snapCoordinateY : topCoordinate;
      const top = topCoordinate / this._container.clientHeight;
      leftCoordinate = Math.max(0, Math.min(leftCoordinate, this._container.clientWidth - this._quickInputContainer.clientWidth));
      const snappingToCenterX = Math.abs(leftCoordinate - snapCoordinateX) < this._snapThreshold;
      leftCoordinate = snappingToCenterX ? snapCoordinateX : leftCoordinate;
      const b = this._container.clientWidth;
      const c = this._quickInputContainer.clientWidth;
      const d = leftCoordinate;
      const left = (d + c / 2) / b;
      this.dndViewState.set({ top, left, done: false }, void 0);
      if (snappingToCenterX) {
        if (snappingToTop) {
          this._quickInputAlignmentContext.set("top");
          return;
        } else if (snappingToCenter) {
          this._quickInputAlignmentContext.set("center");
          return;
        }
      }
      this._quickInputAlignmentContext.set(void 0);
    }
    _getTopSnapValue() {
      return this._layoutService.activeContainerOffset.quickPickTop;
    }
    _getCenterYSnapValue() {
      return Math.round(this._container.clientHeight * this._snapLineHorizontalRatio);
    }
    _getCenterXSnapValue() {
      return Math.round(this._container.clientWidth / 2) - Math.round(this._quickInputContainer.clientWidth / 2);
    }
  };
  QuickInputDragAndDropController = __decorate$b([
    __param$b(4, ILayoutService),
    __param$b(5, IContextKeyService),
    __param$b(6, IConfigurationService)
  ], QuickInputDragAndDropController);
  var __decorate$a = 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$a = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  let QuickInputService = class QuickInputService extends Themable {
    get controller() {
      if (!this._controller) {
        this._controller = this._register(this.createController());
      }
      return this._controller;
    }
    get hasController() {
      return !!this._controller;
    }
    get currentQuickInput() {
      return this.controller.currentQuickInput;
    }
    get quickAccess() {
      if (!this._quickAccess) {
        this._quickAccess = this._register(this.instantiationService.createInstance(QuickAccessController));
      }
      return this._quickAccess;
    }
    constructor(instantiationService, contextKeyService, themeService, layoutService, configurationService) {
      super(themeService);
      this.instantiationService = instantiationService;
      this.contextKeyService = contextKeyService;
      this.layoutService = layoutService;
      this.configurationService = configurationService;
      this._onShow = this._register(new Emitter$1());
      this._onHide = this._register(new Emitter$1());
      this.contexts = /* @__PURE__ */ new Map();
    }
    createController(host = this.layoutService, options) {
      const defaultOptions2 = {
        idPrefix: "quickInput_",
        container: host.activeContainer,
        ignoreFocusOut: () => false,
        backKeybindingLabel: () => void 0,
        setContextKey: (id) => this.setContextKey(id),
        linkOpenerDelegate: (content) => {
          this.instantiationService.invokeFunction((accessor) => {
            const openerService = accessor.get(IOpenerService);
            openerService.open(content, { allowCommands: true, fromUserGesture: true });
          });
        },
        returnFocus: () => host.focus(),
        styles: this.computeStyles(),
        hoverDelegate: this._register(this.instantiationService.createInstance(QuickInputHoverDelegate))
      };
      const controller = this._register(this.instantiationService.createInstance(QuickInputController, {
        ...defaultOptions2,
        ...options
      }));
      controller.layout(host.activeContainerDimension, host.activeContainerOffset.quickPickTop);
      this._register(host.onDidLayoutActiveContainer((dimension) => {
        if (getWindow(host.activeContainer) === getWindow(controller.container)) {
          controller.layout(dimension, host.activeContainerOffset.quickPickTop);
        }
      }));
      this._register(host.onDidChangeActiveContainer(() => {
        if (controller.isVisible()) {
          return;
        }
        controller.layout(host.activeContainerDimension, host.activeContainerOffset.quickPickTop);
      }));
      this._register(controller.onShow(() => {
        this.resetContextKeys();
        this._onShow.fire();
      }));
      this._register(controller.onHide(() => {
        this.resetContextKeys();
        this._onHide.fire();
      }));
      return controller;
    }
    setContextKey(id) {
      let key;
      if (id) {
        key = this.contexts.get(id);
        if (!key) {
          key = new RawContextKey(id, false).bindTo(this.contextKeyService);
          this.contexts.set(id, key);
        }
      }
      if (key && key.get()) {
        return;
      }
      this.resetContextKeys();
      key?.set(true);
    }
    resetContextKeys() {
      this.contexts.forEach((context) => {
        if (context.get()) {
          context.reset();
        }
      });
    }
    pick(picks, options, token = CancellationToken.None) {
      return this.controller.pick(picks, options, token);
    }
    input(options = {}, token = CancellationToken.None) {
      return this.controller.input(options, token);
    }
    createQuickPick(options = { useSeparators: false }) {
      return this.controller.createQuickPick(options);
    }
    createInputBox() {
      return this.controller.createInputBox();
    }
    toggleHover() {
      if (this.hasController) {
        this.controller.toggleHover();
      }
    }
    updateStyles() {
      if (this.hasController) {
        this.controller.applyStyles(this.computeStyles());
      }
    }
    computeStyles() {
      return {
        widget: {
          quickInputBackground: asCssVariable(quickInputBackground),
          quickInputForeground: asCssVariable(quickInputForeground),
          quickInputTitleBackground: asCssVariable(quickInputTitleBackground),
          widgetBorder: asCssVariable(widgetBorder),
          widgetShadow: asCssVariable(widgetShadow)
        },
        inputBox: defaultInputBoxStyles,
        toggle: defaultToggleStyles,
        countBadge: defaultCountBadgeStyles,
        button: defaultButtonStyles,
        progressBar: defaultProgressBarStyles,
        keybindingLabel: defaultKeybindingLabelStyles,
        list: getListStyles({
          listBackground: quickInputBackground,
          listFocusBackground: quickInputListFocusBackground,
          listFocusForeground: quickInputListFocusForeground,
          // Look like focused when inactive.
          listInactiveFocusForeground: quickInputListFocusForeground,
          listInactiveSelectionIconForeground: quickInputListFocusIconForeground,
          listInactiveFocusBackground: quickInputListFocusBackground,
          listFocusOutline: activeContrastBorder,
          listInactiveFocusOutline: activeContrastBorder,
          treeStickyScrollBackground: quickInputBackground
        }),
        pickerGroup: {
          pickerGroupBorder: asCssVariable(pickerGroupBorder),
          pickerGroupForeground: asCssVariable(pickerGroupForeground)
        }
      };
    }
  };
  QuickInputService = __decorate$a([
    __param$a(0, IInstantiationService),
    __param$a(1, IContextKeyService),
    __param$a(2, IThemeService),
    __param$a(3, ILayoutService),
    __param$a(4, IConfigurationService)
  ], QuickInputService);
  var __decorate$9 = 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$9 = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  let EditorScopedQuickInputService = class EditorScopedQuickInputService extends QuickInputService {
    constructor(editor2, instantiationService, contextKeyService, themeService, codeEditorService, configurationService) {
      super(instantiationService, contextKeyService, themeService, new EditorScopedLayoutService(editor2.getContainerDomNode(), codeEditorService), configurationService);
      this.host = void 0;
      const contribution = QuickInputEditorContribution.get(editor2);
      if (contribution) {
        const widget = contribution.widget;
        this.host = {
          _serviceBrand: void 0,
          get mainContainer() {
            return widget.getDomNode();
          },
          getContainer() {
            return widget.getDomNode();
          },
          whenContainerStylesLoaded() {
            return void 0;
          },
          get containers() {
            return [widget.getDomNode()];
          },
          get activeContainer() {
            return widget.getDomNode();
          },
          get mainContainerDimension() {
            return editor2.getLayoutInfo();
          },
          get activeContainerDimension() {
            return editor2.getLayoutInfo();
          },
          get onDidLayoutMainContainer() {
            return editor2.onDidLayoutChange;
          },
          get onDidLayoutActiveContainer() {
            return editor2.onDidLayoutChange;
          },
          get onDidLayoutContainer() {
            return Event.map(editor2.onDidLayoutChange, (dimension) => ({ container: widget.getDomNode(), dimension }));
          },
          get onDidChangeActiveContainer() {
            return Event.None;
          },
          get onDidAddContainer() {
            return Event.None;
          },
          get mainContainerOffset() {
            return { top: 0, quickPickTop: 0 };
          },
          get activeContainerOffset() {
            return { top: 0, quickPickTop: 0 };
          },
          focus: () => editor2.focus()
        };
      } else {
        this.host = void 0;
      }
    }
    createController() {
      return super.createController(this.host);
    }
  };
  EditorScopedQuickInputService = __decorate$9([
    __param$9(1, IInstantiationService),
    __param$9(2, IContextKeyService),
    __param$9(3, IThemeService),
    __param$9(4, ICodeEditorService),
    __param$9(5, IConfigurationService)
  ], EditorScopedQuickInputService);
  let StandaloneQuickInputService = class StandaloneQuickInputService {
    get activeService() {
      const editor2 = this.codeEditorService.getFocusedCodeEditor();
      if (!editor2) {
        throw new Error("Quick input service needs a focused editor to work.");
      }
      let quickInputService = this.mapEditorToService.get(editor2);
      if (!quickInputService) {
        const newQuickInputService = quickInputService = this.instantiationService.createInstance(EditorScopedQuickInputService, editor2);
        this.mapEditorToService.set(editor2, quickInputService);
        createSingleCallFunction(editor2.onDidDispose)(() => {
          newQuickInputService.dispose();
          this.mapEditorToService.delete(editor2);
        });
      }
      return quickInputService;
    }
    get currentQuickInput() {
      return this.activeService.currentQuickInput;
    }
    get quickAccess() {
      return this.activeService.quickAccess;
    }
    constructor(instantiationService, codeEditorService) {
      this.instantiationService = instantiationService;
      this.codeEditorService = codeEditorService;
      this.mapEditorToService = /* @__PURE__ */ new Map();
    }
    pick(picks, options, token = CancellationToken.None) {
      return this.activeService.pick(picks, options, token);
    }
    input(options, token) {
      return this.activeService.input(options, token);
    }
    createQuickPick(options = { useSeparators: false }) {
      return this.activeService.createQuickPick(options);
    }
    createInputBox() {
      return this.activeService.createInputBox();
    }
    toggleHover() {
      return this.activeService.toggleHover();
    }
  };
  StandaloneQuickInputService = __decorate$9([
    __param$9(0, IInstantiationService),
    __param$9(1, ICodeEditorService)
  ], StandaloneQuickInputService);
  const _QuickInputEditorContribution = class _QuickInputEditorContribution {
    static get(editor2) {
      return editor2.getContribution(_QuickInputEditorContribution.ID);
    }
    constructor(editor2) {
      this.editor = editor2;
      this.widget = new QuickInputEditorWidget(this.editor);
    }
    dispose() {
      this.widget.dispose();
    }
  };
  _QuickInputEditorContribution.ID = "editor.controller.quickInput";
  let QuickInputEditorContribution = _QuickInputEditorContribution;
  const _QuickInputEditorWidget = class _QuickInputEditorWidget {
    constructor(codeEditor) {
      this.codeEditor = codeEditor;
      this.domNode = document.createElement("div");
      this.codeEditor.addOverlayWidget(this);
    }
    getId() {
      return _QuickInputEditorWidget.ID;
    }
    getDomNode() {
      return this.domNode;
    }
    getPosition() {
      return { preference: { top: 0, left: 0 } };
    }
    dispose() {
      this.codeEditor.removeOverlayWidget(this);
    }
  };
  _QuickInputEditorWidget.ID = "editor.contrib.quickInputWidget";
  let QuickInputEditorWidget = _QuickInputEditorWidget;
  registerEditorContribution(
    QuickInputEditorContribution.ID,
    QuickInputEditorContribution,
    4
    /* EditorContributionInstantiation.Lazy */
  );
  var __decorate$8 = 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$8 = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  let AccessibilityService = class AccessibilityService extends Disposable {
    constructor(_contextKeyService, _layoutService, _configurationService) {
      super();
      this._contextKeyService = _contextKeyService;
      this._layoutService = _layoutService;
      this._configurationService = _configurationService;
      this._accessibilitySupport = 0;
      this._onDidChangeScreenReaderOptimized = new Emitter$1();
      this._onDidChangeReducedMotion = new Emitter$1();
      this._onDidChangeLinkUnderline = new Emitter$1();
      this._accessibilityModeEnabledContext = CONTEXT_ACCESSIBILITY_MODE_ENABLED.bindTo(this._contextKeyService);
      const updateContextKey = () => this._accessibilityModeEnabledContext.set(this.isScreenReaderOptimized());
      this._register(this._configurationService.onDidChangeConfiguration((e) => {
        if (e.affectsConfiguration("editor.accessibilitySupport")) {
          updateContextKey();
          this._onDidChangeScreenReaderOptimized.fire();
        }
        if (e.affectsConfiguration("workbench.reduceMotion")) {
          this._configMotionReduced = this._configurationService.getValue("workbench.reduceMotion");
          this._onDidChangeReducedMotion.fire();
        }
      }));
      updateContextKey();
      this._register(this.onDidChangeScreenReaderOptimized(() => updateContextKey()));
      const reduceMotionMatcher = mainWindow.matchMedia(`(prefers-reduced-motion: reduce)`);
      this._systemMotionReduced = reduceMotionMatcher.matches;
      this._configMotionReduced = this._configurationService.getValue("workbench.reduceMotion");
      this._linkUnderlinesEnabled = this._configurationService.getValue("accessibility.underlineLinks");
      this.initReducedMotionListeners(reduceMotionMatcher);
      this.initLinkUnderlineListeners();
    }
    initReducedMotionListeners(reduceMotionMatcher) {
      this._register(addDisposableListener(reduceMotionMatcher, "change", () => {
        this._systemMotionReduced = reduceMotionMatcher.matches;
        if (this._configMotionReduced === "auto") {
          this._onDidChangeReducedMotion.fire();
        }
      }));
      const updateRootClasses = () => {
        const reduce = this.isMotionReduced();
        this._layoutService.mainContainer.classList.toggle("monaco-reduce-motion", reduce);
        this._layoutService.mainContainer.classList.toggle("monaco-enable-motion", !reduce);
      };
      updateRootClasses();
      this._register(this.onDidChangeReducedMotion(() => updateRootClasses()));
    }
    initLinkUnderlineListeners() {
      this._register(this._configurationService.onDidChangeConfiguration((e) => {
        if (e.affectsConfiguration("accessibility.underlineLinks")) {
          const linkUnderlinesEnabled = this._configurationService.getValue("accessibility.underlineLinks");
          this._linkUnderlinesEnabled = linkUnderlinesEnabled;
          this._onDidChangeLinkUnderline.fire();
        }
      }));
      const updateLinkUnderlineClasses = () => {
        const underlineLinks = this._linkUnderlinesEnabled;
        this._layoutService.mainContainer.classList.toggle("underline-links", underlineLinks);
      };
      updateLinkUnderlineClasses();
      this._register(this.onDidChangeLinkUnderlines(() => updateLinkUnderlineClasses()));
    }
    onDidChangeLinkUnderlines(listener) {
      return this._onDidChangeLinkUnderline.event(listener);
    }
    get onDidChangeScreenReaderOptimized() {
      return this._onDidChangeScreenReaderOptimized.event;
    }
    isScreenReaderOptimized() {
      const config = this._configurationService.getValue("editor.accessibilitySupport");
      return config === "on" || config === "auto" && this._accessibilitySupport === 2;
    }
    get onDidChangeReducedMotion() {
      return this._onDidChangeReducedMotion.event;
    }
    isMotionReduced() {
      const config = this._configMotionReduced;
      return config === "on" || config === "auto" && this._systemMotionReduced;
    }
    getAccessibilitySupport() {
      return this._accessibilitySupport;
    }
  };
  AccessibilityService = __decorate$8([
    __param$8(0, IContextKeyService),
    __param$8(1, ILayoutService),
    __param$8(2, IConfigurationService)
  ], AccessibilityService);
  var __decorate$7 = 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$7 = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  var BrowserClipboardService_1;
  const vscodeResourcesMime = "application/vnd.code.resources";
  let BrowserClipboardService = (_Ra = class extends Disposable {
    constructor(layoutService, logService) {
      super();
      this.layoutService = layoutService;
      this.logService = logService;
      this.mapTextToType = /* @__PURE__ */ new Map();
      this.findText = "";
      this.resources = [];
      this.resourcesStateHash = void 0;
      if (isSafari$1 || isWebkitWebView) {
        this.installWebKitWriteTextWorkaround();
      }
      this._register(Event.runAndSubscribe(onDidRegisterWindow, ({ window: window2, disposables }) => {
        disposables.add(addDisposableListener(window2.document, "copy", () => this.clearResourcesState()));
      }, { window: mainWindow, disposables: this._store }));
    }
    triggerPaste() {
      this.logService.trace("BrowserClipboardService#triggerPaste");
      return void 0;
    }
    // In Safari, it has the following note:
    //
    // "The request to write to the clipboard must be triggered during a user gesture.
    // A call to clipboard.write or clipboard.writeText outside the scope of a user
    // gesture(such as "click" or "touch" event handlers) will result in the immediate
    // rejection of the promise returned by the API call."
    // From: https://webkit.org/blog/10855/async-clipboard-api/
    //
    // Since extensions run in a web worker, and handle gestures in an asynchronous way,
    // they are not classified by Safari as "in response to a user gesture" and will reject.
    //
    // This function sets up some handlers to work around that behavior.
    installWebKitWriteTextWorkaround() {
      const handler = () => {
        const currentWritePromise = new DeferredPromise();
        if (this.webKitPendingClipboardWritePromise && !this.webKitPendingClipboardWritePromise.isSettled) {
          this.webKitPendingClipboardWritePromise.cancel();
        }
        this.webKitPendingClipboardWritePromise = currentWritePromise;
        getActiveWindow().navigator.clipboard.write([new ClipboardItem({
          "text/plain": currentWritePromise.p
        })]).catch(async (err) => {
          if (!(err instanceof Error) || err.name !== "NotAllowedError" || !currentWritePromise.isRejected) {
            this.logService.error(err);
          }
        });
      };
      this._register(Event.runAndSubscribe(this.layoutService.onDidAddContainer, ({ container, disposables }) => {
        disposables.add(addDisposableListener(container, "click", handler));
        disposables.add(addDisposableListener(container, "keydown", handler));
      }, { container: this.layoutService.mainContainer, disposables: this._store }));
    }
    async writeText(text2, type) {
      this.logService.trace("BrowserClipboardService#writeText called with type:", type, " text.length:", text2.length);
      this.clearResourcesState();
      if (type) {
        this.mapTextToType.set(type, text2);
        this.logService.trace("BrowserClipboardService#writeText");
        return;
      }
      if (this.webKitPendingClipboardWritePromise) {
        return this.webKitPendingClipboardWritePromise.complete(text2);
      }
      try {
        this.logService.trace("before navigator.clipboard.writeText");
        return await getActiveWindow().navigator.clipboard.writeText(text2);
      } catch (error) {
        console.error(error);
      }
      this.fallbackWriteText(text2);
    }
    fallbackWriteText(text2) {
      this.logService.trace("BrowserClipboardService#fallbackWriteText");
      const activeDocument = getActiveDocument();
      const activeElement = activeDocument.activeElement;
      const textArea = activeDocument.body.appendChild($$l("textarea", { "aria-hidden": true }));
      textArea.style.height = "1px";
      textArea.style.width = "1px";
      textArea.style.position = "absolute";
      textArea.value = text2;
      textArea.focus();
      textArea.select();
      activeDocument.execCommand("copy");
      if (isHTMLElement(activeElement)) {
        activeElement.focus();
      }
      textArea.remove();
    }
    async readText(type) {
      this.logService.trace("BrowserClipboardService#readText called with type:", type);
      if (type) {
        const readText = this.mapTextToType.get(type) || "";
        this.logService.trace("BrowserClipboardService#readText text.length:", readText.length);
        return readText;
      }
      try {
        const readText = await getActiveWindow().navigator.clipboard.readText();
        this.logService.trace("BrowserClipboardService#readText text.length:", readText.length);
        return readText;
      } catch (error) {
        console.error(error);
      }
      return "";
    }
    async readFindText() {
      return this.findText;
    }
    async writeFindText(text2) {
      this.findText = text2;
    }
    async readResources() {
      try {
        const items = await getActiveWindow().navigator.clipboard.read();
        for (const item of items) {
          if (item.types.includes(`web ${vscodeResourcesMime}`)) {
            const blob = await item.getType(`web ${vscodeResourcesMime}`);
            const resources = JSON.parse(await blob.text()).map((x) => URI.from(x));
            return resources;
          }
        }
      } catch (error) {
      }
      const resourcesStateHash = await this.computeResourcesStateHash();
      if (this.resourcesStateHash !== resourcesStateHash) {
        this.clearResourcesState();
      }
      return this.resources;
    }
    async computeResourcesStateHash() {
      if (this.resources.length === 0) {
        return void 0;
      }
      const clipboardText = await this.readText();
      return hash(clipboardText.substring(0, BrowserClipboardService_1.MAX_RESOURCE_STATE_SOURCE_LENGTH));
    }
    clearInternalState() {
      this.clearResourcesState();
    }
    clearResourcesState() {
      this.resources = [];
      this.resourcesStateHash = void 0;
    }
  }, BrowserClipboardService_1 = _Ra, _Ra.MAX_RESOURCE_STATE_SOURCE_LENGTH = 1e3, _Ra);
  BrowserClipboardService = BrowserClipboardService_1 = __decorate$7([
    __param$7(0, ILayoutService),
    __param$7(1, ILogService)
  ], BrowserClipboardService);
  var __decorate$6 = 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$6 = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  const KEYBINDING_CONTEXT_ATTR = "data-keybinding-context";
  class Context {
    constructor(id, parent) {
      this._id = id;
      this._parent = parent;
      this._value = /* @__PURE__ */ Object.create(null);
      this._value["_contextId"] = id;
    }
    get value() {
      return { ...this._value };
    }
    setValue(key, value) {
      if (this._value[key] !== value) {
        this._value[key] = value;
        return true;
      }
      return false;
    }
    removeValue(key) {
      if (key in this._value) {
        delete this._value[key];
        return true;
      }
      return false;
    }
    getValue(key) {
      const ret = this._value[key];
      if (typeof ret === "undefined" && this._parent) {
        return this._parent.getValue(key);
      }
      return ret;
    }
  }
  const _NullContext = class _NullContext extends Context {
    constructor() {
      super(-1, null);
    }
    setValue(key, value) {
      return false;
    }
    removeValue(key) {
      return false;
    }
    getValue(key) {
      return void 0;
    }
  };
  _NullContext.INSTANCE = new _NullContext();
  let NullContext = _NullContext;
  const _ConfigAwareContextValuesContainer = class _ConfigAwareContextValuesContainer extends Context {
    constructor(id, _configurationService, emitter) {
      super(id, null);
      this._configurationService = _configurationService;
      this._values = TernarySearchTree.forConfigKeys();
      this._listener = this._configurationService.onDidChangeConfiguration((event) => {
        if (event.source === 7) {
          const allKeys = Array.from(this._values, ([k]) => k);
          this._values.clear();
          emitter.fire(new ArrayContextKeyChangeEvent(allKeys));
        } else {
          const changedKeys = [];
          for (const configKey of event.affectedKeys) {
            const contextKey = `config.${configKey}`;
            const cachedItems = this._values.findSuperstr(contextKey);
            if (cachedItems !== void 0) {
              changedKeys.push(...Iterable.map(cachedItems, ([key]) => key));
              this._values.deleteSuperstr(contextKey);
            }
            if (this._values.has(contextKey)) {
              changedKeys.push(contextKey);
              this._values.delete(contextKey);
            }
          }
          emitter.fire(new ArrayContextKeyChangeEvent(changedKeys));
        }
      });
    }
    dispose() {
      this._listener.dispose();
    }
    getValue(key) {
      if (key.indexOf(_ConfigAwareContextValuesContainer._keyPrefix) !== 0) {
        return super.getValue(key);
      }
      if (this._values.has(key)) {
        return this._values.get(key);
      }
      const configKey = key.substr(_ConfigAwareContextValuesContainer._keyPrefix.length);
      const configValue = this._configurationService.getValue(configKey);
      let value = void 0;
      switch (typeof configValue) {
        case "number":
        case "boolean":
        case "string":
          value = configValue;
          break;
        default:
          if (Array.isArray(configValue)) {
            value = JSON.stringify(configValue);
          } else {
            value = configValue;
          }
      }
      this._values.set(key, value);
      return value;
    }
    setValue(key, value) {
      return super.setValue(key, value);
    }
    removeValue(key) {
      return super.removeValue(key);
    }
  };
  _ConfigAwareContextValuesContainer._keyPrefix = "config.";
  let ConfigAwareContextValuesContainer = _ConfigAwareContextValuesContainer;
  class ContextKey {
    constructor(service, key, defaultValue) {
      this._service = service;
      this._key = key;
      this._defaultValue = defaultValue;
      this.reset();
    }
    set(value) {
      this._service.setContext(this._key, value);
    }
    reset() {
      if (typeof this._defaultValue === "undefined") {
        this._service.removeContext(this._key);
      } else {
        this._service.setContext(this._key, this._defaultValue);
      }
    }
    get() {
      return this._service.getContextKeyValue(this._key);
    }
  }
  class SimpleContextKeyChangeEvent {
    constructor(key) {
      this.key = key;
    }
    affectsSome(keys) {
      return keys.has(this.key);
    }
    allKeysContainedIn(keys) {
      return this.affectsSome(keys);
    }
  }
  class ArrayContextKeyChangeEvent {
    constructor(keys) {
      this.keys = keys;
    }
    affectsSome(keys) {
      for (const key of this.keys) {
        if (keys.has(key)) {
          return true;
        }
      }
      return false;
    }
    allKeysContainedIn(keys) {
      return this.keys.every((key) => keys.has(key));
    }
  }
  class CompositeContextKeyChangeEvent {
    constructor(events) {
      this.events = events;
    }
    affectsSome(keys) {
      for (const e of this.events) {
        if (e.affectsSome(keys)) {
          return true;
        }
      }
      return false;
    }
    allKeysContainedIn(keys) {
      return this.events.every((evt) => evt.allKeysContainedIn(keys));
    }
  }
  function allEventKeysInContext(event, context) {
    return event.allKeysContainedIn(new Set(Object.keys(context)));
  }
  class AbstractContextKeyService extends Disposable {
    get onDidChangeContext() {
      return this._onDidChangeContext.event;
    }
    constructor(myContextId) {
      super();
      this._onDidChangeContext = this._register(new PauseableEmitter({ merge: (input) => new CompositeContextKeyChangeEvent(input) }));
      this._isDisposed = false;
      this._myContextId = myContextId;
    }
    createKey(key, defaultValue) {
      if (this._isDisposed) {
        throw new Error(`AbstractContextKeyService has been disposed`);
      }
      return new ContextKey(this, key, defaultValue);
    }
    bufferChangeEvents(callback) {
      this._onDidChangeContext.pause();
      try {
        callback();
      } finally {
        this._onDidChangeContext.resume();
      }
    }
    createScoped(domNode) {
      if (this._isDisposed) {
        throw new Error(`AbstractContextKeyService has been disposed`);
      }
      return new ScopedContextKeyService(this, domNode);
    }
    contextMatchesRules(rules) {
      if (this._isDisposed) {
        throw new Error(`AbstractContextKeyService has been disposed`);
      }
      const context = this.getContextValuesContainer(this._myContextId);
      const result = rules ? rules.evaluate(context) : true;
      return result;
    }
    getContextKeyValue(key) {
      if (this._isDisposed) {
        return void 0;
      }
      return this.getContextValuesContainer(this._myContextId).getValue(key);
    }
    setContext(key, value) {
      if (this._isDisposed) {
        return;
      }
      const myContext = this.getContextValuesContainer(this._myContextId);
      if (!myContext) {
        return;
      }
      if (myContext.setValue(key, value)) {
        this._onDidChangeContext.fire(new SimpleContextKeyChangeEvent(key));
      }
    }
    removeContext(key) {
      if (this._isDisposed) {
        return;
      }
      if (this.getContextValuesContainer(this._myContextId).removeValue(key)) {
        this._onDidChangeContext.fire(new SimpleContextKeyChangeEvent(key));
      }
    }
    getContext(target) {
      if (this._isDisposed) {
        return NullContext.INSTANCE;
      }
      return this.getContextValuesContainer(findContextAttr(target));
    }
    dispose() {
      super.dispose();
      this._isDisposed = true;
    }
  }
  let ContextKeyService = class ContextKeyService extends AbstractContextKeyService {
    constructor(configurationService) {
      super(0);
      this._contexts = /* @__PURE__ */ new Map();
      this._lastContextId = 0;
      this.inputFocusedContext = InputFocusedContext.bindTo(this);
      const myContext = this._register(new ConfigAwareContextValuesContainer(this._myContextId, configurationService, this._onDidChangeContext));
      this._contexts.set(this._myContextId, myContext);
      this._register(Event.runAndSubscribe(onDidRegisterWindow, ({ window: window2, disposables }) => {
        const onFocusDisposables = disposables.add(new MutableDisposable());
        disposables.add(addDisposableListener(window2, EventType$1.FOCUS_IN, () => {
          onFocusDisposables.value = new DisposableStore();
          this.updateInputContextKeys(window2.document, onFocusDisposables.value);
        }, true));
      }, { window: mainWindow, disposables: this._store }));
    }
    updateInputContextKeys(ownerDocument, disposables) {
      function activeElementIsInput() {
        return !!ownerDocument.activeElement && isEditableElement(ownerDocument.activeElement);
      }
      const isInputFocused = activeElementIsInput();
      this.inputFocusedContext.set(isInputFocused);
      if (isInputFocused) {
        const tracker = disposables.add(trackFocus(ownerDocument.activeElement));
        Event.once(tracker.onDidBlur)(() => {
          if (getActiveWindow().document === ownerDocument) {
            this.inputFocusedContext.set(activeElementIsInput());
          }
          tracker.dispose();
        }, void 0, disposables);
      }
    }
    getContextValuesContainer(contextId) {
      if (this._isDisposed) {
        return NullContext.INSTANCE;
      }
      return this._contexts.get(contextId) || NullContext.INSTANCE;
    }
    createChildContext(parentContextId = this._myContextId) {
      if (this._isDisposed) {
        throw new Error(`ContextKeyService has been disposed`);
      }
      const id = ++this._lastContextId;
      this._contexts.set(id, new Context(id, this.getContextValuesContainer(parentContextId)));
      return id;
    }
    disposeContext(contextId) {
      if (!this._isDisposed) {
        this._contexts.delete(contextId);
      }
    }
  };
  ContextKeyService = __decorate$6([
    __param$6(0, IConfigurationService)
  ], ContextKeyService);
  class ScopedContextKeyService extends AbstractContextKeyService {
    constructor(parent, domNode) {
      super(parent.createChildContext());
      this._parentChangeListener = this._register(new MutableDisposable());
      this._parent = parent;
      this._updateParentChangeListener();
      this._domNode = domNode;
      if (this._domNode.hasAttribute(KEYBINDING_CONTEXT_ATTR)) {
        let extraInfo = "";
        if (this._domNode.classList) {
          extraInfo = Array.from(this._domNode.classList.values()).join(", ");
        }
        console.error(`Element already has context attribute${extraInfo ? ": " + extraInfo : ""}`);
      }
      this._domNode.setAttribute(KEYBINDING_CONTEXT_ATTR, String(this._myContextId));
    }
    _updateParentChangeListener() {
      this._parentChangeListener.value = this._parent.onDidChangeContext((e) => {
        const thisContainer = this._parent.getContextValuesContainer(this._myContextId);
        const thisContextValues = thisContainer.value;
        if (!allEventKeysInContext(e, thisContextValues)) {
          this._onDidChangeContext.fire(e);
        }
      });
    }
    dispose() {
      if (this._isDisposed) {
        return;
      }
      this._parent.disposeContext(this._myContextId);
      this._domNode.removeAttribute(KEYBINDING_CONTEXT_ATTR);
      super.dispose();
    }
    getContextValuesContainer(contextId) {
      if (this._isDisposed) {
        return NullContext.INSTANCE;
      }
      return this._parent.getContextValuesContainer(contextId);
    }
    createChildContext(parentContextId = this._myContextId) {
      if (this._isDisposed) {
        throw new Error(`ScopedContextKeyService has been disposed`);
      }
      return this._parent.createChildContext(parentContextId);
    }
    disposeContext(contextId) {
      if (this._isDisposed) {
        return;
      }
      this._parent.disposeContext(contextId);
    }
  }
  function findContextAttr(domNode) {
    while (domNode) {
      if (domNode.hasAttribute(KEYBINDING_CONTEXT_ATTR)) {
        const attr = domNode.getAttribute(KEYBINDING_CONTEXT_ATTR);
        if (attr) {
          return parseInt(attr, 10);
        }
        return NaN;
      }
      domNode = domNode.parentElement;
    }
    return 0;
  }
  function setContext(accessor, contextKey, contextValue) {
    const contextKeyService = accessor.get(IContextKeyService);
    contextKeyService.createKey(String(contextKey), stringifyURIs(contextValue));
  }
  function stringifyURIs(contextValue) {
    return cloneAndChange(contextValue, (obj) => {
      if (typeof obj === "object" && obj.$mid === 1) {
        return URI.revive(obj).toString();
      }
      if (obj instanceof URI) {
        return obj.toString();
      }
      return void 0;
    });
  }
  CommandsRegistry.registerCommand("_setContext", setContext);
  CommandsRegistry.registerCommand({
    id: "getContextKeyInfo",
    handler() {
      return [...RawContextKey.all()].sort((a, b) => a.key.localeCompare(b.key));
    },
    metadata: {
      description: localize(1674, "A command that returns information about context keys"),
      args: []
    }
  });
  CommandsRegistry.registerCommand("_generateContextKeyInfo", function() {
    const result = [];
    const seen = /* @__PURE__ */ new Set();
    for (const info of RawContextKey.all()) {
      if (!seen.has(info.key)) {
        seen.add(info.key);
        result.push(info);
      }
    }
    result.sort((a, b) => a.key.localeCompare(b.key));
    console.log(JSON.stringify(result, void 0, 2));
  });
  let Node$1 = class Node {
    constructor(key, data) {
      this.key = key;
      this.data = data;
      this.incoming = /* @__PURE__ */ new Map();
      this.outgoing = /* @__PURE__ */ new Map();
    }
  };
  class Graph {
    constructor(_hashFn) {
      this._hashFn = _hashFn;
      this._nodes = /* @__PURE__ */ new Map();
    }
    roots() {
      const ret = [];
      for (const node of this._nodes.values()) {
        if (node.outgoing.size === 0) {
          ret.push(node);
        }
      }
      return ret;
    }
    insertEdge(from, to) {
      const fromNode = this.lookupOrInsertNode(from);
      const toNode = this.lookupOrInsertNode(to);
      fromNode.outgoing.set(toNode.key, toNode);
      toNode.incoming.set(fromNode.key, fromNode);
    }
    removeNode(data) {
      const key = this._hashFn(data);
      this._nodes.delete(key);
      for (const node of this._nodes.values()) {
        node.outgoing.delete(key);
        node.incoming.delete(key);
      }
    }
    lookupOrInsertNode(data) {
      const key = this._hashFn(data);
      let node = this._nodes.get(key);
      if (!node) {
        node = new Node$1(key, data);
        this._nodes.set(key, node);
      }
      return node;
    }
    isEmpty() {
      return this._nodes.size === 0;
    }
    toString() {
      const data = [];
      for (const [key, value] of this._nodes) {
        data.push(`${key}
	(-> incoming)[${[...value.incoming.keys()].join(", ")}]
	(outgoing ->)[${[...value.outgoing.keys()].join(",")}]
`);
      }
      return data.join("\n");
    }
    /**
     * This is brute force and slow and **only** be used
     * to trouble shoot.
     */
    findCycleSlow() {
      for (const [id, node] of this._nodes) {
        const seen = /* @__PURE__ */ new Set([id]);
        const res = this._findCycle(node, seen);
        if (res) {
          return res;
        }
      }
      return void 0;
    }
    _findCycle(node, seen) {
      for (const [id, outgoing] of node.outgoing) {
        if (seen.has(id)) {
          return [...seen, id].join(" -> ");
        }
        seen.add(id);
        const value = this._findCycle(outgoing, seen);
        if (value) {
          return value;
        }
        seen.delete(id);
      }
      return void 0;
    }
  }
  const _enableAllTracing = false;
  class CyclicDependencyError extends Error {
    constructor(graph) {
      super("cyclic dependency between services");
      this.message = graph.findCycleSlow() ?? `UNABLE to detect cycle, dumping graph: 
${graph.toString()}`;
    }
  }
  class InstantiationService {
    constructor(_services = new ServiceCollection(), _strict = false, _parent, _enableTracing = _enableAllTracing) {
      this._services = _services;
      this._strict = _strict;
      this._parent = _parent;
      this._enableTracing = _enableTracing;
      this._isDisposed = false;
      this._servicesToMaybeDispose = /* @__PURE__ */ new Set();
      this._children = /* @__PURE__ */ new Set();
      this._activeInstantiations = /* @__PURE__ */ new Set();
      this._services.set(IInstantiationService, this);
      this._globalGraph = _enableTracing ? _parent?._globalGraph ?? new Graph((e) => e) : void 0;
    }
    dispose() {
      if (!this._isDisposed) {
        this._isDisposed = true;
        dispose(this._children);
        this._children.clear();
        for (const candidate of this._servicesToMaybeDispose) {
          if (isDisposable(candidate)) {
            candidate.dispose();
          }
        }
        this._servicesToMaybeDispose.clear();
      }
    }
    _throwIfDisposed() {
      if (this._isDisposed) {
        throw new Error("InstantiationService has been disposed");
      }
    }
    createChild(services, store) {
      this._throwIfDisposed();
      const that = this;
      const result = new class extends InstantiationService {
        dispose() {
          that._children.delete(result);
          super.dispose();
        }
      }(services, this._strict, this, this._enableTracing);
      this._children.add(result);
      store?.add(result);
      return result;
    }
    invokeFunction(fn, ...args) {
      this._throwIfDisposed();
      const _trace = Trace.traceInvocation(this._enableTracing, fn);
      let _done = false;
      try {
        const accessor = {
          get: (id) => {
            if (_done) {
              throw illegalState("service accessor is only valid during the invocation of its target method");
            }
            const result = this._getOrCreateServiceInstance(id, _trace);
            if (!result) {
              throw new Error(`[invokeFunction] unknown service '${id}'`);
            }
            return result;
          },
          getIfExists: (id) => {
            if (_done) {
              throw illegalState("service accessor is only valid during the invocation of its target method");
            }
            const result = this._getOrCreateServiceInstance(id, _trace);
            return result;
          }
        };
        return fn(accessor, ...args);
      } finally {
        _done = true;
        _trace.stop();
      }
    }
    createInstance(ctorOrDescriptor, ...rest) {
      this._throwIfDisposed();
      let _trace;
      let result;
      if (ctorOrDescriptor instanceof SyncDescriptor) {
        _trace = Trace.traceCreation(this._enableTracing, ctorOrDescriptor.ctor);
        result = this._createInstance(ctorOrDescriptor.ctor, ctorOrDescriptor.staticArguments.concat(rest), _trace);
      } else {
        _trace = Trace.traceCreation(this._enableTracing, ctorOrDescriptor);
        result = this._createInstance(ctorOrDescriptor, rest, _trace);
      }
      _trace.stop();
      return result;
    }
    _createInstance(ctor, args = [], _trace) {
      const serviceDependencies = _util.getServiceDependencies(ctor).sort((a, b) => a.index - b.index);
      const serviceArgs = [];
      for (const dependency of serviceDependencies) {
        const service = this._getOrCreateServiceInstance(dependency.id, _trace);
        if (!service) {
          this._throwIfStrict(`[createInstance] ${ctor.name} depends on UNKNOWN service ${dependency.id}.`, false);
        }
        serviceArgs.push(service);
      }
      const firstServiceArgPos = serviceDependencies.length > 0 ? serviceDependencies[0].index : args.length;
      if (args.length !== firstServiceArgPos) {
        console.trace(`[createInstance] First service dependency of ${ctor.name} at position ${firstServiceArgPos + 1} conflicts with ${args.length} static arguments`);
        const delta = firstServiceArgPos - args.length;
        if (delta > 0) {
          args = args.concat(new Array(delta));
        } else {
          args = args.slice(0, firstServiceArgPos);
        }
      }
      return Reflect.construct(ctor, args.concat(serviceArgs));
    }
    _setCreatedServiceInstance(id, instance) {
      if (this._services.get(id) instanceof SyncDescriptor) {
        this._services.set(id, instance);
      } else if (this._parent) {
        this._parent._setCreatedServiceInstance(id, instance);
      } else {
        throw new Error("illegalState - setting UNKNOWN service instance");
      }
    }
    _getServiceInstanceOrDescriptor(id) {
      const instanceOrDesc = this._services.get(id);
      if (!instanceOrDesc && this._parent) {
        return this._parent._getServiceInstanceOrDescriptor(id);
      } else {
        return instanceOrDesc;
      }
    }
    _getOrCreateServiceInstance(id, _trace) {
      if (this._globalGraph && this._globalGraphImplicitDependency) {
        this._globalGraph.insertEdge(this._globalGraphImplicitDependency, String(id));
      }
      const thing = this._getServiceInstanceOrDescriptor(id);
      if (thing instanceof SyncDescriptor) {
        return this._safeCreateAndCacheServiceInstance(id, thing, _trace.branch(id, true));
      } else {
        _trace.branch(id, false);
        return thing;
      }
    }
    _safeCreateAndCacheServiceInstance(id, desc, _trace) {
      if (this._activeInstantiations.has(id)) {
        throw new Error(`illegal state - RECURSIVELY instantiating service '${id}'`);
      }
      this._activeInstantiations.add(id);
      try {
        return this._createAndCacheServiceInstance(id, desc, _trace);
      } finally {
        this._activeInstantiations.delete(id);
      }
    }
    _createAndCacheServiceInstance(id, desc, _trace) {
      const graph = new Graph((data) => data.id.toString());
      let cycleCount = 0;
      const stack = [{ id, desc, _trace }];
      const seen = /* @__PURE__ */ new Set();
      while (stack.length) {
        const item = stack.pop();
        if (seen.has(String(item.id))) {
          continue;
        }
        seen.add(String(item.id));
        graph.lookupOrInsertNode(item);
        if (cycleCount++ > 1e3) {
          throw new CyclicDependencyError(graph);
        }
        for (const dependency of _util.getServiceDependencies(item.desc.ctor)) {
          const instanceOrDesc = this._getServiceInstanceOrDescriptor(dependency.id);
          if (!instanceOrDesc) {
            this._throwIfStrict(`[createInstance] ${id} depends on ${dependency.id} which is NOT registered.`, true);
          }
          this._globalGraph?.insertEdge(String(item.id), String(dependency.id));
          if (instanceOrDesc instanceof SyncDescriptor) {
            const d = { id: dependency.id, desc: instanceOrDesc, _trace: item._trace.branch(dependency.id, true) };
            graph.insertEdge(item, d);
            stack.push(d);
          }
        }
      }
      while (true) {
        const roots = graph.roots();
        if (roots.length === 0) {
          if (!graph.isEmpty()) {
            throw new CyclicDependencyError(graph);
          }
          break;
        }
        for (const { data } of roots) {
          const instanceOrDesc = this._getServiceInstanceOrDescriptor(data.id);
          if (instanceOrDesc instanceof SyncDescriptor) {
            const instance = this._createServiceInstanceWithOwner(data.id, data.desc.ctor, data.desc.staticArguments, data.desc.supportsDelayedInstantiation, data._trace);
            this._setCreatedServiceInstance(data.id, instance);
          }
          graph.removeNode(data);
        }
      }
      return this._getServiceInstanceOrDescriptor(id);
    }
    _createServiceInstanceWithOwner(id, ctor, args = [], supportsDelayedInstantiation, _trace) {
      if (this._services.get(id) instanceof SyncDescriptor) {
        return this._createServiceInstance(id, ctor, args, supportsDelayedInstantiation, _trace, this._servicesToMaybeDispose);
      } else if (this._parent) {
        return this._parent._createServiceInstanceWithOwner(id, ctor, args, supportsDelayedInstantiation, _trace);
      } else {
        throw new Error(`illegalState - creating UNKNOWN service instance ${ctor.name}`);
      }
    }
    _createServiceInstance(id, ctor, args = [], supportsDelayedInstantiation, _trace, disposeBucket) {
      if (!supportsDelayedInstantiation) {
        const result = this._createInstance(ctor, args, _trace);
        disposeBucket.add(result);
        return result;
      } else {
        const child = new InstantiationService(void 0, this._strict, this, this._enableTracing);
        child._globalGraphImplicitDependency = String(id);
        const earlyListeners = /* @__PURE__ */ new Map();
        const idle = new GlobalIdleValue(() => {
          const result = child._createInstance(ctor, args, _trace);
          for (const [key, values] of earlyListeners) {
            const candidate = result[key];
            if (typeof candidate === "function") {
              for (const value of values) {
                value.disposable = candidate.apply(result, value.listener);
              }
            }
          }
          earlyListeners.clear();
          disposeBucket.add(result);
          return result;
        });
        return new Proxy(/* @__PURE__ */ Object.create(null), {
          get(target, key) {
            if (!idle.isInitialized) {
              if (typeof key === "string" && (key.startsWith("onDid") || key.startsWith("onWill"))) {
                let list2 = earlyListeners.get(key);
                if (!list2) {
                  list2 = new LinkedList();
                  earlyListeners.set(key, list2);
                }
                const event = (callback, thisArg, disposables) => {
                  if (idle.isInitialized) {
                    return idle.value[key](callback, thisArg, disposables);
                  } else {
                    const entry = { listener: [callback, thisArg, disposables], disposable: void 0 };
                    const rm = list2.push(entry);
                    const result = toDisposable(() => {
                      rm();
                      entry.disposable?.dispose();
                    });
                    return result;
                  }
                };
                return event;
              }
            }
            if (key in target) {
              return target[key];
            }
            const obj = idle.value;
            let prop = obj[key];
            if (typeof prop !== "function") {
              return prop;
            }
            prop = prop.bind(obj);
            target[key] = prop;
            return prop;
          },
          set(_target, p, value) {
            idle.value[p] = value;
            return true;
          },
          getPrototypeOf(_target) {
            return ctor.prototype;
          }
        });
      }
    }
    _throwIfStrict(msg, printWarning) {
      if (printWarning) {
        console.warn(msg);
      }
      if (this._strict) {
        throw new Error(msg);
      }
    }
  }
  const _Trace = class _Trace {
    static traceInvocation(_enableTracing, ctor) {
      return !_enableTracing ? _Trace._None : new _Trace(2, ctor.name || new Error().stack.split("\n").slice(3, 4).join("\n"));
    }
    static traceCreation(_enableTracing, ctor) {
      return !_enableTracing ? _Trace._None : new _Trace(1, ctor.name);
    }
    constructor(type, name) {
      this.type = type;
      this.name = name;
      this._start = Date.now();
      this._dep = [];
    }
    branch(id, first2) {
      const child = new _Trace(3, id.toString());
      this._dep.push([id, first2, child]);
      return child;
    }
    stop() {
      const dur = Date.now() - this._start;
      _Trace._totals += dur;
      let causedCreation = false;
      function printChild(n2, trace) {
        const res = [];
        const prefix = new Array(n2 + 1).join("	");
        for (const [id, first2, child] of trace._dep) {
          if (first2 && child) {
            causedCreation = true;
            res.push(`${prefix}CREATES -> ${id}`);
            const nested = printChild(n2 + 1, child);
            if (nested) {
              res.push(nested);
            }
          } else {
            res.push(`${prefix}uses -> ${id}`);
          }
        }
        return res.join("\n");
      }
      const lines = [
        `${this.type === 1 ? "CREATE" : "CALL"} ${this.name}`,
        `${printChild(1, this)}`,
        `DONE, took ${dur.toFixed(2)}ms (grand total ${_Trace._totals.toFixed(2)}ms)`
      ];
      if (dur > 2 || causedCreation) {
        _Trace.all.add(lines.join("\n"));
      }
    }
  };
  _Trace.all = /* @__PURE__ */ new Set();
  _Trace._None = new class extends _Trace {
    constructor() {
      super(0, null);
    }
    stop() {
    }
    branch() {
      return this;
    }
  }();
  _Trace._totals = 0;
  let Trace = _Trace;
  const unsupportedSchemas = /* @__PURE__ */ new Set([
    Schemas.inMemory,
    Schemas.vscodeSourceControl,
    Schemas.walkThrough,
    Schemas.walkThroughSnippet,
    Schemas.vscodeChatCodeBlock,
    Schemas.vscodeTerminal
  ]);
  class DoubleResourceMap {
    constructor() {
      this._byResource = new ResourceMap();
      this._byOwner = /* @__PURE__ */ new Map();
    }
    set(resource, owner, value) {
      let ownerMap = this._byResource.get(resource);
      if (!ownerMap) {
        ownerMap = /* @__PURE__ */ new Map();
        this._byResource.set(resource, ownerMap);
      }
      ownerMap.set(owner, value);
      let resourceMap = this._byOwner.get(owner);
      if (!resourceMap) {
        resourceMap = new ResourceMap();
        this._byOwner.set(owner, resourceMap);
      }
      resourceMap.set(resource, value);
    }
    get(resource, owner) {
      const ownerMap = this._byResource.get(resource);
      return ownerMap?.get(owner);
    }
    delete(resource, owner) {
      let removedA = false;
      let removedB = false;
      const ownerMap = this._byResource.get(resource);
      if (ownerMap) {
        removedA = ownerMap.delete(owner);
      }
      const resourceMap = this._byOwner.get(owner);
      if (resourceMap) {
        removedB = resourceMap.delete(resource);
      }
      if (removedA !== removedB) {
        throw new Error("illegal state");
      }
      return removedA && removedB;
    }
    values(key) {
      if (typeof key === "string") {
        return this._byOwner.get(key)?.values() ?? Iterable.empty();
      }
      if (URI.isUri(key)) {
        return this._byResource.get(key)?.values() ?? Iterable.empty();
      }
      return Iterable.map(Iterable.concat(...this._byOwner.values()), (map) => map[1]);
    }
  }
  class MarkerStats {
    constructor(service) {
      this.errors = 0;
      this.infos = 0;
      this.warnings = 0;
      this.unknowns = 0;
      this._data = new ResourceMap();
      this._service = service;
      this._subscription = service.onMarkerChanged(this._update, this);
    }
    dispose() {
      this._subscription.dispose();
    }
    _update(resources) {
      for (const resource of resources) {
        const oldStats = this._data.get(resource);
        if (oldStats) {
          this._substract(oldStats);
        }
        const newStats = this._resourceStats(resource);
        this._add(newStats);
        this._data.set(resource, newStats);
      }
    }
    _resourceStats(resource) {
      const result = { errors: 0, warnings: 0, infos: 0, unknowns: 0 };
      if (unsupportedSchemas.has(resource.scheme)) {
        return result;
      }
      for (const { severity } of this._service.read({ resource })) {
        if (severity === MarkerSeverity$2.Error) {
          result.errors += 1;
        } else if (severity === MarkerSeverity$2.Warning) {
          result.warnings += 1;
        } else if (severity === MarkerSeverity$2.Info) {
          result.infos += 1;
        } else {
          result.unknowns += 1;
        }
      }
      return result;
    }
    _substract(op) {
      this.errors -= op.errors;
      this.warnings -= op.warnings;
      this.infos -= op.infos;
      this.unknowns -= op.unknowns;
    }
    _add(op) {
      this.errors += op.errors;
      this.warnings += op.warnings;
      this.infos += op.infos;
      this.unknowns += op.unknowns;
    }
  }
  class MarkerService {
    constructor() {
      this._onMarkerChanged = new DebounceEmitter({
        delay: 0,
        merge: MarkerService._merge
      });
      this.onMarkerChanged = this._onMarkerChanged.event;
      this._data = new DoubleResourceMap();
      this._stats = new MarkerStats(this);
      this._filteredResources = new ResourceMap();
    }
    dispose() {
      this._stats.dispose();
      this._onMarkerChanged.dispose();
    }
    remove(owner, resources) {
      for (const resource of resources || []) {
        this.changeOne(owner, resource, []);
      }
    }
    changeOne(owner, resource, markerData) {
      if (isFalsyOrEmpty(markerData)) {
        const removed = this._data.delete(resource, owner);
        if (removed) {
          this._onMarkerChanged.fire([resource]);
        }
      } else {
        const markers = [];
        for (const data of markerData) {
          const marker = MarkerService._toMarker(owner, resource, data);
          if (marker) {
            markers.push(marker);
          }
        }
        this._data.set(resource, owner, markers);
        this._onMarkerChanged.fire([resource]);
      }
    }
    static _toMarker(owner, resource, data) {
      let { code, severity, message, source, startLineNumber, startColumn, endLineNumber, endColumn, relatedInformation, tags, origin } = data;
      if (!message) {
        return void 0;
      }
      startLineNumber = startLineNumber > 0 ? startLineNumber : 1;
      startColumn = startColumn > 0 ? startColumn : 1;
      endLineNumber = endLineNumber >= startLineNumber ? endLineNumber : startLineNumber;
      endColumn = endColumn > 0 ? endColumn : startColumn;
      return {
        resource,
        owner,
        code,
        severity,
        message,
        source,
        startLineNumber,
        startColumn,
        endLineNumber,
        endColumn,
        relatedInformation,
        tags,
        origin
      };
    }
    changeAll(owner, data) {
      const changes = [];
      const existing = this._data.values(owner);
      if (existing) {
        for (const data2 of existing) {
          const first2 = Iterable.first(data2);
          if (first2) {
            changes.push(first2.resource);
            this._data.delete(first2.resource, owner);
          }
        }
      }
      if (isNonEmptyArray(data)) {
        const groups = new ResourceMap();
        for (const { resource, marker: markerData } of data) {
          const marker = MarkerService._toMarker(owner, resource, markerData);
          if (!marker) {
            continue;
          }
          const array2 = groups.get(resource);
          if (!array2) {
            groups.set(resource, [marker]);
            changes.push(resource);
          } else {
            array2.push(marker);
          }
        }
        for (const [resource, value] of groups) {
          this._data.set(resource, owner, value);
        }
      }
      if (changes.length > 0) {
        this._onMarkerChanged.fire(changes);
      }
    }
    /**
     * Creates an information marker for filtered resources
     */
    _createFilteredMarker(resource, reasons) {
      const message = reasons.length === 1 ? localize(1738, 'Problems are paused because: "{0}"', reasons[0]) : localize(1739, 'Problems are paused because: "{0}" and {1} more', reasons[0], reasons.length - 1);
      return {
        owner: "markersFilter",
        resource,
        severity: MarkerSeverity$2.Info,
        message,
        startLineNumber: 1,
        startColumn: 1,
        endLineNumber: 1,
        endColumn: 1
      };
    }
    read(filter = /* @__PURE__ */ Object.create(null)) {
      let { owner, resource, severities, take } = filter;
      if (!take || take < 0) {
        take = -1;
      }
      if (owner && resource) {
        const reasons = !filter.ignoreResourceFilters ? this._filteredResources.get(resource) : void 0;
        if (reasons?.length) {
          const infoMarker = this._createFilteredMarker(resource, reasons);
          return [infoMarker];
        }
        const data = this._data.get(resource, owner);
        if (!data) {
          return [];
        }
        const result = [];
        for (const marker of data) {
          if (take > 0 && result.length === take) {
            break;
          }
          const reasons2 = !filter.ignoreResourceFilters ? this._filteredResources.get(resource) : void 0;
          if (reasons2?.length) {
            result.push(this._createFilteredMarker(resource, reasons2));
          } else if (MarkerService._accept(marker, severities)) {
            result.push(marker);
          }
        }
        return result;
      } else {
        const iterable = !owner && !resource ? this._data.values() : this._data.values(resource ?? owner);
        const result = [];
        const filtered = new ResourceSet();
        for (const markers of iterable) {
          for (const data of markers) {
            if (filtered.has(data.resource)) {
              continue;
            }
            if (take > 0 && result.length === take) {
              break;
            }
            const reasons = !filter.ignoreResourceFilters ? this._filteredResources.get(data.resource) : void 0;
            if (reasons?.length) {
              result.push(this._createFilteredMarker(data.resource, reasons));
              filtered.add(data.resource);
            } else if (MarkerService._accept(data, severities)) {
              result.push(data);
            }
          }
        }
        return result;
      }
    }
    static _accept(marker, severities) {
      return severities === void 0 || (severities & marker.severity) === marker.severity;
    }
    // --- event debounce logic
    static _merge(all) {
      const set = new ResourceMap();
      for (const array2 of all) {
        for (const item of array2) {
          set.set(item, true);
        }
      }
      return Array.from(set.keys());
    }
  }
  class DefaultConfiguration extends Disposable {
    get configurationModel() {
      return this._configurationModel;
    }
    constructor(logService) {
      super();
      this.logService = logService;
      this._configurationModel = ConfigurationModel.createEmptyModel(logService);
    }
    reload() {
      this.resetConfigurationModel();
      return this.configurationModel;
    }
    getConfigurationDefaultOverrides() {
      return {};
    }
    resetConfigurationModel() {
      this._configurationModel = ConfigurationModel.createEmptyModel(this.logService);
      const properties = Registry.as(Extensions$6.Configuration).getConfigurationProperties();
      this.updateConfigurationModel(Object.keys(properties), properties);
    }
    updateConfigurationModel(properties, configurationProperties) {
      const configurationDefaultsOverrides = this.getConfigurationDefaultOverrides();
      for (const key of properties) {
        const defaultOverrideValue = configurationDefaultsOverrides[key];
        const propertySchema = configurationProperties[key];
        if (defaultOverrideValue !== void 0) {
          this._configurationModel.setValue(key, defaultOverrideValue);
        } else if (propertySchema) {
          this._configurationModel.setValue(key, deepClone(propertySchema.default));
        } else {
          this._configurationModel.removeValue(key);
        }
      }
    }
  }
  class LogService extends Disposable {
    constructor(primaryLogger, otherLoggers = []) {
      super();
      this.logger = new MultiplexLogger([primaryLogger, ...otherLoggers]);
      this._register(primaryLogger.onDidChangeLogLevel((level) => this.setLevel(level)));
    }
    get onDidChangeLogLevel() {
      return this.logger.onDidChangeLogLevel;
    }
    setLevel(level) {
      this.logger.setLevel(level);
    }
    getLevel() {
      return this.logger.getLevel();
    }
    trace(message, ...args) {
      this.logger.trace(message, ...args);
    }
    debug(message, ...args) {
      this.logger.debug(message, ...args);
    }
    info(message, ...args) {
      this.logger.info(message, ...args);
    }
    warn(message, ...args) {
      this.logger.warn(message, ...args);
    }
    error(message, ...args) {
      this.logger.error(message, ...args);
    }
  }
  class StandaloneTreeSitterLibraryService {
    getParserClass() {
      throw new Error("not implemented in StandaloneTreeSitterLibraryService");
    }
    supportsLanguage(languageId, reader) {
      return false;
    }
    getLanguage(languageId, ignoreSupportsCheck, reader) {
      return void 0;
    }
    getInjectionQueries(languageId, reader) {
      return null;
    }
    getHighlightingQueries(languageId, reader) {
      return null;
    }
  }
  var __decorate$5 = 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$5 = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  class SimpleModel {
    constructor(model) {
      this.disposed = false;
      this.model = model;
      this._onWillDispose = new Emitter$1();
    }
    get textEditorModel() {
      return this.model;
    }
    dispose() {
      this.disposed = true;
      this._onWillDispose.fire();
    }
  }
  let StandaloneTextModelService = class StandaloneTextModelService {
    constructor(modelService) {
      this.modelService = modelService;
    }
    createModelReference(resource) {
      const model = this.modelService.getModel(resource);
      if (!model) {
        return Promise.reject(new Error(`Model not found`));
      }
      return Promise.resolve(new ImmortalReference(new SimpleModel(model)));
    }
  };
  StandaloneTextModelService = __decorate$5([
    __param$5(0, IModelService)
  ], StandaloneTextModelService);
  const _StandaloneEditorProgressService = class _StandaloneEditorProgressService {
    show() {
      return _StandaloneEditorProgressService.NULL_PROGRESS_RUNNER;
    }
    async showWhile(promise, delay) {
      await promise;
    }
  };
  _StandaloneEditorProgressService.NULL_PROGRESS_RUNNER = {
    done: () => {
    },
    total: () => {
    },
    worked: () => {
    }
  };
  let StandaloneEditorProgressService = _StandaloneEditorProgressService;
  class StandaloneProgressService {
    withProgress(_options, task, onDidCancel) {
      return task({
        report: () => {
        }
      });
    }
  }
  class StandaloneEnvironmentService {
    constructor() {
      this.isExtensionDevelopment = false;
      this.isBuilt = false;
    }
  }
  class StandaloneDialogService {
    async confirm(confirmation) {
      const confirmed = this.doConfirm(confirmation.message, confirmation.detail);
      return {
        confirmed,
        checkboxChecked: false
        // unsupported
      };
    }
    doConfirm(message, detail) {
      let messageText = message;
      if (detail) {
        messageText = messageText + "\n\n" + detail;
      }
      return mainWindow.confirm(messageText);
    }
    async prompt(prompt) {
      let result = void 0;
      const confirmed = this.doConfirm(prompt.message, prompt.detail);
      if (confirmed) {
        const promptButtons = [...prompt.buttons ?? []];
        if (prompt.cancelButton && typeof prompt.cancelButton !== "string" && typeof prompt.cancelButton !== "boolean") {
          promptButtons.push(prompt.cancelButton);
        }
        result = await promptButtons[0]?.run({ checkboxChecked: false });
      }
      return { result };
    }
    async error(message, detail) {
      await this.prompt({ type: Severity$2.Error, message, detail });
    }
  }
  const _StandaloneNotificationService = class _StandaloneNotificationService {
    info(message) {
      return this.notify({ severity: Severity$2.Info, message });
    }
    warn(message) {
      return this.notify({ severity: Severity$2.Warning, message });
    }
    error(error) {
      return this.notify({ severity: Severity$2.Error, message: error });
    }
    notify(notification) {
      switch (notification.severity) {
        case Severity$2.Error:
          console.error(notification.message);
          break;
        case Severity$2.Warning:
          console.warn(notification.message);
          break;
        default:
          console.log(notification.message);
          break;
      }
      return _StandaloneNotificationService.NO_OP;
    }
    prompt(severity, message, choices, options) {
      return _StandaloneNotificationService.NO_OP;
    }
    status(message, options) {
      return { close: () => {
      } };
    }
  };
  _StandaloneNotificationService.NO_OP = new NoOpNotification();
  let StandaloneNotificationService = _StandaloneNotificationService;
  let StandaloneCommandService = class StandaloneCommandService {
    constructor(instantiationService) {
      this._onWillExecuteCommand = new Emitter$1();
      this._onDidExecuteCommand = new Emitter$1();
      this.onDidExecuteCommand = this._onDidExecuteCommand.event;
      this._instantiationService = instantiationService;
    }
    executeCommand(id, ...args) {
      const command = CommandsRegistry.getCommand(id);
      if (!command) {
        return Promise.reject(new Error(`command '${id}' not found`));
      }
      try {
        this._onWillExecuteCommand.fire({ commandId: id, args });
        const result = this._instantiationService.invokeFunction.apply(this._instantiationService, [command.handler, ...args]);
        this._onDidExecuteCommand.fire({ commandId: id, args });
        return Promise.resolve(result);
      } catch (err) {
        return Promise.reject(err);
      }
    }
  };
  StandaloneCommandService = __decorate$5([
    __param$5(0, IInstantiationService)
  ], StandaloneCommandService);
  let StandaloneKeybindingService = class StandaloneKeybindingService extends AbstractKeybindingService {
    constructor(contextKeyService, commandService, telemetryService, notificationService, logService, codeEditorService) {
      super(contextKeyService, commandService, telemetryService, notificationService, logService);
      this._cachedResolver = null;
      this._dynamicKeybindings = [];
      this._domNodeListeners = [];
      const addContainer = (domNode) => {
        const disposables = new DisposableStore();
        disposables.add(addDisposableListener(domNode, EventType$1.KEY_DOWN, (e) => {
          const keyEvent = new StandardKeyboardEvent(e);
          const shouldPreventDefault = this._dispatch(keyEvent, keyEvent.target);
          if (shouldPreventDefault) {
            keyEvent.preventDefault();
            keyEvent.stopPropagation();
          }
        }));
        disposables.add(addDisposableListener(domNode, EventType$1.KEY_UP, (e) => {
          const keyEvent = new StandardKeyboardEvent(e);
          const shouldPreventDefault = this._singleModifierDispatch(keyEvent, keyEvent.target);
          if (shouldPreventDefault) {
            keyEvent.preventDefault();
          }
        }));
        this._domNodeListeners.push(new DomNodeListeners(domNode, disposables));
      };
      const removeContainer = (domNode) => {
        for (let i2 = 0; i2 < this._domNodeListeners.length; i2++) {
          const domNodeListeners = this._domNodeListeners[i2];
          if (domNodeListeners.domNode === domNode) {
            this._domNodeListeners.splice(i2, 1);
            domNodeListeners.dispose();
          }
        }
      };
      const addCodeEditor = (codeEditor) => {
        if (codeEditor.getOption(
          70
          /* EditorOption.inDiffEditor */
        )) {
          return;
        }
        addContainer(codeEditor.getContainerDomNode());
      };
      const removeCodeEditor = (codeEditor) => {
        if (codeEditor.getOption(
          70
          /* EditorOption.inDiffEditor */
        )) {
          return;
        }
        removeContainer(codeEditor.getContainerDomNode());
      };
      this._register(codeEditorService.onCodeEditorAdd(addCodeEditor));
      this._register(codeEditorService.onCodeEditorRemove(removeCodeEditor));
      codeEditorService.listCodeEditors().forEach(addCodeEditor);
      const addDiffEditor = (diffEditor) => {
        addContainer(diffEditor.getContainerDomNode());
      };
      const removeDiffEditor = (diffEditor) => {
        removeContainer(diffEditor.getContainerDomNode());
      };
      this._register(codeEditorService.onDiffEditorAdd(addDiffEditor));
      this._register(codeEditorService.onDiffEditorRemove(removeDiffEditor));
      codeEditorService.listDiffEditors().forEach(addDiffEditor);
    }
    addDynamicKeybinding(command, keybinding, handler, when) {
      return combinedDisposable(CommandsRegistry.registerCommand(command, handler), this.addDynamicKeybindings([{
        keybinding,
        command,
        when
      }]));
    }
    addDynamicKeybindings(rules) {
      const entries2 = rules.map((rule) => {
        const keybinding = decodeKeybinding(rule.keybinding, OS);
        return {
          keybinding,
          command: rule.command ?? null,
          commandArgs: rule.commandArgs,
          when: rule.when,
          weight1: 1e3,
          weight2: 0,
          extensionId: null,
          isBuiltinExtension: false
        };
      });
      this._dynamicKeybindings = this._dynamicKeybindings.concat(entries2);
      this.updateResolver();
      return toDisposable(() => {
        for (let i2 = 0; i2 < this._dynamicKeybindings.length; i2++) {
          if (this._dynamicKeybindings[i2] === entries2[0]) {
            this._dynamicKeybindings.splice(i2, entries2.length);
            this.updateResolver();
            return;
          }
        }
      });
    }
    updateResolver() {
      this._cachedResolver = null;
      this._onDidUpdateKeybindings.fire();
    }
    _getResolver() {
      if (!this._cachedResolver) {
        const defaults = this._toNormalizedKeybindingItems(KeybindingsRegistry.getDefaultKeybindings(), true);
        const overrides = this._toNormalizedKeybindingItems(this._dynamicKeybindings, false);
        this._cachedResolver = new KeybindingResolver(defaults, overrides, (str) => this._log(str));
      }
      return this._cachedResolver;
    }
    _documentHasFocus() {
      return mainWindow.document.hasFocus();
    }
    _toNormalizedKeybindingItems(items, isDefault) {
      const result = [];
      let resultLen = 0;
      for (const item of items) {
        const when = item.when || void 0;
        const keybinding = item.keybinding;
        if (!keybinding) {
          result[resultLen++] = new ResolvedKeybindingItem(void 0, item.command, item.commandArgs, when, isDefault, null, false);
        } else {
          const resolvedKeybindings = USLayoutResolvedKeybinding.resolveKeybinding(keybinding, OS);
          for (const resolvedKeybinding of resolvedKeybindings) {
            result[resultLen++] = new ResolvedKeybindingItem(resolvedKeybinding, item.command, item.commandArgs, when, isDefault, null, false);
          }
        }
      }
      return result;
    }
    resolveKeyboardEvent(keyboardEvent) {
      const chord = new KeyCodeChord(keyboardEvent.ctrlKey, keyboardEvent.shiftKey, keyboardEvent.altKey, keyboardEvent.metaKey, keyboardEvent.keyCode);
      return new USLayoutResolvedKeybinding([chord], OS);
    }
  };
  StandaloneKeybindingService = __decorate$5([
    __param$5(0, IContextKeyService),
    __param$5(1, ICommandService),
    __param$5(2, ITelemetryService),
    __param$5(3, INotificationService),
    __param$5(4, ILogService),
    __param$5(5, ICodeEditorService)
  ], StandaloneKeybindingService);
  class DomNodeListeners extends Disposable {
    constructor(domNode, disposables) {
      super();
      this.domNode = domNode;
      this._register(disposables);
    }
  }
  function isConfigurationOverrides(thing) {
    return !!thing && typeof thing === "object" && (!thing.overrideIdentifier || typeof thing.overrideIdentifier === "string") && (!thing.resource || thing.resource instanceof URI);
  }
  let StandaloneConfigurationService = class StandaloneConfigurationService {
    constructor(logService) {
      this.logService = logService;
      this._onDidChangeConfiguration = new Emitter$1();
      this.onDidChangeConfiguration = this._onDidChangeConfiguration.event;
      const defaultConfiguration = new DefaultConfiguration(logService);
      this._configuration = new Configuration(defaultConfiguration.reload(), ConfigurationModel.createEmptyModel(logService), ConfigurationModel.createEmptyModel(logService), ConfigurationModel.createEmptyModel(logService), ConfigurationModel.createEmptyModel(logService), ConfigurationModel.createEmptyModel(logService), new ResourceMap(), ConfigurationModel.createEmptyModel(logService), new ResourceMap(), logService);
      defaultConfiguration.dispose();
    }
    getValue(arg1, arg2) {
      const section = typeof arg1 === "string" ? arg1 : void 0;
      const overrides = isConfigurationOverrides(arg1) ? arg1 : isConfigurationOverrides(arg2) ? arg2 : {};
      return this._configuration.getValue(section, overrides, void 0);
    }
    updateValues(values) {
      const previous = { data: this._configuration.toData() };
      const changedKeys = [];
      for (const entry of values) {
        const [key, value] = entry;
        if (this.getValue(key) === value) {
          continue;
        }
        this._configuration.updateValue(key, value);
        changedKeys.push(key);
      }
      if (changedKeys.length > 0) {
        const configurationChangeEvent = new ConfigurationChangeEvent({ keys: changedKeys, overrides: [] }, previous, this._configuration, void 0, this.logService);
        configurationChangeEvent.source = 8;
        this._onDidChangeConfiguration.fire(configurationChangeEvent);
      }
      return Promise.resolve();
    }
    updateValue(key, value, arg3, arg4) {
      return this.updateValues([[key, value]]);
    }
    inspect(key, options = {}) {
      return this._configuration.inspect(key, options, void 0);
    }
  };
  StandaloneConfigurationService = __decorate$5([
    __param$5(0, ILogService)
  ], StandaloneConfigurationService);
  let StandaloneResourceConfigurationService = class StandaloneResourceConfigurationService {
    constructor(configurationService, modelService, languageService) {
      this.configurationService = configurationService;
      this.modelService = modelService;
      this.languageService = languageService;
      this._onDidChangeConfiguration = new Emitter$1();
      this.configurationService.onDidChangeConfiguration((e) => {
        this._onDidChangeConfiguration.fire({ affectedKeys: e.affectedKeys, affectsConfiguration: (resource, configuration) => e.affectsConfiguration(configuration) });
      });
    }
    getValue(resource, arg2, arg3) {
      const position = Position$1.isIPosition(arg2) ? arg2 : null;
      const section = position ? typeof arg3 === "string" ? arg3 : void 0 : typeof arg2 === "string" ? arg2 : void 0;
      const language2 = resource ? this.getLanguage(resource, position) : void 0;
      if (typeof section === "undefined") {
        return this.configurationService.getValue({
          resource,
          overrideIdentifier: language2
        });
      }
      return this.configurationService.getValue(section, {
        resource,
        overrideIdentifier: language2
      });
    }
    getLanguage(resource, position) {
      const model = this.modelService.getModel(resource);
      if (model) {
        return position ? model.getLanguageIdAtPosition(position.lineNumber, position.column) : model.getLanguageId();
      }
      return this.languageService.guessLanguageIdByFilepathOrFirstLine(resource);
    }
  };
  StandaloneResourceConfigurationService = __decorate$5([
    __param$5(0, IConfigurationService),
    __param$5(1, IModelService),
    __param$5(2, ILanguageService)
  ], StandaloneResourceConfigurationService);
  let StandaloneResourcePropertiesService = class StandaloneResourcePropertiesService {
    constructor(configurationService) {
      this.configurationService = configurationService;
    }
    getEOL(resource, language2) {
      const eol = this.configurationService.getValue("files.eol", { overrideIdentifier: language2, resource });
      if (eol && typeof eol === "string" && eol !== "auto") {
        return eol;
      }
      return isLinux || isMacintosh ? "\n" : "\r\n";
    }
  };
  StandaloneResourcePropertiesService = __decorate$5([
    __param$5(0, IConfigurationService)
  ], StandaloneResourcePropertiesService);
  class StandaloneTelemetryService {
    publicLog2() {
    }
  }
  const _StandaloneWorkspaceContextService = class _StandaloneWorkspaceContextService {
    constructor() {
      const resource = URI.from({ scheme: _StandaloneWorkspaceContextService.SCHEME, authority: "model", path: "/" });
      this.workspace = { id: STANDALONE_EDITOR_WORKSPACE_ID, folders: [new WorkspaceFolder({ uri: resource, name: "", index: 0 })] };
    }
    getWorkspace() {
      return this.workspace;
    }
    getWorkspaceFolder(resource) {
      return resource && resource.scheme === _StandaloneWorkspaceContextService.SCHEME ? this.workspace.folders[0] : null;
    }
  };
  _StandaloneWorkspaceContextService.SCHEME = "inmemory";
  let StandaloneWorkspaceContextService = _StandaloneWorkspaceContextService;
  function updateConfigurationService(configurationService, source, isDiffEditor2) {
    if (!source) {
      return;
    }
    if (!(configurationService instanceof StandaloneConfigurationService)) {
      return;
    }
    const toUpdate = [];
    Object.keys(source).forEach((key) => {
      if (isEditorConfigurationKey(key)) {
        toUpdate.push([`editor.${key}`, source[key]]);
      }
      if (isDiffEditor2 && isDiffEditorConfigurationKey(key)) {
        toUpdate.push([`diffEditor.${key}`, source[key]]);
      }
    });
    if (toUpdate.length > 0) {
      configurationService.updateValues(toUpdate);
    }
  }
  let StandaloneBulkEditService = class StandaloneBulkEditService {
    constructor(_modelService) {
      this._modelService = _modelService;
    }
    hasPreviewHandler() {
      return false;
    }
    async apply(editsIn, _options) {
      const edits = Array.isArray(editsIn) ? editsIn : ResourceEdit.convert(editsIn);
      const textEdits = /* @__PURE__ */ new Map();
      for (const edit2 of edits) {
        if (!(edit2 instanceof ResourceTextEdit)) {
          throw new Error("bad edit - only text edits are supported");
        }
        const model = this._modelService.getModel(edit2.resource);
        if (!model) {
          throw new Error("bad edit - model not found");
        }
        if (typeof edit2.versionId === "number" && model.getVersionId() !== edit2.versionId) {
          throw new Error("bad state - model changed in the meantime");
        }
        let array2 = textEdits.get(model);
        if (!array2) {
          array2 = [];
          textEdits.set(model, array2);
        }
        array2.push(EditOperation.replaceMove(Range$2.lift(edit2.textEdit.range), edit2.textEdit.text));
      }
      let totalEdits = 0;
      let totalFiles = 0;
      for (const [model, edits2] of textEdits) {
        model.pushStackElement();
        model.pushEditOperations([], edits2, () => []);
        model.pushStackElement();
        totalFiles += 1;
        totalEdits += edits2.length;
      }
      return {
        ariaSummary: format(StandaloneServicesNLS.bulkEditServiceSummary, totalEdits, totalFiles),
        isApplied: totalEdits > 0
      };
    }
  };
  StandaloneBulkEditService = __decorate$5([
    __param$5(0, IModelService)
  ], StandaloneBulkEditService);
  class StandaloneUriLabelService {
    getUriLabel(resource, options) {
      if (resource.scheme === "file") {
        return resource.fsPath;
      }
      return resource.path;
    }
    getUriBasenameLabel(resource) {
      return basename(resource);
    }
  }
  let StandaloneContextViewService = class StandaloneContextViewService extends ContextViewService {
    constructor(layoutService, _codeEditorService) {
      super(layoutService);
      this._codeEditorService = _codeEditorService;
    }
    showContextView(delegate, container, shadowRoot) {
      if (!container) {
        const codeEditor = this._codeEditorService.getFocusedCodeEditor() || this._codeEditorService.getActiveCodeEditor();
        if (codeEditor) {
          container = codeEditor.getContainerDomNode();
        }
      }
      return super.showContextView(delegate, container, shadowRoot);
    }
  };
  StandaloneContextViewService = __decorate$5([
    __param$5(0, ILayoutService),
    __param$5(1, ICodeEditorService)
  ], StandaloneContextViewService);
  class StandaloneWorkspaceTrustManagementService {
    constructor() {
      this._neverEmitter = new Emitter$1();
      this.onDidChangeTrust = this._neverEmitter.event;
    }
    isWorkspaceTrusted() {
      return true;
    }
  }
  class StandaloneLanguageService extends LanguageService {
    constructor() {
      super();
    }
  }
  class StandaloneLogService extends LogService {
    constructor() {
      super(new ConsoleLogger());
    }
  }
  let StandaloneContextMenuService = class StandaloneContextMenuService extends ContextMenuService {
    constructor(telemetryService, notificationService, contextViewService, keybindingService, menuService, contextKeyService) {
      super(telemetryService, notificationService, contextViewService, keybindingService, menuService, contextKeyService);
      this.configure({ blockMouse: false });
    }
  };
  StandaloneContextMenuService = __decorate$5([
    __param$5(0, ITelemetryService),
    __param$5(1, INotificationService),
    __param$5(2, IContextViewService),
    __param$5(3, IKeybindingService),
    __param$5(4, IMenuService),
    __param$5(5, IContextKeyService)
  ], StandaloneContextMenuService);
  const standaloneEditorWorkerDescriptor = {
    esmModuleLocation: void 0,
    label: "editorWorkerService"
  };
  let StandaloneEditorWorkerService = class StandaloneEditorWorkerService extends EditorWorkerService {
    constructor(modelService, configurationService, logService, languageConfigurationService, languageFeaturesService) {
      super(standaloneEditorWorkerDescriptor, modelService, configurationService, logService, languageConfigurationService, languageFeaturesService);
    }
  };
  StandaloneEditorWorkerService = __decorate$5([
    __param$5(0, IModelService),
    __param$5(1, ITextResourceConfigurationService),
    __param$5(2, ILogService),
    __param$5(3, ILanguageConfigurationService),
    __param$5(4, ILanguageFeaturesService)
  ], StandaloneEditorWorkerService);
  class StandaloneAccessbilitySignalService {
    async playSignal(cue, options) {
    }
  }
  registerSingleton(
    ILogService,
    StandaloneLogService,
    0
    /* InstantiationType.Eager */
  );
  registerSingleton(
    IConfigurationService,
    StandaloneConfigurationService,
    0
    /* InstantiationType.Eager */
  );
  registerSingleton(
    ITextResourceConfigurationService,
    StandaloneResourceConfigurationService,
    0
    /* InstantiationType.Eager */
  );
  registerSingleton(
    ITextResourcePropertiesService,
    StandaloneResourcePropertiesService,
    0
    /* InstantiationType.Eager */
  );
  registerSingleton(
    IWorkspaceContextService,
    StandaloneWorkspaceContextService,
    0
    /* InstantiationType.Eager */
  );
  registerSingleton(
    ILabelService,
    StandaloneUriLabelService,
    0
    /* InstantiationType.Eager */
  );
  registerSingleton(
    ITelemetryService,
    StandaloneTelemetryService,
    0
    /* InstantiationType.Eager */
  );
  registerSingleton(
    IDialogService,
    StandaloneDialogService,
    0
    /* InstantiationType.Eager */
  );
  registerSingleton(
    IEnvironmentService,
    StandaloneEnvironmentService,
    0
    /* InstantiationType.Eager */
  );
  registerSingleton(
    INotificationService,
    StandaloneNotificationService,
    0
    /* InstantiationType.Eager */
  );
  registerSingleton(
    IMarkerService,
    MarkerService,
    0
    /* InstantiationType.Eager */
  );
  registerSingleton(
    ILanguageService,
    StandaloneLanguageService,
    0
    /* InstantiationType.Eager */
  );
  registerSingleton(
    IStandaloneThemeService,
    StandaloneThemeService,
    0
    /* InstantiationType.Eager */
  );
  registerSingleton(
    IModelService,
    ModelService,
    0
    /* InstantiationType.Eager */
  );
  registerSingleton(
    IMarkerDecorationsService,
    MarkerDecorationsService,
    0
    /* InstantiationType.Eager */
  );
  registerSingleton(
    IContextKeyService,
    ContextKeyService,
    0
    /* InstantiationType.Eager */
  );
  registerSingleton(
    IProgressService,
    StandaloneProgressService,
    0
    /* InstantiationType.Eager */
  );
  registerSingleton(
    IEditorProgressService,
    StandaloneEditorProgressService,
    0
    /* InstantiationType.Eager */
  );
  registerSingleton(
    IStorageService,
    InMemoryStorageService,
    0
    /* InstantiationType.Eager */
  );
  registerSingleton(
    IEditorWorkerService,
    StandaloneEditorWorkerService,
    0
    /* InstantiationType.Eager */
  );
  registerSingleton(
    IBulkEditService,
    StandaloneBulkEditService,
    0
    /* InstantiationType.Eager */
  );
  registerSingleton(
    IWorkspaceTrustManagementService,
    StandaloneWorkspaceTrustManagementService,
    0
    /* InstantiationType.Eager */
  );
  registerSingleton(
    ITextModelService,
    StandaloneTextModelService,
    0
    /* InstantiationType.Eager */
  );
  registerSingleton(
    IAccessibilityService,
    AccessibilityService,
    0
    /* InstantiationType.Eager */
  );
  registerSingleton(
    IListService,
    ListService,
    0
    /* InstantiationType.Eager */
  );
  registerSingleton(
    ICommandService,
    StandaloneCommandService,
    0
    /* InstantiationType.Eager */
  );
  registerSingleton(
    IKeybindingService,
    StandaloneKeybindingService,
    0
    /* InstantiationType.Eager */
  );
  registerSingleton(
    IQuickInputService,
    StandaloneQuickInputService,
    0
    /* InstantiationType.Eager */
  );
  registerSingleton(
    IContextViewService,
    StandaloneContextViewService,
    0
    /* InstantiationType.Eager */
  );
  registerSingleton(
    IOpenerService,
    OpenerService,
    0
    /* InstantiationType.Eager */
  );
  registerSingleton(
    IClipboardService,
    BrowserClipboardService,
    0
    /* InstantiationType.Eager */
  );
  registerSingleton(
    IContextMenuService,
    StandaloneContextMenuService,
    0
    /* InstantiationType.Eager */
  );
  registerSingleton(
    IMenuService,
    MenuService,
    0
    /* InstantiationType.Eager */
  );
  registerSingleton(
    IAccessibilitySignalService,
    StandaloneAccessbilitySignalService,
    0
    /* InstantiationType.Eager */
  );
  registerSingleton(
    ITreeSitterLibraryService,
    StandaloneTreeSitterLibraryService,
    0
    /* InstantiationType.Eager */
  );
  registerSingleton(
    ILoggerService,
    NullLoggerService,
    0
    /* InstantiationType.Eager */
  );
  registerSingleton(
    IDataChannelService,
    NullDataChannelService,
    0
    /* InstantiationType.Eager */
  );
  var StandaloneServices;
  (function(StandaloneServices2) {
    const serviceCollection = new ServiceCollection();
    for (const [id, descriptor] of getSingletonServiceDescriptors()) {
      serviceCollection.set(id, descriptor);
    }
    const instantiationService = new InstantiationService(serviceCollection, true);
    serviceCollection.set(IInstantiationService, instantiationService);
    function get(serviceId) {
      if (!initialized) {
        initialize2({});
      }
      const r = serviceCollection.get(serviceId);
      if (!r) {
        throw new Error("Missing service " + serviceId);
      }
      if (r instanceof SyncDescriptor) {
        return instantiationService.invokeFunction((accessor) => accessor.get(serviceId));
      } else {
        return r;
      }
    }
    StandaloneServices2.get = get;
    let initialized = false;
    const onDidInitialize = new Emitter$1();
    function initialize2(overrides) {
      if (initialized) {
        return instantiationService;
      }
      initialized = true;
      for (const [id, descriptor] of getSingletonServiceDescriptors()) {
        if (!serviceCollection.get(id)) {
          serviceCollection.set(id, descriptor);
        }
      }
      for (const serviceId in overrides) {
        if (overrides.hasOwnProperty(serviceId)) {
          const serviceIdentifier = createDecorator(serviceId);
          const r = serviceCollection.get(serviceIdentifier);
          if (r instanceof SyncDescriptor) {
            serviceCollection.set(serviceIdentifier, overrides[serviceId]);
          }
        }
      }
      const editorFeatures2 = getEditorFeatures();
      for (const feature of editorFeatures2) {
        try {
          instantiationService.createInstance(feature);
        } catch (err) {
          onUnexpectedError(err);
        }
      }
      onDidInitialize.fire();
      return instantiationService;
    }
    StandaloneServices2.initialize = initialize2;
    function withServices(callback) {
      if (initialized) {
        return callback();
      }
      const disposable = new DisposableStore();
      const listener = disposable.add(onDidInitialize.event(() => {
        listener.dispose();
        disposable.add(callback());
      }));
      return disposable;
    }
    StandaloneServices2.withServices = withServices;
  })(StandaloneServices || (StandaloneServices = {}));
  var __decorate$4 = 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$4 = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  var EditorMarkdownCodeBlockRenderer_1;
  let EditorMarkdownCodeBlockRenderer = (_Sa = class {
    constructor(_configurationService, _languageService) {
      this._configurationService = _configurationService;
      this._languageService = _languageService;
    }
    async renderCodeBlock(languageAlias, value, options) {
      const editor2 = isCodeEditor(options.context) ? options.context : void 0;
      let languageId;
      if (languageAlias) {
        languageId = this._languageService.getLanguageIdByLanguageName(languageAlias);
      } else if (editor2) {
        languageId = editor2.getModel()?.getLanguageId();
      }
      if (!languageId) {
        languageId = PLAINTEXT_LANGUAGE_ID;
      }
      const html2 = await tokenizeToString(this._languageService, value, languageId);
      const content = EditorMarkdownCodeBlockRenderer_1._ttpTokenizer ? EditorMarkdownCodeBlockRenderer_1._ttpTokenizer.createHTML(html2) ?? html2 : html2;
      const root = document.createElement("span");
      root.innerHTML = content;
      const codeElement = root.querySelector(".monaco-tokenized-source");
      if (!isHTMLElement(codeElement)) {
        return document.createElement("span");
      }
      applyFontInfo(codeElement, this.getFontInfo(editor2));
      return root;
    }
    getFontInfo(editor2) {
      if (editor2) {
        return editor2.getOption(
          59
          /* EditorOption.fontInfo */
        );
      } else {
        return createBareFontInfoFromRawSettings({
          fontFamily: this._configurationService.getValue("editor").fontFamily
        }, 1);
      }
    }
  }, EditorMarkdownCodeBlockRenderer_1 = _Sa, _Sa._ttpTokenizer = createTrustedTypesPolicy("tokenizeToString", {
    createHTML(html2) {
      return html2;
    }
  }), _Sa);
  EditorMarkdownCodeBlockRenderer = EditorMarkdownCodeBlockRenderer_1 = __decorate$4([
    __param$4(0, IConfigurationService),
    __param$4(1, ILanguageService)
  ], EditorMarkdownCodeBlockRenderer);
  var __decorate$3 = 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$3 = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  let LAST_GENERATED_COMMAND_ID = 0;
  let ariaDomNodeCreated = false;
  function createAriaDomNode(parent) {
    if (!parent) {
      if (ariaDomNodeCreated) {
        return;
      }
      ariaDomNodeCreated = true;
    }
    setARIAContainer(parent || mainWindow.document.body);
  }
  let StandaloneCodeEditor = class StandaloneCodeEditor extends CodeEditorWidget {
    constructor(domElement, _options, instantiationService, codeEditorService, commandService, contextKeyService, hoverService, keybindingService, themeService, notificationService, accessibilityService, languageConfigurationService, languageFeaturesService, markdownRendererService) {
      const options = { ..._options };
      options.ariaLabel = options.ariaLabel || StandaloneCodeEditorNLS.editorViewAccessibleLabel;
      super(domElement, options, {}, instantiationService, codeEditorService, commandService, contextKeyService, themeService, notificationService, accessibilityService, languageConfigurationService, languageFeaturesService);
      if (keybindingService instanceof StandaloneKeybindingService) {
        this._standaloneKeybindingService = keybindingService;
      } else {
        this._standaloneKeybindingService = null;
      }
      createAriaDomNode(options.ariaContainerElement);
      setHoverDelegateFactory((placement, enableInstantHover) => instantiationService.createInstance(WorkbenchHoverDelegate, placement, { instantHover: enableInstantHover }, {}));
      setBaseLayerHoverDelegate(hoverService);
      markdownRendererService.setDefaultCodeBlockRenderer(instantiationService.createInstance(EditorMarkdownCodeBlockRenderer));
    }
    addCommand(keybinding, handler, context) {
      if (!this._standaloneKeybindingService) {
        console.warn("Cannot add command because the editor is configured with an unrecognized KeybindingService");
        return null;
      }
      const commandId = "DYNAMIC_" + ++LAST_GENERATED_COMMAND_ID;
      const whenExpression = ContextKeyExpr.deserialize(context);
      this._standaloneKeybindingService.addDynamicKeybinding(commandId, keybinding, handler, whenExpression);
      return commandId;
    }
    createContextKey(key, defaultValue) {
      return this._contextKeyService.createKey(key, defaultValue);
    }
    addAction(_descriptor) {
      if (typeof _descriptor.id !== "string" || typeof _descriptor.label !== "string" || typeof _descriptor.run !== "function") {
        throw new Error("Invalid action descriptor, `id`, `label` and `run` are required properties!");
      }
      if (!this._standaloneKeybindingService) {
        console.warn("Cannot add keybinding because the editor is configured with an unrecognized KeybindingService");
        return Disposable.None;
      }
      const id = _descriptor.id;
      const label = _descriptor.label;
      const precondition = ContextKeyExpr.and(ContextKeyExpr.equals("editorId", this.getId()), ContextKeyExpr.deserialize(_descriptor.precondition));
      const keybindings = _descriptor.keybindings;
      const keybindingsWhen = ContextKeyExpr.and(precondition, ContextKeyExpr.deserialize(_descriptor.keybindingContext));
      const contextMenuGroupId = _descriptor.contextMenuGroupId || null;
      const contextMenuOrder = _descriptor.contextMenuOrder || 0;
      const run = (_accessor, ...args) => {
        return Promise.resolve(_descriptor.run(this, ...args));
      };
      const toDispose = new DisposableStore();
      const uniqueId = this.getId() + ":" + id;
      toDispose.add(CommandsRegistry.registerCommand(uniqueId, run));
      if (contextMenuGroupId) {
        const menuItem = {
          command: {
            id: uniqueId,
            title: label
          },
          when: precondition,
          group: contextMenuGroupId,
          order: contextMenuOrder
        };
        toDispose.add(MenuRegistry.appendMenuItem(MenuId.EditorContext, menuItem));
      }
      if (Array.isArray(keybindings)) {
        for (const kb of keybindings) {
          toDispose.add(this._standaloneKeybindingService.addDynamicKeybinding(uniqueId, kb, run, keybindingsWhen));
        }
      }
      const internalAction = new InternalEditorAction(uniqueId, label, label, void 0, precondition, (...args) => Promise.resolve(_descriptor.run(this, ...args)), this._contextKeyService);
      this._actions.set(id, internalAction);
      toDispose.add(toDisposable(() => {
        this._actions.delete(id);
      }));
      return toDispose;
    }
    _triggerCommand(handlerId, payload) {
      if (this._codeEditorService instanceof StandaloneCodeEditorService) {
        try {
          this._codeEditorService.setActiveCodeEditor(this);
          super._triggerCommand(handlerId, payload);
        } finally {
          this._codeEditorService.setActiveCodeEditor(null);
        }
      } else {
        super._triggerCommand(handlerId, payload);
      }
    }
  };
  StandaloneCodeEditor = __decorate$3([
    __param$3(2, IInstantiationService),
    __param$3(3, ICodeEditorService),
    __param$3(4, ICommandService),
    __param$3(5, IContextKeyService),
    __param$3(6, IHoverService),
    __param$3(7, IKeybindingService),
    __param$3(8, IThemeService),
    __param$3(9, INotificationService),
    __param$3(10, IAccessibilityService),
    __param$3(11, ILanguageConfigurationService),
    __param$3(12, ILanguageFeaturesService),
    __param$3(13, IMarkdownRendererService)
  ], StandaloneCodeEditor);
  let StandaloneEditor = class StandaloneEditor extends StandaloneCodeEditor {
    constructor(domElement, _options, instantiationService, codeEditorService, commandService, contextKeyService, hoverService, keybindingService, themeService, notificationService, configurationService, accessibilityService, modelService, languageService, languageConfigurationService, languageFeaturesService, markdownRendererService) {
      const options = { ..._options };
      updateConfigurationService(configurationService, options, false);
      const themeDomRegistration = themeService.registerEditorContainer(domElement);
      if (typeof options.theme === "string") {
        themeService.setTheme(options.theme);
      }
      if (typeof options.autoDetectHighContrast !== "undefined") {
        themeService.setAutoDetectHighContrast(Boolean(options.autoDetectHighContrast));
      }
      const _model = options.model;
      delete options.model;
      super(domElement, options, instantiationService, codeEditorService, commandService, contextKeyService, hoverService, keybindingService, themeService, notificationService, accessibilityService, languageConfigurationService, languageFeaturesService, markdownRendererService);
      this._configurationService = configurationService;
      this._standaloneThemeService = themeService;
      this._register(themeDomRegistration);
      let model;
      if (typeof _model === "undefined") {
        const languageId = languageService.getLanguageIdByMimeType(options.language) || options.language || PLAINTEXT_LANGUAGE_ID;
        model = createTextModel(modelService, languageService, options.value || "", languageId, void 0);
        this._ownsModel = true;
      } else {
        model = _model;
        this._ownsModel = false;
      }
      this._attachModel(model);
      if (model) {
        const e = {
          oldModelUrl: null,
          newModelUrl: model.uri
        };
        this._onDidChangeModel.fire(e);
      }
    }
    dispose() {
      super.dispose();
    }
    updateOptions(newOptions) {
      updateConfigurationService(this._configurationService, newOptions, false);
      if (typeof newOptions.theme === "string") {
        this._standaloneThemeService.setTheme(newOptions.theme);
      }
      if (typeof newOptions.autoDetectHighContrast !== "undefined") {
        this._standaloneThemeService.setAutoDetectHighContrast(Boolean(newOptions.autoDetectHighContrast));
      }
      super.updateOptions(newOptions);
    }
    _postDetachModelCleanup(detachedModel) {
      super._postDetachModelCleanup(detachedModel);
      if (detachedModel && this._ownsModel) {
        detachedModel.dispose();
        this._ownsModel = false;
      }
    }
  };
  StandaloneEditor = __decorate$3([
    __param$3(2, IInstantiationService),
    __param$3(3, ICodeEditorService),
    __param$3(4, ICommandService),
    __param$3(5, IContextKeyService),
    __param$3(6, IHoverService),
    __param$3(7, IKeybindingService),
    __param$3(8, IStandaloneThemeService),
    __param$3(9, INotificationService),
    __param$3(10, IConfigurationService),
    __param$3(11, IAccessibilityService),
    __param$3(12, IModelService),
    __param$3(13, ILanguageService),
    __param$3(14, ILanguageConfigurationService),
    __param$3(15, ILanguageFeaturesService),
    __param$3(16, IMarkdownRendererService)
  ], StandaloneEditor);
  let StandaloneDiffEditor2 = class StandaloneDiffEditor2 extends DiffEditorWidget {
    constructor(domElement, _options, instantiationService, contextKeyService, codeEditorService, themeService, notificationService, configurationService, contextMenuService, editorProgressService, clipboardService, accessibilitySignalService) {
      const options = { ..._options };
      updateConfigurationService(configurationService, options, true);
      const themeDomRegistration = themeService.registerEditorContainer(domElement);
      if (typeof options.theme === "string") {
        themeService.setTheme(options.theme);
      }
      if (typeof options.autoDetectHighContrast !== "undefined") {
        themeService.setAutoDetectHighContrast(Boolean(options.autoDetectHighContrast));
      }
      super(domElement, options, {}, contextKeyService, instantiationService, codeEditorService, accessibilitySignalService, editorProgressService);
      this._configurationService = configurationService;
      this._standaloneThemeService = themeService;
      this._register(themeDomRegistration);
    }
    dispose() {
      super.dispose();
    }
    updateOptions(newOptions) {
      updateConfigurationService(this._configurationService, newOptions, true);
      if (typeof newOptions.theme === "string") {
        this._standaloneThemeService.setTheme(newOptions.theme);
      }
      if (typeof newOptions.autoDetectHighContrast !== "undefined") {
        this._standaloneThemeService.setAutoDetectHighContrast(Boolean(newOptions.autoDetectHighContrast));
      }
      super.updateOptions(newOptions);
    }
    _createInnerEditor(instantiationService, container, options) {
      return instantiationService.createInstance(StandaloneCodeEditor, container, options);
    }
    getOriginalEditor() {
      return super.getOriginalEditor();
    }
    getModifiedEditor() {
      return super.getModifiedEditor();
    }
    addCommand(keybinding, handler, context) {
      return this.getModifiedEditor().addCommand(keybinding, handler, context);
    }
    createContextKey(key, defaultValue) {
      return this.getModifiedEditor().createContextKey(key, defaultValue);
    }
    addAction(descriptor) {
      return this.getModifiedEditor().addAction(descriptor);
    }
  };
  StandaloneDiffEditor2 = __decorate$3([
    __param$3(2, IInstantiationService),
    __param$3(3, IContextKeyService),
    __param$3(4, ICodeEditorService),
    __param$3(5, IStandaloneThemeService),
    __param$3(6, INotificationService),
    __param$3(7, IConfigurationService),
    __param$3(8, IContextMenuService),
    __param$3(9, IEditorProgressService),
    __param$3(10, IClipboardService),
    __param$3(11, IAccessibilitySignalService)
  ], StandaloneDiffEditor2);
  function createTextModel(modelService, languageService, value, languageId, uri) {
    value = value || "";
    if (!languageId) {
      const firstLF = value.indexOf("\n");
      let firstLine = value;
      if (firstLF !== -1) {
        firstLine = value.substring(0, firstLF);
      }
      return doCreateModel(modelService, value, languageService.createByFilepathOrFirstLine(uri || null, firstLine), uri);
    }
    return doCreateModel(modelService, value, languageService.createById(languageId), uri);
  }
  function doCreateModel(modelService, value, languageSelection, uri) {
    return modelService.createModel(value, languageSelection, uri);
  }
  registerColor("multiDiffEditor.headerBackground", { dark: "#262626", light: "tab.inactiveBackground", hcDark: "tab.inactiveBackground", hcLight: "tab.inactiveBackground" }, localize(142, "The background color of the diff editor's header"));
  registerColor("multiDiffEditor.background", editorBackground, localize(143, "The background color of the multi file diff editor"));
  registerColor("multiDiffEditor.border", { dark: "sideBarSectionHeader.border", light: "#cccccc", hcDark: "sideBarSectionHeader.border", hcLight: "#cccccc" }, localize(144, "The border color of the multi file diff editor"));
  var __decorate$2 = 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);
    };
  };
  class TemplateData {
    constructor(viewModel, deltaScrollVertical) {
      this.viewModel = viewModel;
      this.deltaScrollVertical = deltaScrollVertical;
    }
    getId() {
      return this.viewModel;
    }
  }
  let DiffEditorItemTemplate = class DiffEditorItemTemplate extends Disposable {
    constructor(_container, _overflowWidgetsDomNode, _workbenchUIElementFactory, _instantiationService, _parentContextKeyService) {
      super();
      this._container = _container;
      this._overflowWidgetsDomNode = _overflowWidgetsDomNode;
      this._workbenchUIElementFactory = _workbenchUIElementFactory;
      this._instantiationService = _instantiationService;
      this._viewModel = observableValue(this, void 0);
      this._collapsed = derived(this, (reader) => this._viewModel.read(reader)?.collapsed.read(reader));
      this._editorContentHeight = observableValue(this, 500);
      this.contentHeight = derived(this, (reader) => {
        const h2 = this._collapsed.read(reader) ? 0 : this._editorContentHeight.read(reader);
        return h2 + this._outerEditorHeight;
      });
      this._modifiedContentWidth = observableValue(this, 0);
      this._modifiedWidth = observableValue(this, 0);
      this._originalContentWidth = observableValue(this, 0);
      this._originalWidth = observableValue(this, 0);
      this.maxScroll = derived(this, (reader) => {
        const scroll1 = this._modifiedContentWidth.read(reader) - this._modifiedWidth.read(reader);
        const scroll2 = this._originalContentWidth.read(reader) - this._originalWidth.read(reader);
        if (scroll1 > scroll2) {
          return { maxScroll: scroll1, width: this._modifiedWidth.read(reader) };
        } else {
          return { maxScroll: scroll2, width: this._originalWidth.read(reader) };
        }
      });
      this._elements = h("div.multiDiffEntry", [
        h("div.header@header", [
          h("div.header-content", [
            h("div.collapse-button@collapseButton"),
            h("div.file-path", [
              // eslint-disable-next-line local/code-no-any-casts, @typescript-eslint/no-explicit-any
              h("div.title.modified.show-file-icons@primaryPath", []),
              h("div.status.deleted@status", ["R"]),
              // eslint-disable-next-line local/code-no-any-casts, @typescript-eslint/no-explicit-any
              h("div.title.original.show-file-icons@secondaryPath", [])
            ]),
            h("div.actions@actions")
          ])
        ]),
        h("div.editorParent", [
          h("div.editorContainer@editor")
        ])
      ]);
      this.editor = this._register(this._instantiationService.createInstance(DiffEditorWidget, this._elements.editor, {
        overflowWidgetsDomNode: this._overflowWidgetsDomNode,
        fixedOverflowWidgets: true
      }, {}));
      this.isModifedFocused = observableCodeEditor(this.editor.getModifiedEditor()).isFocused;
      this.isOriginalFocused = observableCodeEditor(this.editor.getOriginalEditor()).isFocused;
      this.isFocused = derived(this, (reader) => this.isModifedFocused.read(reader) || this.isOriginalFocused.read(reader));
      this._resourceLabel = this._workbenchUIElementFactory.createResourceLabel ? this._register(this._workbenchUIElementFactory.createResourceLabel(this._elements.primaryPath)) : void 0;
      this._resourceLabel2 = this._workbenchUIElementFactory.createResourceLabel ? this._register(this._workbenchUIElementFactory.createResourceLabel(this._elements.secondaryPath)) : void 0;
      this._dataStore = this._register(new DisposableStore());
      this._headerHeight = 40;
      this._lastScrollTop = -1;
      this._isSettingScrollTop = false;
      const btn = new Button(this._elements.collapseButton, {});
      this._register(autorun((reader) => {
        btn.element.className = "";
        btn.icon = this._collapsed.read(reader) ? Codicon.chevronRight : Codicon.chevronDown;
      }));
      this._register(btn.onDidClick(() => {
        this._viewModel.get()?.collapsed.set(!this._collapsed.get(), void 0);
      }));
      this._register(autorun((reader) => {
        this._elements.editor.style.display = this._collapsed.read(reader) ? "none" : "block";
      }));
      this._register(this.editor.getModifiedEditor().onDidLayoutChange((e) => {
        const width2 = this.editor.getModifiedEditor().getLayoutInfo().contentWidth;
        this._modifiedWidth.set(width2, void 0);
      }));
      this._register(this.editor.getOriginalEditor().onDidLayoutChange((e) => {
        const width2 = this.editor.getOriginalEditor().getLayoutInfo().contentWidth;
        this._originalWidth.set(width2, void 0);
      }));
      this._register(this.editor.onDidContentSizeChange((e) => {
        globalTransaction((tx) => {
          this._editorContentHeight.set(e.contentHeight, tx);
          this._modifiedContentWidth.set(this.editor.getModifiedEditor().getContentWidth(), tx);
          this._originalContentWidth.set(this.editor.getOriginalEditor().getContentWidth(), tx);
        });
      }));
      this._register(this.editor.getOriginalEditor().onDidScrollChange((e) => {
        if (this._isSettingScrollTop) {
          return;
        }
        if (!e.scrollTopChanged || !this._data) {
          return;
        }
        const delta = e.scrollTop - this._lastScrollTop;
        this._data.deltaScrollVertical(delta);
      }));
      this._register(autorun((reader) => {
        const isActive = this._viewModel.read(reader)?.isActive.read(reader);
        this._elements.root.classList.toggle("active", isActive);
      }));
      this._container.appendChild(this._elements.root);
      this._outerEditorHeight = this._headerHeight;
      this._contextKeyService = this._register(_parentContextKeyService.createScoped(this._elements.actions));
      const instantiationService = this._register(this._instantiationService.createChild(new ServiceCollection([IContextKeyService, this._contextKeyService])));
      this._register(instantiationService.createInstance(MenuWorkbenchToolBar, this._elements.actions, MenuId.MultiDiffEditorFileToolbar, {
        actionRunner: this._register(new ActionRunnerWithContext(() => this._viewModel.get()?.modifiedUri ?? this._viewModel.get()?.originalUri)),
        menuOptions: {
          shouldForwardArgs: true
        },
        toolbarOptions: { primaryGroup: (g) => g.startsWith("navigation") },
        actionViewItemProvider: (action, options) => createActionViewItem(instantiationService, action, options)
      }));
    }
    setScrollLeft(left) {
      if (this._modifiedContentWidth.get() - this._modifiedWidth.get() > this._originalContentWidth.get() - this._originalWidth.get()) {
        this.editor.getModifiedEditor().setScrollLeft(left);
      } else {
        this.editor.getOriginalEditor().setScrollLeft(left);
      }
    }
    setData(data) {
      this._data = data;
      function updateOptions(options) {
        return {
          ...options,
          scrollBeyondLastLine: false,
          hideUnchangedRegions: {
            enabled: true
          },
          scrollbar: {
            vertical: "hidden",
            horizontal: "hidden",
            handleMouseWheel: false,
            useShadows: false
          },
          renderOverviewRuler: false,
          fixedOverflowWidgets: true,
          overviewRulerBorder: false
        };
      }
      if (!data) {
        globalTransaction((tx) => {
          this._viewModel.set(void 0, tx);
          this.editor.setDiffModel(null, tx);
          this._dataStore.clear();
        });
        return;
      }
      const value = data.viewModel.documentDiffItem;
      globalTransaction((tx) => {
        this._resourceLabel?.setUri(data.viewModel.modifiedUri ?? data.viewModel.originalUri, { strikethrough: data.viewModel.modifiedUri === void 0 });
        let isRenamed = false;
        let isDeleted = false;
        let isAdded = false;
        let flag = "";
        if (data.viewModel.modifiedUri && data.viewModel.originalUri && data.viewModel.modifiedUri.path !== data.viewModel.originalUri.path) {
          flag = "R";
          isRenamed = true;
        } else if (!data.viewModel.modifiedUri) {
          flag = "D";
          isDeleted = true;
        } else if (!data.viewModel.originalUri) {
          flag = "A";
          isAdded = true;
        }
        this._elements.status.classList.toggle("renamed", isRenamed);
        this._elements.status.classList.toggle("deleted", isDeleted);
        this._elements.status.classList.toggle("added", isAdded);
        this._elements.status.innerText = flag;
        this._resourceLabel2?.setUri(isRenamed ? data.viewModel.originalUri : void 0, { strikethrough: true });
        this._dataStore.clear();
        this._viewModel.set(data.viewModel, tx);
        this.editor.setDiffModel(data.viewModel.diffEditorViewModelRef, tx);
        this.editor.updateOptions(updateOptions(value.options ?? {}));
      });
      if (value.onOptionsDidChange) {
        this._dataStore.add(value.onOptionsDidChange(() => {
          this.editor.updateOptions(updateOptions(value.options ?? {}));
        }));
      }
      data.viewModel.isAlive.recomputeInitiallyAndOnChange(this._dataStore, (value2) => {
        if (!value2) {
          this.setData(void 0);
        }
      });
      if (data.viewModel.documentDiffItem.contextKeys) {
        for (const [key, value2] of Object.entries(data.viewModel.documentDiffItem.contextKeys)) {
          this._contextKeyService.createKey(key, value2);
        }
      }
    }
    render(verticalRange, width2, editorScroll, viewPort) {
      this._elements.root.style.visibility = "visible";
      this._elements.root.style.top = `${verticalRange.start}px`;
      this._elements.root.style.height = `${verticalRange.length}px`;
      this._elements.root.style.width = `${width2}px`;
      this._elements.root.style.position = "absolute";
      const maxDelta = verticalRange.length - this._headerHeight;
      const delta = Math.max(0, Math.min(viewPort.start - verticalRange.start, maxDelta));
      this._elements.header.style.transform = `translateY(${delta}px)`;
      globalTransaction((tx) => {
        this.editor.layout({
          width: width2 - 2 * 8 - 2 * 1,
          height: verticalRange.length - this._outerEditorHeight
        });
      });
      try {
        this._isSettingScrollTop = true;
        this._lastScrollTop = editorScroll;
        this.editor.getOriginalEditor().setScrollTop(editorScroll);
      } finally {
        this._isSettingScrollTop = false;
      }
      this._elements.header.classList.toggle("shadow", delta > 0 || editorScroll > 0);
      this._elements.header.classList.toggle("collapsed", delta === maxDelta);
    }
    hide() {
      this._elements.root.style.top = `-100000px`;
      this._elements.root.style.visibility = "hidden";
    }
  };
  DiffEditorItemTemplate = __decorate$2([
    __param$2(3, IInstantiationService),
    __param$2(4, IContextKeyService)
  ], DiffEditorItemTemplate);
  class ObjectPool {
    constructor(_create) {
      this._create = _create;
      this._unused = /* @__PURE__ */ new Set();
      this._used = /* @__PURE__ */ new Set();
      this._itemData = /* @__PURE__ */ new Map();
    }
    getUnusedObj(data) {
      let obj;
      if (this._unused.size === 0) {
        obj = this._create(data);
        this._itemData.set(obj, data);
      } else {
        const values = [...this._unused.values()];
        obj = values.find((obj2) => this._itemData.get(obj2).getId() === data.getId()) ?? values[0];
        this._unused.delete(obj);
        this._itemData.set(obj, data);
        obj.setData(data);
      }
      this._used.add(obj);
      return {
        object: obj,
        dispose: () => {
          this._used.delete(obj);
          if (this._unused.size > 5) {
            obj.dispose();
          } else {
            this._unused.add(obj);
          }
        }
      };
    }
    dispose() {
      for (const obj of this._used) {
        obj.dispose();
      }
      for (const obj of this._unused) {
        obj.dispose();
      }
      this._used.clear();
      this._unused.clear();
    }
  }
  var __decorate$1 = 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$1 = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  let MultiDiffEditorWidgetImpl = class MultiDiffEditorWidgetImpl extends Disposable {
    constructor(_element, _dimension, _viewModel, _workbenchUIElementFactory, _parentContextKeyService, _parentInstantiationService) {
      super();
      this._element = _element;
      this._dimension = _dimension;
      this._viewModel = _viewModel;
      this._workbenchUIElementFactory = _workbenchUIElementFactory;
      this._parentContextKeyService = _parentContextKeyService;
      this._parentInstantiationService = _parentInstantiationService;
      this._scrollableElements = h("div.scrollContent", [
        h("div@content", {
          style: {
            overflow: "hidden"
          }
        }),
        h("div.monaco-editor@overflowWidgetsDomNode", {})
      ]);
      this._scrollable = this._register(new Scrollable({
        forceIntegerValues: false,
        scheduleAtNextAnimationFrame: (cb) => scheduleAtNextAnimationFrame(getWindow(this._element), cb),
        smoothScrollDuration: 100
      }));
      this._scrollableElement = this._register(new SmoothScrollableElement(this._scrollableElements.root, {
        vertical: 1,
        horizontal: 1,
        useShadows: false
      }, this._scrollable));
      this._elements = h("div.monaco-component.multiDiffEditor", {}, [
        h("div", {}, [this._scrollableElement.getDomNode()]),
        h("div.placeholder@placeholder", {}, [h("div")])
      ]);
      this._sizeObserver = this._register(new ObservableElementSizeObserver(this._element, void 0));
      this._objectPool = this._register(new ObjectPool((data) => {
        const template = this._instantiationService.createInstance(DiffEditorItemTemplate, this._scrollableElements.content, this._scrollableElements.overflowWidgetsDomNode, this._workbenchUIElementFactory);
        template.setData(data);
        return template;
      }));
      this.scrollTop = observableFromEvent(this, this._scrollableElement.onScroll, () => (
        /** @description scrollTop */
        this._scrollableElement.getScrollPosition().scrollTop
      ));
      this.scrollLeft = observableFromEvent(this, this._scrollableElement.onScroll, () => (
        /** @description scrollLeft */
        this._scrollableElement.getScrollPosition().scrollLeft
      ));
      this._viewItemsInfo = derived(this, (reader) => {
        const vm = this._viewModel.read(reader);
        if (!vm) {
          return { items: [], getItem: (_d2) => {
            throw new BugIndicatingError();
          } };
        }
        const viewModels = vm.items.read(reader);
        const map = /* @__PURE__ */ new Map();
        const items = viewModels.map((d) => {
          const item = reader.store.add(new VirtualizedViewItem(d, this._objectPool, this.scrollLeft, (delta) => {
            this._scrollableElement.setScrollPosition({ scrollTop: this._scrollableElement.getScrollPosition().scrollTop + delta });
          }));
          const data = this._lastDocStates?.[item.getKey()];
          if (data) {
            transaction((tx) => {
              item.setViewState(data, tx);
            });
          }
          map.set(d, item);
          return item;
        });
        return { items, getItem: (d) => map.get(d) };
      });
      this._viewItems = this._viewItemsInfo.map(this, (items) => items.items);
      this._spaceBetweenPx = 0;
      this._totalHeight = this._viewItems.map(this, (items, reader) => items.reduce((r, i2) => r + i2.contentHeight.read(reader) + this._spaceBetweenPx, 0));
      this.activeControl = derived(this, (reader) => {
        const activeDiffItem = this._viewModel.read(reader)?.activeDiffItem.read(reader);
        if (!activeDiffItem) {
          return void 0;
        }
        const viewItem = this._viewItemsInfo.read(reader).getItem(activeDiffItem);
        return viewItem.template.read(reader)?.editor;
      });
      this._contextKeyService = this._register(this._parentContextKeyService.createScoped(this._element));
      this._instantiationService = this._register(this._parentInstantiationService.createChild(new ServiceCollection([IContextKeyService, this._contextKeyService])));
      this._contextKeyService.createKey(EditorContextKeys.inMultiDiffEditor.key, true);
      this._lastDocStates = {};
      this._register(autorunWithStore((reader, store) => {
        const viewModel = this._viewModel.read(reader);
        if (viewModel && viewModel.contextKeys) {
          for (const [key, value] of Object.entries(viewModel.contextKeys)) {
            const contextKey = this._contextKeyService.createKey(key, void 0);
            contextKey.set(value);
            store.add(toDisposable(() => contextKey.reset()));
          }
        }
      }));
      const ctxAllCollapsed = this._parentContextKeyService.createKey(EditorContextKeys.multiDiffEditorAllCollapsed.key, false);
      this._register(autorun((reader) => {
        const viewModel = this._viewModel.read(reader);
        if (viewModel) {
          const allCollapsed = viewModel.items.read(reader).every((item) => item.collapsed.read(reader));
          ctxAllCollapsed.set(allCollapsed);
        }
      }));
      this._register(autorun((reader) => {
        const dimension = this._dimension.read(reader);
        this._sizeObserver.observe(dimension);
      }));
      const placeholderMessage = derived((reader) => {
        const items = this._viewItems.read(reader);
        if (items.length > 0) {
          return void 0;
        }
        const vm = this._viewModel.read(reader);
        return !vm || vm.isLoading.read(reader) ? localize(145, "Loading...") : localize(146, "No Changed Files");
      });
      this._register(autorun((reader) => {
        const message = placeholderMessage.read(reader);
        this._elements.placeholder.innerText = message ?? "";
        this._elements.placeholder.classList.toggle("visible", !!message);
      }));
      this._scrollableElements.content.style.position = "relative";
      this._register(autorun((reader) => {
        const height = this._sizeObserver.height.read(reader);
        this._scrollableElements.root.style.height = `${height}px`;
        const totalHeight = this._totalHeight.read(reader);
        this._scrollableElements.content.style.height = `${totalHeight}px`;
        const width2 = this._sizeObserver.width.read(reader);
        let scrollWidth = width2;
        const viewItems = this._viewItems.read(reader);
        const max = findFirstMax(viewItems, compareBy((i2) => i2.maxScroll.read(reader).maxScroll, numberComparator));
        if (max) {
          const maxScroll = max.maxScroll.read(reader);
          scrollWidth = width2 + maxScroll.maxScroll;
        }
        this._scrollableElement.setScrollDimensions({
          width: width2,
          height,
          scrollHeight: totalHeight,
          scrollWidth
        });
      }));
      _element.replaceChildren(this._elements.root);
      this._register(toDisposable(() => {
        _element.replaceChildren();
      }));
      this._register(autorun((reader) => {
        const viewModel = this._viewModel.read(reader);
        if (!viewModel) {
          return;
        }
        if (!viewModel.isLoading.read(reader)) {
          const items = viewModel.items.read(reader);
          if (items.length === 0) {
            return;
          }
          const activeDiffItem = viewModel.activeDiffItem.read(reader);
          if (activeDiffItem) {
            return;
          }
          this.goToNextChange();
        }
      }));
      this._register(this._register(autorun((reader) => {
        globalTransaction((tx) => {
          this.render(reader);
        });
      })));
    }
    reveal(resource, options) {
      const viewItems = this._viewItems.get();
      const index = viewItems.findIndex((item) => item.viewModel.originalUri?.toString() === resource.original?.toString() && item.viewModel.modifiedUri?.toString() === resource.modified?.toString());
      if (index === -1) {
        throw new BugIndicatingError("Resource not found in diff editor");
      }
      const viewItem = viewItems[index];
      this._viewModel.get().activeDiffItem.setCache(viewItem.viewModel, void 0);
      let scrollTop = 0;
      for (let i2 = 0; i2 < index; i2++) {
        scrollTop += viewItems[i2].contentHeight.get() + this._spaceBetweenPx;
      }
      this._scrollableElement.setScrollPosition({ scrollTop });
      const diffEditor = viewItem.template.get()?.editor;
      const editor2 = "original" in resource ? diffEditor?.getOriginalEditor() : diffEditor?.getModifiedEditor();
      if (editor2 && options?.range) {
        editor2.revealRangeInCenter(options.range);
        highlightRange(editor2, options.range);
      }
    }
    goToNextChange() {
      this._navigateToChange("next");
    }
    _navigateToChange(direction) {
      const viewItems = this._viewItems.get();
      if (viewItems.length === 0) {
        return;
      }
      const activeViewModel = this._viewModel.get()?.activeDiffItem.get();
      const currentIndex = activeViewModel ? viewItems.findIndex((v) => v.viewModel === activeViewModel) : -1;
      if (currentIndex === -1) {
        this._goToFile(0, "first");
        return;
      }
      const currentItem = viewItems[currentIndex];
      if (currentItem.viewModel.collapsed.get()) {
        currentItem.viewModel.collapsed.set(false, void 0);
      }
      const editor2 = currentItem.template.get()?.editor;
      if (editor2?.getDiffComputationResult()?.changes2?.length) {
        const pos = editor2.getModifiedEditor().getPosition()?.lineNumber || 1;
        const changes = editor2.getDiffComputationResult().changes2;
        const hasNext = direction === "next" ? changes.some((c) => c.modified.startLineNumber > pos) : changes.some((c) => c.modified.endLineNumberExclusive <= pos);
        if (hasNext) {
          editor2.goToDiff(direction);
          return;
        }
      }
      const nextIndex = (currentIndex + (direction === "next" ? 1 : -1) + viewItems.length) % viewItems.length;
      this._goToFile(nextIndex, direction === "next" ? "first" : "last");
    }
    _goToFile(index, position) {
      const item = this._viewItems.get()[index];
      if (item.viewModel.collapsed.get()) {
        item.viewModel.collapsed.set(false, void 0);
      }
      this.reveal({ original: item.viewModel.originalUri, modified: item.viewModel.modifiedUri });
      const editor2 = item.template.get()?.editor;
      if (editor2?.getDiffComputationResult()?.changes2?.length) {
        if (position === "first") {
          editor2.revealFirstDiff();
        } else {
          const lastChange = editor2.getDiffComputationResult().changes2.at(-1);
          const modifiedEditor = editor2.getModifiedEditor();
          modifiedEditor.setPosition({ lineNumber: lastChange.modified.startLineNumber, column: 1 });
          modifiedEditor.revealLineInCenter(lastChange.modified.startLineNumber);
        }
      }
      editor2?.focus();
    }
    render(reader) {
      const scrollTop = this.scrollTop.read(reader);
      let contentScrollOffsetToScrollOffset = 0;
      let itemHeightSumBefore = 0;
      let itemContentHeightSumBefore = 0;
      const viewPortHeight = this._sizeObserver.height.read(reader);
      const contentViewPort = OffsetRange.ofStartAndLength(scrollTop, viewPortHeight);
      const width2 = this._sizeObserver.width.read(reader);
      for (const v of this._viewItems.read(reader)) {
        const itemContentHeight = v.contentHeight.read(reader);
        const itemHeight = Math.min(itemContentHeight, viewPortHeight);
        const itemRange = OffsetRange.ofStartAndLength(itemHeightSumBefore, itemHeight);
        const itemContentRange = OffsetRange.ofStartAndLength(itemContentHeightSumBefore, itemContentHeight);
        if (itemContentRange.isBefore(contentViewPort)) {
          contentScrollOffsetToScrollOffset -= itemContentHeight - itemHeight;
          v.hide();
        } else if (itemContentRange.isAfter(contentViewPort)) {
          v.hide();
        } else {
          const scroll = Math.max(0, Math.min(contentViewPort.start - itemContentRange.start, itemContentHeight - itemHeight));
          contentScrollOffsetToScrollOffset -= scroll;
          const viewPort = OffsetRange.ofStartAndLength(scrollTop + contentScrollOffsetToScrollOffset, viewPortHeight);
          v.render(itemRange, scroll, width2, viewPort);
        }
        itemHeightSumBefore += itemHeight + this._spaceBetweenPx;
        itemContentHeightSumBefore += itemContentHeight + this._spaceBetweenPx;
      }
      this._scrollableElements.content.style.transform = `translateY(${-(scrollTop + contentScrollOffsetToScrollOffset)}px)`;
    }
  };
  MultiDiffEditorWidgetImpl = __decorate$1([
    __param$1(4, IContextKeyService),
    __param$1(5, IInstantiationService)
  ], MultiDiffEditorWidgetImpl);
  function highlightRange(targetEditor, range2) {
    const modelNow = targetEditor.getModel();
    const decorations = targetEditor.createDecorationsCollection([{ range: range2, options: { description: "symbol-navigate-action-highlight", className: "symbolHighlight" } }]);
    setTimeout(() => {
      if (targetEditor.getModel() === modelNow) {
        decorations.clear();
      }
    }, 350);
  }
  class VirtualizedViewItem extends Disposable {
    constructor(viewModel, _objectPool, _scrollLeft, _deltaScrollVertical) {
      super();
      this.viewModel = viewModel;
      this._objectPool = _objectPool;
      this._scrollLeft = _scrollLeft;
      this._deltaScrollVertical = _deltaScrollVertical;
      this._templateRef = this._register(disposableObservableValue(this, void 0));
      this.contentHeight = derived(this, (reader) => this._templateRef.read(reader)?.object.contentHeight?.read(reader) ?? this.viewModel.lastTemplateData.read(reader).contentHeight);
      this.maxScroll = derived(this, (reader) => this._templateRef.read(reader)?.object.maxScroll.read(reader) ?? { maxScroll: 0, scrollWidth: 0 });
      this.template = derived(this, (reader) => this._templateRef.read(reader)?.object);
      this._isHidden = observableValue(this, false);
      this._isFocused = derived(this, (reader) => this.template.read(reader)?.isFocused.read(reader) ?? false);
      this.viewModel.setIsFocused(this._isFocused, void 0);
      this._register(autorun((reader) => {
        const scrollLeft = this._scrollLeft.read(reader);
        this._templateRef.read(reader)?.object.setScrollLeft(scrollLeft);
      }));
      this._register(autorun((reader) => {
        const ref = this._templateRef.read(reader);
        if (!ref) {
          return;
        }
        const isHidden = this._isHidden.read(reader);
        if (!isHidden) {
          return;
        }
        const isFocused = ref.object.isFocused.read(reader);
        if (isFocused) {
          return;
        }
        this._clear();
      }));
    }
    dispose() {
      this._clear();
      super.dispose();
    }
    toString() {
      return `VirtualViewItem(${this.viewModel.documentDiffItem.modified?.uri.toString()})`;
    }
    getKey() {
      return this.viewModel.getKey();
    }
    setViewState(viewState, tx) {
      this.viewModel.collapsed.set(viewState.collapsed, tx);
      this._updateTemplateData(tx);
      const data = this.viewModel.lastTemplateData.get();
      const selections = viewState.selections?.map(Selection$1.liftSelection);
      this.viewModel.lastTemplateData.set({
        ...data,
        selections
      }, tx);
      const ref = this._templateRef.get();
      if (ref) {
        if (selections) {
          ref.object.editor.setSelections(selections);
        }
      }
    }
    _updateTemplateData(tx) {
      const ref = this._templateRef.get();
      if (!ref) {
        return;
      }
      this.viewModel.lastTemplateData.set({
        contentHeight: ref.object.contentHeight.get(),
        selections: ref.object.editor.getSelections() ?? void 0
      }, tx);
    }
    _clear() {
      const ref = this._templateRef.get();
      if (!ref) {
        return;
      }
      transaction((tx) => {
        this._updateTemplateData(tx);
        ref.object.hide();
        this._templateRef.set(void 0, tx);
      });
    }
    hide() {
      this._isHidden.set(true, void 0);
    }
    render(verticalSpace, offset, width2, viewPort) {
      this._isHidden.set(false, void 0);
      let ref = this._templateRef.get();
      if (!ref) {
        ref = this._objectPool.getUnusedObj(new TemplateData(this.viewModel, this._deltaScrollVertical));
        this._templateRef.set(ref, void 0);
        const selections = this.viewModel.lastTemplateData.get().selections;
        if (selections) {
          ref.object.editor.setSelections(selections);
        }
      }
      ref.object.render(verticalSpace, width2, offset, viewPort);
    }
  }
  var __decorate = 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 = function(paramIndex, decorator) {
    return function(target, key) {
      decorator(target, key, paramIndex);
    };
  };
  let MultiDiffEditorWidget = class MultiDiffEditorWidget extends Disposable {
    constructor(_element, _workbenchUIElementFactory, _instantiationService) {
      super();
      this._element = _element;
      this._workbenchUIElementFactory = _workbenchUIElementFactory;
      this._instantiationService = _instantiationService;
      this._dimension = observableValue(this, void 0);
      this._viewModel = observableValue(this, void 0);
      this._widgetImpl = derived(this, (reader) => {
        return reader.store.add(this._instantiationService.createInstance(readHotReloadableExport(MultiDiffEditorWidgetImpl), this._element, this._dimension, this._viewModel, this._workbenchUIElementFactory));
      });
      this._register(recomputeInitiallyAndOnChange(this._widgetImpl));
    }
  };
  MultiDiffEditorWidget = __decorate([
    __param(2, IInstantiationService)
  ], MultiDiffEditorWidget);
  function create(domElement, options, override) {
    const instantiationService = StandaloneServices.initialize(override || {});
    return instantiationService.createInstance(StandaloneEditor, domElement, options);
  }
  function onDidCreateEditor(listener) {
    const codeEditorService = StandaloneServices.get(ICodeEditorService);
    return codeEditorService.onCodeEditorAdd((editor2) => {
      listener(editor2);
    });
  }
  function onDidCreateDiffEditor(listener) {
    const codeEditorService = StandaloneServices.get(ICodeEditorService);
    return codeEditorService.onDiffEditorAdd((editor2) => {
      listener(editor2);
    });
  }
  function getEditors() {
    const codeEditorService = StandaloneServices.get(ICodeEditorService);
    return codeEditorService.listCodeEditors();
  }
  function getDiffEditors() {
    const codeEditorService = StandaloneServices.get(ICodeEditorService);
    return codeEditorService.listDiffEditors();
  }
  function createDiffEditor(domElement, options, override) {
    const instantiationService = StandaloneServices.initialize(override || {});
    return instantiationService.createInstance(StandaloneDiffEditor2, domElement, options);
  }
  function createMultiFileDiffEditor(domElement, override) {
    const instantiationService = StandaloneServices.initialize(override || {});
    return new MultiDiffEditorWidget(domElement, {}, instantiationService);
  }
  function addCommand(descriptor) {
    if (typeof descriptor.id !== "string" || typeof descriptor.run !== "function") {
      throw new Error("Invalid command descriptor, `id` and `run` are required properties!");
    }
    return CommandsRegistry.registerCommand(descriptor.id, descriptor.run);
  }
  function addEditorAction(descriptor) {
    if (typeof descriptor.id !== "string" || typeof descriptor.label !== "string" || typeof descriptor.run !== "function") {
      throw new Error("Invalid action descriptor, `id`, `label` and `run` are required properties!");
    }
    const precondition = ContextKeyExpr.deserialize(descriptor.precondition);
    const run = (accessor, ...args) => {
      return EditorCommand.runEditorCommand(accessor, args, precondition, (accessor2, editor2, args2) => Promise.resolve(descriptor.run(editor2, ...args2)));
    };
    const toDispose = new DisposableStore();
    toDispose.add(CommandsRegistry.registerCommand(descriptor.id, run));
    if (descriptor.contextMenuGroupId) {
      const menuItem = {
        command: {
          id: descriptor.id,
          title: descriptor.label
        },
        when: precondition,
        group: descriptor.contextMenuGroupId,
        order: descriptor.contextMenuOrder || 0
      };
      toDispose.add(MenuRegistry.appendMenuItem(MenuId.EditorContext, menuItem));
    }
    if (Array.isArray(descriptor.keybindings)) {
      const keybindingService = StandaloneServices.get(IKeybindingService);
      if (!(keybindingService instanceof StandaloneKeybindingService)) {
        console.warn("Cannot add keybinding because the editor is configured with an unrecognized KeybindingService");
      } else {
        const keybindingsWhen = ContextKeyExpr.and(precondition, ContextKeyExpr.deserialize(descriptor.keybindingContext));
        toDispose.add(keybindingService.addDynamicKeybindings(descriptor.keybindings.map((keybinding) => {
          return {
            keybinding,
            command: descriptor.id,
            when: keybindingsWhen
          };
        })));
      }
    }
    return toDispose;
  }
  function addKeybindingRule(rule) {
    return addKeybindingRules([rule]);
  }
  function addKeybindingRules(rules) {
    const keybindingService = StandaloneServices.get(IKeybindingService);
    if (!(keybindingService instanceof StandaloneKeybindingService)) {
      console.warn("Cannot add keybinding because the editor is configured with an unrecognized KeybindingService");
      return Disposable.None;
    }
    return keybindingService.addDynamicKeybindings(rules.map((rule) => {
      return {
        keybinding: rule.keybinding,
        command: rule.command,
        commandArgs: rule.commandArgs,
        when: ContextKeyExpr.deserialize(rule.when)
      };
    }));
  }
  function createModel(value, language2, uri) {
    const languageService = StandaloneServices.get(ILanguageService);
    const languageId = languageService.getLanguageIdByMimeType(language2) || language2;
    return createTextModel(StandaloneServices.get(IModelService), languageService, value, languageId, uri);
  }
  function setModelLanguage(model, mimeTypeOrLanguageId) {
    const languageService = StandaloneServices.get(ILanguageService);
    const languageId = languageService.getLanguageIdByMimeType(mimeTypeOrLanguageId) || mimeTypeOrLanguageId || PLAINTEXT_LANGUAGE_ID;
    model.setLanguage(languageService.createById(languageId));
  }
  function setModelMarkers(model, owner, markers) {
    if (model) {
      const markerService = StandaloneServices.get(IMarkerService);
      markerService.changeOne(owner, model.uri, markers);
    }
  }
  function removeAllMarkers(owner) {
    const markerService = StandaloneServices.get(IMarkerService);
    markerService.changeAll(owner, []);
  }
  function getModelMarkers(filter) {
    const markerService = StandaloneServices.get(IMarkerService);
    return markerService.read(filter);
  }
  function onDidChangeMarkers(listener) {
    const markerService = StandaloneServices.get(IMarkerService);
    return markerService.onMarkerChanged(listener);
  }
  function getModel(uri) {
    const modelService = StandaloneServices.get(IModelService);
    return modelService.getModel(uri);
  }
  function getModels() {
    const modelService = StandaloneServices.get(IModelService);
    return modelService.getModels();
  }
  function onDidCreateModel(listener) {
    const modelService = StandaloneServices.get(IModelService);
    return modelService.onModelAdded(listener);
  }
  function onWillDisposeModel(listener) {
    const modelService = StandaloneServices.get(IModelService);
    return modelService.onModelRemoved(listener);
  }
  function onDidChangeModelLanguage(listener) {
    const modelService = StandaloneServices.get(IModelService);
    return modelService.onModelLanguageChanged((e) => {
      listener({
        model: e.model,
        oldLanguage: e.oldLanguageId
      });
    });
  }
  function createWebWorker(opts) {
    return createWebWorker$1(StandaloneServices.get(IModelService), opts);
  }
  function colorizeElement(domNode, options) {
    const languageService = StandaloneServices.get(ILanguageService);
    const themeService = StandaloneServices.get(IStandaloneThemeService);
    return Colorizer.colorizeElement(themeService, languageService, domNode, options).then(() => {
      themeService.registerEditorContainer(domNode);
    });
  }
  function colorize(text2, languageId, options) {
    const languageService = StandaloneServices.get(ILanguageService);
    const themeService = StandaloneServices.get(IStandaloneThemeService);
    themeService.registerEditorContainer(mainWindow.document.body);
    return Colorizer.colorize(languageService, text2, languageId, options);
  }
  function colorizeModelLine(model, lineNumber, tabSize = 4) {
    const themeService = StandaloneServices.get(IStandaloneThemeService);
    themeService.registerEditorContainer(mainWindow.document.body);
    return Colorizer.colorizeModelLine(model, lineNumber, tabSize);
  }
  function getSafeTokenizationSupport(language2) {
    const tokenizationSupport = TokenizationRegistry.get(language2);
    if (tokenizationSupport) {
      return tokenizationSupport;
    }
    return {
      getInitialState: () => NullState,
      tokenize: (line, hasEOL, state) => nullTokenize(language2, state)
    };
  }
  function tokenize(text2, languageId) {
    TokenizationRegistry.getOrCreate(languageId);
    const tokenizationSupport = getSafeTokenizationSupport(languageId);
    const lines = splitLines(text2);
    const result = [];
    let state = tokenizationSupport.getInitialState();
    for (let i2 = 0, len = lines.length; i2 < len; i2++) {
      const line = lines[i2];
      const tokenizationResult = tokenizationSupport.tokenize(line, true, state);
      result[i2] = tokenizationResult.tokens;
      state = tokenizationResult.endState;
    }
    return result;
  }
  function defineTheme(themeName, themeData) {
    const standaloneThemeService = StandaloneServices.get(IStandaloneThemeService);
    standaloneThemeService.defineTheme(themeName, themeData);
  }
  function setTheme(themeName) {
    const standaloneThemeService = StandaloneServices.get(IStandaloneThemeService);
    standaloneThemeService.setTheme(themeName);
  }
  function remeasureFonts() {
    FontMeasurements.clearAllFontInfos();
  }
  function registerCommand(id, handler) {
    return CommandsRegistry.registerCommand({ id, handler });
  }
  function registerLinkOpener(opener) {
    const openerService = StandaloneServices.get(IOpenerService);
    return openerService.registerOpener({
      async open(resource) {
        if (typeof resource === "string") {
          resource = URI.parse(resource);
        }
        return opener.open(resource);
      }
    });
  }
  function registerEditorOpener(opener) {
    const codeEditorService = StandaloneServices.get(ICodeEditorService);
    return codeEditorService.registerCodeEditorOpenHandler(async (input, source, sideBySide) => {
      if (!source) {
        return null;
      }
      const selection = input.options?.selection;
      let selectionOrPosition;
      if (selection && typeof selection.endLineNumber === "number" && typeof selection.endColumn === "number") {
        selectionOrPosition = selection;
      } else if (selection) {
        selectionOrPosition = { lineNumber: selection.startLineNumber, column: selection.startColumn };
      }
      if (await opener.openCodeEditor(source, input.resource, selectionOrPosition)) {
        return source;
      }
      return null;
    });
  }
  function createMonacoEditorAPI() {
    return {
      // methods
      // eslint-disable-next-line local/code-no-any-casts
      create,
      // eslint-disable-next-line local/code-no-any-casts
      getEditors,
      // eslint-disable-next-line local/code-no-any-casts
      getDiffEditors,
      // eslint-disable-next-line local/code-no-any-casts
      onDidCreateEditor,
      // eslint-disable-next-line local/code-no-any-casts
      onDidCreateDiffEditor,
      // eslint-disable-next-line local/code-no-any-casts
      createDiffEditor,
      // eslint-disable-next-line local/code-no-any-casts
      addCommand,
      // eslint-disable-next-line local/code-no-any-casts
      addEditorAction,
      // eslint-disable-next-line local/code-no-any-casts
      addKeybindingRule,
      // eslint-disable-next-line local/code-no-any-casts
      addKeybindingRules,
      // eslint-disable-next-line local/code-no-any-casts
      createModel,
      // eslint-disable-next-line local/code-no-any-casts
      setModelLanguage,
      // eslint-disable-next-line local/code-no-any-casts
      setModelMarkers,
      // eslint-disable-next-line local/code-no-any-casts
      getModelMarkers,
      removeAllMarkers,
      // eslint-disable-next-line local/code-no-any-casts
      onDidChangeMarkers,
      // eslint-disable-next-line local/code-no-any-casts
      getModels,
      // eslint-disable-next-line local/code-no-any-casts
      getModel,
      // eslint-disable-next-line local/code-no-any-casts
      onDidCreateModel,
      // eslint-disable-next-line local/code-no-any-casts
      onWillDisposeModel,
      // eslint-disable-next-line local/code-no-any-casts
      onDidChangeModelLanguage,
      // eslint-disable-next-line local/code-no-any-casts
      createWebWorker,
      // eslint-disable-next-line local/code-no-any-casts
      colorizeElement,
      // eslint-disable-next-line local/code-no-any-casts
      colorize,
      // eslint-disable-next-line local/code-no-any-casts
      colorizeModelLine,
      // eslint-disable-next-line local/code-no-any-casts
      tokenize,
      // eslint-disable-next-line local/code-no-any-casts
      defineTheme,
      // eslint-disable-next-line local/code-no-any-casts
      setTheme,
      remeasureFonts,
      registerCommand,
      registerLinkOpener,
      // eslint-disable-next-line local/code-no-any-casts
      registerEditorOpener,
      // enums
      AccessibilitySupport,
      ContentWidgetPositionPreference,
      CursorChangeReason,
      DefaultEndOfLine,
      EditorAutoIndentStrategy,
      EditorOption,
      EndOfLinePreference,
      EndOfLineSequence,
      MinimapPosition,
      MinimapSectionHeaderStyle,
      MouseTargetType,
      OverlayWidgetPositionPreference,
      OverviewRulerLane,
      GlyphMarginLane,
      RenderLineNumbersType,
      RenderMinimap,
      ScrollbarVisibility,
      ScrollType,
      TextEditorCursorBlinkingStyle,
      TextEditorCursorStyle,
      TrackedRangeStickiness,
      WrappingIndent,
      InjectedTextCursorStops,
      PositionAffinity,
      ShowLightbulbIconMode,
      TextDirection,
      // classes
      // eslint-disable-next-line local/code-no-any-casts
      ConfigurationChangedEvent,
      // eslint-disable-next-line local/code-no-any-casts
      BareFontInfo,
      // eslint-disable-next-line local/code-no-any-casts
      FontInfo,
      // eslint-disable-next-line local/code-no-any-casts
      TextModelResolvedOptions,
      // eslint-disable-next-line local/code-no-any-casts
      FindMatch,
      // eslint-disable-next-line local/code-no-any-casts
      ApplyUpdateResult,
      // eslint-disable-next-line local/code-no-any-casts
      EditorZoom,
      // eslint-disable-next-line local/code-no-any-casts
      createMultiFileDiffEditor,
      // vars
      EditorType,
      // eslint-disable-next-line local/code-no-any-casts
      EditorOptions
    };
  }
  function isArrayOf(elemType, obj) {
    if (!obj) {
      return false;
    }
    if (!Array.isArray(obj)) {
      return false;
    }
    for (const el of obj) {
      if (!elemType(el)) {
        return false;
      }
    }
    return true;
  }
  function bool(prop, defValue) {
    if (typeof prop === "boolean") {
      return prop;
    }
    return defValue;
  }
  function string(prop, defValue) {
    if (typeof prop === "string") {
      return prop;
    }
    return defValue;
  }
  function arrayToHash(array2) {
    const result = {};
    for (const e of array2) {
      result[e] = true;
    }
    return result;
  }
  function createKeywordMatcher(arr, caseInsensitive = false) {
    if (caseInsensitive) {
      arr = arr.map(function(x) {
        return x.toLowerCase();
      });
    }
    const hash2 = arrayToHash(arr);
    if (caseInsensitive) {
      return function(word) {
        return hash2[word.toLowerCase()] !== void 0 && hash2.hasOwnProperty(word.toLowerCase());
      };
    } else {
      return function(word) {
        return hash2[word] !== void 0 && hash2.hasOwnProperty(word);
      };
    }
  }
  function compileRegExp(lexer2, str, handleSn) {
    str = str.replace(/@@/g, ``);
    let n2 = 0;
    let hadExpansion;
    do {
      hadExpansion = false;
      str = str.replace(/@(\w+)/g, function(s, attr) {
        hadExpansion = true;
        let sub = "";
        if (typeof lexer2[attr] === "string") {
          sub = lexer2[attr];
        } else if (lexer2[attr] && lexer2[attr] instanceof RegExp) {
          sub = lexer2[attr].source;
        } else {
          if (lexer2[attr] === void 0) {
            throw createError(lexer2, "language definition does not contain attribute '" + attr + "', used at: " + str);
          } else {
            throw createError(lexer2, "attribute reference '" + attr + "' must be a string, used at: " + str);
          }
        }
        return empty(sub) ? "" : "(?:" + sub + ")";
      });
      n2++;
    } while (hadExpansion && n2 < 5);
    str = str.replace(/\x01/g, "@");
    const flags = (lexer2.ignoreCase ? "i" : "") + (lexer2.unicode ? "u" : "");
    if (handleSn) {
      const match2 = str.match(/\$[sS](\d\d?)/g);
      if (match2) {
        let lastState = null;
        let lastRegEx = null;
        return (state) => {
          if (lastRegEx && lastState === state) {
            return lastRegEx;
          }
          lastState = state;
          lastRegEx = new RegExp(substituteMatchesRe(lexer2, str, state), flags);
          return lastRegEx;
        };
      }
    }
    return new RegExp(str, flags);
  }
  function selectScrutinee(id, matches, state, num) {
    if (num < 0) {
      return id;
    }
    if (num < matches.length) {
      return matches[num];
    }
    if (num >= 100) {
      num = num - 100;
      const parts = state.split(".");
      parts.unshift(state);
      if (num < parts.length) {
        return parts[num];
      }
    }
    return null;
  }
  function createGuard(lexer2, ruleName, tkey, val) {
    let scrut = -1;
    let oppat = tkey;
    let matches = tkey.match(/^\$(([sS]?)(\d\d?)|#)(.*)$/);
    if (matches) {
      if (matches[3]) {
        scrut = parseInt(matches[3]);
        if (matches[2]) {
          scrut = scrut + 100;
        }
      }
      oppat = matches[4];
    }
    let op = "~";
    let pat = oppat;
    if (!oppat || oppat.length === 0) {
      op = "!=";
      pat = "";
    } else if (/^\w*$/.test(pat)) {
      op = "==";
    } else {
      matches = oppat.match(/^(@|!@|~|!~|==|!=)(.*)$/);
      if (matches) {
        op = matches[1];
        pat = matches[2];
      }
    }
    let tester;
    if ((op === "~" || op === "!~") && /^(\w|\|)*$/.test(pat)) {
      const inWords = createKeywordMatcher(pat.split("|"), lexer2.ignoreCase);
      tester = function(s) {
        return op === "~" ? inWords(s) : !inWords(s);
      };
    } else if (op === "@" || op === "!@") {
      const words = lexer2[pat];
      if (!words) {
        throw createError(lexer2, "the @ match target '" + pat + "' is not defined, in rule: " + ruleName);
      }
      if (!isArrayOf(function(elem) {
        return typeof elem === "string";
      }, words)) {
        throw createError(lexer2, "the @ match target '" + pat + "' must be an array of strings, in rule: " + ruleName);
      }
      const inWords = createKeywordMatcher(words, lexer2.ignoreCase);
      tester = function(s) {
        return op === "@" ? inWords(s) : !inWords(s);
      };
    } else if (op === "~" || op === "!~") {
      if (pat.indexOf("$") < 0) {
        const re = compileRegExp(lexer2, "^" + pat + "$", false);
        tester = function(s) {
          return op === "~" ? re.test(s) : !re.test(s);
        };
      } else {
        tester = function(s, id, matches2, state) {
          const re = compileRegExp(lexer2, "^" + substituteMatches(lexer2, pat, id, matches2, state) + "$", false);
          return re.test(s);
        };
      }
    } else {
      if (pat.indexOf("$") < 0) {
        const patx = fixCase(lexer2, pat);
        tester = function(s) {
          return op === "==" ? s === patx : s !== patx;
        };
      } else {
        const patx = fixCase(lexer2, pat);
        tester = function(s, id, matches2, state, eos) {
          const patexp = substituteMatches(lexer2, patx, id, matches2, state);
          return op === "==" ? s === patexp : s !== patexp;
        };
      }
    }
    if (scrut === -1) {
      return {
        name: tkey,
        value: val,
        test: function(id, matches2, state, eos) {
          return tester(id, id, matches2, state, eos);
        }
      };
    } else {
      return {
        name: tkey,
        value: val,
        test: function(id, matches2, state, eos) {
          const scrutinee = selectScrutinee(id, matches2, state, scrut);
          return tester(!scrutinee ? "" : scrutinee, id, matches2, state, eos);
        }
      };
    }
  }
  function compileAction(lexer2, ruleName, action) {
    if (!action) {
      return { token: "" };
    } else if (typeof action === "string") {
      return action;
    } else if (action.token || action.token === "") {
      if (typeof action.token !== "string") {
        throw createError(lexer2, "a 'token' attribute must be of type string, in rule: " + ruleName);
      } else {
        const newAction = { token: action.token };
        if (action.token.indexOf("$") >= 0) {
          newAction.tokenSubst = true;
        }
        if (typeof action.bracket === "string") {
          if (action.bracket === "@open") {
            newAction.bracket = 1;
          } else if (action.bracket === "@close") {
            newAction.bracket = -1;
          } else {
            throw createError(lexer2, "a 'bracket' attribute must be either '@open' or '@close', in rule: " + ruleName);
          }
        }
        if (action.next) {
          if (typeof action.next !== "string") {
            throw createError(lexer2, "the next state must be a string value in rule: " + ruleName);
          } else {
            let next = action.next;
            if (!/^(@pop|@push|@popall)$/.test(next)) {
              if (next[0] === "@") {
                next = next.substr(1);
              }
              if (next.indexOf("$") < 0) {
                if (!stateExists(lexer2, substituteMatches(lexer2, next, "", [], ""))) {
                  throw createError(lexer2, "the next state '" + action.next + "' is not defined in rule: " + ruleName);
                }
              }
            }
            newAction.next = next;
          }
        }
        if (typeof action.goBack === "number") {
          newAction.goBack = action.goBack;
        }
        if (typeof action.switchTo === "string") {
          newAction.switchTo = action.switchTo;
        }
        if (typeof action.log === "string") {
          newAction.log = action.log;
        }
        if (typeof action.nextEmbedded === "string") {
          newAction.nextEmbedded = action.nextEmbedded;
          lexer2.usesEmbedded = true;
        }
        return newAction;
      }
    } else if (Array.isArray(action)) {
      const results = [];
      for (let i2 = 0, len = action.length; i2 < len; i2++) {
        results[i2] = compileAction(lexer2, ruleName, action[i2]);
      }
      return { group: results };
    } else if (action.cases) {
      const cases = [];
      let hasEmbeddedEndInCases = false;
      for (const tkey in action.cases) {
        if (action.cases.hasOwnProperty(tkey)) {
          const val = compileAction(lexer2, ruleName, action.cases[tkey]);
          if (tkey === "@default" || tkey === "@" || tkey === "") {
            cases.push({ test: void 0, value: val, name: tkey });
          } else if (tkey === "@eos") {
            cases.push({ test: function(id, matches, state, eos) {
              return eos;
            }, value: val, name: tkey });
          } else {
            cases.push(createGuard(lexer2, ruleName, tkey, val));
          }
          if (!hasEmbeddedEndInCases) {
            hasEmbeddedEndInCases = !isString$1(val) && (val.hasEmbeddedEndInCases || ["@pop", "@popall"].includes(val.nextEmbedded || ""));
          }
        }
      }
      const def2 = lexer2.defaultToken;
      return {
        hasEmbeddedEndInCases,
        test: function(id, matches, state, eos) {
          for (const _case of cases) {
            const didmatch = !_case.test || _case.test(id, matches, state, eos);
            if (didmatch) {
              return _case.value;
            }
          }
          return def2;
        }
      };
    } else {
      throw createError(lexer2, "an action must be a string, an object with a 'token' or 'cases' attribute, or an array of actions; in rule: " + ruleName);
    }
  }
  class Rule {
    constructor(name) {
      this.regex = new RegExp("");
      this.action = { token: "" };
      this.matchOnlyAtLineStart = false;
      this.name = "";
      this.name = name;
    }
    setRegex(lexer2, re) {
      let sregex;
      if (typeof re === "string") {
        sregex = re;
      } else if (re instanceof RegExp) {
        sregex = re.source;
      } else {
        throw createError(lexer2, "rules must start with a match string or regular expression: " + this.name);
      }
      this.matchOnlyAtLineStart = sregex.length > 0 && sregex[0] === "^";
      this.name = this.name + ": " + sregex;
      this.regex = compileRegExp(lexer2, "^(?:" + (this.matchOnlyAtLineStart ? sregex.substr(1) : sregex) + ")", true);
    }
    setAction(lexer2, act) {
      this.action = compileAction(lexer2, this.name, act);
    }
    resolveRegex(state) {
      if (this.regex instanceof RegExp) {
        return this.regex;
      } else {
        return this.regex(state);
      }
    }
  }
  function compile(languageId, json) {
    if (!json || typeof json !== "object") {
      throw new Error("Monarch: expecting a language definition object");
    }
    const lexer2 = {
      languageId,
      includeLF: bool(json.includeLF, false),
      noThrow: false,
      // raise exceptions during compilation
      maxStack: 100,
      start: typeof json.start === "string" ? json.start : null,
      ignoreCase: bool(json.ignoreCase, false),
      unicode: bool(json.unicode, false),
      tokenPostfix: string(json.tokenPostfix, "." + languageId),
      defaultToken: string(json.defaultToken, "source"),
      usesEmbedded: false,
      // becomes true if we find a nextEmbedded action
      stateNames: {},
      tokenizer: {},
      brackets: []
    };
    const lexerMin = json;
    lexerMin.languageId = languageId;
    lexerMin.includeLF = lexer2.includeLF;
    lexerMin.ignoreCase = lexer2.ignoreCase;
    lexerMin.unicode = lexer2.unicode;
    lexerMin.noThrow = lexer2.noThrow;
    lexerMin.usesEmbedded = lexer2.usesEmbedded;
    lexerMin.stateNames = json.tokenizer;
    lexerMin.defaultToken = lexer2.defaultToken;
    function addRules(state, newrules, rules) {
      for (const rule of rules) {
        let include = rule.include;
        if (include) {
          if (typeof include !== "string") {
            throw createError(lexer2, "an 'include' attribute must be a string at: " + state);
          }
          if (include[0] === "@") {
            include = include.substr(1);
          }
          if (!json.tokenizer[include]) {
            throw createError(lexer2, "include target '" + include + "' is not defined at: " + state);
          }
          addRules(state + "." + include, newrules, json.tokenizer[include]);
        } else {
          const newrule = new Rule(state);
          if (Array.isArray(rule) && rule.length >= 1 && rule.length <= 3) {
            newrule.setRegex(lexerMin, rule[0]);
            if (rule.length >= 3) {
              if (typeof rule[1] === "string") {
                newrule.setAction(lexerMin, { token: rule[1], next: rule[2] });
              } else if (typeof rule[1] === "object") {
                const rule1 = rule[1];
                rule1.next = rule[2];
                newrule.setAction(lexerMin, rule1);
              } else {
                throw createError(lexer2, "a next state as the last element of a rule can only be given if the action is either an object or a string, at: " + state);
              }
            } else {
              newrule.setAction(lexerMin, rule[1]);
            }
          } else {
            if (!rule.regex) {
              throw createError(lexer2, "a rule must either be an array, or an object with a 'regex' or 'include' field at: " + state);
            }
            if (rule.name) {
              if (typeof rule.name === "string") {
                newrule.name = rule.name;
              }
            }
            if (rule.matchOnlyAtStart) {
              newrule.matchOnlyAtLineStart = bool(rule.matchOnlyAtLineStart, false);
            }
            newrule.setRegex(lexerMin, rule.regex);
            newrule.setAction(lexerMin, rule.action);
          }
          newrules.push(newrule);
        }
      }
    }
    if (!json.tokenizer || typeof json.tokenizer !== "object") {
      throw createError(lexer2, "a language definition must define the 'tokenizer' attribute as an object");
    }
    lexer2.tokenizer = [];
    for (const key in json.tokenizer) {
      if (json.tokenizer.hasOwnProperty(key)) {
        if (!lexer2.start) {
          lexer2.start = key;
        }
        const rules = json.tokenizer[key];
        lexer2.tokenizer[key] = new Array();
        addRules("tokenizer." + key, lexer2.tokenizer[key], rules);
      }
    }
    lexer2.usesEmbedded = lexerMin.usesEmbedded;
    if (json.brackets) {
      if (!Array.isArray(json.brackets)) {
        throw createError(lexer2, "the 'brackets' attribute must be defined as an array");
      }
    } else {
      json.brackets = [
        { open: "{", close: "}", token: "delimiter.curly" },
        { open: "[", close: "]", token: "delimiter.square" },
        { open: "(", close: ")", token: "delimiter.parenthesis" },
        { open: "<", close: ">", token: "delimiter.angle" }
      ];
    }
    const brackets = [];
    for (const el of json.brackets) {
      let desc = el;
      if (desc && Array.isArray(desc) && desc.length === 3) {
        desc = { token: desc[2], open: desc[0], close: desc[1] };
      }
      if (desc.open === desc.close) {
        throw createError(lexer2, "open and close brackets in a 'brackets' attribute must be different: " + desc.open + "\n hint: use the 'bracket' attribute if matching on equal brackets is required.");
      }
      if (typeof desc.open === "string" && typeof desc.token === "string" && typeof desc.close === "string") {
        brackets.push({
          token: desc.token + lexer2.tokenPostfix,
          open: fixCase(lexer2, desc.open),
          close: fixCase(lexer2, desc.close)
        });
      } else {
        throw createError(lexer2, "every element in the 'brackets' array must be a '{open,close,token}' object or array");
      }
    }
    lexer2.brackets = brackets;
    lexer2.noThrow = true;
    return lexer2;
  }
  function register(language2) {
    ModesRegistry.registerLanguage(language2);
  }
  function getLanguages() {
    let result = [];
    result = result.concat(ModesRegistry.getLanguages());
    return result;
  }
  function getEncodedLanguageId(languageId) {
    const languageService = StandaloneServices.get(ILanguageService);
    return languageService.languageIdCodec.encodeLanguageId(languageId);
  }
  function onLanguage(languageId, callback) {
    return StandaloneServices.withServices(() => {
      const languageService = StandaloneServices.get(ILanguageService);
      const disposable = languageService.onDidRequestRichLanguageFeatures((encounteredLanguageId) => {
        if (encounteredLanguageId === languageId) {
          disposable.dispose();
          callback();
        }
      });
      return disposable;
    });
  }
  function onLanguageEncountered(languageId, callback) {
    return StandaloneServices.withServices(() => {
      const languageService = StandaloneServices.get(ILanguageService);
      const disposable = languageService.onDidRequestBasicLanguageFeatures((encounteredLanguageId) => {
        if (encounteredLanguageId === languageId) {
          disposable.dispose();
          callback();
        }
      });
      return disposable;
    });
  }
  function setLanguageConfiguration(languageId, configuration) {
    const languageService = StandaloneServices.get(ILanguageService);
    if (!languageService.isRegisteredLanguageId(languageId)) {
      throw new Error(`Cannot set configuration for unknown language ${languageId}`);
    }
    const languageConfigurationService = StandaloneServices.get(ILanguageConfigurationService);
    return languageConfigurationService.register(languageId, configuration, 100);
  }
  class EncodedTokenizationSupportAdapter {
    constructor(languageId, actual) {
      this._languageId = languageId;
      this._actual = actual;
    }
    dispose() {
    }
    getInitialState() {
      return this._actual.getInitialState();
    }
    tokenize(line, hasEOL, state) {
      if (typeof this._actual.tokenize === "function") {
        return TokenizationSupportAdapter.adaptTokenize(this._languageId, this._actual, line, state);
      }
      throw new Error("Not supported!");
    }
    tokenizeEncoded(line, hasEOL, state) {
      const result = this._actual.tokenizeEncoded(line, state);
      return new EncodedTokenizationResult(result.tokens, result.endState);
    }
  }
  class TokenizationSupportAdapter {
    constructor(_languageId, _actual, _languageService, _standaloneThemeService) {
      this._languageId = _languageId;
      this._actual = _actual;
      this._languageService = _languageService;
      this._standaloneThemeService = _standaloneThemeService;
    }
    dispose() {
    }
    getInitialState() {
      return this._actual.getInitialState();
    }
    static _toClassicTokens(tokens, language2) {
      const result = [];
      let previousStartIndex = 0;
      for (let i2 = 0, len = tokens.length; i2 < len; i2++) {
        const t = tokens[i2];
        let startIndex = t.startIndex;
        if (i2 === 0) {
          startIndex = 0;
        } else if (startIndex < previousStartIndex) {
          startIndex = previousStartIndex;
        }
        result[i2] = new Token$2(startIndex, t.scopes, language2);
        previousStartIndex = startIndex;
      }
      return result;
    }
    static adaptTokenize(language2, actual, line, state) {
      const actualResult = actual.tokenize(line, state);
      const tokens = TokenizationSupportAdapter._toClassicTokens(actualResult.tokens, language2);
      let endState;
      if (actualResult.endState.equals(state)) {
        endState = state;
      } else {
        endState = actualResult.endState;
      }
      return new TokenizationResult(tokens, endState);
    }
    tokenize(line, hasEOL, state) {
      return TokenizationSupportAdapter.adaptTokenize(this._languageId, this._actual, line, state);
    }
    _toBinaryTokens(languageIdCodec, tokens) {
      const languageId = languageIdCodec.encodeLanguageId(this._languageId);
      const tokenTheme = this._standaloneThemeService.getColorTheme().tokenTheme;
      const result = [];
      let resultLen = 0;
      let previousStartIndex = 0;
      for (let i2 = 0, len = tokens.length; i2 < len; i2++) {
        const t = tokens[i2];
        const metadata = tokenTheme.match(languageId, t.scopes) | 1024;
        if (resultLen > 0 && result[resultLen - 1] === metadata) {
          continue;
        }
        let startIndex = t.startIndex;
        if (i2 === 0) {
          startIndex = 0;
        } else if (startIndex < previousStartIndex) {
          startIndex = previousStartIndex;
        }
        result[resultLen++] = startIndex;
        result[resultLen++] = metadata;
        previousStartIndex = startIndex;
      }
      const actualResult = new Uint32Array(resultLen);
      for (let i2 = 0; i2 < resultLen; i2++) {
        actualResult[i2] = result[i2];
      }
      return actualResult;
    }
    tokenizeEncoded(line, hasEOL, state) {
      const actualResult = this._actual.tokenize(line, state);
      const tokens = this._toBinaryTokens(this._languageService.languageIdCodec, actualResult.tokens);
      let endState;
      if (actualResult.endState.equals(state)) {
        endState = state;
      } else {
        endState = actualResult.endState;
      }
      return new EncodedTokenizationResult(tokens, endState);
    }
  }
  function isATokensProvider(provider) {
    return typeof provider.getInitialState === "function";
  }
  function isEncodedTokensProvider(provider) {
    return "tokenizeEncoded" in provider;
  }
  function isThenable(obj) {
    return obj && typeof obj.then === "function";
  }
  function setColorMap(colorMap) {
    const standaloneThemeService = StandaloneServices.get(IStandaloneThemeService);
    if (colorMap) {
      const result = [null];
      for (let i2 = 1, len = colorMap.length; i2 < len; i2++) {
        result[i2] = Color.fromHex(colorMap[i2]);
      }
      standaloneThemeService.setColorMapOverride(result);
    } else {
      standaloneThemeService.setColorMapOverride(null);
    }
  }
  function createTokenizationSupportAdapter(languageId, provider) {
    if (isEncodedTokensProvider(provider)) {
      return new EncodedTokenizationSupportAdapter(languageId, provider);
    } else {
      return new TokenizationSupportAdapter(languageId, provider, StandaloneServices.get(ILanguageService), StandaloneServices.get(IStandaloneThemeService));
    }
  }
  function registerTokensProviderFactory(languageId, factory) {
    const adaptedFactory = new LazyTokenizationSupport(async () => {
      const result = await Promise.resolve(factory.create());
      if (!result) {
        return null;
      }
      if (isATokensProvider(result)) {
        return createTokenizationSupportAdapter(languageId, result);
      }
      return new MonarchTokenizer(StandaloneServices.get(ILanguageService), StandaloneServices.get(IStandaloneThemeService), languageId, compile(languageId, result), StandaloneServices.get(IConfigurationService));
    });
    return TokenizationRegistry.registerFactory(languageId, adaptedFactory);
  }
  function setTokensProvider(languageId, provider) {
    const languageService = StandaloneServices.get(ILanguageService);
    if (!languageService.isRegisteredLanguageId(languageId)) {
      throw new Error(`Cannot set tokens provider for unknown language ${languageId}`);
    }
    if (isThenable(provider)) {
      return registerTokensProviderFactory(languageId, { create: () => provider });
    }
    return TokenizationRegistry.register(languageId, createTokenizationSupportAdapter(languageId, provider));
  }
  function setMonarchTokensProvider(languageId, languageDef) {
    const create2 = (languageDef2) => {
      return new MonarchTokenizer(StandaloneServices.get(ILanguageService), StandaloneServices.get(IStandaloneThemeService), languageId, compile(languageId, languageDef2), StandaloneServices.get(IConfigurationService));
    };
    if (isThenable(languageDef)) {
      return registerTokensProviderFactory(languageId, { create: () => languageDef });
    }
    return TokenizationRegistry.register(languageId, create2(languageDef));
  }
  function registerReferenceProvider(languageSelector, provider) {
    const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService);
    return languageFeaturesService.referenceProvider.register(languageSelector, provider);
  }
  function registerRenameProvider(languageSelector, provider) {
    const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService);
    return languageFeaturesService.renameProvider.register(languageSelector, provider);
  }
  function registerNewSymbolNameProvider(languageSelector, provider) {
    const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService);
    return languageFeaturesService.newSymbolNamesProvider.register(languageSelector, provider);
  }
  function registerSignatureHelpProvider(languageSelector, provider) {
    const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService);
    return languageFeaturesService.signatureHelpProvider.register(languageSelector, provider);
  }
  function registerHoverProvider(languageSelector, provider) {
    const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService);
    return languageFeaturesService.hoverProvider.register(languageSelector, {
      provideHover: async (model, position, token, context) => {
        const word = model.getWordAtPosition(position);
        return Promise.resolve(provider.provideHover(model, position, token, context)).then((value) => {
          if (!value) {
            return void 0;
          }
          if (!value.range && word) {
            value.range = new Range$2(position.lineNumber, word.startColumn, position.lineNumber, word.endColumn);
          }
          if (!value.range) {
            value.range = new Range$2(position.lineNumber, position.column, position.lineNumber, position.column);
          }
          return value;
        });
      }
    });
  }
  function registerDocumentSymbolProvider(languageSelector, provider) {
    const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService);
    return languageFeaturesService.documentSymbolProvider.register(languageSelector, provider);
  }
  function registerDocumentHighlightProvider(languageSelector, provider) {
    const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService);
    return languageFeaturesService.documentHighlightProvider.register(languageSelector, provider);
  }
  function registerLinkedEditingRangeProvider(languageSelector, provider) {
    const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService);
    return languageFeaturesService.linkedEditingRangeProvider.register(languageSelector, provider);
  }
  function registerDefinitionProvider(languageSelector, provider) {
    const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService);
    return languageFeaturesService.definitionProvider.register(languageSelector, provider);
  }
  function registerImplementationProvider(languageSelector, provider) {
    const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService);
    return languageFeaturesService.implementationProvider.register(languageSelector, provider);
  }
  function registerTypeDefinitionProvider(languageSelector, provider) {
    const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService);
    return languageFeaturesService.typeDefinitionProvider.register(languageSelector, provider);
  }
  function registerCodeLensProvider(languageSelector, provider) {
    const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService);
    return languageFeaturesService.codeLensProvider.register(languageSelector, provider);
  }
  function registerCodeActionProvider(languageSelector, provider, metadata) {
    const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService);
    return languageFeaturesService.codeActionProvider.register(languageSelector, {
      providedCodeActionKinds: metadata?.providedCodeActionKinds,
      documentation: metadata?.documentation,
      provideCodeActions: (model, range2, context, token) => {
        const markerService = StandaloneServices.get(IMarkerService);
        const markers = markerService.read({ resource: model.uri }).filter((m) => {
          return Range$2.areIntersectingOrTouching(m, range2);
        });
        return provider.provideCodeActions(model, range2, { markers, only: context.only, trigger: context.trigger }, token);
      },
      resolveCodeAction: provider.resolveCodeAction
    });
  }
  function registerDocumentFormattingEditProvider(languageSelector, provider) {
    const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService);
    return languageFeaturesService.documentFormattingEditProvider.register(languageSelector, provider);
  }
  function registerDocumentRangeFormattingEditProvider(languageSelector, provider) {
    const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService);
    return languageFeaturesService.documentRangeFormattingEditProvider.register(languageSelector, provider);
  }
  function registerOnTypeFormattingEditProvider(languageSelector, provider) {
    const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService);
    return languageFeaturesService.onTypeFormattingEditProvider.register(languageSelector, provider);
  }
  function registerLinkProvider(languageSelector, provider) {
    const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService);
    return languageFeaturesService.linkProvider.register(languageSelector, provider);
  }
  function registerCompletionItemProvider(languageSelector, provider) {
    const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService);
    return languageFeaturesService.completionProvider.register(languageSelector, provider);
  }
  function registerColorProvider(languageSelector, provider) {
    const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService);
    return languageFeaturesService.colorProvider.register(languageSelector, provider);
  }
  function registerFoldingRangeProvider(languageSelector, provider) {
    const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService);
    return languageFeaturesService.foldingRangeProvider.register(languageSelector, provider);
  }
  function registerDeclarationProvider(languageSelector, provider) {
    const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService);
    return languageFeaturesService.declarationProvider.register(languageSelector, provider);
  }
  function registerSelectionRangeProvider(languageSelector, provider) {
    const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService);
    return languageFeaturesService.selectionRangeProvider.register(languageSelector, provider);
  }
  function registerDocumentSemanticTokensProvider(languageSelector, provider) {
    const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService);
    return languageFeaturesService.documentSemanticTokensProvider.register(languageSelector, provider);
  }
  function registerDocumentRangeSemanticTokensProvider(languageSelector, provider) {
    const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService);
    return languageFeaturesService.documentRangeSemanticTokensProvider.register(languageSelector, provider);
  }
  function registerInlineCompletionsProvider(languageSelector, provider) {
    const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService);
    return languageFeaturesService.inlineCompletionsProvider.register(languageSelector, provider);
  }
  function registerInlayHintsProvider(languageSelector, provider) {
    const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService);
    return languageFeaturesService.inlayHintsProvider.register(languageSelector, provider);
  }
  function createMonacoLanguagesAPI() {
    return {
      // eslint-disable-next-line local/code-no-any-casts
      register,
      // eslint-disable-next-line local/code-no-any-casts
      getLanguages,
      // eslint-disable-next-line local/code-no-any-casts
      onLanguage,
      // eslint-disable-next-line local/code-no-any-casts
      onLanguageEncountered,
      // eslint-disable-next-line local/code-no-any-casts
      getEncodedLanguageId,
      // provider methods
      // eslint-disable-next-line local/code-no-any-casts
      setLanguageConfiguration,
      setColorMap,
      // eslint-disable-next-line local/code-no-any-casts
      registerTokensProviderFactory,
      // eslint-disable-next-line local/code-no-any-casts
      setTokensProvider,
      // eslint-disable-next-line local/code-no-any-casts
      setMonarchTokensProvider,
      // eslint-disable-next-line local/code-no-any-casts
      registerReferenceProvider,
      // eslint-disable-next-line local/code-no-any-casts
      registerRenameProvider,
      // eslint-disable-next-line local/code-no-any-casts
      registerNewSymbolNameProvider,
      // eslint-disable-next-line local/code-no-any-casts
      registerCompletionItemProvider,
      // eslint-disable-next-line local/code-no-any-casts
      registerSignatureHelpProvider,
      // eslint-disable-next-line local/code-no-any-casts
      registerHoverProvider,
      // eslint-disable-next-line local/code-no-any-casts
      registerDocumentSymbolProvider,
      // eslint-disable-next-line local/code-no-any-casts
      registerDocumentHighlightProvider,
      // eslint-disable-next-line local/code-no-any-casts
      registerLinkedEditingRangeProvider,
      // eslint-disable-next-line local/code-no-any-casts
      registerDefinitionProvider,
      // eslint-disable-next-line local/code-no-any-casts
      registerImplementationProvider,
      // eslint-disable-next-line local/code-no-any-casts
      registerTypeDefinitionProvider,
      // eslint-disable-next-line local/code-no-any-casts
      registerCodeLensProvider,
      // eslint-disable-next-line local/code-no-any-casts
      registerCodeActionProvider,
      // eslint-disable-next-line local/code-no-any-casts
      registerDocumentFormattingEditProvider,
      // eslint-disable-next-line local/code-no-any-casts
      registerDocumentRangeFormattingEditProvider,
      // eslint-disable-next-line local/code-no-any-casts
      registerOnTypeFormattingEditProvider,
      // eslint-disable-next-line local/code-no-any-casts
      registerLinkProvider,
      // eslint-disable-next-line local/code-no-any-casts
      registerColorProvider,
      // eslint-disable-next-line local/code-no-any-casts
      registerFoldingRangeProvider,
      // eslint-disable-next-line local/code-no-any-casts
      registerDeclarationProvider,
      // eslint-disable-next-line local/code-no-any-casts
      registerSelectionRangeProvider,
      // eslint-disable-next-line local/code-no-any-casts
      registerDocumentSemanticTokensProvider,
      // eslint-disable-next-line local/code-no-any-casts
      registerDocumentRangeSemanticTokensProvider,
      // eslint-disable-next-line local/code-no-any-casts
      registerInlineCompletionsProvider,
      // eslint-disable-next-line local/code-no-any-casts
      registerInlayHintsProvider,
      // enums
      DocumentHighlightKind,
      CompletionItemKind,
      CompletionItemTag,
      CompletionItemInsertTextRule,
      SymbolKind,
      SymbolTag,
      IndentAction,
      CompletionTriggerKind,
      SignatureHelpTriggerKind,
      InlayHintKind,
      InlineCompletionTriggerKind,
      CodeActionTriggerType,
      NewSymbolNameTag,
      NewSymbolNameTriggerKind,
      PartialAcceptTriggerKind,
      HoverVerbosityAction,
      InlineCompletionEndOfLifeReasonKind,
      InlineCompletionHintStyle,
      // classes
      FoldingRangeKind,
      // eslint-disable-next-line local/code-no-any-casts
      SelectedSuggestionInfo,
      // eslint-disable-next-line local/code-no-any-casts
      EditDeltaInfo
    };
  }
  EditorOptions.wrappingIndent.defaultValue = 0;
  EditorOptions.glyphMargin.defaultValue = false;
  EditorOptions.autoIndent.defaultValue = 3;
  EditorOptions.overviewRulerLanes.defaultValue = 2;
  FormattingConflicts.setFormatterSelector((formatter, document2, mode) => Promise.resolve(formatter[0]));
  const api = createMonacoBaseAPI();
  api.editor = createMonacoEditorAPI();
  api.languages = createMonacoLanguagesAPI();
  const CancellationTokenSource = api.CancellationTokenSource;
  const Emitter = api.Emitter;
  const KeyCode = api.KeyCode;
  const KeyMod = api.KeyMod;
  const Position = api.Position;
  const Range = api.Range;
  const Selection = api.Selection;
  const SelectionDirection = api.SelectionDirection;
  const MarkerSeverity = api.MarkerSeverity;
  const MarkerTag = api.MarkerTag;
  const Uri = api.Uri;
  const Token = api.Token;
  const editor = api.editor;
  const languages = api.languages;
  const monacoEnvironment = getMonacoEnvironment();
  const globalWithAMD = globalThis;
  if (monacoEnvironment?.globalAPI || typeof globalWithAMD.define === "function" && globalWithAMD.define.amd) {
    globalWithAMD.monaco = api;
  }
  if (typeof globalWithAMD.require !== "undefined" && typeof globalWithAMD.require.config === "function") {
    globalWithAMD.require.config({
      ignoreDuplicateModules: [
        "vscode-languageserver-types",
        "vscode-languageserver-types/main",
        "vscode-languageserver-textdocument",
        "vscode-languageserver-textdocument/main",
        "vscode-nls",
        "vscode-nls/vscode-nls",
        "jsonc-parser",
        "jsonc-parser/main",
        "vscode-uri",
        "vscode-uri/index",
        "vs/basic-languages/typescript/typescript"
      ]
    });
  }
  const monaco = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
    __proto__: null,
    CancellationTokenSource,
    Emitter,
    KeyCode,
    KeyMod,
    MarkerSeverity,
    MarkerTag,
    Position,
    Range,
    Selection,
    SelectionDirection,
    Token,
    Uri,
    editor,
    languages
  }, Symbol.toStringTag, { value: "Module" }));
  exports.CancellationTokenSource = CancellationTokenSource;
  exports.Emitter = Emitter;
  exports.KeyCode = KeyCode;
  exports.KeyMod = KeyMod;
  exports.MarkerSeverity = MarkerSeverity;
  exports.MarkerTag = MarkerTag;
  exports.Position = Position;
  exports.Range = Range;
  exports.Selection = Selection;
  exports.SelectionDirection = SelectionDirection;
  exports.Token = Token;
  exports.Uri = Uri;
  exports.editor = editor;
  exports.languages = languages;
  exports.monaco = monaco;
}));
