@codemirror/language 0.19.10 → 0.20.2

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.
package/dist/index.js CHANGED
@@ -1,12 +1,13 @@
1
- import { NodeProp, Tree, TreeFragment, Parser, NodeType } from '@lezer/common';
2
- import { StateEffect, StateField, Facet, EditorState } from '@codemirror/state';
3
- import { ViewPlugin, logException } from '@codemirror/view';
4
- import { countColumn } from '@codemirror/text';
1
+ import { NodeProp, Tree, IterMode, TreeFragment, Parser, NodeType, NodeSet } from '@lezer/common';
2
+ import { StateEffect, StateField, Facet, EditorState, countColumn, combineConfig, RangeSet, RangeSetBuilder, Prec } from '@codemirror/state';
3
+ import { ViewPlugin, logException, Decoration, EditorView, WidgetType, gutter, GutterMarker } from '@codemirror/view';
4
+ import { tags, tagHighlighter, highlightTree, styleTags } from '@lezer/highlight';
5
+ import { StyleModule } from 'style-mod';
5
6
 
6
7
  var _a;
7
8
  /**
8
- Node prop stored in a grammar's top syntax node to provide the
9
- facet that stores language data for that language.
9
+ Node prop stored in a parser's top syntax node to provide the
10
+ facet that stores language-specific data for that language.
10
11
  */
11
12
  const languageDataProp = /*@__PURE__*/new NodeProp();
12
13
  /**
@@ -25,31 +26,27 @@ function defineLanguageFacet(baseData) {
25
26
  /**
26
27
  A language object manages parsing and per-language
27
28
  [metadata](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt). Parse data is
28
- managed as a [Lezer](https://lezer.codemirror.net) tree. You'll
29
- want to subclass this class for custom parsers, or use the
30
- [`LRLanguage`](https://codemirror.net/6/docs/ref/#language.LRLanguage) or
31
- [`StreamLanguage`](https://codemirror.net/6/docs/ref/#stream-parser.StreamLanguage) abstractions for
32
- [Lezer](https://lezer.codemirror.net/) or stream parsers.
29
+ managed as a [Lezer](https://lezer.codemirror.net) tree. The class
30
+ can be used directly, via the [`LRLanguage`](https://codemirror.net/6/docs/ref/#language.LRLanguage)
31
+ subclass for [Lezer](https://lezer.codemirror.net/) LR parsers, or
32
+ via the [`StreamLanguage`](https://codemirror.net/6/docs/ref/#language.StreamLanguage) subclass
33
+ for stream parsers.
33
34
  */
34
35
  class Language {
35
36
  /**
36
- Construct a language object. You usually don't need to invoke
37
- this directly. But when you do, make sure you use
38
- [`defineLanguageFacet`](https://codemirror.net/6/docs/ref/#language.defineLanguageFacet) to create
39
- the first argument.
37
+ Construct a language object. If you need to invoke this
38
+ directly, first define a data facet with
39
+ [`defineLanguageFacet`](https://codemirror.net/6/docs/ref/#language.defineLanguageFacet), and then
40
+ configure your parser to [attach](https://codemirror.net/6/docs/ref/#language.languageDataProp) it
41
+ to the language's outer syntax node.
40
42
  */
41
43
  constructor(
42
44
  /**
43
- The [language data](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt) data
44
- facet used for this language.
45
+ The [language data](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt) facet
46
+ used for this language.
45
47
  */
46
- data, parser,
47
- /**
48
- The node type of the top node of trees produced by this parser.
49
- */
50
- topNode, extraExtensions = []) {
48
+ data, parser, extraExtensions = []) {
51
49
  this.data = data;
52
- this.topNode = topNode;
53
50
  // Kludge to define EditorState.tree as a debugging helper,
54
51
  // without the EditorState package actually knowing about
55
52
  // languages and lezer trees.
@@ -126,7 +123,7 @@ function languageDataFacetAt(state, pos, side) {
126
123
  return null;
127
124
  let facet = topLang.data;
128
125
  if (topLang.allowsNesting) {
129
- for (let node = syntaxTree(state).topNode; node; node = node.enter(pos, side, true, false))
126
+ for (let node = syntaxTree(state).topNode; node; node = node.enter(pos, side, IterMode.ExcludeBuffers))
130
127
  facet = node.type.prop(languageDataProp) || facet;
131
128
  }
132
129
  return facet;
@@ -138,7 +135,7 @@ parsers.
138
135
  */
139
136
  class LRLanguage extends Language {
140
137
  constructor(data, parser) {
141
- super(data, parser, parser.topNode);
138
+ super(data, parser);
142
139
  this.parser = parser;
143
140
  }
144
141
  /**
@@ -157,12 +154,13 @@ class LRLanguage extends Language {
157
154
  configure(options) {
158
155
  return new LRLanguage(this.data, this.parser.configure(options));
159
156
  }
160
- get allowsNesting() { return this.parser.wrappers.length > 0; } // FIXME
157
+ get allowsNesting() { return this.parser.hasWrappers(); }
161
158
  }
162
159
  /**
163
160
  Get the syntax tree for a state, which is the current (possibly
164
- incomplete) parse tree of active [language](https://codemirror.net/6/docs/ref/#language.Language),
165
- or the empty tree if there is no language available.
161
+ incomplete) parse tree of the active
162
+ [language](https://codemirror.net/6/docs/ref/#language.Language), or the empty tree if there is no
163
+ language available.
166
164
  */
167
165
  function syntaxTree(state) {
168
166
  let field = state.field(Language.state, false);
@@ -183,7 +181,7 @@ Queries whether there is a full syntax tree available up to the
183
181
  given document position. If there isn't, the background parse
184
182
  process _might_ still be working and update the tree further, but
185
183
  there is no guarantee of that—the parser will [stop
186
- working](https://codemirror.net/6/docs/ref/#language.syntaxParserStopped) when it has spent a
184
+ working](https://codemirror.net/6/docs/ref/#language.syntaxParserRunning) when it has spent a
187
185
  certain amount of time or has moved beyond the visible viewport.
188
186
  Always returns false if no language has been enabled.
189
187
  */
@@ -192,6 +190,18 @@ function syntaxTreeAvailable(state, upto = state.doc.length) {
192
190
  return ((_a = state.field(Language.state, false)) === null || _a === void 0 ? void 0 : _a.context.isDone(upto)) || false;
193
191
  }
194
192
  /**
193
+ Move parsing forward, and update the editor state afterwards to
194
+ reflect the new tree. Will work for at most `timeout`
195
+ milliseconds. Returns true if the parser managed get to the given
196
+ position in that time.
197
+ */
198
+ function forceParsing(view, upto = view.viewport.to, timeout = 100) {
199
+ let success = ensureSyntaxTree(view.state, upto, timeout);
200
+ if (success != syntaxTree(view.state))
201
+ view.dispatch({});
202
+ return !!success;
203
+ }
204
+ /**
195
205
  Tells you whether the language parser is planning to do more
196
206
  parsing work (in a `requestIdleCallback` pseudo-thread) or has
197
207
  stopped running, either because it parsed the entire document,
@@ -234,9 +244,6 @@ let currentContext = null;
234
244
  A parse context provided to parsers working on the editor content.
235
245
  */
236
246
  class ParseContext {
237
- /**
238
- @internal
239
- */
240
247
  constructor(parser,
241
248
  /**
242
249
  The current editor state.
@@ -249,7 +256,11 @@ class ParseContext {
249
256
  /**
250
257
  @internal
251
258
  */
252
- tree, treeLen,
259
+ tree,
260
+ /**
261
+ @internal
262
+ */
263
+ treeLen,
253
264
  /**
254
265
  The current editor viewport (or some overapproximation
255
266
  thereof). Intended to be used for opportunistically avoiding
@@ -283,6 +294,12 @@ class ParseContext {
283
294
  */
284
295
  this.tempSkipped = [];
285
296
  }
297
+ /**
298
+ @internal
299
+ */
300
+ static create(parser, state, viewport) {
301
+ return new ParseContext(parser, state, [], Tree.empty, 0, viewport, [], null);
302
+ }
286
303
  startParse() {
287
304
  return this.parser.startParse(new DocInput(this.state.doc), this.fragments);
288
305
  }
@@ -488,7 +505,7 @@ class LanguageState {
488
505
  }
489
506
  static init(state) {
490
507
  let vpTo = Math.min(3000 /* InitViewport */, state.doc.length);
491
- let parseState = new ParseContext(state.facet(language).parser, state, [], Tree.empty, 0, { from: 0, to: vpTo }, [], null);
508
+ let parseState = ParseContext.create(state.facet(language).parser, state, { from: 0, to: vpTo });
492
509
  if (!parseState.work(20 /* Apply */, vpTo))
493
510
  parseState.takeTree();
494
511
  return new LanguageState(parseState);
@@ -602,7 +619,7 @@ const language = /*@__PURE__*/Facet.define({
602
619
  enables: [Language.state, parseWorker]
603
620
  });
604
621
  /**
605
- This class bundles a [language object](https://codemirror.net/6/docs/ref/#language.Language) with an
622
+ This class bundles a [language](https://codemirror.net/6/docs/ref/#language.Language) with an
606
623
  optional set of supporting extensions. Language packages are
607
624
  encouraged to export a function that optionally takes a
608
625
  configuration object and returns a `LanguageSupport` instance, as
@@ -610,7 +627,7 @@ the main way for client code to use the package.
610
627
  */
611
628
  class LanguageSupport {
612
629
  /**
613
- Create a support object.
630
+ Create a language support object.
614
631
  */
615
632
  constructor(
616
633
  /**
@@ -916,19 +933,16 @@ function indentFrom(node, pos, base) {
916
933
  for (; node; node = node.parent) {
917
934
  let strategy = indentStrategy(node);
918
935
  if (strategy)
919
- return strategy(new TreeIndentContext(base, pos, node));
936
+ return strategy(TreeIndentContext.create(base, pos, node));
920
937
  }
921
938
  return null;
922
939
  }
923
940
  function topIndent() { return 0; }
924
941
  /**
925
942
  Objects of this type provide context information and helper
926
- methods to indentation functions.
943
+ methods to indentation functions registered on syntax nodes.
927
944
  */
928
945
  class TreeIndentContext extends IndentContext {
929
- /**
930
- @internal
931
- */
932
946
  constructor(base,
933
947
  /**
934
948
  The position at which indentation is being computed.
@@ -945,6 +959,12 @@ class TreeIndentContext extends IndentContext {
945
959
  this.node = node;
946
960
  }
947
961
  /**
962
+ @internal
963
+ */
964
+ static create(base, pos, node) {
965
+ return new TreeIndentContext(base, pos, node);
966
+ }
967
+ /**
948
968
  Get the text directly after `this.pos`, either the entire line
949
969
  or the next 100 characters, whichever is shorter.
950
970
  */
@@ -1117,7 +1137,7 @@ function foldInside(node) {
1117
1137
  }
1118
1138
  function syntaxFolding(state, start, end) {
1119
1139
  let tree = syntaxTree(state);
1120
- if (tree.length == 0)
1140
+ if (tree.length < end)
1121
1141
  return null;
1122
1142
  let inner = tree.resolveInner(end);
1123
1143
  let found = null;
@@ -1155,5 +1175,1134 @@ function foldable(state, lineStart, lineEnd) {
1155
1175
  }
1156
1176
  return syntaxFolding(state, lineStart, lineEnd);
1157
1177
  }
1178
+ function mapRange(range, mapping) {
1179
+ let from = mapping.mapPos(range.from, 1), to = mapping.mapPos(range.to, -1);
1180
+ return from >= to ? undefined : { from, to };
1181
+ }
1182
+ /**
1183
+ State effect that can be attached to a transaction to fold the
1184
+ given range. (You probably only need this in exceptional
1185
+ circumstances—usually you'll just want to let
1186
+ [`foldCode`](https://codemirror.net/6/docs/ref/#language.foldCode) and the [fold
1187
+ gutter](https://codemirror.net/6/docs/ref/#language.foldGutter) create the transactions.)
1188
+ */
1189
+ const foldEffect = /*@__PURE__*/StateEffect.define({ map: mapRange });
1190
+ /**
1191
+ State effect that unfolds the given range (if it was folded).
1192
+ */
1193
+ const unfoldEffect = /*@__PURE__*/StateEffect.define({ map: mapRange });
1194
+ function selectedLines(view) {
1195
+ let lines = [];
1196
+ for (let { head } of view.state.selection.ranges) {
1197
+ if (lines.some(l => l.from <= head && l.to >= head))
1198
+ continue;
1199
+ lines.push(view.lineBlockAt(head));
1200
+ }
1201
+ return lines;
1202
+ }
1203
+ const foldState = /*@__PURE__*/StateField.define({
1204
+ create() {
1205
+ return Decoration.none;
1206
+ },
1207
+ update(folded, tr) {
1208
+ folded = folded.map(tr.changes);
1209
+ for (let e of tr.effects) {
1210
+ if (e.is(foldEffect) && !foldExists(folded, e.value.from, e.value.to))
1211
+ folded = folded.update({ add: [foldWidget.range(e.value.from, e.value.to)] });
1212
+ else if (e.is(unfoldEffect))
1213
+ folded = folded.update({ filter: (from, to) => e.value.from != from || e.value.to != to,
1214
+ filterFrom: e.value.from, filterTo: e.value.to });
1215
+ }
1216
+ // Clear folded ranges that cover the selection head
1217
+ if (tr.selection) {
1218
+ let onSelection = false, { head } = tr.selection.main;
1219
+ folded.between(head, head, (a, b) => { if (a < head && b > head)
1220
+ onSelection = true; });
1221
+ if (onSelection)
1222
+ folded = folded.update({
1223
+ filterFrom: head,
1224
+ filterTo: head,
1225
+ filter: (a, b) => b <= head || a >= head
1226
+ });
1227
+ }
1228
+ return folded;
1229
+ },
1230
+ provide: f => EditorView.decorations.from(f)
1231
+ });
1232
+ /**
1233
+ Get a [range set](https://codemirror.net/6/docs/ref/#state.RangeSet) containing the folded ranges
1234
+ in the given state.
1235
+ */
1236
+ function foldedRanges(state) {
1237
+ return state.field(foldState, false) || RangeSet.empty;
1238
+ }
1239
+ function findFold(state, from, to) {
1240
+ var _a;
1241
+ let found = null;
1242
+ (_a = state.field(foldState, false)) === null || _a === void 0 ? void 0 : _a.between(from, to, (from, to) => {
1243
+ if (!found || found.from > from)
1244
+ found = { from, to };
1245
+ });
1246
+ return found;
1247
+ }
1248
+ function foldExists(folded, from, to) {
1249
+ let found = false;
1250
+ folded.between(from, from, (a, b) => { if (a == from && b == to)
1251
+ found = true; });
1252
+ return found;
1253
+ }
1254
+ function maybeEnable(state, other) {
1255
+ return state.field(foldState, false) ? other : other.concat(StateEffect.appendConfig.of(codeFolding()));
1256
+ }
1257
+ /**
1258
+ Fold the lines that are selected, if possible.
1259
+ */
1260
+ const foldCode = view => {
1261
+ for (let line of selectedLines(view)) {
1262
+ let range = foldable(view.state, line.from, line.to);
1263
+ if (range) {
1264
+ view.dispatch({ effects: maybeEnable(view.state, [foldEffect.of(range), announceFold(view, range)]) });
1265
+ return true;
1266
+ }
1267
+ }
1268
+ return false;
1269
+ };
1270
+ /**
1271
+ Unfold folded ranges on selected lines.
1272
+ */
1273
+ const unfoldCode = view => {
1274
+ if (!view.state.field(foldState, false))
1275
+ return false;
1276
+ let effects = [];
1277
+ for (let line of selectedLines(view)) {
1278
+ let folded = findFold(view.state, line.from, line.to);
1279
+ if (folded)
1280
+ effects.push(unfoldEffect.of(folded), announceFold(view, folded, false));
1281
+ }
1282
+ if (effects.length)
1283
+ view.dispatch({ effects });
1284
+ return effects.length > 0;
1285
+ };
1286
+ function announceFold(view, range, fold = true) {
1287
+ let lineFrom = view.state.doc.lineAt(range.from).number, lineTo = view.state.doc.lineAt(range.to).number;
1288
+ return EditorView.announce.of(`${view.state.phrase(fold ? "Folded lines" : "Unfolded lines")} ${lineFrom} ${view.state.phrase("to")} ${lineTo}.`);
1289
+ }
1290
+ /**
1291
+ Fold all top-level foldable ranges. Note that, in most cases,
1292
+ folding information will depend on the [syntax
1293
+ tree](https://codemirror.net/6/docs/ref/#language.syntaxTree), and folding everything may not work
1294
+ reliably when the document hasn't been fully parsed (either
1295
+ because the editor state was only just initialized, or because the
1296
+ document is so big that the parser decided not to parse it
1297
+ entirely).
1298
+ */
1299
+ const foldAll = view => {
1300
+ let { state } = view, effects = [];
1301
+ for (let pos = 0; pos < state.doc.length;) {
1302
+ let line = view.lineBlockAt(pos), range = foldable(state, line.from, line.to);
1303
+ if (range)
1304
+ effects.push(foldEffect.of(range));
1305
+ pos = (range ? view.lineBlockAt(range.to) : line).to + 1;
1306
+ }
1307
+ if (effects.length)
1308
+ view.dispatch({ effects: maybeEnable(view.state, effects) });
1309
+ return !!effects.length;
1310
+ };
1311
+ /**
1312
+ Unfold all folded code.
1313
+ */
1314
+ const unfoldAll = view => {
1315
+ let field = view.state.field(foldState, false);
1316
+ if (!field || !field.size)
1317
+ return false;
1318
+ let effects = [];
1319
+ field.between(0, view.state.doc.length, (from, to) => { effects.push(unfoldEffect.of({ from, to })); });
1320
+ view.dispatch({ effects });
1321
+ return true;
1322
+ };
1323
+ /**
1324
+ Default fold-related key bindings.
1325
+
1326
+ - Ctrl-Shift-[ (Cmd-Alt-[ on macOS): [`foldCode`](https://codemirror.net/6/docs/ref/#language.foldCode).
1327
+ - Ctrl-Shift-] (Cmd-Alt-] on macOS): [`unfoldCode`](https://codemirror.net/6/docs/ref/#language.unfoldCode).
1328
+ - Ctrl-Alt-[: [`foldAll`](https://codemirror.net/6/docs/ref/#language.foldAll).
1329
+ - Ctrl-Alt-]: [`unfoldAll`](https://codemirror.net/6/docs/ref/#language.unfoldAll).
1330
+ */
1331
+ const foldKeymap = [
1332
+ { key: "Ctrl-Shift-[", mac: "Cmd-Alt-[", run: foldCode },
1333
+ { key: "Ctrl-Shift-]", mac: "Cmd-Alt-]", run: unfoldCode },
1334
+ { key: "Ctrl-Alt-[", run: foldAll },
1335
+ { key: "Ctrl-Alt-]", run: unfoldAll }
1336
+ ];
1337
+ const defaultConfig = {
1338
+ placeholderDOM: null,
1339
+ placeholderText: "…"
1340
+ };
1341
+ const foldConfig = /*@__PURE__*/Facet.define({
1342
+ combine(values) { return combineConfig(values, defaultConfig); }
1343
+ });
1344
+ /**
1345
+ Create an extension that configures code folding.
1346
+ */
1347
+ function codeFolding(config) {
1348
+ let result = [foldState, baseTheme$1];
1349
+ if (config)
1350
+ result.push(foldConfig.of(config));
1351
+ return result;
1352
+ }
1353
+ const foldWidget = /*@__PURE__*/Decoration.replace({ widget: /*@__PURE__*/new class extends WidgetType {
1354
+ toDOM(view) {
1355
+ let { state } = view, conf = state.facet(foldConfig);
1356
+ let onclick = (event) => {
1357
+ let line = view.lineBlockAt(view.posAtDOM(event.target));
1358
+ let folded = findFold(view.state, line.from, line.to);
1359
+ if (folded)
1360
+ view.dispatch({ effects: unfoldEffect.of(folded) });
1361
+ event.preventDefault();
1362
+ };
1363
+ if (conf.placeholderDOM)
1364
+ return conf.placeholderDOM(view, onclick);
1365
+ let element = document.createElement("span");
1366
+ element.textContent = conf.placeholderText;
1367
+ element.setAttribute("aria-label", state.phrase("folded code"));
1368
+ element.title = state.phrase("unfold");
1369
+ element.className = "cm-foldPlaceholder";
1370
+ element.onclick = onclick;
1371
+ return element;
1372
+ }
1373
+ } });
1374
+ const foldGutterDefaults = {
1375
+ openText: "⌄",
1376
+ closedText: "›",
1377
+ markerDOM: null,
1378
+ domEventHandlers: {},
1379
+ };
1380
+ class FoldMarker extends GutterMarker {
1381
+ constructor(config, open) {
1382
+ super();
1383
+ this.config = config;
1384
+ this.open = open;
1385
+ }
1386
+ eq(other) { return this.config == other.config && this.open == other.open; }
1387
+ toDOM(view) {
1388
+ if (this.config.markerDOM)
1389
+ return this.config.markerDOM(this.open);
1390
+ let span = document.createElement("span");
1391
+ span.textContent = this.open ? this.config.openText : this.config.closedText;
1392
+ span.title = view.state.phrase(this.open ? "Fold line" : "Unfold line");
1393
+ return span;
1394
+ }
1395
+ }
1396
+ /**
1397
+ Create an extension that registers a fold gutter, which shows a
1398
+ fold status indicator before foldable lines (which can be clicked
1399
+ to fold or unfold the line).
1400
+ */
1401
+ function foldGutter(config = {}) {
1402
+ let fullConfig = Object.assign(Object.assign({}, foldGutterDefaults), config);
1403
+ let canFold = new FoldMarker(fullConfig, true), canUnfold = new FoldMarker(fullConfig, false);
1404
+ let markers = ViewPlugin.fromClass(class {
1405
+ constructor(view) {
1406
+ this.from = view.viewport.from;
1407
+ this.markers = this.buildMarkers(view);
1408
+ }
1409
+ update(update) {
1410
+ if (update.docChanged || update.viewportChanged ||
1411
+ update.startState.facet(language) != update.state.facet(language) ||
1412
+ update.startState.field(foldState, false) != update.state.field(foldState, false) ||
1413
+ syntaxTree(update.startState) != syntaxTree(update.state))
1414
+ this.markers = this.buildMarkers(update.view);
1415
+ }
1416
+ buildMarkers(view) {
1417
+ let builder = new RangeSetBuilder();
1418
+ for (let line of view.viewportLineBlocks) {
1419
+ let mark = findFold(view.state, line.from, line.to) ? canUnfold
1420
+ : foldable(view.state, line.from, line.to) ? canFold : null;
1421
+ if (mark)
1422
+ builder.add(line.from, line.from, mark);
1423
+ }
1424
+ return builder.finish();
1425
+ }
1426
+ });
1427
+ let { domEventHandlers } = fullConfig;
1428
+ return [
1429
+ markers,
1430
+ gutter({
1431
+ class: "cm-foldGutter",
1432
+ markers(view) { var _a; return ((_a = view.plugin(markers)) === null || _a === void 0 ? void 0 : _a.markers) || RangeSet.empty; },
1433
+ initialSpacer() {
1434
+ return new FoldMarker(fullConfig, false);
1435
+ },
1436
+ domEventHandlers: Object.assign(Object.assign({}, domEventHandlers), { click: (view, line, event) => {
1437
+ if (domEventHandlers.click && domEventHandlers.click(view, line, event))
1438
+ return true;
1439
+ let folded = findFold(view.state, line.from, line.to);
1440
+ if (folded) {
1441
+ view.dispatch({ effects: unfoldEffect.of(folded) });
1442
+ return true;
1443
+ }
1444
+ let range = foldable(view.state, line.from, line.to);
1445
+ if (range) {
1446
+ view.dispatch({ effects: foldEffect.of(range) });
1447
+ return true;
1448
+ }
1449
+ return false;
1450
+ } })
1451
+ }),
1452
+ codeFolding()
1453
+ ];
1454
+ }
1455
+ const baseTheme$1 = /*@__PURE__*/EditorView.baseTheme({
1456
+ ".cm-foldPlaceholder": {
1457
+ backgroundColor: "#eee",
1458
+ border: "1px solid #ddd",
1459
+ color: "#888",
1460
+ borderRadius: ".2em",
1461
+ margin: "0 1px",
1462
+ padding: "0 1px",
1463
+ cursor: "pointer"
1464
+ },
1465
+ ".cm-foldGutter span": {
1466
+ padding: "0 1px",
1467
+ cursor: "pointer"
1468
+ }
1469
+ });
1470
+
1471
+ /**
1472
+ A highlight style associates CSS styles with higlighting
1473
+ [tags](https://lezer.codemirror.net/docs/ref#highlight.Tag).
1474
+ */
1475
+ class HighlightStyle {
1476
+ constructor(spec, options) {
1477
+ let modSpec;
1478
+ function def(spec) {
1479
+ let cls = StyleModule.newName();
1480
+ (modSpec || (modSpec = Object.create(null)))["." + cls] = spec;
1481
+ return cls;
1482
+ }
1483
+ const all = typeof options.all == "string" ? options.all : options.all ? def(options.all) : undefined;
1484
+ const scopeOpt = options.scope;
1485
+ this.scope = scopeOpt instanceof Language ? (type) => type.prop(languageDataProp) == scopeOpt.data
1486
+ : scopeOpt ? (type) => type == scopeOpt : undefined;
1487
+ this.style = tagHighlighter(spec.map(style => ({
1488
+ tag: style.tag,
1489
+ class: style.class || def(Object.assign({}, style, { tag: null }))
1490
+ })), {
1491
+ all,
1492
+ }).style;
1493
+ this.module = modSpec ? new StyleModule(modSpec) : null;
1494
+ this.themeType = options.themeType;
1495
+ }
1496
+ /**
1497
+ Create a highlighter style that associates the given styles to
1498
+ the given tags. The specs must be objects that hold a style tag
1499
+ or array of tags in their `tag` property, and either a single
1500
+ `class` property providing a static CSS class (for highlighter
1501
+ that rely on external styling), or a
1502
+ [`style-mod`](https://github.com/marijnh/style-mod#documentation)-style
1503
+ set of CSS properties (which define the styling for those tags).
1504
+
1505
+ The CSS rules created for a highlighter will be emitted in the
1506
+ order of the spec's properties. That means that for elements that
1507
+ have multiple tags associated with them, styles defined further
1508
+ down in the list will have a higher CSS precedence than styles
1509
+ defined earlier.
1510
+ */
1511
+ static define(specs, options) {
1512
+ return new HighlightStyle(specs, options || {});
1513
+ }
1514
+ }
1515
+ const highlighterFacet = /*@__PURE__*/Facet.define();
1516
+ const fallbackHighlighter = /*@__PURE__*/Facet.define({
1517
+ combine(values) { return values.length ? [values[0]] : null; }
1518
+ });
1519
+ function getHighlighters(state) {
1520
+ let main = state.facet(highlighterFacet);
1521
+ return main.length ? main : state.facet(fallbackHighlighter);
1522
+ }
1523
+ /**
1524
+ Wrap a highlighter in an editor extension that uses it to apply
1525
+ syntax highlighting to the editor content.
1526
+
1527
+ When multiple (non-fallback) styles are provided, the styling
1528
+ applied is the union of the classes they emit.
1529
+ */
1530
+ function syntaxHighlighting(highlighter, options) {
1531
+ let ext = [treeHighlighter], themeType;
1532
+ if (highlighter instanceof HighlightStyle) {
1533
+ if (highlighter.module)
1534
+ ext.push(EditorView.styleModule.of(highlighter.module));
1535
+ themeType = highlighter.themeType;
1536
+ }
1537
+ if (options === null || options === void 0 ? void 0 : options.fallback)
1538
+ ext.push(fallbackHighlighter.of(highlighter));
1539
+ else if (themeType)
1540
+ ext.push(highlighterFacet.computeN([EditorView.darkTheme], state => {
1541
+ return state.facet(EditorView.darkTheme) == (themeType == "dark") ? [highlighter] : [];
1542
+ }));
1543
+ else
1544
+ ext.push(highlighterFacet.of(highlighter));
1545
+ return ext;
1546
+ }
1547
+ /**
1548
+ Returns the CSS classes (if any) that the highlighters active in
1549
+ the state would assign to the given style
1550
+ [tags](https://lezer.codemirror.net/docs/ref#highlight.Tag) and
1551
+ (optional) language
1552
+ [scope](https://codemirror.net/6/docs/ref/#language.HighlightStyle^define^options.scope).
1553
+ */
1554
+ function highlightingFor(state, tags, scope) {
1555
+ let highlighters = getHighlighters(state);
1556
+ let result = null;
1557
+ if (highlighters)
1558
+ for (let highlighter of highlighters) {
1559
+ if (!highlighter.scope || scope && highlighter.scope(scope)) {
1560
+ let cls = highlighter.style(tags);
1561
+ if (cls)
1562
+ result = result ? result + " " + cls : cls;
1563
+ }
1564
+ }
1565
+ return result;
1566
+ }
1567
+ class TreeHighlighter {
1568
+ constructor(view) {
1569
+ this.markCache = Object.create(null);
1570
+ this.tree = syntaxTree(view.state);
1571
+ this.decorations = this.buildDeco(view, getHighlighters(view.state));
1572
+ }
1573
+ update(update) {
1574
+ let tree = syntaxTree(update.state), highlighters = getHighlighters(update.state);
1575
+ let styleChange = highlighters != getHighlighters(update.startState);
1576
+ if (tree.length < update.view.viewport.to && !styleChange && tree.type == this.tree.type) {
1577
+ this.decorations = this.decorations.map(update.changes);
1578
+ }
1579
+ else if (tree != this.tree || update.viewportChanged || styleChange) {
1580
+ this.tree = tree;
1581
+ this.decorations = this.buildDeco(update.view, highlighters);
1582
+ }
1583
+ }
1584
+ buildDeco(view, highlighters) {
1585
+ if (!highlighters || !this.tree.length)
1586
+ return Decoration.none;
1587
+ let builder = new RangeSetBuilder();
1588
+ for (let { from, to } of view.visibleRanges) {
1589
+ highlightTree(this.tree, highlighters, (from, to, style) => {
1590
+ builder.add(from, to, this.markCache[style] || (this.markCache[style] = Decoration.mark({ class: style })));
1591
+ }, from, to);
1592
+ }
1593
+ return builder.finish();
1594
+ }
1595
+ }
1596
+ const treeHighlighter = /*@__PURE__*/Prec.high(/*@__PURE__*/ViewPlugin.fromClass(TreeHighlighter, {
1597
+ decorations: v => v.decorations
1598
+ }));
1599
+ /**
1600
+ A default highlight style (works well with light themes).
1601
+ */
1602
+ const defaultHighlightStyle = /*@__PURE__*/HighlightStyle.define([
1603
+ { tag: tags.meta,
1604
+ color: "#7a757a" },
1605
+ { tag: tags.link,
1606
+ textDecoration: "underline" },
1607
+ { tag: tags.heading,
1608
+ textDecoration: "underline",
1609
+ fontWeight: "bold" },
1610
+ { tag: tags.emphasis,
1611
+ fontStyle: "italic" },
1612
+ { tag: tags.strong,
1613
+ fontWeight: "bold" },
1614
+ { tag: tags.strikethrough,
1615
+ textDecoration: "line-through" },
1616
+ { tag: tags.keyword,
1617
+ color: "#708" },
1618
+ { tag: [tags.atom, tags.bool, tags.url, tags.contentSeparator, tags.labelName],
1619
+ color: "#219" },
1620
+ { tag: [tags.literal, tags.inserted],
1621
+ color: "#164" },
1622
+ { tag: [tags.string, tags.deleted],
1623
+ color: "#a11" },
1624
+ { tag: [tags.regexp, tags.escape, /*@__PURE__*/tags.special(tags.string)],
1625
+ color: "#e40" },
1626
+ { tag: /*@__PURE__*/tags.definition(tags.variableName),
1627
+ color: "#00f" },
1628
+ { tag: /*@__PURE__*/tags.local(tags.variableName),
1629
+ color: "#30a" },
1630
+ { tag: [tags.typeName, tags.namespace],
1631
+ color: "#085" },
1632
+ { tag: tags.className,
1633
+ color: "#167" },
1634
+ { tag: [/*@__PURE__*/tags.special(tags.variableName), tags.macroName],
1635
+ color: "#256" },
1636
+ { tag: /*@__PURE__*/tags.definition(tags.propertyName),
1637
+ color: "#00c" },
1638
+ { tag: tags.comment,
1639
+ color: "#940" },
1640
+ { tag: tags.invalid,
1641
+ color: "#f00" }
1642
+ ]);
1643
+
1644
+ const baseTheme = /*@__PURE__*/EditorView.baseTheme({
1645
+ "&.cm-focused .cm-matchingBracket": { backgroundColor: "#328c8252" },
1646
+ "&.cm-focused .cm-nonmatchingBracket": { backgroundColor: "#bb555544" }
1647
+ });
1648
+ const DefaultScanDist = 10000, DefaultBrackets = "()[]{}";
1649
+ const bracketMatchingConfig = /*@__PURE__*/Facet.define({
1650
+ combine(configs) {
1651
+ return combineConfig(configs, {
1652
+ afterCursor: true,
1653
+ brackets: DefaultBrackets,
1654
+ maxScanDistance: DefaultScanDist,
1655
+ renderMatch: defaultRenderMatch
1656
+ });
1657
+ }
1658
+ });
1659
+ const matchingMark = /*@__PURE__*/Decoration.mark({ class: "cm-matchingBracket" }), nonmatchingMark = /*@__PURE__*/Decoration.mark({ class: "cm-nonmatchingBracket" });
1660
+ function defaultRenderMatch(match) {
1661
+ let decorations = [];
1662
+ let mark = match.matched ? matchingMark : nonmatchingMark;
1663
+ decorations.push(mark.range(match.start.from, match.start.to));
1664
+ if (match.end)
1665
+ decorations.push(mark.range(match.end.from, match.end.to));
1666
+ return decorations;
1667
+ }
1668
+ const bracketMatchingState = /*@__PURE__*/StateField.define({
1669
+ create() { return Decoration.none; },
1670
+ update(deco, tr) {
1671
+ if (!tr.docChanged && !tr.selection)
1672
+ return deco;
1673
+ let decorations = [];
1674
+ let config = tr.state.facet(bracketMatchingConfig);
1675
+ for (let range of tr.state.selection.ranges) {
1676
+ if (!range.empty)
1677
+ continue;
1678
+ let match = matchBrackets(tr.state, range.head, -1, config)
1679
+ || (range.head > 0 && matchBrackets(tr.state, range.head - 1, 1, config))
1680
+ || (config.afterCursor &&
1681
+ (matchBrackets(tr.state, range.head, 1, config) ||
1682
+ (range.head < tr.state.doc.length && matchBrackets(tr.state, range.head + 1, -1, config))));
1683
+ if (match)
1684
+ decorations = decorations.concat(config.renderMatch(match, tr.state));
1685
+ }
1686
+ return Decoration.set(decorations, true);
1687
+ },
1688
+ provide: f => EditorView.decorations.from(f)
1689
+ });
1690
+ const bracketMatchingUnique = [
1691
+ bracketMatchingState,
1692
+ baseTheme
1693
+ ];
1694
+ /**
1695
+ Create an extension that enables bracket matching. Whenever the
1696
+ cursor is next to a bracket, that bracket and the one it matches
1697
+ are highlighted. Or, when no matching bracket is found, another
1698
+ highlighting style is used to indicate this.
1699
+ */
1700
+ function bracketMatching(config = {}) {
1701
+ return [bracketMatchingConfig.of(config), bracketMatchingUnique];
1702
+ }
1703
+ function matchingNodes(node, dir, brackets) {
1704
+ let byProp = node.prop(dir < 0 ? NodeProp.openedBy : NodeProp.closedBy);
1705
+ if (byProp)
1706
+ return byProp;
1707
+ if (node.name.length == 1) {
1708
+ let index = brackets.indexOf(node.name);
1709
+ if (index > -1 && index % 2 == (dir < 0 ? 1 : 0))
1710
+ return [brackets[index + dir]];
1711
+ }
1712
+ return null;
1713
+ }
1714
+ /**
1715
+ Find the matching bracket for the token at `pos`, scanning
1716
+ direction `dir`. Only the `brackets` and `maxScanDistance`
1717
+ properties are used from `config`, if given. Returns null if no
1718
+ bracket was found at `pos`, or a match result otherwise.
1719
+ */
1720
+ function matchBrackets(state, pos, dir, config = {}) {
1721
+ let maxScanDistance = config.maxScanDistance || DefaultScanDist, brackets = config.brackets || DefaultBrackets;
1722
+ let tree = syntaxTree(state), node = tree.resolveInner(pos, dir);
1723
+ for (let cur = node; cur; cur = cur.parent) {
1724
+ let matches = matchingNodes(cur.type, dir, brackets);
1725
+ if (matches && cur.from < cur.to)
1726
+ return matchMarkedBrackets(state, pos, dir, cur, matches, brackets);
1727
+ }
1728
+ return matchPlainBrackets(state, pos, dir, tree, node.type, maxScanDistance, brackets);
1729
+ }
1730
+ function matchMarkedBrackets(_state, _pos, dir, token, matching, brackets) {
1731
+ let parent = token.parent, firstToken = { from: token.from, to: token.to };
1732
+ let depth = 0, cursor = parent === null || parent === void 0 ? void 0 : parent.cursor();
1733
+ if (cursor && (dir < 0 ? cursor.childBefore(token.from) : cursor.childAfter(token.to)))
1734
+ do {
1735
+ if (dir < 0 ? cursor.to <= token.from : cursor.from >= token.to) {
1736
+ if (depth == 0 && matching.indexOf(cursor.type.name) > -1 && cursor.from < cursor.to) {
1737
+ return { start: firstToken, end: { from: cursor.from, to: cursor.to }, matched: true };
1738
+ }
1739
+ else if (matchingNodes(cursor.type, dir, brackets)) {
1740
+ depth++;
1741
+ }
1742
+ else if (matchingNodes(cursor.type, -dir, brackets)) {
1743
+ depth--;
1744
+ if (depth == 0)
1745
+ return {
1746
+ start: firstToken,
1747
+ end: cursor.from == cursor.to ? undefined : { from: cursor.from, to: cursor.to },
1748
+ matched: false
1749
+ };
1750
+ }
1751
+ }
1752
+ } while (dir < 0 ? cursor.prevSibling() : cursor.nextSibling());
1753
+ return { start: firstToken, matched: false };
1754
+ }
1755
+ function matchPlainBrackets(state, pos, dir, tree, tokenType, maxScanDistance, brackets) {
1756
+ let startCh = dir < 0 ? state.sliceDoc(pos - 1, pos) : state.sliceDoc(pos, pos + 1);
1757
+ let bracket = brackets.indexOf(startCh);
1758
+ if (bracket < 0 || (bracket % 2 == 0) != (dir > 0))
1759
+ return null;
1760
+ let startToken = { from: dir < 0 ? pos - 1 : pos, to: dir > 0 ? pos + 1 : pos };
1761
+ let iter = state.doc.iterRange(pos, dir > 0 ? state.doc.length : 0), depth = 0;
1762
+ for (let distance = 0; !(iter.next()).done && distance <= maxScanDistance;) {
1763
+ let text = iter.value;
1764
+ if (dir < 0)
1765
+ distance += text.length;
1766
+ let basePos = pos + distance * dir;
1767
+ for (let pos = dir > 0 ? 0 : text.length - 1, end = dir > 0 ? text.length : -1; pos != end; pos += dir) {
1768
+ let found = brackets.indexOf(text[pos]);
1769
+ if (found < 0 || tree.resolve(basePos + pos, 1).type != tokenType)
1770
+ continue;
1771
+ if ((found % 2 == 0) == (dir > 0)) {
1772
+ depth++;
1773
+ }
1774
+ else if (depth == 1) { // Closing
1775
+ return { start: startToken, end: { from: basePos + pos, to: basePos + pos + 1 }, matched: (found >> 1) == (bracket >> 1) };
1776
+ }
1777
+ else {
1778
+ depth--;
1779
+ }
1780
+ }
1781
+ if (dir > 0)
1782
+ distance += text.length;
1783
+ }
1784
+ return iter.done ? { start: startToken, matched: false } : null;
1785
+ }
1786
+
1787
+ // Counts the column offset in a string, taking tabs into account.
1788
+ // Used mostly to find indentation.
1789
+ function countCol(string, end, tabSize, startIndex = 0, startValue = 0) {
1790
+ if (end == null) {
1791
+ end = string.search(/[^\s\u00a0]/);
1792
+ if (end == -1)
1793
+ end = string.length;
1794
+ }
1795
+ let n = startValue;
1796
+ for (let i = startIndex; i < end; i++) {
1797
+ if (string.charCodeAt(i) == 9)
1798
+ n += tabSize - (n % tabSize);
1799
+ else
1800
+ n++;
1801
+ }
1802
+ return n;
1803
+ }
1804
+ /**
1805
+ Encapsulates a single line of input. Given to stream syntax code,
1806
+ which uses it to tokenize the content.
1807
+ */
1808
+ class StringStream {
1809
+ /**
1810
+ Create a stream.
1811
+ */
1812
+ constructor(
1813
+ /**
1814
+ The line.
1815
+ */
1816
+ string, tabSize,
1817
+ /**
1818
+ The current indent unit size.
1819
+ */
1820
+ indentUnit) {
1821
+ this.string = string;
1822
+ this.tabSize = tabSize;
1823
+ this.indentUnit = indentUnit;
1824
+ /**
1825
+ The current position on the line.
1826
+ */
1827
+ this.pos = 0;
1828
+ /**
1829
+ The start position of the current token.
1830
+ */
1831
+ this.start = 0;
1832
+ this.lastColumnPos = 0;
1833
+ this.lastColumnValue = 0;
1834
+ }
1835
+ /**
1836
+ True if we are at the end of the line.
1837
+ */
1838
+ eol() { return this.pos >= this.string.length; }
1839
+ /**
1840
+ True if we are at the start of the line.
1841
+ */
1842
+ sol() { return this.pos == 0; }
1843
+ /**
1844
+ Get the next code unit after the current position, or undefined
1845
+ if we're at the end of the line.
1846
+ */
1847
+ peek() { return this.string.charAt(this.pos) || undefined; }
1848
+ /**
1849
+ Read the next code unit and advance `this.pos`.
1850
+ */
1851
+ next() {
1852
+ if (this.pos < this.string.length)
1853
+ return this.string.charAt(this.pos++);
1854
+ }
1855
+ /**
1856
+ Match the next character against the given string, regular
1857
+ expression, or predicate. Consume and return it if it matches.
1858
+ */
1859
+ eat(match) {
1860
+ let ch = this.string.charAt(this.pos);
1861
+ let ok;
1862
+ if (typeof match == "string")
1863
+ ok = ch == match;
1864
+ else
1865
+ ok = ch && (match instanceof RegExp ? match.test(ch) : match(ch));
1866
+ if (ok) {
1867
+ ++this.pos;
1868
+ return ch;
1869
+ }
1870
+ }
1871
+ /**
1872
+ Continue matching characters that match the given string,
1873
+ regular expression, or predicate function. Return true if any
1874
+ characters were consumed.
1875
+ */
1876
+ eatWhile(match) {
1877
+ let start = this.pos;
1878
+ while (this.eat(match)) { }
1879
+ return this.pos > start;
1880
+ }
1881
+ /**
1882
+ Consume whitespace ahead of `this.pos`. Return true if any was
1883
+ found.
1884
+ */
1885
+ eatSpace() {
1886
+ let start = this.pos;
1887
+ while (/[\s\u00a0]/.test(this.string.charAt(this.pos)))
1888
+ ++this.pos;
1889
+ return this.pos > start;
1890
+ }
1891
+ /**
1892
+ Move to the end of the line.
1893
+ */
1894
+ skipToEnd() { this.pos = this.string.length; }
1895
+ /**
1896
+ Move to directly before the given character, if found on the
1897
+ current line.
1898
+ */
1899
+ skipTo(ch) {
1900
+ let found = this.string.indexOf(ch, this.pos);
1901
+ if (found > -1) {
1902
+ this.pos = found;
1903
+ return true;
1904
+ }
1905
+ }
1906
+ /**
1907
+ Move back `n` characters.
1908
+ */
1909
+ backUp(n) { this.pos -= n; }
1910
+ /**
1911
+ Get the column position at `this.pos`.
1912
+ */
1913
+ column() {
1914
+ if (this.lastColumnPos < this.start) {
1915
+ this.lastColumnValue = countCol(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue);
1916
+ this.lastColumnPos = this.start;
1917
+ }
1918
+ return this.lastColumnValue;
1919
+ }
1920
+ /**
1921
+ Get the indentation column of the current line.
1922
+ */
1923
+ indentation() {
1924
+ return countCol(this.string, null, this.tabSize);
1925
+ }
1926
+ /**
1927
+ Match the input against the given string or regular expression
1928
+ (which should start with a `^`). Return true or the regexp match
1929
+ if it matches.
1930
+
1931
+ Unless `consume` is set to `false`, this will move `this.pos`
1932
+ past the matched text.
1933
+
1934
+ When matching a string `caseInsensitive` can be set to true to
1935
+ make the match case-insensitive.
1936
+ */
1937
+ match(pattern, consume, caseInsensitive) {
1938
+ if (typeof pattern == "string") {
1939
+ let cased = (str) => caseInsensitive ? str.toLowerCase() : str;
1940
+ let substr = this.string.substr(this.pos, pattern.length);
1941
+ if (cased(substr) == cased(pattern)) {
1942
+ if (consume !== false)
1943
+ this.pos += pattern.length;
1944
+ return true;
1945
+ }
1946
+ else
1947
+ return null;
1948
+ }
1949
+ else {
1950
+ let match = this.string.slice(this.pos).match(pattern);
1951
+ if (match && match.index > 0)
1952
+ return null;
1953
+ if (match && consume !== false)
1954
+ this.pos += match[0].length;
1955
+ return match;
1956
+ }
1957
+ }
1958
+ /**
1959
+ Get the current token.
1960
+ */
1961
+ current() { return this.string.slice(this.start, this.pos); }
1962
+ }
1963
+
1964
+ function fullParser(spec) {
1965
+ return {
1966
+ token: spec.token,
1967
+ blankLine: spec.blankLine || (() => { }),
1968
+ startState: spec.startState || (() => true),
1969
+ copyState: spec.copyState || defaultCopyState,
1970
+ indent: spec.indent || (() => null),
1971
+ languageData: spec.languageData || {},
1972
+ tokenTable: spec.tokenTable || noTokens
1973
+ };
1974
+ }
1975
+ function defaultCopyState(state) {
1976
+ if (typeof state != "object")
1977
+ return state;
1978
+ let newState = {};
1979
+ for (let prop in state) {
1980
+ let val = state[prop];
1981
+ newState[prop] = (val instanceof Array ? val.slice() : val);
1982
+ }
1983
+ return newState;
1984
+ }
1985
+ /**
1986
+ A [language](https://codemirror.net/6/docs/ref/#language.Language) class based on a CodeMirror
1987
+ 5-style [streaming parser](https://codemirror.net/6/docs/ref/#language.StreamParser).
1988
+ */
1989
+ class StreamLanguage extends Language {
1990
+ constructor(parser) {
1991
+ let data = defineLanguageFacet(parser.languageData);
1992
+ let p = fullParser(parser), self;
1993
+ let impl = new class extends Parser {
1994
+ createParse(input, fragments, ranges) {
1995
+ return new Parse(self, input, fragments, ranges);
1996
+ }
1997
+ };
1998
+ super(data, impl, [indentService.of((cx, pos) => this.getIndent(cx, pos))]);
1999
+ this.topNode = docID(data);
2000
+ self = this;
2001
+ this.streamParser = p;
2002
+ this.stateAfter = new NodeProp({ perNode: true });
2003
+ this.tokenTable = parser.tokenTable ? new TokenTable(p.tokenTable) : defaultTokenTable;
2004
+ }
2005
+ /**
2006
+ Define a stream language.
2007
+ */
2008
+ static define(spec) { return new StreamLanguage(spec); }
2009
+ getIndent(cx, pos) {
2010
+ let tree = syntaxTree(cx.state), at = tree.resolve(pos);
2011
+ while (at && at.type != this.topNode)
2012
+ at = at.parent;
2013
+ if (!at)
2014
+ return null;
2015
+ let start = findState(this, tree, 0, at.from, pos), statePos, state;
2016
+ if (start) {
2017
+ state = start.state;
2018
+ statePos = start.pos + 1;
2019
+ }
2020
+ else {
2021
+ state = this.streamParser.startState(cx.unit);
2022
+ statePos = 0;
2023
+ }
2024
+ if (pos - statePos > 10000 /* MaxIndentScanDist */)
2025
+ return null;
2026
+ while (statePos < pos) {
2027
+ let line = cx.state.doc.lineAt(statePos), end = Math.min(pos, line.to);
2028
+ if (line.length) {
2029
+ let stream = new StringStream(line.text, cx.state.tabSize, cx.unit);
2030
+ while (stream.pos < end - line.from)
2031
+ readToken(this.streamParser.token, stream, state);
2032
+ }
2033
+ else {
2034
+ this.streamParser.blankLine(state, cx.unit);
2035
+ }
2036
+ if (end == pos)
2037
+ break;
2038
+ statePos = line.to + 1;
2039
+ }
2040
+ let { text } = cx.lineAt(pos);
2041
+ return this.streamParser.indent(state, /^\s*(.*)/.exec(text)[1], cx);
2042
+ }
2043
+ get allowsNesting() { return false; }
2044
+ }
2045
+ function findState(lang, tree, off, startPos, before) {
2046
+ let state = off >= startPos && off + tree.length <= before && tree.prop(lang.stateAfter);
2047
+ if (state)
2048
+ return { state: lang.streamParser.copyState(state), pos: off + tree.length };
2049
+ for (let i = tree.children.length - 1; i >= 0; i--) {
2050
+ let child = tree.children[i], pos = off + tree.positions[i];
2051
+ let found = child instanceof Tree && pos < before && findState(lang, child, pos, startPos, before);
2052
+ if (found)
2053
+ return found;
2054
+ }
2055
+ return null;
2056
+ }
2057
+ function cutTree(lang, tree, from, to, inside) {
2058
+ if (inside && from <= 0 && to >= tree.length)
2059
+ return tree;
2060
+ if (!inside && tree.type == lang.topNode)
2061
+ inside = true;
2062
+ for (let i = tree.children.length - 1; i >= 0; i--) {
2063
+ let pos = tree.positions[i], child = tree.children[i], inner;
2064
+ if (pos < to && child instanceof Tree) {
2065
+ if (!(inner = cutTree(lang, child, from - pos, to - pos, inside)))
2066
+ break;
2067
+ return !inside ? inner
2068
+ : new Tree(tree.type, tree.children.slice(0, i).concat(inner), tree.positions.slice(0, i + 1), pos + inner.length);
2069
+ }
2070
+ }
2071
+ return null;
2072
+ }
2073
+ function findStartInFragments(lang, fragments, startPos, editorState) {
2074
+ for (let f of fragments) {
2075
+ let from = f.from + (f.openStart ? 25 : 0), to = f.to - (f.openEnd ? 25 : 0);
2076
+ let found = from <= startPos && to > startPos && findState(lang, f.tree, 0 - f.offset, startPos, to), tree;
2077
+ if (found && (tree = cutTree(lang, f.tree, startPos + f.offset, found.pos + f.offset, false)))
2078
+ return { state: found.state, tree };
2079
+ }
2080
+ return { state: lang.streamParser.startState(editorState ? getIndentUnit(editorState) : 4), tree: Tree.empty };
2081
+ }
2082
+ class Parse {
2083
+ constructor(lang, input, fragments, ranges) {
2084
+ this.lang = lang;
2085
+ this.input = input;
2086
+ this.fragments = fragments;
2087
+ this.ranges = ranges;
2088
+ this.stoppedAt = null;
2089
+ this.chunks = [];
2090
+ this.chunkPos = [];
2091
+ this.chunk = [];
2092
+ this.chunkReused = undefined;
2093
+ this.rangeIndex = 0;
2094
+ this.to = ranges[ranges.length - 1].to;
2095
+ let context = ParseContext.get(), from = ranges[0].from;
2096
+ let { state, tree } = findStartInFragments(lang, fragments, from, context === null || context === void 0 ? void 0 : context.state);
2097
+ this.state = state;
2098
+ this.parsedPos = this.chunkStart = from + tree.length;
2099
+ for (let i = 0; i < tree.children.length; i++) {
2100
+ this.chunks.push(tree.children[i]);
2101
+ this.chunkPos.push(tree.positions[i]);
2102
+ }
2103
+ if (context && this.parsedPos < context.viewport.from - 100000 /* MaxDistanceBeforeViewport */) {
2104
+ this.state = this.lang.streamParser.startState(getIndentUnit(context.state));
2105
+ context.skipUntilInView(this.parsedPos, context.viewport.from);
2106
+ this.parsedPos = context.viewport.from;
2107
+ }
2108
+ this.moveRangeIndex();
2109
+ }
2110
+ advance() {
2111
+ let context = ParseContext.get();
2112
+ let parseEnd = this.stoppedAt == null ? this.to : Math.min(this.to, this.stoppedAt);
2113
+ let end = Math.min(parseEnd, this.chunkStart + 2048 /* ChunkSize */);
2114
+ if (context)
2115
+ end = Math.min(end, context.viewport.to);
2116
+ while (this.parsedPos < end)
2117
+ this.parseLine(context);
2118
+ if (this.chunkStart < this.parsedPos)
2119
+ this.finishChunk();
2120
+ if (this.parsedPos >= parseEnd)
2121
+ return this.finish();
2122
+ if (context && this.parsedPos >= context.viewport.to) {
2123
+ context.skipUntilInView(this.parsedPos, parseEnd);
2124
+ return this.finish();
2125
+ }
2126
+ return null;
2127
+ }
2128
+ stopAt(pos) {
2129
+ this.stoppedAt = pos;
2130
+ }
2131
+ lineAfter(pos) {
2132
+ let chunk = this.input.chunk(pos);
2133
+ if (!this.input.lineChunks) {
2134
+ let eol = chunk.indexOf("\n");
2135
+ if (eol > -1)
2136
+ chunk = chunk.slice(0, eol);
2137
+ }
2138
+ else if (chunk == "\n") {
2139
+ chunk = "";
2140
+ }
2141
+ return pos + chunk.length <= this.to ? chunk : chunk.slice(0, this.to - pos);
2142
+ }
2143
+ nextLine() {
2144
+ let from = this.parsedPos, line = this.lineAfter(from), end = from + line.length;
2145
+ for (let index = this.rangeIndex;;) {
2146
+ let rangeEnd = this.ranges[index].to;
2147
+ if (rangeEnd >= end)
2148
+ break;
2149
+ line = line.slice(0, rangeEnd - (end - line.length));
2150
+ index++;
2151
+ if (index == this.ranges.length)
2152
+ break;
2153
+ let rangeStart = this.ranges[index].from;
2154
+ let after = this.lineAfter(rangeStart);
2155
+ line += after;
2156
+ end = rangeStart + after.length;
2157
+ }
2158
+ return { line, end };
2159
+ }
2160
+ skipGapsTo(pos, offset, side) {
2161
+ for (;;) {
2162
+ let end = this.ranges[this.rangeIndex].to, offPos = pos + offset;
2163
+ if (side > 0 ? end > offPos : end >= offPos)
2164
+ break;
2165
+ let start = this.ranges[++this.rangeIndex].from;
2166
+ offset += start - end;
2167
+ }
2168
+ return offset;
2169
+ }
2170
+ moveRangeIndex() {
2171
+ while (this.ranges[this.rangeIndex].to < this.parsedPos)
2172
+ this.rangeIndex++;
2173
+ }
2174
+ emitToken(id, from, to, size, offset) {
2175
+ if (this.ranges.length > 1) {
2176
+ offset = this.skipGapsTo(from, offset, 1);
2177
+ from += offset;
2178
+ let len0 = this.chunk.length;
2179
+ offset = this.skipGapsTo(to, offset, -1);
2180
+ to += offset;
2181
+ size += this.chunk.length - len0;
2182
+ }
2183
+ this.chunk.push(id, from, to, size);
2184
+ return offset;
2185
+ }
2186
+ parseLine(context) {
2187
+ let { line, end } = this.nextLine(), offset = 0, { streamParser } = this.lang;
2188
+ let stream = new StringStream(line, context ? context.state.tabSize : 4, context ? getIndentUnit(context.state) : 2);
2189
+ if (stream.eol()) {
2190
+ streamParser.blankLine(this.state, stream.indentUnit);
2191
+ }
2192
+ else {
2193
+ while (!stream.eol()) {
2194
+ let token = readToken(streamParser.token, stream, this.state);
2195
+ if (token)
2196
+ offset = this.emitToken(this.lang.tokenTable.resolve(token), this.parsedPos + stream.start, this.parsedPos + stream.pos, 4, offset);
2197
+ if (stream.start > 10000 /* MaxLineLength */)
2198
+ break;
2199
+ }
2200
+ }
2201
+ this.parsedPos = end;
2202
+ this.moveRangeIndex();
2203
+ if (this.parsedPos < this.to)
2204
+ this.parsedPos++;
2205
+ }
2206
+ finishChunk() {
2207
+ let tree = Tree.build({
2208
+ buffer: this.chunk,
2209
+ start: this.chunkStart,
2210
+ length: this.parsedPos - this.chunkStart,
2211
+ nodeSet,
2212
+ topID: 0,
2213
+ maxBufferLength: 2048 /* ChunkSize */,
2214
+ reused: this.chunkReused
2215
+ });
2216
+ tree = new Tree(tree.type, tree.children, tree.positions, tree.length, [[this.lang.stateAfter, this.lang.streamParser.copyState(this.state)]]);
2217
+ this.chunks.push(tree);
2218
+ this.chunkPos.push(this.chunkStart - this.ranges[0].from);
2219
+ this.chunk = [];
2220
+ this.chunkReused = undefined;
2221
+ this.chunkStart = this.parsedPos;
2222
+ }
2223
+ finish() {
2224
+ return new Tree(this.lang.topNode, this.chunks, this.chunkPos, this.parsedPos - this.ranges[0].from).balance();
2225
+ }
2226
+ }
2227
+ function readToken(token, stream, state) {
2228
+ stream.start = stream.pos;
2229
+ for (let i = 0; i < 10; i++) {
2230
+ let result = token(stream, state);
2231
+ if (stream.pos > stream.start)
2232
+ return result;
2233
+ }
2234
+ throw new Error("Stream parser failed to advance stream.");
2235
+ }
2236
+ const noTokens = /*@__PURE__*/Object.create(null);
2237
+ const typeArray = [NodeType.none];
2238
+ const nodeSet = /*@__PURE__*/new NodeSet(typeArray);
2239
+ const warned = [];
2240
+ const defaultTable = /*@__PURE__*/Object.create(null);
2241
+ for (let [legacyName, name] of [
2242
+ ["variable", "variableName"],
2243
+ ["variable-2", "variableName.special"],
2244
+ ["string-2", "string.special"],
2245
+ ["def", "variableName.definition"],
2246
+ ["tag", "typeName"],
2247
+ ["attribute", "propertyName"],
2248
+ ["type", "typeName"],
2249
+ ["builtin", "variableName.standard"],
2250
+ ["qualifier", "modifier"],
2251
+ ["error", "invalid"],
2252
+ ["header", "heading"],
2253
+ ["property", "propertyName"]
2254
+ ])
2255
+ defaultTable[legacyName] = /*@__PURE__*/createTokenType(noTokens, name);
2256
+ class TokenTable {
2257
+ constructor(extra) {
2258
+ this.extra = extra;
2259
+ this.table = Object.assign(Object.create(null), defaultTable);
2260
+ }
2261
+ resolve(tag) {
2262
+ return !tag ? 0 : this.table[tag] || (this.table[tag] = createTokenType(this.extra, tag));
2263
+ }
2264
+ }
2265
+ const defaultTokenTable = /*@__PURE__*/new TokenTable(noTokens);
2266
+ function warnForPart(part, msg) {
2267
+ if (warned.indexOf(part) > -1)
2268
+ return;
2269
+ warned.push(part);
2270
+ console.warn(msg);
2271
+ }
2272
+ function createTokenType(extra, tagStr) {
2273
+ let tag = null;
2274
+ for (let part of tagStr.split(".")) {
2275
+ let value = (extra[part] || tags[part]);
2276
+ if (!value) {
2277
+ warnForPart(part, `Unknown highlighting tag ${part}`);
2278
+ }
2279
+ else if (typeof value == "function") {
2280
+ if (!tag)
2281
+ warnForPart(part, `Modifier ${part} used at start of tag`);
2282
+ else
2283
+ tag = value(tag);
2284
+ }
2285
+ else {
2286
+ if (tag)
2287
+ warnForPart(part, `Tag ${part} used as modifier`);
2288
+ else
2289
+ tag = value;
2290
+ }
2291
+ }
2292
+ if (!tag)
2293
+ return 0;
2294
+ let name = tagStr.replace(/ /g, "_"), type = NodeType.define({
2295
+ id: typeArray.length,
2296
+ name,
2297
+ props: [styleTags({ [name]: tag })]
2298
+ });
2299
+ typeArray.push(type);
2300
+ return type.id;
2301
+ }
2302
+ function docID(data) {
2303
+ let type = NodeType.define({ id: typeArray.length, name: "Document", props: [languageDataProp.add(() => data)] });
2304
+ typeArray.push(type);
2305
+ return type;
2306
+ }
1158
2307
 
1159
- export { IndentContext, LRLanguage, Language, LanguageDescription, LanguageSupport, ParseContext, TreeIndentContext, continuedIndent, defineLanguageFacet, delimitedIndent, ensureSyntaxTree, flatIndent, foldInside, foldNodeProp, foldService, foldable, getIndentUnit, getIndentation, indentNodeProp, indentOnInput, indentService, indentString, indentUnit, language, languageDataProp, syntaxParserRunning, syntaxTree, syntaxTreeAvailable };
2308
+ export { HighlightStyle, IndentContext, LRLanguage, Language, LanguageDescription, LanguageSupport, ParseContext, StreamLanguage, StringStream, TreeIndentContext, bracketMatching, codeFolding, continuedIndent, defaultHighlightStyle, defineLanguageFacet, delimitedIndent, ensureSyntaxTree, flatIndent, foldAll, foldCode, foldEffect, foldGutter, foldInside, foldKeymap, foldNodeProp, foldService, foldable, foldedRanges, forceParsing, getIndentUnit, getIndentation, highlightingFor, indentNodeProp, indentOnInput, indentService, indentString, indentUnit, language, languageDataProp, matchBrackets, syntaxHighlighting, syntaxParserRunning, syntaxTree, syntaxTreeAvailable, unfoldAll, unfoldCode, unfoldEffect };