@onereach/ui-components 4.0.2 → 4.1.0-beta.2508.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. package/dist/bundled/v2/components/OrCode/OrCode.js +6 -3727
  2. package/dist/bundled/v2/components/OrCode/index.js +6 -2
  3. package/dist/bundled/v2/components/OrCode/lang.js +3898 -3
  4. package/dist/bundled/v2/components/OrCode/theme.js +3 -1
  5. package/dist/bundled/v2/components/OrRichTextEditorV3/OrRichTextEditor.js +2033 -0
  6. package/dist/bundled/v2/components/OrRichTextEditorV3/OrRichTextEditor.vue.d.ts +181 -0
  7. package/dist/bundled/v2/components/OrRichTextEditorV3/index.d.ts +1 -0
  8. package/dist/bundled/v2/components/OrRichTextEditorV3/index.js +67 -0
  9. package/dist/bundled/v2/components/OrRichTextEditorV3/styles.d.ts +7 -0
  10. package/dist/bundled/v2/components/OrRichTextEditorV3/styles.js +43 -0
  11. package/dist/bundled/v2/components/OrRichTextEditorV3/utils/codemirror/codemirrorNode.d.ts +3 -0
  12. package/dist/bundled/v2/components/OrRichTextEditorV3/utils/codemirror/codemirrorNode.js +45 -0
  13. package/dist/bundled/v2/components/OrRichTextEditorV3/utils/codemirror/codemirrorView.d.ts +27 -0
  14. package/dist/bundled/v2/components/OrRichTextEditorV3/utils/codemirror/codemirrorView.js +183 -0
  15. package/dist/bundled/v2/components/OrRichTextEditorV3/utils/codemirror/index.d.ts +1 -0
  16. package/dist/bundled/v2/components/OrRichTextEditorV3/utils/codemirror/index.js +4 -0
  17. package/dist/bundled/v2/components/OrRichTextEditorV3/utils/codemirror/types.d.ts +19 -0
  18. package/dist/bundled/v2/components/OrRichTextEditorV3/utils/codemirror/types.js +1 -0
  19. package/dist/bundled/v2/components/OrRichTextEditorV3/utils/markdown.d.ts +3 -0
  20. package/dist/bundled/v2/components/OrRichTextEditorV3/utils/markdown.js +5 -0
  21. package/dist/bundled/v2/components/index.d.ts +1 -0
  22. package/dist/bundled/v2/components/index.js +14 -2
  23. package/dist/bundled/v2/index-62c3221b.js +6956 -0
  24. package/dist/bundled/v2/index-62e39ec2.js +4534 -0
  25. package/dist/bundled/{v3/OrCode.vue_vue_type_script_lang-c5a9adb7.js → v2/index-92e69736.js} +15 -234
  26. package/dist/bundled/v2/{index-6976c52a.js → index-c76372bb.js} +16 -4659
  27. package/dist/bundled/{v3/lang-02d2bb2d.js → v2/index-db5e8c99.js} +74 -3965
  28. package/dist/bundled/v2/index.es-3f39f316.js +115 -0
  29. package/dist/bundled/v2/index.js +17 -5
  30. package/dist/bundled/v2/markdown-00716a39.js +18683 -0
  31. package/dist/bundled/v2/tiptap-core.esm-f85402b1.js +9360 -0
  32. package/dist/bundled/v3/OrCode.vue_vue_type_script_lang-0c5e41b0.js +236 -0
  33. package/dist/bundled/v3/OrRichTextEditor.vue_vue_type_script_lang-33b56bd6.js +1815 -0
  34. package/dist/bundled/v3/components/OrCode/OrCode.js +9 -5
  35. package/dist/bundled/v3/components/OrCode/index.js +7 -3
  36. package/dist/bundled/v3/components/OrCode/lang.js +3898 -3
  37. package/dist/bundled/v3/components/OrCode/theme.js +3 -1
  38. package/dist/bundled/v3/components/OrRichTextEditorV3/OrRichTextEditor.js +219 -0
  39. package/dist/bundled/v3/components/OrRichTextEditorV3/OrRichTextEditor.vue.d.ts +181 -0
  40. package/dist/bundled/v3/components/OrRichTextEditorV3/index.d.ts +1 -0
  41. package/dist/bundled/v3/components/OrRichTextEditorV3/index.js +83 -0
  42. package/dist/bundled/v3/components/OrRichTextEditorV3/styles.d.ts +7 -0
  43. package/dist/bundled/v3/components/OrRichTextEditorV3/styles.js +43 -0
  44. package/dist/bundled/v3/components/OrRichTextEditorV3/utils/codemirror/codemirrorNode.d.ts +3 -0
  45. package/dist/bundled/v3/components/OrRichTextEditorV3/utils/codemirror/codemirrorNode.js +45 -0
  46. package/dist/bundled/v3/components/OrRichTextEditorV3/utils/codemirror/codemirrorView.d.ts +27 -0
  47. package/dist/bundled/v3/components/OrRichTextEditorV3/utils/codemirror/codemirrorView.js +183 -0
  48. package/dist/bundled/v3/components/OrRichTextEditorV3/utils/codemirror/index.d.ts +1 -0
  49. package/dist/bundled/v3/components/OrRichTextEditorV3/utils/codemirror/index.js +4 -0
  50. package/dist/bundled/v3/components/OrRichTextEditorV3/utils/codemirror/types.d.ts +19 -0
  51. package/dist/bundled/v3/components/OrRichTextEditorV3/utils/codemirror/types.js +1 -0
  52. package/dist/bundled/v3/components/OrRichTextEditorV3/utils/markdown.d.ts +3 -0
  53. package/dist/bundled/v3/components/OrRichTextEditorV3/utils/markdown.js +5 -0
  54. package/dist/bundled/v3/components/index.d.ts +1 -0
  55. package/dist/bundled/v3/components/index.js +16 -3
  56. package/dist/bundled/v3/index-62c3221b.js +6956 -0
  57. package/dist/bundled/v3/index-62e39ec2.js +4534 -0
  58. package/dist/bundled/v3/index-92e69736.js +3741 -0
  59. package/dist/bundled/v3/{index-6976c52a.js → index-c76372bb.js} +16 -4659
  60. package/dist/bundled/{v2/lang-02d2bb2d.js → v3/index-db5e8c99.js} +74 -3965
  61. package/dist/bundled/v3/index.es-3f39f316.js +115 -0
  62. package/dist/bundled/v3/index.js +20 -7
  63. package/dist/bundled/v3/markdown-00716a39.js +18683 -0
  64. package/dist/bundled/v3/tiptap-core.esm-f85402b1.js +9360 -0
  65. package/dist/esm/v2/OrRichTextEditor-45fb1867.js +718 -0
  66. package/dist/esm/v2/codemirrorView-2e87c938.js +184 -0
  67. package/dist/esm/v2/components/index.d.ts +1 -0
  68. package/dist/esm/v2/components/index.js +24 -0
  69. package/dist/esm/v2/components/or-rich-text-editor-v3/OrRichTextEditor.vue.d.ts +181 -0
  70. package/dist/esm/v2/components/or-rich-text-editor-v3/index.d.ts +1 -0
  71. package/dist/esm/v2/components/or-rich-text-editor-v3/index.js +56 -0
  72. package/dist/esm/v2/components/or-rich-text-editor-v3/styles.d.ts +7 -0
  73. package/dist/esm/v2/components/or-rich-text-editor-v3/utils/codemirror/codemirrorNode.d.ts +3 -0
  74. package/dist/esm/v2/components/or-rich-text-editor-v3/utils/codemirror/codemirrorView.d.ts +27 -0
  75. package/dist/esm/v2/components/or-rich-text-editor-v3/utils/codemirror/index.d.ts +1 -0
  76. package/dist/esm/v2/components/or-rich-text-editor-v3/utils/codemirror/index.js +5 -0
  77. package/dist/esm/v2/components/or-rich-text-editor-v3/utils/codemirror/types.d.ts +19 -0
  78. package/dist/esm/v2/components/or-rich-text-editor-v3/utils/markdown.d.ts +3 -0
  79. package/dist/esm/v2/index.js +24 -0
  80. package/dist/esm/v3/OrRichTextEditor-4c0b6030.js +680 -0
  81. package/dist/esm/v3/codemirrorView-2e87c938.js +184 -0
  82. package/dist/esm/v3/components/index.d.ts +1 -0
  83. package/dist/esm/v3/components/index.js +24 -0
  84. package/dist/esm/v3/components/or-rich-text-editor-v3/OrRichTextEditor.vue.d.ts +181 -0
  85. package/dist/esm/v3/components/or-rich-text-editor-v3/index.d.ts +1 -0
  86. package/dist/esm/v3/components/or-rich-text-editor-v3/index.js +54 -0
  87. package/dist/esm/v3/components/or-rich-text-editor-v3/styles.d.ts +7 -0
  88. package/dist/esm/v3/components/or-rich-text-editor-v3/utils/codemirror/codemirrorNode.d.ts +3 -0
  89. package/dist/esm/v3/components/or-rich-text-editor-v3/utils/codemirror/codemirrorView.d.ts +27 -0
  90. package/dist/esm/v3/components/or-rich-text-editor-v3/utils/codemirror/index.d.ts +1 -0
  91. package/dist/esm/v3/components/or-rich-text-editor-v3/utils/codemirror/index.js +5 -0
  92. package/dist/esm/v3/components/or-rich-text-editor-v3/utils/codemirror/types.d.ts +19 -0
  93. package/dist/esm/v3/components/or-rich-text-editor-v3/utils/markdown.d.ts +3 -0
  94. package/dist/esm/v3/index.js +24 -0
  95. package/package.json +25 -5
  96. package/src/components/index.ts +1 -0
  97. package/src/components/or-rich-text-editor-v3/OrRichTextEditor.docs.mdx +7 -0
  98. package/src/components/or-rich-text-editor-v3/OrRichTextEditor.stories3.ts +79 -0
  99. package/src/components/or-rich-text-editor-v3/OrRichTextEditor.vue +622 -0
  100. package/src/components/or-rich-text-editor-v3/index.ts +1 -0
  101. package/src/components/or-rich-text-editor-v3/styles.ts +72 -0
  102. package/src/components/or-rich-text-editor-v3/utils/codemirror/codemirrorNode.ts +40 -0
  103. package/src/components/or-rich-text-editor-v3/utils/codemirror/codemirrorView.ts +252 -0
  104. package/src/components/or-rich-text-editor-v3/utils/codemirror/index.ts +1 -0
  105. package/src/components/or-rich-text-editor-v3/utils/codemirror/types.ts +22 -0
  106. package/src/components/or-rich-text-editor-v3/utils/markdown.ts +110 -0
@@ -1,3 +1,5 @@
1
+ import { k as keyName, b as base, s as shift } from './index.es-3f39f316.js';
2
+
1
3
  /**
2
4
  The data structure for documents. @nonabstract
3
5
  */
@@ -1541,7 +1543,7 @@ class Facet {
1541
1543
  Define a new facet.
1542
1544
  */
1543
1545
  static define(config = {}) {
1544
- return new Facet(config.combine || (a => a), config.compareInput || ((a, b) => a === b), config.compare || (!config.combine ? sameArray$1 : (a, b) => a === b), !!config.static, config.enables);
1546
+ return new Facet(config.combine || (a => a), config.compareInput || ((a, b) => a === b), config.compare || (!config.combine ? sameArray : (a, b) => a === b), !!config.static, config.enables);
1545
1547
  }
1546
1548
  /**
1547
1549
  Returns an extension that adds the given value to this facet.
@@ -1575,7 +1577,7 @@ class Facet {
1575
1577
  return this.compute([field], state => get(state.field(field)));
1576
1578
  }
1577
1579
  }
1578
- function sameArray$1(a, b) {
1580
+ function sameArray(a, b) {
1579
1581
  return a == b || a.length == b.length && a.every((e, i) => e === b[i]);
1580
1582
  }
1581
1583
  class FacetProvider {
@@ -1679,7 +1681,7 @@ function dynamicFacetSlot(addresses, facet, providers) {
1679
1681
  let depChanged = ensureAll(state, providerAddrs);
1680
1682
  let oldProviders = oldState.config.facets[facet.id],
1681
1683
  oldValue = oldState.facet(facet);
1682
- if (oldProviders && !depChanged && sameArray$1(providers, oldProviders)) {
1684
+ if (oldProviders && !depChanged && sameArray(providers, oldProviders)) {
1683
1685
  state.values[idx] = oldValue;
1684
1686
  return 0;
1685
1687
  }
@@ -1910,7 +1912,7 @@ class Configuration {
1910
1912
  let oldProviders = oldFacets && oldFacets[id] || [];
1911
1913
  if (providers.every(p => p.type == 0 /* Provider.Static */)) {
1912
1914
  address[facet.id] = staticValues.length << 1 | 1;
1913
- if (sameArray$1(oldProviders, providers)) {
1915
+ if (sameArray(oldProviders, providers)) {
1914
1916
  staticValues.push(oldState.facet(facet));
1915
1917
  } else {
1916
1918
  let value = facet.combine(providers.map(p => p.value));
@@ -2949,7 +2951,7 @@ class RangeValue {
2949
2951
  Create a [range](https://codemirror.net/6/docs/ref/#state.Range) with this value.
2950
2952
  */
2951
2953
  range(from, to = from) {
2952
- return Range$1.create(from, to, this);
2954
+ return Range.create(from, to, this);
2953
2955
  }
2954
2956
  }
2955
2957
  RangeValue.prototype.startSide = RangeValue.prototype.endSide = 0;
@@ -2958,7 +2960,7 @@ RangeValue.prototype.mapMode = MapMode.TrackDel;
2958
2960
  /**
2959
2961
  A range associates a value with a range of positions.
2960
2962
  */
2961
- class Range$1 {
2963
+ class Range {
2962
2964
  constructor(
2963
2965
  /**
2964
2966
  The range's start position.
@@ -2980,7 +2982,7 @@ class Range$1 {
2980
2982
  @internal
2981
2983
  */
2982
2984
  static create(from, to, value) {
2983
- return new Range$1(from, to, value);
2985
+ return new Range(from, to, value);
2984
2986
  }
2985
2987
  }
2986
2988
  function cmpRange(a, b) {
@@ -3143,7 +3145,7 @@ class RangeSet {
3143
3145
  cur.nextChunk();
3144
3146
  } else {
3145
3147
  if (!filter || filterFrom > cur.to || filterTo < cur.from || filter(cur.from, cur.to, cur.value)) {
3146
- if (!builder.addInner(cur.from, cur.to, cur.value)) spill.push(Range$1.create(cur.from, cur.to, cur.value));
3148
+ if (!builder.addInner(cur.from, cur.to, cur.value)) spill.push(Range.create(cur.from, cur.to, cur.value));
3147
3149
  }
3148
3150
  cur.next();
3149
3151
  }
@@ -3306,7 +3308,7 @@ class RangeSet {
3306
3308
  */
3307
3309
  static of(ranges, sort = false) {
3308
3310
  let build = new RangeSetBuilder();
3309
- for (let range of ranges instanceof Range$1 ? [ranges] : sort ? lazySort(ranges) : ranges) build.add(range.from, range.to, range.value);
3311
+ for (let range of ranges instanceof Range ? [ranges] : sort ? lazySort(ranges) : ranges) build.add(range.from, range.to, range.value);
3310
3312
  return build.finish();
3311
3313
  }
3312
3314
  }
@@ -3909,120 +3911,6 @@ class StyleSet {
3909
3911
  // example to create a media query you can do `{"@media screen and
3910
3912
  // (min-width: 400px)": {...}}`.
3911
3913
 
3912
- var base = {
3913
- 8: "Backspace",
3914
- 9: "Tab",
3915
- 10: "Enter",
3916
- 12: "NumLock",
3917
- 13: "Enter",
3918
- 16: "Shift",
3919
- 17: "Control",
3920
- 18: "Alt",
3921
- 20: "CapsLock",
3922
- 27: "Escape",
3923
- 32: " ",
3924
- 33: "PageUp",
3925
- 34: "PageDown",
3926
- 35: "End",
3927
- 36: "Home",
3928
- 37: "ArrowLeft",
3929
- 38: "ArrowUp",
3930
- 39: "ArrowRight",
3931
- 40: "ArrowDown",
3932
- 44: "PrintScreen",
3933
- 45: "Insert",
3934
- 46: "Delete",
3935
- 59: ";",
3936
- 61: "=",
3937
- 91: "Meta",
3938
- 92: "Meta",
3939
- 106: "*",
3940
- 107: "+",
3941
- 108: ",",
3942
- 109: "-",
3943
- 110: ".",
3944
- 111: "/",
3945
- 144: "NumLock",
3946
- 145: "ScrollLock",
3947
- 160: "Shift",
3948
- 161: "Shift",
3949
- 162: "Control",
3950
- 163: "Control",
3951
- 164: "Alt",
3952
- 165: "Alt",
3953
- 173: "-",
3954
- 186: ";",
3955
- 187: "=",
3956
- 188: ",",
3957
- 189: "-",
3958
- 190: ".",
3959
- 191: "/",
3960
- 192: "`",
3961
- 219: "[",
3962
- 220: "\\",
3963
- 221: "]",
3964
- 222: "'"
3965
- };
3966
- var shift = {
3967
- 48: ")",
3968
- 49: "!",
3969
- 50: "@",
3970
- 51: "#",
3971
- 52: "$",
3972
- 53: "%",
3973
- 54: "^",
3974
- 55: "&",
3975
- 56: "*",
3976
- 57: "(",
3977
- 59: ":",
3978
- 61: "+",
3979
- 173: "_",
3980
- 186: ":",
3981
- 187: "+",
3982
- 188: "<",
3983
- 189: "_",
3984
- 190: ">",
3985
- 191: "?",
3986
- 192: "~",
3987
- 219: "{",
3988
- 220: "|",
3989
- 221: "}",
3990
- 222: "\""
3991
- };
3992
- var chrome$1 = typeof navigator != "undefined" && /Chrome\/(\d+)/.exec(navigator.userAgent);
3993
- typeof navigator != "undefined" && /Gecko\/\d+/.test(navigator.userAgent);
3994
- var mac = typeof navigator != "undefined" && /Mac/.test(navigator.platform);
3995
- var ie$1 = typeof navigator != "undefined" && /MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);
3996
- var brokenModifierNames = mac || chrome$1 && +chrome$1[1] < 57;
3997
-
3998
- // Fill in the digit keys
3999
- for (var i = 0; i < 10; i++) base[48 + i] = base[96 + i] = String(i);
4000
-
4001
- // The function keys
4002
- for (var i = 1; i <= 24; i++) base[i + 111] = "F" + i;
4003
-
4004
- // And the alphabetic keys
4005
- for (var i = 65; i <= 90; i++) {
4006
- base[i] = String.fromCharCode(i + 32);
4007
- shift[i] = String.fromCharCode(i);
4008
- }
4009
-
4010
- // For each code that doesn't have a shift-equivalent, copy the base name
4011
- for (var code in base) if (!shift.hasOwnProperty(code)) shift[code] = base[code];
4012
- function keyName(event) {
4013
- var ignoreKey = brokenModifierNames && (event.ctrlKey || event.altKey || event.metaKey) || ie$1 && event.shiftKey && event.key && event.key.length == 1 || event.key == "Unidentified";
4014
- var name = !ignoreKey && event.key || (event.shiftKey ? shift : base)[event.keyCode] || event.key || "Unidentified";
4015
- // Edge sometimes produces wrong names (Issue #3)
4016
- if (name == "Esc") name = "Escape";
4017
- if (name == "Del") name = "Delete";
4018
- // https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/8860571/
4019
- if (name == "Left") name = "ArrowLeft";
4020
- if (name == "Up") name = "ArrowUp";
4021
- if (name == "Right") name = "ArrowRight";
4022
- if (name == "Down") name = "ArrowDown";
4023
- return name;
4024
- }
4025
-
4026
3914
  function getSelection(root) {
4027
3915
  let target;
4028
3916
  // Browsers differ on whether shadow roots have a getSelection
@@ -9322,7 +9210,7 @@ function buildTheme(main, spec, scopes) {
9322
9210
  }
9323
9211
  });
9324
9212
  }
9325
- const baseTheme$1$1 = /*@__PURE__*/buildTheme("." + baseThemeID, {
9213
+ const baseTheme$1 = /*@__PURE__*/buildTheme("." + baseThemeID, {
9326
9214
  "&": {
9327
9215
  position: "relative !important",
9328
9216
  boxSizing: "border-box",
@@ -10628,7 +10516,7 @@ class EditorView {
10628
10516
  }
10629
10517
  mountStyles() {
10630
10518
  this.styleModules = this.state.facet(styleModule);
10631
- StyleModule.mount(this.root, this.styleModules.concat(baseTheme$1$1).reverse());
10519
+ StyleModule.mount(this.root, this.styleModules.concat(baseTheme$1).reverse());
10632
10520
  }
10633
10521
  readMeasured() {
10634
10522
  if (this.updateState == 2 /* UpdateState.Updating */) throw new Error("Reading the editor layout isn't allowed during an update");
@@ -12437,7 +12325,7 @@ const tooltipPlugin = /*@__PURE__*/ViewPlugin.fromClass(class {
12437
12325
  }
12438
12326
  }
12439
12327
  });
12440
- const baseTheme$2 = /*@__PURE__*/EditorView.baseTheme({
12328
+ const baseTheme = /*@__PURE__*/EditorView.baseTheme({
12441
12329
  ".cm-tooltip": {
12442
12330
  zIndex: 100,
12443
12331
  boxSizing: "border-box"
@@ -12507,7 +12395,7 @@ const noOffset = {
12507
12395
  Facet to which an extension can add a value to show a tooltip.
12508
12396
  */
12509
12397
  const showTooltip = /*@__PURE__*/Facet.define({
12510
- enables: [tooltipPlugin, baseTheme$2]
12398
+ enables: [tooltipPlugin, baseTheme]
12511
12399
  });
12512
12400
  const showHoverTooltip = /*@__PURE__*/Facet.define();
12513
12401
  class HoverTooltipHost {
@@ -13304,4535 +13192,4 @@ function highlightActiveLineGutter() {
13304
13192
  return activeLineGutterHighlighter;
13305
13193
  }
13306
13194
 
13307
- // FIXME profile adding a per-Tree TreeNode cache, validating it by
13308
- // parent pointer
13309
- /// The default maximum length of a `TreeBuffer` node.
13310
- const DefaultBufferLength = 1024;
13311
- let nextPropID = 0;
13312
- class Range {
13313
- constructor(from, to) {
13314
- this.from = from;
13315
- this.to = to;
13316
- }
13317
- }
13318
- /// Each [node type](#common.NodeType) or [individual tree](#common.Tree)
13319
- /// can have metadata associated with it in props. Instances of this
13320
- /// class represent prop names.
13321
- class NodeProp {
13322
- /// Create a new node prop type.
13323
- constructor(config = {}) {
13324
- this.id = nextPropID++;
13325
- this.perNode = !!config.perNode;
13326
- this.deserialize = config.deserialize || (() => {
13327
- throw new Error("This node type doesn't define a deserialize function");
13328
- });
13329
- }
13330
- /// This is meant to be used with
13331
- /// [`NodeSet.extend`](#common.NodeSet.extend) or
13332
- /// [`LRParser.configure`](#lr.ParserConfig.props) to compute
13333
- /// prop values for each node type in the set. Takes a [match
13334
- /// object](#common.NodeType^match) or function that returns undefined
13335
- /// if the node type doesn't get this prop, and the prop's value if
13336
- /// it does.
13337
- add(match) {
13338
- if (this.perNode) throw new RangeError("Can't add per-node props to node types");
13339
- if (typeof match != "function") match = NodeType.match(match);
13340
- return type => {
13341
- let result = match(type);
13342
- return result === undefined ? null : [this, result];
13343
- };
13344
- }
13345
- }
13346
- /// Prop that is used to describe matching delimiters. For opening
13347
- /// delimiters, this holds an array of node names (written as a
13348
- /// space-separated string when declaring this prop in a grammar)
13349
- /// for the node types of closing delimiters that match it.
13350
- NodeProp.closedBy = new NodeProp({
13351
- deserialize: str => str.split(" ")
13352
- });
13353
- /// The inverse of [`closedBy`](#common.NodeProp^closedBy). This is
13354
- /// attached to closing delimiters, holding an array of node names
13355
- /// of types of matching opening delimiters.
13356
- NodeProp.openedBy = new NodeProp({
13357
- deserialize: str => str.split(" ")
13358
- });
13359
- /// Used to assign node types to groups (for example, all node
13360
- /// types that represent an expression could be tagged with an
13361
- /// `"Expression"` group).
13362
- NodeProp.group = new NodeProp({
13363
- deserialize: str => str.split(" ")
13364
- });
13365
- /// The hash of the [context](#lr.ContextTracker.constructor)
13366
- /// that the node was parsed in, if any. Used to limit reuse of
13367
- /// contextual nodes.
13368
- NodeProp.contextHash = new NodeProp({
13369
- perNode: true
13370
- });
13371
- /// The distance beyond the end of the node that the tokenizer
13372
- /// looked ahead for any of the tokens inside the node. (The LR
13373
- /// parser only stores this when it is larger than 25, for
13374
- /// efficiency reasons.)
13375
- NodeProp.lookAhead = new NodeProp({
13376
- perNode: true
13377
- });
13378
- /// This per-node prop is used to replace a given node, or part of a
13379
- /// node, with another tree. This is useful to include trees from
13380
- /// different languages in mixed-language parsers.
13381
- NodeProp.mounted = new NodeProp({
13382
- perNode: true
13383
- });
13384
- /// A mounted tree, which can be [stored](#common.NodeProp^mounted) on
13385
- /// a tree node to indicate that parts of its content are
13386
- /// represented by another tree.
13387
- class MountedTree {
13388
- constructor(
13389
- /// The inner tree.
13390
- tree,
13391
- /// If this is null, this tree replaces the entire node (it will
13392
- /// be included in the regular iteration instead of its host
13393
- /// node). If not, only the given ranges are considered to be
13394
- /// covered by this tree. This is used for trees that are mixed in
13395
- /// a way that isn't strictly hierarchical. Such mounted trees are
13396
- /// only entered by [`resolveInner`](#common.Tree.resolveInner)
13397
- /// and [`enter`](#common.SyntaxNode.enter).
13398
- overlay,
13399
- /// The parser used to create this subtree.
13400
- parser) {
13401
- this.tree = tree;
13402
- this.overlay = overlay;
13403
- this.parser = parser;
13404
- }
13405
- }
13406
- const noProps = Object.create(null);
13407
- /// Each node in a syntax tree has a node type associated with it.
13408
- class NodeType {
13409
- /// @internal
13410
- constructor(
13411
- /// The name of the node type. Not necessarily unique, but if the
13412
- /// grammar was written properly, different node types with the
13413
- /// same name within a node set should play the same semantic
13414
- /// role.
13415
- name,
13416
- /// @internal
13417
- props,
13418
- /// The id of this node in its set. Corresponds to the term ids
13419
- /// used in the parser.
13420
- id,
13421
- /// @internal
13422
- flags = 0) {
13423
- this.name = name;
13424
- this.props = props;
13425
- this.id = id;
13426
- this.flags = flags;
13427
- }
13428
- /// Define a node type.
13429
- static define(spec) {
13430
- let props = spec.props && spec.props.length ? Object.create(null) : noProps;
13431
- let flags = (spec.top ? 1 /* NodeFlag.Top */ : 0) | (spec.skipped ? 2 /* NodeFlag.Skipped */ : 0) | (spec.error ? 4 /* NodeFlag.Error */ : 0) | (spec.name == null ? 8 /* NodeFlag.Anonymous */ : 0);
13432
- let type = new NodeType(spec.name || "", props, spec.id, flags);
13433
- if (spec.props) for (let src of spec.props) {
13434
- if (!Array.isArray(src)) src = src(type);
13435
- if (src) {
13436
- if (src[0].perNode) throw new RangeError("Can't store a per-node prop on a node type");
13437
- props[src[0].id] = src[1];
13438
- }
13439
- }
13440
- return type;
13441
- }
13442
- /// Retrieves a node prop for this type. Will return `undefined` if
13443
- /// the prop isn't present on this node.
13444
- prop(prop) {
13445
- return this.props[prop.id];
13446
- }
13447
- /// True when this is the top node of a grammar.
13448
- get isTop() {
13449
- return (this.flags & 1 /* NodeFlag.Top */) > 0;
13450
- }
13451
- /// True when this node is produced by a skip rule.
13452
- get isSkipped() {
13453
- return (this.flags & 2 /* NodeFlag.Skipped */) > 0;
13454
- }
13455
- /// Indicates whether this is an error node.
13456
- get isError() {
13457
- return (this.flags & 4 /* NodeFlag.Error */) > 0;
13458
- }
13459
- /// When true, this node type doesn't correspond to a user-declared
13460
- /// named node, for example because it is used to cache repetition.
13461
- get isAnonymous() {
13462
- return (this.flags & 8 /* NodeFlag.Anonymous */) > 0;
13463
- }
13464
- /// Returns true when this node's name or one of its
13465
- /// [groups](#common.NodeProp^group) matches the given string.
13466
- is(name) {
13467
- if (typeof name == 'string') {
13468
- if (this.name == name) return true;
13469
- let group = this.prop(NodeProp.group);
13470
- return group ? group.indexOf(name) > -1 : false;
13471
- }
13472
- return this.id == name;
13473
- }
13474
- /// Create a function from node types to arbitrary values by
13475
- /// specifying an object whose property names are node or
13476
- /// [group](#common.NodeProp^group) names. Often useful with
13477
- /// [`NodeProp.add`](#common.NodeProp.add). You can put multiple
13478
- /// names, separated by spaces, in a single property name to map
13479
- /// multiple node names to a single value.
13480
- static match(map) {
13481
- let direct = Object.create(null);
13482
- for (let prop in map) for (let name of prop.split(" ")) direct[name] = map[prop];
13483
- return node => {
13484
- for (let groups = node.prop(NodeProp.group), i = -1; i < (groups ? groups.length : 0); i++) {
13485
- let found = direct[i < 0 ? node.name : groups[i]];
13486
- if (found) return found;
13487
- }
13488
- };
13489
- }
13490
- }
13491
- /// An empty dummy node type to use when no actual type is available.
13492
- NodeType.none = new NodeType("", Object.create(null), 0, 8 /* NodeFlag.Anonymous */);
13493
- /// A node set holds a collection of node types. It is used to
13494
- /// compactly represent trees by storing their type ids, rather than a
13495
- /// full pointer to the type object, in a numeric array. Each parser
13496
- /// [has](#lr.LRParser.nodeSet) a node set, and [tree
13497
- /// buffers](#common.TreeBuffer) can only store collections of nodes
13498
- /// from the same set. A set can have a maximum of 2**16 (65536) node
13499
- /// types in it, so that the ids fit into 16-bit typed array slots.
13500
- class NodeSet {
13501
- /// Create a set with the given types. The `id` property of each
13502
- /// type should correspond to its position within the array.
13503
- constructor(
13504
- /// The node types in this set, by id.
13505
- types) {
13506
- this.types = types;
13507
- for (let i = 0; i < types.length; i++) if (types[i].id != i) throw new RangeError("Node type ids should correspond to array positions when creating a node set");
13508
- }
13509
- /// Create a copy of this set with some node properties added. The
13510
- /// arguments to this method can be created with
13511
- /// [`NodeProp.add`](#common.NodeProp.add).
13512
- extend(...props) {
13513
- let newTypes = [];
13514
- for (let type of this.types) {
13515
- let newProps = null;
13516
- for (let source of props) {
13517
- let add = source(type);
13518
- if (add) {
13519
- if (!newProps) newProps = Object.assign({}, type.props);
13520
- newProps[add[0].id] = add[1];
13521
- }
13522
- }
13523
- newTypes.push(newProps ? new NodeType(type.name, newProps, type.id, type.flags) : type);
13524
- }
13525
- return new NodeSet(newTypes);
13526
- }
13527
- }
13528
- const CachedNode = new WeakMap(),
13529
- CachedInnerNode = new WeakMap();
13530
- /// Options that control iteration. Can be combined with the `|`
13531
- /// operator to enable multiple ones.
13532
- var IterMode;
13533
- (function (IterMode) {
13534
- /// When enabled, iteration will only visit [`Tree`](#common.Tree)
13535
- /// objects, not nodes packed into
13536
- /// [`TreeBuffer`](#common.TreeBuffer)s.
13537
- IterMode[IterMode["ExcludeBuffers"] = 1] = "ExcludeBuffers";
13538
- /// Enable this to make iteration include anonymous nodes (such as
13539
- /// the nodes that wrap repeated grammar constructs into a balanced
13540
- /// tree).
13541
- IterMode[IterMode["IncludeAnonymous"] = 2] = "IncludeAnonymous";
13542
- /// By default, regular [mounted](#common.NodeProp^mounted) nodes
13543
- /// replace their base node in iteration. Enable this to ignore them
13544
- /// instead.
13545
- IterMode[IterMode["IgnoreMounts"] = 4] = "IgnoreMounts";
13546
- /// This option only applies in
13547
- /// [`enter`](#common.SyntaxNode.enter)-style methods. It tells the
13548
- /// library to not enter mounted overlays if one covers the given
13549
- /// position.
13550
- IterMode[IterMode["IgnoreOverlays"] = 8] = "IgnoreOverlays";
13551
- })(IterMode || (IterMode = {}));
13552
- /// A piece of syntax tree. There are two ways to approach these
13553
- /// trees: the way they are actually stored in memory, and the
13554
- /// convenient way.
13555
- ///
13556
- /// Syntax trees are stored as a tree of `Tree` and `TreeBuffer`
13557
- /// objects. By packing detail information into `TreeBuffer` leaf
13558
- /// nodes, the representation is made a lot more memory-efficient.
13559
- ///
13560
- /// However, when you want to actually work with tree nodes, this
13561
- /// representation is very awkward, so most client code will want to
13562
- /// use the [`TreeCursor`](#common.TreeCursor) or
13563
- /// [`SyntaxNode`](#common.SyntaxNode) interface instead, which provides
13564
- /// a view on some part of this data structure, and can be used to
13565
- /// move around to adjacent nodes.
13566
- class Tree {
13567
- /// Construct a new tree. See also [`Tree.build`](#common.Tree^build).
13568
- constructor(
13569
- /// The type of the top node.
13570
- type,
13571
- /// This node's child nodes.
13572
- children,
13573
- /// The positions (offsets relative to the start of this tree) of
13574
- /// the children.
13575
- positions,
13576
- /// The total length of this tree
13577
- length,
13578
- /// Per-node [node props](#common.NodeProp) to associate with this node.
13579
- props) {
13580
- this.type = type;
13581
- this.children = children;
13582
- this.positions = positions;
13583
- this.length = length;
13584
- /// @internal
13585
- this.props = null;
13586
- if (props && props.length) {
13587
- this.props = Object.create(null);
13588
- for (let [prop, value] of props) this.props[typeof prop == "number" ? prop : prop.id] = value;
13589
- }
13590
- }
13591
- /// @internal
13592
- toString() {
13593
- let mounted = this.prop(NodeProp.mounted);
13594
- if (mounted && !mounted.overlay) return mounted.tree.toString();
13595
- let children = "";
13596
- for (let ch of this.children) {
13597
- let str = ch.toString();
13598
- if (str) {
13599
- if (children) children += ",";
13600
- children += str;
13601
- }
13602
- }
13603
- return !this.type.name ? children : (/\W/.test(this.type.name) && !this.type.isError ? JSON.stringify(this.type.name) : this.type.name) + (children.length ? "(" + children + ")" : "");
13604
- }
13605
- /// Get a [tree cursor](#common.TreeCursor) positioned at the top of
13606
- /// the tree. Mode can be used to [control](#common.IterMode) which
13607
- /// nodes the cursor visits.
13608
- cursor(mode = 0) {
13609
- return new TreeCursor(this.topNode, mode);
13610
- }
13611
- /// Get a [tree cursor](#common.TreeCursor) pointing into this tree
13612
- /// at the given position and side (see
13613
- /// [`moveTo`](#common.TreeCursor.moveTo).
13614
- cursorAt(pos, side = 0, mode = 0) {
13615
- let scope = CachedNode.get(this) || this.topNode;
13616
- let cursor = new TreeCursor(scope);
13617
- cursor.moveTo(pos, side);
13618
- CachedNode.set(this, cursor._tree);
13619
- return cursor;
13620
- }
13621
- /// Get a [syntax node](#common.SyntaxNode) object for the top of the
13622
- /// tree.
13623
- get topNode() {
13624
- return new TreeNode(this, 0, 0, null);
13625
- }
13626
- /// Get the [syntax node](#common.SyntaxNode) at the given position.
13627
- /// If `side` is -1, this will move into nodes that end at the
13628
- /// position. If 1, it'll move into nodes that start at the
13629
- /// position. With 0, it'll only enter nodes that cover the position
13630
- /// from both sides.
13631
- ///
13632
- /// Note that this will not enter
13633
- /// [overlays](#common.MountedTree.overlay), and you often want
13634
- /// [`resolveInner`](#common.Tree.resolveInner) instead.
13635
- resolve(pos, side = 0) {
13636
- let node = resolveNode(CachedNode.get(this) || this.topNode, pos, side, false);
13637
- CachedNode.set(this, node);
13638
- return node;
13639
- }
13640
- /// Like [`resolve`](#common.Tree.resolve), but will enter
13641
- /// [overlaid](#common.MountedTree.overlay) nodes, producing a syntax node
13642
- /// pointing into the innermost overlaid tree at the given position
13643
- /// (with parent links going through all parent structure, including
13644
- /// the host trees).
13645
- resolveInner(pos, side = 0) {
13646
- let node = resolveNode(CachedInnerNode.get(this) || this.topNode, pos, side, true);
13647
- CachedInnerNode.set(this, node);
13648
- return node;
13649
- }
13650
- /// Iterate over the tree and its children, calling `enter` for any
13651
- /// node that touches the `from`/`to` region (if given) before
13652
- /// running over such a node's children, and `leave` (if given) when
13653
- /// leaving the node. When `enter` returns `false`, that node will
13654
- /// not have its children iterated over (or `leave` called).
13655
- iterate(spec) {
13656
- let {
13657
- enter,
13658
- leave,
13659
- from = 0,
13660
- to = this.length
13661
- } = spec;
13662
- for (let c = this.cursor((spec.mode || 0) | IterMode.IncludeAnonymous);;) {
13663
- let entered = false;
13664
- if (c.from <= to && c.to >= from && (c.type.isAnonymous || enter(c) !== false)) {
13665
- if (c.firstChild()) continue;
13666
- entered = true;
13667
- }
13668
- for (;;) {
13669
- if (entered && leave && !c.type.isAnonymous) leave(c);
13670
- if (c.nextSibling()) break;
13671
- if (!c.parent()) return;
13672
- entered = true;
13673
- }
13674
- }
13675
- }
13676
- /// Get the value of the given [node prop](#common.NodeProp) for this
13677
- /// node. Works with both per-node and per-type props.
13678
- prop(prop) {
13679
- return !prop.perNode ? this.type.prop(prop) : this.props ? this.props[prop.id] : undefined;
13680
- }
13681
- /// Returns the node's [per-node props](#common.NodeProp.perNode) in a
13682
- /// format that can be passed to the [`Tree`](#common.Tree)
13683
- /// constructor.
13684
- get propValues() {
13685
- let result = [];
13686
- if (this.props) for (let id in this.props) result.push([+id, this.props[id]]);
13687
- return result;
13688
- }
13689
- /// Balance the direct children of this tree, producing a copy of
13690
- /// which may have children grouped into subtrees with type
13691
- /// [`NodeType.none`](#common.NodeType^none).
13692
- balance(config = {}) {
13693
- return this.children.length <= 8 /* Balance.BranchFactor */ ? this : balanceRange(NodeType.none, this.children, this.positions, 0, this.children.length, 0, this.length, (children, positions, length) => new Tree(this.type, children, positions, length, this.propValues), config.makeTree || ((children, positions, length) => new Tree(NodeType.none, children, positions, length)));
13694
- }
13695
- /// Build a tree from a postfix-ordered buffer of node information,
13696
- /// or a cursor over such a buffer.
13697
- static build(data) {
13698
- return buildTree(data);
13699
- }
13700
- }
13701
- /// The empty tree
13702
- Tree.empty = new Tree(NodeType.none, [], [], 0);
13703
- class FlatBufferCursor {
13704
- constructor(buffer, index) {
13705
- this.buffer = buffer;
13706
- this.index = index;
13707
- }
13708
- get id() {
13709
- return this.buffer[this.index - 4];
13710
- }
13711
- get start() {
13712
- return this.buffer[this.index - 3];
13713
- }
13714
- get end() {
13715
- return this.buffer[this.index - 2];
13716
- }
13717
- get size() {
13718
- return this.buffer[this.index - 1];
13719
- }
13720
- get pos() {
13721
- return this.index;
13722
- }
13723
- next() {
13724
- this.index -= 4;
13725
- }
13726
- fork() {
13727
- return new FlatBufferCursor(this.buffer, this.index);
13728
- }
13729
- }
13730
- /// Tree buffers contain (type, start, end, endIndex) quads for each
13731
- /// node. In such a buffer, nodes are stored in prefix order (parents
13732
- /// before children, with the endIndex of the parent indicating which
13733
- /// children belong to it).
13734
- class TreeBuffer {
13735
- /// Create a tree buffer.
13736
- constructor(
13737
- /// The buffer's content.
13738
- buffer,
13739
- /// The total length of the group of nodes in the buffer.
13740
- length,
13741
- /// The node set used in this buffer.
13742
- set) {
13743
- this.buffer = buffer;
13744
- this.length = length;
13745
- this.set = set;
13746
- }
13747
- /// @internal
13748
- get type() {
13749
- return NodeType.none;
13750
- }
13751
- /// @internal
13752
- toString() {
13753
- let result = [];
13754
- for (let index = 0; index < this.buffer.length;) {
13755
- result.push(this.childString(index));
13756
- index = this.buffer[index + 3];
13757
- }
13758
- return result.join(",");
13759
- }
13760
- /// @internal
13761
- childString(index) {
13762
- let id = this.buffer[index],
13763
- endIndex = this.buffer[index + 3];
13764
- let type = this.set.types[id],
13765
- result = type.name;
13766
- if (/\W/.test(result) && !type.isError) result = JSON.stringify(result);
13767
- index += 4;
13768
- if (endIndex == index) return result;
13769
- let children = [];
13770
- while (index < endIndex) {
13771
- children.push(this.childString(index));
13772
- index = this.buffer[index + 3];
13773
- }
13774
- return result + "(" + children.join(",") + ")";
13775
- }
13776
- /// @internal
13777
- findChild(startIndex, endIndex, dir, pos, side) {
13778
- let {
13779
- buffer
13780
- } = this,
13781
- pick = -1;
13782
- for (let i = startIndex; i != endIndex; i = buffer[i + 3]) {
13783
- if (checkSide(side, pos, buffer[i + 1], buffer[i + 2])) {
13784
- pick = i;
13785
- if (dir > 0) break;
13786
- }
13787
- }
13788
- return pick;
13789
- }
13790
- /// @internal
13791
- slice(startI, endI, from) {
13792
- let b = this.buffer;
13793
- let copy = new Uint16Array(endI - startI),
13794
- len = 0;
13795
- for (let i = startI, j = 0; i < endI;) {
13796
- copy[j++] = b[i++];
13797
- copy[j++] = b[i++] - from;
13798
- let to = copy[j++] = b[i++] - from;
13799
- copy[j++] = b[i++] - startI;
13800
- len = Math.max(len, to);
13801
- }
13802
- return new TreeBuffer(copy, len, this.set);
13803
- }
13804
- }
13805
- function checkSide(side, pos, from, to) {
13806
- switch (side) {
13807
- case -2 /* Side.Before */:
13808
- return from < pos;
13809
- case -1 /* Side.AtOrBefore */:
13810
- return to >= pos && from < pos;
13811
- case 0 /* Side.Around */:
13812
- return from < pos && to > pos;
13813
- case 1 /* Side.AtOrAfter */:
13814
- return from <= pos && to > pos;
13815
- case 2 /* Side.After */:
13816
- return to > pos;
13817
- case 4 /* Side.DontCare */:
13818
- return true;
13819
- }
13820
- }
13821
- function enterUnfinishedNodesBefore(node, pos) {
13822
- let scan = node.childBefore(pos);
13823
- while (scan) {
13824
- let last = scan.lastChild;
13825
- if (!last || last.to != scan.to) break;
13826
- if (last.type.isError && last.from == last.to) {
13827
- node = scan;
13828
- scan = last.prevSibling;
13829
- } else {
13830
- scan = last;
13831
- }
13832
- }
13833
- return node;
13834
- }
13835
- function resolveNode(node, pos, side, overlays) {
13836
- var _a;
13837
- // Move up to a node that actually holds the position, if possible
13838
- while (node.from == node.to || (side < 1 ? node.from >= pos : node.from > pos) || (side > -1 ? node.to <= pos : node.to < pos)) {
13839
- let parent = !overlays && node instanceof TreeNode && node.index < 0 ? null : node.parent;
13840
- if (!parent) return node;
13841
- node = parent;
13842
- }
13843
- let mode = overlays ? 0 : IterMode.IgnoreOverlays;
13844
- // Must go up out of overlays when those do not overlap with pos
13845
- if (overlays) for (let scan = node, parent = scan.parent; parent; scan = parent, parent = scan.parent) {
13846
- if (scan instanceof TreeNode && scan.index < 0 && ((_a = parent.enter(pos, side, mode)) === null || _a === void 0 ? void 0 : _a.from) != scan.from) node = parent;
13847
- }
13848
- for (;;) {
13849
- let inner = node.enter(pos, side, mode);
13850
- if (!inner) return node;
13851
- node = inner;
13852
- }
13853
- }
13854
- class TreeNode {
13855
- constructor(_tree, from,
13856
- // Index in parent node, set to -1 if the node is not a direct child of _parent.node (overlay)
13857
- index, _parent) {
13858
- this._tree = _tree;
13859
- this.from = from;
13860
- this.index = index;
13861
- this._parent = _parent;
13862
- }
13863
- get type() {
13864
- return this._tree.type;
13865
- }
13866
- get name() {
13867
- return this._tree.type.name;
13868
- }
13869
- get to() {
13870
- return this.from + this._tree.length;
13871
- }
13872
- nextChild(i, dir, pos, side, mode = 0) {
13873
- for (let parent = this;;) {
13874
- for (let {
13875
- children,
13876
- positions
13877
- } = parent._tree, e = dir > 0 ? children.length : -1; i != e; i += dir) {
13878
- let next = children[i],
13879
- start = positions[i] + parent.from;
13880
- if (!checkSide(side, pos, start, start + next.length)) continue;
13881
- if (next instanceof TreeBuffer) {
13882
- if (mode & IterMode.ExcludeBuffers) continue;
13883
- let index = next.findChild(0, next.buffer.length, dir, pos - start, side);
13884
- if (index > -1) return new BufferNode(new BufferContext(parent, next, i, start), null, index);
13885
- } else if (mode & IterMode.IncludeAnonymous || !next.type.isAnonymous || hasChild(next)) {
13886
- let mounted;
13887
- if (!(mode & IterMode.IgnoreMounts) && next.props && (mounted = next.prop(NodeProp.mounted)) && !mounted.overlay) return new TreeNode(mounted.tree, start, i, parent);
13888
- let inner = new TreeNode(next, start, i, parent);
13889
- return mode & IterMode.IncludeAnonymous || !inner.type.isAnonymous ? inner : inner.nextChild(dir < 0 ? next.children.length - 1 : 0, dir, pos, side);
13890
- }
13891
- }
13892
- if (mode & IterMode.IncludeAnonymous || !parent.type.isAnonymous) return null;
13893
- if (parent.index >= 0) i = parent.index + dir;else i = dir < 0 ? -1 : parent._parent._tree.children.length;
13894
- parent = parent._parent;
13895
- if (!parent) return null;
13896
- }
13897
- }
13898
- get firstChild() {
13899
- return this.nextChild(0, 1, 0, 4 /* Side.DontCare */);
13900
- }
13901
- get lastChild() {
13902
- return this.nextChild(this._tree.children.length - 1, -1, 0, 4 /* Side.DontCare */);
13903
- }
13904
- childAfter(pos) {
13905
- return this.nextChild(0, 1, pos, 2 /* Side.After */);
13906
- }
13907
- childBefore(pos) {
13908
- return this.nextChild(this._tree.children.length - 1, -1, pos, -2 /* Side.Before */);
13909
- }
13910
- enter(pos, side, mode = 0) {
13911
- let mounted;
13912
- if (!(mode & IterMode.IgnoreOverlays) && (mounted = this._tree.prop(NodeProp.mounted)) && mounted.overlay) {
13913
- let rPos = pos - this.from;
13914
- for (let {
13915
- from,
13916
- to
13917
- } of mounted.overlay) {
13918
- if ((side > 0 ? from <= rPos : from < rPos) && (side < 0 ? to >= rPos : to > rPos)) return new TreeNode(mounted.tree, mounted.overlay[0].from + this.from, -1, this);
13919
- }
13920
- }
13921
- return this.nextChild(0, 1, pos, side, mode);
13922
- }
13923
- nextSignificantParent() {
13924
- let val = this;
13925
- while (val.type.isAnonymous && val._parent) val = val._parent;
13926
- return val;
13927
- }
13928
- get parent() {
13929
- return this._parent ? this._parent.nextSignificantParent() : null;
13930
- }
13931
- get nextSibling() {
13932
- return this._parent && this.index >= 0 ? this._parent.nextChild(this.index + 1, 1, 0, 4 /* Side.DontCare */) : null;
13933
- }
13934
- get prevSibling() {
13935
- return this._parent && this.index >= 0 ? this._parent.nextChild(this.index - 1, -1, 0, 4 /* Side.DontCare */) : null;
13936
- }
13937
- cursor(mode = 0) {
13938
- return new TreeCursor(this, mode);
13939
- }
13940
- get tree() {
13941
- return this._tree;
13942
- }
13943
- toTree() {
13944
- return this._tree;
13945
- }
13946
- resolve(pos, side = 0) {
13947
- return resolveNode(this, pos, side, false);
13948
- }
13949
- resolveInner(pos, side = 0) {
13950
- return resolveNode(this, pos, side, true);
13951
- }
13952
- enterUnfinishedNodesBefore(pos) {
13953
- return enterUnfinishedNodesBefore(this, pos);
13954
- }
13955
- getChild(type, before = null, after = null) {
13956
- let r = getChildren(this, type, before, after);
13957
- return r.length ? r[0] : null;
13958
- }
13959
- getChildren(type, before = null, after = null) {
13960
- return getChildren(this, type, before, after);
13961
- }
13962
- /// @internal
13963
- toString() {
13964
- return this._tree.toString();
13965
- }
13966
- get node() {
13967
- return this;
13968
- }
13969
- matchContext(context) {
13970
- return matchNodeContext(this, context);
13971
- }
13972
- }
13973
- function getChildren(node, type, before, after) {
13974
- let cur = node.cursor(),
13975
- result = [];
13976
- if (!cur.firstChild()) return result;
13977
- if (before != null) while (!cur.type.is(before)) if (!cur.nextSibling()) return result;
13978
- for (;;) {
13979
- if (after != null && cur.type.is(after)) return result;
13980
- if (cur.type.is(type)) result.push(cur.node);
13981
- if (!cur.nextSibling()) return after == null ? result : [];
13982
- }
13983
- }
13984
- function matchNodeContext(node, context, i = context.length - 1) {
13985
- for (let p = node.parent; i >= 0; p = p.parent) {
13986
- if (!p) return false;
13987
- if (!p.type.isAnonymous) {
13988
- if (context[i] && context[i] != p.name) return false;
13989
- i--;
13990
- }
13991
- }
13992
- return true;
13993
- }
13994
- class BufferContext {
13995
- constructor(parent, buffer, index, start) {
13996
- this.parent = parent;
13997
- this.buffer = buffer;
13998
- this.index = index;
13999
- this.start = start;
14000
- }
14001
- }
14002
- class BufferNode {
14003
- get name() {
14004
- return this.type.name;
14005
- }
14006
- get from() {
14007
- return this.context.start + this.context.buffer.buffer[this.index + 1];
14008
- }
14009
- get to() {
14010
- return this.context.start + this.context.buffer.buffer[this.index + 2];
14011
- }
14012
- constructor(context, _parent, index) {
14013
- this.context = context;
14014
- this._parent = _parent;
14015
- this.index = index;
14016
- this.type = context.buffer.set.types[context.buffer.buffer[index]];
14017
- }
14018
- child(dir, pos, side) {
14019
- let {
14020
- buffer
14021
- } = this.context;
14022
- let index = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], dir, pos - this.context.start, side);
14023
- return index < 0 ? null : new BufferNode(this.context, this, index);
14024
- }
14025
- get firstChild() {
14026
- return this.child(1, 0, 4 /* Side.DontCare */);
14027
- }
14028
- get lastChild() {
14029
- return this.child(-1, 0, 4 /* Side.DontCare */);
14030
- }
14031
- childAfter(pos) {
14032
- return this.child(1, pos, 2 /* Side.After */);
14033
- }
14034
- childBefore(pos) {
14035
- return this.child(-1, pos, -2 /* Side.Before */);
14036
- }
14037
- enter(pos, side, mode = 0) {
14038
- if (mode & IterMode.ExcludeBuffers) return null;
14039
- let {
14040
- buffer
14041
- } = this.context;
14042
- let index = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], side > 0 ? 1 : -1, pos - this.context.start, side);
14043
- return index < 0 ? null : new BufferNode(this.context, this, index);
14044
- }
14045
- get parent() {
14046
- return this._parent || this.context.parent.nextSignificantParent();
14047
- }
14048
- externalSibling(dir) {
14049
- return this._parent ? null : this.context.parent.nextChild(this.context.index + dir, dir, 0, 4 /* Side.DontCare */);
14050
- }
14051
-
14052
- get nextSibling() {
14053
- let {
14054
- buffer
14055
- } = this.context;
14056
- let after = buffer.buffer[this.index + 3];
14057
- if (after < (this._parent ? buffer.buffer[this._parent.index + 3] : buffer.buffer.length)) return new BufferNode(this.context, this._parent, after);
14058
- return this.externalSibling(1);
14059
- }
14060
- get prevSibling() {
14061
- let {
14062
- buffer
14063
- } = this.context;
14064
- let parentStart = this._parent ? this._parent.index + 4 : 0;
14065
- if (this.index == parentStart) return this.externalSibling(-1);
14066
- return new BufferNode(this.context, this._parent, buffer.findChild(parentStart, this.index, -1, 0, 4 /* Side.DontCare */));
14067
- }
14068
-
14069
- cursor(mode = 0) {
14070
- return new TreeCursor(this, mode);
14071
- }
14072
- get tree() {
14073
- return null;
14074
- }
14075
- toTree() {
14076
- let children = [],
14077
- positions = [];
14078
- let {
14079
- buffer
14080
- } = this.context;
14081
- let startI = this.index + 4,
14082
- endI = buffer.buffer[this.index + 3];
14083
- if (endI > startI) {
14084
- let from = buffer.buffer[this.index + 1];
14085
- children.push(buffer.slice(startI, endI, from));
14086
- positions.push(0);
14087
- }
14088
- return new Tree(this.type, children, positions, this.to - this.from);
14089
- }
14090
- resolve(pos, side = 0) {
14091
- return resolveNode(this, pos, side, false);
14092
- }
14093
- resolveInner(pos, side = 0) {
14094
- return resolveNode(this, pos, side, true);
14095
- }
14096
- enterUnfinishedNodesBefore(pos) {
14097
- return enterUnfinishedNodesBefore(this, pos);
14098
- }
14099
- /// @internal
14100
- toString() {
14101
- return this.context.buffer.childString(this.index);
14102
- }
14103
- getChild(type, before = null, after = null) {
14104
- let r = getChildren(this, type, before, after);
14105
- return r.length ? r[0] : null;
14106
- }
14107
- getChildren(type, before = null, after = null) {
14108
- return getChildren(this, type, before, after);
14109
- }
14110
- get node() {
14111
- return this;
14112
- }
14113
- matchContext(context) {
14114
- return matchNodeContext(this, context);
14115
- }
14116
- }
14117
- /// A tree cursor object focuses on a given node in a syntax tree, and
14118
- /// allows you to move to adjacent nodes.
14119
- class TreeCursor {
14120
- /// Shorthand for `.type.name`.
14121
- get name() {
14122
- return this.type.name;
14123
- }
14124
- /// @internal
14125
- constructor(node,
14126
- /// @internal
14127
- mode = 0) {
14128
- this.mode = mode;
14129
- /// @internal
14130
- this.buffer = null;
14131
- this.stack = [];
14132
- /// @internal
14133
- this.index = 0;
14134
- this.bufferNode = null;
14135
- if (node instanceof TreeNode) {
14136
- this.yieldNode(node);
14137
- } else {
14138
- this._tree = node.context.parent;
14139
- this.buffer = node.context;
14140
- for (let n = node._parent; n; n = n._parent) this.stack.unshift(n.index);
14141
- this.bufferNode = node;
14142
- this.yieldBuf(node.index);
14143
- }
14144
- }
14145
- yieldNode(node) {
14146
- if (!node) return false;
14147
- this._tree = node;
14148
- this.type = node.type;
14149
- this.from = node.from;
14150
- this.to = node.to;
14151
- return true;
14152
- }
14153
- yieldBuf(index, type) {
14154
- this.index = index;
14155
- let {
14156
- start,
14157
- buffer
14158
- } = this.buffer;
14159
- this.type = type || buffer.set.types[buffer.buffer[index]];
14160
- this.from = start + buffer.buffer[index + 1];
14161
- this.to = start + buffer.buffer[index + 2];
14162
- return true;
14163
- }
14164
- yield(node) {
14165
- if (!node) return false;
14166
- if (node instanceof TreeNode) {
14167
- this.buffer = null;
14168
- return this.yieldNode(node);
14169
- }
14170
- this.buffer = node.context;
14171
- return this.yieldBuf(node.index, node.type);
14172
- }
14173
- /// @internal
14174
- toString() {
14175
- return this.buffer ? this.buffer.buffer.childString(this.index) : this._tree.toString();
14176
- }
14177
- /// @internal
14178
- enterChild(dir, pos, side) {
14179
- if (!this.buffer) return this.yield(this._tree.nextChild(dir < 0 ? this._tree._tree.children.length - 1 : 0, dir, pos, side, this.mode));
14180
- let {
14181
- buffer
14182
- } = this.buffer;
14183
- let index = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], dir, pos - this.buffer.start, side);
14184
- if (index < 0) return false;
14185
- this.stack.push(this.index);
14186
- return this.yieldBuf(index);
14187
- }
14188
- /// Move the cursor to this node's first child. When this returns
14189
- /// false, the node has no child, and the cursor has not been moved.
14190
- firstChild() {
14191
- return this.enterChild(1, 0, 4 /* Side.DontCare */);
14192
- }
14193
- /// Move the cursor to this node's last child.
14194
- lastChild() {
14195
- return this.enterChild(-1, 0, 4 /* Side.DontCare */);
14196
- }
14197
- /// Move the cursor to the first child that ends after `pos`.
14198
- childAfter(pos) {
14199
- return this.enterChild(1, pos, 2 /* Side.After */);
14200
- }
14201
- /// Move to the last child that starts before `pos`.
14202
- childBefore(pos) {
14203
- return this.enterChild(-1, pos, -2 /* Side.Before */);
14204
- }
14205
- /// Move the cursor to the child around `pos`. If side is -1 the
14206
- /// child may end at that position, when 1 it may start there. This
14207
- /// will also enter [overlaid](#common.MountedTree.overlay)
14208
- /// [mounted](#common.NodeProp^mounted) trees unless `overlays` is
14209
- /// set to false.
14210
- enter(pos, side, mode = this.mode) {
14211
- if (!this.buffer) return this.yield(this._tree.enter(pos, side, mode));
14212
- return mode & IterMode.ExcludeBuffers ? false : this.enterChild(1, pos, side);
14213
- }
14214
- /// Move to the node's parent node, if this isn't the top node.
14215
- parent() {
14216
- if (!this.buffer) return this.yieldNode(this.mode & IterMode.IncludeAnonymous ? this._tree._parent : this._tree.parent);
14217
- if (this.stack.length) return this.yieldBuf(this.stack.pop());
14218
- let parent = this.mode & IterMode.IncludeAnonymous ? this.buffer.parent : this.buffer.parent.nextSignificantParent();
14219
- this.buffer = null;
14220
- return this.yieldNode(parent);
14221
- }
14222
- /// @internal
14223
- sibling(dir) {
14224
- if (!this.buffer) return !this._tree._parent ? false : this.yield(this._tree.index < 0 ? null : this._tree._parent.nextChild(this._tree.index + dir, dir, 0, 4 /* Side.DontCare */, this.mode));
14225
- let {
14226
- buffer
14227
- } = this.buffer,
14228
- d = this.stack.length - 1;
14229
- if (dir < 0) {
14230
- let parentStart = d < 0 ? 0 : this.stack[d] + 4;
14231
- if (this.index != parentStart) return this.yieldBuf(buffer.findChild(parentStart, this.index, -1, 0, 4 /* Side.DontCare */));
14232
- } else {
14233
- let after = buffer.buffer[this.index + 3];
14234
- if (after < (d < 0 ? buffer.buffer.length : buffer.buffer[this.stack[d] + 3])) return this.yieldBuf(after);
14235
- }
14236
- return d < 0 ? this.yield(this.buffer.parent.nextChild(this.buffer.index + dir, dir, 0, 4 /* Side.DontCare */, this.mode)) : false;
14237
- }
14238
- /// Move to this node's next sibling, if any.
14239
- nextSibling() {
14240
- return this.sibling(1);
14241
- }
14242
- /// Move to this node's previous sibling, if any.
14243
- prevSibling() {
14244
- return this.sibling(-1);
14245
- }
14246
- atLastNode(dir) {
14247
- let index,
14248
- parent,
14249
- {
14250
- buffer
14251
- } = this;
14252
- if (buffer) {
14253
- if (dir > 0) {
14254
- if (this.index < buffer.buffer.buffer.length) return false;
14255
- } else {
14256
- for (let i = 0; i < this.index; i++) if (buffer.buffer.buffer[i + 3] < this.index) return false;
14257
- }
14258
- ({
14259
- index,
14260
- parent
14261
- } = buffer);
14262
- } else {
14263
- ({
14264
- index,
14265
- _parent: parent
14266
- } = this._tree);
14267
- }
14268
- for (; parent; ({
14269
- index,
14270
- _parent: parent
14271
- } = parent)) {
14272
- if (index > -1) for (let i = index + dir, e = dir < 0 ? -1 : parent._tree.children.length; i != e; i += dir) {
14273
- let child = parent._tree.children[i];
14274
- if (this.mode & IterMode.IncludeAnonymous || child instanceof TreeBuffer || !child.type.isAnonymous || hasChild(child)) return false;
14275
- }
14276
- }
14277
- return true;
14278
- }
14279
- move(dir, enter) {
14280
- if (enter && this.enterChild(dir, 0, 4 /* Side.DontCare */)) return true;
14281
- for (;;) {
14282
- if (this.sibling(dir)) return true;
14283
- if (this.atLastNode(dir) || !this.parent()) return false;
14284
- }
14285
- }
14286
- /// Move to the next node in a
14287
- /// [pre-order](https://en.wikipedia.org/wiki/Tree_traversal#Pre-order,_NLR)
14288
- /// traversal, going from a node to its first child or, if the
14289
- /// current node is empty or `enter` is false, its next sibling or
14290
- /// the next sibling of the first parent node that has one.
14291
- next(enter = true) {
14292
- return this.move(1, enter);
14293
- }
14294
- /// Move to the next node in a last-to-first pre-order traveral. A
14295
- /// node is followed by its last child or, if it has none, its
14296
- /// previous sibling or the previous sibling of the first parent
14297
- /// node that has one.
14298
- prev(enter = true) {
14299
- return this.move(-1, enter);
14300
- }
14301
- /// Move the cursor to the innermost node that covers `pos`. If
14302
- /// `side` is -1, it will enter nodes that end at `pos`. If it is 1,
14303
- /// it will enter nodes that start at `pos`.
14304
- moveTo(pos, side = 0) {
14305
- // Move up to a node that actually holds the position, if possible
14306
- while (this.from == this.to || (side < 1 ? this.from >= pos : this.from > pos) || (side > -1 ? this.to <= pos : this.to < pos)) if (!this.parent()) break;
14307
- // Then scan down into child nodes as far as possible
14308
- while (this.enterChild(1, pos, side)) {}
14309
- return this;
14310
- }
14311
- /// Get a [syntax node](#common.SyntaxNode) at the cursor's current
14312
- /// position.
14313
- get node() {
14314
- if (!this.buffer) return this._tree;
14315
- let cache = this.bufferNode,
14316
- result = null,
14317
- depth = 0;
14318
- if (cache && cache.context == this.buffer) {
14319
- scan: for (let index = this.index, d = this.stack.length; d >= 0;) {
14320
- for (let c = cache; c; c = c._parent) if (c.index == index) {
14321
- if (index == this.index) return c;
14322
- result = c;
14323
- depth = d + 1;
14324
- break scan;
14325
- }
14326
- index = this.stack[--d];
14327
- }
14328
- }
14329
- for (let i = depth; i < this.stack.length; i++) result = new BufferNode(this.buffer, result, this.stack[i]);
14330
- return this.bufferNode = new BufferNode(this.buffer, result, this.index);
14331
- }
14332
- /// Get the [tree](#common.Tree) that represents the current node, if
14333
- /// any. Will return null when the node is in a [tree
14334
- /// buffer](#common.TreeBuffer).
14335
- get tree() {
14336
- return this.buffer ? null : this._tree._tree;
14337
- }
14338
- /// Iterate over the current node and all its descendants, calling
14339
- /// `enter` when entering a node and `leave`, if given, when leaving
14340
- /// one. When `enter` returns `false`, any children of that node are
14341
- /// skipped, and `leave` isn't called for it.
14342
- iterate(enter, leave) {
14343
- for (let depth = 0;;) {
14344
- let mustLeave = false;
14345
- if (this.type.isAnonymous || enter(this) !== false) {
14346
- if (this.firstChild()) {
14347
- depth++;
14348
- continue;
14349
- }
14350
- if (!this.type.isAnonymous) mustLeave = true;
14351
- }
14352
- for (;;) {
14353
- if (mustLeave && leave) leave(this);
14354
- mustLeave = this.type.isAnonymous;
14355
- if (this.nextSibling()) break;
14356
- if (!depth) return;
14357
- this.parent();
14358
- depth--;
14359
- mustLeave = true;
14360
- }
14361
- }
14362
- }
14363
- /// Test whether the current node matches a given context—a sequence
14364
- /// of direct parent node names. Empty strings in the context array
14365
- /// are treated as wildcards.
14366
- matchContext(context) {
14367
- if (!this.buffer) return matchNodeContext(this.node, context);
14368
- let {
14369
- buffer
14370
- } = this.buffer,
14371
- {
14372
- types
14373
- } = buffer.set;
14374
- for (let i = context.length - 1, d = this.stack.length - 1; i >= 0; d--) {
14375
- if (d < 0) return matchNodeContext(this.node, context, i);
14376
- let type = types[buffer.buffer[this.stack[d]]];
14377
- if (!type.isAnonymous) {
14378
- if (context[i] && context[i] != type.name) return false;
14379
- i--;
14380
- }
14381
- }
14382
- return true;
14383
- }
14384
- }
14385
- function hasChild(tree) {
14386
- return tree.children.some(ch => ch instanceof TreeBuffer || !ch.type.isAnonymous || hasChild(ch));
14387
- }
14388
- function buildTree(data) {
14389
- var _a;
14390
- let {
14391
- buffer,
14392
- nodeSet,
14393
- maxBufferLength = DefaultBufferLength,
14394
- reused = [],
14395
- minRepeatType = nodeSet.types.length
14396
- } = data;
14397
- let cursor = Array.isArray(buffer) ? new FlatBufferCursor(buffer, buffer.length) : buffer;
14398
- let types = nodeSet.types;
14399
- let contextHash = 0,
14400
- lookAhead = 0;
14401
- function takeNode(parentStart, minPos, children, positions, inRepeat) {
14402
- let {
14403
- id,
14404
- start,
14405
- end,
14406
- size
14407
- } = cursor;
14408
- let lookAheadAtStart = lookAhead;
14409
- while (size < 0) {
14410
- cursor.next();
14411
- if (size == -1 /* SpecialRecord.Reuse */) {
14412
- let node = reused[id];
14413
- children.push(node);
14414
- positions.push(start - parentStart);
14415
- return;
14416
- } else if (size == -3 /* SpecialRecord.ContextChange */) {
14417
- // Context change
14418
- contextHash = id;
14419
- return;
14420
- } else if (size == -4 /* SpecialRecord.LookAhead */) {
14421
- lookAhead = id;
14422
- return;
14423
- } else {
14424
- throw new RangeError(`Unrecognized record size: ${size}`);
14425
- }
14426
- }
14427
- let type = types[id],
14428
- node,
14429
- buffer;
14430
- let startPos = start - parentStart;
14431
- if (end - start <= maxBufferLength && (buffer = findBufferSize(cursor.pos - minPos, inRepeat))) {
14432
- // Small enough for a buffer, and no reused nodes inside
14433
- let data = new Uint16Array(buffer.size - buffer.skip);
14434
- let endPos = cursor.pos - buffer.size,
14435
- index = data.length;
14436
- while (cursor.pos > endPos) index = copyToBuffer(buffer.start, data, index);
14437
- node = new TreeBuffer(data, end - buffer.start, nodeSet);
14438
- startPos = buffer.start - parentStart;
14439
- } else {
14440
- // Make it a node
14441
- let endPos = cursor.pos - size;
14442
- cursor.next();
14443
- let localChildren = [],
14444
- localPositions = [];
14445
- let localInRepeat = id >= minRepeatType ? id : -1;
14446
- let lastGroup = 0,
14447
- lastEnd = end;
14448
- while (cursor.pos > endPos) {
14449
- if (localInRepeat >= 0 && cursor.id == localInRepeat && cursor.size >= 0) {
14450
- if (cursor.end <= lastEnd - maxBufferLength) {
14451
- makeRepeatLeaf(localChildren, localPositions, start, lastGroup, cursor.end, lastEnd, localInRepeat, lookAheadAtStart);
14452
- lastGroup = localChildren.length;
14453
- lastEnd = cursor.end;
14454
- }
14455
- cursor.next();
14456
- } else {
14457
- takeNode(start, endPos, localChildren, localPositions, localInRepeat);
14458
- }
14459
- }
14460
- if (localInRepeat >= 0 && lastGroup > 0 && lastGroup < localChildren.length) makeRepeatLeaf(localChildren, localPositions, start, lastGroup, start, lastEnd, localInRepeat, lookAheadAtStart);
14461
- localChildren.reverse();
14462
- localPositions.reverse();
14463
- if (localInRepeat > -1 && lastGroup > 0) {
14464
- let make = makeBalanced(type);
14465
- node = balanceRange(type, localChildren, localPositions, 0, localChildren.length, 0, end - start, make, make);
14466
- } else {
14467
- node = makeTree(type, localChildren, localPositions, end - start, lookAheadAtStart - end);
14468
- }
14469
- }
14470
- children.push(node);
14471
- positions.push(startPos);
14472
- }
14473
- function makeBalanced(type) {
14474
- return (children, positions, length) => {
14475
- let lookAhead = 0,
14476
- lastI = children.length - 1,
14477
- last,
14478
- lookAheadProp;
14479
- if (lastI >= 0 && (last = children[lastI]) instanceof Tree) {
14480
- if (!lastI && last.type == type && last.length == length) return last;
14481
- if (lookAheadProp = last.prop(NodeProp.lookAhead)) lookAhead = positions[lastI] + last.length + lookAheadProp;
14482
- }
14483
- return makeTree(type, children, positions, length, lookAhead);
14484
- };
14485
- }
14486
- function makeRepeatLeaf(children, positions, base, i, from, to, type, lookAhead) {
14487
- let localChildren = [],
14488
- localPositions = [];
14489
- while (children.length > i) {
14490
- localChildren.push(children.pop());
14491
- localPositions.push(positions.pop() + base - from);
14492
- }
14493
- children.push(makeTree(nodeSet.types[type], localChildren, localPositions, to - from, lookAhead - to));
14494
- positions.push(from - base);
14495
- }
14496
- function makeTree(type, children, positions, length, lookAhead = 0, props) {
14497
- if (contextHash) {
14498
- let pair = [NodeProp.contextHash, contextHash];
14499
- props = props ? [pair].concat(props) : [pair];
14500
- }
14501
- if (lookAhead > 25) {
14502
- let pair = [NodeProp.lookAhead, lookAhead];
14503
- props = props ? [pair].concat(props) : [pair];
14504
- }
14505
- return new Tree(type, children, positions, length, props);
14506
- }
14507
- function findBufferSize(maxSize, inRepeat) {
14508
- // Scan through the buffer to find previous siblings that fit
14509
- // together in a TreeBuffer, and don't contain any reused nodes
14510
- // (which can't be stored in a buffer).
14511
- // If `inRepeat` is > -1, ignore node boundaries of that type for
14512
- // nesting, but make sure the end falls either at the start
14513
- // (`maxSize`) or before such a node.
14514
- let fork = cursor.fork();
14515
- let size = 0,
14516
- start = 0,
14517
- skip = 0,
14518
- minStart = fork.end - maxBufferLength;
14519
- let result = {
14520
- size: 0,
14521
- start: 0,
14522
- skip: 0
14523
- };
14524
- scan: for (let minPos = fork.pos - maxSize; fork.pos > minPos;) {
14525
- let nodeSize = fork.size;
14526
- // Pretend nested repeat nodes of the same type don't exist
14527
- if (fork.id == inRepeat && nodeSize >= 0) {
14528
- // Except that we store the current state as a valid return
14529
- // value.
14530
- result.size = size;
14531
- result.start = start;
14532
- result.skip = skip;
14533
- skip += 4;
14534
- size += 4;
14535
- fork.next();
14536
- continue;
14537
- }
14538
- let startPos = fork.pos - nodeSize;
14539
- if (nodeSize < 0 || startPos < minPos || fork.start < minStart) break;
14540
- let localSkipped = fork.id >= minRepeatType ? 4 : 0;
14541
- let nodeStart = fork.start;
14542
- fork.next();
14543
- while (fork.pos > startPos) {
14544
- if (fork.size < 0) {
14545
- if (fork.size == -3 /* SpecialRecord.ContextChange */) localSkipped += 4;else break scan;
14546
- } else if (fork.id >= minRepeatType) {
14547
- localSkipped += 4;
14548
- }
14549
- fork.next();
14550
- }
14551
- start = nodeStart;
14552
- size += nodeSize;
14553
- skip += localSkipped;
14554
- }
14555
- if (inRepeat < 0 || size == maxSize) {
14556
- result.size = size;
14557
- result.start = start;
14558
- result.skip = skip;
14559
- }
14560
- return result.size > 4 ? result : undefined;
14561
- }
14562
- function copyToBuffer(bufferStart, buffer, index) {
14563
- let {
14564
- id,
14565
- start,
14566
- end,
14567
- size
14568
- } = cursor;
14569
- cursor.next();
14570
- if (size >= 0 && id < minRepeatType) {
14571
- let startIndex = index;
14572
- if (size > 4) {
14573
- let endPos = cursor.pos - (size - 4);
14574
- while (cursor.pos > endPos) index = copyToBuffer(bufferStart, buffer, index);
14575
- }
14576
- buffer[--index] = startIndex;
14577
- buffer[--index] = end - bufferStart;
14578
- buffer[--index] = start - bufferStart;
14579
- buffer[--index] = id;
14580
- } else if (size == -3 /* SpecialRecord.ContextChange */) {
14581
- contextHash = id;
14582
- } else if (size == -4 /* SpecialRecord.LookAhead */) {
14583
- lookAhead = id;
14584
- }
14585
- return index;
14586
- }
14587
- let children = [],
14588
- positions = [];
14589
- while (cursor.pos > 0) takeNode(data.start || 0, data.bufferStart || 0, children, positions, -1);
14590
- let length = (_a = data.length) !== null && _a !== void 0 ? _a : children.length ? positions[0] + children[0].length : 0;
14591
- return new Tree(types[data.topID], children.reverse(), positions.reverse(), length);
14592
- }
14593
- const nodeSizeCache = new WeakMap();
14594
- function nodeSize(balanceType, node) {
14595
- if (!balanceType.isAnonymous || node instanceof TreeBuffer || node.type != balanceType) return 1;
14596
- let size = nodeSizeCache.get(node);
14597
- if (size == null) {
14598
- size = 1;
14599
- for (let child of node.children) {
14600
- if (child.type != balanceType || !(child instanceof Tree)) {
14601
- size = 1;
14602
- break;
14603
- }
14604
- size += nodeSize(balanceType, child);
14605
- }
14606
- nodeSizeCache.set(node, size);
14607
- }
14608
- return size;
14609
- }
14610
- function balanceRange(
14611
- // The type the balanced tree's inner nodes.
14612
- balanceType,
14613
- // The direct children and their positions
14614
- children, positions,
14615
- // The index range in children/positions to use
14616
- from, to,
14617
- // The start position of the nodes, relative to their parent.
14618
- start,
14619
- // Length of the outer node
14620
- length,
14621
- // Function to build the top node of the balanced tree
14622
- mkTop,
14623
- // Function to build internal nodes for the balanced tree
14624
- mkTree) {
14625
- let total = 0;
14626
- for (let i = from; i < to; i++) total += nodeSize(balanceType, children[i]);
14627
- let maxChild = Math.ceil(total * 1.5 / 8 /* Balance.BranchFactor */);
14628
- let localChildren = [],
14629
- localPositions = [];
14630
- function divide(children, positions, from, to, offset) {
14631
- for (let i = from; i < to;) {
14632
- let groupFrom = i,
14633
- groupStart = positions[i],
14634
- groupSize = nodeSize(balanceType, children[i]);
14635
- i++;
14636
- for (; i < to; i++) {
14637
- let nextSize = nodeSize(balanceType, children[i]);
14638
- if (groupSize + nextSize >= maxChild) break;
14639
- groupSize += nextSize;
14640
- }
14641
- if (i == groupFrom + 1) {
14642
- if (groupSize > maxChild) {
14643
- let only = children[groupFrom]; // Only trees can have a size > 1
14644
- divide(only.children, only.positions, 0, only.children.length, positions[groupFrom] + offset);
14645
- continue;
14646
- }
14647
- localChildren.push(children[groupFrom]);
14648
- } else {
14649
- let length = positions[i - 1] + children[i - 1].length - groupStart;
14650
- localChildren.push(balanceRange(balanceType, children, positions, groupFrom, i, groupStart, length, null, mkTree));
14651
- }
14652
- localPositions.push(groupStart + offset - start);
14653
- }
14654
- }
14655
- divide(children, positions, from, to, 0);
14656
- return (mkTop || mkTree)(localChildren, localPositions, length);
14657
- }
14658
- /// Provides a way to associate values with pieces of trees. As long
14659
- /// as that part of the tree is reused, the associated values can be
14660
- /// retrieved from an updated tree.
14661
- class NodeWeakMap {
14662
- constructor() {
14663
- this.map = new WeakMap();
14664
- }
14665
- setBuffer(buffer, index, value) {
14666
- let inner = this.map.get(buffer);
14667
- if (!inner) this.map.set(buffer, inner = new Map());
14668
- inner.set(index, value);
14669
- }
14670
- getBuffer(buffer, index) {
14671
- let inner = this.map.get(buffer);
14672
- return inner && inner.get(index);
14673
- }
14674
- /// Set the value for this syntax node.
14675
- set(node, value) {
14676
- if (node instanceof BufferNode) this.setBuffer(node.context.buffer, node.index, value);else if (node instanceof TreeNode) this.map.set(node.tree, value);
14677
- }
14678
- /// Retrieve value for this syntax node, if it exists in the map.
14679
- get(node) {
14680
- return node instanceof BufferNode ? this.getBuffer(node.context.buffer, node.index) : node instanceof TreeNode ? this.map.get(node.tree) : undefined;
14681
- }
14682
- /// Set the value for the node that a cursor currently points to.
14683
- cursorSet(cursor, value) {
14684
- if (cursor.buffer) this.setBuffer(cursor.buffer.buffer, cursor.index, value);else this.map.set(cursor.tree, value);
14685
- }
14686
- /// Retrieve the value for the node that a cursor currently points
14687
- /// to.
14688
- cursorGet(cursor) {
14689
- return cursor.buffer ? this.getBuffer(cursor.buffer.buffer, cursor.index) : this.map.get(cursor.tree);
14690
- }
14691
- }
14692
-
14693
- /// Tree fragments are used during [incremental
14694
- /// parsing](#common.Parser.startParse) to track parts of old trees
14695
- /// that can be reused in a new parse. An array of fragments is used
14696
- /// to track regions of an old tree whose nodes might be reused in new
14697
- /// parses. Use the static
14698
- /// [`applyChanges`](#common.TreeFragment^applyChanges) method to
14699
- /// update fragments for document changes.
14700
- class TreeFragment {
14701
- /// Construct a tree fragment. You'll usually want to use
14702
- /// [`addTree`](#common.TreeFragment^addTree) and
14703
- /// [`applyChanges`](#common.TreeFragment^applyChanges) instead of
14704
- /// calling this directly.
14705
- constructor(
14706
- /// The start of the unchanged range pointed to by this fragment.
14707
- /// This refers to an offset in the _updated_ document (as opposed
14708
- /// to the original tree).
14709
- from,
14710
- /// The end of the unchanged range.
14711
- to,
14712
- /// The tree that this fragment is based on.
14713
- tree,
14714
- /// The offset between the fragment's tree and the document that
14715
- /// this fragment can be used against. Add this when going from
14716
- /// document to tree positions, subtract it to go from tree to
14717
- /// document positions.
14718
- offset, openStart = false, openEnd = false) {
14719
- this.from = from;
14720
- this.to = to;
14721
- this.tree = tree;
14722
- this.offset = offset;
14723
- this.open = (openStart ? 1 /* Open.Start */ : 0) | (openEnd ? 2 /* Open.End */ : 0);
14724
- }
14725
- /// Whether the start of the fragment represents the start of a
14726
- /// parse, or the end of a change. (In the second case, it may not
14727
- /// be safe to reuse some nodes at the start, depending on the
14728
- /// parsing algorithm.)
14729
- get openStart() {
14730
- return (this.open & 1 /* Open.Start */) > 0;
14731
- }
14732
- /// Whether the end of the fragment represents the end of a
14733
- /// full-document parse, or the start of a change.
14734
- get openEnd() {
14735
- return (this.open & 2 /* Open.End */) > 0;
14736
- }
14737
- /// Create a set of fragments from a freshly parsed tree, or update
14738
- /// an existing set of fragments by replacing the ones that overlap
14739
- /// with a tree with content from the new tree. When `partial` is
14740
- /// true, the parse is treated as incomplete, and the resulting
14741
- /// fragment has [`openEnd`](#common.TreeFragment.openEnd) set to
14742
- /// true.
14743
- static addTree(tree, fragments = [], partial = false) {
14744
- let result = [new TreeFragment(0, tree.length, tree, 0, false, partial)];
14745
- for (let f of fragments) if (f.to > tree.length) result.push(f);
14746
- return result;
14747
- }
14748
- /// Apply a set of edits to an array of fragments, removing or
14749
- /// splitting fragments as necessary to remove edited ranges, and
14750
- /// adjusting offsets for fragments that moved.
14751
- static applyChanges(fragments, changes, minGap = 128) {
14752
- if (!changes.length) return fragments;
14753
- let result = [];
14754
- let fI = 1,
14755
- nextF = fragments.length ? fragments[0] : null;
14756
- for (let cI = 0, pos = 0, off = 0;; cI++) {
14757
- let nextC = cI < changes.length ? changes[cI] : null;
14758
- let nextPos = nextC ? nextC.fromA : 1e9;
14759
- if (nextPos - pos >= minGap) while (nextF && nextF.from < nextPos) {
14760
- let cut = nextF;
14761
- if (pos >= cut.from || nextPos <= cut.to || off) {
14762
- let fFrom = Math.max(cut.from, pos) - off,
14763
- fTo = Math.min(cut.to, nextPos) - off;
14764
- cut = fFrom >= fTo ? null : new TreeFragment(fFrom, fTo, cut.tree, cut.offset + off, cI > 0, !!nextC);
14765
- }
14766
- if (cut) result.push(cut);
14767
- if (nextF.to > nextPos) break;
14768
- nextF = fI < fragments.length ? fragments[fI++] : null;
14769
- }
14770
- if (!nextC) break;
14771
- pos = nextC.toA;
14772
- off = nextC.toA - nextC.toB;
14773
- }
14774
- return result;
14775
- }
14776
- }
14777
- /// A superclass that parsers should extend.
14778
- class Parser {
14779
- /// Start a parse, returning a [partial parse](#common.PartialParse)
14780
- /// object. [`fragments`](#common.TreeFragment) can be passed in to
14781
- /// make the parse incremental.
14782
- ///
14783
- /// By default, the entire input is parsed. You can pass `ranges`,
14784
- /// which should be a sorted array of non-empty, non-overlapping
14785
- /// ranges, to parse only those ranges. The tree returned in that
14786
- /// case will start at `ranges[0].from`.
14787
- startParse(input, fragments, ranges) {
14788
- if (typeof input == "string") input = new StringInput(input);
14789
- ranges = !ranges ? [new Range(0, input.length)] : ranges.length ? ranges.map(r => new Range(r.from, r.to)) : [new Range(0, 0)];
14790
- return this.createParse(input, fragments || [], ranges);
14791
- }
14792
- /// Run a full parse, returning the resulting tree.
14793
- parse(input, fragments, ranges) {
14794
- let parse = this.startParse(input, fragments, ranges);
14795
- for (;;) {
14796
- let done = parse.advance();
14797
- if (done) return done;
14798
- }
14799
- }
14800
- }
14801
- class StringInput {
14802
- constructor(string) {
14803
- this.string = string;
14804
- }
14805
- get length() {
14806
- return this.string.length;
14807
- }
14808
- chunk(from) {
14809
- return this.string.slice(from);
14810
- }
14811
- get lineChunks() {
14812
- return false;
14813
- }
14814
- read(from, to) {
14815
- return this.string.slice(from, to);
14816
- }
14817
- }
14818
-
14819
- /// Create a parse wrapper that, after the inner parse completes,
14820
- /// scans its tree for mixed language regions with the `nest`
14821
- /// function, runs the resulting [inner parses](#common.NestedParse),
14822
- /// and then [mounts](#common.NodeProp^mounted) their results onto the
14823
- /// tree.
14824
- function parseMixed(nest) {
14825
- return (parse, input, fragments, ranges) => new MixedParse(parse, nest, input, fragments, ranges);
14826
- }
14827
- class InnerParse {
14828
- constructor(parser, parse, overlay, target, ranges) {
14829
- this.parser = parser;
14830
- this.parse = parse;
14831
- this.overlay = overlay;
14832
- this.target = target;
14833
- this.ranges = ranges;
14834
- }
14835
- }
14836
- class ActiveOverlay {
14837
- constructor(parser, predicate, mounts, index, start, target, prev) {
14838
- this.parser = parser;
14839
- this.predicate = predicate;
14840
- this.mounts = mounts;
14841
- this.index = index;
14842
- this.start = start;
14843
- this.target = target;
14844
- this.prev = prev;
14845
- this.depth = 0;
14846
- this.ranges = [];
14847
- }
14848
- }
14849
- const stoppedInner = new NodeProp({
14850
- perNode: true
14851
- });
14852
- class MixedParse {
14853
- constructor(base, nest, input, fragments, ranges) {
14854
- this.nest = nest;
14855
- this.input = input;
14856
- this.fragments = fragments;
14857
- this.ranges = ranges;
14858
- this.inner = [];
14859
- this.innerDone = 0;
14860
- this.baseTree = null;
14861
- this.stoppedAt = null;
14862
- this.baseParse = base;
14863
- }
14864
- advance() {
14865
- if (this.baseParse) {
14866
- let done = this.baseParse.advance();
14867
- if (!done) return null;
14868
- this.baseParse = null;
14869
- this.baseTree = done;
14870
- this.startInner();
14871
- if (this.stoppedAt != null) for (let inner of this.inner) inner.parse.stopAt(this.stoppedAt);
14872
- }
14873
- if (this.innerDone == this.inner.length) {
14874
- let result = this.baseTree;
14875
- if (this.stoppedAt != null) result = new Tree(result.type, result.children, result.positions, result.length, result.propValues.concat([[stoppedInner, this.stoppedAt]]));
14876
- return result;
14877
- }
14878
- let inner = this.inner[this.innerDone],
14879
- done = inner.parse.advance();
14880
- if (done) {
14881
- this.innerDone++;
14882
- // This is a somewhat dodgy but super helpful hack where we
14883
- // patch up nodes created by the inner parse (and thus
14884
- // presumably not aliased anywhere else) to hold the information
14885
- // about the inner parse.
14886
- let props = Object.assign(Object.create(null), inner.target.props);
14887
- props[NodeProp.mounted.id] = new MountedTree(done, inner.overlay, inner.parser);
14888
- inner.target.props = props;
14889
- }
14890
- return null;
14891
- }
14892
- get parsedPos() {
14893
- if (this.baseParse) return 0;
14894
- let pos = this.input.length;
14895
- for (let i = this.innerDone; i < this.inner.length; i++) {
14896
- if (this.inner[i].ranges[0].from < pos) pos = Math.min(pos, this.inner[i].parse.parsedPos);
14897
- }
14898
- return pos;
14899
- }
14900
- stopAt(pos) {
14901
- this.stoppedAt = pos;
14902
- if (this.baseParse) this.baseParse.stopAt(pos);else for (let i = this.innerDone; i < this.inner.length; i++) this.inner[i].parse.stopAt(pos);
14903
- }
14904
- startInner() {
14905
- let fragmentCursor = new FragmentCursor(this.fragments);
14906
- let overlay = null;
14907
- let covered = null;
14908
- let cursor = new TreeCursor(new TreeNode(this.baseTree, this.ranges[0].from, 0, null), IterMode.IncludeAnonymous | IterMode.IgnoreMounts);
14909
- scan: for (let nest, isCovered; this.stoppedAt == null || cursor.from < this.stoppedAt;) {
14910
- let enter = true,
14911
- range;
14912
- if (fragmentCursor.hasNode(cursor)) {
14913
- if (overlay) {
14914
- let match = overlay.mounts.find(m => m.frag.from <= cursor.from && m.frag.to >= cursor.to && m.mount.overlay);
14915
- if (match) for (let r of match.mount.overlay) {
14916
- let from = r.from + match.pos,
14917
- to = r.to + match.pos;
14918
- if (from >= cursor.from && to <= cursor.to && !overlay.ranges.some(r => r.from < to && r.to > from)) overlay.ranges.push({
14919
- from,
14920
- to
14921
- });
14922
- }
14923
- }
14924
- enter = false;
14925
- } else if (covered && (isCovered = checkCover(covered.ranges, cursor.from, cursor.to))) {
14926
- enter = isCovered != 2 /* Cover.Full */;
14927
- } else if (!cursor.type.isAnonymous && cursor.from < cursor.to && (nest = this.nest(cursor, this.input))) {
14928
- if (!cursor.tree) materialize(cursor);
14929
- let oldMounts = fragmentCursor.findMounts(cursor.from, nest.parser);
14930
- if (typeof nest.overlay == "function") {
14931
- overlay = new ActiveOverlay(nest.parser, nest.overlay, oldMounts, this.inner.length, cursor.from, cursor.tree, overlay);
14932
- } else {
14933
- let ranges = punchRanges(this.ranges, nest.overlay || [new Range(cursor.from, cursor.to)]);
14934
- if (ranges.length) this.inner.push(new InnerParse(nest.parser, nest.parser.startParse(this.input, enterFragments(oldMounts, ranges), ranges), nest.overlay ? nest.overlay.map(r => new Range(r.from - cursor.from, r.to - cursor.from)) : null, cursor.tree, ranges));
14935
- if (!nest.overlay) enter = false;else if (ranges.length) covered = {
14936
- ranges,
14937
- depth: 0,
14938
- prev: covered
14939
- };
14940
- }
14941
- } else if (overlay && (range = overlay.predicate(cursor))) {
14942
- if (range === true) range = new Range(cursor.from, cursor.to);
14943
- if (range.from < range.to) overlay.ranges.push(range);
14944
- }
14945
- if (enter && cursor.firstChild()) {
14946
- if (overlay) overlay.depth++;
14947
- if (covered) covered.depth++;
14948
- } else {
14949
- for (;;) {
14950
- if (cursor.nextSibling()) break;
14951
- if (!cursor.parent()) break scan;
14952
- if (overlay && ! --overlay.depth) {
14953
- let ranges = punchRanges(this.ranges, overlay.ranges);
14954
- if (ranges.length) this.inner.splice(overlay.index, 0, new InnerParse(overlay.parser, overlay.parser.startParse(this.input, enterFragments(overlay.mounts, ranges), ranges), overlay.ranges.map(r => new Range(r.from - overlay.start, r.to - overlay.start)), overlay.target, ranges));
14955
- overlay = overlay.prev;
14956
- }
14957
- if (covered && ! --covered.depth) covered = covered.prev;
14958
- }
14959
- }
14960
- }
14961
- }
14962
- }
14963
- function checkCover(covered, from, to) {
14964
- for (let range of covered) {
14965
- if (range.from >= to) break;
14966
- if (range.to > from) return range.from <= from && range.to >= to ? 2 /* Cover.Full */ : 1 /* Cover.Partial */;
14967
- }
14968
-
14969
- return 0 /* Cover.None */;
14970
- }
14971
- // Take a piece of buffer and convert it into a stand-alone
14972
- // TreeBuffer.
14973
- function sliceBuf(buf, startI, endI, nodes, positions, off) {
14974
- if (startI < endI) {
14975
- let from = buf.buffer[startI + 1];
14976
- nodes.push(buf.slice(startI, endI, from));
14977
- positions.push(from - off);
14978
- }
14979
- }
14980
- // This function takes a node that's in a buffer, and converts it, and
14981
- // its parent buffer nodes, into a Tree. This is again acting on the
14982
- // assumption that the trees and buffers have been constructed by the
14983
- // parse that was ran via the mix parser, and thus aren't shared with
14984
- // any other code, making violations of the immutability safe.
14985
- function materialize(cursor) {
14986
- let {
14987
- node
14988
- } = cursor,
14989
- depth = 0;
14990
- // Scan up to the nearest tree
14991
- do {
14992
- cursor.parent();
14993
- depth++;
14994
- } while (!cursor.tree);
14995
- // Find the index of the buffer in that tree
14996
- let i = 0,
14997
- base = cursor.tree,
14998
- off = 0;
14999
- for (;; i++) {
15000
- off = base.positions[i] + cursor.from;
15001
- if (off <= node.from && off + base.children[i].length >= node.to) break;
15002
- }
15003
- let buf = base.children[i],
15004
- b = buf.buffer;
15005
- // Split a level in the buffer, putting the nodes before and after
15006
- // the child that contains `node` into new buffers.
15007
- function split(startI, endI, type, innerOffset, length) {
15008
- let i = startI;
15009
- while (b[i + 2] + off <= node.from) i = b[i + 3];
15010
- let children = [],
15011
- positions = [];
15012
- sliceBuf(buf, startI, i, children, positions, innerOffset);
15013
- let from = b[i + 1],
15014
- to = b[i + 2];
15015
- let isTarget = from + off == node.from && to + off == node.to && b[i] == node.type.id;
15016
- children.push(isTarget ? node.toTree() : split(i + 4, b[i + 3], buf.set.types[b[i]], from, to - from));
15017
- positions.push(from - innerOffset);
15018
- sliceBuf(buf, b[i + 3], endI, children, positions, innerOffset);
15019
- return new Tree(type, children, positions, length);
15020
- }
15021
- base.children[i] = split(0, b.length, NodeType.none, 0, buf.length);
15022
- // Move the cursor back to the target node
15023
- for (let d = 0; d <= depth; d++) cursor.childAfter(node.from);
15024
- }
15025
- class StructureCursor {
15026
- constructor(root, offset) {
15027
- this.offset = offset;
15028
- this.done = false;
15029
- this.cursor = root.cursor(IterMode.IncludeAnonymous | IterMode.IgnoreMounts);
15030
- }
15031
- // Move to the first node (in pre-order) that starts at or after `pos`.
15032
- moveTo(pos) {
15033
- let {
15034
- cursor
15035
- } = this,
15036
- p = pos - this.offset;
15037
- while (!this.done && cursor.from < p) {
15038
- if (cursor.to >= pos && cursor.enter(p, 1, IterMode.IgnoreOverlays | IterMode.ExcludeBuffers)) ;else if (!cursor.next(false)) this.done = true;
15039
- }
15040
- }
15041
- hasNode(cursor) {
15042
- this.moveTo(cursor.from);
15043
- if (!this.done && this.cursor.from + this.offset == cursor.from && this.cursor.tree) {
15044
- for (let tree = this.cursor.tree;;) {
15045
- if (tree == cursor.tree) return true;
15046
- if (tree.children.length && tree.positions[0] == 0 && tree.children[0] instanceof Tree) tree = tree.children[0];else break;
15047
- }
15048
- }
15049
- return false;
15050
- }
15051
- }
15052
- class FragmentCursor {
15053
- constructor(fragments) {
15054
- var _a;
15055
- this.fragments = fragments;
15056
- this.curTo = 0;
15057
- this.fragI = 0;
15058
- if (fragments.length) {
15059
- let first = this.curFrag = fragments[0];
15060
- this.curTo = (_a = first.tree.prop(stoppedInner)) !== null && _a !== void 0 ? _a : first.to;
15061
- this.inner = new StructureCursor(first.tree, -first.offset);
15062
- } else {
15063
- this.curFrag = this.inner = null;
15064
- }
15065
- }
15066
- hasNode(node) {
15067
- while (this.curFrag && node.from >= this.curTo) this.nextFrag();
15068
- return this.curFrag && this.curFrag.from <= node.from && this.curTo >= node.to && this.inner.hasNode(node);
15069
- }
15070
- nextFrag() {
15071
- var _a;
15072
- this.fragI++;
15073
- if (this.fragI == this.fragments.length) {
15074
- this.curFrag = this.inner = null;
15075
- } else {
15076
- let frag = this.curFrag = this.fragments[this.fragI];
15077
- this.curTo = (_a = frag.tree.prop(stoppedInner)) !== null && _a !== void 0 ? _a : frag.to;
15078
- this.inner = new StructureCursor(frag.tree, -frag.offset);
15079
- }
15080
- }
15081
- findMounts(pos, parser) {
15082
- var _a;
15083
- let result = [];
15084
- if (this.inner) {
15085
- this.inner.cursor.moveTo(pos, 1);
15086
- for (let pos = this.inner.cursor.node; pos; pos = pos.parent) {
15087
- let mount = (_a = pos.tree) === null || _a === void 0 ? void 0 : _a.prop(NodeProp.mounted);
15088
- if (mount && mount.parser == parser) {
15089
- for (let i = this.fragI; i < this.fragments.length; i++) {
15090
- let frag = this.fragments[i];
15091
- if (frag.from >= pos.to) break;
15092
- if (frag.tree == this.curFrag.tree) result.push({
15093
- frag,
15094
- pos: pos.from - frag.offset,
15095
- mount
15096
- });
15097
- }
15098
- }
15099
- }
15100
- }
15101
- return result;
15102
- }
15103
- }
15104
- function punchRanges(outer, ranges) {
15105
- let copy = null,
15106
- current = ranges;
15107
- for (let i = 1, j = 0; i < outer.length; i++) {
15108
- let gapFrom = outer[i - 1].to,
15109
- gapTo = outer[i].from;
15110
- for (; j < current.length; j++) {
15111
- let r = current[j];
15112
- if (r.from >= gapTo) break;
15113
- if (r.to <= gapFrom) continue;
15114
- if (!copy) current = copy = ranges.slice();
15115
- if (r.from < gapFrom) {
15116
- copy[j] = new Range(r.from, gapFrom);
15117
- if (r.to > gapTo) copy.splice(j + 1, 0, new Range(gapTo, r.to));
15118
- } else if (r.to > gapTo) {
15119
- copy[j--] = new Range(gapTo, r.to);
15120
- } else {
15121
- copy.splice(j--, 1);
15122
- }
15123
- }
15124
- }
15125
- return current;
15126
- }
15127
- function findCoverChanges(a, b, from, to) {
15128
- let iA = 0,
15129
- iB = 0,
15130
- inA = false,
15131
- inB = false,
15132
- pos = -1e9;
15133
- let result = [];
15134
- for (;;) {
15135
- let nextA = iA == a.length ? 1e9 : inA ? a[iA].to : a[iA].from;
15136
- let nextB = iB == b.length ? 1e9 : inB ? b[iB].to : b[iB].from;
15137
- if (inA != inB) {
15138
- let start = Math.max(pos, from),
15139
- end = Math.min(nextA, nextB, to);
15140
- if (start < end) result.push(new Range(start, end));
15141
- }
15142
- pos = Math.min(nextA, nextB);
15143
- if (pos == 1e9) break;
15144
- if (nextA == pos) {
15145
- if (!inA) inA = true;else {
15146
- inA = false;
15147
- iA++;
15148
- }
15149
- }
15150
- if (nextB == pos) {
15151
- if (!inB) inB = true;else {
15152
- inB = false;
15153
- iB++;
15154
- }
15155
- }
15156
- }
15157
- return result;
15158
- }
15159
- // Given a number of fragments for the outer tree, and a set of ranges
15160
- // to parse, find fragments for inner trees mounted around those
15161
- // ranges, if any.
15162
- function enterFragments(mounts, ranges) {
15163
- let result = [];
15164
- for (let {
15165
- pos,
15166
- mount,
15167
- frag
15168
- } of mounts) {
15169
- let startPos = pos + (mount.overlay ? mount.overlay[0].from : 0),
15170
- endPos = startPos + mount.tree.length;
15171
- let from = Math.max(frag.from, startPos),
15172
- to = Math.min(frag.to, endPos);
15173
- if (mount.overlay) {
15174
- let overlay = mount.overlay.map(r => new Range(r.from + pos, r.to + pos));
15175
- let changes = findCoverChanges(ranges, overlay, from, to);
15176
- for (let i = 0, pos = from;; i++) {
15177
- let last = i == changes.length,
15178
- end = last ? to : changes[i].from;
15179
- if (end > pos) result.push(new TreeFragment(pos, end, mount.tree, -startPos, frag.from >= pos || frag.openStart, frag.to <= end || frag.openEnd));
15180
- if (last) break;
15181
- pos = changes[i].to;
15182
- }
15183
- } else {
15184
- result.push(new TreeFragment(from, to, mount.tree, -startPos, frag.from >= startPos || frag.openStart, frag.to <= endPos || frag.openEnd));
15185
- }
15186
- }
15187
- return result;
15188
- }
15189
-
15190
- let nextTagID = 0;
15191
- /// Highlighting tags are markers that denote a highlighting category.
15192
- /// They are [associated](#highlight.styleTags) with parts of a syntax
15193
- /// tree by a language mode, and then mapped to an actual CSS style by
15194
- /// a [highlighter](#highlight.Highlighter).
15195
- ///
15196
- /// Because syntax tree node types and highlight styles have to be
15197
- /// able to talk the same language, CodeMirror uses a mostly _closed_
15198
- /// [vocabulary](#highlight.tags) of syntax tags (as opposed to
15199
- /// traditional open string-based systems, which make it hard for
15200
- /// highlighting themes to cover all the tokens produced by the
15201
- /// various languages).
15202
- ///
15203
- /// It _is_ possible to [define](#highlight.Tag^define) your own
15204
- /// highlighting tags for system-internal use (where you control both
15205
- /// the language package and the highlighter), but such tags will not
15206
- /// be picked up by regular highlighters (though you can derive them
15207
- /// from standard tags to allow highlighters to fall back to those).
15208
- class Tag {
15209
- /// @internal
15210
- constructor(
15211
- /// The set of this tag and all its parent tags, starting with
15212
- /// this one itself and sorted in order of decreasing specificity.
15213
- set,
15214
- /// The base unmodified tag that this one is based on, if it's
15215
- /// modified @internal
15216
- base,
15217
- /// The modifiers applied to this.base @internal
15218
- modified) {
15219
- this.set = set;
15220
- this.base = base;
15221
- this.modified = modified;
15222
- /// @internal
15223
- this.id = nextTagID++;
15224
- }
15225
- /// Define a new tag. If `parent` is given, the tag is treated as a
15226
- /// sub-tag of that parent, and
15227
- /// [highlighters](#highlight.tagHighlighter) that don't mention
15228
- /// this tag will try to fall back to the parent tag (or grandparent
15229
- /// tag, etc).
15230
- static define(parent) {
15231
- if (parent === null || parent === void 0 ? void 0 : parent.base) throw new Error("Can not derive from a modified tag");
15232
- let tag = new Tag([], null, []);
15233
- tag.set.push(tag);
15234
- if (parent) for (let t of parent.set) tag.set.push(t);
15235
- return tag;
15236
- }
15237
- /// Define a tag _modifier_, which is a function that, given a tag,
15238
- /// will return a tag that is a subtag of the original. Applying the
15239
- /// same modifier to a twice tag will return the same value (`m1(t1)
15240
- /// == m1(t1)`) and applying multiple modifiers will, regardless or
15241
- /// order, produce the same tag (`m1(m2(t1)) == m2(m1(t1))`).
15242
- ///
15243
- /// When multiple modifiers are applied to a given base tag, each
15244
- /// smaller set of modifiers is registered as a parent, so that for
15245
- /// example `m1(m2(m3(t1)))` is a subtype of `m1(m2(t1))`,
15246
- /// `m1(m3(t1)`, and so on.
15247
- static defineModifier() {
15248
- let mod = new Modifier();
15249
- return tag => {
15250
- if (tag.modified.indexOf(mod) > -1) return tag;
15251
- return Modifier.get(tag.base || tag, tag.modified.concat(mod).sort((a, b) => a.id - b.id));
15252
- };
15253
- }
15254
- }
15255
- let nextModifierID = 0;
15256
- class Modifier {
15257
- constructor() {
15258
- this.instances = [];
15259
- this.id = nextModifierID++;
15260
- }
15261
- static get(base, mods) {
15262
- if (!mods.length) return base;
15263
- let exists = mods[0].instances.find(t => t.base == base && sameArray(mods, t.modified));
15264
- if (exists) return exists;
15265
- let set = [],
15266
- tag = new Tag(set, base, mods);
15267
- for (let m of mods) m.instances.push(tag);
15268
- let configs = powerSet(mods);
15269
- for (let parent of base.set) if (!parent.modified.length) for (let config of configs) set.push(Modifier.get(parent, config));
15270
- return tag;
15271
- }
15272
- }
15273
- function sameArray(a, b) {
15274
- return a.length == b.length && a.every((x, i) => x == b[i]);
15275
- }
15276
- function powerSet(array) {
15277
- let sets = [[]];
15278
- for (let i = 0; i < array.length; i++) {
15279
- for (let j = 0, e = sets.length; j < e; j++) {
15280
- sets.push(sets[j].concat(array[i]));
15281
- }
15282
- }
15283
- return sets.sort((a, b) => b.length - a.length);
15284
- }
15285
- /// This function is used to add a set of tags to a language syntax
15286
- /// via [`NodeSet.extend`](#common.NodeSet.extend) or
15287
- /// [`LRParser.configure`](#lr.LRParser.configure).
15288
- ///
15289
- /// The argument object maps node selectors to [highlighting
15290
- /// tags](#highlight.Tag) or arrays of tags.
15291
- ///
15292
- /// Node selectors may hold one or more (space-separated) node paths.
15293
- /// Such a path can be a [node name](#common.NodeType.name), or
15294
- /// multiple node names (or `*` wildcards) separated by slash
15295
- /// characters, as in `"Block/Declaration/VariableName"`. Such a path
15296
- /// matches the final node but only if its direct parent nodes are the
15297
- /// other nodes mentioned. A `*` in such a path matches any parent,
15298
- /// but only a single level—wildcards that match multiple parents
15299
- /// aren't supported, both for efficiency reasons and because Lezer
15300
- /// trees make it rather hard to reason about what they would match.)
15301
- ///
15302
- /// A path can be ended with `/...` to indicate that the tag assigned
15303
- /// to the node should also apply to all child nodes, even if they
15304
- /// match their own style (by default, only the innermost style is
15305
- /// used).
15306
- ///
15307
- /// When a path ends in `!`, as in `Attribute!`, no further matching
15308
- /// happens for the node's child nodes, and the entire node gets the
15309
- /// given style.
15310
- ///
15311
- /// In this notation, node names that contain `/`, `!`, `*`, or `...`
15312
- /// must be quoted as JSON strings.
15313
- ///
15314
- /// For example:
15315
- ///
15316
- /// ```javascript
15317
- /// parser.withProps(
15318
- /// styleTags({
15319
- /// // Style Number and BigNumber nodes
15320
- /// "Number BigNumber": tags.number,
15321
- /// // Style Escape nodes whose parent is String
15322
- /// "String/Escape": tags.escape,
15323
- /// // Style anything inside Attributes nodes
15324
- /// "Attributes!": tags.meta,
15325
- /// // Add a style to all content inside Italic nodes
15326
- /// "Italic/...": tags.emphasis,
15327
- /// // Style InvalidString nodes as both `string` and `invalid`
15328
- /// "InvalidString": [tags.string, tags.invalid],
15329
- /// // Style the node named "/" as punctuation
15330
- /// '"/"': tags.punctuation
15331
- /// })
15332
- /// )
15333
- /// ```
15334
- function styleTags(spec) {
15335
- let byName = Object.create(null);
15336
- for (let prop in spec) {
15337
- let tags = spec[prop];
15338
- if (!Array.isArray(tags)) tags = [tags];
15339
- for (let part of prop.split(" ")) if (part) {
15340
- let pieces = [],
15341
- mode = 2 /* Mode.Normal */,
15342
- rest = part;
15343
- for (let pos = 0;;) {
15344
- if (rest == "..." && pos > 0 && pos + 3 == part.length) {
15345
- mode = 1 /* Mode.Inherit */;
15346
- break;
15347
- }
15348
- let m = /^"(?:[^"\\]|\\.)*?"|[^\/!]+/.exec(rest);
15349
- if (!m) throw new RangeError("Invalid path: " + part);
15350
- pieces.push(m[0] == "*" ? "" : m[0][0] == '"' ? JSON.parse(m[0]) : m[0]);
15351
- pos += m[0].length;
15352
- if (pos == part.length) break;
15353
- let next = part[pos++];
15354
- if (pos == part.length && next == "!") {
15355
- mode = 0 /* Mode.Opaque */;
15356
- break;
15357
- }
15358
- if (next != "/") throw new RangeError("Invalid path: " + part);
15359
- rest = part.slice(pos);
15360
- }
15361
- let last = pieces.length - 1,
15362
- inner = pieces[last];
15363
- if (!inner) throw new RangeError("Invalid path: " + part);
15364
- let rule = new Rule(tags, mode, last > 0 ? pieces.slice(0, last) : null);
15365
- byName[inner] = rule.sort(byName[inner]);
15366
- }
15367
- }
15368
- return ruleNodeProp.add(byName);
15369
- }
15370
- const ruleNodeProp = new NodeProp();
15371
- class Rule {
15372
- constructor(tags, mode, context, next) {
15373
- this.tags = tags;
15374
- this.mode = mode;
15375
- this.context = context;
15376
- this.next = next;
15377
- }
15378
- get opaque() {
15379
- return this.mode == 0 /* Mode.Opaque */;
15380
- }
15381
- get inherit() {
15382
- return this.mode == 1 /* Mode.Inherit */;
15383
- }
15384
- sort(other) {
15385
- if (!other || other.depth < this.depth) {
15386
- this.next = other;
15387
- return this;
15388
- }
15389
- other.next = this.sort(other.next);
15390
- return other;
15391
- }
15392
- get depth() {
15393
- return this.context ? this.context.length : 0;
15394
- }
15395
- }
15396
- Rule.empty = new Rule([], 2 /* Mode.Normal */, null);
15397
- /// Define a [highlighter](#highlight.Highlighter) from an array of
15398
- /// tag/class pairs. Classes associated with more specific tags will
15399
- /// take precedence.
15400
- function tagHighlighter(tags, options) {
15401
- let map = Object.create(null);
15402
- for (let style of tags) {
15403
- if (!Array.isArray(style.tag)) map[style.tag.id] = style.class;else for (let tag of style.tag) map[tag.id] = style.class;
15404
- }
15405
- let {
15406
- scope,
15407
- all = null
15408
- } = options || {};
15409
- return {
15410
- style: tags => {
15411
- let cls = all;
15412
- for (let tag of tags) {
15413
- for (let sub of tag.set) {
15414
- let tagClass = map[sub.id];
15415
- if (tagClass) {
15416
- cls = cls ? cls + " " + tagClass : tagClass;
15417
- break;
15418
- }
15419
- }
15420
- }
15421
- return cls;
15422
- },
15423
- scope
15424
- };
15425
- }
15426
- function highlightTags(highlighters, tags) {
15427
- let result = null;
15428
- for (let highlighter of highlighters) {
15429
- let value = highlighter.style(tags);
15430
- if (value) result = result ? result + " " + value : value;
15431
- }
15432
- return result;
15433
- }
15434
- /// Highlight the given [tree](#common.Tree) with the given
15435
- /// [highlighter](#highlight.Highlighter).
15436
- function highlightTree(tree, highlighter,
15437
- /// Assign styling to a region of the text. Will be called, in order
15438
- /// of position, for any ranges where more than zero classes apply.
15439
- /// `classes` is a space separated string of CSS classes.
15440
- putStyle,
15441
- /// The start of the range to highlight.
15442
- from = 0,
15443
- /// The end of the range.
15444
- to = tree.length) {
15445
- let builder = new HighlightBuilder(from, Array.isArray(highlighter) ? highlighter : [highlighter], putStyle);
15446
- builder.highlightRange(tree.cursor(), from, to, "", builder.highlighters);
15447
- builder.flush(to);
15448
- }
15449
- class HighlightBuilder {
15450
- constructor(at, highlighters, span) {
15451
- this.at = at;
15452
- this.highlighters = highlighters;
15453
- this.span = span;
15454
- this.class = "";
15455
- }
15456
- startSpan(at, cls) {
15457
- if (cls != this.class) {
15458
- this.flush(at);
15459
- if (at > this.at) this.at = at;
15460
- this.class = cls;
15461
- }
15462
- }
15463
- flush(to) {
15464
- if (to > this.at && this.class) this.span(this.at, to, this.class);
15465
- }
15466
- highlightRange(cursor, from, to, inheritedClass, highlighters) {
15467
- let {
15468
- type,
15469
- from: start,
15470
- to: end
15471
- } = cursor;
15472
- if (start >= to || end <= from) return;
15473
- if (type.isTop) highlighters = this.highlighters.filter(h => !h.scope || h.scope(type));
15474
- let cls = inheritedClass;
15475
- let rule = getStyleTags(cursor) || Rule.empty;
15476
- let tagCls = highlightTags(highlighters, rule.tags);
15477
- if (tagCls) {
15478
- if (cls) cls += " ";
15479
- cls += tagCls;
15480
- if (rule.mode == 1 /* Mode.Inherit */) inheritedClass += (inheritedClass ? " " : "") + tagCls;
15481
- }
15482
- this.startSpan(cursor.from, cls);
15483
- if (rule.opaque) return;
15484
- let mounted = cursor.tree && cursor.tree.prop(NodeProp.mounted);
15485
- if (mounted && mounted.overlay) {
15486
- let inner = cursor.node.enter(mounted.overlay[0].from + start, 1);
15487
- let innerHighlighters = this.highlighters.filter(h => !h.scope || h.scope(mounted.tree.type));
15488
- let hasChild = cursor.firstChild();
15489
- for (let i = 0, pos = start;; i++) {
15490
- let next = i < mounted.overlay.length ? mounted.overlay[i] : null;
15491
- let nextPos = next ? next.from + start : end;
15492
- let rangeFrom = Math.max(from, pos),
15493
- rangeTo = Math.min(to, nextPos);
15494
- if (rangeFrom < rangeTo && hasChild) {
15495
- while (cursor.from < rangeTo) {
15496
- this.highlightRange(cursor, rangeFrom, rangeTo, inheritedClass, highlighters);
15497
- this.startSpan(Math.min(rangeTo, cursor.to), cls);
15498
- if (cursor.to >= nextPos || !cursor.nextSibling()) break;
15499
- }
15500
- }
15501
- if (!next || nextPos > to) break;
15502
- pos = next.to + start;
15503
- if (pos > from) {
15504
- this.highlightRange(inner.cursor(), Math.max(from, next.from + start), Math.min(to, pos), inheritedClass, innerHighlighters);
15505
- this.startSpan(pos, cls);
15506
- }
15507
- }
15508
- if (hasChild) cursor.parent();
15509
- } else if (cursor.firstChild()) {
15510
- do {
15511
- if (cursor.to <= from) continue;
15512
- if (cursor.from >= to) break;
15513
- this.highlightRange(cursor, from, to, inheritedClass, highlighters);
15514
- this.startSpan(Math.min(to, cursor.to), cls);
15515
- } while (cursor.nextSibling());
15516
- cursor.parent();
15517
- }
15518
- }
15519
- }
15520
- /// Match a syntax node's [highlight rules](#highlight.styleTags). If
15521
- /// there's a match, return its set of tags, and whether it is
15522
- /// opaque (uses a `!`) or applies to all child nodes (`/...`).
15523
- function getStyleTags(node) {
15524
- let rule = node.type.prop(ruleNodeProp);
15525
- while (rule && rule.context && !node.matchContext(rule.context)) rule = rule.next;
15526
- return rule || null;
15527
- }
15528
- const t = Tag.define;
15529
- const comment = t(),
15530
- name = t(),
15531
- typeName = t(name),
15532
- propertyName = t(name),
15533
- literal = t(),
15534
- string = t(literal),
15535
- number = t(literal),
15536
- content = t(),
15537
- heading = t(content),
15538
- keyword = t(),
15539
- operator = t(),
15540
- punctuation = t(),
15541
- bracket = t(punctuation),
15542
- meta = t();
15543
- /// The default set of highlighting [tags](#highlight.Tag).
15544
- ///
15545
- /// This collection is heavily biased towards programming languages,
15546
- /// and necessarily incomplete. A full ontology of syntactic
15547
- /// constructs would fill a stack of books, and be impractical to
15548
- /// write themes for. So try to make do with this set. If all else
15549
- /// fails, [open an
15550
- /// issue](https://github.com/codemirror/codemirror.next) to propose a
15551
- /// new tag, or [define](#highlight.Tag^define) a local custom tag for
15552
- /// your use case.
15553
- ///
15554
- /// Note that it is not obligatory to always attach the most specific
15555
- /// tag possible to an element—if your grammar can't easily
15556
- /// distinguish a certain type of element (such as a local variable),
15557
- /// it is okay to style it as its more general variant (a variable).
15558
- ///
15559
- /// For tags that extend some parent tag, the documentation links to
15560
- /// the parent.
15561
- const tags = {
15562
- /// A comment.
15563
- comment,
15564
- /// A line [comment](#highlight.tags.comment).
15565
- lineComment: t(comment),
15566
- /// A block [comment](#highlight.tags.comment).
15567
- blockComment: t(comment),
15568
- /// A documentation [comment](#highlight.tags.comment).
15569
- docComment: t(comment),
15570
- /// Any kind of identifier.
15571
- name,
15572
- /// The [name](#highlight.tags.name) of a variable.
15573
- variableName: t(name),
15574
- /// A type [name](#highlight.tags.name).
15575
- typeName: typeName,
15576
- /// A tag name (subtag of [`typeName`](#highlight.tags.typeName)).
15577
- tagName: t(typeName),
15578
- /// A property or field [name](#highlight.tags.name).
15579
- propertyName: propertyName,
15580
- /// An attribute name (subtag of [`propertyName`](#highlight.tags.propertyName)).
15581
- attributeName: t(propertyName),
15582
- /// The [name](#highlight.tags.name) of a class.
15583
- className: t(name),
15584
- /// A label [name](#highlight.tags.name).
15585
- labelName: t(name),
15586
- /// A namespace [name](#highlight.tags.name).
15587
- namespace: t(name),
15588
- /// The [name](#highlight.tags.name) of a macro.
15589
- macroName: t(name),
15590
- /// A literal value.
15591
- literal,
15592
- /// A string [literal](#highlight.tags.literal).
15593
- string,
15594
- /// A documentation [string](#highlight.tags.string).
15595
- docString: t(string),
15596
- /// A character literal (subtag of [string](#highlight.tags.string)).
15597
- character: t(string),
15598
- /// An attribute value (subtag of [string](#highlight.tags.string)).
15599
- attributeValue: t(string),
15600
- /// A number [literal](#highlight.tags.literal).
15601
- number,
15602
- /// An integer [number](#highlight.tags.number) literal.
15603
- integer: t(number),
15604
- /// A floating-point [number](#highlight.tags.number) literal.
15605
- float: t(number),
15606
- /// A boolean [literal](#highlight.tags.literal).
15607
- bool: t(literal),
15608
- /// Regular expression [literal](#highlight.tags.literal).
15609
- regexp: t(literal),
15610
- /// An escape [literal](#highlight.tags.literal), for example a
15611
- /// backslash escape in a string.
15612
- escape: t(literal),
15613
- /// A color [literal](#highlight.tags.literal).
15614
- color: t(literal),
15615
- /// A URL [literal](#highlight.tags.literal).
15616
- url: t(literal),
15617
- /// A language keyword.
15618
- keyword,
15619
- /// The [keyword](#highlight.tags.keyword) for the self or this
15620
- /// object.
15621
- self: t(keyword),
15622
- /// The [keyword](#highlight.tags.keyword) for null.
15623
- null: t(keyword),
15624
- /// A [keyword](#highlight.tags.keyword) denoting some atomic value.
15625
- atom: t(keyword),
15626
- /// A [keyword](#highlight.tags.keyword) that represents a unit.
15627
- unit: t(keyword),
15628
- /// A modifier [keyword](#highlight.tags.keyword).
15629
- modifier: t(keyword),
15630
- /// A [keyword](#highlight.tags.keyword) that acts as an operator.
15631
- operatorKeyword: t(keyword),
15632
- /// A control-flow related [keyword](#highlight.tags.keyword).
15633
- controlKeyword: t(keyword),
15634
- /// A [keyword](#highlight.tags.keyword) that defines something.
15635
- definitionKeyword: t(keyword),
15636
- /// A [keyword](#highlight.tags.keyword) related to defining or
15637
- /// interfacing with modules.
15638
- moduleKeyword: t(keyword),
15639
- /// An operator.
15640
- operator,
15641
- /// An [operator](#highlight.tags.operator) that dereferences something.
15642
- derefOperator: t(operator),
15643
- /// Arithmetic-related [operator](#highlight.tags.operator).
15644
- arithmeticOperator: t(operator),
15645
- /// Logical [operator](#highlight.tags.operator).
15646
- logicOperator: t(operator),
15647
- /// Bit [operator](#highlight.tags.operator).
15648
- bitwiseOperator: t(operator),
15649
- /// Comparison [operator](#highlight.tags.operator).
15650
- compareOperator: t(operator),
15651
- /// [Operator](#highlight.tags.operator) that updates its operand.
15652
- updateOperator: t(operator),
15653
- /// [Operator](#highlight.tags.operator) that defines something.
15654
- definitionOperator: t(operator),
15655
- /// Type-related [operator](#highlight.tags.operator).
15656
- typeOperator: t(operator),
15657
- /// Control-flow [operator](#highlight.tags.operator).
15658
- controlOperator: t(operator),
15659
- /// Program or markup punctuation.
15660
- punctuation,
15661
- /// [Punctuation](#highlight.tags.punctuation) that separates
15662
- /// things.
15663
- separator: t(punctuation),
15664
- /// Bracket-style [punctuation](#highlight.tags.punctuation).
15665
- bracket,
15666
- /// Angle [brackets](#highlight.tags.bracket) (usually `<` and `>`
15667
- /// tokens).
15668
- angleBracket: t(bracket),
15669
- /// Square [brackets](#highlight.tags.bracket) (usually `[` and `]`
15670
- /// tokens).
15671
- squareBracket: t(bracket),
15672
- /// Parentheses (usually `(` and `)` tokens). Subtag of
15673
- /// [bracket](#highlight.tags.bracket).
15674
- paren: t(bracket),
15675
- /// Braces (usually `{` and `}` tokens). Subtag of
15676
- /// [bracket](#highlight.tags.bracket).
15677
- brace: t(bracket),
15678
- /// Content, for example plain text in XML or markup documents.
15679
- content,
15680
- /// [Content](#highlight.tags.content) that represents a heading.
15681
- heading,
15682
- /// A level 1 [heading](#highlight.tags.heading).
15683
- heading1: t(heading),
15684
- /// A level 2 [heading](#highlight.tags.heading).
15685
- heading2: t(heading),
15686
- /// A level 3 [heading](#highlight.tags.heading).
15687
- heading3: t(heading),
15688
- /// A level 4 [heading](#highlight.tags.heading).
15689
- heading4: t(heading),
15690
- /// A level 5 [heading](#highlight.tags.heading).
15691
- heading5: t(heading),
15692
- /// A level 6 [heading](#highlight.tags.heading).
15693
- heading6: t(heading),
15694
- /// A prose separator (such as a horizontal rule).
15695
- contentSeparator: t(content),
15696
- /// [Content](#highlight.tags.content) that represents a list.
15697
- list: t(content),
15698
- /// [Content](#highlight.tags.content) that represents a quote.
15699
- quote: t(content),
15700
- /// [Content](#highlight.tags.content) that is emphasized.
15701
- emphasis: t(content),
15702
- /// [Content](#highlight.tags.content) that is styled strong.
15703
- strong: t(content),
15704
- /// [Content](#highlight.tags.content) that is part of a link.
15705
- link: t(content),
15706
- /// [Content](#highlight.tags.content) that is styled as code or
15707
- /// monospace.
15708
- monospace: t(content),
15709
- /// [Content](#highlight.tags.content) that has a strike-through
15710
- /// style.
15711
- strikethrough: t(content),
15712
- /// Inserted text in a change-tracking format.
15713
- inserted: t(),
15714
- /// Deleted text.
15715
- deleted: t(),
15716
- /// Changed text.
15717
- changed: t(),
15718
- /// An invalid or unsyntactic element.
15719
- invalid: t(),
15720
- /// Metadata or meta-instruction.
15721
- meta,
15722
- /// [Metadata](#highlight.tags.meta) that applies to the entire
15723
- /// document.
15724
- documentMeta: t(meta),
15725
- /// [Metadata](#highlight.tags.meta) that annotates or adds
15726
- /// attributes to a given syntactic element.
15727
- annotation: t(meta),
15728
- /// Processing instruction or preprocessor directive. Subtag of
15729
- /// [meta](#highlight.tags.meta).
15730
- processingInstruction: t(meta),
15731
- /// [Modifier](#highlight.Tag^defineModifier) that indicates that a
15732
- /// given element is being defined. Expected to be used with the
15733
- /// various [name](#highlight.tags.name) tags.
15734
- definition: Tag.defineModifier(),
15735
- /// [Modifier](#highlight.Tag^defineModifier) that indicates that
15736
- /// something is constant. Mostly expected to be used with
15737
- /// [variable names](#highlight.tags.variableName).
15738
- constant: Tag.defineModifier(),
15739
- /// [Modifier](#highlight.Tag^defineModifier) used to indicate that
15740
- /// a [variable](#highlight.tags.variableName) or [property
15741
- /// name](#highlight.tags.propertyName) is being called or defined
15742
- /// as a function.
15743
- function: Tag.defineModifier(),
15744
- /// [Modifier](#highlight.Tag^defineModifier) that can be applied to
15745
- /// [names](#highlight.tags.name) to indicate that they belong to
15746
- /// the language's standard environment.
15747
- standard: Tag.defineModifier(),
15748
- /// [Modifier](#highlight.Tag^defineModifier) that indicates a given
15749
- /// [names](#highlight.tags.name) is local to some scope.
15750
- local: Tag.defineModifier(),
15751
- /// A generic variant [modifier](#highlight.Tag^defineModifier) that
15752
- /// can be used to tag language-specific alternative variants of
15753
- /// some common tag. It is recommended for themes to define special
15754
- /// forms of at least the [string](#highlight.tags.string) and
15755
- /// [variable name](#highlight.tags.variableName) tags, since those
15756
- /// come up a lot.
15757
- special: Tag.defineModifier()
15758
- };
15759
- /// This is a highlighter that adds stable, predictable classes to
15760
- /// tokens, for styling with external CSS.
15761
- ///
15762
- /// The following tags are mapped to their name prefixed with `"tok-"`
15763
- /// (for example `"tok-comment"`):
15764
- ///
15765
- /// * [`link`](#highlight.tags.link)
15766
- /// * [`heading`](#highlight.tags.heading)
15767
- /// * [`emphasis`](#highlight.tags.emphasis)
15768
- /// * [`strong`](#highlight.tags.strong)
15769
- /// * [`keyword`](#highlight.tags.keyword)
15770
- /// * [`atom`](#highlight.tags.atom)
15771
- /// * [`bool`](#highlight.tags.bool)
15772
- /// * [`url`](#highlight.tags.url)
15773
- /// * [`labelName`](#highlight.tags.labelName)
15774
- /// * [`inserted`](#highlight.tags.inserted)
15775
- /// * [`deleted`](#highlight.tags.deleted)
15776
- /// * [`literal`](#highlight.tags.literal)
15777
- /// * [`string`](#highlight.tags.string)
15778
- /// * [`number`](#highlight.tags.number)
15779
- /// * [`variableName`](#highlight.tags.variableName)
15780
- /// * [`typeName`](#highlight.tags.typeName)
15781
- /// * [`namespace`](#highlight.tags.namespace)
15782
- /// * [`className`](#highlight.tags.className)
15783
- /// * [`macroName`](#highlight.tags.macroName)
15784
- /// * [`propertyName`](#highlight.tags.propertyName)
15785
- /// * [`operator`](#highlight.tags.operator)
15786
- /// * [`comment`](#highlight.tags.comment)
15787
- /// * [`meta`](#highlight.tags.meta)
15788
- /// * [`punctuation`](#highlight.tags.punctuation)
15789
- /// * [`invalid`](#highlight.tags.invalid)
15790
- ///
15791
- /// In addition, these mappings are provided:
15792
- ///
15793
- /// * [`regexp`](#highlight.tags.regexp),
15794
- /// [`escape`](#highlight.tags.escape), and
15795
- /// [`special`](#highlight.tags.special)[`(string)`](#highlight.tags.string)
15796
- /// are mapped to `"tok-string2"`
15797
- /// * [`special`](#highlight.tags.special)[`(variableName)`](#highlight.tags.variableName)
15798
- /// to `"tok-variableName2"`
15799
- /// * [`local`](#highlight.tags.local)[`(variableName)`](#highlight.tags.variableName)
15800
- /// to `"tok-variableName tok-local"`
15801
- /// * [`definition`](#highlight.tags.definition)[`(variableName)`](#highlight.tags.variableName)
15802
- /// to `"tok-variableName tok-definition"`
15803
- /// * [`definition`](#highlight.tags.definition)[`(propertyName)`](#highlight.tags.propertyName)
15804
- /// to `"tok-propertyName tok-definition"`
15805
- tagHighlighter([{
15806
- tag: tags.link,
15807
- class: "tok-link"
15808
- }, {
15809
- tag: tags.heading,
15810
- class: "tok-heading"
15811
- }, {
15812
- tag: tags.emphasis,
15813
- class: "tok-emphasis"
15814
- }, {
15815
- tag: tags.strong,
15816
- class: "tok-strong"
15817
- }, {
15818
- tag: tags.keyword,
15819
- class: "tok-keyword"
15820
- }, {
15821
- tag: tags.atom,
15822
- class: "tok-atom"
15823
- }, {
15824
- tag: tags.bool,
15825
- class: "tok-bool"
15826
- }, {
15827
- tag: tags.url,
15828
- class: "tok-url"
15829
- }, {
15830
- tag: tags.labelName,
15831
- class: "tok-labelName"
15832
- }, {
15833
- tag: tags.inserted,
15834
- class: "tok-inserted"
15835
- }, {
15836
- tag: tags.deleted,
15837
- class: "tok-deleted"
15838
- }, {
15839
- tag: tags.literal,
15840
- class: "tok-literal"
15841
- }, {
15842
- tag: tags.string,
15843
- class: "tok-string"
15844
- }, {
15845
- tag: tags.number,
15846
- class: "tok-number"
15847
- }, {
15848
- tag: [tags.regexp, tags.escape, tags.special(tags.string)],
15849
- class: "tok-string2"
15850
- }, {
15851
- tag: tags.variableName,
15852
- class: "tok-variableName"
15853
- }, {
15854
- tag: tags.local(tags.variableName),
15855
- class: "tok-variableName tok-local"
15856
- }, {
15857
- tag: tags.definition(tags.variableName),
15858
- class: "tok-variableName tok-definition"
15859
- }, {
15860
- tag: tags.special(tags.variableName),
15861
- class: "tok-variableName2"
15862
- }, {
15863
- tag: tags.definition(tags.propertyName),
15864
- class: "tok-propertyName tok-definition"
15865
- }, {
15866
- tag: tags.typeName,
15867
- class: "tok-typeName"
15868
- }, {
15869
- tag: tags.namespace,
15870
- class: "tok-namespace"
15871
- }, {
15872
- tag: tags.className,
15873
- class: "tok-className"
15874
- }, {
15875
- tag: tags.macroName,
15876
- class: "tok-macroName"
15877
- }, {
15878
- tag: tags.propertyName,
15879
- class: "tok-propertyName"
15880
- }, {
15881
- tag: tags.operator,
15882
- class: "tok-operator"
15883
- }, {
15884
- tag: tags.comment,
15885
- class: "tok-comment"
15886
- }, {
15887
- tag: tags.meta,
15888
- class: "tok-meta"
15889
- }, {
15890
- tag: tags.invalid,
15891
- class: "tok-invalid"
15892
- }, {
15893
- tag: tags.punctuation,
15894
- class: "tok-punctuation"
15895
- }]);
15896
-
15897
- var _a;
15898
- /**
15899
- Node prop stored in a parser's top syntax node to provide the
15900
- facet that stores language-specific data for that language.
15901
- */
15902
- const languageDataProp = /*@__PURE__*/new NodeProp();
15903
- /**
15904
- Helper function to define a facet (to be added to the top syntax
15905
- node(s) for a language via
15906
- [`languageDataProp`](https://codemirror.net/6/docs/ref/#language.languageDataProp)), that will be
15907
- used to associate language data with the language. You
15908
- probably only need this when subclassing
15909
- [`Language`](https://codemirror.net/6/docs/ref/#language.Language).
15910
- */
15911
- function defineLanguageFacet(baseData) {
15912
- return Facet.define({
15913
- combine: baseData ? values => values.concat(baseData) : undefined
15914
- });
15915
- }
15916
- /**
15917
- A language object manages parsing and per-language
15918
- [metadata](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt). Parse data is
15919
- managed as a [Lezer](https://lezer.codemirror.net) tree. The class
15920
- can be used directly, via the [`LRLanguage`](https://codemirror.net/6/docs/ref/#language.LRLanguage)
15921
- subclass for [Lezer](https://lezer.codemirror.net/) LR parsers, or
15922
- via the [`StreamLanguage`](https://codemirror.net/6/docs/ref/#language.StreamLanguage) subclass
15923
- for stream parsers.
15924
- */
15925
- class Language {
15926
- /**
15927
- Construct a language object. If you need to invoke this
15928
- directly, first define a data facet with
15929
- [`defineLanguageFacet`](https://codemirror.net/6/docs/ref/#language.defineLanguageFacet), and then
15930
- configure your parser to [attach](https://codemirror.net/6/docs/ref/#language.languageDataProp) it
15931
- to the language's outer syntax node.
15932
- */
15933
- constructor(
15934
- /**
15935
- The [language data](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt) facet
15936
- used for this language.
15937
- */
15938
- data, parser, extraExtensions = [],
15939
- /**
15940
- A language name.
15941
- */
15942
- name = "") {
15943
- this.data = data;
15944
- this.name = name;
15945
- // Kludge to define EditorState.tree as a debugging helper,
15946
- // without the EditorState package actually knowing about
15947
- // languages and lezer trees.
15948
- if (!EditorState.prototype.hasOwnProperty("tree")) Object.defineProperty(EditorState.prototype, "tree", {
15949
- get() {
15950
- return syntaxTree(this);
15951
- }
15952
- });
15953
- this.parser = parser;
15954
- this.extension = [language.of(this), EditorState.languageData.of((state, pos, side) => state.facet(languageDataFacetAt(state, pos, side)))].concat(extraExtensions);
15955
- }
15956
- /**
15957
- Query whether this language is active at the given position.
15958
- */
15959
- isActiveAt(state, pos, side = -1) {
15960
- return languageDataFacetAt(state, pos, side) == this.data;
15961
- }
15962
- /**
15963
- Find the document regions that were parsed using this language.
15964
- The returned regions will _include_ any nested languages rooted
15965
- in this language, when those exist.
15966
- */
15967
- findRegions(state) {
15968
- let lang = state.facet(language);
15969
- if ((lang === null || lang === void 0 ? void 0 : lang.data) == this.data) return [{
15970
- from: 0,
15971
- to: state.doc.length
15972
- }];
15973
- if (!lang || !lang.allowsNesting) return [];
15974
- let result = [];
15975
- let explore = (tree, from) => {
15976
- if (tree.prop(languageDataProp) == this.data) {
15977
- result.push({
15978
- from,
15979
- to: from + tree.length
15980
- });
15981
- return;
15982
- }
15983
- let mount = tree.prop(NodeProp.mounted);
15984
- if (mount) {
15985
- if (mount.tree.prop(languageDataProp) == this.data) {
15986
- if (mount.overlay) for (let r of mount.overlay) result.push({
15987
- from: r.from + from,
15988
- to: r.to + from
15989
- });else result.push({
15990
- from: from,
15991
- to: from + tree.length
15992
- });
15993
- return;
15994
- } else if (mount.overlay) {
15995
- let size = result.length;
15996
- explore(mount.tree, mount.overlay[0].from + from);
15997
- if (result.length > size) return;
15998
- }
15999
- }
16000
- for (let i = 0; i < tree.children.length; i++) {
16001
- let ch = tree.children[i];
16002
- if (ch instanceof Tree) explore(ch, tree.positions[i] + from);
16003
- }
16004
- };
16005
- explore(syntaxTree(state), 0);
16006
- return result;
16007
- }
16008
- /**
16009
- Indicates whether this language allows nested languages. The
16010
- default implementation returns true.
16011
- */
16012
- get allowsNesting() {
16013
- return true;
16014
- }
16015
- }
16016
- /**
16017
- @internal
16018
- */
16019
- Language.setState = /*@__PURE__*/StateEffect.define();
16020
- function languageDataFacetAt(state, pos, side) {
16021
- let topLang = state.facet(language);
16022
- if (!topLang) return null;
16023
- let facet = topLang.data;
16024
- if (topLang.allowsNesting) {
16025
- for (let node = syntaxTree(state).topNode; node; node = node.enter(pos, side, IterMode.ExcludeBuffers)) facet = node.type.prop(languageDataProp) || facet;
16026
- }
16027
- return facet;
16028
- }
16029
- /**
16030
- A subclass of [`Language`](https://codemirror.net/6/docs/ref/#language.Language) for use with Lezer
16031
- [LR parsers](https://lezer.codemirror.net/docs/ref#lr.LRParser)
16032
- parsers.
16033
- */
16034
- class LRLanguage extends Language {
16035
- constructor(data, parser, name) {
16036
- super(data, parser, [], name);
16037
- this.parser = parser;
16038
- }
16039
- /**
16040
- Define a language from a parser.
16041
- */
16042
- static define(spec) {
16043
- let data = defineLanguageFacet(spec.languageData);
16044
- return new LRLanguage(data, spec.parser.configure({
16045
- props: [languageDataProp.add(type => type.isTop ? data : undefined)]
16046
- }), spec.name);
16047
- }
16048
- /**
16049
- Create a new instance of this language with a reconfigured
16050
- version of its parser and optionally a new name.
16051
- */
16052
- configure(options, name) {
16053
- return new LRLanguage(this.data, this.parser.configure(options), name || this.name);
16054
- }
16055
- get allowsNesting() {
16056
- return this.parser.hasWrappers();
16057
- }
16058
- }
16059
- /**
16060
- Get the syntax tree for a state, which is the current (possibly
16061
- incomplete) parse tree of the active
16062
- [language](https://codemirror.net/6/docs/ref/#language.Language), or the empty tree if there is no
16063
- language available.
16064
- */
16065
- function syntaxTree(state) {
16066
- let field = state.field(Language.state, false);
16067
- return field ? field.tree : Tree.empty;
16068
- }
16069
- // Lezer-style Input object for a Text document.
16070
- class DocInput {
16071
- constructor(doc, length = doc.length) {
16072
- this.doc = doc;
16073
- this.length = length;
16074
- this.cursorPos = 0;
16075
- this.string = "";
16076
- this.cursor = doc.iter();
16077
- }
16078
- syncTo(pos) {
16079
- this.string = this.cursor.next(pos - this.cursorPos).value;
16080
- this.cursorPos = pos + this.string.length;
16081
- return this.cursorPos - this.string.length;
16082
- }
16083
- chunk(pos) {
16084
- this.syncTo(pos);
16085
- return this.string;
16086
- }
16087
- get lineChunks() {
16088
- return true;
16089
- }
16090
- read(from, to) {
16091
- let stringStart = this.cursorPos - this.string.length;
16092
- if (from < stringStart || to >= this.cursorPos) return this.doc.sliceString(from, to);else return this.string.slice(from - stringStart, to - stringStart);
16093
- }
16094
- }
16095
- let currentContext = null;
16096
- /**
16097
- A parse context provided to parsers working on the editor content.
16098
- */
16099
- class ParseContext {
16100
- constructor(parser,
16101
- /**
16102
- The current editor state.
16103
- */
16104
- state,
16105
- /**
16106
- Tree fragments that can be reused by incremental re-parses.
16107
- */
16108
- fragments = [],
16109
- /**
16110
- @internal
16111
- */
16112
- tree,
16113
- /**
16114
- @internal
16115
- */
16116
- treeLen,
16117
- /**
16118
- The current editor viewport (or some overapproximation
16119
- thereof). Intended to be used for opportunistically avoiding
16120
- work (in which case
16121
- [`skipUntilInView`](https://codemirror.net/6/docs/ref/#language.ParseContext.skipUntilInView)
16122
- should be called to make sure the parser is restarted when the
16123
- skipped region becomes visible).
16124
- */
16125
- viewport,
16126
- /**
16127
- @internal
16128
- */
16129
- skipped,
16130
- /**
16131
- This is where skipping parsers can register a promise that,
16132
- when resolved, will schedule a new parse. It is cleared when
16133
- the parse worker picks up the promise. @internal
16134
- */
16135
- scheduleOn) {
16136
- this.parser = parser;
16137
- this.state = state;
16138
- this.fragments = fragments;
16139
- this.tree = tree;
16140
- this.treeLen = treeLen;
16141
- this.viewport = viewport;
16142
- this.skipped = skipped;
16143
- this.scheduleOn = scheduleOn;
16144
- this.parse = null;
16145
- /**
16146
- @internal
16147
- */
16148
- this.tempSkipped = [];
16149
- }
16150
- /**
16151
- @internal
16152
- */
16153
- static create(parser, state, viewport) {
16154
- return new ParseContext(parser, state, [], Tree.empty, 0, viewport, [], null);
16155
- }
16156
- startParse() {
16157
- return this.parser.startParse(new DocInput(this.state.doc), this.fragments);
16158
- }
16159
- /**
16160
- @internal
16161
- */
16162
- work(until, upto) {
16163
- if (upto != null && upto >= this.state.doc.length) upto = undefined;
16164
- if (this.tree != Tree.empty && this.isDone(upto !== null && upto !== void 0 ? upto : this.state.doc.length)) {
16165
- this.takeTree();
16166
- return true;
16167
- }
16168
- return this.withContext(() => {
16169
- var _a;
16170
- if (typeof until == "number") {
16171
- let endTime = Date.now() + until;
16172
- until = () => Date.now() > endTime;
16173
- }
16174
- if (!this.parse) this.parse = this.startParse();
16175
- if (upto != null && (this.parse.stoppedAt == null || this.parse.stoppedAt > upto) && upto < this.state.doc.length) this.parse.stopAt(upto);
16176
- for (;;) {
16177
- let done = this.parse.advance();
16178
- if (done) {
16179
- this.fragments = this.withoutTempSkipped(TreeFragment.addTree(done, this.fragments, this.parse.stoppedAt != null));
16180
- this.treeLen = (_a = this.parse.stoppedAt) !== null && _a !== void 0 ? _a : this.state.doc.length;
16181
- this.tree = done;
16182
- this.parse = null;
16183
- if (this.treeLen < (upto !== null && upto !== void 0 ? upto : this.state.doc.length)) this.parse = this.startParse();else return true;
16184
- }
16185
- if (until()) return false;
16186
- }
16187
- });
16188
- }
16189
- /**
16190
- @internal
16191
- */
16192
- takeTree() {
16193
- let pos, tree;
16194
- if (this.parse && (pos = this.parse.parsedPos) >= this.treeLen) {
16195
- if (this.parse.stoppedAt == null || this.parse.stoppedAt > pos) this.parse.stopAt(pos);
16196
- this.withContext(() => {
16197
- while (!(tree = this.parse.advance())) {}
16198
- });
16199
- this.treeLen = pos;
16200
- this.tree = tree;
16201
- this.fragments = this.withoutTempSkipped(TreeFragment.addTree(this.tree, this.fragments, true));
16202
- this.parse = null;
16203
- }
16204
- }
16205
- withContext(f) {
16206
- let prev = currentContext;
16207
- currentContext = this;
16208
- try {
16209
- return f();
16210
- } finally {
16211
- currentContext = prev;
16212
- }
16213
- }
16214
- withoutTempSkipped(fragments) {
16215
- for (let r; r = this.tempSkipped.pop();) fragments = cutFragments(fragments, r.from, r.to);
16216
- return fragments;
16217
- }
16218
- /**
16219
- @internal
16220
- */
16221
- changes(changes, newState) {
16222
- let {
16223
- fragments,
16224
- tree,
16225
- treeLen,
16226
- viewport,
16227
- skipped
16228
- } = this;
16229
- this.takeTree();
16230
- if (!changes.empty) {
16231
- let ranges = [];
16232
- changes.iterChangedRanges((fromA, toA, fromB, toB) => ranges.push({
16233
- fromA,
16234
- toA,
16235
- fromB,
16236
- toB
16237
- }));
16238
- fragments = TreeFragment.applyChanges(fragments, ranges);
16239
- tree = Tree.empty;
16240
- treeLen = 0;
16241
- viewport = {
16242
- from: changes.mapPos(viewport.from, -1),
16243
- to: changes.mapPos(viewport.to, 1)
16244
- };
16245
- if (this.skipped.length) {
16246
- skipped = [];
16247
- for (let r of this.skipped) {
16248
- let from = changes.mapPos(r.from, 1),
16249
- to = changes.mapPos(r.to, -1);
16250
- if (from < to) skipped.push({
16251
- from,
16252
- to
16253
- });
16254
- }
16255
- }
16256
- }
16257
- return new ParseContext(this.parser, newState, fragments, tree, treeLen, viewport, skipped, this.scheduleOn);
16258
- }
16259
- /**
16260
- @internal
16261
- */
16262
- updateViewport(viewport) {
16263
- if (this.viewport.from == viewport.from && this.viewport.to == viewport.to) return false;
16264
- this.viewport = viewport;
16265
- let startLen = this.skipped.length;
16266
- for (let i = 0; i < this.skipped.length; i++) {
16267
- let {
16268
- from,
16269
- to
16270
- } = this.skipped[i];
16271
- if (from < viewport.to && to > viewport.from) {
16272
- this.fragments = cutFragments(this.fragments, from, to);
16273
- this.skipped.splice(i--, 1);
16274
- }
16275
- }
16276
- if (this.skipped.length >= startLen) return false;
16277
- this.reset();
16278
- return true;
16279
- }
16280
- /**
16281
- @internal
16282
- */
16283
- reset() {
16284
- if (this.parse) {
16285
- this.takeTree();
16286
- this.parse = null;
16287
- }
16288
- }
16289
- /**
16290
- Notify the parse scheduler that the given region was skipped
16291
- because it wasn't in view, and the parse should be restarted
16292
- when it comes into view.
16293
- */
16294
- skipUntilInView(from, to) {
16295
- this.skipped.push({
16296
- from,
16297
- to
16298
- });
16299
- }
16300
- /**
16301
- Returns a parser intended to be used as placeholder when
16302
- asynchronously loading a nested parser. It'll skip its input and
16303
- mark it as not-really-parsed, so that the next update will parse
16304
- it again.
16305
-
16306
- When `until` is given, a reparse will be scheduled when that
16307
- promise resolves.
16308
- */
16309
- static getSkippingParser(until) {
16310
- return new class extends Parser {
16311
- createParse(input, fragments, ranges) {
16312
- let from = ranges[0].from,
16313
- to = ranges[ranges.length - 1].to;
16314
- let parser = {
16315
- parsedPos: from,
16316
- advance() {
16317
- let cx = currentContext;
16318
- if (cx) {
16319
- for (let r of ranges) cx.tempSkipped.push(r);
16320
- if (until) cx.scheduleOn = cx.scheduleOn ? Promise.all([cx.scheduleOn, until]) : until;
16321
- }
16322
- this.parsedPos = to;
16323
- return new Tree(NodeType.none, [], [], to - from);
16324
- },
16325
- stoppedAt: null,
16326
- stopAt() {}
16327
- };
16328
- return parser;
16329
- }
16330
- }();
16331
- }
16332
- /**
16333
- @internal
16334
- */
16335
- isDone(upto) {
16336
- upto = Math.min(upto, this.state.doc.length);
16337
- let frags = this.fragments;
16338
- return this.treeLen >= upto && frags.length && frags[0].from == 0 && frags[0].to >= upto;
16339
- }
16340
- /**
16341
- Get the context for the current parse, or `null` if no editor
16342
- parse is in progress.
16343
- */
16344
- static get() {
16345
- return currentContext;
16346
- }
16347
- }
16348
- function cutFragments(fragments, from, to) {
16349
- return TreeFragment.applyChanges(fragments, [{
16350
- fromA: from,
16351
- toA: to,
16352
- fromB: from,
16353
- toB: to
16354
- }]);
16355
- }
16356
- class LanguageState {
16357
- constructor(
16358
- // A mutable parse state that is used to preserve work done during
16359
- // the lifetime of a state when moving to the next state.
16360
- context) {
16361
- this.context = context;
16362
- this.tree = context.tree;
16363
- }
16364
- apply(tr) {
16365
- if (!tr.docChanged && this.tree == this.context.tree) return this;
16366
- let newCx = this.context.changes(tr.changes, tr.state);
16367
- // If the previous parse wasn't done, go forward only up to its
16368
- // end position or the end of the viewport, to avoid slowing down
16369
- // state updates with parse work beyond the viewport.
16370
- let upto = this.context.treeLen == tr.startState.doc.length ? undefined : Math.max(tr.changes.mapPos(this.context.treeLen), newCx.viewport.to);
16371
- if (!newCx.work(20 /* Work.Apply */, upto)) newCx.takeTree();
16372
- return new LanguageState(newCx);
16373
- }
16374
- static init(state) {
16375
- let vpTo = Math.min(3000 /* Work.InitViewport */, state.doc.length);
16376
- let parseState = ParseContext.create(state.facet(language).parser, state, {
16377
- from: 0,
16378
- to: vpTo
16379
- });
16380
- if (!parseState.work(20 /* Work.Apply */, vpTo)) parseState.takeTree();
16381
- return new LanguageState(parseState);
16382
- }
16383
- }
16384
- Language.state = /*@__PURE__*/StateField.define({
16385
- create: LanguageState.init,
16386
- update(value, tr) {
16387
- for (let e of tr.effects) if (e.is(Language.setState)) return e.value;
16388
- if (tr.startState.facet(language) != tr.state.facet(language)) return LanguageState.init(tr.state);
16389
- return value.apply(tr);
16390
- }
16391
- });
16392
- let requestIdle = callback => {
16393
- let timeout = setTimeout(() => callback(), 500 /* Work.MaxPause */);
16394
- return () => clearTimeout(timeout);
16395
- };
16396
- if (typeof requestIdleCallback != "undefined") requestIdle = callback => {
16397
- let idle = -1,
16398
- timeout = setTimeout(() => {
16399
- idle = requestIdleCallback(callback, {
16400
- timeout: 500 /* Work.MaxPause */ - 100 /* Work.MinPause */
16401
- });
16402
- }, 100 /* Work.MinPause */);
16403
- return () => idle < 0 ? clearTimeout(timeout) : cancelIdleCallback(idle);
16404
- };
16405
- const isInputPending = typeof navigator != "undefined" && ((_a = navigator.scheduling) === null || _a === void 0 ? void 0 : _a.isInputPending) ? () => navigator.scheduling.isInputPending() : null;
16406
- const parseWorker = /*@__PURE__*/ViewPlugin.fromClass(class ParseWorker {
16407
- constructor(view) {
16408
- this.view = view;
16409
- this.working = null;
16410
- this.workScheduled = 0;
16411
- // End of the current time chunk
16412
- this.chunkEnd = -1;
16413
- // Milliseconds of budget left for this chunk
16414
- this.chunkBudget = -1;
16415
- this.work = this.work.bind(this);
16416
- this.scheduleWork();
16417
- }
16418
- update(update) {
16419
- let cx = this.view.state.field(Language.state).context;
16420
- if (cx.updateViewport(update.view.viewport) || this.view.viewport.to > cx.treeLen) this.scheduleWork();
16421
- if (update.docChanged) {
16422
- if (this.view.hasFocus) this.chunkBudget += 50 /* Work.ChangeBonus */;
16423
- this.scheduleWork();
16424
- }
16425
- this.checkAsyncSchedule(cx);
16426
- }
16427
- scheduleWork() {
16428
- if (this.working) return;
16429
- let {
16430
- state
16431
- } = this.view,
16432
- field = state.field(Language.state);
16433
- if (field.tree != field.context.tree || !field.context.isDone(state.doc.length)) this.working = requestIdle(this.work);
16434
- }
16435
- work(deadline) {
16436
- this.working = null;
16437
- let now = Date.now();
16438
- if (this.chunkEnd < now && (this.chunkEnd < 0 || this.view.hasFocus)) {
16439
- // Start a new chunk
16440
- this.chunkEnd = now + 30000 /* Work.ChunkTime */;
16441
- this.chunkBudget = 3000 /* Work.ChunkBudget */;
16442
- }
16443
-
16444
- if (this.chunkBudget <= 0) return; // No more budget
16445
- let {
16446
- state,
16447
- viewport: {
16448
- to: vpTo
16449
- }
16450
- } = this.view,
16451
- field = state.field(Language.state);
16452
- if (field.tree == field.context.tree && field.context.isDone(vpTo + 100000 /* Work.MaxParseAhead */)) return;
16453
- let endTime = Date.now() + Math.min(this.chunkBudget, 100 /* Work.Slice */, deadline && !isInputPending ? Math.max(25 /* Work.MinSlice */, deadline.timeRemaining() - 5) : 1e9);
16454
- let viewportFirst = field.context.treeLen < vpTo && state.doc.length > vpTo + 1000;
16455
- let done = field.context.work(() => {
16456
- return isInputPending && isInputPending() || Date.now() > endTime;
16457
- }, vpTo + (viewportFirst ? 0 : 100000 /* Work.MaxParseAhead */));
16458
- this.chunkBudget -= Date.now() - now;
16459
- if (done || this.chunkBudget <= 0) {
16460
- field.context.takeTree();
16461
- this.view.dispatch({
16462
- effects: Language.setState.of(new LanguageState(field.context))
16463
- });
16464
- }
16465
- if (this.chunkBudget > 0 && !(done && !viewportFirst)) this.scheduleWork();
16466
- this.checkAsyncSchedule(field.context);
16467
- }
16468
- checkAsyncSchedule(cx) {
16469
- if (cx.scheduleOn) {
16470
- this.workScheduled++;
16471
- cx.scheduleOn.then(() => this.scheduleWork()).catch(err => logException(this.view.state, err)).then(() => this.workScheduled--);
16472
- cx.scheduleOn = null;
16473
- }
16474
- }
16475
- destroy() {
16476
- if (this.working) this.working();
16477
- }
16478
- isWorking() {
16479
- return !!(this.working || this.workScheduled > 0);
16480
- }
16481
- }, {
16482
- eventHandlers: {
16483
- focus() {
16484
- this.scheduleWork();
16485
- }
16486
- }
16487
- });
16488
- /**
16489
- The facet used to associate a language with an editor state. Used
16490
- by `Language` object's `extension` property (so you don't need to
16491
- manually wrap your languages in this). Can be used to access the
16492
- current language on a state.
16493
- */
16494
- const language = /*@__PURE__*/Facet.define({
16495
- combine(languages) {
16496
- return languages.length ? languages[0] : null;
16497
- },
16498
- enables: language => [Language.state, parseWorker, EditorView.contentAttributes.compute([language], state => {
16499
- let lang = state.facet(language);
16500
- return lang && lang.name ? {
16501
- "data-language": lang.name
16502
- } : {};
16503
- })]
16504
- });
16505
- /**
16506
- This class bundles a [language](https://codemirror.net/6/docs/ref/#language.Language) with an
16507
- optional set of supporting extensions. Language packages are
16508
- encouraged to export a function that optionally takes a
16509
- configuration object and returns a `LanguageSupport` instance, as
16510
- the main way for client code to use the package.
16511
- */
16512
- class LanguageSupport {
16513
- /**
16514
- Create a language support object.
16515
- */
16516
- constructor(
16517
- /**
16518
- The language object.
16519
- */
16520
- language,
16521
- /**
16522
- An optional set of supporting extensions. When nesting a
16523
- language in another language, the outer language is encouraged
16524
- to include the supporting extensions for its inner languages
16525
- in its own set of support extensions.
16526
- */
16527
- support = []) {
16528
- this.language = language;
16529
- this.support = support;
16530
- this.extension = [language, support];
16531
- }
16532
- }
16533
- /**
16534
- Language descriptions are used to store metadata about languages
16535
- and to dynamically load them. Their main role is finding the
16536
- appropriate language for a filename or dynamically loading nested
16537
- parsers.
16538
- */
16539
- class LanguageDescription {
16540
- constructor(
16541
- /**
16542
- The name of this language.
16543
- */
16544
- name,
16545
- /**
16546
- Alternative names for the mode (lowercased, includes `this.name`).
16547
- */
16548
- alias,
16549
- /**
16550
- File extensions associated with this language.
16551
- */
16552
- extensions,
16553
- /**
16554
- Optional filename pattern that should be associated with this
16555
- language.
16556
- */
16557
- filename, loadFunc,
16558
- /**
16559
- If the language has been loaded, this will hold its value.
16560
- */
16561
- support = undefined) {
16562
- this.name = name;
16563
- this.alias = alias;
16564
- this.extensions = extensions;
16565
- this.filename = filename;
16566
- this.loadFunc = loadFunc;
16567
- this.support = support;
16568
- this.loading = null;
16569
- }
16570
- /**
16571
- Start loading the the language. Will return a promise that
16572
- resolves to a [`LanguageSupport`](https://codemirror.net/6/docs/ref/#language.LanguageSupport)
16573
- object when the language successfully loads.
16574
- */
16575
- load() {
16576
- return this.loading || (this.loading = this.loadFunc().then(support => this.support = support, err => {
16577
- this.loading = null;
16578
- throw err;
16579
- }));
16580
- }
16581
- /**
16582
- Create a language description.
16583
- */
16584
- static of(spec) {
16585
- let {
16586
- load,
16587
- support
16588
- } = spec;
16589
- if (!load) {
16590
- if (!support) throw new RangeError("Must pass either 'load' or 'support' to LanguageDescription.of");
16591
- load = () => Promise.resolve(support);
16592
- }
16593
- return new LanguageDescription(spec.name, (spec.alias || []).concat(spec.name).map(s => s.toLowerCase()), spec.extensions || [], spec.filename, load, support);
16594
- }
16595
- /**
16596
- Look for a language in the given array of descriptions that
16597
- matches the filename. Will first match
16598
- [`filename`](https://codemirror.net/6/docs/ref/#language.LanguageDescription.filename) patterns,
16599
- and then [extensions](https://codemirror.net/6/docs/ref/#language.LanguageDescription.extensions),
16600
- and return the first language that matches.
16601
- */
16602
- static matchFilename(descs, filename) {
16603
- for (let d of descs) if (d.filename && d.filename.test(filename)) return d;
16604
- let ext = /\.([^.]+)$/.exec(filename);
16605
- if (ext) for (let d of descs) if (d.extensions.indexOf(ext[1]) > -1) return d;
16606
- return null;
16607
- }
16608
- /**
16609
- Look for a language whose name or alias matches the the given
16610
- name (case-insensitively). If `fuzzy` is true, and no direct
16611
- matchs is found, this'll also search for a language whose name
16612
- or alias occurs in the string (for names shorter than three
16613
- characters, only when surrounded by non-word characters).
16614
- */
16615
- static matchLanguageName(descs, name, fuzzy = true) {
16616
- name = name.toLowerCase();
16617
- for (let d of descs) if (d.alias.some(a => a == name)) return d;
16618
- if (fuzzy) for (let d of descs) for (let a of d.alias) {
16619
- let found = name.indexOf(a);
16620
- if (found > -1 && (a.length > 2 || !/\w/.test(name[found - 1]) && !/\w/.test(name[found + a.length]))) return d;
16621
- }
16622
- return null;
16623
- }
16624
- }
16625
-
16626
- /**
16627
- Facet that defines a way to provide a function that computes the
16628
- appropriate indentation depth, as a column number (see
16629
- [`indentString`](https://codemirror.net/6/docs/ref/#language.indentString)), at the start of a given
16630
- line. A return value of `null` indicates no indentation can be
16631
- determined, and the line should inherit the indentation of the one
16632
- above it. A return value of `undefined` defers to the next indent
16633
- service.
16634
- */
16635
- const indentService = /*@__PURE__*/Facet.define();
16636
- /**
16637
- Facet for overriding the unit by which indentation happens.
16638
- Should be a string consisting either entirely of spaces or
16639
- entirely of tabs. When not set, this defaults to 2 spaces.
16640
- */
16641
- const indentUnit = /*@__PURE__*/Facet.define({
16642
- combine: values => {
16643
- if (!values.length) return " ";
16644
- if (!/^(?: +|\t+)$/.test(values[0])) throw new Error("Invalid indent unit: " + JSON.stringify(values[0]));
16645
- return values[0];
16646
- }
16647
- });
16648
- /**
16649
- Return the _column width_ of an indent unit in the state.
16650
- Determined by the [`indentUnit`](https://codemirror.net/6/docs/ref/#language.indentUnit)
16651
- facet, and [`tabSize`](https://codemirror.net/6/docs/ref/#state.EditorState^tabSize) when that
16652
- contains tabs.
16653
- */
16654
- function getIndentUnit(state) {
16655
- let unit = state.facet(indentUnit);
16656
- return unit.charCodeAt(0) == 9 ? state.tabSize * unit.length : unit.length;
16657
- }
16658
- /**
16659
- Create an indentation string that covers columns 0 to `cols`.
16660
- Will use tabs for as much of the columns as possible when the
16661
- [`indentUnit`](https://codemirror.net/6/docs/ref/#language.indentUnit) facet contains
16662
- tabs.
16663
- */
16664
- function indentString(state, cols) {
16665
- let result = "",
16666
- ts = state.tabSize;
16667
- if (state.facet(indentUnit).charCodeAt(0) == 9) while (cols >= ts) {
16668
- result += "\t";
16669
- cols -= ts;
16670
- }
16671
- for (let i = 0; i < cols; i++) result += " ";
16672
- return result;
16673
- }
16674
- /**
16675
- Get the indentation, as a column number, at the given position.
16676
- Will first consult any [indent services](https://codemirror.net/6/docs/ref/#language.indentService)
16677
- that are registered, and if none of those return an indentation,
16678
- this will check the syntax tree for the [indent node
16679
- prop](https://codemirror.net/6/docs/ref/#language.indentNodeProp) and use that if found. Returns a
16680
- number when an indentation could be determined, and null
16681
- otherwise.
16682
- */
16683
- function getIndentation(context, pos) {
16684
- if (context instanceof EditorState) context = new IndentContext(context);
16685
- for (let service of context.state.facet(indentService)) {
16686
- let result = service(context, pos);
16687
- if (result !== undefined) return result;
16688
- }
16689
- let tree = syntaxTree(context.state);
16690
- return tree ? syntaxIndentation(context, tree, pos) : null;
16691
- }
16692
- /**
16693
- Indentation contexts are used when calling [indentation
16694
- services](https://codemirror.net/6/docs/ref/#language.indentService). They provide helper utilities
16695
- useful in indentation logic, and can selectively override the
16696
- indentation reported for some lines.
16697
- */
16698
- class IndentContext {
16699
- /**
16700
- Create an indent context.
16701
- */
16702
- constructor(
16703
- /**
16704
- The editor state.
16705
- */
16706
- state,
16707
- /**
16708
- @internal
16709
- */
16710
- options = {}) {
16711
- this.state = state;
16712
- this.options = options;
16713
- this.unit = getIndentUnit(state);
16714
- }
16715
- /**
16716
- Get a description of the line at the given position, taking
16717
- [simulated line
16718
- breaks](https://codemirror.net/6/docs/ref/#language.IndentContext.constructor^options.simulateBreak)
16719
- into account. If there is such a break at `pos`, the `bias`
16720
- argument determines whether the part of the line line before or
16721
- after the break is used.
16722
- */
16723
- lineAt(pos, bias = 1) {
16724
- let line = this.state.doc.lineAt(pos);
16725
- let {
16726
- simulateBreak,
16727
- simulateDoubleBreak
16728
- } = this.options;
16729
- if (simulateBreak != null && simulateBreak >= line.from && simulateBreak <= line.to) {
16730
- if (simulateDoubleBreak && simulateBreak == pos) return {
16731
- text: "",
16732
- from: pos
16733
- };else if (bias < 0 ? simulateBreak < pos : simulateBreak <= pos) return {
16734
- text: line.text.slice(simulateBreak - line.from),
16735
- from: simulateBreak
16736
- };else return {
16737
- text: line.text.slice(0, simulateBreak - line.from),
16738
- from: line.from
16739
- };
16740
- }
16741
- return line;
16742
- }
16743
- /**
16744
- Get the text directly after `pos`, either the entire line
16745
- or the next 100 characters, whichever is shorter.
16746
- */
16747
- textAfterPos(pos, bias = 1) {
16748
- if (this.options.simulateDoubleBreak && pos == this.options.simulateBreak) return "";
16749
- let {
16750
- text,
16751
- from
16752
- } = this.lineAt(pos, bias);
16753
- return text.slice(pos - from, Math.min(text.length, pos + 100 - from));
16754
- }
16755
- /**
16756
- Find the column for the given position.
16757
- */
16758
- column(pos, bias = 1) {
16759
- let {
16760
- text,
16761
- from
16762
- } = this.lineAt(pos, bias);
16763
- let result = this.countColumn(text, pos - from);
16764
- let override = this.options.overrideIndentation ? this.options.overrideIndentation(from) : -1;
16765
- if (override > -1) result += override - this.countColumn(text, text.search(/\S|$/));
16766
- return result;
16767
- }
16768
- /**
16769
- Find the column position (taking tabs into account) of the given
16770
- position in the given string.
16771
- */
16772
- countColumn(line, pos = line.length) {
16773
- return countColumn(line, this.state.tabSize, pos);
16774
- }
16775
- /**
16776
- Find the indentation column of the line at the given point.
16777
- */
16778
- lineIndent(pos, bias = 1) {
16779
- let {
16780
- text,
16781
- from
16782
- } = this.lineAt(pos, bias);
16783
- let override = this.options.overrideIndentation;
16784
- if (override) {
16785
- let overriden = override(from);
16786
- if (overriden > -1) return overriden;
16787
- }
16788
- return this.countColumn(text, text.search(/\S|$/));
16789
- }
16790
- /**
16791
- Returns the [simulated line
16792
- break](https://codemirror.net/6/docs/ref/#language.IndentContext.constructor^options.simulateBreak)
16793
- for this context, if any.
16794
- */
16795
- get simulatedBreak() {
16796
- return this.options.simulateBreak || null;
16797
- }
16798
- }
16799
- /**
16800
- A syntax tree node prop used to associate indentation strategies
16801
- with node types. Such a strategy is a function from an indentation
16802
- context to a column number (see also
16803
- [`indentString`](https://codemirror.net/6/docs/ref/#language.indentString)) or null, where null
16804
- indicates that no definitive indentation can be determined.
16805
- */
16806
- const indentNodeProp = /*@__PURE__*/new NodeProp();
16807
- // Compute the indentation for a given position from the syntax tree.
16808
- function syntaxIndentation(cx, ast, pos) {
16809
- return indentFrom(ast.resolveInner(pos).enterUnfinishedNodesBefore(pos), pos, cx);
16810
- }
16811
- function ignoreClosed(cx) {
16812
- return cx.pos == cx.options.simulateBreak && cx.options.simulateDoubleBreak;
16813
- }
16814
- function indentStrategy(tree) {
16815
- let strategy = tree.type.prop(indentNodeProp);
16816
- if (strategy) return strategy;
16817
- let first = tree.firstChild,
16818
- close;
16819
- if (first && (close = first.type.prop(NodeProp.closedBy))) {
16820
- let last = tree.lastChild,
16821
- closed = last && close.indexOf(last.name) > -1;
16822
- return cx => delimitedStrategy(cx, true, 1, undefined, closed && !ignoreClosed(cx) ? last.from : undefined);
16823
- }
16824
- return tree.parent == null ? topIndent : null;
16825
- }
16826
- function indentFrom(node, pos, base) {
16827
- for (; node; node = node.parent) {
16828
- let strategy = indentStrategy(node);
16829
- if (strategy) return strategy(TreeIndentContext.create(base, pos, node));
16830
- }
16831
- return null;
16832
- }
16833
- function topIndent() {
16834
- return 0;
16835
- }
16836
- /**
16837
- Objects of this type provide context information and helper
16838
- methods to indentation functions registered on syntax nodes.
16839
- */
16840
- class TreeIndentContext extends IndentContext {
16841
- constructor(base,
16842
- /**
16843
- The position at which indentation is being computed.
16844
- */
16845
- pos,
16846
- /**
16847
- The syntax tree node to which the indentation strategy
16848
- applies.
16849
- */
16850
- node) {
16851
- super(base.state, base.options);
16852
- this.base = base;
16853
- this.pos = pos;
16854
- this.node = node;
16855
- }
16856
- /**
16857
- @internal
16858
- */
16859
- static create(base, pos, node) {
16860
- return new TreeIndentContext(base, pos, node);
16861
- }
16862
- /**
16863
- Get the text directly after `this.pos`, either the entire line
16864
- or the next 100 characters, whichever is shorter.
16865
- */
16866
- get textAfter() {
16867
- return this.textAfterPos(this.pos);
16868
- }
16869
- /**
16870
- Get the indentation at the reference line for `this.node`, which
16871
- is the line on which it starts, unless there is a node that is
16872
- _not_ a parent of this node covering the start of that line. If
16873
- so, the line at the start of that node is tried, again skipping
16874
- on if it is covered by another such node.
16875
- */
16876
- get baseIndent() {
16877
- let line = this.state.doc.lineAt(this.node.from);
16878
- // Skip line starts that are covered by a sibling (or cousin, etc)
16879
- for (;;) {
16880
- let atBreak = this.node.resolve(line.from);
16881
- while (atBreak.parent && atBreak.parent.from == atBreak.from) atBreak = atBreak.parent;
16882
- if (isParent(atBreak, this.node)) break;
16883
- line = this.state.doc.lineAt(atBreak.from);
16884
- }
16885
- return this.lineIndent(line.from);
16886
- }
16887
- /**
16888
- Continue looking for indentations in the node's parent nodes,
16889
- and return the result of that.
16890
- */
16891
- continue() {
16892
- let parent = this.node.parent;
16893
- return parent ? indentFrom(parent, this.pos, this.base) : 0;
16894
- }
16895
- }
16896
- function isParent(parent, of) {
16897
- for (let cur = of; cur; cur = cur.parent) if (parent == cur) return true;
16898
- return false;
16899
- }
16900
- // Check whether a delimited node is aligned (meaning there are
16901
- // non-skipped nodes on the same line as the opening delimiter). And
16902
- // if so, return the opening token.
16903
- function bracketedAligned(context) {
16904
- let tree = context.node;
16905
- let openToken = tree.childAfter(tree.from),
16906
- last = tree.lastChild;
16907
- if (!openToken) return null;
16908
- let sim = context.options.simulateBreak;
16909
- let openLine = context.state.doc.lineAt(openToken.from);
16910
- let lineEnd = sim == null || sim <= openLine.from ? openLine.to : Math.min(openLine.to, sim);
16911
- for (let pos = openToken.to;;) {
16912
- let next = tree.childAfter(pos);
16913
- if (!next || next == last) return null;
16914
- if (!next.type.isSkipped) return next.from < lineEnd ? openToken : null;
16915
- pos = next.to;
16916
- }
16917
- }
16918
- /**
16919
- An indentation strategy for delimited (usually bracketed) nodes.
16920
- Will, by default, indent one unit more than the parent's base
16921
- indent unless the line starts with a closing token. When `align`
16922
- is true and there are non-skipped nodes on the node's opening
16923
- line, the content of the node will be aligned with the end of the
16924
- opening node, like this:
16925
-
16926
- foo(bar,
16927
- baz)
16928
- */
16929
- function delimitedIndent({
16930
- closing,
16931
- align = true,
16932
- units = 1
16933
- }) {
16934
- return context => delimitedStrategy(context, align, units, closing);
16935
- }
16936
- function delimitedStrategy(context, align, units, closing, closedAt) {
16937
- let after = context.textAfter,
16938
- space = after.match(/^\s*/)[0].length;
16939
- let closed = closing && after.slice(space, space + closing.length) == closing || closedAt == context.pos + space;
16940
- let aligned = align ? bracketedAligned(context) : null;
16941
- if (aligned) return closed ? context.column(aligned.from) : context.column(aligned.to);
16942
- return context.baseIndent + (closed ? 0 : context.unit * units);
16943
- }
16944
- /**
16945
- An indentation strategy that aligns a node's content to its base
16946
- indentation.
16947
- */
16948
- const flatIndent = context => context.baseIndent;
16949
- /**
16950
- Creates an indentation strategy that, by default, indents
16951
- continued lines one unit more than the node's base indentation.
16952
- You can provide `except` to prevent indentation of lines that
16953
- match a pattern (for example `/^else\b/` in `if`/`else`
16954
- constructs), and you can change the amount of units used with the
16955
- `units` option.
16956
- */
16957
- function continuedIndent({
16958
- except,
16959
- units = 1
16960
- } = {}) {
16961
- return context => {
16962
- let matchExcept = except && except.test(context.textAfter);
16963
- return context.baseIndent + (matchExcept ? 0 : units * context.unit);
16964
- };
16965
- }
16966
- const DontIndentBeyond = 200;
16967
- /**
16968
- Enables reindentation on input. When a language defines an
16969
- `indentOnInput` field in its [language
16970
- data](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt), which must hold a regular
16971
- expression, the line at the cursor will be reindented whenever new
16972
- text is typed and the input from the start of the line up to the
16973
- cursor matches that regexp.
16974
-
16975
- To avoid unneccesary reindents, it is recommended to start the
16976
- regexp with `^` (usually followed by `\s*`), and end it with `$`.
16977
- For example, `/^\s*\}$/` will reindent when a closing brace is
16978
- added at the start of a line.
16979
- */
16980
- function indentOnInput() {
16981
- return EditorState.transactionFilter.of(tr => {
16982
- if (!tr.docChanged || !tr.isUserEvent("input.type") && !tr.isUserEvent("input.complete")) return tr;
16983
- let rules = tr.startState.languageDataAt("indentOnInput", tr.startState.selection.main.head);
16984
- if (!rules.length) return tr;
16985
- let doc = tr.newDoc,
16986
- {
16987
- head
16988
- } = tr.newSelection.main,
16989
- line = doc.lineAt(head);
16990
- if (head > line.from + DontIndentBeyond) return tr;
16991
- let lineStart = doc.sliceString(line.from, head);
16992
- if (!rules.some(r => r.test(lineStart))) return tr;
16993
- let {
16994
- state
16995
- } = tr,
16996
- last = -1,
16997
- changes = [];
16998
- for (let {
16999
- head
17000
- } of state.selection.ranges) {
17001
- let line = state.doc.lineAt(head);
17002
- if (line.from == last) continue;
17003
- last = line.from;
17004
- let indent = getIndentation(state, line.from);
17005
- if (indent == null) continue;
17006
- let cur = /^\s*/.exec(line.text)[0];
17007
- let norm = indentString(state, indent);
17008
- if (cur != norm) changes.push({
17009
- from: line.from,
17010
- to: line.from + cur.length,
17011
- insert: norm
17012
- });
17013
- }
17014
- return changes.length ? [tr, {
17015
- changes,
17016
- sequential: true
17017
- }] : tr;
17018
- });
17019
- }
17020
-
17021
- /**
17022
- A facet that registers a code folding service. When called with
17023
- the extent of a line, such a function should return a foldable
17024
- range that starts on that line (but continues beyond it), if one
17025
- can be found.
17026
- */
17027
- const foldService = /*@__PURE__*/Facet.define();
17028
- /**
17029
- This node prop is used to associate folding information with
17030
- syntax node types. Given a syntax node, it should check whether
17031
- that tree is foldable and return the range that can be collapsed
17032
- when it is.
17033
- */
17034
- const foldNodeProp = /*@__PURE__*/new NodeProp();
17035
- /**
17036
- [Fold](https://codemirror.net/6/docs/ref/#language.foldNodeProp) function that folds everything but
17037
- the first and the last child of a syntax node. Useful for nodes
17038
- that start and end with delimiters.
17039
- */
17040
- function foldInside(node) {
17041
- let first = node.firstChild,
17042
- last = node.lastChild;
17043
- return first && first.to < last.from ? {
17044
- from: first.to,
17045
- to: last.type.isError ? node.to : last.from
17046
- } : null;
17047
- }
17048
- function syntaxFolding(state, start, end) {
17049
- let tree = syntaxTree(state);
17050
- if (tree.length < end) return null;
17051
- let inner = tree.resolveInner(end, 1);
17052
- let found = null;
17053
- for (let cur = inner; cur; cur = cur.parent) {
17054
- if (cur.to <= end || cur.from > end) continue;
17055
- if (found && cur.from < start) break;
17056
- let prop = cur.type.prop(foldNodeProp);
17057
- if (prop && (cur.to < tree.length - 50 || tree.length == state.doc.length || !isUnfinished(cur))) {
17058
- let value = prop(cur, state);
17059
- if (value && value.from <= end && value.from >= start && value.to > end) found = value;
17060
- }
17061
- }
17062
- return found;
17063
- }
17064
- function isUnfinished(node) {
17065
- let ch = node.lastChild;
17066
- return ch && ch.to == node.to && ch.type.isError;
17067
- }
17068
- /**
17069
- Check whether the given line is foldable. First asks any fold
17070
- services registered through
17071
- [`foldService`](https://codemirror.net/6/docs/ref/#language.foldService), and if none of them return
17072
- a result, tries to query the [fold node
17073
- prop](https://codemirror.net/6/docs/ref/#language.foldNodeProp) of syntax nodes that cover the end
17074
- of the line.
17075
- */
17076
- function foldable(state, lineStart, lineEnd) {
17077
- for (let service of state.facet(foldService)) {
17078
- let result = service(state, lineStart, lineEnd);
17079
- if (result) return result;
17080
- }
17081
- return syntaxFolding(state, lineStart, lineEnd);
17082
- }
17083
- function mapRange(range, mapping) {
17084
- let from = mapping.mapPos(range.from, 1),
17085
- to = mapping.mapPos(range.to, -1);
17086
- return from >= to ? undefined : {
17087
- from,
17088
- to
17089
- };
17090
- }
17091
- /**
17092
- State effect that can be attached to a transaction to fold the
17093
- given range. (You probably only need this in exceptional
17094
- circumstances—usually you'll just want to let
17095
- [`foldCode`](https://codemirror.net/6/docs/ref/#language.foldCode) and the [fold
17096
- gutter](https://codemirror.net/6/docs/ref/#language.foldGutter) create the transactions.)
17097
- */
17098
- const foldEffect = /*@__PURE__*/StateEffect.define({
17099
- map: mapRange
17100
- });
17101
- /**
17102
- State effect that unfolds the given range (if it was folded).
17103
- */
17104
- const unfoldEffect = /*@__PURE__*/StateEffect.define({
17105
- map: mapRange
17106
- });
17107
- function selectedLines(view) {
17108
- let lines = [];
17109
- for (let {
17110
- head
17111
- } of view.state.selection.ranges) {
17112
- if (lines.some(l => l.from <= head && l.to >= head)) continue;
17113
- lines.push(view.lineBlockAt(head));
17114
- }
17115
- return lines;
17116
- }
17117
- /**
17118
- The state field that stores the folded ranges (as a [decoration
17119
- set](https://codemirror.net/6/docs/ref/#view.DecorationSet)). Can be passed to
17120
- [`EditorState.toJSON`](https://codemirror.net/6/docs/ref/#state.EditorState.toJSON) and
17121
- [`fromJSON`](https://codemirror.net/6/docs/ref/#state.EditorState^fromJSON) to serialize the fold
17122
- state.
17123
- */
17124
- const foldState = /*@__PURE__*/StateField.define({
17125
- create() {
17126
- return Decoration.none;
17127
- },
17128
- update(folded, tr) {
17129
- folded = folded.map(tr.changes);
17130
- for (let e of tr.effects) {
17131
- if (e.is(foldEffect) && !foldExists(folded, e.value.from, e.value.to)) folded = folded.update({
17132
- add: [foldWidget.range(e.value.from, e.value.to)]
17133
- });else if (e.is(unfoldEffect)) folded = folded.update({
17134
- filter: (from, to) => e.value.from != from || e.value.to != to,
17135
- filterFrom: e.value.from,
17136
- filterTo: e.value.to
17137
- });
17138
- }
17139
- // Clear folded ranges that cover the selection head
17140
- if (tr.selection) {
17141
- let onSelection = false,
17142
- {
17143
- head
17144
- } = tr.selection.main;
17145
- folded.between(head, head, (a, b) => {
17146
- if (a < head && b > head) onSelection = true;
17147
- });
17148
- if (onSelection) folded = folded.update({
17149
- filterFrom: head,
17150
- filterTo: head,
17151
- filter: (a, b) => b <= head || a >= head
17152
- });
17153
- }
17154
- return folded;
17155
- },
17156
- provide: f => EditorView.decorations.from(f),
17157
- toJSON(folded, state) {
17158
- let ranges = [];
17159
- folded.between(0, state.doc.length, (from, to) => {
17160
- ranges.push(from, to);
17161
- });
17162
- return ranges;
17163
- },
17164
- fromJSON(value) {
17165
- if (!Array.isArray(value) || value.length % 2) throw new RangeError("Invalid JSON for fold state");
17166
- let ranges = [];
17167
- for (let i = 0; i < value.length;) {
17168
- let from = value[i++],
17169
- to = value[i++];
17170
- if (typeof from != "number" || typeof to != "number") throw new RangeError("Invalid JSON for fold state");
17171
- ranges.push(foldWidget.range(from, to));
17172
- }
17173
- return Decoration.set(ranges, true);
17174
- }
17175
- });
17176
- function findFold(state, from, to) {
17177
- var _a;
17178
- let found = null;
17179
- (_a = state.field(foldState, false)) === null || _a === void 0 ? void 0 : _a.between(from, to, (from, to) => {
17180
- if (!found || found.from > from) found = {
17181
- from,
17182
- to
17183
- };
17184
- });
17185
- return found;
17186
- }
17187
- function foldExists(folded, from, to) {
17188
- let found = false;
17189
- folded.between(from, from, (a, b) => {
17190
- if (a == from && b == to) found = true;
17191
- });
17192
- return found;
17193
- }
17194
- function maybeEnable(state, other) {
17195
- return state.field(foldState, false) ? other : other.concat(StateEffect.appendConfig.of(codeFolding()));
17196
- }
17197
- /**
17198
- Fold the lines that are selected, if possible.
17199
- */
17200
- const foldCode = view => {
17201
- for (let line of selectedLines(view)) {
17202
- let range = foldable(view.state, line.from, line.to);
17203
- if (range) {
17204
- view.dispatch({
17205
- effects: maybeEnable(view.state, [foldEffect.of(range), announceFold(view, range)])
17206
- });
17207
- return true;
17208
- }
17209
- }
17210
- return false;
17211
- };
17212
- /**
17213
- Unfold folded ranges on selected lines.
17214
- */
17215
- const unfoldCode = view => {
17216
- if (!view.state.field(foldState, false)) return false;
17217
- let effects = [];
17218
- for (let line of selectedLines(view)) {
17219
- let folded = findFold(view.state, line.from, line.to);
17220
- if (folded) effects.push(unfoldEffect.of(folded), announceFold(view, folded, false));
17221
- }
17222
- if (effects.length) view.dispatch({
17223
- effects
17224
- });
17225
- return effects.length > 0;
17226
- };
17227
- function announceFold(view, range, fold = true) {
17228
- let lineFrom = view.state.doc.lineAt(range.from).number,
17229
- lineTo = view.state.doc.lineAt(range.to).number;
17230
- return EditorView.announce.of(`${view.state.phrase(fold ? "Folded lines" : "Unfolded lines")} ${lineFrom} ${view.state.phrase("to")} ${lineTo}.`);
17231
- }
17232
- /**
17233
- Fold all top-level foldable ranges. Note that, in most cases,
17234
- folding information will depend on the [syntax
17235
- tree](https://codemirror.net/6/docs/ref/#language.syntaxTree), and folding everything may not work
17236
- reliably when the document hasn't been fully parsed (either
17237
- because the editor state was only just initialized, or because the
17238
- document is so big that the parser decided not to parse it
17239
- entirely).
17240
- */
17241
- const foldAll = view => {
17242
- let {
17243
- state
17244
- } = view,
17245
- effects = [];
17246
- for (let pos = 0; pos < state.doc.length;) {
17247
- let line = view.lineBlockAt(pos),
17248
- range = foldable(state, line.from, line.to);
17249
- if (range) effects.push(foldEffect.of(range));
17250
- pos = (range ? view.lineBlockAt(range.to) : line).to + 1;
17251
- }
17252
- if (effects.length) view.dispatch({
17253
- effects: maybeEnable(view.state, effects)
17254
- });
17255
- return !!effects.length;
17256
- };
17257
- /**
17258
- Unfold all folded code.
17259
- */
17260
- const unfoldAll = view => {
17261
- let field = view.state.field(foldState, false);
17262
- if (!field || !field.size) return false;
17263
- let effects = [];
17264
- field.between(0, view.state.doc.length, (from, to) => {
17265
- effects.push(unfoldEffect.of({
17266
- from,
17267
- to
17268
- }));
17269
- });
17270
- view.dispatch({
17271
- effects
17272
- });
17273
- return true;
17274
- };
17275
- /**
17276
- Default fold-related key bindings.
17277
-
17278
- - Ctrl-Shift-[ (Cmd-Alt-[ on macOS): [`foldCode`](https://codemirror.net/6/docs/ref/#language.foldCode).
17279
- - Ctrl-Shift-] (Cmd-Alt-] on macOS): [`unfoldCode`](https://codemirror.net/6/docs/ref/#language.unfoldCode).
17280
- - Ctrl-Alt-[: [`foldAll`](https://codemirror.net/6/docs/ref/#language.foldAll).
17281
- - Ctrl-Alt-]: [`unfoldAll`](https://codemirror.net/6/docs/ref/#language.unfoldAll).
17282
- */
17283
- const foldKeymap = [{
17284
- key: "Ctrl-Shift-[",
17285
- mac: "Cmd-Alt-[",
17286
- run: foldCode
17287
- }, {
17288
- key: "Ctrl-Shift-]",
17289
- mac: "Cmd-Alt-]",
17290
- run: unfoldCode
17291
- }, {
17292
- key: "Ctrl-Alt-[",
17293
- run: foldAll
17294
- }, {
17295
- key: "Ctrl-Alt-]",
17296
- run: unfoldAll
17297
- }];
17298
- const defaultConfig = {
17299
- placeholderDOM: null,
17300
- placeholderText: "…"
17301
- };
17302
- const foldConfig = /*@__PURE__*/Facet.define({
17303
- combine(values) {
17304
- return combineConfig(values, defaultConfig);
17305
- }
17306
- });
17307
- /**
17308
- Create an extension that configures code folding.
17309
- */
17310
- function codeFolding(config) {
17311
- let result = [foldState, baseTheme$1];
17312
- if (config) result.push(foldConfig.of(config));
17313
- return result;
17314
- }
17315
- const foldWidget = /*@__PURE__*/Decoration.replace({
17316
- widget: /*@__PURE__*/new class extends WidgetType {
17317
- toDOM(view) {
17318
- let {
17319
- state
17320
- } = view,
17321
- conf = state.facet(foldConfig);
17322
- let onclick = event => {
17323
- let line = view.lineBlockAt(view.posAtDOM(event.target));
17324
- let folded = findFold(view.state, line.from, line.to);
17325
- if (folded) view.dispatch({
17326
- effects: unfoldEffect.of(folded)
17327
- });
17328
- event.preventDefault();
17329
- };
17330
- if (conf.placeholderDOM) return conf.placeholderDOM(view, onclick);
17331
- let element = document.createElement("span");
17332
- element.textContent = conf.placeholderText;
17333
- element.setAttribute("aria-label", state.phrase("folded code"));
17334
- element.title = state.phrase("unfold");
17335
- element.className = "cm-foldPlaceholder";
17336
- element.onclick = onclick;
17337
- return element;
17338
- }
17339
- }()
17340
- });
17341
- const foldGutterDefaults = {
17342
- openText: "⌄",
17343
- closedText: "›",
17344
- markerDOM: null,
17345
- domEventHandlers: {},
17346
- foldingChanged: () => false
17347
- };
17348
- class FoldMarker extends GutterMarker {
17349
- constructor(config, open) {
17350
- super();
17351
- this.config = config;
17352
- this.open = open;
17353
- }
17354
- eq(other) {
17355
- return this.config == other.config && this.open == other.open;
17356
- }
17357
- toDOM(view) {
17358
- if (this.config.markerDOM) return this.config.markerDOM(this.open);
17359
- let span = document.createElement("span");
17360
- span.textContent = this.open ? this.config.openText : this.config.closedText;
17361
- span.title = view.state.phrase(this.open ? "Fold line" : "Unfold line");
17362
- return span;
17363
- }
17364
- }
17365
- /**
17366
- Create an extension that registers a fold gutter, which shows a
17367
- fold status indicator before foldable lines (which can be clicked
17368
- to fold or unfold the line).
17369
- */
17370
- function foldGutter(config = {}) {
17371
- let fullConfig = Object.assign(Object.assign({}, foldGutterDefaults), config);
17372
- let canFold = new FoldMarker(fullConfig, true),
17373
- canUnfold = new FoldMarker(fullConfig, false);
17374
- let markers = ViewPlugin.fromClass(class {
17375
- constructor(view) {
17376
- this.from = view.viewport.from;
17377
- this.markers = this.buildMarkers(view);
17378
- }
17379
- update(update) {
17380
- if (update.docChanged || update.viewportChanged || update.startState.facet(language) != update.state.facet(language) || update.startState.field(foldState, false) != update.state.field(foldState, false) || syntaxTree(update.startState) != syntaxTree(update.state) || fullConfig.foldingChanged(update)) this.markers = this.buildMarkers(update.view);
17381
- }
17382
- buildMarkers(view) {
17383
- let builder = new RangeSetBuilder();
17384
- for (let line of view.viewportLineBlocks) {
17385
- let mark = findFold(view.state, line.from, line.to) ? canUnfold : foldable(view.state, line.from, line.to) ? canFold : null;
17386
- if (mark) builder.add(line.from, line.from, mark);
17387
- }
17388
- return builder.finish();
17389
- }
17390
- });
17391
- let {
17392
- domEventHandlers
17393
- } = fullConfig;
17394
- return [markers, gutter({
17395
- class: "cm-foldGutter",
17396
- markers(view) {
17397
- var _a;
17398
- return ((_a = view.plugin(markers)) === null || _a === void 0 ? void 0 : _a.markers) || RangeSet.empty;
17399
- },
17400
- initialSpacer() {
17401
- return new FoldMarker(fullConfig, false);
17402
- },
17403
- domEventHandlers: Object.assign(Object.assign({}, domEventHandlers), {
17404
- click: (view, line, event) => {
17405
- if (domEventHandlers.click && domEventHandlers.click(view, line, event)) return true;
17406
- let folded = findFold(view.state, line.from, line.to);
17407
- if (folded) {
17408
- view.dispatch({
17409
- effects: unfoldEffect.of(folded)
17410
- });
17411
- return true;
17412
- }
17413
- let range = foldable(view.state, line.from, line.to);
17414
- if (range) {
17415
- view.dispatch({
17416
- effects: foldEffect.of(range)
17417
- });
17418
- return true;
17419
- }
17420
- return false;
17421
- }
17422
- })
17423
- }), codeFolding()];
17424
- }
17425
- const baseTheme$1 = /*@__PURE__*/EditorView.baseTheme({
17426
- ".cm-foldPlaceholder": {
17427
- backgroundColor: "#eee",
17428
- border: "1px solid #ddd",
17429
- color: "#888",
17430
- borderRadius: ".2em",
17431
- margin: "0 1px",
17432
- padding: "0 1px",
17433
- cursor: "pointer"
17434
- },
17435
- ".cm-foldGutter span": {
17436
- padding: "0 1px",
17437
- cursor: "pointer"
17438
- }
17439
- });
17440
-
17441
- /**
17442
- A highlight style associates CSS styles with higlighting
17443
- [tags](https://lezer.codemirror.net/docs/ref#highlight.Tag).
17444
- */
17445
- class HighlightStyle {
17446
- constructor(
17447
- /**
17448
- The tag styles used to create this highlight style.
17449
- */
17450
- specs, options) {
17451
- this.specs = specs;
17452
- let modSpec;
17453
- function def(spec) {
17454
- let cls = StyleModule.newName();
17455
- (modSpec || (modSpec = Object.create(null)))["." + cls] = spec;
17456
- return cls;
17457
- }
17458
- const all = typeof options.all == "string" ? options.all : options.all ? def(options.all) : undefined;
17459
- const scopeOpt = options.scope;
17460
- this.scope = scopeOpt instanceof Language ? type => type.prop(languageDataProp) == scopeOpt.data : scopeOpt ? type => type == scopeOpt : undefined;
17461
- this.style = tagHighlighter(specs.map(style => ({
17462
- tag: style.tag,
17463
- class: style.class || def(Object.assign({}, style, {
17464
- tag: null
17465
- }))
17466
- })), {
17467
- all
17468
- }).style;
17469
- this.module = modSpec ? new StyleModule(modSpec) : null;
17470
- this.themeType = options.themeType;
17471
- }
17472
- /**
17473
- Create a highlighter style that associates the given styles to
17474
- the given tags. The specs must be objects that hold a style tag
17475
- or array of tags in their `tag` property, and either a single
17476
- `class` property providing a static CSS class (for highlighter
17477
- that rely on external styling), or a
17478
- [`style-mod`](https://github.com/marijnh/style-mod#documentation)-style
17479
- set of CSS properties (which define the styling for those tags).
17480
-
17481
- The CSS rules created for a highlighter will be emitted in the
17482
- order of the spec's properties. That means that for elements that
17483
- have multiple tags associated with them, styles defined further
17484
- down in the list will have a higher CSS precedence than styles
17485
- defined earlier.
17486
- */
17487
- static define(specs, options) {
17488
- return new HighlightStyle(specs, options || {});
17489
- }
17490
- }
17491
- const highlighterFacet = /*@__PURE__*/Facet.define();
17492
- const fallbackHighlighter = /*@__PURE__*/Facet.define({
17493
- combine(values) {
17494
- return values.length ? [values[0]] : null;
17495
- }
17496
- });
17497
- function getHighlighters(state) {
17498
- let main = state.facet(highlighterFacet);
17499
- return main.length ? main : state.facet(fallbackHighlighter);
17500
- }
17501
- /**
17502
- Wrap a highlighter in an editor extension that uses it to apply
17503
- syntax highlighting to the editor content.
17504
-
17505
- When multiple (non-fallback) styles are provided, the styling
17506
- applied is the union of the classes they emit.
17507
- */
17508
- function syntaxHighlighting(highlighter, options) {
17509
- let ext = [treeHighlighter],
17510
- themeType;
17511
- if (highlighter instanceof HighlightStyle) {
17512
- if (highlighter.module) ext.push(EditorView.styleModule.of(highlighter.module));
17513
- themeType = highlighter.themeType;
17514
- }
17515
- if (options === null || options === void 0 ? void 0 : options.fallback) ext.push(fallbackHighlighter.of(highlighter));else if (themeType) ext.push(highlighterFacet.computeN([EditorView.darkTheme], state => {
17516
- return state.facet(EditorView.darkTheme) == (themeType == "dark") ? [highlighter] : [];
17517
- }));else ext.push(highlighterFacet.of(highlighter));
17518
- return ext;
17519
- }
17520
- class TreeHighlighter {
17521
- constructor(view) {
17522
- this.markCache = Object.create(null);
17523
- this.tree = syntaxTree(view.state);
17524
- this.decorations = this.buildDeco(view, getHighlighters(view.state));
17525
- }
17526
- update(update) {
17527
- let tree = syntaxTree(update.state),
17528
- highlighters = getHighlighters(update.state);
17529
- let styleChange = highlighters != getHighlighters(update.startState);
17530
- if (tree.length < update.view.viewport.to && !styleChange && tree.type == this.tree.type) {
17531
- this.decorations = this.decorations.map(update.changes);
17532
- } else if (tree != this.tree || update.viewportChanged || styleChange) {
17533
- this.tree = tree;
17534
- this.decorations = this.buildDeco(update.view, highlighters);
17535
- }
17536
- }
17537
- buildDeco(view, highlighters) {
17538
- if (!highlighters || !this.tree.length) return Decoration.none;
17539
- let builder = new RangeSetBuilder();
17540
- for (let {
17541
- from,
17542
- to
17543
- } of view.visibleRanges) {
17544
- highlightTree(this.tree, highlighters, (from, to, style) => {
17545
- builder.add(from, to, this.markCache[style] || (this.markCache[style] = Decoration.mark({
17546
- class: style
17547
- })));
17548
- }, from, to);
17549
- }
17550
- return builder.finish();
17551
- }
17552
- }
17553
- const treeHighlighter = /*@__PURE__*/Prec.high( /*@__PURE__*/ViewPlugin.fromClass(TreeHighlighter, {
17554
- decorations: v => v.decorations
17555
- }));
17556
- /**
17557
- A default highlight style (works well with light themes).
17558
- */
17559
- const defaultHighlightStyle = /*@__PURE__*/HighlightStyle.define([{
17560
- tag: tags.meta,
17561
- color: "#404740"
17562
- }, {
17563
- tag: tags.link,
17564
- textDecoration: "underline"
17565
- }, {
17566
- tag: tags.heading,
17567
- textDecoration: "underline",
17568
- fontWeight: "bold"
17569
- }, {
17570
- tag: tags.emphasis,
17571
- fontStyle: "italic"
17572
- }, {
17573
- tag: tags.strong,
17574
- fontWeight: "bold"
17575
- }, {
17576
- tag: tags.strikethrough,
17577
- textDecoration: "line-through"
17578
- }, {
17579
- tag: tags.keyword,
17580
- color: "#708"
17581
- }, {
17582
- tag: [tags.atom, tags.bool, tags.url, tags.contentSeparator, tags.labelName],
17583
- color: "#219"
17584
- }, {
17585
- tag: [tags.literal, tags.inserted],
17586
- color: "#164"
17587
- }, {
17588
- tag: [tags.string, tags.deleted],
17589
- color: "#a11"
17590
- }, {
17591
- tag: [tags.regexp, tags.escape, /*@__PURE__*/tags.special(tags.string)],
17592
- color: "#e40"
17593
- }, {
17594
- tag: /*@__PURE__*/tags.definition(tags.variableName),
17595
- color: "#00f"
17596
- }, {
17597
- tag: /*@__PURE__*/tags.local(tags.variableName),
17598
- color: "#30a"
17599
- }, {
17600
- tag: [tags.typeName, tags.namespace],
17601
- color: "#085"
17602
- }, {
17603
- tag: tags.className,
17604
- color: "#167"
17605
- }, {
17606
- tag: [/*@__PURE__*/tags.special(tags.variableName), tags.macroName],
17607
- color: "#256"
17608
- }, {
17609
- tag: /*@__PURE__*/tags.definition(tags.propertyName),
17610
- color: "#00c"
17611
- }, {
17612
- tag: tags.comment,
17613
- color: "#940"
17614
- }, {
17615
- tag: tags.invalid,
17616
- color: "#f00"
17617
- }]);
17618
- const baseTheme = /*@__PURE__*/EditorView.baseTheme({
17619
- "&.cm-focused .cm-matchingBracket": {
17620
- backgroundColor: "#328c8252"
17621
- },
17622
- "&.cm-focused .cm-nonmatchingBracket": {
17623
- backgroundColor: "#bb555544"
17624
- }
17625
- });
17626
- const DefaultScanDist = 10000,
17627
- DefaultBrackets = "()[]{}";
17628
- const bracketMatchingConfig = /*@__PURE__*/Facet.define({
17629
- combine(configs) {
17630
- return combineConfig(configs, {
17631
- afterCursor: true,
17632
- brackets: DefaultBrackets,
17633
- maxScanDistance: DefaultScanDist,
17634
- renderMatch: defaultRenderMatch
17635
- });
17636
- }
17637
- });
17638
- const matchingMark = /*@__PURE__*/Decoration.mark({
17639
- class: "cm-matchingBracket"
17640
- }),
17641
- nonmatchingMark = /*@__PURE__*/Decoration.mark({
17642
- class: "cm-nonmatchingBracket"
17643
- });
17644
- function defaultRenderMatch(match) {
17645
- let decorations = [];
17646
- let mark = match.matched ? matchingMark : nonmatchingMark;
17647
- decorations.push(mark.range(match.start.from, match.start.to));
17648
- if (match.end) decorations.push(mark.range(match.end.from, match.end.to));
17649
- return decorations;
17650
- }
17651
- const bracketMatchingState = /*@__PURE__*/StateField.define({
17652
- create() {
17653
- return Decoration.none;
17654
- },
17655
- update(deco, tr) {
17656
- if (!tr.docChanged && !tr.selection) return deco;
17657
- let decorations = [];
17658
- let config = tr.state.facet(bracketMatchingConfig);
17659
- for (let range of tr.state.selection.ranges) {
17660
- if (!range.empty) continue;
17661
- let match = matchBrackets(tr.state, range.head, -1, config) || range.head > 0 && matchBrackets(tr.state, range.head - 1, 1, config) || config.afterCursor && (matchBrackets(tr.state, range.head, 1, config) || range.head < tr.state.doc.length && matchBrackets(tr.state, range.head + 1, -1, config));
17662
- if (match) decorations = decorations.concat(config.renderMatch(match, tr.state));
17663
- }
17664
- return Decoration.set(decorations, true);
17665
- },
17666
- provide: f => EditorView.decorations.from(f)
17667
- });
17668
- const bracketMatchingUnique = [bracketMatchingState, baseTheme];
17669
- /**
17670
- Create an extension that enables bracket matching. Whenever the
17671
- cursor is next to a bracket, that bracket and the one it matches
17672
- are highlighted. Or, when no matching bracket is found, another
17673
- highlighting style is used to indicate this.
17674
- */
17675
- function bracketMatching(config = {}) {
17676
- return [bracketMatchingConfig.of(config), bracketMatchingUnique];
17677
- }
17678
- /**
17679
- When larger syntax nodes, such as HTML tags, are marked as
17680
- opening/closing, it can be a bit messy to treat the whole node as
17681
- a matchable bracket. This node prop allows you to define, for such
17682
- a node, a ‘handle’—the part of the node that is highlighted, and
17683
- that the cursor must be on to activate highlighting in the first
17684
- place.
17685
- */
17686
- const bracketMatchingHandle = /*@__PURE__*/new NodeProp();
17687
- function matchingNodes(node, dir, brackets) {
17688
- let byProp = node.prop(dir < 0 ? NodeProp.openedBy : NodeProp.closedBy);
17689
- if (byProp) return byProp;
17690
- if (node.name.length == 1) {
17691
- let index = brackets.indexOf(node.name);
17692
- if (index > -1 && index % 2 == (dir < 0 ? 1 : 0)) return [brackets[index + dir]];
17693
- }
17694
- return null;
17695
- }
17696
- function findHandle(node) {
17697
- let hasHandle = node.type.prop(bracketMatchingHandle);
17698
- return hasHandle ? hasHandle(node.node) : node;
17699
- }
17700
- /**
17701
- Find the matching bracket for the token at `pos`, scanning
17702
- direction `dir`. Only the `brackets` and `maxScanDistance`
17703
- properties are used from `config`, if given. Returns null if no
17704
- bracket was found at `pos`, or a match result otherwise.
17705
- */
17706
- function matchBrackets(state, pos, dir, config = {}) {
17707
- let maxScanDistance = config.maxScanDistance || DefaultScanDist,
17708
- brackets = config.brackets || DefaultBrackets;
17709
- let tree = syntaxTree(state),
17710
- node = tree.resolveInner(pos, dir);
17711
- for (let cur = node; cur; cur = cur.parent) {
17712
- let matches = matchingNodes(cur.type, dir, brackets);
17713
- if (matches && cur.from < cur.to) {
17714
- let handle = findHandle(cur);
17715
- if (handle && (dir > 0 ? pos >= handle.from && pos < handle.to : pos > handle.from && pos <= handle.to)) return matchMarkedBrackets(state, pos, dir, cur, handle, matches, brackets);
17716
- }
17717
- }
17718
- return matchPlainBrackets(state, pos, dir, tree, node.type, maxScanDistance, brackets);
17719
- }
17720
- function matchMarkedBrackets(_state, _pos, dir, token, handle, matching, brackets) {
17721
- let parent = token.parent,
17722
- firstToken = {
17723
- from: handle.from,
17724
- to: handle.to
17725
- };
17726
- let depth = 0,
17727
- cursor = parent === null || parent === void 0 ? void 0 : parent.cursor();
17728
- if (cursor && (dir < 0 ? cursor.childBefore(token.from) : cursor.childAfter(token.to))) do {
17729
- if (dir < 0 ? cursor.to <= token.from : cursor.from >= token.to) {
17730
- if (depth == 0 && matching.indexOf(cursor.type.name) > -1 && cursor.from < cursor.to) {
17731
- let endHandle = findHandle(cursor);
17732
- return {
17733
- start: firstToken,
17734
- end: endHandle ? {
17735
- from: endHandle.from,
17736
- to: endHandle.to
17737
- } : undefined,
17738
- matched: true
17739
- };
17740
- } else if (matchingNodes(cursor.type, dir, brackets)) {
17741
- depth++;
17742
- } else if (matchingNodes(cursor.type, -dir, brackets)) {
17743
- if (depth == 0) {
17744
- let endHandle = findHandle(cursor);
17745
- return {
17746
- start: firstToken,
17747
- end: endHandle && endHandle.from < endHandle.to ? {
17748
- from: endHandle.from,
17749
- to: endHandle.to
17750
- } : undefined,
17751
- matched: false
17752
- };
17753
- }
17754
- depth--;
17755
- }
17756
- }
17757
- } while (dir < 0 ? cursor.prevSibling() : cursor.nextSibling());
17758
- return {
17759
- start: firstToken,
17760
- matched: false
17761
- };
17762
- }
17763
- function matchPlainBrackets(state, pos, dir, tree, tokenType, maxScanDistance, brackets) {
17764
- let startCh = dir < 0 ? state.sliceDoc(pos - 1, pos) : state.sliceDoc(pos, pos + 1);
17765
- let bracket = brackets.indexOf(startCh);
17766
- if (bracket < 0 || bracket % 2 == 0 != dir > 0) return null;
17767
- let startToken = {
17768
- from: dir < 0 ? pos - 1 : pos,
17769
- to: dir > 0 ? pos + 1 : pos
17770
- };
17771
- let iter = state.doc.iterRange(pos, dir > 0 ? state.doc.length : 0),
17772
- depth = 0;
17773
- for (let distance = 0; !iter.next().done && distance <= maxScanDistance;) {
17774
- let text = iter.value;
17775
- if (dir < 0) distance += text.length;
17776
- let basePos = pos + distance * dir;
17777
- for (let pos = dir > 0 ? 0 : text.length - 1, end = dir > 0 ? text.length : -1; pos != end; pos += dir) {
17778
- let found = brackets.indexOf(text[pos]);
17779
- if (found < 0 || tree.resolveInner(basePos + pos, 1).type != tokenType) continue;
17780
- if (found % 2 == 0 == dir > 0) {
17781
- depth++;
17782
- } else if (depth == 1) {
17783
- // Closing
17784
- return {
17785
- start: startToken,
17786
- end: {
17787
- from: basePos + pos,
17788
- to: basePos + pos + 1
17789
- },
17790
- matched: found >> 1 == bracket >> 1
17791
- };
17792
- } else {
17793
- depth--;
17794
- }
17795
- }
17796
- if (dir > 0) distance += text.length;
17797
- }
17798
- return iter.done ? {
17799
- start: startToken,
17800
- matched: false
17801
- } : null;
17802
- }
17803
- const noTokens = /*@__PURE__*/Object.create(null);
17804
- const typeArray = [NodeType.none];
17805
- const warned = [];
17806
- const defaultTable = /*@__PURE__*/Object.create(null);
17807
- for (let [legacyName, name] of [["variable", "variableName"], ["variable-2", "variableName.special"], ["string-2", "string.special"], ["def", "variableName.definition"], ["tag", "tagName"], ["attribute", "attributeName"], ["type", "typeName"], ["builtin", "variableName.standard"], ["qualifier", "modifier"], ["error", "invalid"], ["header", "heading"], ["property", "propertyName"]]) defaultTable[legacyName] = /*@__PURE__*/createTokenType(noTokens, name);
17808
- function warnForPart(part, msg) {
17809
- if (warned.indexOf(part) > -1) return;
17810
- warned.push(part);
17811
- console.warn(msg);
17812
- }
17813
- function createTokenType(extra, tagStr) {
17814
- let tag = null;
17815
- for (let part of tagStr.split(".")) {
17816
- let value = extra[part] || tags[part];
17817
- if (!value) {
17818
- warnForPart(part, `Unknown highlighting tag ${part}`);
17819
- } else if (typeof value == "function") {
17820
- if (!tag) warnForPart(part, `Modifier ${part} used at start of tag`);else tag = value(tag);
17821
- } else {
17822
- if (tag) warnForPart(part, `Tag ${part} used as modifier`);else tag = value;
17823
- }
17824
- }
17825
- if (!tag) return 0;
17826
- let name = tagStr.replace(/ /g, "_"),
17827
- type = NodeType.define({
17828
- id: typeArray.length,
17829
- name,
17830
- props: [styleTags({
17831
- [name]: tag
17832
- })]
17833
- });
17834
- typeArray.push(type);
17835
- return type.id;
17836
- }
17837
-
17838
- export { getTooltip as $, Annotation as A, highlightSpecialChars as B, ChangeSet as C, Direction as D, EditorView as E, Facet as F, foldGutter as G, drawSelection as H, IndentContext as I, dropCursor as J, indentOnInput as K, syntaxHighlighting as L, defaultHighlightStyle as M, NodeProp as N, bracketMatching as O, Prec as P, rectangularSelection as Q, RangeSetBuilder as R, StateField as S, Transaction as T, crosshairCursor as U, ViewPlugin as V, WidgetType as W, highlightActiveLine as X, keymap as Y, foldKeymap as Z, showTooltip as _, EditorSelection as a, MapMode as a0, RangeValue as a1, RangeSet as a2, Parser as a3, NodeSet as a4, NodeType as a5, DefaultBufferLength as a6, Tree as a7, IterMode as a8, styleTags as a9, tags as aa, parseMixed as ab, LanguageSupport as ac, LRLanguage as ad, indentNodeProp as ae, continuedIndent as af, foldNodeProp as ag, foldInside as ah, flatIndent as ai, delimitedIndent as aj, NodeWeakMap as ak, Tag as al, Language as am, defineLanguageFacet as an, languageDataProp as ao, LanguageDescription as ap, ParseContext as aq, HighlightStyle as ar, ChangeDesc as b, combineConfig as c, Text as d, indentUnit as e, countColumn as f, getIndentation as g, getIndentUnit as h, indentString as i, StateEffect as j, findClusterBreak as k, Decoration as l, matchBrackets as m, codePointAt as n, codePointSize as o, getPanel as p, CharCategory as q, fromCodePoint as r, syntaxTree as s, showPanel as t, EditorState as u, runScopeHandlers as v, hoverTooltip as w, logException as x, lineNumbers as y, highlightActiveLineGutter as z };
13195
+ export { Annotation as A, highlightActiveLine as B, ChangeSet as C, Direction as D, EditorView as E, Facet as F, gutter as G, RangeSet as H, StyleModule as I, GutterMarker as J, showTooltip as K, getTooltip as L, MapMode as M, RangeValue as N, Prec as P, RangeSetBuilder as R, StateField as S, Transaction as T, ViewPlugin as V, WidgetType as W, EditorState as a, EditorSelection as b, combineConfig as c, ChangeDesc as d, Text as e, countColumn as f, StateEffect as g, findClusterBreak as h, Decoration as i, codePointAt as j, keymap as k, codePointSize as l, getPanel as m, CharCategory as n, fromCodePoint as o, hoverTooltip as p, logException as q, runScopeHandlers as r, showPanel as s, lineNumbers as t, highlightActiveLineGutter as u, highlightSpecialChars as v, drawSelection as w, dropCursor as x, rectangularSelection as y, crosshairCursor as z };