1import { findClusterBreak as findClusterBreak$1 } from '@marijn/find-cluster-break';
2
3/**
4The data structure for documents. @nonabstract
5*/
6class 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.
134class 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).
217class 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}
353Text.empty = /*@__PURE__*/new TextLeaf([""], 0);
354function textLength(text) {
355 let length = -1;
356 for (let line of text)
357 length += line.length + 1;
358 return length;
359}
360function 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}
379function sliceText(text, from, to) {
380 return appendText(text, [""], from, to);
381}
382class 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}
450class 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}
485class 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}
519if (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/**
525This type describes a line in the document. It is created
526on-demand when lines are [queried](https://codemirror.net/6/docs/ref/#state.Text.lineAt).
527*/
528class 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}
560function 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/**
566Returns a next grapheme cluster break _after_ (not equal to)
567`pos`, if `forward` is true, or before otherwise. Returns `pos`
568itself if no further cluster break is available in the string.
569Moves across surrogate pairs, extending characters (when
570`includeExtending` is true), characters joined with zero-width
571joiners, and flag emoji.
572*/
573function findClusterBreak(str, pos, forward = true, includeExtending = true) {
574 return findClusterBreak$1(str, pos, forward, includeExtending);
575}
576function surrogateLow(ch) { return ch >= 0xDC00 && ch < 0xE000; }
577function surrogateHigh(ch) { return ch >= 0xD800 && ch < 0xDC00; }
578/**
579Find 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)
581string method).
582*/
583function 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/**
593Given a Unicode codepoint, return the JavaScript string that
594respresents it (like
595[`String.fromCodePoint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCodePoint)).
596*/
597function fromCodePoint(code) {
598 if (code <= 0xffff)
599 return String.fromCharCode(code);
600 code -= 0x10000;
601 return String.fromCharCode((code >> 10) + 0xd800, (code & 1023) + 0xdc00);
602}
603/**
604The amount of positions a character takes up in a JavaScript string.
605*/
606function codePointSize(code) { return code < 0x10000 ? 1 : 2; }
607
608const DefaultSplit = /\r\n?|\n/;
609/**
610Distinguishes different ways in which positions can be mapped.
611*/
612var MapMode = /*@__PURE__*/(function (MapMode) {
613 /**
614 Map a position to a valid new position, even when its context
615 was deleted.
616 */
617 MapMode[MapMode["Simple"] = 0] = "Simple";
618 /**
619 Return null if deletion happens across the position.
620 */
621 MapMode[MapMode["TrackDel"] = 1] = "TrackDel";
622 /**
623 Return null if the character _before_ the position is deleted.
624 */
625 MapMode[MapMode["TrackBefore"] = 2] = "TrackBefore";
626 /**
627 Return null if the character _after_ the position is deleted.
628 */
629 MapMode[MapMode["TrackAfter"] = 3] = "TrackAfter";
630return MapMode})(MapMode || (MapMode = {}));
631/**
632A change description is a variant of [change set](https://codemirror.net/6/docs/ref/#state.ChangeSet)
633that doesn't store the inserted text. As such, it can't be
634applied, but is cheaper to store and manipulate.
635*/
636class ChangeDesc {
637 // Sections are encoded as pairs of integers. The first is the
638 // length in the current document, and the second is -1 for
639 // unaffected sections, and the length of the replacement content
640 // otherwise. So an insertion would be (0, n>0), a deletion (n>0,
641 // 0), and a replacement two positive numbers.
642 /**
643 @internal
644 */
645 constructor(
646 /**
647 @internal
648 */
649 sections) {
650 this.sections = sections;
651 }
652 /**
653 The length of the document before the change.
654 */
655 get length() {
656 let result = 0;
657 for (let i = 0; i < this.sections.length; i += 2)
658 result += this.sections[i];
659 return result;
660 }
661 /**
662 The length of the document after the change.
663 */
664 get newLength() {
665 let result = 0;
666 for (let i = 0; i < this.sections.length; i += 2) {
667 let ins = this.sections[i + 1];
668 result += ins < 0 ? this.sections[i] : ins;
669 }
670 return result;
671 }
672 /**
673 False when there are actual changes in this set.
674 */
675 get empty() { return this.sections.length == 0 || this.sections.length == 2 && this.sections[1] < 0; }
676 /**
677 Iterate over the unchanged parts left by these changes. `posA`
678 provides the position of the range in the old document, `posB`
679 the new position in the changed document.
680 */
681 iterGaps(f) {
682 for (let i = 0, posA = 0, posB = 0; i < this.sections.length;) {
683 let len = this.sections[i++], ins = this.sections[i++];
684 if (ins < 0) {
685 f(posA, posB, len);
686 posB += len;
687 }
688 else {
689 posB += ins;
690 }
691 posA += len;
692 }
693 }
694 /**
695 Iterate over the ranges changed by these changes. (See
696 [`ChangeSet.iterChanges`](https://codemirror.net/6/docs/ref/#state.ChangeSet.iterChanges) for a
697 variant that also provides you with the inserted text.)
698 `fromA`/`toA` provides the extent of the change in the starting
699 document, `fromB`/`toB` the extent of the replacement in the
700 changed document.
701
702 When `individual` is true, adjacent changes (which are kept
703 separate for [position mapping](https://codemirror.net/6/docs/ref/#state.ChangeDesc.mapPos)) are
704 reported separately.
705 */
706 iterChangedRanges(f, individual = false) {
707 iterChanges(this, f, individual);
708 }
709 /**
710 Get a description of the inverted form of these changes.
711 */
712 get invertedDesc() {
713 let sections = [];
714 for (let i = 0; i < this.sections.length;) {
715 let len = this.sections[i++], ins = this.sections[i++];
716 if (ins < 0)
717 sections.push(len, ins);
718 else
719 sections.push(ins, len);
720 }
721 return new ChangeDesc(sections);
722 }
723 /**
724 Compute the combined effect of applying another set of changes
725 after this one. The length of the document after this set should
726 match the length before `other`.
727 */
728 composeDesc(other) { return this.empty ? other : other.empty ? this : composeSets(this, other); }
729 /**
730 Map this description, which should start with the same document
731 as `other`, over another set of changes, so that it can be
732 applied after it. When `before` is true, map as if the changes
733 in `this` happened before the ones in `other`.
734 */
735 mapDesc(other, before = false) { return other.empty ? this : mapSet(this, other, before); }
736 mapPos(pos, assoc = -1, mode = MapMode.Simple) {
737 let posA = 0, posB = 0;
738 for (let i = 0; i < this.sections.length;) {
739 let len = this.sections[i++], ins = this.sections[i++], endA = posA + len;
740 if (ins < 0) {
741 if (endA > pos)
742 return posB + (pos - posA);
743 posB += len;
744 }
745 else {
746 if (mode != MapMode.Simple && endA >= pos &&
747 (mode == MapMode.TrackDel && posA < pos && endA > pos ||
748 mode == MapMode.TrackBefore && posA < pos ||
749 mode == MapMode.TrackAfter && endA > pos))
750 return null;
751 if (endA > pos || endA == pos && assoc < 0 && !len)
752 return pos == posA || assoc < 0 ? posB : posB + ins;
753 posB += ins;
754 }
755 posA = endA;
756 }
757 if (pos > posA)
758 throw new RangeError(`Position ${pos} is out of range for changeset of length ${posA}`);
759 return posB;
760 }
761 /**
762 Check whether these changes touch a given range. When one of the
763 changes entirely covers the range, the string `"cover"` is
764 returned.
765 */
766 touchesRange(from, to = from) {
767 for (let i = 0, pos = 0; i < this.sections.length && pos <= to;) {
768 let len = this.sections[i++], ins = this.sections[i++], end = pos + len;
769 if (ins >= 0 && pos <= to && end >= from)
770 return pos < from && end > to ? "cover" : true;
771 pos = end;
772 }
773 return false;
774 }
775 /**
776 @internal
777 */
778 toString() {
779 let result = "";
780 for (let i = 0; i < this.sections.length;) {
781 let len = this.sections[i++], ins = this.sections[i++];
782 result += (result ? " " : "") + len + (ins >= 0 ? ":" + ins : "");
783 }
784 return result;
785 }
786 /**
787 Serialize this change desc to a JSON-representable value.
788 */
789 toJSON() { return this.sections; }
790 /**
791 Create a change desc from its JSON representation (as produced
792 by [`toJSON`](https://codemirror.net/6/docs/ref/#state.ChangeDesc.toJSON).
793 */
794 static fromJSON(json) {
795 if (!Array.isArray(json) || json.length % 2 || json.some(a => typeof a != "number"))
796 throw new RangeError("Invalid JSON representation of ChangeDesc");
797 return new ChangeDesc(json);
798 }
799 /**
800 @internal
801 */
802 static create(sections) { return new ChangeDesc(sections); }
803}
804/**
805A change set represents a group of modifications to a document. It
806stores the document length, and can only be applied to documents
807with exactly that length.
808*/
809class ChangeSet extends ChangeDesc {
810 constructor(sections,
811 /**
812 @internal
813 */
814 inserted) {
815 super(sections);
816 this.inserted = inserted;
817 }
818 /**
819 Apply the changes to a document, returning the modified
820 document.
821 */
822 apply(doc) {
823 if (this.length != doc.length)
824 throw new RangeError("Applying change set to a document with the wrong length");
825 iterChanges(this, (fromA, toA, fromB, _toB, text) => doc = doc.replace(fromB, fromB + (toA - fromA), text), false);
826 return doc;
827 }
828 mapDesc(other, before = false) { return mapSet(this, other, before, true); }
829 /**
830 Given the document as it existed _before_ the changes, return a
831 change set that represents the inverse of this set, which could
832 be used to go from the document created by the changes back to
833 the document as it existed before the changes.
834 */
835 invert(doc) {
836 let sections = this.sections.slice(), inserted = [];
837 for (let i = 0, pos = 0; i < sections.length; i += 2) {
838 let len = sections[i], ins = sections[i + 1];
839 if (ins >= 0) {
840 sections[i] = ins;
841 sections[i + 1] = len;
842 let index = i >> 1;
843 while (inserted.length < index)
844 inserted.push(Text.empty);
845 inserted.push(len ? doc.slice(pos, pos + len) : Text.empty);
846 }
847 pos += len;
848 }
849 return new ChangeSet(sections, inserted);
850 }
851 /**
852 Combine two subsequent change sets into a single set. `other`
853 must start in the document produced by `this`. If `this` goes
854 `docA` → `docB` and `other` represents `docB` → `docC`, the
855 returned value will represent the change `docA` → `docC`.
856 */
857 compose(other) { return this.empty ? other : other.empty ? this : composeSets(this, other, true); }
858 /**
859 Given another change set starting in the same document, maps this
860 change set over the other, producing a new change set that can be
861 applied to the document produced by applying `other`. When
862 `before` is `true`, order changes as if `this` comes before
863 `other`, otherwise (the default) treat `other` as coming first.
864
865 Given two changes `A` and `B`, `A.compose(B.map(A))` and
866 `B.compose(A.map(B, true))` will produce the same document. This
867 provides a basic form of [operational
868 transformation](https://en.wikipedia.org/wiki/Operational_transformation),
869 and can be used for collaborative editing.
870 */
871 map(other, before = false) { return other.empty ? this : mapSet(this, other, before, true); }
872 /**
873 Iterate over the changed ranges in the document, calling `f` for
874 each, with the range in the original document (`fromA`-`toA`)
875 and the range that replaces it in the new document
876 (`fromB`-`toB`).
877
878 When `individual` is true, adjacent changes are reported
879 separately.
880 */
881 iterChanges(f, individual = false) {
882 iterChanges(this, f, individual);
883 }
884 /**
885 Get a [change description](https://codemirror.net/6/docs/ref/#state.ChangeDesc) for this change
886 set.
887 */
888 get desc() { return ChangeDesc.create(this.sections); }
889 /**
890 @internal
891 */
892 filter(ranges) {
893 let resultSections = [], resultInserted = [], filteredSections = [];
894 let iter = new SectionIter(this);
895 done: for (let i = 0, pos = 0;;) {
896 let next = i == ranges.length ? 1e9 : ranges[i++];
897 while (pos < next || pos == next && iter.len == 0) {
898 if (iter.done)
899 break done;
900 let len = Math.min(iter.len, next - pos);
901 addSection(filteredSections, len, -1);
902 let ins = iter.ins == -1 ? -1 : iter.off == 0 ? iter.ins : 0;
903 addSection(resultSections, len, ins);
904 if (ins > 0)
905 addInsert(resultInserted, resultSections, iter.text);
906 iter.forward(len);
907 pos += len;
908 }
909 let end = ranges[i++];
910 while (pos < end) {
911 if (iter.done)
912 break done;
913 let len = Math.min(iter.len, end - pos);
914 addSection(resultSections, len, -1);
915 addSection(filteredSections, len, iter.ins == -1 ? -1 : iter.off == 0 ? iter.ins : 0);
916 iter.forward(len);
917 pos += len;
918 }
919 }
920 return { changes: new ChangeSet(resultSections, resultInserted),
921 filtered: ChangeDesc.create(filteredSections) };
922 }
923 /**
924 Serialize this change set to a JSON-representable value.
925 */
926 toJSON() {
927 let parts = [];
928 for (let i = 0; i < this.sections.length; i += 2) {
929 let len = this.sections[i], ins = this.sections[i + 1];
930 if (ins < 0)
931 parts.push(len);
932 else if (ins == 0)
933 parts.push([len]);
934 else
935 parts.push([len].concat(this.inserted[i >> 1].toJSON()));
936 }
937 return parts;
938 }
939 /**
940 Create a change set for the given changes, for a document of the
941 given length, using `lineSep` as line separator.
942 */
943 static of(changes, length, lineSep) {
944 let sections = [], inserted = [], pos = 0;
945 let total = null;
946 function flush(force = false) {
947 if (!force && !sections.length)
948 return;
949 if (pos < length)
950 addSection(sections, length - pos, -1);
951 let set = new ChangeSet(sections, inserted);
952 total = total ? total.compose(set.map(total)) : set;
953 sections = [];
954 inserted = [];
955 pos = 0;
956 }
957 function process(spec) {
958 if (Array.isArray(spec)) {
959 for (let sub of spec)
960 process(sub);
961 }
962 else if (spec instanceof ChangeSet) {
963 if (spec.length != length)
964 throw new RangeError(`Mismatched change set length (got ${spec.length}, expected ${length})`);
965 flush();
966 total = total ? total.compose(spec.map(total)) : spec;
967 }
968 else {
969 let { from, to = from, insert } = spec;
970 if (from > to || from < 0 || to > length)
971 throw new RangeError(`Invalid change range ${from} to ${to} (in doc of length ${length})`);
972 let insText = !insert ? Text.empty : typeof insert == "string" ? Text.of(insert.split(lineSep || DefaultSplit)) : insert;
973 let insLen = insText.length;
974 if (from == to && insLen == 0)
975 return;
976 if (from < pos)
977 flush();
978 if (from > pos)
979 addSection(sections, from - pos, -1);
980 addSection(sections, to - from, insLen);
981 addInsert(inserted, sections, insText);
982 pos = to;
983 }
984 }
985 process(changes);
986 flush(!total);
987 return total;
988 }
989 /**
990 Create an empty changeset of the given length.
991 */
992 static empty(length) {
993 return new ChangeSet(length ? [length, -1] : [], []);
994 }
995 /**
996 Create a changeset from its JSON representation (as produced by
997 [`toJSON`](https://codemirror.net/6/docs/ref/#state.ChangeSet.toJSON).
998 */
999 static fromJSON(json) {
1000 if (!Array.isArray(json))
1001 throw new RangeError("Invalid JSON representation of ChangeSet");
1002 let sections = [], inserted = [];
1003 for (let i = 0; i < json.length; i++) {
1004 let part = json[i];
1005 if (typeof part == "number") {
1006 sections.push(part, -1);
1007 }
1008 else if (!Array.isArray(part) || typeof part[0] != "number" || part.some((e, i) => i && typeof e != "string")) {
1009 throw new RangeError("Invalid JSON representation of ChangeSet");
1010 }
1011 else if (part.length == 1) {
1012 sections.push(part[0], 0);
1013 }
1014 else {
1015 while (inserted.length < i)
1016 inserted.push(Text.empty);
1017 inserted[i] = Text.of(part.slice(1));
1018 sections.push(part[0], inserted[i].length);
1019 }
1020 }
1021 return new ChangeSet(sections, inserted);
1022 }
1023 /**
1024 @internal
1025 */
1026 static createSet(sections, inserted) {
1027 return new ChangeSet(sections, inserted);
1028 }
1029}
1030function addSection(sections, len, ins, forceJoin = false) {
1031 if (len == 0 && ins <= 0)
1032 return;
1033 let last = sections.length - 2;
1034 if (last >= 0 && ins <= 0 && ins == sections[last + 1])
1035 sections[last] += len;
1036 else if (last >= 0 && len == 0 && sections[last] == 0)
1037 sections[last + 1] += ins;
1038 else if (forceJoin) {
1039 sections[last] += len;
1040 sections[last + 1] += ins;
1041 }
1042 else
1043 sections.push(len, ins);
1044}
1045function addInsert(values, sections, value) {
1046 if (value.length == 0)
1047 return;
1048 let index = (sections.length - 2) >> 1;
1049 if (index < values.length) {
1050 values[values.length - 1] = values[values.length - 1].append(value);
1051 }
1052 else {
1053 while (values.length < index)
1054 values.push(Text.empty);
1055 values.push(value);
1056 }
1057}
1058function iterChanges(desc, f, individual) {
1059 let inserted = desc.inserted;
1060 for (let posA = 0, posB = 0, i = 0; i < desc.sections.length;) {
1061 let len = desc.sections[i++], ins = desc.sections[i++];
1062 if (ins < 0) {
1063 posA += len;
1064 posB += len;
1065 }
1066 else {
1067 let endA = posA, endB = posB, text = Text.empty;
1068 for (;;) {
1069 endA += len;
1070 endB += ins;
1071 if (ins && inserted)
1072 text = text.append(inserted[(i - 2) >> 1]);
1073 if (individual || i == desc.sections.length || desc.sections[i + 1] < 0)
1074 break;
1075 len = desc.sections[i++];
1076 ins = desc.sections[i++];
1077 }
1078 f(posA, endA, posB, endB, text);
1079 posA = endA;
1080 posB = endB;
1081 }
1082 }
1083}
1084function mapSet(setA, setB, before, mkSet = false) {
1085 // Produce a copy of setA that applies to the document after setB
1086 // has been applied (assuming both start at the same document).
1087 let sections = [], insert = mkSet ? [] : null;
1088 let a = new SectionIter(setA), b = new SectionIter(setB);
1089 // Iterate over both sets in parallel. inserted tracks, for changes
1090 // in A that have to be processed piece-by-piece, whether their
1091 // content has been inserted already, and refers to the section
1092 // index.
1093 for (let inserted = -1;;) {
1094 if (a.done && b.len || b.done && a.len) {
1095 throw new Error("Mismatched change set lengths");
1096 }
1097 else if (a.ins == -1 && b.ins == -1) {
1098 // Move across ranges skipped by both sets.
1099 let len = Math.min(a.len, b.len);
1100 addSection(sections, len, -1);
1101 a.forward(len);
1102 b.forward(len);
1103 }
1104 else if (b.ins >= 0 && (a.ins < 0 || inserted == a.i || a.off == 0 && (b.len < a.len || b.len == a.len && !before))) {
1105 // If there's a change in B that comes before the next change in
1106 // A (ordered by start pos, then len, then before flag), skip
1107 // that (and process any changes in A it covers).
1108 let len = b.len;
1109 addSection(sections, b.ins, -1);
1110 while (len) {
1111 let piece = Math.min(a.len, len);
1112 if (a.ins >= 0 && inserted < a.i && a.len <= piece) {
1113 addSection(sections, 0, a.ins);
1114 if (insert)
1115 addInsert(insert, sections, a.text);
1116 inserted = a.i;
1117 }
1118 a.forward(piece);
1119 len -= piece;
1120 }
1121 b.next();
1122 }
1123 else if (a.ins >= 0) {
1124 // Process the part of a change in A up to the start of the next
1125 // non-deletion change in B (if overlapping).
1126 let len = 0, left = a.len;
1127 while (left) {
1128 if (b.ins == -1) {
1129 let piece = Math.min(left, b.len);
1130 len += piece;
1131 left -= piece;
1132 b.forward(piece);
1133 }
1134 else if (b.ins == 0 && b.len < left) {
1135 left -= b.len;
1136 b.next();
1137 }
1138 else {
1139 break;
1140 }
1141 }
1142 addSection(sections, len, inserted < a.i ? a.ins : 0);
1143 if (insert && inserted < a.i)
1144 addInsert(insert, sections, a.text);
1145 inserted = a.i;
1146 a.forward(a.len - left);
1147 }
1148 else if (a.done && b.done) {
1149 return insert ? ChangeSet.createSet(sections, insert) : ChangeDesc.create(sections);
1150 }
1151 else {
1152 throw new Error("Mismatched change set lengths");
1153 }
1154 }
1155}
1156function composeSets(setA, setB, mkSet = false) {
1157 let sections = [];
1158 let insert = mkSet ? [] : null;
1159 let a = new SectionIter(setA), b = new SectionIter(setB);
1160 for (let open = false;;) {
1161 if (a.done && b.done) {
1162 return insert ? ChangeSet.createSet(sections, insert) : ChangeDesc.create(sections);
1163 }
1164 else if (a.ins == 0) { // Deletion in A
1165 addSection(sections, a.len, 0, open);
1166 a.next();
1167 }
1168 else if (b.len == 0 && !b.done) { // Insertion in B
1169 addSection(sections, 0, b.ins, open);
1170 if (insert)
1171 addInsert(insert, sections, b.text);
1172 b.next();
1173 }
1174 else if (a.done || b.done) {
1175 throw new Error("Mismatched change set lengths");
1176 }
1177 else {
1178 let len = Math.min(a.len2, b.len), sectionLen = sections.length;
1179 if (a.ins == -1) {
1180 let insB = b.ins == -1 ? -1 : b.off ? 0 : b.ins;
1181 addSection(sections, len, insB, open);
1182 if (insert && insB)
1183 addInsert(insert, sections, b.text);
1184 }
1185 else if (b.ins == -1) {
1186 addSection(sections, a.off ? 0 : a.len, len, open);
1187 if (insert)
1188 addInsert(insert, sections, a.textBit(len));
1189 }
1190 else {
1191 addSection(sections, a.off ? 0 : a.len, b.off ? 0 : b.ins, open);
1192 if (insert && !b.off)
1193 addInsert(insert, sections, b.text);
1194 }
1195 open = (a.ins > len || b.ins >= 0 && b.len > len) && (open || sections.length > sectionLen);
1196 a.forward2(len);
1197 b.forward(len);
1198 }
1199 }
1200}
1201class SectionIter {
1202 constructor(set) {
1203 this.set = set;
1204 this.i = 0;
1205 this.next();
1206 }
1207 next() {
1208 let { sections } = this.set;
1209 if (this.i < sections.length) {
1210 this.len = sections[this.i++];
1211 this.ins = sections[this.i++];
1212 }
1213 else {
1214 this.len = 0;
1215 this.ins = -2;
1216 }
1217 this.off = 0;
1218 }
1219 get done() { return this.ins == -2; }
1220 get len2() { return this.ins < 0 ? this.len : this.ins; }
1221 get text() {
1222 let { inserted } = this.set, index = (this.i - 2) >> 1;
1223 return index >= inserted.length ? Text.empty : inserted[index];
1224 }
1225 textBit(len) {
1226 let { inserted } = this.set, index = (this.i - 2) >> 1;
1227 return index >= inserted.length && !len ? Text.empty
1228 : inserted[index].slice(this.off, len == null ? undefined : this.off + len);
1229 }
1230 forward(len) {
1231 if (len == this.len)
1232 this.next();
1233 else {
1234 this.len -= len;
1235 this.off += len;
1236 }
1237 }
1238 forward2(len) {
1239 if (this.ins == -1)
1240 this.forward(len);
1241 else if (len == this.ins)
1242 this.next();
1243 else {
1244 this.ins -= len;
1245 this.off += len;
1246 }
1247 }
1248}
1249
1250/**
1251A single selection range. When
1252[`allowMultipleSelections`](https://codemirror.net/6/docs/ref/#state.EditorState^allowMultipleSelections)
1253is enabled, a [selection](https://codemirror.net/6/docs/ref/#state.EditorSelection) may hold
1254multiple ranges. By default, selections hold exactly one range.
1255*/
1256class SelectionRange {
1257 constructor(
1258 /**
1259 The lower boundary of the range.
1260 */
1261 from,
1262 /**
1263 The upper boundary of the range.
1264 */
1265 to, flags) {
1266 this.from = from;
1267 this.to = to;
1268 this.flags = flags;
1269 }
1270 /**
1271 The anchor of the range—the side that doesn't move when you
1272 extend it.
1273 */
1274 get anchor() { return this.flags & 32 /* RangeFlag.Inverted */ ? this.to : this.from; }
1275 /**
1276 The head of the range, which is moved when the range is
1277 [extended](https://codemirror.net/6/docs/ref/#state.SelectionRange.extend).
1278 */
1279 get head() { return this.flags & 32 /* RangeFlag.Inverted */ ? this.from : this.to; }
1280 /**
1281 True when `anchor` and `head` are at the same position.
1282 */
1283 get empty() { return this.from == this.to; }
1284 /**
1285 If this is a cursor that is explicitly associated with the
1286 character on one of its sides, this returns the side. -1 means
1287 the character before its position, 1 the character after, and 0
1288 means no association.
1289 */
1290 get assoc() { return this.flags & 8 /* RangeFlag.AssocBefore */ ? -1 : this.flags & 16 /* RangeFlag.AssocAfter */ ? 1 : 0; }
1291 /**
1292 The bidirectional text level associated with this cursor, if
1293 any.
1294 */
1295 get bidiLevel() {
1296 let level = this.flags & 7 /* RangeFlag.BidiLevelMask */;
1297 return level == 7 ? null : level;
1298 }
1299 /**
1300 The goal column (stored vertical offset) associated with a
1301 cursor. This is used to preserve the vertical position when
1302 [moving](https://codemirror.net/6/docs/ref/#view.EditorView.moveVertically) across
1303 lines of different length.
1304 */
1305 get goalColumn() {
1306 let value = this.flags >> 6 /* RangeFlag.GoalColumnOffset */;
1307 return value == 16777215 /* RangeFlag.NoGoalColumn */ ? undefined : value;
1308 }
1309 /**
1310 Map this range through a change, producing a valid range in the
1311 updated document.
1312 */
1313 map(change, assoc = -1) {
1314 let from, to;
1315 if (this.empty) {
1316 from = to = change.mapPos(this.from, assoc);
1317 }
1318 else {
1319 from = change.mapPos(this.from, 1);
1320 to = change.mapPos(this.to, -1);
1321 }
1322 return from == this.from && to == this.to ? this : new SelectionRange(from, to, this.flags);
1323 }
1324 /**
1325 Extend this range to cover at least `from` to `to`.
1326 */
1327 extend(from, to = from) {
1328 if (from <= this.anchor && to >= this.anchor)
1329 return EditorSelection.range(from, to);
1330 let head = Math.abs(from - this.anchor) > Math.abs(to - this.anchor) ? from : to;
1331 return EditorSelection.range(this.anchor, head);
1332 }
1333 /**
1334 Compare this range to another range.
1335 */
1336 eq(other, includeAssoc = false) {
1337 return this.anchor == other.anchor && this.head == other.head &&
1338 (!includeAssoc || !this.empty || this.assoc == other.assoc);
1339 }
1340 /**
1341 Return a JSON-serializable object representing the range.
1342 */
1343 toJSON() { return { anchor: this.anchor, head: this.head }; }
1344 /**
1345 Convert a JSON representation of a range to a `SelectionRange`
1346 instance.
1347 */
1348 static fromJSON(json) {
1349 if (!json || typeof json.anchor != "number" || typeof json.head != "number")
1350 throw new RangeError("Invalid JSON representation for SelectionRange");
1351 return EditorSelection.range(json.anchor, json.head);
1352 }
1353 /**
1354 @internal
1355 */
1356 static create(from, to, flags) {
1357 return new SelectionRange(from, to, flags);
1358 }
1359}
1360/**
1361An editor selection holds one or more selection ranges.
1362*/
1363class EditorSelection {
1364 constructor(
1365 /**
1366 The ranges in the selection, sorted by position. Ranges cannot
1367 overlap (but they may touch, if they aren't empty).
1368 */
1369 ranges,
1370 /**
1371 The index of the _main_ range in the selection (which is
1372 usually the range that was added last).
1373 */
1374 mainIndex) {
1375 this.ranges = ranges;
1376 this.mainIndex = mainIndex;
1377 }
1378 /**
1379 Map a selection through a change. Used to adjust the selection
1380 position for changes.
1381 */
1382 map(change, assoc = -1) {
1383 if (change.empty)
1384 return this;
1385 return EditorSelection.create(this.ranges.map(r => r.map(change, assoc)), this.mainIndex);
1386 }
1387 /**
1388 Compare this selection to another selection. By default, ranges
1389 are compared only by position. When `includeAssoc` is true,
1390 cursor ranges must also have the same
1391 [`assoc`](https://codemirror.net/6/docs/ref/#state.SelectionRange.assoc) value.
1392 */
1393 eq(other, includeAssoc = false) {
1394 if (this.ranges.length != other.ranges.length ||
1395 this.mainIndex != other.mainIndex)
1396 return false;
1397 for (let i = 0; i < this.ranges.length; i++)
1398 if (!this.ranges[i].eq(other.ranges[i], includeAssoc))
1399 return false;
1400 return true;
1401 }
1402 /**
1403 Get the primary selection range. Usually, you should make sure
1404 your code applies to _all_ ranges, by using methods like
1405 [`changeByRange`](https://codemirror.net/6/docs/ref/#state.EditorState.changeByRange).
1406 */
1407 get main() { return this.ranges[this.mainIndex]; }
1408 /**
1409 Make sure the selection only has one range. Returns a selection
1410 holding only the main range from this selection.
1411 */
1412 asSingle() {
1413 return this.ranges.length == 1 ? this : new EditorSelection([this.main], 0);
1414 }
1415 /**
1416 Extend this selection with an extra range.
1417 */
1418 addRange(range, main = true) {
1419 return EditorSelection.create([range].concat(this.ranges), main ? 0 : this.mainIndex + 1);
1420 }
1421 /**
1422 Replace a given range with another range, and then normalize the
1423 selection to merge and sort ranges if necessary.
1424 */
1425 replaceRange(range, which = this.mainIndex) {
1426 let ranges = this.ranges.slice();
1427 ranges[which] = range;
1428 return EditorSelection.create(ranges, this.mainIndex);
1429 }
1430 /**
1431 Convert this selection to an object that can be serialized to
1432 JSON.
1433 */
1434 toJSON() {
1435 return { ranges: this.ranges.map(r => r.toJSON()), main: this.mainIndex };
1436 }
1437 /**
1438 Create a selection from a JSON representation.
1439 */
1440 static fromJSON(json) {
1441 if (!json || !Array.isArray(json.ranges) || typeof json.main != "number" || json.main >= json.ranges.length)
1442 throw new RangeError("Invalid JSON representation for EditorSelection");
1443 return new EditorSelection(json.ranges.map((r) => SelectionRange.fromJSON(r)), json.main);
1444 }
1445 /**
1446 Create a selection holding a single range.
1447 */
1448 static single(anchor, head = anchor) {
1449 return new EditorSelection([EditorSelection.range(anchor, head)], 0);
1450 }
1451 /**
1452 Sort and merge the given set of ranges, creating a valid
1453 selection.
1454 */
1455 static create(ranges, mainIndex = 0) {
1456 if (ranges.length == 0)
1457 throw new RangeError("A selection needs at least one range");
1458 for (let pos = 0, i = 0; i < ranges.length; i++) {
1459 let range = ranges[i];
1460 if (range.empty ? range.from <= pos : range.from < pos)
1461 return EditorSelection.normalized(ranges.slice(), mainIndex);
1462 pos = range.to;
1463 }
1464 return new EditorSelection(ranges, mainIndex);
1465 }
1466 /**
1467 Create a cursor selection range at the given position. You can
1468 safely ignore the optional arguments in most situations.
1469 */
1470 static cursor(pos, assoc = 0, bidiLevel, goalColumn) {
1471 return SelectionRange.create(pos, pos, (assoc == 0 ? 0 : assoc < 0 ? 8 /* RangeFlag.AssocBefore */ : 16 /* RangeFlag.AssocAfter */) |
1472 (bidiLevel == null ? 7 : Math.min(6, bidiLevel)) |
1473 ((goalColumn !== null && goalColumn !== void 0 ? goalColumn : 16777215 /* RangeFlag.NoGoalColumn */) << 6 /* RangeFlag.GoalColumnOffset */));
1474 }
1475 /**
1476 Create a selection range.
1477 */
1478 static range(anchor, head, goalColumn, bidiLevel) {
1479 let flags = ((goalColumn !== null && goalColumn !== void 0 ? goalColumn : 16777215 /* RangeFlag.NoGoalColumn */) << 6 /* RangeFlag.GoalColumnOffset */) |
1480 (bidiLevel == null ? 7 : Math.min(6, bidiLevel));
1481 return head < anchor ? SelectionRange.create(head, anchor, 32 /* RangeFlag.Inverted */ | 16 /* RangeFlag.AssocAfter */ | flags)
1482 : SelectionRange.create(anchor, head, (head > anchor ? 8 /* RangeFlag.AssocBefore */ : 0) | flags);
1483 }
1484 /**
1485 @internal
1486 */
1487 static normalized(ranges, mainIndex = 0) {
1488 let main = ranges[mainIndex];
1489 ranges.sort((a, b) => a.from - b.from);
1490 mainIndex = ranges.indexOf(main);
1491 for (let i = 1; i < ranges.length; i++) {
1492 let range = ranges[i], prev = ranges[i - 1];
1493 if (range.empty ? range.from <= prev.to : range.from < prev.to) {
1494 let from = prev.from, to = Math.max(range.to, prev.to);
1495 if (i <= mainIndex)
1496 mainIndex--;
1497 ranges.splice(--i, 2, range.anchor > range.head ? EditorSelection.range(to, from) : EditorSelection.range(from, to));
1498 }
1499 }
1500 return new EditorSelection(ranges, mainIndex);
1501 }
1502}
1503function checkSelection(selection, docLength) {
1504 for (let range of selection.ranges)
1505 if (range.to > docLength)
1506 throw new RangeError("Selection points outside of document");
1507}
1508
1509let nextID = 0;
1510/**
1511A facet is a labeled value that is associated with an editor
1512state. It takes inputs from any number of extensions, and combines
1513those into a single output value.
1514
1515Examples of uses of facets are the [tab
1516size](https://codemirror.net/6/docs/ref/#state.EditorState^tabSize), [editor
1517attributes](https://codemirror.net/6/docs/ref/#view.EditorView^editorAttributes), and [update
1518listeners](https://codemirror.net/6/docs/ref/#view.EditorView^updateListener).
1519
1520Note that `Facet` instances can be used anywhere where
1521[`FacetReader`](https://codemirror.net/6/docs/ref/#state.FacetReader) is expected.
1522*/
1523class Facet {
1524 constructor(
1525 /**
1526 @internal
1527 */
1528 combine,
1529 /**
1530 @internal
1531 */
1532 compareInput,
1533 /**
1534 @internal
1535 */
1536 compare, isStatic, enables) {
1537 this.combine = combine;
1538 this.compareInput = compareInput;
1539 this.compare = compare;
1540 this.isStatic = isStatic;
1541 /**
1542 @internal
1543 */
1544 this.id = nextID++;
1545 this.default = combine([]);
1546 this.extensions = typeof enables == "function" ? enables(this) : enables;
1547 }
1548 /**
1549 Returns a facet reader for this facet, which can be used to
1550 [read](https://codemirror.net/6/docs/ref/#state.EditorState.facet) it but not to define values for it.
1551 */
1552 get reader() { return this; }
1553 /**
1554 Define a new facet.
1555 */
1556 static define(config = {}) {
1557 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);
1558 }
1559 /**
1560 Returns an extension that adds the given value to this facet.
1561 */
1562 of(value) {
1563 return new FacetProvider([], this, 0 /* Provider.Static */, value);
1564 }
1565 /**
1566 Create an extension that computes a value for the facet from a
1567 state. You must take care to declare the parts of the state that
1568 this value depends on, since your function is only called again
1569 for a new state when one of those parts changed.
1570
1571 In cases where your value depends only on a single field, you'll
1572 want to use the [`from`](https://codemirror.net/6/docs/ref/#state.Facet.from) method instead.
1573 */
1574 compute(deps, get) {
1575 if (this.isStatic)
1576 throw new Error("Can't compute a static facet");
1577 return new FacetProvider(deps, this, 1 /* Provider.Single */, get);
1578 }
1579 /**
1580 Create an extension that computes zero or more values for this
1581 facet from a state.
1582 */
1583 computeN(deps, get) {
1584 if (this.isStatic)
1585 throw new Error("Can't compute a static facet");
1586 return new FacetProvider(deps, this, 2 /* Provider.Multi */, get);
1587 }
1588 from(field, get) {
1589 if (!get)
1590 get = x => x;
1591 return this.compute([field], state => get(state.field(field)));
1592 }
1593}
1594function sameArray(a, b) {
1595 return a == b || a.length == b.length && a.every((e, i) => e === b[i]);
1596}
1597class FacetProvider {
1598 constructor(dependencies, facet, type, value) {
1599 this.dependencies = dependencies;
1600 this.facet = facet;
1601 this.type = type;
1602 this.value = value;
1603 this.id = nextID++;
1604 }
1605 dynamicSlot(addresses) {
1606 var _a;
1607 let getter = this.value;
1608 let compare = this.facet.compareInput;
1609 let id = this.id, idx = addresses[id] >> 1, multi = this.type == 2 /* Provider.Multi */;
1610 let depDoc = false, depSel = false, depAddrs = [];
1611 for (let dep of this.dependencies) {
1612 if (dep == "doc")
1613 depDoc = true;
1614 else if (dep == "selection")
1615 depSel = true;
1616 else if ((((_a = addresses[dep.id]) !== null && _a !== void 0 ? _a : 1) & 1) == 0)
1617 depAddrs.push(addresses[dep.id]);
1618 }
1619 return {
1620 create(state) {
1621 state.values[idx] = getter(state);
1622 return 1 /* SlotStatus.Changed */;
1623 },
1624 update(state, tr) {
1625 if ((depDoc && tr.docChanged) || (depSel && (tr.docChanged || tr.selection)) || ensureAll(state, depAddrs)) {
1626 let newVal = getter(state);
1627 if (multi ? !compareArray(newVal, state.values[idx], compare) : !compare(newVal, state.values[idx])) {
1628 state.values[idx] = newVal;
1629 return 1 /* SlotStatus.Changed */;
1630 }
1631 }
1632 return 0;
1633 },
1634 reconfigure: (state, oldState) => {
1635 let newVal, oldAddr = oldState.config.address[id];
1636 if (oldAddr != null) {
1637 let oldVal = getAddr(oldState, oldAddr);
1638 if (this.dependencies.every(dep => {
1639 return dep instanceof Facet ? oldState.facet(dep) === state.facet(dep) :
1640 dep instanceof StateField ? oldState.field(dep, false) == state.field(dep, false) : true;
1641 }) || (multi ? compareArray(newVal = getter(state), oldVal, compare) : compare(newVal = getter(state), oldVal))) {
1642 state.values[idx] = oldVal;
1643 return 0;
1644 }
1645 }
1646 else {
1647 newVal = getter(state);
1648 }
1649 state.values[idx] = newVal;
1650 return 1 /* SlotStatus.Changed */;
1651 }
1652 };
1653 }
1654}
1655function compareArray(a, b, compare) {
1656 if (a.length != b.length)
1657 return false;
1658 for (let i = 0; i < a.length; i++)
1659 if (!compare(a[i], b[i]))
1660 return false;
1661 return true;
1662}
1663function ensureAll(state, addrs) {
1664 let changed = false;
1665 for (let addr of addrs)
1666 if (ensureAddr(state, addr) & 1 /* SlotStatus.Changed */)
1667 changed = true;
1668 return changed;
1669}
1670function dynamicFacetSlot(addresses, facet, providers) {
1671 let providerAddrs = providers.map(p => addresses[p.id]);
1672 let providerTypes = providers.map(p => p.type);
1673 let dynamic = providerAddrs.filter(p => !(p & 1));
1674 let idx = addresses[facet.id] >> 1;
1675 function get(state) {
1676 let values = [];
1677 for (let i = 0; i < providerAddrs.length; i++) {
1678 let value = getAddr(state, providerAddrs[i]);
1679 if (providerTypes[i] == 2 /* Provider.Multi */)
1680 for (let val of value)
1681 values.push(val);
1682 else
1683 values.push(value);
1684 }
1685 return facet.combine(values);
1686 }
1687 return {
1688 create(state) {
1689 for (let addr of providerAddrs)
1690 ensureAddr(state, addr);
1691 state.values[idx] = get(state);
1692 return 1 /* SlotStatus.Changed */;
1693 },
1694 update(state, tr) {
1695 if (!ensureAll(state, dynamic))
1696 return 0;
1697 let value = get(state);
1698 if (facet.compare(value, state.values[idx]))
1699 return 0;
1700 state.values[idx] = value;
1701 return 1 /* SlotStatus.Changed */;
1702 },
1703 reconfigure(state, oldState) {
1704 let depChanged = ensureAll(state, providerAddrs);
1705 let oldProviders = oldState.config.facets[facet.id], oldValue = oldState.facet(facet);
1706 if (oldProviders && !depChanged && sameArray(providers, oldProviders)) {
1707 state.values[idx] = oldValue;
1708 return 0;
1709 }
1710 let value = get(state);
1711 if (facet.compare(value, oldValue)) {
1712 state.values[idx] = oldValue;
1713 return 0;
1714 }
1715 state.values[idx] = value;
1716 return 1 /* SlotStatus.Changed */;
1717 }
1718 };
1719}
1720const initField = /*@__PURE__*/Facet.define({ static: true });
1721/**
1722Fields can store additional information in an editor state, and
1723keep it in sync with the rest of the state.
1724*/
1725class StateField {
1726 constructor(
1727 /**
1728 @internal
1729 */
1730 id, createF, updateF, compareF,
1731 /**
1732 @internal
1733 */
1734 spec) {
1735 this.id = id;
1736 this.createF = createF;
1737 this.updateF = updateF;
1738 this.compareF = compareF;
1739 this.spec = spec;
1740 /**
1741 @internal
1742 */
1743 this.provides = undefined;
1744 }
1745 /**
1746 Define a state field.
1747 */
1748 static define(config) {
1749 let field = new StateField(nextID++, config.create, config.update, config.compare || ((a, b) => a === b), config);
1750 if (config.provide)
1751 field.provides = config.provide(field);
1752 return field;
1753 }
1754 create(state) {
1755 let init = state.facet(initField).find(i => i.field == this);
1756 return ((init === null || init === void 0 ? void 0 : init.create) || this.createF)(state);
1757 }
1758 /**
1759 @internal
1760 */
1761 slot(addresses) {
1762 let idx = addresses[this.id] >> 1;
1763 return {
1764 create: (state) => {
1765 state.values[idx] = this.create(state);
1766 return 1 /* SlotStatus.Changed */;
1767 },
1768 update: (state, tr) => {
1769 let oldVal = state.values[idx];
1770 let value = this.updateF(oldVal, tr);
1771 if (this.compareF(oldVal, value))
1772 return 0;
1773 state.values[idx] = value;
1774 return 1 /* SlotStatus.Changed */;
1775 },
1776 reconfigure: (state, oldState) => {
1777 if (oldState.config.address[this.id] != null) {
1778 state.values[idx] = oldState.field(this);
1779 return 0;
1780 }
1781 state.values[idx] = this.create(state);
1782 return 1 /* SlotStatus.Changed */;
1783 }
1784 };
1785 }
1786 /**
1787 Returns an extension that enables this field and overrides the
1788 way it is initialized. Can be useful when you need to provide a
1789 non-default starting value for the field.
1790 */
1791 init(create) {
1792 return [this, initField.of({ field: this, create })];
1793 }
1794 /**
1795 State field instances can be used as
1796 [`Extension`](https://codemirror.net/6/docs/ref/#state.Extension) values to enable the field in a
1797 given state.
1798 */
1799 get extension() { return this; }
1800}
1801const Prec_ = { lowest: 4, low: 3, default: 2, high: 1, highest: 0 };
1802function prec(value) {
1803 return (ext) => new PrecExtension(ext, value);
1804}
1805/**
1806By default extensions are registered in the order they are found
1807in the flattened form of nested array that was provided.
1808Individual extension values can be assigned a precedence to
1809override this. Extensions that do not have a precedence set get
1810the precedence of the nearest parent with a precedence, or
1811[`default`](https://codemirror.net/6/docs/ref/#state.Prec.default) if there is no such parent. The
1812final ordering of extensions is determined by first sorting by
1813precedence and then by order within each precedence.
1814*/
1815const Prec = {
1816 /**
1817 The highest precedence level, for extensions that should end up
1818 near the start of the precedence ordering.
1819 */
1820 highest: /*@__PURE__*/prec(Prec_.highest),
1821 /**
1822 A higher-than-default precedence, for extensions that should
1823 come before those with default precedence.
1824 */
1825 high: /*@__PURE__*/prec(Prec_.high),
1826 /**
1827 The default precedence, which is also used for extensions
1828 without an explicit precedence.
1829 */
1830 default: /*@__PURE__*/prec(Prec_.default),
1831 /**
1832 A lower-than-default precedence.
1833 */
1834 low: /*@__PURE__*/prec(Prec_.low),
1835 /**
1836 The lowest precedence level. Meant for things that should end up
1837 near the end of the extension order.
1838 */
1839 lowest: /*@__PURE__*/prec(Prec_.lowest)
1840};
1841class PrecExtension {
1842 constructor(inner, prec) {
1843 this.inner = inner;
1844 this.prec = prec;
1845 }
1846}
1847/**
1848Extension compartments can be used to make a configuration
1849dynamic. By [wrapping](https://codemirror.net/6/docs/ref/#state.Compartment.of) part of your
1850configuration in a compartment, you can later
1851[replace](https://codemirror.net/6/docs/ref/#state.Compartment.reconfigure) that part through a
1852transaction.
1853*/
1854class Compartment {
1855 /**
1856 Create an instance of this compartment to add to your [state
1857 configuration](https://codemirror.net/6/docs/ref/#state.EditorStateConfig.extensions).
1858 */
1859 of(ext) { return new CompartmentInstance(this, ext); }
1860 /**
1861 Create an [effect](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects) that
1862 reconfigures this compartment.
1863 */
1864 reconfigure(content) {
1865 return Compartment.reconfigure.of({ compartment: this, extension: content });
1866 }
1867 /**
1868 Get the current content of the compartment in the state, or
1869 `undefined` if it isn't present.
1870 */
1871 get(state) {
1872 return state.config.compartments.get(this);
1873 }
1874}
1875class CompartmentInstance {
1876 constructor(compartment, inner) {
1877 this.compartment = compartment;
1878 this.inner = inner;
1879 }
1880}
1881class Configuration {
1882 constructor(base, compartments, dynamicSlots, address, staticValues, facets) {
1883 this.base = base;
1884 this.compartments = compartments;
1885 this.dynamicSlots = dynamicSlots;
1886 this.address = address;
1887 this.staticValues = staticValues;
1888 this.facets = facets;
1889 this.statusTemplate = [];
1890 while (this.statusTemplate.length < dynamicSlots.length)
1891 this.statusTemplate.push(0 /* SlotStatus.Unresolved */);
1892 }
1893 staticFacet(facet) {
1894 let addr = this.address[facet.id];
1895 return addr == null ? facet.default : this.staticValues[addr >> 1];
1896 }
1897 static resolve(base, compartments, oldState) {
1898 let fields = [];
1899 let facets = Object.create(null);
1900 let newCompartments = new Map();
1901 for (let ext of flatten(base, compartments, newCompartments)) {
1902 if (ext instanceof StateField)
1903 fields.push(ext);
1904 else
1905 (facets[ext.facet.id] || (facets[ext.facet.id] = [])).push(ext);
1906 }
1907 let address = Object.create(null);
1908 let staticValues = [];
1909 let dynamicSlots = [];
1910 for (let field of fields) {
1911 address[field.id] = dynamicSlots.length << 1;
1912 dynamicSlots.push(a => field.slot(a));
1913 }
1914 let oldFacets = oldState === null || oldState === void 0 ? void 0 : oldState.config.facets;
1915 for (let id in facets) {
1916 let providers = facets[id], facet = providers[0].facet;
1917 let oldProviders = oldFacets && oldFacets[id] || [];
1918 if (providers.every(p => p.type == 0 /* Provider.Static */)) {
1919 address[facet.id] = (staticValues.length << 1) | 1;
1920 if (sameArray(oldProviders, providers)) {
1921 staticValues.push(oldState.facet(facet));
1922 }
1923 else {
1924 let value = facet.combine(providers.map(p => p.value));
1925 staticValues.push(oldState && facet.compare(value, oldState.facet(facet)) ? oldState.facet(facet) : value);
1926 }
1927 }
1928 else {
1929 for (let p of providers) {
1930 if (p.type == 0 /* Provider.Static */) {
1931 address[p.id] = (staticValues.length << 1) | 1;
1932 staticValues.push(p.value);
1933 }
1934 else {
1935 address[p.id] = dynamicSlots.length << 1;
1936 dynamicSlots.push(a => p.dynamicSlot(a));
1937 }
1938 }
1939 address[facet.id] = dynamicSlots.length << 1;
1940 dynamicSlots.push(a => dynamicFacetSlot(a, facet, providers));
1941 }
1942 }
1943 let dynamic = dynamicSlots.map(f => f(address));
1944 return new Configuration(base, newCompartments, dynamic, address, staticValues, facets);
1945 }
1946}
1947function flatten(extension, compartments, newCompartments) {
1948 let result = [[], [], [], [], []];
1949 let seen = new Map();
1950 function inner(ext, prec) {
1951 let known = seen.get(ext);
1952 if (known != null) {
1953 if (known <= prec)
1954 return;
1955 let found = result[known].indexOf(ext);
1956 if (found > -1)
1957 result[known].splice(found, 1);
1958 if (ext instanceof CompartmentInstance)
1959 newCompartments.delete(ext.compartment);
1960 }
1961 seen.set(ext, prec);
1962 if (Array.isArray(ext)) {
1963 for (let e of ext)
1964 inner(e, prec);
1965 }
1966 else if (ext instanceof CompartmentInstance) {
1967 if (newCompartments.has(ext.compartment))
1968 throw new RangeError(`Duplicate use of compartment in extensions`);
1969 let content = compartments.get(ext.compartment) || ext.inner;
1970 newCompartments.set(ext.compartment, content);
1971 inner(content, prec);
1972 }
1973 else if (ext instanceof PrecExtension) {
1974 inner(ext.inner, ext.prec);
1975 }
1976 else if (ext instanceof StateField) {
1977 result[prec].push(ext);
1978 if (ext.provides)
1979 inner(ext.provides, prec);
1980 }
1981 else if (ext instanceof FacetProvider) {
1982 result[prec].push(ext);
1983 if (ext.facet.extensions)
1984 inner(ext.facet.extensions, Prec_.default);
1985 }
1986 else {
1987 let content = ext.extension;
1988 if (!content)
1989 throw new Error(`Unrecognized extension value in extension set (${ext}). This sometimes happens because multiple instances of @codemirror/state are loaded, breaking instanceof checks.`);
1990 inner(content, prec);
1991 }
1992 }
1993 inner(extension, Prec_.default);
1994 return result.reduce((a, b) => a.concat(b));
1995}
1996function ensureAddr(state, addr) {
1997 if (addr & 1)
1998 return 2 /* SlotStatus.Computed */;
1999 let idx = addr >> 1;
2000 let status = state.status[idx];
2001 if (status == 4 /* SlotStatus.Computing */)
2002 throw new Error("Cyclic dependency between fields and/or facets");
2003 if (status & 2 /* SlotStatus.Computed */)
2004 return status;
2005 state.status[idx] = 4 /* SlotStatus.Computing */;
2006 let changed = state.computeSlot(state, state.config.dynamicSlots[idx]);
2007 return state.status[idx] = 2 /* SlotStatus.Computed */ | changed;
2008}
2009function getAddr(state, addr) {
2010 return addr & 1 ? state.config.staticValues[addr >> 1] : state.values[addr >> 1];
2011}
2012
2013const languageData = /*@__PURE__*/Facet.define();
2014const allowMultipleSelections = /*@__PURE__*/Facet.define({
2015 combine: values => values.some(v => v),
2016 static: true
2017});
2018const lineSeparator = /*@__PURE__*/Facet.define({
2019 combine: values => values.length ? values[0] : undefined,
2020 static: true
2021});
2022const changeFilter = /*@__PURE__*/Facet.define();
2023const transactionFilter = /*@__PURE__*/Facet.define();
2024const transactionExtender = /*@__PURE__*/Facet.define();
2025const readOnly = /*@__PURE__*/Facet.define({
2026 combine: values => values.length ? values[0] : false
2027});
2028
2029/**
2030Annotations are tagged values that are used to add metadata to
2031transactions in an extensible way. They should be used to model
2032things that effect the entire transaction (such as its [time
2033stamp](https://codemirror.net/6/docs/ref/#state.Transaction^time) or information about its
2034[origin](https://codemirror.net/6/docs/ref/#state.Transaction^userEvent)). For effects that happen
2035_alongside_ the other changes made by the transaction, [state
2036effects](https://codemirror.net/6/docs/ref/#state.StateEffect) are more appropriate.
2037*/
2038class Annotation {
2039 /**
2040 @internal
2041 */
2042 constructor(
2043 /**
2044 The annotation type.
2045 */
2046 type,
2047 /**
2048 The value of this annotation.
2049 */
2050 value) {
2051 this.type = type;
2052 this.value = value;
2053 }
2054 /**
2055 Define a new type of annotation.
2056 */
2057 static define() { return new AnnotationType(); }
2058}
2059/**
2060Marker that identifies a type of [annotation](https://codemirror.net/6/docs/ref/#state.Annotation).
2061*/
2062class AnnotationType {
2063 /**
2064 Create an instance of this annotation.
2065 */
2066 of(value) { return new Annotation(this, value); }
2067}
2068/**
2069Representation of a type of state effect. Defined with
2070[`StateEffect.define`](https://codemirror.net/6/docs/ref/#state.StateEffect^define).
2071*/
2072class StateEffectType {
2073 /**
2074 @internal
2075 */
2076 constructor(
2077 // The `any` types in these function types are there to work
2078 // around TypeScript issue #37631, where the type guard on
2079 // `StateEffect.is` mysteriously stops working when these properly
2080 // have type `Value`.
2081 /**
2082 @internal
2083 */
2084 map) {
2085 this.map = map;
2086 }
2087 /**
2088 Create a [state effect](https://codemirror.net/6/docs/ref/#state.StateEffect) instance of this
2089 type.
2090 */
2091 of(value) { return new StateEffect(this, value); }
2092}
2093/**
2094State effects can be used to represent additional effects
2095associated with a [transaction](https://codemirror.net/6/docs/ref/#state.Transaction.effects). They
2096are often useful to model changes to custom [state
2097fields](https://codemirror.net/6/docs/ref/#state.StateField), when those changes aren't implicit in
2098document or selection changes.
2099*/
2100class StateEffect {
2101 /**
2102 @internal
2103 */
2104 constructor(
2105 /**
2106 @internal
2107 */
2108 type,
2109 /**
2110 The value of this effect.
2111 */
2112 value) {
2113 this.type = type;
2114 this.value = value;
2115 }
2116 /**
2117 Map this effect through a position mapping. Will return
2118 `undefined` when that ends up deleting the effect.
2119 */
2120 map(mapping) {
2121 let mapped = this.type.map(this.value, mapping);
2122 return mapped === undefined ? undefined : mapped == this.value ? this : new StateEffect(this.type, mapped);
2123 }
2124 /**
2125 Tells you whether this effect object is of a given
2126 [type](https://codemirror.net/6/docs/ref/#state.StateEffectType).
2127 */
2128 is(type) { return this.type == type; }
2129 /**
2130 Define a new effect type. The type parameter indicates the type
2131 of values that his effect holds. It should be a type that
2132 doesn't include `undefined`, since that is used in
2133 [mapping](https://codemirror.net/6/docs/ref/#state.StateEffect.map) to indicate that an effect is
2134 removed.
2135 */
2136 static define(spec = {}) {
2137 return new StateEffectType(spec.map || (v => v));
2138 }
2139 /**
2140 Map an array of effects through a change set.
2141 */
2142 static mapEffects(effects, mapping) {
2143 if (!effects.length)
2144 return effects;
2145 let result = [];
2146 for (let effect of effects) {
2147 let mapped = effect.map(mapping);
2148 if (mapped)
2149 result.push(mapped);
2150 }
2151 return result;
2152 }
2153}
2154/**
2155This effect can be used to reconfigure the root extensions of
2156the editor. Doing this will discard any extensions
2157[appended](https://codemirror.net/6/docs/ref/#state.StateEffect^appendConfig), but does not reset
2158the content of [reconfigured](https://codemirror.net/6/docs/ref/#state.Compartment.reconfigure)
2159compartments.
2160*/
2161StateEffect.reconfigure = /*@__PURE__*/StateEffect.define();
2162/**
2163Append extensions to the top-level configuration of the editor.
2164*/
2165StateEffect.appendConfig = /*@__PURE__*/StateEffect.define();
2166/**
2167Changes to the editor state are grouped into transactions.
2168Typically, a user action creates a single transaction, which may
2169contain any number of document changes, may change the selection,
2170or have other effects. Create a transaction by calling
2171[`EditorState.update`](https://codemirror.net/6/docs/ref/#state.EditorState.update), or immediately
2172dispatch one by calling
2173[`EditorView.dispatch`](https://codemirror.net/6/docs/ref/#view.EditorView.dispatch).
2174*/
2175class Transaction {
2176 constructor(
2177 /**
2178 The state from which the transaction starts.
2179 */
2180 startState,
2181 /**
2182 The document changes made by this transaction.
2183 */
2184 changes,
2185 /**
2186 The selection set by this transaction, or undefined if it
2187 doesn't explicitly set a selection.
2188 */
2189 selection,
2190 /**
2191 The effects added to the transaction.
2192 */
2193 effects,
2194 /**
2195 @internal
2196 */
2197 annotations,
2198 /**
2199 Whether the selection should be scrolled into view after this
2200 transaction is dispatched.
2201 */
2202 scrollIntoView) {
2203 this.startState = startState;
2204 this.changes = changes;
2205 this.selection = selection;
2206 this.effects = effects;
2207 this.annotations = annotations;
2208 this.scrollIntoView = scrollIntoView;
2209 /**
2210 @internal
2211 */
2212 this._doc = null;
2213 /**
2214 @internal
2215 */
2216 this._state = null;
2217 if (selection)
2218 checkSelection(selection, changes.newLength);
2219 if (!annotations.some((a) => a.type == Transaction.time))
2220 this.annotations = annotations.concat(Transaction.time.of(Date.now()));
2221 }
2222 /**
2223 @internal
2224 */
2225 static create(startState, changes, selection, effects, annotations, scrollIntoView) {
2226 return new Transaction(startState, changes, selection, effects, annotations, scrollIntoView);
2227 }
2228 /**
2229 The new document produced by the transaction. Contrary to
2230 [`.state`](https://codemirror.net/6/docs/ref/#state.Transaction.state)`.doc`, accessing this won't
2231 force the entire new state to be computed right away, so it is
2232 recommended that [transaction
2233 filters](https://codemirror.net/6/docs/ref/#state.EditorState^transactionFilter) use this getter
2234 when they need to look at the new document.
2235 */
2236 get newDoc() {
2237 return this._doc || (this._doc = this.changes.apply(this.startState.doc));
2238 }
2239 /**
2240 The new selection produced by the transaction. If
2241 [`this.selection`](https://codemirror.net/6/docs/ref/#state.Transaction.selection) is undefined,
2242 this will [map](https://codemirror.net/6/docs/ref/#state.EditorSelection.map) the start state's
2243 current selection through the changes made by the transaction.
2244 */
2245 get newSelection() {
2246 return this.selection || this.startState.selection.map(this.changes);
2247 }
2248 /**
2249 The new state created by the transaction. Computed on demand
2250 (but retained for subsequent access), so it is recommended not to
2251 access it in [transaction
2252 filters](https://codemirror.net/6/docs/ref/#state.EditorState^transactionFilter) when possible.
2253 */
2254 get state() {
2255 if (!this._state)
2256 this.startState.applyTransaction(this);
2257 return this._state;
2258 }
2259 /**
2260 Get the value of the given annotation type, if any.
2261 */
2262 annotation(type) {
2263 for (let ann of this.annotations)
2264 if (ann.type == type)
2265 return ann.value;
2266 return undefined;
2267 }
2268 /**
2269 Indicates whether the transaction changed the document.
2270 */
2271 get docChanged() { return !this.changes.empty; }
2272 /**
2273 Indicates whether this transaction reconfigures the state
2274 (through a [configuration compartment](https://codemirror.net/6/docs/ref/#state.Compartment) or
2275 with a top-level configuration
2276 [effect](https://codemirror.net/6/docs/ref/#state.StateEffect^reconfigure).
2277 */
2278 get reconfigured() { return this.startState.config != this.state.config; }
2279 /**
2280 Returns true if the transaction has a [user
2281 event](https://codemirror.net/6/docs/ref/#state.Transaction^userEvent) annotation that is equal to
2282 or more specific than `event`. For example, if the transaction
2283 has `"select.pointer"` as user event, `"select"` and
2284 `"select.pointer"` will match it.
2285 */
2286 isUserEvent(event) {
2287 let e = this.annotation(Transaction.userEvent);
2288 return !!(e && (e == event || e.length > event.length && e.slice(0, event.length) == event && e[event.length] == "."));
2289 }
2290}
2291/**
2292Annotation used to store transaction timestamps. Automatically
2293added to every transaction, holding `Date.now()`.
2294*/
2295Transaction.time = /*@__PURE__*/Annotation.define();
2296/**
2297Annotation used to associate a transaction with a user interface
2298event. Holds a string identifying the event, using a
2299dot-separated format to support attaching more specific
2300information. The events used by the core libraries are:
2301
2302 - `"input"` when content is entered
2303 - `"input.type"` for typed input
2304 - `"input.type.compose"` for composition
2305 - `"input.paste"` for pasted input
2306 - `"input.drop"` when adding content with drag-and-drop
2307 - `"input.complete"` when autocompleting
2308 - `"delete"` when the user deletes content
2309 - `"delete.selection"` when deleting the selection
2310 - `"delete.forward"` when deleting forward from the selection
2311 - `"delete.backward"` when deleting backward from the selection
2312 - `"delete.cut"` when cutting to the clipboard
2313 - `"move"` when content is moved
2314 - `"move.drop"` when content is moved within the editor through drag-and-drop
2315 - `"select"` when explicitly changing the selection
2316 - `"select.pointer"` when selecting with a mouse or other pointing device
2317 - `"undo"` and `"redo"` for history actions
2318
2319Use [`isUserEvent`](https://codemirror.net/6/docs/ref/#state.Transaction.isUserEvent) to check
2320whether the annotation matches a given event.
2321*/
2322Transaction.userEvent = /*@__PURE__*/Annotation.define();
2323/**
2324Annotation indicating whether a transaction should be added to
2325the undo history or not.
2326*/
2327Transaction.addToHistory = /*@__PURE__*/Annotation.define();
2328/**
2329Annotation indicating (when present and true) that a transaction
2330represents a change made by some other actor, not the user. This
2331is used, for example, to tag other people's changes in
2332collaborative editing.
2333*/
2334Transaction.remote = /*@__PURE__*/Annotation.define();
2335function joinRanges(a, b) {
2336 let result = [];
2337 for (let iA = 0, iB = 0;;) {
2338 let from, to;
2339 if (iA < a.length && (iB == b.length || b[iB] >= a[iA])) {
2340 from = a[iA++];
2341 to = a[iA++];
2342 }
2343 else if (iB < b.length) {
2344 from = b[iB++];
2345 to = b[iB++];
2346 }
2347 else
2348 return result;
2349 if (!result.length || result[result.length - 1] < from)
2350 result.push(from, to);
2351 else if (result[result.length - 1] < to)
2352 result[result.length - 1] = to;
2353 }
2354}
2355function mergeTransaction(a, b, sequential) {
2356 var _a;
2357 let mapForA, mapForB, changes;
2358 if (sequential) {
2359 mapForA = b.changes;
2360 mapForB = ChangeSet.empty(b.changes.length);
2361 changes = a.changes.compose(b.changes);
2362 }
2363 else {
2364 mapForA = b.changes.map(a.changes);
2365 mapForB = a.changes.mapDesc(b.changes, true);
2366 changes = a.changes.compose(mapForA);
2367 }
2368 return {
2369 changes,
2370 selection: b.selection ? b.selection.map(mapForB) : (_a = a.selection) === null || _a === void 0 ? void 0 : _a.map(mapForA),
2371 effects: StateEffect.mapEffects(a.effects, mapForA).concat(StateEffect.mapEffects(b.effects, mapForB)),
2372 annotations: a.annotations.length ? a.annotations.concat(b.annotations) : b.annotations,
2373 scrollIntoView: a.scrollIntoView || b.scrollIntoView
2374 };
2375}
2376function resolveTransactionInner(state, spec, docSize) {
2377 let sel = spec.selection, annotations = asArray(spec.annotations);
2378 if (spec.userEvent)
2379 annotations = annotations.concat(Transaction.userEvent.of(spec.userEvent));
2380 return {
2381 changes: spec.changes instanceof ChangeSet ? spec.changes
2382 : ChangeSet.of(spec.changes || [], docSize, state.facet(lineSeparator)),
2383 selection: sel && (sel instanceof EditorSelection ? sel : EditorSelection.single(sel.anchor, sel.head)),
2384 effects: asArray(spec.effects),
2385 annotations,
2386 scrollIntoView: !!spec.scrollIntoView
2387 };
2388}
2389function resolveTransaction(state, specs, filter) {
2390 let s = resolveTransactionInner(state, specs.length ? specs[0] : {}, state.doc.length);
2391 if (specs.length && specs[0].filter === false)
2392 filter = false;
2393 for (let i = 1; i < specs.length; i++) {
2394 if (specs[i].filter === false)
2395 filter = false;
2396 let seq = !!specs[i].sequential;
2397 s = mergeTransaction(s, resolveTransactionInner(state, specs[i], seq ? s.changes.newLength : state.doc.length), seq);
2398 }
2399 let tr = Transaction.create(state, s.changes, s.selection, s.effects, s.annotations, s.scrollIntoView);
2400 return extendTransaction(filter ? filterTransaction(tr) : tr);
2401}
2402// Finish a transaction by applying filters if necessary.
2403function filterTransaction(tr) {
2404 let state = tr.startState;
2405 // Change filters
2406 let result = true;
2407 for (let filter of state.facet(changeFilter)) {
2408 let value = filter(tr);
2409 if (value === false) {
2410 result = false;
2411 break;
2412 }
2413 if (Array.isArray(value))
2414 result = result === true ? value : joinRanges(result, value);
2415 }
2416 if (result !== true) {
2417 let changes, back;
2418 if (result === false) {
2419 back = tr.changes.invertedDesc;
2420 changes = ChangeSet.empty(state.doc.length);
2421 }
2422 else {
2423 let filtered = tr.changes.filter(result);
2424 changes = filtered.changes;
2425 back = filtered.filtered.mapDesc(filtered.changes).invertedDesc;
2426 }
2427 tr = Transaction.create(state, changes, tr.selection && tr.selection.map(back), StateEffect.mapEffects(tr.effects, back), tr.annotations, tr.scrollIntoView);
2428 }
2429 // Transaction filters
2430 let filters = state.facet(transactionFilter);
2431 for (let i = filters.length - 1; i >= 0; i--) {
2432 let filtered = filters[i](tr);
2433 if (filtered instanceof Transaction)
2434 tr = filtered;
2435 else if (Array.isArray(filtered) && filtered.length == 1 && filtered[0] instanceof Transaction)
2436 tr = filtered[0];
2437 else
2438 tr = resolveTransaction(state, asArray(filtered), false);
2439 }
2440 return tr;
2441}
2442function extendTransaction(tr) {
2443 let state = tr.startState, extenders = state.facet(transactionExtender), spec = tr;
2444 for (let i = extenders.length - 1; i >= 0; i--) {
2445 let extension = extenders[i](tr);
2446 if (extension && Object.keys(extension).length)
2447 spec = mergeTransaction(spec, resolveTransactionInner(state, extension, tr.changes.newLength), true);
2448 }
2449 return spec == tr ? tr : Transaction.create(state, tr.changes, tr.selection, spec.effects, spec.annotations, spec.scrollIntoView);
2450}
2451const none = [];
2452function asArray(value) {
2453 return value == null ? none : Array.isArray(value) ? value : [value];
2454}
2455
2456/**
2457The categories produced by a [character
2458categorizer](https://codemirror.net/6/docs/ref/#state.EditorState.charCategorizer). These are used
2459do things like selecting by word.
2460*/
2461var CharCategory = /*@__PURE__*/(function (CharCategory) {
2462 /**
2463 Word characters.
2464 */
2465 CharCategory[CharCategory["Word"] = 0] = "Word";
2466 /**
2467 Whitespace.
2468 */
2469 CharCategory[CharCategory["Space"] = 1] = "Space";
2470 /**
2471 Anything else.
2472 */
2473 CharCategory[CharCategory["Other"] = 2] = "Other";
2474return CharCategory})(CharCategory || (CharCategory = {}));
2475const nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;
2476let wordChar;
2477try {
2478 wordChar = /*@__PURE__*/new RegExp("[\\p{Alphabetic}\\p{Number}_]", "u");
2479}
2480catch (_) { }
2481function hasWordChar(str) {
2482 if (wordChar)
2483 return wordChar.test(str);
2484 for (let i = 0; i < str.length; i++) {
2485 let ch = str[i];
2486 if (/\w/.test(ch) || ch > "\x80" && (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch)))
2487 return true;
2488 }
2489 return false;
2490}
2491function makeCategorizer(wordChars) {
2492 return (char) => {
2493 if (!/\S/.test(char))
2494 return CharCategory.Space;
2495 if (hasWordChar(char))
2496 return CharCategory.Word;
2497 for (let i = 0; i < wordChars.length; i++)
2498 if (char.indexOf(wordChars[i]) > -1)
2499 return CharCategory.Word;
2500 return CharCategory.Other;
2501 };
2502}
2503
2504/**
2505The editor state class is a persistent (immutable) data structure.
2506To update a state, you [create](https://codemirror.net/6/docs/ref/#state.EditorState.update) a
2507[transaction](https://codemirror.net/6/docs/ref/#state.Transaction), which produces a _new_ state
2508instance, without modifying the original object.
2509
2510As such, _never_ mutate properties of a state directly. That'll
2511just break things.
2512*/
2513class EditorState {
2514 constructor(
2515 /**
2516 @internal
2517 */
2518 config,
2519 /**
2520 The current document.
2521 */
2522 doc,
2523 /**
2524 The current selection.
2525 */
2526 selection,
2527 /**
2528 @internal
2529 */
2530 values, computeSlot, tr) {
2531 this.config = config;
2532 this.doc = doc;
2533 this.selection = selection;
2534 this.values = values;
2535 this.status = config.statusTemplate.slice();
2536 this.computeSlot = computeSlot;
2537 // Fill in the computed state immediately, so that further queries
2538 // for it made during the update return this state
2539 if (tr)
2540 tr._state = this;
2541 for (let i = 0; i < this.config.dynamicSlots.length; i++)
2542 ensureAddr(this, i << 1);
2543 this.computeSlot = null;
2544 }
2545 field(field, require = true) {
2546 let addr = this.config.address[field.id];
2547 if (addr == null) {
2548 if (require)
2549 throw new RangeError("Field is not present in this state");
2550 return undefined;
2551 }
2552 ensureAddr(this, addr);
2553 return getAddr(this, addr);
2554 }
2555 /**
2556 Create a [transaction](https://codemirror.net/6/docs/ref/#state.Transaction) that updates this
2557 state. Any number of [transaction specs](https://codemirror.net/6/docs/ref/#state.TransactionSpec)
2558 can be passed. Unless
2559 [`sequential`](https://codemirror.net/6/docs/ref/#state.TransactionSpec.sequential) is set, the
2560 [changes](https://codemirror.net/6/docs/ref/#state.TransactionSpec.changes) (if any) of each spec
2561 are assumed to start in the _current_ document (not the document
2562 produced by previous specs), and its
2563 [selection](https://codemirror.net/6/docs/ref/#state.TransactionSpec.selection) and
2564 [effects](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects) are assumed to refer
2565 to the document created by its _own_ changes. The resulting
2566 transaction contains the combined effect of all the different
2567 specs. For [selection](https://codemirror.net/6/docs/ref/#state.TransactionSpec.selection), later
2568 specs take precedence over earlier ones.
2569 */
2570 update(...specs) {
2571 return resolveTransaction(this, specs, true);
2572 }
2573 /**
2574 @internal
2575 */
2576 applyTransaction(tr) {
2577 let conf = this.config, { base, compartments } = conf;
2578 for (let effect of tr.effects) {
2579 if (effect.is(Compartment.reconfigure)) {
2580 if (conf) {
2581 compartments = new Map;
2582 conf.compartments.forEach((val, key) => compartments.set(key, val));
2583 conf = null;
2584 }
2585 compartments.set(effect.value.compartment, effect.value.extension);
2586 }
2587 else if (effect.is(StateEffect.reconfigure)) {
2588 conf = null;
2589 base = effect.value;
2590 }
2591 else if (effect.is(StateEffect.appendConfig)) {
2592 conf = null;
2593 base = asArray(base).concat(effect.value);
2594 }
2595 }
2596 let startValues;
2597 if (!conf) {
2598 conf = Configuration.resolve(base, compartments, this);
2599 let intermediateState = new EditorState(conf, this.doc, this.selection, conf.dynamicSlots.map(() => null), (state, slot) => slot.reconfigure(state, this), null);
2600 startValues = intermediateState.values;
2601 }
2602 else {
2603 startValues = tr.startState.values.slice();
2604 }
2605 let selection = tr.startState.facet(allowMultipleSelections) ? tr.newSelection : tr.newSelection.asSingle();
2606 new EditorState(conf, tr.newDoc, selection, startValues, (state, slot) => slot.update(state, tr), tr);
2607 }
2608 /**
2609 Create a [transaction spec](https://codemirror.net/6/docs/ref/#state.TransactionSpec) that
2610 replaces every selection range with the given content.
2611 */
2612 replaceSelection(text) {
2613 if (typeof text == "string")
2614 text = this.toText(text);
2615 return this.changeByRange(range => ({ changes: { from: range.from, to: range.to, insert: text },
2616 range: EditorSelection.cursor(range.from + text.length) }));
2617 }
2618 /**
2619 Create a set of changes and a new selection by running the given
2620 function for each range in the active selection. The function
2621 can return an optional set of changes (in the coordinate space
2622 of the start document), plus an updated range (in the coordinate
2623 space of the document produced by the call's own changes). This
2624 method will merge all the changes and ranges into a single
2625 changeset and selection, and return it as a [transaction
2626 spec](https://codemirror.net/6/docs/ref/#state.TransactionSpec), which can be passed to
2627 [`update`](https://codemirror.net/6/docs/ref/#state.EditorState.update).
2628 */
2629 changeByRange(f) {
2630 let sel = this.selection;
2631 let result1 = f(sel.ranges[0]);
2632 let changes = this.changes(result1.changes), ranges = [result1.range];
2633 let effects = asArray(result1.effects);
2634 for (let i = 1; i < sel.ranges.length; i++) {
2635 let result = f(sel.ranges[i]);
2636 let newChanges = this.changes(result.changes), newMapped = newChanges.map(changes);
2637 for (let j = 0; j < i; j++)
2638 ranges[j] = ranges[j].map(newMapped);
2639 let mapBy = changes.mapDesc(newChanges, true);
2640 ranges.push(result.range.map(mapBy));
2641 changes = changes.compose(newMapped);
2642 effects = StateEffect.mapEffects(effects, newMapped).concat(StateEffect.mapEffects(asArray(result.effects), mapBy));
2643 }
2644 return {
2645 changes,
2646 selection: EditorSelection.create(ranges, sel.mainIndex),
2647 effects
2648 };
2649 }
2650 /**
2651 Create a [change set](https://codemirror.net/6/docs/ref/#state.ChangeSet) from the given change
2652 description, taking the state's document length and line
2653 separator into account.
2654 */
2655 changes(spec = []) {
2656 if (spec instanceof ChangeSet)
2657 return spec;
2658 return ChangeSet.of(spec, this.doc.length, this.facet(EditorState.lineSeparator));
2659 }
2660 /**
2661 Using the state's [line
2662 separator](https://codemirror.net/6/docs/ref/#state.EditorState^lineSeparator), create a
2663 [`Text`](https://codemirror.net/6/docs/ref/#state.Text) instance from the given string.
2664 */
2665 toText(string) {
2666 return Text.of(string.split(this.facet(EditorState.lineSeparator) || DefaultSplit));
2667 }
2668 /**
2669 Return the given range of the document as a string.
2670 */
2671 sliceDoc(from = 0, to = this.doc.length) {
2672 return this.doc.sliceString(from, to, this.lineBreak);
2673 }
2674 /**
2675 Get the value of a state [facet](https://codemirror.net/6/docs/ref/#state.Facet).
2676 */
2677 facet(facet) {
2678 let addr = this.config.address[facet.id];
2679 if (addr == null)
2680 return facet.default;
2681 ensureAddr(this, addr);
2682 return getAddr(this, addr);
2683 }
2684 /**
2685 Convert this state to a JSON-serializable object. When custom
2686 fields should be serialized, you can pass them in as an object
2687 mapping property names (in the resulting object, which should
2688 not use `doc` or `selection`) to fields.
2689 */
2690 toJSON(fields) {
2691 let result = {
2692 doc: this.sliceDoc(),
2693 selection: this.selection.toJSON()
2694 };
2695 if (fields)
2696 for (let prop in fields) {
2697 let value = fields[prop];
2698 if (value instanceof StateField && this.config.address[value.id] != null)
2699 result[prop] = value.spec.toJSON(this.field(fields[prop]), this);
2700 }
2701 return result;
2702 }
2703 /**
2704 Deserialize a state from its JSON representation. When custom
2705 fields should be deserialized, pass the same object you passed
2706 to [`toJSON`](https://codemirror.net/6/docs/ref/#state.EditorState.toJSON) when serializing as
2707 third argument.
2708 */
2709 static fromJSON(json, config = {}, fields) {
2710 if (!json || typeof json.doc != "string")
2711 throw new RangeError("Invalid JSON representation for EditorState");
2712 let fieldInit = [];
2713 if (fields)
2714 for (let prop in fields) {
2715 if (Object.prototype.hasOwnProperty.call(json, prop)) {
2716 let field = fields[prop], value = json[prop];
2717 fieldInit.push(field.init(state => field.spec.fromJSON(value, state)));
2718 }
2719 }
2720 return EditorState.create({
2721 doc: json.doc,
2722 selection: EditorSelection.fromJSON(json.selection),
2723 extensions: config.extensions ? fieldInit.concat([config.extensions]) : fieldInit
2724 });
2725 }
2726 /**
2727 Create a new state. You'll usually only need this when
2728 initializing an editor—updated states are created by applying
2729 transactions.
2730 */
2731 static create(config = {}) {
2732 let configuration = Configuration.resolve(config.extensions || [], new Map);
2733 let doc = config.doc instanceof Text ? config.doc
2734 : Text.of((config.doc || "").split(configuration.staticFacet(EditorState.lineSeparator) || DefaultSplit));
2735 let selection = !config.selection ? EditorSelection.single(0)
2736 : config.selection instanceof EditorSelection ? config.selection
2737 : EditorSelection.single(config.selection.anchor, config.selection.head);
2738 checkSelection(selection, doc.length);
2739 if (!configuration.staticFacet(allowMultipleSelections))
2740 selection = selection.asSingle();
2741 return new EditorState(configuration, doc, selection, configuration.dynamicSlots.map(() => null), (state, slot) => slot.create(state), null);
2742 }
2743 /**
2744 The size (in columns) of a tab in the document, determined by
2745 the [`tabSize`](https://codemirror.net/6/docs/ref/#state.EditorState^tabSize) facet.
2746 */
2747 get tabSize() { return this.facet(EditorState.tabSize); }
2748 /**
2749 Get the proper [line-break](https://codemirror.net/6/docs/ref/#state.EditorState^lineSeparator)
2750 string for this state.
2751 */
2752 get lineBreak() { return this.facet(EditorState.lineSeparator) || "\n"; }
2753 /**
2754 Returns true when the editor is
2755 [configured](https://codemirror.net/6/docs/ref/#state.EditorState^readOnly) to be read-only.
2756 */
2757 get readOnly() { return this.facet(readOnly); }
2758 /**
2759 Look up a translation for the given phrase (via the
2760 [`phrases`](https://codemirror.net/6/docs/ref/#state.EditorState^phrases) facet), or return the
2761 original string if no translation is found.
2762
2763 If additional arguments are passed, they will be inserted in
2764 place of markers like `$1` (for the first value) and `$2`, etc.
2765 A single `$` is equivalent to `$1`, and `$$` will produce a
2766 literal dollar sign.
2767 */
2768 phrase(phrase, ...insert) {
2769 for (let map of this.facet(EditorState.phrases))
2770 if (Object.prototype.hasOwnProperty.call(map, phrase)) {
2771 phrase = map[phrase];
2772 break;
2773 }
2774 if (insert.length)
2775 phrase = phrase.replace(/\$(\$|\d*)/g, (m, i) => {
2776 if (i == "$")
2777 return "$";
2778 let n = +(i || 1);
2779 return !n || n > insert.length ? m : insert[n - 1];
2780 });
2781 return phrase;
2782 }
2783 /**
2784 Find the values for a given language data field, provided by the
2785 the [`languageData`](https://codemirror.net/6/docs/ref/#state.EditorState^languageData) facet.
2786
2787 Examples of language data fields are...
2788
2789 - [`"commentTokens"`](https://codemirror.net/6/docs/ref/#commands.CommentTokens) for specifying
2790 comment syntax.
2791 - [`"autocomplete"`](https://codemirror.net/6/docs/ref/#autocomplete.autocompletion^config.override)
2792 for providing language-specific completion sources.
2793 - [`"wordChars"`](https://codemirror.net/6/docs/ref/#state.EditorState.charCategorizer) for adding
2794 characters that should be considered part of words in this
2795 language.
2796 - [`"closeBrackets"`](https://codemirror.net/6/docs/ref/#autocomplete.CloseBracketConfig) controls
2797 bracket closing behavior.
2798 */
2799 languageDataAt(name, pos, side = -1) {
2800 let values = [];
2801 for (let provider of this.facet(languageData)) {
2802 for (let result of provider(this, pos, side)) {
2803 if (Object.prototype.hasOwnProperty.call(result, name))
2804 values.push(result[name]);
2805 }
2806 }
2807 return values;
2808 }
2809 /**
2810 Return a function that can categorize strings (expected to
2811 represent a single [grapheme cluster](https://codemirror.net/6/docs/ref/#state.findClusterBreak))
2812 into one of:
2813
2814 - Word (contains an alphanumeric character or a character
2815 explicitly listed in the local language's `"wordChars"`
2816 language data, which should be a string)
2817 - Space (contains only whitespace)
2818 - Other (anything else)
2819 */
2820 charCategorizer(at) {
2821 return makeCategorizer(this.languageDataAt("wordChars", at).join(""));
2822 }
2823 /**
2824 Find the word at the given position, meaning the range
2825 containing all [word](https://codemirror.net/6/docs/ref/#state.CharCategory.Word) characters
2826 around it. If no word characters are adjacent to the position,
2827 this returns null.
2828 */
2829 wordAt(pos) {
2830 let { text, from, length } = this.doc.lineAt(pos);
2831 let cat = this.charCategorizer(pos);
2832 let start = pos - from, end = pos - from;
2833 while (start > 0) {
2834 let prev = findClusterBreak(text, start, false);
2835 if (cat(text.slice(prev, start)) != CharCategory.Word)
2836 break;
2837 start = prev;
2838 }
2839 while (end < length) {
2840 let next = findClusterBreak(text, end);
2841 if (cat(text.slice(end, next)) != CharCategory.Word)
2842 break;
2843 end = next;
2844 }
2845 return start == end ? null : EditorSelection.range(start + from, end + from);
2846 }
2847}
2848/**
2849A facet that, when enabled, causes the editor to allow multiple
2850ranges to be selected. Be careful though, because by default the
2851editor relies on the native DOM selection, which cannot handle
2852multiple selections. An extension like
2853[`drawSelection`](https://codemirror.net/6/docs/ref/#view.drawSelection) can be used to make
2854secondary selections visible to the user.
2855*/
2856EditorState.allowMultipleSelections = allowMultipleSelections;
2857/**
2858Configures the tab size to use in this state. The first
2859(highest-precedence) value of the facet is used. If no value is
2860given, this defaults to 4.
2861*/
2862EditorState.tabSize = /*@__PURE__*/Facet.define({
2863 combine: values => values.length ? values[0] : 4
2864});
2865/**
2866The line separator to use. By default, any of `"\n"`, `"\r\n"`
2867and `"\r"` is treated as a separator when splitting lines, and
2868lines are joined with `"\n"`.
2869
2870When you configure a value here, only that precise separator
2871will be used, allowing you to round-trip documents through the
2872editor without normalizing line separators.
2873*/
2874EditorState.lineSeparator = lineSeparator;
2875/**
2876This facet controls the value of the
2877[`readOnly`](https://codemirror.net/6/docs/ref/#state.EditorState.readOnly) getter, which is
2878consulted by commands and extensions that implement editing
2879functionality to determine whether they should apply. It
2880defaults to false, but when its highest-precedence value is
2881`true`, such functionality disables itself.
2882
2883Not to be confused with
2884[`EditorView.editable`](https://codemirror.net/6/docs/ref/#view.EditorView^editable), which
2885controls whether the editor's DOM is set to be editable (and
2886thus focusable).
2887*/
2888EditorState.readOnly = readOnly;
2889/**
2890Registers translation phrases. The
2891[`phrase`](https://codemirror.net/6/docs/ref/#state.EditorState.phrase) method will look through
2892all objects registered with this facet to find translations for
2893its argument.
2894*/
2895EditorState.phrases = /*@__PURE__*/Facet.define({
2896 compare(a, b) {
2897 let kA = Object.keys(a), kB = Object.keys(b);
2898 return kA.length == kB.length && kA.every(k => a[k] == b[k]);
2899 }
2900});
2901/**
2902A facet used to register [language
2903data](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt) providers.
2904*/
2905EditorState.languageData = languageData;
2906/**
2907Facet used to register change filters, which are called for each
2908transaction (unless explicitly
2909[disabled](https://codemirror.net/6/docs/ref/#state.TransactionSpec.filter)), and can suppress
2910part of the transaction's changes.
2911
2912Such a function can return `true` to indicate that it doesn't
2913want to do anything, `false` to completely stop the changes in
2914the transaction, or a set of ranges in which changes should be
2915suppressed. Such ranges are represented as an array of numbers,
2916with each pair of two numbers indicating the start and end of a
2917range. So for example `[10, 20, 100, 110]` suppresses changes
2918between 10 and 20, and between 100 and 110.
2919*/
2920EditorState.changeFilter = changeFilter;
2921/**
2922Facet used to register a hook that gets a chance to update or
2923replace transaction specs before they are applied. This will
2924only be applied for transactions that don't have
2925[`filter`](https://codemirror.net/6/docs/ref/#state.TransactionSpec.filter) set to `false`. You
2926can either return a single transaction spec (possibly the input
2927transaction), or an array of specs (which will be combined in
2928the same way as the arguments to
2929[`EditorState.update`](https://codemirror.net/6/docs/ref/#state.EditorState.update)).
2930
2931When possible, it is recommended to avoid accessing
2932[`Transaction.state`](https://codemirror.net/6/docs/ref/#state.Transaction.state) in a filter,
2933since it will force creation of a state that will then be
2934discarded again, if the transaction is actually filtered.
2935
2936(This functionality should be used with care. Indiscriminately
2937modifying transaction is likely to break something or degrade
2938the user experience.)
2939*/
2940EditorState.transactionFilter = transactionFilter;
2941/**
2942This is a more limited form of
2943[`transactionFilter`](https://codemirror.net/6/docs/ref/#state.EditorState^transactionFilter),
2944which can only add
2945[annotations](https://codemirror.net/6/docs/ref/#state.TransactionSpec.annotations) and
2946[effects](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects). _But_, this type
2947of filter runs even if the transaction has disabled regular
2948[filtering](https://codemirror.net/6/docs/ref/#state.TransactionSpec.filter), making it suitable
2949for effects that don't need to touch the changes or selection,
2950but do want to process every transaction.
2951
2952Extenders run _after_ filters, when both are present.
2953*/
2954EditorState.transactionExtender = transactionExtender;
2955Compartment.reconfigure = /*@__PURE__*/StateEffect.define();
2956
2957/**
2958Utility function for combining behaviors to fill in a config
2959object from an array of provided configs. `defaults` should hold
2960default values for all optional fields in `Config`.
2961
2962The function will, by default, error
2963when a field gets two values that aren't `===`-equal, but you can
2964provide combine functions per field to do something else.
2965*/
2966function combineConfig(configs, defaults, // Should hold only the optional properties of Config, but I haven't managed to express that
2967combine = {}) {
2968 let result = {};
2969 for (let config of configs)
2970 for (let key of Object.keys(config)) {
2971 let value = config[key], current = result[key];
2972 if (current === undefined)
2973 result[key] = value;
2974 else if (current === value || value === undefined) ; // No conflict
2975 else if (Object.hasOwnProperty.call(combine, key))
2976 result[key] = combine[key](current, value);
2977 else
2978 throw new Error("Config merge conflict for field " + key);
2979 }
2980 for (let key in defaults)
2981 if (result[key] === undefined)
2982 result[key] = defaults[key];
2983 return result;
2984}
2985
2986/**
2987Each range is associated with a value, which must inherit from
2988this class.
2989*/
2990class RangeValue {
2991 /**
2992 Compare this value with another value. Used when comparing
2993 rangesets. The default implementation compares by identity.
2994 Unless you are only creating a fixed number of unique instances
2995 of your value type, it is a good idea to implement this
2996 properly.
2997 */
2998 eq(other) { return this == other; }
2999 /**
3000 Create a [range](https://codemirror.net/6/docs/ref/#state.Range) with this value.
3001 */
3002 range(from, to = from) { return Range.create(from, to, this); }
3003}
3004RangeValue.prototype.startSide = RangeValue.prototype.endSide = 0;
3005RangeValue.prototype.point = false;
3006RangeValue.prototype.mapMode = MapMode.TrackDel;
3007/**
3008A range associates a value with a range of positions.
3009*/
3010class 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}
3035function cmpRange(a, b) {
3036 return a.from - b.from || a.value.startSide - b.value.startSide;
3037}
3038class 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, -1000000000 /* 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/**
3108A range set stores a collection of [ranges](https://codemirror.net/6/docs/ref/#state.Range) in a
3109way 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
3111structure.
3112*/
3113class 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 || !sideA.point.eq(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/**
3384The empty set of ranges.
3385*/
3386RangeSet.empty = /*@__PURE__*/new RangeSet([], [], null, -1);
3387function 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}
3397RangeSet.empty.nextLayer = RangeSet.empty;
3398/**
3399A 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
3401an array of [`Range`](https://codemirror.net/6/docs/ref/#state.Range) objects.
3402*/
3403class 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 = -1000000000 /* C.Far */;
3425 this.lastTo = -1000000000 /* 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}
3499function 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}
3515class 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 = -1000000000 /* 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}
3592class 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 = -1000000000 /* 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}
3641function 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}
3658class 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 = -1000000000 /* 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 = -1000000000 /* 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}
3783function 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 for (;;) {
3789 let dEnd = (a.to + dPos) - b.to, diff = dEnd || a.endSide - b.endSide;
3790 let end = diff < 0 ? a.to + dPos : b.to, clipEnd = Math.min(end, endB);
3791 if (a.point || b.point) {
3792 if (!(a.point && b.point && (a.point == b.point || a.point.eq(b.point)) &&
3793 sameValues(a.activeForPoint(a.to), b.activeForPoint(b.to))))
3794 comparator.comparePoint(pos, clipEnd, a.point, b.point);
3795 }
3796 else {
3797 if (clipEnd > pos && !sameValues(a.active, b.active))
3798 comparator.compareRange(pos, clipEnd, a.active, b.active);
3799 }
3800 if (end > endB)
3801 break;
3802 if ((dEnd || a.openEnd != b.openEnd) && comparator.boundChange)
3803 comparator.boundChange(end);
3804 pos = end;
3805 if (diff <= 0)
3806 a.next();
3807 if (diff >= 0)
3808 b.next();
3809 }
3810}
3811function sameValues(a, b) {
3812 if (a.length != b.length)
3813 return false;
3814 for (let i = 0; i < a.length; i++)
3815 if (a[i] != b[i] && !a[i].eq(b[i]))
3816 return false;
3817 return true;
3818}
3819function remove(array, index) {
3820 for (let i = index, e = array.length - 1; i < e; i++)
3821 array[i] = array[i + 1];
3822 array.pop();
3823}
3824function insert(array, index, value) {
3825 for (let i = array.length - 1; i >= index; i--)
3826 array[i + 1] = array[i];
3827 array[index] = value;
3828}
3829function findMinIndex(value, array) {
3830 let found = -1, foundPos = 1000000000 /* C.Far */;
3831 for (let i = 0; i < array.length; i++)
3832 if ((array[i] - foundPos || value[i].endSide - value[found].endSide) < 0) {
3833 found = i;
3834 foundPos = array[i];
3835 }
3836 return found;
3837}
3838
3839/**
3840Count the column position at the given offset into the string,
3841taking extending characters and tab size into account.
3842*/
3843function countColumn(string, tabSize, to = string.length) {
3844 let n = 0;
3845 for (let i = 0; i < to;) {
3846 if (string.charCodeAt(i) == 9) {
3847 n += tabSize - (n % tabSize);
3848 i++;
3849 }
3850 else {
3851 n++;
3852 i = findClusterBreak(string, i);
3853 }
3854 }
3855 return n;
3856}
3857/**
3858Find the offset that corresponds to the given column position in a
3859string, taking extending characters and tab size into account. By
3860default, the string length is returned when it is too short to
3861reach the column. Pass `strict` true to make it return -1 in that
3862situation.
3863*/
3864function findColumn(string, col, tabSize, strict) {
3865 for (let i = 0, n = 0;;) {
3866 if (n >= col)
3867 return i;
3868 if (i == string.length)
3869 break;
3870 n += string.charCodeAt(i) == 9 ? tabSize - (n % tabSize) : 1;
3871 i = findClusterBreak(string, i);
3872 }
3873 return strict === true ? -1 : string.length;
3874}
3875
3876export { Annotation, AnnotationType, ChangeDesc, ChangeSet, CharCategory, Compartment, EditorSelection, EditorState, Facet, Line, MapMode, Prec, Range, RangeSet, RangeSetBuilder, RangeValue, SelectionRange, StateEffect, StateEffectType, StateField, Text, Transaction, codePointAt, codePointSize, combineConfig, countColumn, findClusterBreak, findColumn, fromCodePoint };