@es-joy/jsoe 0.27.0 → 0.28.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 (49) hide show
  1. package/CHANGES.md +33 -0
  2. package/README.md +3 -1
  3. package/badges/coverage-badge.svg +1 -1
  4. package/badges/tests-badge.svg +1 -0
  5. package/dist/formats/schema.d.ts +11 -0
  6. package/dist/formats/schema.d.ts.map +1 -1
  7. package/dist/formats/structuredCloning.d.ts.map +1 -1
  8. package/dist/fundamentalTypes/arrayType.d.ts.map +1 -1
  9. package/dist/index.js +2 -2
  10. package/dist/index.js.map +1 -1
  11. package/dist/typeChoices.d.ts +32 -2
  12. package/dist/typeChoices.d.ts.map +1 -1
  13. package/dist/types.d.ts +8 -2
  14. package/dist/types.d.ts.map +1 -1
  15. package/dist/utils/rawTypesonEditor.d.ts +110 -0
  16. package/dist/utils/rawTypesonEditor.d.ts.map +1 -0
  17. package/dist/vendor-imports.d.ts +4 -0
  18. package/docs/proposals/raw-typeson-edit-view.md +575 -0
  19. package/mmr.json +6 -0
  20. package/package.json +13 -4
  21. package/pnpm-workspace.yaml +1 -0
  22. package/src/formats/schema.js +3 -1
  23. package/src/formats/structuredCloning.js +24 -17
  24. package/src/fundamentalTypes/arrayType.js +105 -1
  25. package/src/jsoe.css +12 -0
  26. package/src/typeChoices.js +36 -7
  27. package/src/types.js +13 -2
  28. package/src/utils/rawTypesonEditor.js +669 -0
  29. package/src/vendor-imports.js +12 -0
  30. package/tsconfig.json +1 -1
  31. package/typings/json-6.d.ts +12 -0
  32. package/vendor/@codemirror/autocomplete/dist/index.js +2125 -0
  33. package/vendor/@codemirror/commands/dist/index.js +1826 -0
  34. package/vendor/@codemirror/lang-javascript/dist/index.js +513 -0
  35. package/vendor/@codemirror/language/dist/index.js +2693 -0
  36. package/vendor/@codemirror/lint/dist/index.js +956 -0
  37. package/vendor/@codemirror/search/dist/index.js +1238 -0
  38. package/vendor/@codemirror/state/dist/index.js +3947 -0
  39. package/vendor/@codemirror/view/dist/index.js +11867 -0
  40. package/vendor/@lezer/common/dist/index.js +2202 -0
  41. package/vendor/@lezer/highlight/dist/index.js +927 -0
  42. package/vendor/@lezer/javascript/dist/index.js +192 -0
  43. package/vendor/@lezer/lr/dist/index.js +1889 -0
  44. package/vendor/@marijn/find-cluster-break/src/index.js +87 -0
  45. package/vendor/codemirror/dist/index.js +96 -0
  46. package/vendor/crelt/index.js +28 -0
  47. package/vendor/json-6/dist/index.mjs +1783 -0
  48. package/vendor/style-mod/src/style-mod.js +172 -0
  49. package/vendor/w3c-keyname/index.js +119 -0
@@ -0,0 +1,3947 @@
1
+ import { findClusterBreak as findClusterBreak$1 } from '@marijn/find-cluster-break';
2
+
3
+ /**
4
+ The data structure for documents. @nonabstract
5
+ */
6
+ class Text {
7
+ /**
8
+ Get the line description around the given position.
9
+ */
10
+ lineAt(pos) {
11
+ if (pos < 0 || pos > this.length)
12
+ throw new RangeError(`Invalid position ${pos} in document of length ${this.length}`);
13
+ return this.lineInner(pos, false, 1, 0);
14
+ }
15
+ /**
16
+ Get the description for the given (1-based) line number.
17
+ */
18
+ line(n) {
19
+ if (n < 1 || n > this.lines)
20
+ throw new RangeError(`Invalid line number ${n} in ${this.lines}-line document`);
21
+ return this.lineInner(n, true, 1, 0);
22
+ }
23
+ /**
24
+ Replace a range of the text with the given content.
25
+ */
26
+ replace(from, to, text) {
27
+ [from, to] = clip(this, from, to);
28
+ let parts = [];
29
+ this.decompose(0, from, parts, 2 /* Open.To */);
30
+ if (text.length)
31
+ text.decompose(0, text.length, parts, 1 /* Open.From */ | 2 /* Open.To */);
32
+ this.decompose(to, this.length, parts, 1 /* Open.From */);
33
+ return TextNode.from(parts, this.length - (to - from) + text.length);
34
+ }
35
+ /**
36
+ Append another document to this one.
37
+ */
38
+ append(other) {
39
+ return this.replace(this.length, this.length, other);
40
+ }
41
+ /**
42
+ Retrieve the text between the given points.
43
+ */
44
+ slice(from, to = this.length) {
45
+ [from, to] = clip(this, from, to);
46
+ let parts = [];
47
+ this.decompose(from, to, parts, 0);
48
+ return TextNode.from(parts, to - from);
49
+ }
50
+ /**
51
+ Test whether this text is equal to another instance.
52
+ */
53
+ eq(other) {
54
+ if (other == this)
55
+ return true;
56
+ if (other.length != this.length || other.lines != this.lines)
57
+ return false;
58
+ let start = this.scanIdentical(other, 1), end = this.length - this.scanIdentical(other, -1);
59
+ let a = new RawTextCursor(this), b = new RawTextCursor(other);
60
+ for (let skip = start, pos = start;;) {
61
+ a.next(skip);
62
+ b.next(skip);
63
+ skip = 0;
64
+ if (a.lineBreak != b.lineBreak || a.done != b.done || a.value != b.value)
65
+ return false;
66
+ pos += a.value.length;
67
+ if (a.done || pos >= end)
68
+ return true;
69
+ }
70
+ }
71
+ /**
72
+ Iterate over the text. When `dir` is `-1`, iteration happens
73
+ from end to start. This will return lines and the breaks between
74
+ them as separate strings.
75
+ */
76
+ iter(dir = 1) { return new RawTextCursor(this, dir); }
77
+ /**
78
+ Iterate over a range of the text. When `from` > `to`, the
79
+ iterator will run in reverse.
80
+ */
81
+ iterRange(from, to = this.length) { return new PartialTextCursor(this, from, to); }
82
+ /**
83
+ Return a cursor that iterates over the given range of lines,
84
+ _without_ returning the line breaks between, and yielding empty
85
+ strings for empty lines.
86
+
87
+ When `from` and `to` are given, they should be 1-based line numbers.
88
+ */
89
+ iterLines(from, to) {
90
+ let inner;
91
+ if (from == null) {
92
+ inner = this.iter();
93
+ }
94
+ else {
95
+ if (to == null)
96
+ to = this.lines + 1;
97
+ let start = this.line(from).from;
98
+ inner = this.iterRange(start, Math.max(start, to == this.lines + 1 ? this.length : to <= 1 ? 0 : this.line(to - 1).to));
99
+ }
100
+ return new LineCursor(inner);
101
+ }
102
+ /**
103
+ Return the document as a string, using newline characters to
104
+ separate lines.
105
+ */
106
+ toString() { return this.sliceString(0); }
107
+ /**
108
+ Convert the document to an array of lines (which can be
109
+ deserialized again via [`Text.of`](https://codemirror.net/6/docs/ref/#state.Text^of)).
110
+ */
111
+ toJSON() {
112
+ let lines = [];
113
+ this.flatten(lines);
114
+ return lines;
115
+ }
116
+ /**
117
+ @internal
118
+ */
119
+ constructor() { }
120
+ /**
121
+ Create a `Text` instance for the given array of lines.
122
+ */
123
+ static of(text) {
124
+ if (text.length == 0)
125
+ throw new RangeError("A document must have at least one line");
126
+ if (text.length == 1 && !text[0])
127
+ return Text.empty;
128
+ return text.length <= 32 /* Tree.Branch */ ? new TextLeaf(text) : TextNode.from(TextLeaf.split(text, []));
129
+ }
130
+ }
131
+ // Leaves store an array of line strings. There are always line breaks
132
+ // between these strings. Leaves are limited in size and have to be
133
+ // contained in TextNode instances for bigger documents.
134
+ class TextLeaf extends Text {
135
+ constructor(text, length = textLength(text)) {
136
+ super();
137
+ this.text = text;
138
+ this.length = length;
139
+ }
140
+ get lines() { return this.text.length; }
141
+ get children() { return null; }
142
+ lineInner(target, isLine, line, offset) {
143
+ for (let i = 0;; i++) {
144
+ let string = this.text[i], end = offset + string.length;
145
+ if ((isLine ? line : end) >= target)
146
+ return new Line(offset, end, line, string);
147
+ offset = end + 1;
148
+ line++;
149
+ }
150
+ }
151
+ decompose(from, to, target, open) {
152
+ let text = from <= 0 && to >= this.length ? this
153
+ : new TextLeaf(sliceText(this.text, from, to), Math.min(to, this.length) - Math.max(0, from));
154
+ if (open & 1 /* Open.From */) {
155
+ let prev = target.pop();
156
+ let joined = appendText(text.text, prev.text.slice(), 0, text.length);
157
+ if (joined.length <= 32 /* Tree.Branch */) {
158
+ target.push(new TextLeaf(joined, prev.length + text.length));
159
+ }
160
+ else {
161
+ let mid = joined.length >> 1;
162
+ target.push(new TextLeaf(joined.slice(0, mid)), new TextLeaf(joined.slice(mid)));
163
+ }
164
+ }
165
+ else {
166
+ target.push(text);
167
+ }
168
+ }
169
+ replace(from, to, text) {
170
+ if (!(text instanceof TextLeaf))
171
+ return super.replace(from, to, text);
172
+ [from, to] = clip(this, from, to);
173
+ let lines = appendText(this.text, appendText(text.text, sliceText(this.text, 0, from)), to);
174
+ let newLen = this.length + text.length - (to - from);
175
+ if (lines.length <= 32 /* Tree.Branch */)
176
+ return new TextLeaf(lines, newLen);
177
+ return TextNode.from(TextLeaf.split(lines, []), newLen);
178
+ }
179
+ sliceString(from, to = this.length, lineSep = "\n") {
180
+ [from, to] = clip(this, from, to);
181
+ let result = "";
182
+ for (let pos = 0, i = 0; pos <= to && i < this.text.length; i++) {
183
+ let line = this.text[i], end = pos + line.length;
184
+ if (pos > from && i)
185
+ result += lineSep;
186
+ if (from < end && to > pos)
187
+ result += line.slice(Math.max(0, from - pos), to - pos);
188
+ pos = end + 1;
189
+ }
190
+ return result;
191
+ }
192
+ flatten(target) {
193
+ for (let line of this.text)
194
+ target.push(line);
195
+ }
196
+ scanIdentical() { return 0; }
197
+ static split(text, target) {
198
+ let part = [], len = -1;
199
+ for (let line of text) {
200
+ part.push(line);
201
+ len += line.length + 1;
202
+ if (part.length == 32 /* Tree.Branch */) {
203
+ target.push(new TextLeaf(part, len));
204
+ part = [];
205
+ len = -1;
206
+ }
207
+ }
208
+ if (len > -1)
209
+ target.push(new TextLeaf(part, len));
210
+ return target;
211
+ }
212
+ }
213
+ // Nodes provide the tree structure of the `Text` type. They store a
214
+ // number of other nodes or leaves, taking care to balance themselves
215
+ // on changes. There are implied line breaks _between_ the children of
216
+ // a node (but not before the first or after the last child).
217
+ class TextNode extends Text {
218
+ constructor(children, length) {
219
+ super();
220
+ this.children = children;
221
+ this.length = length;
222
+ this.lines = 0;
223
+ for (let child of children)
224
+ this.lines += child.lines;
225
+ }
226
+ lineInner(target, isLine, line, offset) {
227
+ for (let i = 0;; i++) {
228
+ let child = this.children[i], end = offset + child.length, endLine = line + child.lines - 1;
229
+ if ((isLine ? endLine : end) >= target)
230
+ return child.lineInner(target, isLine, line, offset);
231
+ offset = end + 1;
232
+ line = endLine + 1;
233
+ }
234
+ }
235
+ decompose(from, to, target, open) {
236
+ for (let i = 0, pos = 0; pos <= to && i < this.children.length; i++) {
237
+ let child = this.children[i], end = pos + child.length;
238
+ if (from <= end && to >= pos) {
239
+ let childOpen = open & ((pos <= from ? 1 /* Open.From */ : 0) | (end >= to ? 2 /* Open.To */ : 0));
240
+ if (pos >= from && end <= to && !childOpen)
241
+ target.push(child);
242
+ else
243
+ child.decompose(from - pos, to - pos, target, childOpen);
244
+ }
245
+ pos = end + 1;
246
+ }
247
+ }
248
+ replace(from, to, text) {
249
+ [from, to] = clip(this, from, to);
250
+ if (text.lines < this.lines)
251
+ for (let i = 0, pos = 0; i < this.children.length; i++) {
252
+ let child = this.children[i], end = pos + child.length;
253
+ // Fast path: if the change only affects one child and the
254
+ // child's size remains in the acceptable range, only update
255
+ // that child
256
+ if (from >= pos && to <= end) {
257
+ let updated = child.replace(from - pos, to - pos, text);
258
+ let totalLines = this.lines - child.lines + updated.lines;
259
+ if (updated.lines < (totalLines >> (5 /* Tree.BranchShift */ - 1)) &&
260
+ updated.lines > (totalLines >> (5 /* Tree.BranchShift */ + 1))) {
261
+ let copy = this.children.slice();
262
+ copy[i] = updated;
263
+ return new TextNode(copy, this.length - (to - from) + text.length);
264
+ }
265
+ return super.replace(pos, end, updated);
266
+ }
267
+ pos = end + 1;
268
+ }
269
+ return super.replace(from, to, text);
270
+ }
271
+ sliceString(from, to = this.length, lineSep = "\n") {
272
+ [from, to] = clip(this, from, to);
273
+ let result = "";
274
+ for (let i = 0, pos = 0; i < this.children.length && pos <= to; i++) {
275
+ let child = this.children[i], end = pos + child.length;
276
+ if (pos > from && i)
277
+ result += lineSep;
278
+ if (from < end && to > pos)
279
+ result += child.sliceString(from - pos, to - pos, lineSep);
280
+ pos = end + 1;
281
+ }
282
+ return result;
283
+ }
284
+ flatten(target) {
285
+ for (let child of this.children)
286
+ child.flatten(target);
287
+ }
288
+ scanIdentical(other, dir) {
289
+ if (!(other instanceof TextNode))
290
+ return 0;
291
+ let length = 0;
292
+ let [iA, iB, eA, eB] = dir > 0 ? [0, 0, this.children.length, other.children.length]
293
+ : [this.children.length - 1, other.children.length - 1, -1, -1];
294
+ for (;; iA += dir, iB += dir) {
295
+ if (iA == eA || iB == eB)
296
+ return length;
297
+ let chA = this.children[iA], chB = other.children[iB];
298
+ if (chA != chB)
299
+ return length + chA.scanIdentical(chB, dir);
300
+ length += chA.length + 1;
301
+ }
302
+ }
303
+ static from(children, length = children.reduce((l, ch) => l + ch.length + 1, -1)) {
304
+ let lines = 0;
305
+ for (let ch of children)
306
+ lines += ch.lines;
307
+ if (lines < 32 /* Tree.Branch */) {
308
+ let flat = [];
309
+ for (let ch of children)
310
+ ch.flatten(flat);
311
+ return new TextLeaf(flat, length);
312
+ }
313
+ let chunk = Math.max(32 /* Tree.Branch */, lines >> 5 /* Tree.BranchShift */), maxChunk = chunk << 1, minChunk = chunk >> 1;
314
+ let chunked = [], currentLines = 0, currentLen = -1, currentChunk = [];
315
+ function add(child) {
316
+ let last;
317
+ if (child.lines > maxChunk && child instanceof TextNode) {
318
+ for (let node of child.children)
319
+ add(node);
320
+ }
321
+ else if (child.lines > minChunk && (currentLines > minChunk || !currentLines)) {
322
+ flush();
323
+ chunked.push(child);
324
+ }
325
+ else if (child instanceof TextLeaf && currentLines &&
326
+ (last = currentChunk[currentChunk.length - 1]) instanceof TextLeaf &&
327
+ child.lines + last.lines <= 32 /* Tree.Branch */) {
328
+ currentLines += child.lines;
329
+ currentLen += child.length + 1;
330
+ currentChunk[currentChunk.length - 1] = new TextLeaf(last.text.concat(child.text), last.length + 1 + child.length);
331
+ }
332
+ else {
333
+ if (currentLines + child.lines > chunk)
334
+ flush();
335
+ currentLines += child.lines;
336
+ currentLen += child.length + 1;
337
+ currentChunk.push(child);
338
+ }
339
+ }
340
+ function flush() {
341
+ if (currentLines == 0)
342
+ return;
343
+ chunked.push(currentChunk.length == 1 ? currentChunk[0] : TextNode.from(currentChunk, currentLen));
344
+ currentLen = -1;
345
+ currentLines = currentChunk.length = 0;
346
+ }
347
+ for (let child of children)
348
+ add(child);
349
+ flush();
350
+ return chunked.length == 1 ? chunked[0] : new TextNode(chunked, length);
351
+ }
352
+ }
353
+ Text.empty = /*@__PURE__*/new TextLeaf([""], 0);
354
+ function textLength(text) {
355
+ let length = -1;
356
+ for (let line of text)
357
+ length += line.length + 1;
358
+ return length;
359
+ }
360
+ function appendText(text, target, from = 0, to = 1e9) {
361
+ for (let pos = 0, i = 0, first = true; i < text.length && pos <= to; i++) {
362
+ let line = text[i], end = pos + line.length;
363
+ if (end >= from) {
364
+ if (end > to)
365
+ line = line.slice(0, to - pos);
366
+ if (pos < from)
367
+ line = line.slice(from - pos);
368
+ if (first) {
369
+ target[target.length - 1] += line;
370
+ first = false;
371
+ }
372
+ else
373
+ target.push(line);
374
+ }
375
+ pos = end + 1;
376
+ }
377
+ return target;
378
+ }
379
+ function sliceText(text, from, to) {
380
+ return appendText(text, [""], from, to);
381
+ }
382
+ class RawTextCursor {
383
+ constructor(text, dir = 1) {
384
+ this.dir = dir;
385
+ this.done = false;
386
+ this.lineBreak = false;
387
+ this.value = "";
388
+ this.nodes = [text];
389
+ this.offsets = [dir > 0 ? 1 : (text instanceof TextLeaf ? text.text.length : text.children.length) << 1];
390
+ }
391
+ nextInner(skip, dir) {
392
+ this.done = this.lineBreak = false;
393
+ for (;;) {
394
+ let last = this.nodes.length - 1;
395
+ let top = this.nodes[last], offsetValue = this.offsets[last], offset = offsetValue >> 1;
396
+ let size = top instanceof TextLeaf ? top.text.length : top.children.length;
397
+ if (offset == (dir > 0 ? size : 0)) {
398
+ if (last == 0) {
399
+ this.done = true;
400
+ this.value = "";
401
+ return this;
402
+ }
403
+ if (dir > 0)
404
+ this.offsets[last - 1]++;
405
+ this.nodes.pop();
406
+ this.offsets.pop();
407
+ }
408
+ else if ((offsetValue & 1) == (dir > 0 ? 0 : 1)) {
409
+ this.offsets[last] += dir;
410
+ if (skip == 0) {
411
+ this.lineBreak = true;
412
+ this.value = "\n";
413
+ return this;
414
+ }
415
+ skip--;
416
+ }
417
+ else if (top instanceof TextLeaf) {
418
+ // Move to the next string
419
+ let next = top.text[offset + (dir < 0 ? -1 : 0)];
420
+ this.offsets[last] += dir;
421
+ if (next.length > Math.max(0, skip)) {
422
+ this.value = skip == 0 ? next : dir > 0 ? next.slice(skip) : next.slice(0, next.length - skip);
423
+ return this;
424
+ }
425
+ skip -= next.length;
426
+ }
427
+ else {
428
+ let next = top.children[offset + (dir < 0 ? -1 : 0)];
429
+ if (skip > next.length) {
430
+ skip -= next.length;
431
+ this.offsets[last] += dir;
432
+ }
433
+ else {
434
+ if (dir < 0)
435
+ this.offsets[last]--;
436
+ this.nodes.push(next);
437
+ this.offsets.push(dir > 0 ? 1 : (next instanceof TextLeaf ? next.text.length : next.children.length) << 1);
438
+ }
439
+ }
440
+ }
441
+ }
442
+ next(skip = 0) {
443
+ if (skip < 0) {
444
+ this.nextInner(-skip, (-this.dir));
445
+ skip = this.value.length;
446
+ }
447
+ return this.nextInner(skip, this.dir);
448
+ }
449
+ }
450
+ class PartialTextCursor {
451
+ constructor(text, start, end) {
452
+ this.value = "";
453
+ this.done = false;
454
+ this.cursor = new RawTextCursor(text, start > end ? -1 : 1);
455
+ this.pos = start > end ? text.length : 0;
456
+ this.from = Math.min(start, end);
457
+ this.to = Math.max(start, end);
458
+ }
459
+ nextInner(skip, dir) {
460
+ if (dir < 0 ? this.pos <= this.from : this.pos >= this.to) {
461
+ this.value = "";
462
+ this.done = true;
463
+ return this;
464
+ }
465
+ skip += Math.max(0, dir < 0 ? this.pos - this.to : this.from - this.pos);
466
+ let limit = dir < 0 ? this.pos - this.from : this.to - this.pos;
467
+ if (skip > limit)
468
+ skip = limit;
469
+ limit -= skip;
470
+ let { value } = this.cursor.next(skip);
471
+ this.pos += (value.length + skip) * dir;
472
+ this.value = value.length <= limit ? value : dir < 0 ? value.slice(value.length - limit) : value.slice(0, limit);
473
+ this.done = !this.value;
474
+ return this;
475
+ }
476
+ next(skip = 0) {
477
+ if (skip < 0)
478
+ skip = Math.max(skip, this.from - this.pos);
479
+ else if (skip > 0)
480
+ skip = Math.min(skip, this.to - this.pos);
481
+ return this.nextInner(skip, this.cursor.dir);
482
+ }
483
+ get lineBreak() { return this.cursor.lineBreak && this.value != ""; }
484
+ }
485
+ class LineCursor {
486
+ constructor(inner) {
487
+ this.inner = inner;
488
+ this.afterBreak = true;
489
+ this.value = "";
490
+ this.done = false;
491
+ }
492
+ next(skip = 0) {
493
+ let { done, lineBreak, value } = this.inner.next(skip);
494
+ if (done && this.afterBreak) {
495
+ this.value = "";
496
+ this.afterBreak = false;
497
+ }
498
+ else if (done) {
499
+ this.done = true;
500
+ this.value = "";
501
+ }
502
+ else if (lineBreak) {
503
+ if (this.afterBreak) {
504
+ this.value = "";
505
+ }
506
+ else {
507
+ this.afterBreak = true;
508
+ this.next();
509
+ }
510
+ }
511
+ else {
512
+ this.value = value;
513
+ this.afterBreak = false;
514
+ }
515
+ return this;
516
+ }
517
+ get lineBreak() { return false; }
518
+ }
519
+ if (typeof Symbol != "undefined") {
520
+ Text.prototype[Symbol.iterator] = function () { return this.iter(); };
521
+ RawTextCursor.prototype[Symbol.iterator] = PartialTextCursor.prototype[Symbol.iterator] =
522
+ LineCursor.prototype[Symbol.iterator] = function () { return this; };
523
+ }
524
+ /**
525
+ This type describes a line in the document. It is created
526
+ on-demand when lines are [queried](https://codemirror.net/6/docs/ref/#state.Text.lineAt).
527
+ */
528
+ class Line {
529
+ /**
530
+ @internal
531
+ */
532
+ constructor(
533
+ /**
534
+ The position of the start of the line.
535
+ */
536
+ from,
537
+ /**
538
+ The position at the end of the line (_before_ the line break,
539
+ or at the end of document for the last line).
540
+ */
541
+ to,
542
+ /**
543
+ This line's line number (1-based).
544
+ */
545
+ number,
546
+ /**
547
+ The line's content.
548
+ */
549
+ text) {
550
+ this.from = from;
551
+ this.to = to;
552
+ this.number = number;
553
+ this.text = text;
554
+ }
555
+ /**
556
+ The length of the line (not including any line break after it).
557
+ */
558
+ get length() { return this.to - this.from; }
559
+ }
560
+ function clip(text, from, to) {
561
+ from = Math.max(0, Math.min(text.length, from));
562
+ return [from, Math.max(from, Math.min(text.length, to))];
563
+ }
564
+
565
+ /**
566
+ Returns a next grapheme cluster break _after_ (not equal to)
567
+ `pos`, if `forward` is true, or before otherwise. Returns `pos`
568
+ itself if no further cluster break is available in the string.
569
+ Moves across surrogate pairs, extending characters (when
570
+ `includeExtending` is true), characters joined with zero-width
571
+ joiners, and flag emoji.
572
+ */
573
+ function findClusterBreak(str, pos, forward = true, includeExtending = true) {
574
+ return findClusterBreak$1(str, pos, forward, includeExtending);
575
+ }
576
+ function surrogateLow(ch) { return ch >= 0xDC00 && ch < 0xE000; }
577
+ function surrogateHigh(ch) { return ch >= 0xD800 && ch < 0xDC00; }
578
+ /**
579
+ Find the code point at the given position in a string (like the
580
+ [`codePointAt`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/codePointAt)
581
+ string method).
582
+ */
583
+ function codePointAt(str, pos) {
584
+ let code0 = str.charCodeAt(pos);
585
+ if (!surrogateHigh(code0) || pos + 1 == str.length)
586
+ return code0;
587
+ let code1 = str.charCodeAt(pos + 1);
588
+ if (!surrogateLow(code1))
589
+ return code0;
590
+ return ((code0 - 0xd800) << 10) + (code1 - 0xdc00) + 0x10000;
591
+ }
592
+ /**
593
+ Given a Unicode codepoint, return the JavaScript string that
594
+ respresents it (like
595
+ [`String.fromCodePoint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCodePoint)).
596
+ */
597
+ function fromCodePoint(code) {
598
+ if (code <= 0xffff)
599
+ return String.fromCharCode(code);
600
+ code -= 0x10000;
601
+ return String.fromCharCode((code >> 10) + 0xd800, (code & 1023) + 0xdc00);
602
+ }
603
+ /**
604
+ The amount of positions a character takes up in a JavaScript string.
605
+ */
606
+ function codePointSize(code) { return code < 0x10000 ? 1 : 2; }
607
+
608
+ const DefaultSplit = /\r\n?|\n/;
609
+ /**
610
+ Distinguishes different ways in which positions can be mapped.
611
+ */
612
+ var MapMode = /*@__PURE__*/(function (MapMode) {
613
+ /**
614
+ Map a position to a valid new position, even when its context
615
+ was deleted.
616
+ */
617
+ MapMode[MapMode["Simple"] = 0] = "Simple";
618
+ /**
619
+ Return null if deletion happens across the position.
620
+ */
621
+ MapMode[MapMode["TrackDel"] = 1] = "TrackDel";
622
+ /**
623
+ Return null if the character _before_ the position is deleted.
624
+ */
625
+ MapMode[MapMode["TrackBefore"] = 2] = "TrackBefore";
626
+ /**
627
+ Return null if the character _after_ the position is deleted.
628
+ */
629
+ MapMode[MapMode["TrackAfter"] = 3] = "TrackAfter";
630
+ return MapMode})(MapMode || (MapMode = {}));
631
+ /**
632
+ A change description is a variant of [change set](https://codemirror.net/6/docs/ref/#state.ChangeSet)
633
+ that doesn't store the inserted text. As such, it can't be
634
+ applied, but is cheaper to store and manipulate.
635
+ */
636
+ class ChangeDesc {
637
+ // Sections are encoded as pairs of integers. The first is the
638
+ // length in the current document, and the second is -1 for
639
+ // unaffected sections, and the length of the replacement content
640
+ // otherwise. So an insertion would be (0, n>0), a deletion (n>0,
641
+ // 0), and a replacement two positive numbers.
642
+ /**
643
+ @internal
644
+ */
645
+ constructor(
646
+ /**
647
+ @internal
648
+ */
649
+ sections) {
650
+ this.sections = sections;
651
+ }
652
+ /**
653
+ The length of the document before the change.
654
+ */
655
+ get length() {
656
+ let result = 0;
657
+ for (let i = 0; i < this.sections.length; i += 2)
658
+ result += this.sections[i];
659
+ return result;
660
+ }
661
+ /**
662
+ The length of the document after the change.
663
+ */
664
+ get newLength() {
665
+ let result = 0;
666
+ for (let i = 0; i < this.sections.length; i += 2) {
667
+ let ins = this.sections[i + 1];
668
+ result += ins < 0 ? this.sections[i] : ins;
669
+ }
670
+ return result;
671
+ }
672
+ /**
673
+ False when there are actual changes in this set.
674
+ */
675
+ get empty() { return this.sections.length == 0 || this.sections.length == 2 && this.sections[1] < 0; }
676
+ /**
677
+ Iterate over the unchanged parts left by these changes. `posA`
678
+ provides the position of the range in the old document, `posB`
679
+ the new position in the changed document.
680
+ */
681
+ iterGaps(f) {
682
+ for (let i = 0, posA = 0, posB = 0; i < this.sections.length;) {
683
+ let len = this.sections[i++], ins = this.sections[i++];
684
+ if (ins < 0) {
685
+ f(posA, posB, len);
686
+ posB += len;
687
+ }
688
+ else {
689
+ posB += ins;
690
+ }
691
+ posA += len;
692
+ }
693
+ }
694
+ /**
695
+ Iterate over the ranges changed by these changes. (See
696
+ [`ChangeSet.iterChanges`](https://codemirror.net/6/docs/ref/#state.ChangeSet.iterChanges) for a
697
+ variant that also provides you with the inserted text.)
698
+ `fromA`/`toA` provides the extent of the change in the starting
699
+ document, `fromB`/`toB` the extent of the replacement in the
700
+ changed document.
701
+
702
+ When `individual` is true, adjacent changes (which are kept
703
+ separate for [position mapping](https://codemirror.net/6/docs/ref/#state.ChangeDesc.mapPos)) are
704
+ reported separately.
705
+ */
706
+ iterChangedRanges(f, individual = false) {
707
+ iterChanges(this, f, individual);
708
+ }
709
+ /**
710
+ Get a description of the inverted form of these changes.
711
+ */
712
+ get invertedDesc() {
713
+ let sections = [];
714
+ for (let i = 0; i < this.sections.length;) {
715
+ let len = this.sections[i++], ins = this.sections[i++];
716
+ if (ins < 0)
717
+ sections.push(len, ins);
718
+ else
719
+ sections.push(ins, len);
720
+ }
721
+ return new ChangeDesc(sections);
722
+ }
723
+ /**
724
+ Compute the combined effect of applying another set of changes
725
+ after this one. The length of the document after this set should
726
+ match the length before `other`.
727
+ */
728
+ composeDesc(other) { return this.empty ? other : other.empty ? this : composeSets(this, other); }
729
+ /**
730
+ Map this description, which should start with the same document
731
+ as `other`, over another set of changes, so that it can be
732
+ applied after it. When `before` is true, map as if the changes
733
+ in `this` happened before the ones in `other`.
734
+ */
735
+ mapDesc(other, before = false) { return other.empty ? this : mapSet(this, other, before); }
736
+ mapPos(pos, assoc = -1, mode = MapMode.Simple) {
737
+ let posA = 0, posB = 0;
738
+ for (let i = 0; i < this.sections.length;) {
739
+ let len = this.sections[i++], ins = this.sections[i++], endA = posA + len;
740
+ if (ins < 0) {
741
+ if (endA > pos)
742
+ return posB + (pos - posA);
743
+ posB += len;
744
+ }
745
+ else {
746
+ if (mode != MapMode.Simple && endA >= pos &&
747
+ (mode == MapMode.TrackDel && posA < pos && endA > pos ||
748
+ mode == MapMode.TrackBefore && posA < pos ||
749
+ mode == MapMode.TrackAfter && endA > pos))
750
+ return null;
751
+ if (endA > pos || endA == pos && assoc < 0 && !len)
752
+ return pos == posA || assoc < 0 ? posB : posB + ins;
753
+ posB += ins;
754
+ }
755
+ posA = endA;
756
+ }
757
+ if (pos > posA)
758
+ throw new RangeError(`Position ${pos} is out of range for changeset of length ${posA}`);
759
+ return posB;
760
+ }
761
+ /**
762
+ Check whether these changes touch a given range. When one of the
763
+ changes entirely covers the range, the string `"cover"` is
764
+ returned.
765
+ */
766
+ touchesRange(from, to = from) {
767
+ for (let i = 0, pos = 0; i < this.sections.length && pos <= to;) {
768
+ let len = this.sections[i++], ins = this.sections[i++], end = pos + len;
769
+ if (ins >= 0 && pos <= to && end >= from)
770
+ return pos < from && end > to ? "cover" : true;
771
+ pos = end;
772
+ }
773
+ return false;
774
+ }
775
+ /**
776
+ @internal
777
+ */
778
+ toString() {
779
+ let result = "";
780
+ for (let i = 0; i < this.sections.length;) {
781
+ let len = this.sections[i++], ins = this.sections[i++];
782
+ result += (result ? " " : "") + len + (ins >= 0 ? ":" + ins : "");
783
+ }
784
+ return result;
785
+ }
786
+ /**
787
+ Serialize this change desc to a JSON-representable value.
788
+ */
789
+ toJSON() { return this.sections; }
790
+ /**
791
+ Create a change desc from its JSON representation (as produced
792
+ by [`toJSON`](https://codemirror.net/6/docs/ref/#state.ChangeDesc.toJSON).
793
+ */
794
+ static fromJSON(json) {
795
+ if (!Array.isArray(json) || json.length % 2 || json.some(a => typeof a != "number"))
796
+ throw new RangeError("Invalid JSON representation of ChangeDesc");
797
+ return new ChangeDesc(json);
798
+ }
799
+ /**
800
+ @internal
801
+ */
802
+ static create(sections) { return new ChangeDesc(sections); }
803
+ }
804
+ /**
805
+ A change set represents a group of modifications to a document. It
806
+ stores the document length, and can only be applied to documents
807
+ with exactly that length.
808
+ */
809
+ class ChangeSet extends ChangeDesc {
810
+ constructor(sections,
811
+ /**
812
+ @internal
813
+ */
814
+ inserted) {
815
+ super(sections);
816
+ this.inserted = inserted;
817
+ }
818
+ /**
819
+ Apply the changes to a document, returning the modified
820
+ document.
821
+ */
822
+ apply(doc) {
823
+ if (this.length != doc.length)
824
+ throw new RangeError("Applying change set to a document with the wrong length");
825
+ iterChanges(this, (fromA, toA, fromB, _toB, text) => doc = doc.replace(fromB, fromB + (toA - fromA), text), false);
826
+ return doc;
827
+ }
828
+ mapDesc(other, before = false) { return mapSet(this, other, before, true); }
829
+ /**
830
+ Given the document as it existed _before_ the changes, return a
831
+ change set that represents the inverse of this set, which could
832
+ be used to go from the document created by the changes back to
833
+ the document as it existed before the changes.
834
+ */
835
+ invert(doc) {
836
+ let sections = this.sections.slice(), inserted = [];
837
+ for (let i = 0, pos = 0; i < sections.length; i += 2) {
838
+ let len = sections[i], ins = sections[i + 1];
839
+ if (ins >= 0) {
840
+ sections[i] = ins;
841
+ sections[i + 1] = len;
842
+ let index = i >> 1;
843
+ while (inserted.length < index)
844
+ inserted.push(Text.empty);
845
+ inserted.push(len ? doc.slice(pos, pos + len) : Text.empty);
846
+ }
847
+ pos += len;
848
+ }
849
+ return new ChangeSet(sections, inserted);
850
+ }
851
+ /**
852
+ Combine two subsequent change sets into a single set. `other`
853
+ must start in the document produced by `this`. If `this` goes
854
+ `docA` → `docB` and `other` represents `docB` → `docC`, the
855
+ returned value will represent the change `docA` → `docC`.
856
+ */
857
+ compose(other) { return this.empty ? other : other.empty ? this : composeSets(this, other, true); }
858
+ /**
859
+ Given another change set starting in the same document, maps this
860
+ change set over the other, producing a new change set that can be
861
+ applied to the document produced by applying `other`. When
862
+ `before` is `true`, order changes as if `this` comes before
863
+ `other`, otherwise (the default) treat `other` as coming first.
864
+
865
+ Given two changes `A` and `B`, `A.compose(B.map(A))` and
866
+ `B.compose(A.map(B, true))` will produce the same document. This
867
+ provides a basic form of [operational
868
+ transformation](https://en.wikipedia.org/wiki/Operational_transformation),
869
+ and can be used for collaborative editing.
870
+ */
871
+ map(other, before = false) { return other.empty ? this : mapSet(this, other, before, true); }
872
+ /**
873
+ Iterate over the changed ranges in the document, calling `f` for
874
+ each, with the range in the original document (`fromA`-`toA`)
875
+ and the range that replaces it in the new document
876
+ (`fromB`-`toB`).
877
+
878
+ When `individual` is true, adjacent changes are reported
879
+ separately.
880
+ */
881
+ iterChanges(f, individual = false) {
882
+ iterChanges(this, f, individual);
883
+ }
884
+ /**
885
+ Get a [change description](https://codemirror.net/6/docs/ref/#state.ChangeDesc) for this change
886
+ set.
887
+ */
888
+ get desc() { return ChangeDesc.create(this.sections); }
889
+ /**
890
+ @internal
891
+ */
892
+ filter(ranges) {
893
+ let resultSections = [], resultInserted = [], filteredSections = [];
894
+ let iter = new SectionIter(this);
895
+ done: for (let i = 0, pos = 0;;) {
896
+ let next = i == ranges.length ? 1e9 : ranges[i++];
897
+ while (pos < next || pos == next && iter.len == 0) {
898
+ if (iter.done)
899
+ break done;
900
+ let len = Math.min(iter.len, next - pos);
901
+ addSection(filteredSections, len, -1);
902
+ let ins = iter.ins == -1 ? -1 : iter.off == 0 ? iter.ins : 0;
903
+ addSection(resultSections, len, ins);
904
+ if (ins > 0)
905
+ addInsert(resultInserted, resultSections, iter.text);
906
+ iter.forward(len);
907
+ pos += len;
908
+ }
909
+ let end = ranges[i++];
910
+ while (pos < end) {
911
+ if (iter.done)
912
+ break done;
913
+ let len = Math.min(iter.len, end - pos);
914
+ addSection(resultSections, len, -1);
915
+ addSection(filteredSections, len, iter.ins == -1 ? -1 : iter.off == 0 ? iter.ins : 0);
916
+ iter.forward(len);
917
+ pos += len;
918
+ }
919
+ }
920
+ return { changes: new ChangeSet(resultSections, resultInserted),
921
+ filtered: ChangeDesc.create(filteredSections) };
922
+ }
923
+ /**
924
+ Serialize this change set to a JSON-representable value.
925
+ */
926
+ toJSON() {
927
+ let parts = [];
928
+ for (let i = 0; i < this.sections.length; i += 2) {
929
+ let len = this.sections[i], ins = this.sections[i + 1];
930
+ if (ins < 0)
931
+ parts.push(len);
932
+ else if (ins == 0)
933
+ parts.push([len]);
934
+ else
935
+ parts.push([len].concat(this.inserted[i >> 1].toJSON()));
936
+ }
937
+ return parts;
938
+ }
939
+ /**
940
+ Create a change set for the given changes, for a document of the
941
+ given length, using `lineSep` as line separator.
942
+ */
943
+ static of(changes, length, lineSep) {
944
+ let sections = [], inserted = [], pos = 0;
945
+ let total = null;
946
+ function flush(force = false) {
947
+ if (!force && !sections.length)
948
+ return;
949
+ if (pos < length)
950
+ addSection(sections, length - pos, -1);
951
+ let set = new ChangeSet(sections, inserted);
952
+ total = total ? total.compose(set.map(total)) : set;
953
+ sections = [];
954
+ inserted = [];
955
+ pos = 0;
956
+ }
957
+ function process(spec) {
958
+ if (Array.isArray(spec)) {
959
+ for (let sub of spec)
960
+ process(sub);
961
+ }
962
+ else if (spec instanceof ChangeSet) {
963
+ if (spec.length != length)
964
+ throw new RangeError(`Mismatched change set length (got ${spec.length}, expected ${length})`);
965
+ flush();
966
+ total = total ? total.compose(spec.map(total)) : spec;
967
+ }
968
+ else {
969
+ let { from, to = from, insert } = spec;
970
+ if (from > to || from < 0 || to > length)
971
+ throw new RangeError(`Invalid change range ${from} to ${to} (in doc of length ${length})`);
972
+ let insText = !insert ? Text.empty : typeof insert == "string" ? Text.of(insert.split(lineSep || DefaultSplit)) : insert;
973
+ let insLen = insText.length;
974
+ if (from == to && insLen == 0)
975
+ return;
976
+ if (from < pos)
977
+ flush();
978
+ if (from > pos)
979
+ addSection(sections, from - pos, -1);
980
+ addSection(sections, to - from, insLen);
981
+ addInsert(inserted, sections, insText);
982
+ pos = to;
983
+ }
984
+ }
985
+ process(changes);
986
+ flush(!total);
987
+ return total;
988
+ }
989
+ /**
990
+ Create an empty changeset of the given length.
991
+ */
992
+ static empty(length) {
993
+ return new ChangeSet(length ? [length, -1] : [], []);
994
+ }
995
+ /**
996
+ Create a changeset from its JSON representation (as produced by
997
+ [`toJSON`](https://codemirror.net/6/docs/ref/#state.ChangeSet.toJSON).
998
+ */
999
+ static fromJSON(json) {
1000
+ if (!Array.isArray(json))
1001
+ throw new RangeError("Invalid JSON representation of ChangeSet");
1002
+ let sections = [], inserted = [];
1003
+ for (let i = 0; i < json.length; i++) {
1004
+ let part = json[i];
1005
+ if (typeof part == "number") {
1006
+ sections.push(part, -1);
1007
+ }
1008
+ else if (!Array.isArray(part) || typeof part[0] != "number" || part.some((e, i) => i && typeof e != "string")) {
1009
+ throw new RangeError("Invalid JSON representation of ChangeSet");
1010
+ }
1011
+ else if (part.length == 1) {
1012
+ sections.push(part[0], 0);
1013
+ }
1014
+ else {
1015
+ while (inserted.length < i)
1016
+ inserted.push(Text.empty);
1017
+ inserted[i] = Text.of(part.slice(1));
1018
+ sections.push(part[0], inserted[i].length);
1019
+ }
1020
+ }
1021
+ return new ChangeSet(sections, inserted);
1022
+ }
1023
+ /**
1024
+ @internal
1025
+ */
1026
+ static createSet(sections, inserted) {
1027
+ return new ChangeSet(sections, inserted);
1028
+ }
1029
+ }
1030
+ function addSection(sections, len, ins, forceJoin = false) {
1031
+ if (len == 0 && ins <= 0)
1032
+ return;
1033
+ let last = sections.length - 2;
1034
+ if (last >= 0 && ins <= 0 && ins == sections[last + 1])
1035
+ sections[last] += len;
1036
+ else if (last >= 0 && len == 0 && sections[last] == 0)
1037
+ sections[last + 1] += ins;
1038
+ else if (forceJoin) {
1039
+ sections[last] += len;
1040
+ sections[last + 1] += ins;
1041
+ }
1042
+ else
1043
+ sections.push(len, ins);
1044
+ }
1045
+ function addInsert(values, sections, value) {
1046
+ if (value.length == 0)
1047
+ return;
1048
+ let index = (sections.length - 2) >> 1;
1049
+ if (index < values.length) {
1050
+ values[values.length - 1] = values[values.length - 1].append(value);
1051
+ }
1052
+ else {
1053
+ while (values.length < index)
1054
+ values.push(Text.empty);
1055
+ values.push(value);
1056
+ }
1057
+ }
1058
+ function iterChanges(desc, f, individual) {
1059
+ let inserted = desc.inserted;
1060
+ for (let posA = 0, posB = 0, i = 0; i < desc.sections.length;) {
1061
+ let len = desc.sections[i++], ins = desc.sections[i++];
1062
+ if (ins < 0) {
1063
+ posA += len;
1064
+ posB += len;
1065
+ }
1066
+ else {
1067
+ let endA = posA, endB = posB, text = Text.empty;
1068
+ for (;;) {
1069
+ endA += len;
1070
+ endB += ins;
1071
+ if (ins && inserted)
1072
+ text = text.append(inserted[(i - 2) >> 1]);
1073
+ if (individual || i == desc.sections.length || desc.sections[i + 1] < 0)
1074
+ break;
1075
+ len = desc.sections[i++];
1076
+ ins = desc.sections[i++];
1077
+ }
1078
+ f(posA, endA, posB, endB, text);
1079
+ posA = endA;
1080
+ posB = endB;
1081
+ }
1082
+ }
1083
+ }
1084
+ function mapSet(setA, setB, before, mkSet = false) {
1085
+ // Produce a copy of setA that applies to the document after setB
1086
+ // has been applied (assuming both start at the same document).
1087
+ let sections = [], insert = mkSet ? [] : null;
1088
+ let a = new SectionIter(setA), b = new SectionIter(setB);
1089
+ // Iterate over both sets in parallel. inserted tracks, for changes
1090
+ // in A that have to be processed piece-by-piece, whether their
1091
+ // content has been inserted already, and refers to the section
1092
+ // index.
1093
+ for (let inserted = -1;;) {
1094
+ if (a.done && b.len || b.done && a.len) {
1095
+ throw new Error("Mismatched change set lengths");
1096
+ }
1097
+ else if (a.ins == -1 && b.ins == -1) {
1098
+ // Move across ranges skipped by both sets.
1099
+ let len = Math.min(a.len, b.len);
1100
+ addSection(sections, len, -1);
1101
+ a.forward(len);
1102
+ b.forward(len);
1103
+ }
1104
+ else if (b.ins >= 0 && (a.ins < 0 || inserted == a.i || a.off == 0 && (b.len < a.len || b.len == a.len && !before))) {
1105
+ // If there's a change in B that comes before the next change in
1106
+ // A (ordered by start pos, then len, then before flag), skip
1107
+ // that (and process any changes in A it covers).
1108
+ let len = b.len;
1109
+ addSection(sections, b.ins, -1);
1110
+ while (len) {
1111
+ let piece = Math.min(a.len, len);
1112
+ if (a.ins >= 0 && inserted < a.i && a.len <= piece) {
1113
+ addSection(sections, 0, a.ins);
1114
+ if (insert)
1115
+ addInsert(insert, sections, a.text);
1116
+ inserted = a.i;
1117
+ }
1118
+ a.forward(piece);
1119
+ len -= piece;
1120
+ }
1121
+ b.next();
1122
+ }
1123
+ else if (a.ins >= 0) {
1124
+ // Process the part of a change in A up to the start of the next
1125
+ // non-deletion change in B (if overlapping).
1126
+ let len = 0, left = a.len;
1127
+ while (left) {
1128
+ if (b.ins == -1) {
1129
+ let piece = Math.min(left, b.len);
1130
+ len += piece;
1131
+ left -= piece;
1132
+ b.forward(piece);
1133
+ }
1134
+ else if (b.ins == 0 && b.len < left) {
1135
+ left -= b.len;
1136
+ b.next();
1137
+ }
1138
+ else {
1139
+ break;
1140
+ }
1141
+ }
1142
+ addSection(sections, len, inserted < a.i ? a.ins : 0);
1143
+ if (insert && inserted < a.i)
1144
+ addInsert(insert, sections, a.text);
1145
+ inserted = a.i;
1146
+ a.forward(a.len - left);
1147
+ }
1148
+ else if (a.done && b.done) {
1149
+ return insert ? ChangeSet.createSet(sections, insert) : ChangeDesc.create(sections);
1150
+ }
1151
+ else {
1152
+ throw new Error("Mismatched change set lengths");
1153
+ }
1154
+ }
1155
+ }
1156
+ function composeSets(setA, setB, mkSet = false) {
1157
+ let sections = [];
1158
+ let insert = mkSet ? [] : null;
1159
+ let a = new SectionIter(setA), b = new SectionIter(setB);
1160
+ for (let open = false;;) {
1161
+ if (a.done && b.done) {
1162
+ return insert ? ChangeSet.createSet(sections, insert) : ChangeDesc.create(sections);
1163
+ }
1164
+ else if (a.ins == 0) { // Deletion in A
1165
+ addSection(sections, a.len, 0, open);
1166
+ a.next();
1167
+ }
1168
+ else if (b.len == 0 && !b.done) { // Insertion in B
1169
+ addSection(sections, 0, b.ins, open);
1170
+ if (insert)
1171
+ addInsert(insert, sections, b.text);
1172
+ b.next();
1173
+ }
1174
+ else if (a.done || b.done) {
1175
+ throw new Error("Mismatched change set lengths");
1176
+ }
1177
+ else {
1178
+ let len = Math.min(a.len2, b.len), sectionLen = sections.length;
1179
+ if (a.ins == -1) {
1180
+ let insB = b.ins == -1 ? -1 : b.off ? 0 : b.ins;
1181
+ addSection(sections, len, insB, open);
1182
+ if (insert && insB)
1183
+ addInsert(insert, sections, b.text);
1184
+ }
1185
+ else if (b.ins == -1) {
1186
+ addSection(sections, a.off ? 0 : a.len, len, open);
1187
+ if (insert)
1188
+ addInsert(insert, sections, a.textBit(len));
1189
+ }
1190
+ else {
1191
+ addSection(sections, a.off ? 0 : a.len, b.off ? 0 : b.ins, open);
1192
+ if (insert && !b.off)
1193
+ addInsert(insert, sections, b.text);
1194
+ }
1195
+ open = (a.ins > len || b.ins >= 0 && b.len > len) && (open || sections.length > sectionLen);
1196
+ a.forward2(len);
1197
+ b.forward(len);
1198
+ }
1199
+ }
1200
+ }
1201
+ class SectionIter {
1202
+ constructor(set) {
1203
+ this.set = set;
1204
+ this.i = 0;
1205
+ this.next();
1206
+ }
1207
+ next() {
1208
+ let { sections } = this.set;
1209
+ if (this.i < sections.length) {
1210
+ this.len = sections[this.i++];
1211
+ this.ins = sections[this.i++];
1212
+ }
1213
+ else {
1214
+ this.len = 0;
1215
+ this.ins = -2;
1216
+ }
1217
+ this.off = 0;
1218
+ }
1219
+ get done() { return this.ins == -2; }
1220
+ get len2() { return this.ins < 0 ? this.len : this.ins; }
1221
+ get text() {
1222
+ let { inserted } = this.set, index = (this.i - 2) >> 1;
1223
+ return index >= inserted.length ? Text.empty : inserted[index];
1224
+ }
1225
+ textBit(len) {
1226
+ let { inserted } = this.set, index = (this.i - 2) >> 1;
1227
+ return index >= inserted.length && !len ? Text.empty
1228
+ : inserted[index].slice(this.off, len == null ? undefined : this.off + len);
1229
+ }
1230
+ forward(len) {
1231
+ if (len == this.len)
1232
+ this.next();
1233
+ else {
1234
+ this.len -= len;
1235
+ this.off += len;
1236
+ }
1237
+ }
1238
+ forward2(len) {
1239
+ if (this.ins == -1)
1240
+ this.forward(len);
1241
+ else if (len == this.ins)
1242
+ this.next();
1243
+ else {
1244
+ this.ins -= len;
1245
+ this.off += len;
1246
+ }
1247
+ }
1248
+ }
1249
+
1250
+ /**
1251
+ A single selection range. When
1252
+ [`allowMultipleSelections`](https://codemirror.net/6/docs/ref/#state.EditorState^allowMultipleSelections)
1253
+ is enabled, a [selection](https://codemirror.net/6/docs/ref/#state.EditorSelection) may hold
1254
+ multiple ranges. By default, selections hold exactly one range.
1255
+ */
1256
+ class SelectionRange {
1257
+ constructor(
1258
+ /**
1259
+ The lower boundary of the range.
1260
+ */
1261
+ from,
1262
+ /**
1263
+ The upper boundary of the range.
1264
+ */
1265
+ to, flags,
1266
+ /**
1267
+ The goal column (stored vertical offset) associated with a
1268
+ cursor. This is used to preserve the vertical position when
1269
+ [moving](https://codemirror.net/6/docs/ref/#view.EditorView.moveVertically) across
1270
+ lines of different length.
1271
+ */
1272
+ goalColumn) {
1273
+ this.from = from;
1274
+ this.to = to;
1275
+ this.flags = flags;
1276
+ this.goalColumn = goalColumn;
1277
+ }
1278
+ /**
1279
+ The anchor of the range—the side that doesn't move when you
1280
+ extend it.
1281
+ */
1282
+ get anchor() { return this.flags & 32 /* RangeFlag.Inverted */ ? this.to : this.from; }
1283
+ /**
1284
+ The head of the range, which is moved when the range is
1285
+ [extended](https://codemirror.net/6/docs/ref/#state.SelectionRange.extend).
1286
+ */
1287
+ get head() { return this.flags & 32 /* RangeFlag.Inverted */ ? this.from : this.to; }
1288
+ /**
1289
+ True when `anchor` and `head` are at the same position.
1290
+ */
1291
+ get empty() { return this.from == this.to; }
1292
+ /**
1293
+ If this is a cursor that is explicitly associated with the
1294
+ character on one of its sides, this returns the side. -1 means
1295
+ the character before its position, 1 the character after, and 0
1296
+ means no association.
1297
+ */
1298
+ get assoc() { return this.flags & 8 /* RangeFlag.AssocBefore */ ? -1 : this.flags & 16 /* RangeFlag.AssocAfter */ ? 1 : 0; }
1299
+ /**
1300
+ A flag that, when set, makes some selection-extending commands
1301
+ treat the range's head and anchor as exchangeable, so that for
1302
+ example Shift-ArrowUp will make the lower side of the selection
1303
+ the anchor, even if that was the head before. Used to implement
1304
+ MacOS-style undirectional selections.
1305
+ */
1306
+ get undirectional() {
1307
+ return (this.flags & 64 /* RangeFlag.Undirectional */) > 0;
1308
+ }
1309
+ /**
1310
+ The bidirectional text level associated with this cursor, if
1311
+ any.
1312
+ */
1313
+ get bidiLevel() {
1314
+ let level = this.flags & 7 /* RangeFlag.BidiLevelMask */;
1315
+ return level == 7 ? null : level;
1316
+ }
1317
+ /**
1318
+ Map this range through a change, producing a valid range in the
1319
+ updated document.
1320
+ */
1321
+ map(change, assoc = -1) {
1322
+ let from, to;
1323
+ if (this.empty) {
1324
+ from = to = change.mapPos(this.from, assoc);
1325
+ }
1326
+ else {
1327
+ from = change.mapPos(this.from, 1);
1328
+ to = change.mapPos(this.to, -1);
1329
+ }
1330
+ return from == this.from && to == this.to ? this : new SelectionRange(from, to, this.flags, this.goalColumn);
1331
+ }
1332
+ /**
1333
+ Extend this range to cover at least `from` to `to`.
1334
+ */
1335
+ extend(from, to = from, assoc = 0) {
1336
+ if (from <= this.anchor && to >= this.anchor)
1337
+ return EditorSelection.range(from, to, undefined, undefined, assoc);
1338
+ let head = Math.abs(from - this.anchor) > Math.abs(to - this.anchor) ? from : to;
1339
+ return EditorSelection.range(this.anchor, head, undefined, undefined, assoc);
1340
+ }
1341
+ /**
1342
+ Compare this range to another range.
1343
+ */
1344
+ eq(other, includeAssoc = false) {
1345
+ return this.anchor == other.anchor && this.head == other.head && this.goalColumn == other.goalColumn &&
1346
+ (!includeAssoc || !this.empty || this.assoc == other.assoc);
1347
+ }
1348
+ /**
1349
+ Return a JSON-serializable object representing the range.
1350
+ */
1351
+ toJSON() { return { anchor: this.anchor, head: this.head }; }
1352
+ /**
1353
+ Convert a JSON representation of a range to a `SelectionRange`
1354
+ instance.
1355
+ */
1356
+ static fromJSON(json) {
1357
+ if (!json || typeof json.anchor != "number" || typeof json.head != "number")
1358
+ throw new RangeError("Invalid JSON representation for SelectionRange");
1359
+ return EditorSelection.range(json.anchor, json.head);
1360
+ }
1361
+ /**
1362
+ @internal
1363
+ */
1364
+ static create(from, to, flags, goalColumn) {
1365
+ return new SelectionRange(from, to, flags, goalColumn);
1366
+ }
1367
+ }
1368
+ /**
1369
+ An editor selection holds one or more selection ranges.
1370
+ */
1371
+ class EditorSelection {
1372
+ constructor(
1373
+ /**
1374
+ The ranges in the selection, sorted by position. Ranges cannot
1375
+ overlap (but they may touch, if they aren't empty).
1376
+ */
1377
+ ranges,
1378
+ /**
1379
+ The index of the _main_ range in the selection (which is
1380
+ usually the range that was added last).
1381
+ */
1382
+ mainIndex) {
1383
+ this.ranges = ranges;
1384
+ this.mainIndex = mainIndex;
1385
+ }
1386
+ /**
1387
+ Map a selection through a change. Used to adjust the selection
1388
+ position for changes.
1389
+ */
1390
+ map(change, assoc = -1) {
1391
+ if (change.empty)
1392
+ return this;
1393
+ return EditorSelection.create(this.ranges.map(r => r.map(change, assoc)), this.mainIndex);
1394
+ }
1395
+ /**
1396
+ Compare this selection to another selection. By default, ranges
1397
+ are compared only by position. When `includeAssoc` is true,
1398
+ cursor ranges must also have the same
1399
+ [`assoc`](https://codemirror.net/6/docs/ref/#state.SelectionRange.assoc) value.
1400
+ */
1401
+ eq(other, includeAssoc = false) {
1402
+ if (this.ranges.length != other.ranges.length ||
1403
+ this.mainIndex != other.mainIndex)
1404
+ return false;
1405
+ for (let i = 0; i < this.ranges.length; i++)
1406
+ if (!this.ranges[i].eq(other.ranges[i], includeAssoc))
1407
+ return false;
1408
+ return true;
1409
+ }
1410
+ /**
1411
+ Get the primary selection range. Usually, you should make sure
1412
+ your code applies to _all_ ranges, by using methods like
1413
+ [`changeByRange`](https://codemirror.net/6/docs/ref/#state.EditorState.changeByRange).
1414
+ */
1415
+ get main() { return this.ranges[this.mainIndex]; }
1416
+ /**
1417
+ Make sure the selection only has one range. Returns a selection
1418
+ holding only the main range from this selection.
1419
+ */
1420
+ asSingle() {
1421
+ return this.ranges.length == 1 ? this : new EditorSelection([this.main], 0);
1422
+ }
1423
+ /**
1424
+ Extend this selection with an extra range.
1425
+ */
1426
+ addRange(range, main = true) {
1427
+ return EditorSelection.create([range].concat(this.ranges), main ? 0 : this.mainIndex + 1);
1428
+ }
1429
+ /**
1430
+ Replace a given range with another range, and then normalize the
1431
+ selection to merge and sort ranges if necessary.
1432
+ */
1433
+ replaceRange(range, which = this.mainIndex) {
1434
+ let ranges = this.ranges.slice();
1435
+ ranges[which] = range;
1436
+ return EditorSelection.create(ranges, this.mainIndex);
1437
+ }
1438
+ /**
1439
+ Convert this selection to an object that can be serialized to
1440
+ JSON.
1441
+ */
1442
+ toJSON() {
1443
+ return { ranges: this.ranges.map(r => r.toJSON()), main: this.mainIndex };
1444
+ }
1445
+ /**
1446
+ Create a selection from a JSON representation.
1447
+ */
1448
+ static fromJSON(json) {
1449
+ if (!json || !Array.isArray(json.ranges) || typeof json.main != "number" || json.main >= json.ranges.length)
1450
+ throw new RangeError("Invalid JSON representation for EditorSelection");
1451
+ return new EditorSelection(json.ranges.map((r) => SelectionRange.fromJSON(r)), json.main);
1452
+ }
1453
+ /**
1454
+ Create a selection holding a single range.
1455
+ */
1456
+ static single(anchor, head = anchor) {
1457
+ return new EditorSelection([EditorSelection.range(anchor, head)], 0);
1458
+ }
1459
+ /**
1460
+ Sort and merge the given set of ranges, creating a valid
1461
+ selection.
1462
+ */
1463
+ static create(ranges, mainIndex = 0) {
1464
+ if (ranges.length == 0)
1465
+ throw new RangeError("A selection needs at least one range");
1466
+ for (let pos = 0, i = 0; i < ranges.length; i++) {
1467
+ let range = ranges[i];
1468
+ if (range.empty ? range.from <= pos : range.from < pos)
1469
+ return EditorSelection.normalized(ranges.slice(), mainIndex);
1470
+ pos = range.to;
1471
+ }
1472
+ return new EditorSelection(ranges, mainIndex);
1473
+ }
1474
+ /**
1475
+ Create a cursor selection range at the given position. You can
1476
+ safely ignore the optional arguments in most situations.
1477
+ */
1478
+ static cursor(pos, assoc = 0, bidiLevel, goalColumn) {
1479
+ return SelectionRange.create(pos, pos, (assoc == 0 ? 0 : assoc < 0 ? 8 /* RangeFlag.AssocBefore */ : 16 /* RangeFlag.AssocAfter */) |
1480
+ (bidiLevel == null ? 7 : Math.min(6, bidiLevel)), goalColumn);
1481
+ }
1482
+ /**
1483
+ Create a selection range.
1484
+ */
1485
+ static range(anchor, head, goalColumn, bidiLevel, assoc) {
1486
+ let flags = bidiLevel == null ? 7 : Math.min(6, bidiLevel);
1487
+ if (!assoc && anchor != head)
1488
+ assoc = head < anchor ? 1 : -1;
1489
+ if (assoc)
1490
+ flags |= assoc < 0 ? 8 /* RangeFlag.AssocBefore */ : 16 /* RangeFlag.AssocAfter */;
1491
+ return head < anchor ? SelectionRange.create(head, anchor, flags | 32 /* RangeFlag.Inverted */, goalColumn)
1492
+ : SelectionRange.create(anchor, head, flags, goalColumn);
1493
+ }
1494
+ /**
1495
+ Create an [undirectional](https://codemirror.net/6/docs/ref/#state.SelectionRange.undirectional)
1496
+ selection range.
1497
+ */
1498
+ static undirectionalRange(from, to) {
1499
+ return SelectionRange.create(from, to, 64 /* RangeFlag.Undirectional */, undefined);
1500
+ }
1501
+ /**
1502
+ @internal
1503
+ */
1504
+ static normalized(ranges, mainIndex = 0) {
1505
+ let main = ranges[mainIndex];
1506
+ ranges.sort((a, b) => a.from - b.from);
1507
+ mainIndex = ranges.indexOf(main);
1508
+ for (let i = 1; i < ranges.length; i++) {
1509
+ let range = ranges[i], prev = ranges[i - 1];
1510
+ if (range.empty ? range.from <= prev.to : range.from < prev.to) {
1511
+ let from = prev.from, to = Math.max(range.to, prev.to);
1512
+ if (i <= mainIndex)
1513
+ mainIndex--;
1514
+ ranges.splice(--i, 2, range.anchor > range.head ? EditorSelection.range(to, from) : EditorSelection.range(from, to));
1515
+ }
1516
+ }
1517
+ return new EditorSelection(ranges, mainIndex);
1518
+ }
1519
+ }
1520
+ function checkSelection(selection, docLength) {
1521
+ for (let range of selection.ranges)
1522
+ if (range.to > docLength)
1523
+ throw new RangeError("Selection points outside of document");
1524
+ }
1525
+
1526
+ let nextID = 0;
1527
+ /**
1528
+ A facet is a labeled value that is associated with an editor
1529
+ state. It takes inputs from any number of extensions, and combines
1530
+ those into a single output value.
1531
+
1532
+ Examples of uses of facets are the [tab
1533
+ size](https://codemirror.net/6/docs/ref/#state.EditorState^tabSize), [editor
1534
+ attributes](https://codemirror.net/6/docs/ref/#view.EditorView^editorAttributes), and [update
1535
+ listeners](https://codemirror.net/6/docs/ref/#view.EditorView^updateListener).
1536
+
1537
+ Note that `Facet` instances can be used anywhere where
1538
+ [`FacetReader`](https://codemirror.net/6/docs/ref/#state.FacetReader) is expected.
1539
+ */
1540
+ class Facet {
1541
+ constructor(
1542
+ /**
1543
+ @internal
1544
+ */
1545
+ combine,
1546
+ /**
1547
+ @internal
1548
+ */
1549
+ compareInput,
1550
+ /**
1551
+ @internal
1552
+ */
1553
+ compare, isStatic, enables) {
1554
+ this.combine = combine;
1555
+ this.compareInput = compareInput;
1556
+ this.compare = compare;
1557
+ this.isStatic = isStatic;
1558
+ /**
1559
+ @internal
1560
+ */
1561
+ this.id = nextID++;
1562
+ this.default = combine([]);
1563
+ this.extensions = typeof enables == "function" ? enables(this) : enables;
1564
+ }
1565
+ /**
1566
+ Returns a facet reader for this facet, which can be used to
1567
+ [read](https://codemirror.net/6/docs/ref/#state.EditorState.facet) it but not to define values for it.
1568
+ */
1569
+ get reader() { return this; }
1570
+ /**
1571
+ Define a new facet.
1572
+ */
1573
+ static define(config = {}) {
1574
+ 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);
1575
+ }
1576
+ /**
1577
+ Returns an extension that adds the given value to this facet.
1578
+ */
1579
+ of(value) {
1580
+ return new FacetProvider([], this, 0 /* Provider.Static */, value);
1581
+ }
1582
+ /**
1583
+ Create an extension that computes a value for the facet from a
1584
+ state. You must take care to declare the parts of the state that
1585
+ this value depends on, since your function is only called again
1586
+ for a new state when one of those parts changed.
1587
+
1588
+ In cases where your value depends only on a single field, you'll
1589
+ want to use the [`from`](https://codemirror.net/6/docs/ref/#state.Facet.from) method instead.
1590
+ */
1591
+ compute(deps, get) {
1592
+ if (this.isStatic)
1593
+ throw new Error("Can't compute a static facet");
1594
+ return new FacetProvider(deps, this, 1 /* Provider.Single */, get);
1595
+ }
1596
+ /**
1597
+ Create an extension that computes zero or more values for this
1598
+ facet from a state.
1599
+ */
1600
+ computeN(deps, get) {
1601
+ if (this.isStatic)
1602
+ throw new Error("Can't compute a static facet");
1603
+ return new FacetProvider(deps, this, 2 /* Provider.Multi */, get);
1604
+ }
1605
+ from(field, get) {
1606
+ if (!get)
1607
+ get = x => x;
1608
+ return this.compute([field], state => get(state.field(field)));
1609
+ }
1610
+ }
1611
+ function sameArray(a, b) {
1612
+ return a == b || a.length == b.length && a.every((e, i) => e === b[i]);
1613
+ }
1614
+ class FacetProvider {
1615
+ constructor(dependencies, facet, type, value) {
1616
+ this.dependencies = dependencies;
1617
+ this.facet = facet;
1618
+ this.type = type;
1619
+ this.value = value;
1620
+ this.id = nextID++;
1621
+ }
1622
+ dynamicSlot(addresses) {
1623
+ var _a;
1624
+ let getter = this.value;
1625
+ let compare = this.facet.compareInput;
1626
+ let id = this.id, idx = addresses[id] >> 1, multi = this.type == 2 /* Provider.Multi */;
1627
+ let depDoc = false, depSel = false, depAddrs = [];
1628
+ for (let dep of this.dependencies) {
1629
+ if (dep == "doc")
1630
+ depDoc = true;
1631
+ else if (dep == "selection")
1632
+ depSel = true;
1633
+ else if ((((_a = addresses[dep.id]) !== null && _a !== void 0 ? _a : 1) & 1) == 0)
1634
+ depAddrs.push(addresses[dep.id]);
1635
+ }
1636
+ return {
1637
+ create(state) {
1638
+ state.values[idx] = getter(state);
1639
+ return 1 /* SlotStatus.Changed */;
1640
+ },
1641
+ update(state, tr) {
1642
+ if ((depDoc && tr.docChanged) || (depSel && (tr.docChanged || tr.selection)) || ensureAll(state, depAddrs)) {
1643
+ let newVal = getter(state);
1644
+ if (multi ? !compareArray(newVal, state.values[idx], compare) : !compare(newVal, state.values[idx])) {
1645
+ state.values[idx] = newVal;
1646
+ return 1 /* SlotStatus.Changed */;
1647
+ }
1648
+ }
1649
+ return 0;
1650
+ },
1651
+ reconfigure: (state, oldState) => {
1652
+ let newVal, oldAddr = oldState.config.address[id];
1653
+ if (oldAddr != null) {
1654
+ let oldVal = getAddr(oldState, oldAddr);
1655
+ if (this.dependencies.every(dep => {
1656
+ return dep instanceof Facet ? oldState.facet(dep) === state.facet(dep) :
1657
+ dep instanceof StateField ? oldState.field(dep, false) == state.field(dep, false) : true;
1658
+ }) || (multi ? compareArray(newVal = getter(state), oldVal, compare) : compare(newVal = getter(state), oldVal))) {
1659
+ state.values[idx] = oldVal;
1660
+ return 0;
1661
+ }
1662
+ }
1663
+ else {
1664
+ newVal = getter(state);
1665
+ }
1666
+ state.values[idx] = newVal;
1667
+ return 1 /* SlotStatus.Changed */;
1668
+ }
1669
+ };
1670
+ }
1671
+ get extension() { return this; }
1672
+ }
1673
+ function compareArray(a, b, compare) {
1674
+ if (a.length != b.length)
1675
+ return false;
1676
+ for (let i = 0; i < a.length; i++)
1677
+ if (!compare(a[i], b[i]))
1678
+ return false;
1679
+ return true;
1680
+ }
1681
+ function ensureAll(state, addrs) {
1682
+ let changed = false;
1683
+ for (let addr of addrs)
1684
+ if (ensureAddr(state, addr) & 1 /* SlotStatus.Changed */)
1685
+ changed = true;
1686
+ return changed;
1687
+ }
1688
+ function dynamicFacetSlot(addresses, facet, providers) {
1689
+ let providerAddrs = providers.map(p => addresses[p.id]);
1690
+ let providerTypes = providers.map(p => p.type);
1691
+ let dynamic = providerAddrs.filter(p => !(p & 1));
1692
+ let idx = addresses[facet.id] >> 1;
1693
+ function get(state) {
1694
+ let values = [];
1695
+ for (let i = 0; i < providerAddrs.length; i++) {
1696
+ let value = getAddr(state, providerAddrs[i]);
1697
+ if (providerTypes[i] == 2 /* Provider.Multi */)
1698
+ for (let val of value)
1699
+ values.push(val);
1700
+ else
1701
+ values.push(value);
1702
+ }
1703
+ return facet.combine(values);
1704
+ }
1705
+ return {
1706
+ create(state) {
1707
+ for (let addr of providerAddrs)
1708
+ ensureAddr(state, addr);
1709
+ state.values[idx] = get(state);
1710
+ return 1 /* SlotStatus.Changed */;
1711
+ },
1712
+ update(state, tr) {
1713
+ if (!ensureAll(state, dynamic))
1714
+ return 0;
1715
+ let value = get(state);
1716
+ if (facet.compare(value, state.values[idx]))
1717
+ return 0;
1718
+ state.values[idx] = value;
1719
+ return 1 /* SlotStatus.Changed */;
1720
+ },
1721
+ reconfigure(state, oldState) {
1722
+ let depChanged = ensureAll(state, providerAddrs);
1723
+ let oldProviders = oldState.config.facets[facet.id], oldValue = oldState.facet(facet);
1724
+ if (oldProviders && !depChanged && sameArray(providers, oldProviders)) {
1725
+ state.values[idx] = oldValue;
1726
+ return 0;
1727
+ }
1728
+ let value = get(state);
1729
+ if (facet.compare(value, oldValue)) {
1730
+ state.values[idx] = oldValue;
1731
+ return 0;
1732
+ }
1733
+ state.values[idx] = value;
1734
+ return 1 /* SlotStatus.Changed */;
1735
+ }
1736
+ };
1737
+ }
1738
+ const initField = /*@__PURE__*/Facet.define({ static: true });
1739
+ /**
1740
+ Fields can store additional information in an editor state, and
1741
+ keep it in sync with the rest of the state.
1742
+ */
1743
+ class StateField {
1744
+ constructor(
1745
+ /**
1746
+ @internal
1747
+ */
1748
+ id, createF, updateF, compareF,
1749
+ /**
1750
+ @internal
1751
+ */
1752
+ spec) {
1753
+ this.id = id;
1754
+ this.createF = createF;
1755
+ this.updateF = updateF;
1756
+ this.compareF = compareF;
1757
+ this.spec = spec;
1758
+ /**
1759
+ @internal
1760
+ */
1761
+ this.provides = undefined;
1762
+ }
1763
+ /**
1764
+ Define a state field.
1765
+ */
1766
+ static define(config) {
1767
+ let field = new StateField(nextID++, config.create, config.update, config.compare || ((a, b) => a === b), config);
1768
+ if (config.provide)
1769
+ field.provides = config.provide(field);
1770
+ return field;
1771
+ }
1772
+ create(state) {
1773
+ let init = state.facet(initField).find(i => i.field == this);
1774
+ return ((init === null || init === void 0 ? void 0 : init.create) || this.createF)(state);
1775
+ }
1776
+ /**
1777
+ @internal
1778
+ */
1779
+ slot(addresses) {
1780
+ let idx = addresses[this.id] >> 1;
1781
+ return {
1782
+ create: (state) => {
1783
+ state.values[idx] = this.create(state);
1784
+ return 1 /* SlotStatus.Changed */;
1785
+ },
1786
+ update: (state, tr) => {
1787
+ let oldVal = state.values[idx];
1788
+ let value = this.updateF(oldVal, tr);
1789
+ if (this.compareF(oldVal, value))
1790
+ return 0;
1791
+ state.values[idx] = value;
1792
+ return 1 /* SlotStatus.Changed */;
1793
+ },
1794
+ reconfigure: (state, oldState) => {
1795
+ let init = state.facet(initField), oldInit = oldState.facet(initField), reInit;
1796
+ if ((reInit = init.find(i => i.field == this)) && reInit != oldInit.find(i => i.field == this)) {
1797
+ state.values[idx] = reInit.create(state);
1798
+ return 1 /* SlotStatus.Changed */;
1799
+ }
1800
+ if (oldState.config.address[this.id] != null) {
1801
+ state.values[idx] = oldState.field(this);
1802
+ return 0;
1803
+ }
1804
+ state.values[idx] = this.create(state);
1805
+ return 1 /* SlotStatus.Changed */;
1806
+ }
1807
+ };
1808
+ }
1809
+ /**
1810
+ Returns an extension that enables this field and overrides the
1811
+ way it is initialized. Can be useful when you need to provide a
1812
+ non-default starting value for the field.
1813
+ */
1814
+ init(create) {
1815
+ return [this, initField.of({ field: this, create })];
1816
+ }
1817
+ /**
1818
+ State field instances can be used as
1819
+ [`Extension`](https://codemirror.net/6/docs/ref/#state.Extension) values to enable the field in a
1820
+ given state.
1821
+ */
1822
+ get extension() { return this; }
1823
+ }
1824
+ const Prec_ = { lowest: 4, low: 3, default: 2, high: 1, highest: 0 };
1825
+ function prec(value) {
1826
+ return (ext) => new PrecExtension(ext, value);
1827
+ }
1828
+ /**
1829
+ By default extensions are registered in the order they are found
1830
+ in the flattened form of nested array that was provided.
1831
+ Individual extension values can be assigned a precedence to
1832
+ override this. Extensions that do not have a precedence set get
1833
+ the precedence of the nearest parent with a precedence, or
1834
+ [`default`](https://codemirror.net/6/docs/ref/#state.Prec.default) if there is no such parent. The
1835
+ final ordering of extensions is determined by first sorting by
1836
+ precedence and then by order within each precedence.
1837
+ */
1838
+ const Prec = {
1839
+ /**
1840
+ The highest precedence level, for extensions that should end up
1841
+ near the start of the precedence ordering.
1842
+ */
1843
+ highest: /*@__PURE__*/prec(Prec_.highest),
1844
+ /**
1845
+ A higher-than-default precedence, for extensions that should
1846
+ come before those with default precedence.
1847
+ */
1848
+ high: /*@__PURE__*/prec(Prec_.high),
1849
+ /**
1850
+ The default precedence, which is also used for extensions
1851
+ without an explicit precedence.
1852
+ */
1853
+ default: /*@__PURE__*/prec(Prec_.default),
1854
+ /**
1855
+ A lower-than-default precedence.
1856
+ */
1857
+ low: /*@__PURE__*/prec(Prec_.low),
1858
+ /**
1859
+ The lowest precedence level. Meant for things that should end up
1860
+ near the end of the extension order.
1861
+ */
1862
+ lowest: /*@__PURE__*/prec(Prec_.lowest)
1863
+ };
1864
+ class PrecExtension {
1865
+ constructor(inner, prec) {
1866
+ this.inner = inner;
1867
+ this.prec = prec;
1868
+ }
1869
+ get extension() { return this; }
1870
+ }
1871
+ /**
1872
+ Extension compartments can be used to make a configuration
1873
+ dynamic. By [wrapping](https://codemirror.net/6/docs/ref/#state.Compartment.of) part of your
1874
+ configuration in a compartment, you can later
1875
+ [replace](https://codemirror.net/6/docs/ref/#state.Compartment.reconfigure) that part through a
1876
+ transaction.
1877
+ */
1878
+ class Compartment {
1879
+ /**
1880
+ Create an instance of this compartment to add to your [state
1881
+ configuration](https://codemirror.net/6/docs/ref/#state.EditorStateConfig.extensions).
1882
+ */
1883
+ of(ext) { return new CompartmentInstance(this, ext); }
1884
+ /**
1885
+ Create an [effect](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects) that
1886
+ reconfigures this compartment.
1887
+ */
1888
+ reconfigure(content) {
1889
+ return Compartment.reconfigure.of({ compartment: this, extension: content });
1890
+ }
1891
+ /**
1892
+ Get the current content of the compartment in the state, or
1893
+ `undefined` if it isn't present.
1894
+ */
1895
+ get(state) {
1896
+ return state.config.compartments.get(this);
1897
+ }
1898
+ }
1899
+ class CompartmentInstance {
1900
+ constructor(compartment, inner) {
1901
+ this.compartment = compartment;
1902
+ this.inner = inner;
1903
+ }
1904
+ get extension() { return this; }
1905
+ }
1906
+ class Configuration {
1907
+ constructor(base, compartments, dynamicSlots, address, staticValues, facets) {
1908
+ this.base = base;
1909
+ this.compartments = compartments;
1910
+ this.dynamicSlots = dynamicSlots;
1911
+ this.address = address;
1912
+ this.staticValues = staticValues;
1913
+ this.facets = facets;
1914
+ this.statusTemplate = [];
1915
+ while (this.statusTemplate.length < dynamicSlots.length)
1916
+ this.statusTemplate.push(0 /* SlotStatus.Unresolved */);
1917
+ }
1918
+ staticFacet(facet) {
1919
+ let addr = this.address[facet.id];
1920
+ return addr == null ? facet.default : this.staticValues[addr >> 1];
1921
+ }
1922
+ static resolve(base, compartments, oldState) {
1923
+ let fields = [];
1924
+ let facets = Object.create(null);
1925
+ let newCompartments = new Map();
1926
+ for (let ext of flatten(base, compartments, newCompartments)) {
1927
+ if (ext instanceof StateField)
1928
+ fields.push(ext);
1929
+ else
1930
+ (facets[ext.facet.id] || (facets[ext.facet.id] = [])).push(ext);
1931
+ }
1932
+ let address = Object.create(null);
1933
+ let staticValues = [];
1934
+ let dynamicSlots = [];
1935
+ for (let field of fields) {
1936
+ address[field.id] = dynamicSlots.length << 1;
1937
+ dynamicSlots.push(a => field.slot(a));
1938
+ }
1939
+ let oldFacets = oldState === null || oldState === void 0 ? void 0 : oldState.config.facets;
1940
+ for (let id in facets) {
1941
+ let providers = facets[id], facet = providers[0].facet;
1942
+ let oldProviders = oldFacets && oldFacets[id] || [];
1943
+ if (providers.every(p => p.type == 0 /* Provider.Static */)) {
1944
+ address[facet.id] = (staticValues.length << 1) | 1;
1945
+ if (sameArray(oldProviders, providers)) {
1946
+ staticValues.push(oldState.facet(facet));
1947
+ }
1948
+ else {
1949
+ let value = facet.combine(providers.map(p => p.value));
1950
+ staticValues.push(oldState && facet.compare(value, oldState.facet(facet)) ? oldState.facet(facet) : value);
1951
+ }
1952
+ }
1953
+ else {
1954
+ for (let p of providers) {
1955
+ if (p.type == 0 /* Provider.Static */) {
1956
+ address[p.id] = (staticValues.length << 1) | 1;
1957
+ staticValues.push(p.value);
1958
+ }
1959
+ else {
1960
+ address[p.id] = dynamicSlots.length << 1;
1961
+ dynamicSlots.push(a => p.dynamicSlot(a));
1962
+ }
1963
+ }
1964
+ address[facet.id] = dynamicSlots.length << 1;
1965
+ dynamicSlots.push(a => dynamicFacetSlot(a, facet, providers));
1966
+ }
1967
+ }
1968
+ let dynamic = dynamicSlots.map(f => f(address));
1969
+ return new Configuration(base, newCompartments, dynamic, address, staticValues, facets);
1970
+ }
1971
+ }
1972
+ function flatten(extension, compartments, newCompartments) {
1973
+ let result = [[], [], [], [], []];
1974
+ let seen = new Map();
1975
+ function inner(ext, prec) {
1976
+ let known = seen.get(ext);
1977
+ if (known != null) {
1978
+ if (known <= prec)
1979
+ return;
1980
+ let found = result[known].indexOf(ext);
1981
+ if (found > -1)
1982
+ result[known].splice(found, 1);
1983
+ if (ext instanceof CompartmentInstance)
1984
+ newCompartments.delete(ext.compartment);
1985
+ }
1986
+ seen.set(ext, prec);
1987
+ if (Array.isArray(ext)) {
1988
+ for (let e of ext)
1989
+ inner(e, prec);
1990
+ }
1991
+ else if (ext instanceof CompartmentInstance) {
1992
+ if (newCompartments.has(ext.compartment))
1993
+ throw new RangeError(`Duplicate use of compartment in extensions`);
1994
+ let content = compartments.get(ext.compartment) || ext.inner;
1995
+ newCompartments.set(ext.compartment, content);
1996
+ inner(content, prec);
1997
+ }
1998
+ else if (ext instanceof PrecExtension) {
1999
+ inner(ext.inner, ext.prec);
2000
+ }
2001
+ else if (ext instanceof StateField) {
2002
+ result[prec].push(ext);
2003
+ if (ext.provides)
2004
+ inner(ext.provides, prec);
2005
+ }
2006
+ else if (ext instanceof FacetProvider) {
2007
+ result[prec].push(ext);
2008
+ if (ext.facet.extensions)
2009
+ inner(ext.facet.extensions, Prec_.default);
2010
+ }
2011
+ else {
2012
+ let content = ext.extension;
2013
+ if (!content)
2014
+ throw new Error(`Unrecognized extension value in extension set (${ext}).`);
2015
+ if (content == ext)
2016
+ throw new Error(`Unrecognized extension value in extension set (${ext}). This sometimes happens because multiple instances of @codemirror/state are loaded, breaking instanceof checks.`);
2017
+ inner(content, prec);
2018
+ }
2019
+ }
2020
+ inner(extension, Prec_.default);
2021
+ return result.reduce((a, b) => a.concat(b));
2022
+ }
2023
+ function ensureAddr(state, addr) {
2024
+ if (addr & 1)
2025
+ return 2 /* SlotStatus.Computed */;
2026
+ let idx = addr >> 1;
2027
+ let status = state.status[idx];
2028
+ if (status == 4 /* SlotStatus.Computing */)
2029
+ throw new Error("Cyclic dependency between fields and/or facets");
2030
+ if (status & 2 /* SlotStatus.Computed */)
2031
+ return status;
2032
+ state.status[idx] = 4 /* SlotStatus.Computing */;
2033
+ let changed = state.computeSlot(state, state.config.dynamicSlots[idx]);
2034
+ return state.status[idx] = 2 /* SlotStatus.Computed */ | changed;
2035
+ }
2036
+ function getAddr(state, addr) {
2037
+ return addr & 1 ? state.config.staticValues[addr >> 1] : state.values[addr >> 1];
2038
+ }
2039
+
2040
+ const languageData = /*@__PURE__*/Facet.define();
2041
+ const allowMultipleSelections = /*@__PURE__*/Facet.define({
2042
+ combine: values => values.some(v => v),
2043
+ static: true
2044
+ });
2045
+ const lineSeparator = /*@__PURE__*/Facet.define({
2046
+ combine: values => values.length ? values[0] : undefined,
2047
+ static: true
2048
+ });
2049
+ const changeFilter = /*@__PURE__*/Facet.define();
2050
+ const transactionFilter = /*@__PURE__*/Facet.define();
2051
+ const transactionExtender = /*@__PURE__*/Facet.define();
2052
+ const readOnly = /*@__PURE__*/Facet.define({
2053
+ combine: values => values.length ? values[0] : false
2054
+ });
2055
+
2056
+ /**
2057
+ Annotations are tagged values that are used to add metadata to
2058
+ transactions in an extensible way. They should be used to model
2059
+ things that effect the entire transaction (such as its [time
2060
+ stamp](https://codemirror.net/6/docs/ref/#state.Transaction^time) or information about its
2061
+ [origin](https://codemirror.net/6/docs/ref/#state.Transaction^userEvent)). For effects that happen
2062
+ _alongside_ the other changes made by the transaction, [state
2063
+ effects](https://codemirror.net/6/docs/ref/#state.StateEffect) are more appropriate.
2064
+ */
2065
+ class Annotation {
2066
+ /**
2067
+ @internal
2068
+ */
2069
+ constructor(
2070
+ /**
2071
+ The annotation type.
2072
+ */
2073
+ type,
2074
+ /**
2075
+ The value of this annotation.
2076
+ */
2077
+ value) {
2078
+ this.type = type;
2079
+ this.value = value;
2080
+ }
2081
+ /**
2082
+ Define a new type of annotation.
2083
+ */
2084
+ static define() { return new AnnotationType(); }
2085
+ }
2086
+ /**
2087
+ Marker that identifies a type of [annotation](https://codemirror.net/6/docs/ref/#state.Annotation).
2088
+ */
2089
+ class AnnotationType {
2090
+ /**
2091
+ Create an instance of this annotation.
2092
+ */
2093
+ of(value) { return new Annotation(this, value); }
2094
+ }
2095
+ /**
2096
+ Representation of a type of state effect. Defined with
2097
+ [`StateEffect.define`](https://codemirror.net/6/docs/ref/#state.StateEffect^define).
2098
+ */
2099
+ class StateEffectType {
2100
+ /**
2101
+ @internal
2102
+ */
2103
+ constructor(
2104
+ // The `any` types in these function types are there to work
2105
+ // around TypeScript issue #37631, where the type guard on
2106
+ // `StateEffect.is` mysteriously stops working when these properly
2107
+ // have type `Value`.
2108
+ /**
2109
+ @internal
2110
+ */
2111
+ map) {
2112
+ this.map = map;
2113
+ }
2114
+ /**
2115
+ Create a [state effect](https://codemirror.net/6/docs/ref/#state.StateEffect) instance of this
2116
+ type.
2117
+ */
2118
+ of(value) { return new StateEffect(this, value); }
2119
+ }
2120
+ /**
2121
+ State effects can be used to represent additional effects
2122
+ associated with a [transaction](https://codemirror.net/6/docs/ref/#state.Transaction.effects). They
2123
+ are often useful to model changes to custom [state
2124
+ fields](https://codemirror.net/6/docs/ref/#state.StateField), when those changes aren't implicit in
2125
+ document or selection changes.
2126
+ */
2127
+ class StateEffect {
2128
+ /**
2129
+ @internal
2130
+ */
2131
+ constructor(
2132
+ /**
2133
+ @internal
2134
+ */
2135
+ type,
2136
+ /**
2137
+ The value of this effect.
2138
+ */
2139
+ value) {
2140
+ this.type = type;
2141
+ this.value = value;
2142
+ }
2143
+ /**
2144
+ Map this effect through a position mapping. Will return
2145
+ `undefined` when that ends up deleting the effect.
2146
+ */
2147
+ map(mapping) {
2148
+ let mapped = this.type.map(this.value, mapping);
2149
+ return mapped === undefined ? undefined : mapped == this.value ? this : new StateEffect(this.type, mapped);
2150
+ }
2151
+ /**
2152
+ Tells you whether this effect object is of a given
2153
+ [type](https://codemirror.net/6/docs/ref/#state.StateEffectType).
2154
+ */
2155
+ is(type) { return this.type == type; }
2156
+ /**
2157
+ Define a new effect type. The type parameter indicates the type
2158
+ of values that his effect holds. It should be a type that
2159
+ doesn't include `undefined`, since that is used in
2160
+ [mapping](https://codemirror.net/6/docs/ref/#state.StateEffect.map) to indicate that an effect is
2161
+ removed.
2162
+ */
2163
+ static define(spec = {}) {
2164
+ return new StateEffectType(spec.map || (v => v));
2165
+ }
2166
+ /**
2167
+ Map an array of effects through a change set.
2168
+ */
2169
+ static mapEffects(effects, mapping) {
2170
+ if (!effects.length)
2171
+ return effects;
2172
+ let result = [];
2173
+ for (let effect of effects) {
2174
+ let mapped = effect.map(mapping);
2175
+ if (mapped)
2176
+ result.push(mapped);
2177
+ }
2178
+ return result;
2179
+ }
2180
+ }
2181
+ /**
2182
+ This effect can be used to reconfigure the root extensions of
2183
+ the editor. Doing this will discard any extensions
2184
+ [appended](https://codemirror.net/6/docs/ref/#state.StateEffect^appendConfig), but does not reset
2185
+ the content of [reconfigured](https://codemirror.net/6/docs/ref/#state.Compartment.reconfigure)
2186
+ compartments.
2187
+ */
2188
+ StateEffect.reconfigure = /*@__PURE__*/StateEffect.define();
2189
+ /**
2190
+ Append extensions to the top-level configuration of the editor.
2191
+ */
2192
+ StateEffect.appendConfig = /*@__PURE__*/StateEffect.define();
2193
+ /**
2194
+ Changes to the editor state are grouped into transactions.
2195
+ Typically, a user action creates a single transaction, which may
2196
+ contain any number of document changes, may change the selection,
2197
+ or have other effects. Create a transaction by calling
2198
+ [`EditorState.update`](https://codemirror.net/6/docs/ref/#state.EditorState.update), or immediately
2199
+ dispatch one by calling
2200
+ [`EditorView.dispatch`](https://codemirror.net/6/docs/ref/#view.EditorView.dispatch).
2201
+ */
2202
+ class Transaction {
2203
+ constructor(
2204
+ /**
2205
+ The state from which the transaction starts.
2206
+ */
2207
+ startState,
2208
+ /**
2209
+ The document changes made by this transaction.
2210
+ */
2211
+ changes,
2212
+ /**
2213
+ The selection set by this transaction, or undefined if it
2214
+ doesn't explicitly set a selection.
2215
+ */
2216
+ selection,
2217
+ /**
2218
+ The effects added to the transaction.
2219
+ */
2220
+ effects,
2221
+ /**
2222
+ @internal
2223
+ */
2224
+ annotations,
2225
+ /**
2226
+ Whether the selection should be scrolled into view after this
2227
+ transaction is dispatched.
2228
+ */
2229
+ scrollIntoView) {
2230
+ this.startState = startState;
2231
+ this.changes = changes;
2232
+ this.selection = selection;
2233
+ this.effects = effects;
2234
+ this.annotations = annotations;
2235
+ this.scrollIntoView = scrollIntoView;
2236
+ /**
2237
+ @internal
2238
+ */
2239
+ this._doc = null;
2240
+ /**
2241
+ @internal
2242
+ */
2243
+ this._state = null;
2244
+ if (selection)
2245
+ checkSelection(selection, changes.newLength);
2246
+ if (!annotations.some((a) => a.type == Transaction.time))
2247
+ this.annotations = annotations.concat(Transaction.time.of(Date.now()));
2248
+ }
2249
+ /**
2250
+ @internal
2251
+ */
2252
+ static create(startState, changes, selection, effects, annotations, scrollIntoView) {
2253
+ return new Transaction(startState, changes, selection, effects, annotations, scrollIntoView);
2254
+ }
2255
+ /**
2256
+ The new document produced by the transaction. Contrary to
2257
+ [`.state`](https://codemirror.net/6/docs/ref/#state.Transaction.state)`.doc`, accessing this won't
2258
+ force the entire new state to be computed right away, so it is
2259
+ recommended that [transaction
2260
+ filters](https://codemirror.net/6/docs/ref/#state.EditorState^transactionFilter) use this getter
2261
+ when they need to look at the new document.
2262
+ */
2263
+ get newDoc() {
2264
+ return this._doc || (this._doc = this.changes.apply(this.startState.doc));
2265
+ }
2266
+ /**
2267
+ The new selection produced by the transaction. If
2268
+ [`this.selection`](https://codemirror.net/6/docs/ref/#state.Transaction.selection) is undefined,
2269
+ this will [map](https://codemirror.net/6/docs/ref/#state.EditorSelection.map) the start state's
2270
+ current selection through the changes made by the transaction.
2271
+ */
2272
+ get newSelection() {
2273
+ return this.selection || this.startState.selection.map(this.changes);
2274
+ }
2275
+ /**
2276
+ The new state created by the transaction. Computed on demand
2277
+ (but retained for subsequent access), so it is recommended not to
2278
+ access it in [transaction
2279
+ filters](https://codemirror.net/6/docs/ref/#state.EditorState^transactionFilter) when possible.
2280
+ */
2281
+ get state() {
2282
+ if (!this._state)
2283
+ this.startState.applyTransaction(this);
2284
+ return this._state;
2285
+ }
2286
+ /**
2287
+ Get the value of the given annotation type, if any.
2288
+ */
2289
+ annotation(type) {
2290
+ for (let ann of this.annotations)
2291
+ if (ann.type == type)
2292
+ return ann.value;
2293
+ return undefined;
2294
+ }
2295
+ /**
2296
+ Indicates whether the transaction changed the document.
2297
+ */
2298
+ get docChanged() { return !this.changes.empty; }
2299
+ /**
2300
+ Indicates whether this transaction reconfigures the state
2301
+ (through a [configuration compartment](https://codemirror.net/6/docs/ref/#state.Compartment) or
2302
+ with a top-level configuration
2303
+ [effect](https://codemirror.net/6/docs/ref/#state.StateEffect^reconfigure).
2304
+ */
2305
+ get reconfigured() { return this.startState.config != this.state.config; }
2306
+ /**
2307
+ Returns true if the transaction has a [user
2308
+ event](https://codemirror.net/6/docs/ref/#state.Transaction^userEvent) annotation that is equal to
2309
+ or more specific than `event`. For example, if the transaction
2310
+ has `"select.pointer"` as user event, `"select"` and
2311
+ `"select.pointer"` will match it.
2312
+ */
2313
+ isUserEvent(event) {
2314
+ let e = this.annotation(Transaction.userEvent);
2315
+ return !!(e && (e == event || e.length > event.length && e.slice(0, event.length) == event && e[event.length] == "."));
2316
+ }
2317
+ }
2318
+ /**
2319
+ Annotation used to store transaction timestamps. Automatically
2320
+ added to every transaction, holding `Date.now()`.
2321
+ */
2322
+ Transaction.time = /*@__PURE__*/Annotation.define();
2323
+ /**
2324
+ Annotation used to associate a transaction with a user interface
2325
+ event. Holds a string identifying the event, using a
2326
+ dot-separated format to support attaching more specific
2327
+ information. The events used by the core libraries are:
2328
+
2329
+ - `"input"` when content is entered
2330
+ - `"input.type"` for typed input
2331
+ - `"input.type.compose"` for composition
2332
+ - `"input.paste"` for pasted input
2333
+ - `"input.drop"` when adding content with drag-and-drop
2334
+ - `"input.complete"` when autocompleting
2335
+ - `"delete"` when the user deletes content
2336
+ - `"delete.selection"` when deleting the selection
2337
+ - `"delete.forward"` when deleting forward from the selection
2338
+ - `"delete.backward"` when deleting backward from the selection
2339
+ - `"delete.cut"` when cutting to the clipboard
2340
+ - `"move"` when content is moved
2341
+ - `"move.drop"` when content is moved within the editor through drag-and-drop
2342
+ - `"select"` when explicitly changing the selection
2343
+ - `"select.pointer"` when selecting with a mouse or other pointing device
2344
+ - `"undo"` and `"redo"` for history actions
2345
+
2346
+ Use [`isUserEvent`](https://codemirror.net/6/docs/ref/#state.Transaction.isUserEvent) to check
2347
+ whether the annotation matches a given event.
2348
+ */
2349
+ Transaction.userEvent = /*@__PURE__*/Annotation.define();
2350
+ /**
2351
+ Annotation indicating whether a transaction should be added to
2352
+ the undo history or not.
2353
+ */
2354
+ Transaction.addToHistory = /*@__PURE__*/Annotation.define();
2355
+ /**
2356
+ Annotation indicating (when present and true) that a transaction
2357
+ represents a change made by some other actor, not the user. This
2358
+ is used, for example, to tag other people's changes in
2359
+ collaborative editing.
2360
+ */
2361
+ Transaction.remote = /*@__PURE__*/Annotation.define();
2362
+ function joinRanges(a, b) {
2363
+ let result = [];
2364
+ for (let iA = 0, iB = 0;;) {
2365
+ let from, to;
2366
+ if (iA < a.length && (iB == b.length || b[iB] >= a[iA])) {
2367
+ from = a[iA++];
2368
+ to = a[iA++];
2369
+ }
2370
+ else if (iB < b.length) {
2371
+ from = b[iB++];
2372
+ to = b[iB++];
2373
+ }
2374
+ else
2375
+ return result;
2376
+ if (!result.length || result[result.length - 1] < from)
2377
+ result.push(from, to);
2378
+ else if (result[result.length - 1] < to)
2379
+ result[result.length - 1] = to;
2380
+ }
2381
+ }
2382
+ function mergeTransaction(a, b, sequential) {
2383
+ var _a;
2384
+ let mapForA, mapForB, changes;
2385
+ if (sequential) {
2386
+ mapForA = b.changes;
2387
+ mapForB = ChangeSet.empty(b.changes.length);
2388
+ changes = a.changes.compose(b.changes);
2389
+ }
2390
+ else {
2391
+ mapForA = b.changes.map(a.changes);
2392
+ mapForB = a.changes.mapDesc(b.changes, true);
2393
+ changes = a.changes.compose(mapForA);
2394
+ }
2395
+ return {
2396
+ changes,
2397
+ selection: b.selection ? b.selection.map(mapForB) : (_a = a.selection) === null || _a === void 0 ? void 0 : _a.map(mapForA),
2398
+ effects: StateEffect.mapEffects(a.effects, mapForA).concat(StateEffect.mapEffects(b.effects, mapForB)),
2399
+ annotations: a.annotations.length ? a.annotations.concat(b.annotations) : b.annotations,
2400
+ scrollIntoView: a.scrollIntoView || b.scrollIntoView
2401
+ };
2402
+ }
2403
+ function resolveTransactionInner(state, spec, docSize) {
2404
+ let sel = spec.selection, annotations = asArray(spec.annotations);
2405
+ if (spec.userEvent)
2406
+ annotations = annotations.concat(Transaction.userEvent.of(spec.userEvent));
2407
+ return {
2408
+ changes: spec.changes instanceof ChangeSet ? spec.changes
2409
+ : ChangeSet.of(spec.changes || [], docSize, state.facet(lineSeparator)),
2410
+ selection: sel && (sel instanceof EditorSelection ? sel : EditorSelection.single(sel.anchor, sel.head)),
2411
+ effects: asArray(spec.effects),
2412
+ annotations,
2413
+ scrollIntoView: !!spec.scrollIntoView
2414
+ };
2415
+ }
2416
+ function resolveTransaction(state, specs, filter) {
2417
+ let s = resolveTransactionInner(state, specs.length ? specs[0] : {}, state.doc.length);
2418
+ if (specs.length && specs[0].filter === false)
2419
+ filter = false;
2420
+ for (let i = 1; i < specs.length; i++) {
2421
+ if (specs[i].filter === false)
2422
+ filter = false;
2423
+ let seq = !!specs[i].sequential;
2424
+ s = mergeTransaction(s, resolveTransactionInner(state, specs[i], seq ? s.changes.newLength : state.doc.length), seq);
2425
+ }
2426
+ let tr = Transaction.create(state, s.changes, s.selection, s.effects, s.annotations, s.scrollIntoView);
2427
+ return extendTransaction(filter ? filterTransaction(tr) : tr);
2428
+ }
2429
+ // Finish a transaction by applying filters if necessary.
2430
+ function filterTransaction(tr) {
2431
+ let state = tr.startState;
2432
+ // Change filters
2433
+ let result = true;
2434
+ for (let filter of state.facet(changeFilter)) {
2435
+ let value = filter(tr);
2436
+ if (value === false) {
2437
+ result = false;
2438
+ break;
2439
+ }
2440
+ if (Array.isArray(value))
2441
+ result = result === true ? value : joinRanges(result, value);
2442
+ }
2443
+ if (result !== true) {
2444
+ let changes, back;
2445
+ if (result === false) {
2446
+ back = tr.changes.invertedDesc;
2447
+ changes = ChangeSet.empty(state.doc.length);
2448
+ }
2449
+ else {
2450
+ let filtered = tr.changes.filter(result);
2451
+ changes = filtered.changes;
2452
+ back = filtered.filtered.mapDesc(filtered.changes).invertedDesc;
2453
+ }
2454
+ tr = Transaction.create(state, changes, tr.selection && tr.selection.map(back), StateEffect.mapEffects(tr.effects, back), tr.annotations, tr.scrollIntoView);
2455
+ }
2456
+ // Transaction filters
2457
+ let filters = state.facet(transactionFilter);
2458
+ for (let i = filters.length - 1; i >= 0; i--) {
2459
+ let filtered = filters[i](tr);
2460
+ if (filtered instanceof Transaction)
2461
+ tr = filtered;
2462
+ else if (Array.isArray(filtered) && filtered.length == 1 && filtered[0] instanceof Transaction)
2463
+ tr = filtered[0];
2464
+ else
2465
+ tr = resolveTransaction(state, asArray(filtered), false);
2466
+ }
2467
+ return tr;
2468
+ }
2469
+ function extendTransaction(tr) {
2470
+ let state = tr.startState, extenders = state.facet(transactionExtender), spec = tr;
2471
+ for (let i = extenders.length - 1; i >= 0; i--) {
2472
+ let extension = extenders[i](tr);
2473
+ if (extension && Object.keys(extension).length)
2474
+ spec = mergeTransaction(spec, resolveTransactionInner(state, extension, tr.changes.newLength), true);
2475
+ }
2476
+ return spec == tr ? tr : Transaction.create(state, tr.changes, tr.selection, spec.effects, spec.annotations, spec.scrollIntoView);
2477
+ }
2478
+ const none = [];
2479
+ function asArray(value) {
2480
+ return value == null ? none : Array.isArray(value) ? value : [value];
2481
+ }
2482
+
2483
+ /**
2484
+ The categories produced by a [character
2485
+ categorizer](https://codemirror.net/6/docs/ref/#state.EditorState.charCategorizer). These are used
2486
+ do things like selecting by word.
2487
+ */
2488
+ var CharCategory = /*@__PURE__*/(function (CharCategory) {
2489
+ /**
2490
+ Word characters.
2491
+ */
2492
+ CharCategory[CharCategory["Word"] = 0] = "Word";
2493
+ /**
2494
+ Whitespace.
2495
+ */
2496
+ CharCategory[CharCategory["Space"] = 1] = "Space";
2497
+ /**
2498
+ Anything else.
2499
+ */
2500
+ CharCategory[CharCategory["Other"] = 2] = "Other";
2501
+ return CharCategory})(CharCategory || (CharCategory = {}));
2502
+ const nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;
2503
+ let wordChar;
2504
+ try {
2505
+ wordChar = /*@__PURE__*/new RegExp("[\\p{Alphabetic}\\p{Number}_]", "u");
2506
+ }
2507
+ catch (_) { }
2508
+ function hasWordChar(str) {
2509
+ if (wordChar)
2510
+ return wordChar.test(str);
2511
+ for (let i = 0; i < str.length; i++) {
2512
+ let ch = str[i];
2513
+ if (/\w/.test(ch) || ch > "\x80" && (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch)))
2514
+ return true;
2515
+ }
2516
+ return false;
2517
+ }
2518
+ function makeCategorizer(wordChars) {
2519
+ return (char) => {
2520
+ if (!/\S/.test(char))
2521
+ return CharCategory.Space;
2522
+ if (hasWordChar(char))
2523
+ return CharCategory.Word;
2524
+ for (let i = 0; i < wordChars.length; i++)
2525
+ if (char.indexOf(wordChars[i]) > -1)
2526
+ return CharCategory.Word;
2527
+ return CharCategory.Other;
2528
+ };
2529
+ }
2530
+
2531
+ /**
2532
+ The editor state class is a persistent (immutable) data structure.
2533
+ To update a state, you [create](https://codemirror.net/6/docs/ref/#state.EditorState.update) a
2534
+ [transaction](https://codemirror.net/6/docs/ref/#state.Transaction), which produces a _new_ state
2535
+ instance, without modifying the original object.
2536
+
2537
+ As such, _never_ mutate properties of a state directly. That'll
2538
+ just break things.
2539
+ */
2540
+ class EditorState {
2541
+ constructor(
2542
+ /**
2543
+ @internal
2544
+ */
2545
+ config,
2546
+ /**
2547
+ The current document.
2548
+ */
2549
+ doc,
2550
+ /**
2551
+ The current selection.
2552
+ */
2553
+ selection,
2554
+ /**
2555
+ @internal
2556
+ */
2557
+ values, computeSlot, tr) {
2558
+ this.config = config;
2559
+ this.doc = doc;
2560
+ this.selection = selection;
2561
+ this.values = values;
2562
+ this.status = config.statusTemplate.slice();
2563
+ this.computeSlot = computeSlot;
2564
+ // Fill in the computed state immediately, so that further queries
2565
+ // for it made during the update return this state
2566
+ if (tr)
2567
+ tr._state = this;
2568
+ for (let i = 0; i < this.config.dynamicSlots.length; i++)
2569
+ ensureAddr(this, i << 1);
2570
+ this.computeSlot = null;
2571
+ }
2572
+ field(field, require = true) {
2573
+ let addr = this.config.address[field.id];
2574
+ if (addr == null) {
2575
+ if (require)
2576
+ throw new RangeError("Field is not present in this state");
2577
+ return undefined;
2578
+ }
2579
+ ensureAddr(this, addr);
2580
+ return getAddr(this, addr);
2581
+ }
2582
+ /**
2583
+ Create a [transaction](https://codemirror.net/6/docs/ref/#state.Transaction) that updates this
2584
+ state. Any number of [transaction specs](https://codemirror.net/6/docs/ref/#state.TransactionSpec)
2585
+ can be passed. Unless
2586
+ [`sequential`](https://codemirror.net/6/docs/ref/#state.TransactionSpec.sequential) is set, the
2587
+ [changes](https://codemirror.net/6/docs/ref/#state.TransactionSpec.changes) (if any) of each spec
2588
+ are assumed to start in the _current_ document (not the document
2589
+ produced by previous specs), and its
2590
+ [selection](https://codemirror.net/6/docs/ref/#state.TransactionSpec.selection) and
2591
+ [effects](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects) are assumed to refer
2592
+ to the document created by its _own_ changes. The resulting
2593
+ transaction contains the combined effect of all the different
2594
+ specs. For [selection](https://codemirror.net/6/docs/ref/#state.TransactionSpec.selection), later
2595
+ specs take precedence over earlier ones.
2596
+ */
2597
+ update(...specs) {
2598
+ return resolveTransaction(this, specs, true);
2599
+ }
2600
+ /**
2601
+ @internal
2602
+ */
2603
+ applyTransaction(tr) {
2604
+ let conf = this.config, { base, compartments } = conf;
2605
+ for (let effect of tr.effects) {
2606
+ if (effect.is(Compartment.reconfigure)) {
2607
+ if (conf) {
2608
+ compartments = new Map;
2609
+ conf.compartments.forEach((val, key) => compartments.set(key, val));
2610
+ conf = null;
2611
+ }
2612
+ compartments.set(effect.value.compartment, effect.value.extension);
2613
+ }
2614
+ else if (effect.is(StateEffect.reconfigure)) {
2615
+ conf = null;
2616
+ base = effect.value;
2617
+ }
2618
+ else if (effect.is(StateEffect.appendConfig)) {
2619
+ conf = null;
2620
+ base = asArray(base).concat(effect.value);
2621
+ }
2622
+ }
2623
+ let startValues;
2624
+ if (!conf) {
2625
+ conf = Configuration.resolve(base, compartments, this);
2626
+ let intermediateState = new EditorState(conf, this.doc, this.selection, conf.dynamicSlots.map(() => null), (state, slot) => slot.reconfigure(state, this), null);
2627
+ startValues = intermediateState.values;
2628
+ }
2629
+ else {
2630
+ startValues = tr.startState.values.slice();
2631
+ }
2632
+ let selection = tr.startState.facet(allowMultipleSelections) ? tr.newSelection : tr.newSelection.asSingle();
2633
+ new EditorState(conf, tr.newDoc, selection, startValues, (state, slot) => slot.update(state, tr), tr);
2634
+ }
2635
+ /**
2636
+ Create a [transaction spec](https://codemirror.net/6/docs/ref/#state.TransactionSpec) that
2637
+ replaces every selection range with the given content.
2638
+ */
2639
+ replaceSelection(text) {
2640
+ if (typeof text == "string")
2641
+ text = this.toText(text);
2642
+ return this.changeByRange(range => ({ changes: { from: range.from, to: range.to, insert: text },
2643
+ range: EditorSelection.cursor(range.from + text.length) }));
2644
+ }
2645
+ /**
2646
+ Create a set of changes and a new selection by running the given
2647
+ function for each range in the active selection. The function
2648
+ can return an optional set of changes (in the coordinate space
2649
+ of the start document), plus an updated range (in the coordinate
2650
+ space of the document produced by the call's own changes). This
2651
+ method will merge all the changes and ranges into a single
2652
+ changeset and selection, and return it as a [transaction
2653
+ spec](https://codemirror.net/6/docs/ref/#state.TransactionSpec), which can be passed to
2654
+ [`update`](https://codemirror.net/6/docs/ref/#state.EditorState.update).
2655
+ */
2656
+ changeByRange(f) {
2657
+ let sel = this.selection;
2658
+ let result1 = f(sel.ranges[0]);
2659
+ let changes = this.changes(result1.changes), ranges = [result1.range];
2660
+ let effects = asArray(result1.effects);
2661
+ for (let i = 1; i < sel.ranges.length; i++) {
2662
+ let result = f(sel.ranges[i]);
2663
+ let newChanges = this.changes(result.changes), newMapped = newChanges.map(changes);
2664
+ for (let j = 0; j < i; j++)
2665
+ ranges[j] = ranges[j].map(newMapped);
2666
+ let mapBy = changes.mapDesc(newChanges, true);
2667
+ ranges.push(result.range.map(mapBy));
2668
+ changes = changes.compose(newMapped);
2669
+ effects = StateEffect.mapEffects(effects, newMapped).concat(StateEffect.mapEffects(asArray(result.effects), mapBy));
2670
+ }
2671
+ return {
2672
+ changes,
2673
+ selection: EditorSelection.create(ranges, sel.mainIndex),
2674
+ effects
2675
+ };
2676
+ }
2677
+ /**
2678
+ Create a [change set](https://codemirror.net/6/docs/ref/#state.ChangeSet) from the given change
2679
+ description, taking the state's document length and line
2680
+ separator into account.
2681
+ */
2682
+ changes(spec = []) {
2683
+ if (spec instanceof ChangeSet)
2684
+ return spec;
2685
+ return ChangeSet.of(spec, this.doc.length, this.facet(EditorState.lineSeparator));
2686
+ }
2687
+ /**
2688
+ Using the state's [line
2689
+ separator](https://codemirror.net/6/docs/ref/#state.EditorState^lineSeparator), create a
2690
+ [`Text`](https://codemirror.net/6/docs/ref/#state.Text) instance from the given string.
2691
+ */
2692
+ toText(string) {
2693
+ return Text.of(string.split(this.facet(EditorState.lineSeparator) || DefaultSplit));
2694
+ }
2695
+ /**
2696
+ Return the given range of the document as a string.
2697
+ */
2698
+ sliceDoc(from = 0, to = this.doc.length) {
2699
+ return this.doc.sliceString(from, to, this.lineBreak);
2700
+ }
2701
+ /**
2702
+ Get the value of a state [facet](https://codemirror.net/6/docs/ref/#state.Facet).
2703
+ */
2704
+ facet(facet) {
2705
+ let addr = this.config.address[facet.id];
2706
+ if (addr == null)
2707
+ return facet.default;
2708
+ ensureAddr(this, addr);
2709
+ return getAddr(this, addr);
2710
+ }
2711
+ /**
2712
+ Convert this state to a JSON-serializable object. When custom
2713
+ fields should be serialized, you can pass them in as an object
2714
+ mapping property names (in the resulting object, which should
2715
+ not use `doc` or `selection`) to fields.
2716
+ */
2717
+ toJSON(fields) {
2718
+ let result = {
2719
+ doc: this.sliceDoc(),
2720
+ selection: this.selection.toJSON()
2721
+ };
2722
+ if (fields)
2723
+ for (let prop in fields) {
2724
+ let value = fields[prop];
2725
+ if (value instanceof StateField && this.config.address[value.id] != null)
2726
+ result[prop] = value.spec.toJSON(this.field(fields[prop]), this);
2727
+ }
2728
+ return result;
2729
+ }
2730
+ /**
2731
+ Deserialize a state from its JSON representation. When custom
2732
+ fields should be deserialized, pass the same object you passed
2733
+ to [`toJSON`](https://codemirror.net/6/docs/ref/#state.EditorState.toJSON) when serializing as
2734
+ third argument.
2735
+ */
2736
+ static fromJSON(json, config = {}, fields) {
2737
+ if (!json || typeof json.doc != "string")
2738
+ throw new RangeError("Invalid JSON representation for EditorState");
2739
+ let fieldInit = [];
2740
+ if (fields)
2741
+ for (let prop in fields) {
2742
+ if (Object.prototype.hasOwnProperty.call(json, prop)) {
2743
+ let field = fields[prop], value = json[prop];
2744
+ fieldInit.push(field.init(state => field.spec.fromJSON(value, state)));
2745
+ }
2746
+ }
2747
+ return EditorState.create({
2748
+ doc: json.doc,
2749
+ selection: EditorSelection.fromJSON(json.selection),
2750
+ extensions: config.extensions ? fieldInit.concat([config.extensions]) : fieldInit
2751
+ });
2752
+ }
2753
+ /**
2754
+ Create a new state. You'll usually only need this when
2755
+ initializing an editor—updated states are created by applying
2756
+ transactions.
2757
+ */
2758
+ static create(config = {}) {
2759
+ let configuration = Configuration.resolve(config.extensions || [], new Map);
2760
+ let doc = config.doc instanceof Text ? config.doc
2761
+ : Text.of((config.doc || "").split(configuration.staticFacet(EditorState.lineSeparator) || DefaultSplit));
2762
+ let selection = !config.selection ? EditorSelection.single(0)
2763
+ : config.selection instanceof EditorSelection ? config.selection
2764
+ : EditorSelection.single(config.selection.anchor, config.selection.head);
2765
+ checkSelection(selection, doc.length);
2766
+ if (!configuration.staticFacet(allowMultipleSelections))
2767
+ selection = selection.asSingle();
2768
+ return new EditorState(configuration, doc, selection, configuration.dynamicSlots.map(() => null), (state, slot) => slot.create(state), null);
2769
+ }
2770
+ /**
2771
+ The size (in columns) of a tab in the document, determined by
2772
+ the [`tabSize`](https://codemirror.net/6/docs/ref/#state.EditorState^tabSize) facet.
2773
+ */
2774
+ get tabSize() { return this.facet(EditorState.tabSize); }
2775
+ /**
2776
+ Get the proper [line-break](https://codemirror.net/6/docs/ref/#state.EditorState^lineSeparator)
2777
+ string for this state.
2778
+ */
2779
+ get lineBreak() { return this.facet(EditorState.lineSeparator) || "\n"; }
2780
+ /**
2781
+ Returns true when the editor is
2782
+ [configured](https://codemirror.net/6/docs/ref/#state.EditorState^readOnly) to be read-only.
2783
+ */
2784
+ get readOnly() { return this.facet(readOnly); }
2785
+ /**
2786
+ Look up a translation for the given phrase (via the
2787
+ [`phrases`](https://codemirror.net/6/docs/ref/#state.EditorState^phrases) facet), or return the
2788
+ original string if no translation is found.
2789
+
2790
+ If additional arguments are passed, they will be inserted in
2791
+ place of markers like `$1` (for the first value) and `$2`, etc.
2792
+ A single `$` is equivalent to `$1`, and `$$` will produce a
2793
+ literal dollar sign.
2794
+ */
2795
+ phrase(phrase, ...insert) {
2796
+ for (let map of this.facet(EditorState.phrases))
2797
+ if (Object.prototype.hasOwnProperty.call(map, phrase)) {
2798
+ phrase = map[phrase];
2799
+ break;
2800
+ }
2801
+ if (insert.length)
2802
+ phrase = phrase.replace(/\$(\$|\d*)/g, (m, i) => {
2803
+ if (i == "$")
2804
+ return "$";
2805
+ let n = +(i || 1);
2806
+ return !n || n > insert.length ? m : insert[n - 1];
2807
+ });
2808
+ return phrase;
2809
+ }
2810
+ /**
2811
+ Find the values for a given language data field, provided by the
2812
+ the [`languageData`](https://codemirror.net/6/docs/ref/#state.EditorState^languageData) facet.
2813
+
2814
+ Examples of language data fields are...
2815
+
2816
+ - [`"commentTokens"`](https://codemirror.net/6/docs/ref/#commands.CommentTokens) for specifying
2817
+ comment syntax.
2818
+ - [`"autocomplete"`](https://codemirror.net/6/docs/ref/#autocomplete.autocompletion^config.override)
2819
+ for providing language-specific completion sources.
2820
+ - [`"wordChars"`](https://codemirror.net/6/docs/ref/#state.EditorState.charCategorizer) for adding
2821
+ characters that should be considered part of words in this
2822
+ language.
2823
+ - [`"closeBrackets"`](https://codemirror.net/6/docs/ref/#autocomplete.CloseBracketConfig) controls
2824
+ bracket closing behavior.
2825
+ */
2826
+ languageDataAt(name, pos, side = -1) {
2827
+ let values = [];
2828
+ for (let provider of this.facet(languageData)) {
2829
+ for (let result of provider(this, pos, side)) {
2830
+ if (Object.prototype.hasOwnProperty.call(result, name))
2831
+ values.push(result[name]);
2832
+ }
2833
+ }
2834
+ return values;
2835
+ }
2836
+ /**
2837
+ Return a function that can categorize strings (expected to
2838
+ represent a single [grapheme cluster](https://codemirror.net/6/docs/ref/#state.findClusterBreak))
2839
+ into one of:
2840
+
2841
+ - Word (contains an alphanumeric character or a character
2842
+ explicitly listed in the local language's `"wordChars"`
2843
+ language data, which should be a string)
2844
+ - Space (contains only whitespace)
2845
+ - Other (anything else)
2846
+ */
2847
+ charCategorizer(at) {
2848
+ let chars = this.languageDataAt("wordChars", at);
2849
+ return makeCategorizer(chars.length ? chars[0] : "");
2850
+ }
2851
+ /**
2852
+ Find the word at the given position, meaning the range
2853
+ containing all [word](https://codemirror.net/6/docs/ref/#state.CharCategory.Word) characters
2854
+ around it. If no word characters are adjacent to the position,
2855
+ this returns null.
2856
+ */
2857
+ wordAt(pos) {
2858
+ let { text, from, length } = this.doc.lineAt(pos);
2859
+ let cat = this.charCategorizer(pos);
2860
+ let start = pos - from, end = pos - from;
2861
+ while (start > 0) {
2862
+ let prev = findClusterBreak(text, start, false);
2863
+ if (cat(text.slice(prev, start)) != CharCategory.Word)
2864
+ break;
2865
+ start = prev;
2866
+ }
2867
+ while (end < length) {
2868
+ let next = findClusterBreak(text, end);
2869
+ if (cat(text.slice(end, next)) != CharCategory.Word)
2870
+ break;
2871
+ end = next;
2872
+ }
2873
+ return start == end ? null : EditorSelection.range(start + from, end + from);
2874
+ }
2875
+ }
2876
+ /**
2877
+ A facet that, when enabled, causes the editor to allow multiple
2878
+ ranges to be selected. Be careful though, because by default the
2879
+ editor relies on the native DOM selection, which cannot handle
2880
+ multiple selections. An extension like
2881
+ [`drawSelection`](https://codemirror.net/6/docs/ref/#view.drawSelection) can be used to make
2882
+ secondary selections visible to the user.
2883
+ */
2884
+ EditorState.allowMultipleSelections = allowMultipleSelections;
2885
+ /**
2886
+ Configures the tab size to use in this state. The first
2887
+ (highest-precedence) value of the facet is used. If no value is
2888
+ given, this defaults to 4.
2889
+ */
2890
+ EditorState.tabSize = /*@__PURE__*/Facet.define({
2891
+ combine: values => values.length ? values[0] : 4
2892
+ });
2893
+ /**
2894
+ The line separator to use. By default, any of `"\n"`, `"\r\n"`
2895
+ and `"\r"` is treated as a separator when splitting lines, and
2896
+ lines are joined with `"\n"`.
2897
+
2898
+ When you configure a value here, only that precise separator
2899
+ will be used, allowing you to round-trip documents through the
2900
+ editor without normalizing line separators.
2901
+ */
2902
+ EditorState.lineSeparator = lineSeparator;
2903
+ /**
2904
+ This facet controls the value of the
2905
+ [`readOnly`](https://codemirror.net/6/docs/ref/#state.EditorState.readOnly) getter, which is
2906
+ consulted by commands and extensions that implement editing
2907
+ functionality to determine whether they should apply. It
2908
+ defaults to false, but when its highest-precedence value is
2909
+ `true`, such functionality disables itself.
2910
+
2911
+ Not to be confused with
2912
+ [`EditorView.editable`](https://codemirror.net/6/docs/ref/#view.EditorView^editable), which
2913
+ controls whether the editor's DOM is set to be editable (and
2914
+ thus focusable).
2915
+ */
2916
+ EditorState.readOnly = readOnly;
2917
+ /**
2918
+ Registers translation phrases. The
2919
+ [`phrase`](https://codemirror.net/6/docs/ref/#state.EditorState.phrase) method will look through
2920
+ all objects registered with this facet to find translations for
2921
+ its argument.
2922
+ */
2923
+ EditorState.phrases = /*@__PURE__*/Facet.define({
2924
+ compare(a, b) {
2925
+ let kA = Object.keys(a), kB = Object.keys(b);
2926
+ return kA.length == kB.length && kA.every(k => a[k] == b[k]);
2927
+ }
2928
+ });
2929
+ /**
2930
+ A facet used to register [language
2931
+ data](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt) providers.
2932
+ */
2933
+ EditorState.languageData = languageData;
2934
+ /**
2935
+ Facet used to register change filters, which are called for each
2936
+ transaction (unless explicitly
2937
+ [disabled](https://codemirror.net/6/docs/ref/#state.TransactionSpec.filter)), and can suppress
2938
+ part of the transaction's changes.
2939
+
2940
+ Such a function can return `true` to indicate that it doesn't
2941
+ want to do anything, `false` to completely stop the changes in
2942
+ the transaction, or a set of ranges in which changes should be
2943
+ suppressed. Such ranges are represented as an array of numbers,
2944
+ with each pair of two numbers indicating the start and end of a
2945
+ range. So for example `[10, 20, 100, 110]` suppresses changes
2946
+ between 10 and 20, and between 100 and 110.
2947
+ */
2948
+ EditorState.changeFilter = changeFilter;
2949
+ /**
2950
+ Facet used to register a hook that gets a chance to update or
2951
+ replace transaction specs before they are applied. This will
2952
+ only be applied for transactions that don't have
2953
+ [`filter`](https://codemirror.net/6/docs/ref/#state.TransactionSpec.filter) set to `false`. You
2954
+ can either return a single transaction spec (possibly the input
2955
+ transaction), or an array of specs (which will be combined in
2956
+ the same way as the arguments to
2957
+ [`EditorState.update`](https://codemirror.net/6/docs/ref/#state.EditorState.update)).
2958
+
2959
+ When possible, it is recommended to avoid accessing
2960
+ [`Transaction.state`](https://codemirror.net/6/docs/ref/#state.Transaction.state) in a filter,
2961
+ since it will force creation of a state that will then be
2962
+ discarded again, if the transaction is actually filtered.
2963
+
2964
+ (This functionality should be used with care. Indiscriminately
2965
+ modifying transaction is likely to break something or degrade
2966
+ the user experience.)
2967
+ */
2968
+ EditorState.transactionFilter = transactionFilter;
2969
+ /**
2970
+ This is a more limited form of
2971
+ [`transactionFilter`](https://codemirror.net/6/docs/ref/#state.EditorState^transactionFilter),
2972
+ which can only add
2973
+ [annotations](https://codemirror.net/6/docs/ref/#state.TransactionSpec.annotations) and
2974
+ [effects](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects). _But_, this type
2975
+ of filter runs even if the transaction has disabled regular
2976
+ [filtering](https://codemirror.net/6/docs/ref/#state.TransactionSpec.filter), making it suitable
2977
+ for effects that don't need to touch the changes or selection,
2978
+ but do want to process every transaction.
2979
+
2980
+ Extenders run _after_ filters, when both are present.
2981
+ */
2982
+ EditorState.transactionExtender = transactionExtender;
2983
+ Compartment.reconfigure = /*@__PURE__*/StateEffect.define();
2984
+
2985
+ /**
2986
+ Utility function for combining behaviors to fill in a config
2987
+ object from an array of provided configs. `defaults` should hold
2988
+ default values for all optional fields in `Config`.
2989
+
2990
+ The function will, by default, error
2991
+ when a field gets two values that aren't `===`-equal, but you can
2992
+ provide combine functions per field to do something else.
2993
+ */
2994
+ function combineConfig(configs, defaults, // Should hold only the optional properties of Config, but I haven't managed to express that
2995
+ combine = {}) {
2996
+ let result = {};
2997
+ for (let config of configs)
2998
+ for (let key of Object.keys(config)) {
2999
+ let value = config[key], current = result[key];
3000
+ if (current === undefined)
3001
+ result[key] = value;
3002
+ else if (current === value || value === undefined) ; // No conflict
3003
+ else if (Object.hasOwnProperty.call(combine, key))
3004
+ result[key] = combine[key](current, value);
3005
+ else
3006
+ throw new Error("Config merge conflict for field " + key);
3007
+ }
3008
+ for (let key in defaults)
3009
+ if (result[key] === undefined)
3010
+ result[key] = defaults[key];
3011
+ return result;
3012
+ }
3013
+
3014
+ /**
3015
+ Each range is associated with a value, which must inherit from
3016
+ this class.
3017
+ */
3018
+ class RangeValue {
3019
+ /**
3020
+ Compare this value with another value. Used when comparing
3021
+ rangesets. The default implementation compares by identity.
3022
+ Unless you are only creating a fixed number of unique instances
3023
+ of your value type, it is a good idea to implement this
3024
+ properly.
3025
+ */
3026
+ eq(other) { return this == other; }
3027
+ /**
3028
+ Create a [range](https://codemirror.net/6/docs/ref/#state.Range) with this value.
3029
+ */
3030
+ range(from, to = from) { return Range.create(from, to, this); }
3031
+ }
3032
+ RangeValue.prototype.startSide = RangeValue.prototype.endSide = 0;
3033
+ RangeValue.prototype.point = false;
3034
+ RangeValue.prototype.mapMode = MapMode.TrackDel;
3035
+ function cmpVal(a, b) {
3036
+ return a == b || a.constructor == b.constructor && a.eq(b);
3037
+ }
3038
+ /**
3039
+ A range associates a value with a range of positions.
3040
+ */
3041
+ class Range {
3042
+ constructor(
3043
+ /**
3044
+ The range's start position.
3045
+ */
3046
+ from,
3047
+ /**
3048
+ Its end position.
3049
+ */
3050
+ to,
3051
+ /**
3052
+ The value associated with this range.
3053
+ */
3054
+ value) {
3055
+ this.from = from;
3056
+ this.to = to;
3057
+ this.value = value;
3058
+ }
3059
+ /**
3060
+ @internal
3061
+ */
3062
+ static create(from, to, value) {
3063
+ return new Range(from, to, value);
3064
+ }
3065
+ }
3066
+ function cmpRange(a, b) {
3067
+ return a.from - b.from || a.value.startSide - b.value.startSide;
3068
+ }
3069
+ class Chunk {
3070
+ constructor(from, to, value,
3071
+ // Chunks are marked with the largest point that occurs
3072
+ // in them (or -1 for no points), so that scans that are
3073
+ // only interested in points (such as the
3074
+ // heightmap-related logic) can skip range-only chunks.
3075
+ maxPoint) {
3076
+ this.from = from;
3077
+ this.to = to;
3078
+ this.value = value;
3079
+ this.maxPoint = maxPoint;
3080
+ }
3081
+ get length() { return last(this.to); }
3082
+ // Find the index of the given position and side. Use the ranges'
3083
+ // `from` pos when `end == false`, `to` when `end == true`.
3084
+ findIndex(pos, side, end, startAt = 0) {
3085
+ let arr = end ? this.to : this.from;
3086
+ for (let lo = startAt, hi = arr.length;;) {
3087
+ if (lo == hi)
3088
+ return lo;
3089
+ let mid = (lo + hi) >> 1;
3090
+ let diff = arr[mid] - pos || (end ? this.value[mid].endSide : this.value[mid].startSide) - side;
3091
+ if (mid == lo)
3092
+ return diff >= 0 ? lo : hi;
3093
+ if (diff >= 0)
3094
+ hi = mid;
3095
+ else
3096
+ lo = mid + 1;
3097
+ }
3098
+ }
3099
+ between(offset, from, to, f) {
3100
+ for (let i = this.findIndex(from, -1000000000 /* C.Far */, true), e = this.findIndex(to, 1000000000 /* C.Far */, false, i); i < e; i++)
3101
+ if (f(this.from[i] + offset, this.to[i] + offset, this.value[i]) === false)
3102
+ return false;
3103
+ }
3104
+ map(offset, changes, basePos, baseSide, spill) {
3105
+ let value = [], from = [], to = [], newPos = -1, maxPoint = -1;
3106
+ iter: for (let i = 0; i < this.value.length; i++) {
3107
+ let val = this.value[i], curFrom = this.from[i] + offset, curTo = this.to[i] + offset, newFrom, newTo;
3108
+ if (curFrom == curTo) {
3109
+ let mapped = changes.mapPos(curFrom, val.startSide, val.mapMode);
3110
+ if (mapped == null)
3111
+ continue;
3112
+ newFrom = newTo = mapped;
3113
+ if (val.startSide != val.endSide) {
3114
+ newTo = changes.mapPos(curFrom, val.endSide);
3115
+ if (newTo < newFrom)
3116
+ continue;
3117
+ }
3118
+ }
3119
+ else {
3120
+ newFrom = changes.mapPos(curFrom, val.startSide);
3121
+ newTo = changes.mapPos(curTo, val.endSide);
3122
+ if (newFrom > newTo || newFrom == newTo && val.startSide > 0 && val.endSide <= 0)
3123
+ continue;
3124
+ }
3125
+ if ((newTo - newFrom || val.endSide - val.startSide) < 0)
3126
+ continue;
3127
+ if (newPos < 0)
3128
+ newPos = newFrom;
3129
+ if (val.point)
3130
+ maxPoint = Math.max(maxPoint, newTo - newFrom);
3131
+ if ((newFrom - basePos || val.startSide - baseSide) >= 0) {
3132
+ value.push(val);
3133
+ from.push(newFrom - newPos);
3134
+ to.push(newTo - newPos);
3135
+ basePos = newTo;
3136
+ baseSide = val.endSide;
3137
+ }
3138
+ else {
3139
+ if (newFrom == newTo) { // Try to reorder points to fit in here
3140
+ for (let i = value.length; i > 0; i--) {
3141
+ if ((newFrom - (to[i - 1] + newPos) || val.startSide - value[i - 1].endSide) >= 0) {
3142
+ value.splice(i, 0, val);
3143
+ from.splice(i, 0, newFrom - newPos);
3144
+ to.splice(i, 0, newTo - newPos);
3145
+ continue iter;
3146
+ }
3147
+ if ((newFrom - (from[i - 1] + newPos) || val.endSide - value[i - 1].startSide) > 0)
3148
+ break;
3149
+ }
3150
+ }
3151
+ // Otherwise, spill into a new layer
3152
+ spill(newFrom, newTo, val);
3153
+ }
3154
+ }
3155
+ return { mapped: value.length ? new Chunk(from, to, value, maxPoint) : null, pos: newPos };
3156
+ }
3157
+ }
3158
+ /**
3159
+ A range set stores a collection of [ranges](https://codemirror.net/6/docs/ref/#state.Range) in a
3160
+ way that makes them efficient to [map](https://codemirror.net/6/docs/ref/#state.RangeSet.map) and
3161
+ [update](https://codemirror.net/6/docs/ref/#state.RangeSet.update). This is an immutable data
3162
+ structure.
3163
+ */
3164
+ class RangeSet {
3165
+ constructor(
3166
+ /**
3167
+ @internal
3168
+ */
3169
+ chunkPos,
3170
+ /**
3171
+ @internal
3172
+ */
3173
+ chunk,
3174
+ /**
3175
+ @internal
3176
+ */
3177
+ nextLayer,
3178
+ /**
3179
+ @internal
3180
+ */
3181
+ maxPoint) {
3182
+ this.chunkPos = chunkPos;
3183
+ this.chunk = chunk;
3184
+ this.nextLayer = nextLayer;
3185
+ this.maxPoint = maxPoint;
3186
+ }
3187
+ /**
3188
+ @internal
3189
+ */
3190
+ static create(chunkPos, chunk, nextLayer, maxPoint) {
3191
+ return new RangeSet(chunkPos, chunk, nextLayer, maxPoint);
3192
+ }
3193
+ /**
3194
+ @internal
3195
+ */
3196
+ get length() {
3197
+ let last = this.chunk.length - 1;
3198
+ return last < 0 ? 0 : Math.max(this.chunkEnd(last), this.nextLayer.length);
3199
+ }
3200
+ /**
3201
+ The number of ranges in the set.
3202
+ */
3203
+ get size() {
3204
+ if (this.isEmpty)
3205
+ return 0;
3206
+ let size = this.nextLayer.size;
3207
+ for (let chunk of this.chunk)
3208
+ size += chunk.value.length;
3209
+ return size;
3210
+ }
3211
+ /**
3212
+ @internal
3213
+ */
3214
+ chunkEnd(index) {
3215
+ return this.chunkPos[index] + this.chunk[index].length;
3216
+ }
3217
+ /**
3218
+ Update the range set, optionally adding new ranges or filtering
3219
+ out existing ones.
3220
+
3221
+ (Note: The type parameter is just there as a kludge to work
3222
+ around TypeScript variance issues that prevented `RangeSet<X>`
3223
+ from being a subtype of `RangeSet<Y>` when `X` is a subtype of
3224
+ `Y`.)
3225
+ */
3226
+ update(updateSpec) {
3227
+ let { add = [], sort = false, filterFrom = 0, filterTo = this.length } = updateSpec;
3228
+ let filter = updateSpec.filter;
3229
+ if (add.length == 0 && !filter)
3230
+ return this;
3231
+ if (sort)
3232
+ add = add.slice().sort(cmpRange);
3233
+ if (this.isEmpty)
3234
+ return add.length ? RangeSet.of(add) : this;
3235
+ let cur = new LayerCursor(this, null, -1).goto(0), i = 0, spill = [];
3236
+ let builder = new RangeSetBuilder();
3237
+ while (cur.value || i < add.length) {
3238
+ if (i < add.length && (cur.from - add[i].from || cur.startSide - add[i].value.startSide) >= 0) {
3239
+ let range = add[i++];
3240
+ if (!builder.addInner(range.from, range.to, range.value, false))
3241
+ spill.push(range);
3242
+ }
3243
+ else if (cur.rangeIndex == 1 && cur.chunkIndex < this.chunk.length &&
3244
+ (i == add.length || this.chunkEnd(cur.chunkIndex) < add[i].from) &&
3245
+ (!filter || filterFrom > this.chunkEnd(cur.chunkIndex) || filterTo < this.chunkPos[cur.chunkIndex]) &&
3246
+ builder.addChunk(this.chunkPos[cur.chunkIndex], this.chunk[cur.chunkIndex])) {
3247
+ cur.nextChunk();
3248
+ }
3249
+ else {
3250
+ if (!filter || filterFrom > cur.to || filterTo < cur.from || filter(cur.from, cur.to, cur.value)) {
3251
+ if (!builder.addInner(cur.from, cur.to, cur.value, false))
3252
+ spill.push(Range.create(cur.from, cur.to, cur.value));
3253
+ }
3254
+ cur.next();
3255
+ }
3256
+ }
3257
+ return builder.finishInner(this.nextLayer.isEmpty && !spill.length ? RangeSet.empty
3258
+ : this.nextLayer.update({ add: spill, filter, filterFrom, filterTo }));
3259
+ }
3260
+ /**
3261
+ Map this range set through a set of changes, return the new set.
3262
+ */
3263
+ map(changes) {
3264
+ if (changes.empty || this.isEmpty)
3265
+ return this;
3266
+ let chunks = [], chunkPos = [], maxPoint = -1;
3267
+ let spilled;
3268
+ let spill = (from, to, value) => {
3269
+ if (!spilled)
3270
+ spilled = new RangeSetBuilder();
3271
+ spilled.addRange(from, to, value, false);
3272
+ };
3273
+ for (let i = 0; i < this.chunk.length; i++) {
3274
+ let start = this.chunkPos[i], chunk = this.chunk[i];
3275
+ let touch = changes.touchesRange(start, start + chunk.length);
3276
+ if (touch === false) {
3277
+ maxPoint = Math.max(maxPoint, chunk.maxPoint);
3278
+ chunks.push(chunk);
3279
+ chunkPos.push(changes.mapPos(start));
3280
+ }
3281
+ else if (touch === true) {
3282
+ let [prevPos, prevSide] = !chunks.length ? [-1, -1]
3283
+ : [last(chunkPos) + last(chunks).length, last(last(chunks).value).endSide];
3284
+ let { mapped, pos } = chunk.map(start, changes, prevPos, prevSide, spill);
3285
+ if (mapped) {
3286
+ maxPoint = Math.max(maxPoint, mapped.maxPoint);
3287
+ chunks.push(mapped);
3288
+ chunkPos.push(pos);
3289
+ }
3290
+ }
3291
+ }
3292
+ let next = this.nextLayer.map(changes);
3293
+ if (spilled)
3294
+ next = spilled.finishInner(next);
3295
+ return chunks.length == 0 ? next : new RangeSet(chunkPos, chunks, next || RangeSet.empty, maxPoint);
3296
+ }
3297
+ /**
3298
+ Iterate over the ranges that touch the region `from` to `to`,
3299
+ calling `f` for each. There is no guarantee that the ranges will
3300
+ be reported in any specific order. When the callback returns
3301
+ `false`, iteration stops.
3302
+ */
3303
+ between(from, to, f) {
3304
+ if (this.isEmpty)
3305
+ return;
3306
+ for (let i = 0; i < this.chunk.length; i++) {
3307
+ let start = this.chunkPos[i], chunk = this.chunk[i];
3308
+ if (to >= start && from <= start + chunk.length &&
3309
+ chunk.between(start, from - start, to - start, f) === false)
3310
+ return;
3311
+ }
3312
+ this.nextLayer.between(from, to, f);
3313
+ }
3314
+ /**
3315
+ Iterate over the ranges in this set, in order, including all
3316
+ ranges that end at or after `from`.
3317
+ */
3318
+ iter(from = 0) {
3319
+ return HeapCursor.from([this]).goto(from);
3320
+ }
3321
+ /**
3322
+ @internal
3323
+ */
3324
+ get isEmpty() { return this.nextLayer == this; }
3325
+ /**
3326
+ Iterate over the ranges in a collection of sets, in order,
3327
+ starting from `from`.
3328
+ */
3329
+ static iter(sets, from = 0) {
3330
+ return HeapCursor.from(sets).goto(from);
3331
+ }
3332
+ /**
3333
+ Iterate over two groups of sets, calling methods on `comparator`
3334
+ to notify it of possible differences.
3335
+ */
3336
+ static compare(oldSets, newSets,
3337
+ /**
3338
+ This indicates how the underlying data changed between these
3339
+ ranges, and is needed to synchronize the iteration.
3340
+ */
3341
+ textDiff, comparator,
3342
+ /**
3343
+ Can be used to ignore all non-point ranges, and points below
3344
+ the given size. When -1, all ranges are compared.
3345
+ */
3346
+ minPointSize = -1) {
3347
+ let a = oldSets.filter(set => set.maxPoint > 0 || !set.isEmpty && set.maxPoint >= minPointSize);
3348
+ let b = newSets.filter(set => set.maxPoint > 0 || !set.isEmpty && set.maxPoint >= minPointSize);
3349
+ let sharedChunks = findSharedChunks(a, b, textDiff);
3350
+ let sideA = new SpanCursor(a, sharedChunks, minPointSize);
3351
+ let sideB = new SpanCursor(b, sharedChunks, minPointSize);
3352
+ textDiff.iterGaps((fromA, fromB, length) => compare(sideA, fromA, sideB, fromB, length, comparator));
3353
+ if (textDiff.empty && textDiff.length == 0)
3354
+ compare(sideA, 0, sideB, 0, 0, comparator);
3355
+ }
3356
+ /**
3357
+ Compare the contents of two groups of range sets, returning true
3358
+ if they are equivalent in the given range.
3359
+ */
3360
+ static eq(oldSets, newSets, from = 0, to) {
3361
+ if (to == null)
3362
+ to = 1000000000 /* C.Far */ - 1;
3363
+ let a = oldSets.filter(set => !set.isEmpty && newSets.indexOf(set) < 0);
3364
+ let b = newSets.filter(set => !set.isEmpty && oldSets.indexOf(set) < 0);
3365
+ if (a.length != b.length)
3366
+ return false;
3367
+ if (!a.length)
3368
+ return true;
3369
+ let sharedChunks = findSharedChunks(a, b);
3370
+ let sideA = new SpanCursor(a, sharedChunks, 0).goto(from), sideB = new SpanCursor(b, sharedChunks, 0).goto(from);
3371
+ for (;;) {
3372
+ if (sideA.to != sideB.to ||
3373
+ !sameValues(sideA.active, sideB.active) ||
3374
+ sideA.point && (!sideB.point || !cmpVal(sideA.point, sideB.point)))
3375
+ return false;
3376
+ if (sideA.to > to)
3377
+ return true;
3378
+ sideA.next();
3379
+ sideB.next();
3380
+ }
3381
+ }
3382
+ /**
3383
+ Iterate over a group of range sets at the same time, notifying
3384
+ the iterator about the ranges covering every given piece of
3385
+ content. Returns the open count (see
3386
+ [`SpanIterator.span`](https://codemirror.net/6/docs/ref/#state.SpanIterator.span)) at the end
3387
+ of the iteration.
3388
+ */
3389
+ static spans(sets, from, to, iterator,
3390
+ /**
3391
+ When given and greater than -1, only points of at least this
3392
+ size are taken into account.
3393
+ */
3394
+ minPointSize = -1) {
3395
+ let cursor = new SpanCursor(sets, null, minPointSize).goto(from), pos = from;
3396
+ let openRanges = cursor.openStart;
3397
+ for (;;) {
3398
+ let curTo = Math.min(cursor.to, to);
3399
+ if (cursor.point) {
3400
+ let active = cursor.activeForPoint(cursor.to);
3401
+ let openCount = cursor.pointFrom < from ? active.length + 1
3402
+ : cursor.point.startSide < 0 ? active.length
3403
+ : Math.min(active.length, openRanges);
3404
+ iterator.point(pos, curTo, cursor.point, active, openCount, cursor.pointRank);
3405
+ openRanges = Math.min(cursor.openEnd(curTo), active.length);
3406
+ }
3407
+ else if (curTo > pos) {
3408
+ iterator.span(pos, curTo, cursor.active, openRanges);
3409
+ openRanges = cursor.openEnd(curTo);
3410
+ }
3411
+ if (cursor.to > to)
3412
+ return openRanges + (cursor.point && cursor.to > to ? 1 : 0);
3413
+ pos = cursor.to;
3414
+ cursor.next();
3415
+ }
3416
+ }
3417
+ /**
3418
+ Create a range set for the given range or array of ranges. By
3419
+ default, this expects the ranges to be _sorted_ (by start
3420
+ position and, if two start at the same position,
3421
+ `value.startSide`). You can pass `true` as second argument to
3422
+ cause the method to sort them.
3423
+ */
3424
+ static of(ranges, sort = false) {
3425
+ let build = new RangeSetBuilder();
3426
+ for (let range of ranges instanceof Range ? [ranges] : sort ? lazySort(ranges) : ranges)
3427
+ build.add(range.from, range.to, range.value);
3428
+ return build.finish();
3429
+ }
3430
+ /**
3431
+ Join an array of range sets into a single set.
3432
+ */
3433
+ static join(sets) {
3434
+ if (!sets.length)
3435
+ return RangeSet.empty;
3436
+ let result = last(sets);
3437
+ for (let i = sets.length - 2; i >= 0; i--) {
3438
+ for (let layer = sets[i]; layer != RangeSet.empty; layer = layer.nextLayer)
3439
+ result = new RangeSet(layer.chunkPos, layer.chunk, result, Math.max(layer.maxPoint, result.maxPoint));
3440
+ }
3441
+ return result;
3442
+ }
3443
+ }
3444
+ /**
3445
+ The empty set of ranges.
3446
+ */
3447
+ RangeSet.empty = /*@__PURE__*/new RangeSet([], [], null, -1);
3448
+ function last(arr) { return arr[arr.length - 1]; }
3449
+ function lazySort(ranges) {
3450
+ if (ranges.length > 1)
3451
+ for (let prev = ranges[0], i = 1; i < ranges.length; i++) {
3452
+ let cur = ranges[i];
3453
+ if (cmpRange(prev, cur) > 0)
3454
+ return ranges.slice().sort(cmpRange);
3455
+ prev = cur;
3456
+ }
3457
+ return ranges;
3458
+ }
3459
+ RangeSet.empty.nextLayer = RangeSet.empty;
3460
+ /**
3461
+ A range set builder is a data structure that helps build up a
3462
+ [range set](https://codemirror.net/6/docs/ref/#state.RangeSet) directly, without first allocating
3463
+ an array of [`Range`](https://codemirror.net/6/docs/ref/#state.Range) objects.
3464
+ */
3465
+ class RangeSetBuilder {
3466
+ finishChunk(newArrays) {
3467
+ this.chunks.push(new Chunk(this.from, this.to, this.value, this.maxPoint));
3468
+ this.chunkPos.push(this.chunkStart);
3469
+ this.chunkStart = -1;
3470
+ this.setMaxPoint = Math.max(this.setMaxPoint, this.maxPoint);
3471
+ this.maxPoint = -1;
3472
+ if (newArrays) {
3473
+ this.from = [];
3474
+ this.to = [];
3475
+ this.value = [];
3476
+ }
3477
+ }
3478
+ /**
3479
+ Create an empty builder.
3480
+ */
3481
+ constructor() {
3482
+ this.chunks = [];
3483
+ this.chunkPos = [];
3484
+ this.chunkStart = -1;
3485
+ this.last = null;
3486
+ this.lastFrom = -1000000000 /* C.Far */;
3487
+ this.lastTo = -1000000000 /* C.Far */;
3488
+ this.from = [];
3489
+ this.to = [];
3490
+ this.value = [];
3491
+ this.maxPoint = -1;
3492
+ this.setMaxPoint = -1;
3493
+ this.nextLayer = null;
3494
+ }
3495
+ /**
3496
+ Add a range. Ranges should be added in sorted (by `from` and
3497
+ `value.startSide`) order.
3498
+ */
3499
+ add(from, to, value) { this.addRange(from, to, value, true); }
3500
+ /**
3501
+ @internal
3502
+ */
3503
+ addRange(from, to, value, strict) {
3504
+ if (!this.addInner(from, to, value, strict))
3505
+ (this.nextLayer || (this.nextLayer = new RangeSetBuilder)).addRange(from, to, value, strict);
3506
+ }
3507
+ /**
3508
+ @internal
3509
+ */
3510
+ addInner(from, to, value, strict) {
3511
+ let diff = from - this.lastTo || value.startSide - this.last.endSide;
3512
+ if (strict && diff <= 0 && (from - this.lastFrom || value.startSide - this.last.startSide) < 0)
3513
+ throw new Error("Ranges must be added sorted by `from` position and `startSide`");
3514
+ if (diff < 0)
3515
+ return false;
3516
+ if (this.from.length == 250 /* C.ChunkSize */)
3517
+ this.finishChunk(true);
3518
+ if (this.chunkStart < 0)
3519
+ this.chunkStart = from;
3520
+ this.from.push(from - this.chunkStart);
3521
+ this.to.push(to - this.chunkStart);
3522
+ this.last = value;
3523
+ this.lastFrom = from;
3524
+ this.lastTo = to;
3525
+ this.value.push(value);
3526
+ if (value.point)
3527
+ this.maxPoint = Math.max(this.maxPoint, to - from);
3528
+ return true;
3529
+ }
3530
+ /**
3531
+ @internal
3532
+ */
3533
+ addChunk(from, chunk) {
3534
+ if ((from - this.lastTo || chunk.value[0].startSide - this.last.endSide) < 0)
3535
+ return false;
3536
+ if (this.from.length)
3537
+ this.finishChunk(true);
3538
+ this.setMaxPoint = Math.max(this.setMaxPoint, chunk.maxPoint);
3539
+ this.chunks.push(chunk);
3540
+ this.chunkPos.push(from);
3541
+ let last = chunk.value.length - 1;
3542
+ this.last = chunk.value[last];
3543
+ this.lastFrom = chunk.from[last] + from;
3544
+ this.lastTo = chunk.to[last] + from;
3545
+ return true;
3546
+ }
3547
+ /**
3548
+ Finish the range set. Returns the new set. The builder can't be
3549
+ used anymore after this has been called.
3550
+ */
3551
+ finish() { return this.finishInner(RangeSet.empty); }
3552
+ /**
3553
+ @internal
3554
+ */
3555
+ finishInner(next) {
3556
+ if (this.from.length)
3557
+ this.finishChunk(false);
3558
+ if (this.chunks.length == 0)
3559
+ return next;
3560
+ let result = RangeSet.create(this.chunkPos, this.chunks, this.nextLayer ? this.nextLayer.finishInner(next) : next, this.setMaxPoint);
3561
+ this.from = null; // Make sure further `add` calls produce errors
3562
+ return result;
3563
+ }
3564
+ }
3565
+ function findSharedChunks(a, b, textDiff) {
3566
+ let inA = new Map();
3567
+ for (let set of a)
3568
+ for (let i = 0; i < set.chunk.length; i++)
3569
+ if (set.chunk[i].maxPoint <= 0)
3570
+ inA.set(set.chunk[i], set.chunkPos[i]);
3571
+ let shared = new Set();
3572
+ for (let set of b)
3573
+ for (let i = 0; i < set.chunk.length; i++) {
3574
+ let known = inA.get(set.chunk[i]);
3575
+ if (known != null && (textDiff ? textDiff.mapPos(known) : known) == set.chunkPos[i] &&
3576
+ !(textDiff === null || textDiff === void 0 ? void 0 : textDiff.touchesRange(known, known + set.chunk[i].length)))
3577
+ shared.add(set.chunk[i]);
3578
+ }
3579
+ return shared;
3580
+ }
3581
+ class LayerCursor {
3582
+ constructor(layer, skip, minPoint, rank = 0) {
3583
+ this.layer = layer;
3584
+ this.skip = skip;
3585
+ this.minPoint = minPoint;
3586
+ this.rank = rank;
3587
+ }
3588
+ get startSide() { return this.value ? this.value.startSide : 0; }
3589
+ get endSide() { return this.value ? this.value.endSide : 0; }
3590
+ goto(pos, side = -1000000000 /* C.Far */) {
3591
+ this.chunkIndex = this.rangeIndex = 0;
3592
+ this.gotoInner(pos, side, false);
3593
+ return this;
3594
+ }
3595
+ gotoInner(pos, side, forward) {
3596
+ while (this.chunkIndex < this.layer.chunk.length) {
3597
+ let next = this.layer.chunk[this.chunkIndex];
3598
+ if (!(this.skip && this.skip.has(next) ||
3599
+ this.layer.chunkEnd(this.chunkIndex) < pos ||
3600
+ next.maxPoint < this.minPoint))
3601
+ break;
3602
+ this.chunkIndex++;
3603
+ forward = false;
3604
+ }
3605
+ if (this.chunkIndex < this.layer.chunk.length) {
3606
+ let rangeIndex = this.layer.chunk[this.chunkIndex].findIndex(pos - this.layer.chunkPos[this.chunkIndex], side, true);
3607
+ if (!forward || this.rangeIndex < rangeIndex)
3608
+ this.setRangeIndex(rangeIndex);
3609
+ }
3610
+ this.next();
3611
+ }
3612
+ forward(pos, side) {
3613
+ if ((this.to - pos || this.endSide - side) < 0)
3614
+ this.gotoInner(pos, side, true);
3615
+ }
3616
+ next() {
3617
+ for (;;) {
3618
+ if (this.chunkIndex == this.layer.chunk.length) {
3619
+ this.from = this.to = 1000000000 /* C.Far */;
3620
+ this.value = null;
3621
+ break;
3622
+ }
3623
+ else {
3624
+ let chunkPos = this.layer.chunkPos[this.chunkIndex], chunk = this.layer.chunk[this.chunkIndex];
3625
+ let from = chunkPos + chunk.from[this.rangeIndex];
3626
+ this.from = from;
3627
+ this.to = chunkPos + chunk.to[this.rangeIndex];
3628
+ this.value = chunk.value[this.rangeIndex];
3629
+ this.setRangeIndex(this.rangeIndex + 1);
3630
+ if (this.minPoint < 0 || this.value.point && this.to - this.from >= this.minPoint)
3631
+ break;
3632
+ }
3633
+ }
3634
+ }
3635
+ setRangeIndex(index) {
3636
+ if (index == this.layer.chunk[this.chunkIndex].value.length) {
3637
+ this.chunkIndex++;
3638
+ if (this.skip) {
3639
+ while (this.chunkIndex < this.layer.chunk.length && this.skip.has(this.layer.chunk[this.chunkIndex]))
3640
+ this.chunkIndex++;
3641
+ }
3642
+ this.rangeIndex = 0;
3643
+ }
3644
+ else {
3645
+ this.rangeIndex = index;
3646
+ }
3647
+ }
3648
+ nextChunk() {
3649
+ this.chunkIndex++;
3650
+ this.rangeIndex = 0;
3651
+ this.next();
3652
+ }
3653
+ compare(other) {
3654
+ return this.from - other.from || this.startSide - other.startSide || this.rank - other.rank ||
3655
+ this.to - other.to || this.endSide - other.endSide;
3656
+ }
3657
+ }
3658
+ class HeapCursor {
3659
+ constructor(heap) {
3660
+ this.heap = heap;
3661
+ }
3662
+ static from(sets, skip = null, minPoint = -1) {
3663
+ let heap = [];
3664
+ for (let i = 0; i < sets.length; i++) {
3665
+ for (let cur = sets[i]; !cur.isEmpty; cur = cur.nextLayer) {
3666
+ if (cur.maxPoint >= minPoint)
3667
+ heap.push(new LayerCursor(cur, skip, minPoint, i));
3668
+ }
3669
+ }
3670
+ return heap.length == 1 ? heap[0] : new HeapCursor(heap);
3671
+ }
3672
+ get startSide() { return this.value ? this.value.startSide : 0; }
3673
+ goto(pos, side = -1000000000 /* C.Far */) {
3674
+ for (let cur of this.heap)
3675
+ cur.goto(pos, side);
3676
+ for (let i = this.heap.length >> 1; i >= 0; i--)
3677
+ heapBubble(this.heap, i);
3678
+ this.next();
3679
+ return this;
3680
+ }
3681
+ forward(pos, side) {
3682
+ for (let cur of this.heap)
3683
+ cur.forward(pos, side);
3684
+ for (let i = this.heap.length >> 1; i >= 0; i--)
3685
+ heapBubble(this.heap, i);
3686
+ if ((this.to - pos || this.value.endSide - side) < 0)
3687
+ this.next();
3688
+ }
3689
+ next() {
3690
+ if (this.heap.length == 0) {
3691
+ this.from = this.to = 1000000000 /* C.Far */;
3692
+ this.value = null;
3693
+ this.rank = -1;
3694
+ }
3695
+ else {
3696
+ let top = this.heap[0];
3697
+ this.from = top.from;
3698
+ this.to = top.to;
3699
+ this.value = top.value;
3700
+ this.rank = top.rank;
3701
+ if (top.value)
3702
+ top.next();
3703
+ heapBubble(this.heap, 0);
3704
+ }
3705
+ }
3706
+ }
3707
+ function heapBubble(heap, index) {
3708
+ for (let cur = heap[index];;) {
3709
+ let childIndex = (index << 1) + 1;
3710
+ if (childIndex >= heap.length)
3711
+ break;
3712
+ let child = heap[childIndex];
3713
+ if (childIndex + 1 < heap.length && child.compare(heap[childIndex + 1]) >= 0) {
3714
+ child = heap[childIndex + 1];
3715
+ childIndex++;
3716
+ }
3717
+ if (cur.compare(child) < 0)
3718
+ break;
3719
+ heap[childIndex] = cur;
3720
+ heap[index] = child;
3721
+ index = childIndex;
3722
+ }
3723
+ }
3724
+ class SpanCursor {
3725
+ constructor(sets, skip, minPoint) {
3726
+ this.minPoint = minPoint;
3727
+ this.active = [];
3728
+ this.activeTo = [];
3729
+ this.activeRank = [];
3730
+ this.minActive = -1;
3731
+ // A currently active point range, if any
3732
+ this.point = null;
3733
+ this.pointFrom = 0;
3734
+ this.pointRank = 0;
3735
+ this.to = -1000000000 /* C.Far */;
3736
+ this.endSide = 0;
3737
+ // The amount of open active ranges at the start of the iterator.
3738
+ // Not including points.
3739
+ this.openStart = -1;
3740
+ this.cursor = HeapCursor.from(sets, skip, minPoint);
3741
+ }
3742
+ goto(pos, side = -1000000000 /* C.Far */) {
3743
+ this.cursor.goto(pos, side);
3744
+ this.active.length = this.activeTo.length = this.activeRank.length = 0;
3745
+ this.minActive = -1;
3746
+ this.to = pos;
3747
+ this.endSide = side;
3748
+ this.openStart = -1;
3749
+ this.next();
3750
+ return this;
3751
+ }
3752
+ forward(pos, side) {
3753
+ while (this.minActive > -1 && (this.activeTo[this.minActive] - pos || this.active[this.minActive].endSide - side) < 0)
3754
+ this.removeActive(this.minActive);
3755
+ this.cursor.forward(pos, side);
3756
+ }
3757
+ removeActive(index) {
3758
+ remove(this.active, index);
3759
+ remove(this.activeTo, index);
3760
+ remove(this.activeRank, index);
3761
+ this.minActive = findMinIndex(this.active, this.activeTo);
3762
+ }
3763
+ addActive(trackOpen) {
3764
+ let i = 0, { value, to, rank } = this.cursor;
3765
+ // Organize active marks by rank first, then by size
3766
+ while (i < this.activeRank.length && (rank - this.activeRank[i] || to - this.activeTo[i]) > 0)
3767
+ i++;
3768
+ insert(this.active, i, value);
3769
+ insert(this.activeTo, i, to);
3770
+ insert(this.activeRank, i, rank);
3771
+ if (trackOpen)
3772
+ insert(trackOpen, i, this.cursor.from);
3773
+ this.minActive = findMinIndex(this.active, this.activeTo);
3774
+ }
3775
+ // After calling this, if `this.point` != null, the next range is a
3776
+ // point. Otherwise, it's a regular range, covered by `this.active`.
3777
+ next() {
3778
+ let from = this.to, wasPoint = this.point;
3779
+ this.point = null;
3780
+ let trackOpen = this.openStart < 0 ? [] : null;
3781
+ for (;;) {
3782
+ let a = this.minActive;
3783
+ if (a > -1 && (this.activeTo[a] - this.cursor.from || this.active[a].endSide - this.cursor.startSide) < 0) {
3784
+ if (this.activeTo[a] > from) {
3785
+ this.to = this.activeTo[a];
3786
+ this.endSide = this.active[a].endSide;
3787
+ break;
3788
+ }
3789
+ this.removeActive(a);
3790
+ if (trackOpen)
3791
+ remove(trackOpen, a);
3792
+ }
3793
+ else if (!this.cursor.value) {
3794
+ this.to = this.endSide = 1000000000 /* C.Far */;
3795
+ break;
3796
+ }
3797
+ else if (this.cursor.from > from) {
3798
+ this.to = this.cursor.from;
3799
+ this.endSide = this.cursor.startSide;
3800
+ break;
3801
+ }
3802
+ else {
3803
+ let nextVal = this.cursor.value;
3804
+ if (!nextVal.point) { // Opening a range
3805
+ this.addActive(trackOpen);
3806
+ this.cursor.next();
3807
+ }
3808
+ else if (wasPoint && this.cursor.to == this.to && this.cursor.from < this.cursor.to) {
3809
+ // Ignore any non-empty points that end precisely at the end of the prev point
3810
+ this.cursor.next();
3811
+ }
3812
+ else { // New point
3813
+ this.point = nextVal;
3814
+ this.pointFrom = this.cursor.from;
3815
+ this.pointRank = this.cursor.rank;
3816
+ this.to = this.cursor.to;
3817
+ this.endSide = nextVal.endSide;
3818
+ this.cursor.next();
3819
+ this.forward(this.to, this.endSide);
3820
+ break;
3821
+ }
3822
+ }
3823
+ }
3824
+ if (trackOpen) {
3825
+ this.openStart = 0;
3826
+ for (let i = trackOpen.length - 1; i >= 0 && trackOpen[i] < from; i--)
3827
+ this.openStart++;
3828
+ }
3829
+ }
3830
+ activeForPoint(to) {
3831
+ if (!this.active.length)
3832
+ return this.active;
3833
+ let active = [];
3834
+ for (let i = this.active.length - 1; i >= 0; i--) {
3835
+ if (this.activeRank[i] < this.pointRank)
3836
+ break;
3837
+ if (this.activeTo[i] > to || this.activeTo[i] == to && this.active[i].endSide >= this.point.endSide)
3838
+ active.push(this.active[i]);
3839
+ }
3840
+ return active.reverse();
3841
+ }
3842
+ openEnd(to) {
3843
+ let open = 0;
3844
+ for (let i = this.activeTo.length - 1; i >= 0 && this.activeTo[i] > to; i--)
3845
+ open++;
3846
+ return open;
3847
+ }
3848
+ }
3849
+ function compare(a, startA, b, startB, length, comparator) {
3850
+ a.goto(startA);
3851
+ b.goto(startB);
3852
+ let endB = startB + length;
3853
+ let pos = startB, dPos = startB - startA;
3854
+ let bounds = !!comparator.boundChange;
3855
+ for (let boundChange = false;;) {
3856
+ let dEnd = (a.to + dPos) - b.to, diff = dEnd || a.endSide - b.endSide;
3857
+ let end = diff < 0 ? a.to + dPos : b.to, clipEnd = Math.min(end, endB);
3858
+ let point = a.point || b.point;
3859
+ if (point) {
3860
+ if (!(a.point && b.point && cmpVal(a.point, b.point) &&
3861
+ sameValues(a.activeForPoint(a.to), b.activeForPoint(b.to))))
3862
+ comparator.comparePoint(pos, clipEnd, a.point, b.point);
3863
+ boundChange = false;
3864
+ }
3865
+ else {
3866
+ if (boundChange)
3867
+ comparator.boundChange(pos);
3868
+ if (clipEnd > pos && !sameValues(a.active, b.active))
3869
+ comparator.compareRange(pos, clipEnd, a.active, b.active);
3870
+ if (bounds && clipEnd < endB && (dEnd || a.openEnd(end) != b.openEnd(end)))
3871
+ boundChange = true;
3872
+ }
3873
+ if (end > endB)
3874
+ break;
3875
+ pos = end;
3876
+ if (diff <= 0)
3877
+ a.next();
3878
+ if (diff >= 0)
3879
+ b.next();
3880
+ }
3881
+ }
3882
+ function sameValues(a, b) {
3883
+ if (a.length != b.length)
3884
+ return false;
3885
+ for (let i = 0; i < a.length; i++)
3886
+ if (a[i] != b[i] && !cmpVal(a[i], b[i]))
3887
+ return false;
3888
+ return true;
3889
+ }
3890
+ function remove(array, index) {
3891
+ for (let i = index, e = array.length - 1; i < e; i++)
3892
+ array[i] = array[i + 1];
3893
+ array.pop();
3894
+ }
3895
+ function insert(array, index, value) {
3896
+ for (let i = array.length - 1; i >= index; i--)
3897
+ array[i + 1] = array[i];
3898
+ array[index] = value;
3899
+ }
3900
+ function findMinIndex(value, array) {
3901
+ let found = -1, foundPos = 1000000000 /* C.Far */;
3902
+ for (let i = 0; i < array.length; i++)
3903
+ if ((array[i] - foundPos || value[i].endSide - value[found].endSide) < 0) {
3904
+ found = i;
3905
+ foundPos = array[i];
3906
+ }
3907
+ return found;
3908
+ }
3909
+
3910
+ /**
3911
+ Count the column position at the given offset into the string,
3912
+ taking extending characters and tab size into account.
3913
+ */
3914
+ function countColumn(string, tabSize, to = string.length) {
3915
+ let n = 0;
3916
+ for (let i = 0; i < to && i < string.length;) {
3917
+ if (string.charCodeAt(i) == 9) {
3918
+ n += tabSize - (n % tabSize);
3919
+ i++;
3920
+ }
3921
+ else {
3922
+ n++;
3923
+ i = findClusterBreak(string, i);
3924
+ }
3925
+ }
3926
+ return n;
3927
+ }
3928
+ /**
3929
+ Find the offset that corresponds to the given column position in a
3930
+ string, taking extending characters and tab size into account. By
3931
+ default, the string length is returned when it is too short to
3932
+ reach the column. Pass `strict` true to make it return -1 in that
3933
+ situation.
3934
+ */
3935
+ function findColumn(string, col, tabSize, strict) {
3936
+ for (let i = 0, n = 0;;) {
3937
+ if (n >= col)
3938
+ return i;
3939
+ if (i == string.length)
3940
+ break;
3941
+ n += string.charCodeAt(i) == 9 ? tabSize - (n % tabSize) : 1;
3942
+ i = findClusterBreak(string, i);
3943
+ }
3944
+ return strict === true ? -1 : string.length;
3945
+ }
3946
+
3947
+ export { Annotation, AnnotationType, ChangeDesc, ChangeSet, CharCategory, Compartment, EditorSelection, EditorState, Facet, Line, MapMode, Prec, Range, RangeSet, RangeSetBuilder, RangeValue, SelectionRange, StateEffect, StateEffectType, StateField, Text, Transaction, codePointAt, codePointSize, combineConfig, countColumn, findClusterBreak, findColumn, fromCodePoint };