@progressive-development/pd-content 1.0.3 → 1.1.1

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