"use client";
function we(t) {
  return Y(t);
}
function Y(t) {
  return Array.isArray(t) ? Ie(t) : t instanceof RegExp ? t : typeof t == "object" ? be(t) : t;
}
function Ie(t) {
  let e = [];
  for (let s = 0, n = t.length; s < n; s++)
    e[s] = Y(t[s]);
  return e;
}
function be(t) {
  let e = {};
  for (let s in t)
    e[s] = Y(t[s]);
  return e;
}
function ae(t, ...e) {
  return e.forEach((s) => {
    for (let n in s)
      t[n] = s[n];
  }), t;
}
function ce(t) {
  const e = ~t.lastIndexOf("/") || ~t.lastIndexOf("\\");
  return e === 0 ? t : ~e === t.length - 1 ? ce(t.substring(0, t.length - 1)) : t.substr(~e + 1);
}
var D = /\$(\d+)|\${(\d+):\/(downcase|upcase)}/g, L = class {
  static hasCaptures(t) {
    return t === null ? !1 : (D.lastIndex = 0, D.test(t));
  }
  static replaceCaptures(t, e, s) {
    return t.replace(D, (n, r, i, a) => {
      let c = s[parseInt(r || i, 10)];
      if (c) {
        let o = e.substring(c.start, c.end);
        for (; o[0] === "."; )
          o = o.substring(1);
        switch (a) {
          case "downcase":
            return o.toLowerCase();
          case "upcase":
            return o.toUpperCase();
          default:
            return o;
        }
      } else
        return n;
    });
  }
};
function le(t, e) {
  return t < e ? -1 : t > e ? 1 : 0;
}
function he(t, e) {
  if (t === null && e === null)
    return 0;
  if (!t)
    return -1;
  if (!e)
    return 1;
  let s = t.length, n = e.length;
  if (s === n) {
    for (let r = 0; r < s; r++) {
      let i = le(t[r], e[r]);
      if (i !== 0)
        return i;
    }
    return 0;
  }
  return s - n;
}
function Z(t) {
  return !!(/^#[0-9a-f]{6}$/i.test(t) || /^#[0-9a-f]{8}$/i.test(t) || /^#[0-9a-f]{3}$/i.test(t) || /^#[0-9a-f]{4}$/i.test(t));
}
function ue(t) {
  return t.replace(/[\-\\\{\}\*\+\?\|\^\$\.\,\[\]\(\)\#\s]/g, "\\$&");
}
var pe = class {
  constructor(t) {
    this.fn = t;
  }
  cache = /* @__PURE__ */ new Map();
  get(t) {
    if (this.cache.has(t))
      return this.cache.get(t);
    const e = this.fn(t);
    return this.cache.set(t, e), e;
  }
}, U = class {
  constructor(t, e, s) {
    this._colorMap = t, this._defaults = e, this._root = s;
  }
  static createFromRawTheme(t, e) {
    return this.createFromParsedTheme(ke(t), e);
  }
  static createFromParsedTheme(t, e) {
    return Ge(t, e);
  }
  _cachedMatchRoot = new pe(
    (t) => this._root.match(t)
  );
  getColorMap() {
    return this._colorMap.getColorMap();
  }
  getDefaults() {
    return this._defaults;
  }
  match(t) {
    if (t === null)
      return this._defaults;
    const e = t.scopeName, n = this._cachedMatchRoot.get(e).find(
      (r) => Ae(t.parent, r.parentScopes)
    );
    return n ? new de(
      n.fontStyle,
      n.foreground,
      n.background
    ) : null;
  }
}, z = class T {
  constructor(e, s) {
    this.parent = e, this.scopeName = s;
  }
  static push(e, s) {
    for (const n of s)
      e = new T(e, n);
    return e;
  }
  static from(...e) {
    let s = null;
    for (let n = 0; n < e.length; n++)
      s = new T(s, e[n]);
    return s;
  }
  push(e) {
    return new T(this, e);
  }
  getSegments() {
    let e = this;
    const s = [];
    for (; e; )
      s.push(e.scopeName), e = e.parent;
    return s.reverse(), s;
  }
  toString() {
    return this.getSegments().join(" ");
  }
  extends(e) {
    return this === e ? !0 : this.parent === null ? !1 : this.parent.extends(e);
  }
  getExtensionIfDefined(e) {
    const s = [];
    let n = this;
    for (; n && n !== e; )
      s.push(n.scopeName), n = n.parent;
    return n === e ? s.reverse() : void 0;
  }
};
function Ae(t, e) {
  if (e.length === 0)
    return !0;
  for (let s = 0; s < e.length; s++) {
    let n = e[s], r = !1;
    if (n === ">") {
      if (s === e.length - 1)
        return !1;
      n = e[++s], r = !0;
    }
    for (; t && !Pe(t.scopeName, n); ) {
      if (r)
        return !1;
      t = t.parent;
    }
    if (!t)
      return !1;
    t = t.parent;
  }
  return !0;
}
function Pe(t, e) {
  return e === t || t.startsWith(e) && t[e.length] === ".";
}
var de = class {
  constructor(t, e, s) {
    this.fontStyle = t, this.foregroundId = e, this.backgroundId = s;
  }
};
function ke(t) {
  if (!t)
    return [];
  if (!t.settings || !Array.isArray(t.settings))
    return [];
  let e = t.settings, s = [], n = 0;
  for (let r = 0, i = e.length; r < i; r++) {
    let a = e[r];
    if (!a.settings)
      continue;
    let c;
    if (typeof a.scope == "string") {
      let u = a.scope;
      u = u.replace(/^[,]+/, ""), u = u.replace(/[,]+$/, ""), c = u.split(",");
    } else Array.isArray(a.scope) ? c = a.scope : c = [""];
    let o = -1;
    if (typeof a.settings.fontStyle == "string") {
      o = 0;
      let u = a.settings.fontStyle.split(" ");
      for (let f = 0, d = u.length; f < d; f++)
        switch (u[f]) {
          case "italic":
            o = o | 1;
            break;
          case "bold":
            o = o | 2;
            break;
          case "underline":
            o = o | 4;
            break;
          case "strikethrough":
            o = o | 8;
            break;
        }
    }
    let l = null;
    typeof a.settings.foreground == "string" && Z(a.settings.foreground) && (l = a.settings.foreground);
    let h = null;
    typeof a.settings.background == "string" && Z(a.settings.background) && (h = a.settings.background);
    for (let u = 0, f = c.length; u < f; u++) {
      let p = c[u].trim().split(" "), S = p[p.length - 1], _ = null;
      p.length > 1 && (_ = p.slice(0, p.length - 1), _.reverse()), s[n++] = new Ne(
        S,
        _,
        r,
        o,
        l,
        h
      );
    }
  }
  return s;
}
var Ne = class {
  constructor(t, e, s, n, r, i) {
    this.scope = t, this.parentScopes = e, this.index = s, this.fontStyle = n, this.foreground = r, this.background = i;
  }
}, ve = /* @__PURE__ */ ((t) => (t[t.NotSet = -1] = "NotSet", t[t.None = 0] = "None", t[t.Italic = 1] = "Italic", t[t.Bold = 2] = "Bold", t[t.Underline = 4] = "Underline", t[t.Strikethrough = 8] = "Strikethrough", t))(ve || {});
function Ge(t, e) {
  t.sort((o, l) => {
    let h = le(o.scope, l.scope);
    return h !== 0 || (h = he(o.parentScopes, l.parentScopes), h !== 0) ? h : o.index - l.index;
  });
  let s = 0, n = "#000000", r = "#ffffff";
  for (; t.length >= 1 && t[0].scope === ""; ) {
    let o = t.shift();
    o.fontStyle !== -1 && (s = o.fontStyle), o.foreground !== null && (n = o.foreground), o.background !== null && (r = o.background);
  }
  let i = new Ee(e), a = new de(s, i.getId(n), i.getId(r)), c = new Te(new K(0, null, -1, 0, 0), []);
  for (let o = 0, l = t.length; o < l; o++) {
    let h = t[o];
    c.insert(0, h.scope, h.parentScopes, h.fontStyle, i.getId(h.foreground), i.getId(h.background));
  }
  return new U(i, a, c);
}
var Ee = class {
  _isFrozen;
  _lastColorId;
  _id2color;
  _color2id;
  constructor(t) {
    if (this._lastColorId = 0, this._id2color = [], this._color2id = /* @__PURE__ */ Object.create(null), Array.isArray(t)) {
      this._isFrozen = !0;
      for (let e = 0, s = t.length; e < s; e++)
        this._color2id[t[e]] = e, this._id2color[e] = t[e];
    } else
      this._isFrozen = !1;
  }
  getId(t) {
    if (t === null)
      return 0;
    t = t.toUpperCase();
    let e = this._color2id[t];
    if (e)
      return e;
    if (this._isFrozen)
      throw new Error(`Missing color in color map - ${t}`);
    return e = ++this._lastColorId, this._color2id[t] = e, this._id2color[e] = t, e;
  }
  getColorMap() {
    return this._id2color.slice(0);
  }
}, Le = Object.freeze([]), K = class fe {
  scopeDepth;
  parentScopes;
  fontStyle;
  foreground;
  background;
  constructor(e, s, n, r, i) {
    this.scopeDepth = e, this.parentScopes = s || Le, this.fontStyle = n, this.foreground = r, this.background = i;
  }
  clone() {
    return new fe(this.scopeDepth, this.parentScopes, this.fontStyle, this.foreground, this.background);
  }
  static cloneArr(e) {
    let s = [];
    for (let n = 0, r = e.length; n < r; n++)
      s[n] = e[n].clone();
    return s;
  }
  acceptOverwrite(e, s, n, r) {
    this.scopeDepth > e ? console.log("how did this happen?") : this.scopeDepth = e, s !== -1 && (this.fontStyle = s), n !== 0 && (this.foreground = n), r !== 0 && (this.background = r);
  }
}, Te = class H {
  constructor(e, s = [], n = {}) {
    this._mainRule = e, this._children = n, this._rulesWithParentScopes = s;
  }
  _rulesWithParentScopes;
  static _cmpBySpecificity(e, s) {
    if (e.scopeDepth !== s.scopeDepth)
      return s.scopeDepth - e.scopeDepth;
    let n = 0, r = 0;
    for (; e.parentScopes[n] === ">" && n++, s.parentScopes[r] === ">" && r++, !(n >= e.parentScopes.length || r >= s.parentScopes.length); ) {
      const i = s.parentScopes[r].length - e.parentScopes[n].length;
      if (i !== 0)
        return i;
      n++, r++;
    }
    return s.parentScopes.length - e.parentScopes.length;
  }
  match(e) {
    if (e !== "") {
      let n = e.indexOf("."), r, i;
      if (n === -1 ? (r = e, i = "") : (r = e.substring(0, n), i = e.substring(n + 1)), this._children.hasOwnProperty(r))
        return this._children[r].match(i);
    }
    const s = this._rulesWithParentScopes.concat(this._mainRule);
    return s.sort(H._cmpBySpecificity), s;
  }
  insert(e, s, n, r, i, a) {
    if (s === "") {
      this._doInsertHere(e, n, r, i, a);
      return;
    }
    let c = s.indexOf("."), o, l;
    c === -1 ? (o = s, l = "") : (o = s.substring(0, c), l = s.substring(c + 1));
    let h;
    this._children.hasOwnProperty(o) ? h = this._children[o] : (h = new H(this._mainRule.clone(), K.cloneArr(this._rulesWithParentScopes)), this._children[o] = h), h.insert(e + 1, l, n, r, i, a);
  }
  _doInsertHere(e, s, n, r, i) {
    if (s === null) {
      this._mainRule.acceptOverwrite(e, n, r, i);
      return;
    }
    for (let a = 0, c = this._rulesWithParentScopes.length; a < c; a++) {
      let o = this._rulesWithParentScopes[a];
      if (he(o.parentScopes, s) === 0) {
        o.acceptOverwrite(e, n, r, i);
        return;
      }
    }
    n === -1 && (n = this._mainRule.fontStyle), r === 0 && (r = this._mainRule.foreground), i === 0 && (i = this._mainRule.background), this._rulesWithParentScopes.push(new K(e, s, n, r, i));
  }
}, M = class C {
  static toBinaryStr(e) {
    return e.toString(2).padStart(32, "0");
  }
  static print(e) {
    const s = C.getLanguageId(e), n = C.getTokenType(e), r = C.getFontStyle(e), i = C.getForeground(e), a = C.getBackground(e);
    console.log({
      languageId: s,
      tokenType: n,
      fontStyle: r,
      foreground: i,
      background: a
    });
  }
  static getLanguageId(e) {
    return (e & 255) >>> 0;
  }
  static getTokenType(e) {
    return (e & 768) >>> 8;
  }
  static containsBalancedBrackets(e) {
    return (e & 1024) !== 0;
  }
  static getFontStyle(e) {
    return (e & 30720) >>> 11;
  }
  static getForeground(e) {
    return (e & 16744448) >>> 15;
  }
  static getBackground(e) {
    return (e & 4278190080) >>> 24;
  }
  /**
   * Updates the fields in `metadata`.
   * A value of `0`, `NotSet` or `null` indicates that the corresponding field should be left as is.
   */
  static set(e, s, n, r, i, a, c) {
    let o = C.getLanguageId(e), l = C.getTokenType(e), h = C.containsBalancedBrackets(e) ? 1 : 0, u = C.getFontStyle(e), f = C.getForeground(e), d = C.getBackground(e);
    return s !== 0 && (o = s), n !== 8 && (l = n), r !== null && (h = r ? 1 : 0), i !== -1 && (u = i), a !== 0 && (f = a), c !== 0 && (d = c), (o << 0 | l << 8 | h << 10 | u << 11 | f << 15 | d << 24) >>> 0;
  }
};
function x(t, e) {
  const s = [], n = Be(t);
  let r = n.next();
  for (; r !== null; ) {
    let o = 0;
    if (r.length === 2 && r.charAt(1) === ":") {
      switch (r.charAt(0)) {
        case "R":
          o = 1;
          break;
        case "L":
          o = -1;
          break;
        default:
          console.log(`Unknown priority ${r} in scope selector`);
      }
      r = n.next();
    }
    let l = a();
    if (s.push({ matcher: l, priority: o }), r !== ",")
      break;
    r = n.next();
  }
  return s;
  function i() {
    if (r === "-") {
      r = n.next();
      const o = i();
      return (l) => !!o && !o(l);
    }
    if (r === "(") {
      r = n.next();
      const o = c();
      return r === ")" && (r = n.next()), o;
    }
    if (ee(r)) {
      const o = [];
      do
        o.push(r), r = n.next();
      while (ee(r));
      return (l) => e(o, l);
    }
    return null;
  }
  function a() {
    const o = [];
    let l = i();
    for (; l; )
      o.push(l), l = i();
    return (h) => o.every((u) => u(h));
  }
  function c() {
    const o = [];
    let l = a();
    for (; l && (o.push(l), r === "|" || r === ","); ) {
      do
        r = n.next();
      while (r === "|" || r === ",");
      l = a();
    }
    return (h) => o.some((u) => u(h));
  }
}
function ee(t) {
  return !!t && !!t.match(/[\w\.:]+/);
}
function Be(t) {
  let e = /([LR]:|[\w\.:][\w\.:\-]*|[\,\|\-\(\)])/g, s = e.exec(t);
  return {
    next: () => {
      if (!s)
        return null;
      const n = s[0];
      return s = e.exec(t), n;
    }
  };
}
function me(t) {
  typeof t.dispose == "function" && t.dispose();
}
var N = class {
  constructor(t) {
    this.scopeName = t;
  }
  toKey() {
    return this.scopeName;
  }
}, Me = class {
  constructor(t, e) {
    this.scopeName = t, this.ruleName = e;
  }
  toKey() {
    return `${this.scopeName}#${this.ruleName}`;
  }
}, xe = class {
  _references = [];
  _seenReferenceKeys = /* @__PURE__ */ new Set();
  get references() {
    return this._references;
  }
  visitedRule = /* @__PURE__ */ new Set();
  add(t) {
    const e = t.toKey();
    this._seenReferenceKeys.has(e) || (this._seenReferenceKeys.add(e), this._references.push(t));
  }
}, Oe = class {
  constructor(t, e) {
    this.repo = t, this.initialScopeName = e, this.seenFullScopeRequests.add(this.initialScopeName), this.Q = [new N(this.initialScopeName)];
  }
  seenFullScopeRequests = /* @__PURE__ */ new Set();
  seenPartialScopeRequests = /* @__PURE__ */ new Set();
  Q;
  processQueue() {
    const t = this.Q;
    this.Q = [];
    const e = new xe();
    for (const s of t)
      je(s, this.initialScopeName, this.repo, e);
    for (const s of e.references)
      if (s instanceof N) {
        if (this.seenFullScopeRequests.has(s.scopeName))
          continue;
        this.seenFullScopeRequests.add(s.scopeName), this.Q.push(s);
      } else {
        if (this.seenFullScopeRequests.has(s.scopeName) || this.seenPartialScopeRequests.has(s.toKey()))
          continue;
        this.seenPartialScopeRequests.add(s.toKey()), this.Q.push(s);
      }
  }
};
function je(t, e, s, n) {
  const r = s.lookup(t.scopeName);
  if (!r) {
    if (t.scopeName === e)
      throw new Error(`No grammar provided for <${e}>`);
    return;
  }
  const i = s.lookup(e);
  t instanceof N ? B({ baseGrammar: i, selfGrammar: r }, n) : Q(
    t.ruleName,
    { baseGrammar: i, selfGrammar: r, repository: r.repository },
    n
  );
  const a = s.injections(t.scopeName);
  if (a)
    for (const c of a)
      n.add(new N(c));
}
function Q(t, e, s) {
  if (e.repository && e.repository[t]) {
    const n = e.repository[t];
    O([n], e, s);
  }
}
function B(t, e) {
  t.selfGrammar.patterns && Array.isArray(t.selfGrammar.patterns) && O(
    t.selfGrammar.patterns,
    { ...t, repository: t.selfGrammar.repository },
    e
  ), t.selfGrammar.injections && O(
    Object.values(t.selfGrammar.injections),
    { ...t, repository: t.selfGrammar.repository },
    e
  );
}
function O(t, e, s) {
  for (const n of t) {
    if (s.visitedRule.has(n))
      continue;
    s.visitedRule.add(n);
    const r = n.repository ? ae({}, e.repository, n.repository) : e.repository;
    Array.isArray(n.patterns) && O(n.patterns, { ...e, repository: r }, s);
    const i = n.include;
    if (!i)
      continue;
    const a = _e(i);
    switch (a.kind) {
      case 0:
        B({ ...e, selfGrammar: e.baseGrammar }, s);
        break;
      case 1:
        B(e, s);
        break;
      case 2:
        Q(a.ruleName, { ...e, repository: r }, s);
        break;
      case 3:
      case 4:
        const c = a.scopeName === e.selfGrammar.scopeName ? e.selfGrammar : a.scopeName === e.baseGrammar.scopeName ? e.baseGrammar : void 0;
        if (c) {
          const o = { baseGrammar: e.baseGrammar, selfGrammar: c, repository: r };
          a.kind === 4 ? Q(a.ruleName, o, s) : B(o, s);
        } else
          a.kind === 4 ? s.add(new Me(a.scopeName, a.ruleName)) : s.add(new N(a.scopeName));
        break;
    }
  }
}
var $e = class {
  kind = 0;
}, Fe = class {
  kind = 1;
}, We = class {
  constructor(t) {
    this.ruleName = t;
  }
  kind = 2;
}, De = class {
  constructor(t) {
    this.scopeName = t;
  }
  kind = 3;
}, ze = class {
  constructor(t, e) {
    this.scopeName = t, this.ruleName = e;
  }
  kind = 4;
};
function _e(t) {
  if (t === "$base")
    return new $e();
  if (t === "$self")
    return new Fe();
  const e = t.indexOf("#");
  if (e === -1)
    return new De(t);
  if (e === 0)
    return new We(t.substring(1));
  {
    const s = t.substring(0, e), n = t.substring(e + 1);
    return new ze(s, n);
  }
}
var qe = /\\(\d+)/, te = /\\(\d+)/g, Ue = -1, ge = -2;
var E = class {
  $location;
  id;
  _nameIsCapturing;
  _name;
  _contentNameIsCapturing;
  _contentName;
  constructor(t, e, s, n) {
    this.$location = t, this.id = e, this._name = s || null, this._nameIsCapturing = L.hasCaptures(this._name), this._contentName = n || null, this._contentNameIsCapturing = L.hasCaptures(this._contentName);
  }
  get debugName() {
    const t = this.$location ? `${ce(this.$location.filename)}:${this.$location.line}` : "unknown";
    return `${this.constructor.name}#${this.id} @ ${t}`;
  }
  getName(t, e) {
    return !this._nameIsCapturing || this._name === null || t === null || e === null ? this._name : L.replaceCaptures(this._name, t, e);
  }
  getContentName(t, e) {
    return !this._contentNameIsCapturing || this._contentName === null ? this._contentName : L.replaceCaptures(this._contentName, t, e);
  }
}, Ke = class extends E {
  retokenizeCapturedWithRuleId;
  constructor(t, e, s, n, r) {
    super(t, e, s, n), this.retokenizeCapturedWithRuleId = r;
  }
  dispose() {
  }
  collectPatterns(t, e) {
    throw new Error("Not supported!");
  }
  compile(t, e) {
    throw new Error("Not supported!");
  }
  compileAG(t, e, s, n) {
    throw new Error("Not supported!");
  }
}, He = class extends E {
  _match;
  captures;
  _cachedCompiledPatterns;
  constructor(t, e, s, n, r) {
    super(t, e, s, null), this._match = new v(n, this.id), this.captures = r, this._cachedCompiledPatterns = null;
  }
  dispose() {
    this._cachedCompiledPatterns && (this._cachedCompiledPatterns.dispose(), this._cachedCompiledPatterns = null);
  }
  get debugMatchRegExp() {
    return `${this._match.source}`;
  }
  collectPatterns(t, e) {
    e.push(this._match);
  }
  compile(t, e) {
    return this._getCachedCompiledPatterns(t).compile(t);
  }
  compileAG(t, e, s, n) {
    return this._getCachedCompiledPatterns(t).compileAG(t, s, n);
  }
  _getCachedCompiledPatterns(t) {
    return this._cachedCompiledPatterns || (this._cachedCompiledPatterns = new G(), this.collectPatterns(t, this._cachedCompiledPatterns)), this._cachedCompiledPatterns;
  }
}, se = class extends E {
  hasMissingPatterns;
  patterns;
  _cachedCompiledPatterns;
  constructor(t, e, s, n, r) {
    super(t, e, s, n), this.patterns = r.patterns, this.hasMissingPatterns = r.hasMissingPatterns, this._cachedCompiledPatterns = null;
  }
  dispose() {
    this._cachedCompiledPatterns && (this._cachedCompiledPatterns.dispose(), this._cachedCompiledPatterns = null);
  }
  collectPatterns(t, e) {
    for (const s of this.patterns)
      t.getRule(s).collectPatterns(t, e);
  }
  compile(t, e) {
    return this._getCachedCompiledPatterns(t).compile(t);
  }
  compileAG(t, e, s, n) {
    return this._getCachedCompiledPatterns(t).compileAG(t, s, n);
  }
  _getCachedCompiledPatterns(t) {
    return this._cachedCompiledPatterns || (this._cachedCompiledPatterns = new G(), this.collectPatterns(t, this._cachedCompiledPatterns)), this._cachedCompiledPatterns;
  }
}, X = class extends E {
  _begin;
  beginCaptures;
  _end;
  endHasBackReferences;
  endCaptures;
  applyEndPatternLast;
  hasMissingPatterns;
  patterns;
  _cachedCompiledPatterns;
  constructor(t, e, s, n, r, i, a, c, o, l) {
    super(t, e, s, n), this._begin = new v(r, this.id), this.beginCaptures = i, this._end = new v(a || "", -1), this.endHasBackReferences = this._end.hasBackReferences, this.endCaptures = c, this.applyEndPatternLast = o || !1, this.patterns = l.patterns, this.hasMissingPatterns = l.hasMissingPatterns, this._cachedCompiledPatterns = null;
  }
  dispose() {
    this._cachedCompiledPatterns && (this._cachedCompiledPatterns.dispose(), this._cachedCompiledPatterns = null);
  }
  get debugBeginRegExp() {
    return `${this._begin.source}`;
  }
  get debugEndRegExp() {
    return `${this._end.source}`;
  }
  getEndWithResolvedBackReferences(t, e) {
    return this._end.resolveBackReferences(t, e);
  }
  collectPatterns(t, e) {
    e.push(this._begin);
  }
  compile(t, e) {
    return this._getCachedCompiledPatterns(t, e).compile(t);
  }
  compileAG(t, e, s, n) {
    return this._getCachedCompiledPatterns(t, e).compileAG(t, s, n);
  }
  _getCachedCompiledPatterns(t, e) {
    if (!this._cachedCompiledPatterns) {
      this._cachedCompiledPatterns = new G();
      for (const s of this.patterns)
        t.getRule(s).collectPatterns(t, this._cachedCompiledPatterns);
      this.applyEndPatternLast ? this._cachedCompiledPatterns.push(this._end.hasBackReferences ? this._end.clone() : this._end) : this._cachedCompiledPatterns.unshift(this._end.hasBackReferences ? this._end.clone() : this._end);
    }
    return this._end.hasBackReferences && (this.applyEndPatternLast ? this._cachedCompiledPatterns.setSource(this._cachedCompiledPatterns.length() - 1, e) : this._cachedCompiledPatterns.setSource(0, e)), this._cachedCompiledPatterns;
  }
}, j = class extends E {
  _begin;
  beginCaptures;
  whileCaptures;
  _while;
  whileHasBackReferences;
  hasMissingPatterns;
  patterns;
  _cachedCompiledPatterns;
  _cachedCompiledWhilePatterns;
  constructor(t, e, s, n, r, i, a, c, o) {
    super(t, e, s, n), this._begin = new v(r, this.id), this.beginCaptures = i, this.whileCaptures = c, this._while = new v(a, ge), this.whileHasBackReferences = this._while.hasBackReferences, this.patterns = o.patterns, this.hasMissingPatterns = o.hasMissingPatterns, this._cachedCompiledPatterns = null, this._cachedCompiledWhilePatterns = null;
  }
  dispose() {
    this._cachedCompiledPatterns && (this._cachedCompiledPatterns.dispose(), this._cachedCompiledPatterns = null), this._cachedCompiledWhilePatterns && (this._cachedCompiledWhilePatterns.dispose(), this._cachedCompiledWhilePatterns = null);
  }
  get debugBeginRegExp() {
    return `${this._begin.source}`;
  }
  get debugWhileRegExp() {
    return `${this._while.source}`;
  }
  getWhileWithResolvedBackReferences(t, e) {
    return this._while.resolveBackReferences(t, e);
  }
  collectPatterns(t, e) {
    e.push(this._begin);
  }
  compile(t, e) {
    return this._getCachedCompiledPatterns(t).compile(t);
  }
  compileAG(t, e, s, n) {
    return this._getCachedCompiledPatterns(t).compileAG(t, s, n);
  }
  _getCachedCompiledPatterns(t) {
    if (!this._cachedCompiledPatterns) {
      this._cachedCompiledPatterns = new G();
      for (const e of this.patterns)
        t.getRule(e).collectPatterns(t, this._cachedCompiledPatterns);
    }
    return this._cachedCompiledPatterns;
  }
  compileWhile(t, e) {
    return this._getCachedCompiledWhilePatterns(t, e).compile(t);
  }
  compileWhileAG(t, e, s, n) {
    return this._getCachedCompiledWhilePatterns(t, e).compileAG(t, s, n);
  }
  _getCachedCompiledWhilePatterns(t, e) {
    return this._cachedCompiledWhilePatterns || (this._cachedCompiledWhilePatterns = new G(), this._cachedCompiledWhilePatterns.push(this._while.hasBackReferences ? this._while.clone() : this._while)), this._while.hasBackReferences && this._cachedCompiledWhilePatterns.setSource(0, e || ""), this._cachedCompiledWhilePatterns;
  }
}, Re = class m {
  static createCaptureRule(e, s, n, r, i) {
    return e.registerRule((a) => new Ke(s, a, n, r, i));
  }
  static getCompiledRuleId(e, s, n) {
    return e.id || s.registerRule((r) => {
      if (e.id = r, e.match)
        return new He(
          e.$vscodeTextmateLocation,
          e.id,
          e.name,
          e.match,
          m._compileCaptures(e.captures, s, n)
        );
      if (typeof e.begin > "u") {
        e.repository && (n = ae({}, n, e.repository));
        let i = e.patterns;
        return typeof i > "u" && e.include && (i = [{ include: e.include }]), new se(
          e.$vscodeTextmateLocation,
          e.id,
          e.name,
          e.contentName,
          m._compilePatterns(i, s, n)
        );
      }
      return e.while ? new j(
        e.$vscodeTextmateLocation,
        e.id,
        e.name,
        e.contentName,
        e.begin,
        m._compileCaptures(e.beginCaptures || e.captures, s, n),
        e.while,
        m._compileCaptures(e.whileCaptures || e.captures, s, n),
        m._compilePatterns(e.patterns, s, n)
      ) : new X(
        e.$vscodeTextmateLocation,
        e.id,
        e.name,
        e.contentName,
        e.begin,
        m._compileCaptures(e.beginCaptures || e.captures, s, n),
        e.end,
        m._compileCaptures(e.endCaptures || e.captures, s, n),
        e.applyEndPatternLast,
        m._compilePatterns(e.patterns, s, n)
      );
    }), e.id;
  }
  static _compileCaptures(e, s, n) {
    let r = [];
    if (e) {
      let i = 0;
      for (const a in e) {
        if (a === "$vscodeTextmateLocation")
          continue;
        const c = parseInt(a, 10);
        c > i && (i = c);
      }
      for (let a = 0; a <= i; a++)
        r[a] = null;
      for (const a in e) {
        if (a === "$vscodeTextmateLocation")
          continue;
        const c = parseInt(a, 10);
        let o = 0;
        e[a].patterns && (o = m.getCompiledRuleId(e[a], s, n)), r[c] = m.createCaptureRule(s, e[a].$vscodeTextmateLocation, e[a].name, e[a].contentName, o);
      }
    }
    return r;
  }
  static _compilePatterns(e, s, n) {
    let r = [];
    if (e)
      for (let i = 0, a = e.length; i < a; i++) {
        const c = e[i];
        let o = -1;
        if (c.include) {
          const l = _e(c.include);
          switch (l.kind) {
            case 0:
            case 1:
              o = m.getCompiledRuleId(n[c.include], s, n);
              break;
            case 2:
              let h = n[l.ruleName];
              h && (o = m.getCompiledRuleId(h, s, n));
              break;
            case 3:
            case 4:
              const u = l.scopeName, f = l.kind === 4 ? l.ruleName : null, d = s.getExternalGrammar(u, n);
              if (d)
                if (f) {
                  let p = d.repository[f];
                  p && (o = m.getCompiledRuleId(p, s, d.repository));
                } else
                  o = m.getCompiledRuleId(d.repository.$self, s, d.repository);
              break;
          }
        } else
          o = m.getCompiledRuleId(c, s, n);
        if (o !== -1) {
          const l = s.getRule(o);
          let h = !1;
          if ((l instanceof se || l instanceof X || l instanceof j) && l.hasMissingPatterns && l.patterns.length === 0 && (h = !0), h)
            continue;
          r.push(o);
        }
      }
    return {
      patterns: r,
      hasMissingPatterns: (e ? e.length : 0) !== r.length
    };
  }
}, v = class Ce {
  source;
  ruleId;
  hasAnchor;
  hasBackReferences;
  _anchorCache;
  constructor(e, s) {
    if (e && typeof e == "string") {
      const n = e.length;
      let r = 0, i = [], a = !1;
      for (let c = 0; c < n; c++)
        if (e.charAt(c) === "\\" && c + 1 < n) {
          const l = e.charAt(c + 1);
          l === "z" ? (i.push(e.substring(r, c)), i.push("$(?!\\n)(?<!\\n)"), r = c + 2) : (l === "A" || l === "G") && (a = !0), c++;
        }
      this.hasAnchor = a, r === 0 ? this.source = e : (i.push(e.substring(r, n)), this.source = i.join(""));
    } else
      this.hasAnchor = !1, this.source = e;
    this.hasAnchor ? this._anchorCache = this._buildAnchorCache() : this._anchorCache = null, this.ruleId = s, typeof this.source == "string" ? this.hasBackReferences = qe.test(this.source) : this.hasBackReferences = !1;
  }
  clone() {
    return new Ce(this.source, this.ruleId);
  }
  setSource(e) {
    this.source !== e && (this.source = e, this.hasAnchor && (this._anchorCache = this._buildAnchorCache()));
  }
  resolveBackReferences(e, s) {
    if (typeof this.source != "string")
      throw new Error("This method should only be called if the source is a string");
    let n = s.map((r) => e.substring(r.start, r.end));
    return te.lastIndex = 0, this.source.replace(te, (r, i) => ue(n[parseInt(i, 10)] || ""));
  }
  _buildAnchorCache() {
    if (typeof this.source != "string")
      throw new Error("This method should only be called if the source is a string");
    let e = [], s = [], n = [], r = [], i, a, c, o;
    for (i = 0, a = this.source.length; i < a; i++)
      c = this.source.charAt(i), e[i] = c, s[i] = c, n[i] = c, r[i] = c, c === "\\" && i + 1 < a && (o = this.source.charAt(i + 1), o === "A" ? (e[i + 1] = "", s[i + 1] = "", n[i + 1] = "A", r[i + 1] = "A") : o === "G" ? (e[i + 1] = "", s[i + 1] = "G", n[i + 1] = "", r[i + 1] = "G") : (e[i + 1] = o, s[i + 1] = o, n[i + 1] = o, r[i + 1] = o), i++);
    return {
      A0_G0: e.join(""),
      A0_G1: s.join(""),
      A1_G0: n.join(""),
      A1_G1: r.join("")
    };
  }
  resolveAnchors(e, s) {
    return !this.hasAnchor || !this._anchorCache || typeof this.source != "string" ? this.source : e ? s ? this._anchorCache.A1_G1 : this._anchorCache.A1_G0 : s ? this._anchorCache.A0_G1 : this._anchorCache.A0_G0;
  }
}, G = class {
  _items;
  _hasAnchors;
  _cached;
  _anchorCache;
  constructor() {
    this._items = [], this._hasAnchors = !1, this._cached = null, this._anchorCache = {
      A0_G0: null,
      A0_G1: null,
      A1_G0: null,
      A1_G1: null
    };
  }
  dispose() {
    this._disposeCaches();
  }
  _disposeCaches() {
    this._cached && (this._cached.dispose(), this._cached = null), this._anchorCache.A0_G0 && (this._anchorCache.A0_G0.dispose(), this._anchorCache.A0_G0 = null), this._anchorCache.A0_G1 && (this._anchorCache.A0_G1.dispose(), this._anchorCache.A0_G1 = null), this._anchorCache.A1_G0 && (this._anchorCache.A1_G0.dispose(), this._anchorCache.A1_G0 = null), this._anchorCache.A1_G1 && (this._anchorCache.A1_G1.dispose(), this._anchorCache.A1_G1 = null);
  }
  push(t) {
    this._items.push(t), this._hasAnchors = this._hasAnchors || t.hasAnchor;
  }
  unshift(t) {
    this._items.unshift(t), this._hasAnchors = this._hasAnchors || t.hasAnchor;
  }
  length() {
    return this._items.length;
  }
  setSource(t, e) {
    this._items[t].source !== e && (this._disposeCaches(), this._items[t].setSource(e));
  }
  compile(t) {
    if (!this._cached) {
      let e = this._items.map((s) => s.source);
      this._cached = new ne(t, e, this._items.map((s) => s.ruleId));
    }
    return this._cached;
  }
  compileAG(t, e, s) {
    return this._hasAnchors ? e ? s ? (this._anchorCache.A1_G1 || (this._anchorCache.A1_G1 = this._resolveAnchors(t, e, s)), this._anchorCache.A1_G1) : (this._anchorCache.A1_G0 || (this._anchorCache.A1_G0 = this._resolveAnchors(t, e, s)), this._anchorCache.A1_G0) : s ? (this._anchorCache.A0_G1 || (this._anchorCache.A0_G1 = this._resolveAnchors(t, e, s)), this._anchorCache.A0_G1) : (this._anchorCache.A0_G0 || (this._anchorCache.A0_G0 = this._resolveAnchors(t, e, s)), this._anchorCache.A0_G0) : this.compile(t);
  }
  _resolveAnchors(t, e, s) {
    let n = this._items.map((r) => r.resolveAnchors(e, s));
    return new ne(t, n, this._items.map((r) => r.ruleId));
  }
}, ne = class {
  constructor(t, e, s) {
    this.regExps = e, this.rules = s, this.scanner = t.createOnigScanner(e);
  }
  scanner;
  dispose() {
    typeof this.scanner.dispose == "function" && this.scanner.dispose();
  }
  toString() {
    const t = [];
    for (let e = 0, s = this.rules.length; e < s; e++)
      t.push("   - " + this.rules[e] + ": " + this.regExps[e]);
    return t.join(`
`);
  }
  findNextMatchSync(t, e, s) {
    const n = this.scanner.findNextMatchSync(t, e, s);
    return n ? {
      ruleId: this.rules[n.index],
      captureIndices: n.captureIndices
    } : null;
  }
}, q = class {
  constructor(t, e) {
    this.languageId = t, this.tokenType = e;
  }
}, Qe = class V {
  _defaultAttributes;
  _embeddedLanguagesMatcher;
  constructor(e, s) {
    this._defaultAttributes = new q(
      e,
      8
      /* NotSet */
    ), this._embeddedLanguagesMatcher = new Xe(Object.entries(s || {}));
  }
  getDefaultAttributes() {
    return this._defaultAttributes;
  }
  getBasicScopeAttributes(e) {
    return e === null ? V._NULL_SCOPE_METADATA : this._getBasicScopeAttributes.get(e);
  }
  static _NULL_SCOPE_METADATA = new q(0, 0);
  _getBasicScopeAttributes = new pe((e) => {
    const s = this._scopeToLanguage(e), n = this._toStandardTokenType(e);
    return new q(s, n);
  });
  /**
   * Given a produced TM scope, return the language that token describes or null if unknown.
   * e.g. source.html => html, source.css.embedded.html => css, punctuation.definition.tag.html => null
   */
  _scopeToLanguage(e) {
    return this._embeddedLanguagesMatcher.match(e) || 0;
  }
  _toStandardTokenType(e) {
    const s = e.match(V.STANDARD_TOKEN_TYPE_REGEXP);
    if (!s)
      return 8;
    switch (s[1]) {
      case "comment":
        return 1;
      case "string":
        return 2;
      case "regex":
        return 3;
      case "meta.embedded":
        return 0;
    }
    throw new Error("Unexpected match for standard token type!");
  }
  static STANDARD_TOKEN_TYPE_REGEXP = /\b(comment|string|regex|meta\.embedded)\b/;
}, Xe = class {
  values;
  scopesRegExp;
  constructor(t) {
    if (t.length === 0)
      this.values = null, this.scopesRegExp = null;
    else {
      this.values = new Map(t);
      const e = t.map(
        ([s, n]) => ue(s)
      );
      e.sort(), e.reverse(), this.scopesRegExp = new RegExp(
        `^((${e.join(")|(")}))($|\\.)`,
        ""
      );
    }
  }
  match(t) {
    if (!this.scopesRegExp)
      return;
    const e = t.match(this.scopesRegExp);
    if (e)
      return this.values.get(e[1]);
  }
};
typeof process < "u" && process.env.VSCODE_TEXTMATE_DEBUG;
var re = class {
  constructor(t, e) {
    this.stack = t, this.stoppedEarly = e;
  }
};
function Se(t, e, s, n, r, i, a, c) {
  const o = e.content.length;
  let l = !1, h = -1;
  if (a) {
    const d = Ve(
      t,
      e,
      s,
      n,
      r,
      i
    );
    r = d.stack, n = d.linePos, s = d.isFirstLine, h = d.anchorPosition;
  }
  const u = Date.now();
  for (; !l; ) {
    if (c !== 0 && Date.now() - u > c)
      return new re(r, !0);
    f();
  }
  return new re(r, !1);
  function f() {
    const d = Je(
      t,
      e,
      s,
      n,
      r,
      h
    );
    if (!d) {
      i.produce(r, o), l = !0;
      return;
    }
    const p = d.captureIndices, S = d.matchedRuleId, _ = p && p.length > 0 ? p[0].end > n : !1;
    if (S === Ue) {
      const R = r.getRule(t);
      i.produce(r, p[0].start), r = r.withContentNameScopesList(r.nameScopesList), P(
        t,
        e,
        s,
        r,
        i,
        R.endCaptures,
        p
      ), i.produce(r, p[0].end);
      const g = r;
      if (r = r.parent, h = g.getAnchorPos(), !_ && g.getEnterPos() === n) {
        r = g, i.produce(r, o), l = !0;
        return;
      }
    } else {
      const R = t.getRule(S);
      i.produce(r, p[0].start);
      const g = r, A = R.getName(e.content, p), I = r.contentNameScopesList.pushAttributed(
        A,
        t
      );
      if (r = r.push(
        S,
        n,
        h,
        p[0].end === o,
        null,
        I,
        I
      ), R instanceof X) {
        const y = R;
        P(
          t,
          e,
          s,
          r,
          i,
          y.beginCaptures,
          p
        ), i.produce(r, p[0].end), h = p[0].end;
        const F = y.getContentName(
          e.content,
          p
        ), W = I.pushAttributed(
          F,
          t
        );
        if (r = r.withContentNameScopesList(W), y.endHasBackReferences && (r = r.withEndRule(
          y.getEndWithResolvedBackReferences(
            e.content,
            p
          )
        )), !_ && g.hasSameRuleAs(r)) {
          r = r.pop(), i.produce(r, o), l = !0;
          return;
        }
      } else if (R instanceof j) {
        const y = R;
        P(
          t,
          e,
          s,
          r,
          i,
          y.beginCaptures,
          p
        ), i.produce(r, p[0].end), h = p[0].end;
        const F = y.getContentName(
          e.content,
          p
        ), W = I.pushAttributed(
          F,
          t
        );
        if (r = r.withContentNameScopesList(W), y.whileHasBackReferences && (r = r.withEndRule(
          y.getWhileWithResolvedBackReferences(
            e.content,
            p
          )
        )), !_ && g.hasSameRuleAs(r)) {
          r = r.pop(), i.produce(r, o), l = !0;
          return;
        }
      } else if (P(
        t,
        e,
        s,
        r,
        i,
        R.captures,
        p
      ), i.produce(r, p[0].end), r = r.pop(), !_) {
        r = r.safePop(), i.produce(r, o), l = !0;
        return;
      }
    }
    p[0].end > n && (n = p[0].end, s = !1);
  }
}
function Ve(t, e, s, n, r, i) {
  let a = r.beginRuleCapturedEOL ? 0 : -1;
  const c = [];
  for (let o = r; o; o = o.pop()) {
    const l = o.getRule(t);
    l instanceof j && c.push({
      rule: l,
      stack: o
    });
  }
  for (let o = c.pop(); o; o = c.pop()) {
    const { ruleScanner: l, findOptions: h } = et(o.rule, t, o.stack.endRule, s, n === a), u = l.findNextMatchSync(e, n, h);
    if (u) {
      if (u.ruleId !== ge) {
        r = o.stack.pop();
        break;
      }
      u.captureIndices && u.captureIndices.length && (i.produce(o.stack, u.captureIndices[0].start), P(t, e, s, o.stack, i, o.rule.whileCaptures, u.captureIndices), i.produce(o.stack, u.captureIndices[0].end), a = u.captureIndices[0].end, u.captureIndices[0].end > n && (n = u.captureIndices[0].end, s = !1));
    } else {
      r = o.stack.pop();
      break;
    }
  }
  return { stack: r, linePos: n, anchorPosition: a, isFirstLine: s };
}
function Je(t, e, s, n, r, i) {
  const a = Ye(t, e, s, n, r, i), c = t.getInjections();
  if (c.length === 0)
    return a;
  const o = Ze(c, t, e, s, n, r, i);
  if (!o)
    return a;
  if (!a)
    return o;
  const l = a.captureIndices[0].start, h = o.captureIndices[0].start;
  return h < l || o.priorityMatch && h === l ? o : a;
}
function Ye(t, e, s, n, r, i) {
  const a = r.getRule(t), { ruleScanner: c, findOptions: o } = ye(a, t, r.endRule, s, n === i), l = c.findNextMatchSync(e, n, o);
  return l ? {
    captureIndices: l.captureIndices,
    matchedRuleId: l.ruleId
  } : null;
}
function Ze(t, e, s, n, r, i, a) {
  let c = Number.MAX_VALUE, o = null, l, h = 0;
  const u = i.contentNameScopesList.getScopeNames();
  for (let f = 0, d = t.length; f < d; f++) {
    const p = t[f];
    if (!p.matcher(u))
      continue;
    const S = e.getRule(p.ruleId), { ruleScanner: _, findOptions: R } = ye(S, e, null, n, r === a), g = _.findNextMatchSync(s, r, R);
    if (!g)
      continue;
    const A = g.captureIndices[0].start;
    if (!(A >= c) && (c = A, o = g.captureIndices, l = g.ruleId, h = p.priority, c === r))
      break;
  }
  return o ? {
    priorityMatch: h === -1,
    captureIndices: o,
    matchedRuleId: l
  } : null;
}
function ye(t, e, s, n, r) {
  return {
    ruleScanner: t.compileAG(e, s, n, r),
    findOptions: 0
    /* None */
  };
}
function et(t, e, s, n, r) {
  return {
    ruleScanner: t.compileWhileAG(e, s, n, r),
    findOptions: 0
    /* None */
  };
}
function P(t, e, s, n, r, i, a) {
  if (i.length === 0)
    return;
  const c = e.content, o = Math.min(i.length, a.length), l = [], h = a[0].end;
  for (let u = 0; u < o; u++) {
    const f = i[u];
    if (f === null)
      continue;
    const d = a[u];
    if (d.length === 0)
      continue;
    if (d.start > h)
      break;
    for (; l.length > 0 && l[l.length - 1].endPos <= d.start; )
      r.produceFromScopes(l[l.length - 1].scopes, l[l.length - 1].endPos), l.pop();
    if (l.length > 0 ? r.produceFromScopes(l[l.length - 1].scopes, d.start) : r.produce(n, d.start), f.retokenizeCapturedWithRuleId) {
      const S = f.getName(c, a), _ = n.contentNameScopesList.pushAttributed(S, t), R = f.getContentName(c, a), g = _.pushAttributed(R, t), A = n.push(f.retokenizeCapturedWithRuleId, d.start, -1, !1, null, _, g), I = t.createOnigString(c.substring(0, d.end));
      Se(
        t,
        I,
        s && d.start === 0,
        d.start,
        A,
        r,
        !1,
        /* no time limit */
        0
      ), me(I);
      continue;
    }
    const p = f.getName(c, a);
    if (p !== null) {
      const _ = (l.length > 0 ? l[l.length - 1].scopes : n.contentNameScopesList).pushAttributed(p, t);
      l.push(new tt(_, d.end));
    }
  }
  for (; l.length > 0; )
    r.produceFromScopes(l[l.length - 1].scopes, l[l.length - 1].endPos), l.pop();
}
var tt = class {
  scopes;
  endPos;
  constructor(t, e) {
    this.scopes = t, this.endPos = e;
  }
};
function st(t, e, s, n, r, i, a, c) {
  return new rt(
    t,
    e,
    s,
    n,
    r,
    i,
    a,
    c
  );
}
function ie(t, e, s, n, r) {
  const i = x(e, $), a = Re.getCompiledRuleId(s, n, r.repository);
  for (const c of i)
    t.push({
      debugSelector: e,
      matcher: c.matcher,
      ruleId: a,
      grammar: r,
      priority: c.priority
    });
}
function $(t, e) {
  if (e.length < t.length)
    return !1;
  let s = 0;
  return t.every((n) => {
    for (let r = s; r < e.length; r++)
      if (nt(e[r], n))
        return s = r + 1, !0;
    return !1;
  });
}
function nt(t, e) {
  if (!t)
    return !1;
  if (t === e)
    return !0;
  const s = e.length;
  return t.length > s && t.substr(0, s) === e && t[s] === ".";
}
var rt = class {
  constructor(t, e, s, n, r, i, a, c) {
    if (this._rootScopeName = t, this.balancedBracketSelectors = i, this._onigLib = c, this._basicScopeAttributesProvider = new Qe(
      s,
      n
    ), this._rootId = -1, this._lastRuleId = 0, this._ruleId2desc = [null], this._includedGrammars = {}, this._grammarRepository = a, this._grammar = oe(e, null), this._injections = null, this._tokenTypeMatchers = [], r)
      for (const o of Object.keys(r)) {
        const l = x(o, $);
        for (const h of l)
          this._tokenTypeMatchers.push({
            matcher: h.matcher,
            type: r[o]
          });
      }
  }
  _rootId;
  _lastRuleId;
  _ruleId2desc;
  _includedGrammars;
  _grammarRepository;
  _grammar;
  _injections;
  _basicScopeAttributesProvider;
  _tokenTypeMatchers;
  get themeProvider() {
    return this._grammarRepository;
  }
  dispose() {
    for (const t of this._ruleId2desc)
      t && t.dispose();
  }
  createOnigScanner(t) {
    return this._onigLib.createOnigScanner(t);
  }
  createOnigString(t) {
    return this._onigLib.createOnigString(t);
  }
  getMetadataForScope(t) {
    return this._basicScopeAttributesProvider.getBasicScopeAttributes(t);
  }
  _collectInjections() {
    const t = {
      lookup: (r) => r === this._rootScopeName ? this._grammar : this.getExternalGrammar(r),
      injections: (r) => this._grammarRepository.injections(r)
    }, e = [], s = this._rootScopeName, n = t.lookup(s);
    if (n) {
      const r = n.injections;
      if (r)
        for (let a in r)
          ie(
            e,
            a,
            r[a],
            this,
            n
          );
      const i = this._grammarRepository.injections(s);
      i && i.forEach((a) => {
        const c = this.getExternalGrammar(a);
        if (c) {
          const o = c.injectionSelector;
          o && ie(
            e,
            o,
            c,
            this,
            c
          );
        }
      });
    }
    return e.sort((r, i) => r.priority - i.priority), e;
  }
  getInjections() {
    return this._injections === null && (this._injections = this._collectInjections()), this._injections;
  }
  registerRule(t) {
    const e = ++this._lastRuleId, s = t(e);
    return this._ruleId2desc[e] = s, s;
  }
  getRule(t) {
    return this._ruleId2desc[t];
  }
  getExternalGrammar(t, e) {
    if (this._includedGrammars[t])
      return this._includedGrammars[t];
    if (this._grammarRepository) {
      const s = this._grammarRepository.lookup(t);
      if (s)
        return this._includedGrammars[t] = oe(
          s,
          e && e.$base
        ), this._includedGrammars[t];
    }
  }
  tokenizeLine(t, e, s = 0) {
    const n = this._tokenize(t, e, !1, s);
    return {
      tokens: n.lineTokens.getResult(n.ruleStack, n.lineLength),
      ruleStack: n.ruleStack,
      stoppedEarly: n.stoppedEarly
    };
  }
  tokenizeLine2(t, e, s = 0) {
    const n = this._tokenize(t, e, !0, s);
    return {
      tokens: n.lineTokens.getBinaryResult(n.ruleStack, n.lineLength),
      ruleStack: n.ruleStack,
      stoppedEarly: n.stoppedEarly
    };
  }
  _tokenize(t, e, s, n) {
    this._rootId === -1 && (this._rootId = Re.getCompiledRuleId(
      this._grammar.repository.$self,
      this,
      this._grammar.repository
    ), this.getInjections());
    let r;
    if (!e || e === J.NULL) {
      r = !0;
      const l = this._basicScopeAttributesProvider.getDefaultAttributes(), h = this.themeProvider.getDefaults(), u = M.set(
        0,
        l.languageId,
        l.tokenType,
        null,
        h.fontStyle,
        h.foregroundId,
        h.backgroundId
      ), f = this.getRule(this._rootId).getName(
        null,
        null
      );
      let d;
      f ? d = k.createRootAndLookUpScopeName(
        f,
        u,
        this
      ) : d = k.createRoot(
        "unknown",
        u
      ), e = new J(
        null,
        this._rootId,
        -1,
        -1,
        !1,
        null,
        d,
        d
      );
    } else
      r = !1, e.reset();
    t = t + `
`;
    const i = this.createOnigString(t), a = i.content.length, c = new ot(
      s,
      t,
      this._tokenTypeMatchers,
      this.balancedBracketSelectors
    ), o = Se(
      this,
      i,
      r,
      0,
      e,
      c,
      !0,
      n
    );
    return me(i), {
      lineLength: a,
      lineTokens: c,
      ruleStack: o.stack,
      stoppedEarly: o.stoppedEarly
    };
  }
};
function oe(t, e) {
  return t = we(t), t.repository = t.repository || {}, t.repository.$self = {
    $vscodeTextmateLocation: t.$vscodeTextmateLocation,
    patterns: t.patterns,
    name: t.scopeName
  }, t.repository.$base = e || t.repository.$self, t;
}
var k = class w {
  /**
   * Invariant:
   * ```
   * if (parent && !scopePath.extends(parent.scopePath)) {
   * 	throw new Error();
   * }
   * ```
   */
  constructor(e, s, n) {
    this.parent = e, this.scopePath = s, this.tokenAttributes = n;
  }
  static fromExtension(e, s) {
    let n = e, r = e?.scopePath ?? null;
    for (const i of s)
      r = z.push(r, i.scopeNames), n = new w(n, r, i.encodedTokenAttributes);
    return n;
  }
  static createRoot(e, s) {
    return new w(null, new z(null, e), s);
  }
  static createRootAndLookUpScopeName(e, s, n) {
    const r = n.getMetadataForScope(e), i = new z(null, e), a = n.themeProvider.themeMatch(i), c = w.mergeAttributes(
      s,
      r,
      a
    );
    return new w(null, i, c);
  }
  get scopeName() {
    return this.scopePath.scopeName;
  }
  toString() {
    return this.getScopeNames().join(" ");
  }
  equals(e) {
    return w.equals(this, e);
  }
  static equals(e, s) {
    do {
      if (e === s || !e && !s)
        return !0;
      if (!e || !s || e.scopeName !== s.scopeName || e.tokenAttributes !== s.tokenAttributes)
        return !1;
      e = e.parent, s = s.parent;
    } while (!0);
  }
  static mergeAttributes(e, s, n) {
    let r = -1, i = 0, a = 0;
    return n !== null && (r = n.fontStyle, i = n.foregroundId, a = n.backgroundId), M.set(
      e,
      s.languageId,
      s.tokenType,
      null,
      r,
      i,
      a
    );
  }
  pushAttributed(e, s) {
    if (e === null)
      return this;
    if (e.indexOf(" ") === -1)
      return w._pushAttributed(this, e, s);
    const n = e.split(/ /g);
    let r = this;
    for (const i of n)
      r = w._pushAttributed(r, i, s);
    return r;
  }
  static _pushAttributed(e, s, n) {
    const r = n.getMetadataForScope(s), i = e.scopePath.push(s), a = n.themeProvider.themeMatch(i), c = w.mergeAttributes(
      e.tokenAttributes,
      r,
      a
    );
    return new w(e, i, c);
  }
  getScopeNames() {
    return this.scopePath.getSegments();
  }
  getExtensionIfDefined(e) {
    const s = [];
    let n = this;
    for (; n && n !== e; )
      s.push({
        encodedTokenAttributes: n.tokenAttributes,
        scopeNames: n.scopePath.getExtensionIfDefined(n.parent?.scopePath ?? null)
      }), n = n.parent;
    return n === e ? s.reverse() : void 0;
  }
}, J = class b {
  /**
   * Invariant:
   * ```
   * if (contentNameScopesList !== nameScopesList && contentNameScopesList?.parent !== nameScopesList) {
   * 	throw new Error();
   * }
   * if (this.parent && !nameScopesList.extends(this.parent.contentNameScopesList)) {
   * 	throw new Error();
   * }
   * ```
   */
  constructor(e, s, n, r, i, a, c, o) {
    this.parent = e, this.ruleId = s, this.beginRuleCapturedEOL = i, this.endRule = a, this.nameScopesList = c, this.contentNameScopesList = o, this.depth = this.parent ? this.parent.depth + 1 : 1, this._enterPos = n, this._anchorPos = r;
  }
  _stackElementBrand = void 0;
  // TODO remove me
  static NULL = new b(
    null,
    0,
    0,
    0,
    !1,
    null,
    null,
    null
  );
  /**
   * The position on the current line where this state was pushed.
   * This is relevant only while tokenizing a line, to detect endless loops.
   * Its value is meaningless across lines.
   */
  _enterPos;
  /**
   * The captured anchor position when this stack element was pushed.
   * This is relevant only while tokenizing a line, to restore the anchor position when popping.
   * Its value is meaningless across lines.
   */
  _anchorPos;
  /**
   * The depth of the stack.
   */
  depth;
  equals(e) {
    return e === null ? !1 : b._equals(this, e);
  }
  static _equals(e, s) {
    return e === s ? !0 : this._structuralEquals(e, s) ? k.equals(e.contentNameScopesList, s.contentNameScopesList) : !1;
  }
  /**
   * A structural equals check. Does not take into account `scopes`.
   */
  static _structuralEquals(e, s) {
    do {
      if (e === s || !e && !s)
        return !0;
      if (!e || !s || e.depth !== s.depth || e.ruleId !== s.ruleId || e.endRule !== s.endRule)
        return !1;
      e = e.parent, s = s.parent;
    } while (!0);
  }
  clone() {
    return this;
  }
  static _reset(e) {
    for (; e; )
      e._enterPos = -1, e._anchorPos = -1, e = e.parent;
  }
  reset() {
    b._reset(this);
  }
  pop() {
    return this.parent;
  }
  safePop() {
    return this.parent ? this.parent : this;
  }
  push(e, s, n, r, i, a, c) {
    return new b(
      this,
      e,
      s,
      n,
      r,
      i,
      a,
      c
    );
  }
  getEnterPos() {
    return this._enterPos;
  }
  getAnchorPos() {
    return this._anchorPos;
  }
  getRule(e) {
    return e.getRule(this.ruleId);
  }
  toString() {
    const e = [];
    return this._writeString(e, 0), "[" + e.join(",") + "]";
  }
  _writeString(e, s) {
    return this.parent && (s = this.parent._writeString(e, s)), e[s++] = `(${this.ruleId}, ${this.nameScopesList?.toString()}, ${this.contentNameScopesList?.toString()})`, s;
  }
  withContentNameScopesList(e) {
    return this.contentNameScopesList === e ? this : this.parent.push(
      this.ruleId,
      this._enterPos,
      this._anchorPos,
      this.beginRuleCapturedEOL,
      this.endRule,
      this.nameScopesList,
      e
    );
  }
  withEndRule(e) {
    return this.endRule === e ? this : new b(
      this.parent,
      this.ruleId,
      this._enterPos,
      this._anchorPos,
      this.beginRuleCapturedEOL,
      e,
      this.nameScopesList,
      this.contentNameScopesList
    );
  }
  // Used to warn of endless loops
  hasSameRuleAs(e) {
    let s = this;
    for (; s && s._enterPos === e._enterPos; ) {
      if (s.ruleId === e.ruleId)
        return !0;
      s = s.parent;
    }
    return !1;
  }
  toStateStackFrame() {
    return {
      ruleId: this.ruleId,
      beginRuleCapturedEOL: this.beginRuleCapturedEOL,
      endRule: this.endRule,
      nameScopesList: this.nameScopesList?.getExtensionIfDefined(this.parent?.nameScopesList ?? null) ?? [],
      contentNameScopesList: this.contentNameScopesList?.getExtensionIfDefined(this.nameScopesList) ?? []
    };
  }
  static pushFrame(e, s) {
    const n = k.fromExtension(e?.nameScopesList ?? null, s.nameScopesList);
    return new b(
      e,
      s.ruleId,
      s.enterPos ?? -1,
      s.anchorPos ?? -1,
      s.beginRuleCapturedEOL,
      s.endRule,
      n,
      k.fromExtension(n, s.contentNameScopesList)
    );
  }
}, it = class {
  balancedBracketScopes;
  unbalancedBracketScopes;
  allowAny = !1;
  constructor(t, e) {
    this.balancedBracketScopes = t.flatMap(
      (s) => s === "*" ? (this.allowAny = !0, []) : x(s, $).map((n) => n.matcher)
    ), this.unbalancedBracketScopes = e.flatMap(
      (s) => x(s, $).map((n) => n.matcher)
    );
  }
  get matchesAlways() {
    return this.allowAny && this.unbalancedBracketScopes.length === 0;
  }
  get matchesNever() {
    return this.balancedBracketScopes.length === 0 && !this.allowAny;
  }
  match(t) {
    for (const e of this.unbalancedBracketScopes)
      if (e(t))
        return !1;
    for (const e of this.balancedBracketScopes)
      if (e(t))
        return !0;
    return this.allowAny;
  }
}, ot = class {
  constructor(t, e, s, n) {
    this.balancedBracketSelectors = n, this._emitBinaryTokens = t, this._tokenTypeOverrides = s, this._lineText = null, this._tokens = [], this._binaryTokens = [], this._lastTokenEndIndex = 0;
  }
  _emitBinaryTokens;
  /**
   * defined only if `false`.
   */
  _lineText;
  /**
   * used only if `_emitBinaryTokens` is false.
   */
  _tokens;
  /**
   * used only if `_emitBinaryTokens` is true.
   */
  _binaryTokens;
  _lastTokenEndIndex;
  _tokenTypeOverrides;
  produce(t, e) {
    this.produceFromScopes(t.contentNameScopesList, e);
  }
  produceFromScopes(t, e) {
    if (this._lastTokenEndIndex >= e)
      return;
    if (this._emitBinaryTokens) {
      let n = t?.tokenAttributes ?? 0, r = !1;
      if (this.balancedBracketSelectors?.matchesAlways && (r = !0), this._tokenTypeOverrides.length > 0 || this.balancedBracketSelectors && !this.balancedBracketSelectors.matchesAlways && !this.balancedBracketSelectors.matchesNever) {
        const i = t?.getScopeNames() ?? [];
        for (const a of this._tokenTypeOverrides)
          a.matcher(i) && (n = M.set(
            n,
            0,
            a.type,
            null,
            -1,
            0,
            0
          ));
        this.balancedBracketSelectors && (r = this.balancedBracketSelectors.match(i));
      }
      if (r && (n = M.set(
        n,
        0,
        8,
        r,
        -1,
        0,
        0
      )), this._binaryTokens.length > 0 && this._binaryTokens[this._binaryTokens.length - 1] === n) {
        this._lastTokenEndIndex = e;
        return;
      }
      this._binaryTokens.push(this._lastTokenEndIndex), this._binaryTokens.push(n), this._lastTokenEndIndex = e;
      return;
    }
    const s = t?.getScopeNames() ?? [];
    this._tokens.push({
      startIndex: this._lastTokenEndIndex,
      endIndex: e,
      // value: lineText.substring(lastTokenEndIndex, endIndex),
      scopes: s
    }), this._lastTokenEndIndex = e;
  }
  getResult(t, e) {
    return this._tokens.length > 0 && this._tokens[this._tokens.length - 1].startIndex === e - 1 && this._tokens.pop(), this._tokens.length === 0 && (this._lastTokenEndIndex = -1, this.produce(t, e), this._tokens[this._tokens.length - 1].startIndex = 0), this._tokens;
  }
  getBinaryResult(t, e) {
    this._binaryTokens.length > 0 && this._binaryTokens[this._binaryTokens.length - 2] === e - 1 && (this._binaryTokens.pop(), this._binaryTokens.pop()), this._binaryTokens.length === 0 && (this._lastTokenEndIndex = -1, this.produce(t, e), this._binaryTokens[this._binaryTokens.length - 2] = 0);
    const s = new Uint32Array(this._binaryTokens.length);
    for (let n = 0, r = this._binaryTokens.length; n < r; n++)
      s[n] = this._binaryTokens[n];
    return s;
  }
}, at = class {
  constructor(t, e) {
    this._onigLib = e, this._theme = t;
  }
  _grammars = /* @__PURE__ */ new Map();
  _rawGrammars = /* @__PURE__ */ new Map();
  _injectionGrammars = /* @__PURE__ */ new Map();
  _theme;
  dispose() {
    for (const t of this._grammars.values())
      t.dispose();
  }
  setTheme(t) {
    this._theme = t;
  }
  getColorMap() {
    return this._theme.getColorMap();
  }
  /**
   * Add `grammar` to registry and return a list of referenced scope names
   */
  addGrammar(t, e) {
    this._rawGrammars.set(t.scopeName, t), e && this._injectionGrammars.set(t.scopeName, e);
  }
  /**
   * Lookup a raw grammar.
   */
  lookup(t) {
    return this._rawGrammars.get(t);
  }
  /**
   * Returns the injections for the given grammar
   */
  injections(t) {
    return this._injectionGrammars.get(t);
  }
  /**
   * Get the default theme settings
   */
  getDefaults() {
    return this._theme.getDefaults();
  }
  /**
   * Match a scope in the theme.
   */
  themeMatch(t) {
    return this._theme.match(t);
  }
  /**
   * Lookup a grammar.
   */
  grammarForScopeName(t, e, s, n, r) {
    if (!this._grammars.has(t)) {
      let i = this._rawGrammars.get(t);
      if (!i)
        return null;
      this._grammars.set(t, st(
        t,
        i,
        e,
        s,
        n,
        r,
        this,
        this._onigLib
      ));
    }
    return this._grammars.get(t);
  }
}, ct = class {
  _options;
  _syncRegistry;
  _ensureGrammarCache;
  constructor(e) {
    this._options = e, this._syncRegistry = new at(
      U.createFromRawTheme(e.theme, e.colorMap),
      e.onigLib
    ), this._ensureGrammarCache = /* @__PURE__ */ new Map();
  }
  dispose() {
    this._syncRegistry.dispose();
  }
  /**
   * Change the theme. Once called, no previous `ruleStack` should be used anymore.
   */
  setTheme(e, s) {
    this._syncRegistry.setTheme(U.createFromRawTheme(e, s));
  }
  /**
   * Returns a lookup array for color ids.
   */
  getColorMap() {
    return this._syncRegistry.getColorMap();
  }
  /**
   * Load the grammar for `scopeName` and all referenced included grammars asynchronously.
   * Please do not use language id 0.
   */
  loadGrammarWithEmbeddedLanguages(e, s, n) {
    return this.loadGrammarWithConfiguration(e, s, { embeddedLanguages: n });
  }
  /**
   * Load the grammar for `scopeName` and all referenced included grammars asynchronously.
   * Please do not use language id 0.
   */
  loadGrammarWithConfiguration(e, s, n) {
    return this._loadGrammar(
      e,
      s,
      n.embeddedLanguages,
      n.tokenTypes,
      new it(
        n.balancedBracketSelectors || [],
        n.unbalancedBracketSelectors || []
      )
    );
  }
  /**
   * Load the grammar for `scopeName` and all referenced included grammars asynchronously.
   */
  loadGrammar(e) {
    return this._loadGrammar(e, 0, null, null, null);
  }
  _loadGrammar(e, s, n, r, i) {
    const a = new Oe(this._syncRegistry, e);
    for (; a.Q.length > 0; )
      a.Q.map((c) => this._loadSingleGrammar(c.scopeName)), a.processQueue();
    return this._grammarForScopeName(
      e,
      s,
      n,
      r,
      i
    );
  }
  _loadSingleGrammar(e) {
    this._ensureGrammarCache.has(e) || (this._doLoadSingleGrammar(e), this._ensureGrammarCache.set(e, !0));
  }
  _doLoadSingleGrammar(e) {
    const s = this._options.loadGrammar(e);
    if (s) {
      const n = typeof this._options.getInjections == "function" ? this._options.getInjections(e) : void 0;
      this._syncRegistry.addGrammar(s, n);
    }
  }
  /**
   * Adds a rawGrammar.
   */
  addGrammar(e, s = [], n = 0, r = null) {
    return this._syncRegistry.addGrammar(e, s), this._grammarForScopeName(e.scopeName, n, r);
  }
  /**
   * Get the grammar for `scopeName`. The grammar must first be created via `loadGrammar` or `addGrammar`.
   */
  _grammarForScopeName(e, s = 0, n = null, r = null, i = null) {
    return this._syncRegistry.grammarForScopeName(
      e,
      s,
      n,
      r,
      i
    );
  }
}, ht = J.NULL;
export {
  M as EncodedTokenMetadata,
  ve as FontStyle,
  ht as INITIAL,
  ct as Registry,
  U as Theme,
  me as disposeOnigString
};
