Diffdown is a real-time collaborative Markdown editor/previewer built on the AT Protocol
diffdown.com
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 && this.goalColumn == other.goalColumn &&
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 let init = state.facet(initField), oldInit = oldState.facet(initField), reInit;
1778 if ((reInit = init.find(i => i.field == this)) && reInit != oldInit.find(i => i.field == this)) {
1779 state.values[idx] = reInit.create(state);
1780 return 1 /* SlotStatus.Changed */;
1781 }
1782 if (oldState.config.address[this.id] != null) {
1783 state.values[idx] = oldState.field(this);
1784 return 0;
1785 }
1786 state.values[idx] = this.create(state);
1787 return 1 /* SlotStatus.Changed */;
1788 }
1789 };
1790 }
1791 /**
1792 Returns an extension that enables this field and overrides the
1793 way it is initialized. Can be useful when you need to provide a
1794 non-default starting value for the field.
1795 */
1796 init(create) {
1797 return [this, initField.of({ field: this, create })];
1798 }
1799 /**
1800 State field instances can be used as
1801 [`Extension`](https://codemirror.net/6/docs/ref/#state.Extension) values to enable the field in a
1802 given state.
1803 */
1804 get extension() { return this; }
1805}
1806const Prec_ = { lowest: 4, low: 3, default: 2, high: 1, highest: 0 };
1807function prec(value) {
1808 return (ext) => new PrecExtension(ext, value);
1809}
1810/**
1811By default extensions are registered in the order they are found
1812in the flattened form of nested array that was provided.
1813Individual extension values can be assigned a precedence to
1814override this. Extensions that do not have a precedence set get
1815the precedence of the nearest parent with a precedence, or
1816[`default`](https://codemirror.net/6/docs/ref/#state.Prec.default) if there is no such parent. The
1817final ordering of extensions is determined by first sorting by
1818precedence and then by order within each precedence.
1819*/
1820const Prec = {
1821 /**
1822 The highest precedence level, for extensions that should end up
1823 near the start of the precedence ordering.
1824 */
1825 highest: /*@__PURE__*/prec(Prec_.highest),
1826 /**
1827 A higher-than-default precedence, for extensions that should
1828 come before those with default precedence.
1829 */
1830 high: /*@__PURE__*/prec(Prec_.high),
1831 /**
1832 The default precedence, which is also used for extensions
1833 without an explicit precedence.
1834 */
1835 default: /*@__PURE__*/prec(Prec_.default),
1836 /**
1837 A lower-than-default precedence.
1838 */
1839 low: /*@__PURE__*/prec(Prec_.low),
1840 /**
1841 The lowest precedence level. Meant for things that should end up
1842 near the end of the extension order.
1843 */
1844 lowest: /*@__PURE__*/prec(Prec_.lowest)
1845};
1846class PrecExtension {
1847 constructor(inner, prec) {
1848 this.inner = inner;
1849 this.prec = prec;
1850 }
1851}
1852/**
1853Extension compartments can be used to make a configuration
1854dynamic. By [wrapping](https://codemirror.net/6/docs/ref/#state.Compartment.of) part of your
1855configuration in a compartment, you can later
1856[replace](https://codemirror.net/6/docs/ref/#state.Compartment.reconfigure) that part through a
1857transaction.
1858*/
1859class Compartment {
1860 /**
1861 Create an instance of this compartment to add to your [state
1862 configuration](https://codemirror.net/6/docs/ref/#state.EditorStateConfig.extensions).
1863 */
1864 of(ext) { return new CompartmentInstance(this, ext); }
1865 /**
1866 Create an [effect](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects) that
1867 reconfigures this compartment.
1868 */
1869 reconfigure(content) {
1870 return Compartment.reconfigure.of({ compartment: this, extension: content });
1871 }
1872 /**
1873 Get the current content of the compartment in the state, or
1874 `undefined` if it isn't present.
1875 */
1876 get(state) {
1877 return state.config.compartments.get(this);
1878 }
1879}
1880class CompartmentInstance {
1881 constructor(compartment, inner) {
1882 this.compartment = compartment;
1883 this.inner = inner;
1884 }
1885}
1886class Configuration {
1887 constructor(base, compartments, dynamicSlots, address, staticValues, facets) {
1888 this.base = base;
1889 this.compartments = compartments;
1890 this.dynamicSlots = dynamicSlots;
1891 this.address = address;
1892 this.staticValues = staticValues;
1893 this.facets = facets;
1894 this.statusTemplate = [];
1895 while (this.statusTemplate.length < dynamicSlots.length)
1896 this.statusTemplate.push(0 /* SlotStatus.Unresolved */);
1897 }
1898 staticFacet(facet) {
1899 let addr = this.address[facet.id];
1900 return addr == null ? facet.default : this.staticValues[addr >> 1];
1901 }
1902 static resolve(base, compartments, oldState) {
1903 let fields = [];
1904 let facets = Object.create(null);
1905 let newCompartments = new Map();
1906 for (let ext of flatten(base, compartments, newCompartments)) {
1907 if (ext instanceof StateField)
1908 fields.push(ext);
1909 else
1910 (facets[ext.facet.id] || (facets[ext.facet.id] = [])).push(ext);
1911 }
1912 let address = Object.create(null);
1913 let staticValues = [];
1914 let dynamicSlots = [];
1915 for (let field of fields) {
1916 address[field.id] = dynamicSlots.length << 1;
1917 dynamicSlots.push(a => field.slot(a));
1918 }
1919 let oldFacets = oldState === null || oldState === void 0 ? void 0 : oldState.config.facets;
1920 for (let id in facets) {
1921 let providers = facets[id], facet = providers[0].facet;
1922 let oldProviders = oldFacets && oldFacets[id] || [];
1923 if (providers.every(p => p.type == 0 /* Provider.Static */)) {
1924 address[facet.id] = (staticValues.length << 1) | 1;
1925 if (sameArray(oldProviders, providers)) {
1926 staticValues.push(oldState.facet(facet));
1927 }
1928 else {
1929 let value = facet.combine(providers.map(p => p.value));
1930 staticValues.push(oldState && facet.compare(value, oldState.facet(facet)) ? oldState.facet(facet) : value);
1931 }
1932 }
1933 else {
1934 for (let p of providers) {
1935 if (p.type == 0 /* Provider.Static */) {
1936 address[p.id] = (staticValues.length << 1) | 1;
1937 staticValues.push(p.value);
1938 }
1939 else {
1940 address[p.id] = dynamicSlots.length << 1;
1941 dynamicSlots.push(a => p.dynamicSlot(a));
1942 }
1943 }
1944 address[facet.id] = dynamicSlots.length << 1;
1945 dynamicSlots.push(a => dynamicFacetSlot(a, facet, providers));
1946 }
1947 }
1948 let dynamic = dynamicSlots.map(f => f(address));
1949 return new Configuration(base, newCompartments, dynamic, address, staticValues, facets);
1950 }
1951}
1952function flatten(extension, compartments, newCompartments) {
1953 let result = [[], [], [], [], []];
1954 let seen = new Map();
1955 function inner(ext, prec) {
1956 let known = seen.get(ext);
1957 if (known != null) {
1958 if (known <= prec)
1959 return;
1960 let found = result[known].indexOf(ext);
1961 if (found > -1)
1962 result[known].splice(found, 1);
1963 if (ext instanceof CompartmentInstance)
1964 newCompartments.delete(ext.compartment);
1965 }
1966 seen.set(ext, prec);
1967 if (Array.isArray(ext)) {
1968 for (let e of ext)
1969 inner(e, prec);
1970 }
1971 else if (ext instanceof CompartmentInstance) {
1972 if (newCompartments.has(ext.compartment))
1973 throw new RangeError(`Duplicate use of compartment in extensions`);
1974 let content = compartments.get(ext.compartment) || ext.inner;
1975 newCompartments.set(ext.compartment, content);
1976 inner(content, prec);
1977 }
1978 else if (ext instanceof PrecExtension) {
1979 inner(ext.inner, ext.prec);
1980 }
1981 else if (ext instanceof StateField) {
1982 result[prec].push(ext);
1983 if (ext.provides)
1984 inner(ext.provides, prec);
1985 }
1986 else if (ext instanceof FacetProvider) {
1987 result[prec].push(ext);
1988 if (ext.facet.extensions)
1989 inner(ext.facet.extensions, Prec_.default);
1990 }
1991 else {
1992 let content = ext.extension;
1993 if (!content)
1994 throw new Error(`Unrecognized extension value in extension set (${ext}). This sometimes happens because multiple instances of @codemirror/state are loaded, breaking instanceof checks.`);
1995 inner(content, prec);
1996 }
1997 }
1998 inner(extension, Prec_.default);
1999 return result.reduce((a, b) => a.concat(b));
2000}
2001function ensureAddr(state, addr) {
2002 if (addr & 1)
2003 return 2 /* SlotStatus.Computed */;
2004 let idx = addr >> 1;
2005 let status = state.status[idx];
2006 if (status == 4 /* SlotStatus.Computing */)
2007 throw new Error("Cyclic dependency between fields and/or facets");
2008 if (status & 2 /* SlotStatus.Computed */)
2009 return status;
2010 state.status[idx] = 4 /* SlotStatus.Computing */;
2011 let changed = state.computeSlot(state, state.config.dynamicSlots[idx]);
2012 return state.status[idx] = 2 /* SlotStatus.Computed */ | changed;
2013}
2014function getAddr(state, addr) {
2015 return addr & 1 ? state.config.staticValues[addr >> 1] : state.values[addr >> 1];
2016}
2017
2018const languageData = /*@__PURE__*/Facet.define();
2019const allowMultipleSelections = /*@__PURE__*/Facet.define({
2020 combine: values => values.some(v => v),
2021 static: true
2022});
2023const lineSeparator = /*@__PURE__*/Facet.define({
2024 combine: values => values.length ? values[0] : undefined,
2025 static: true
2026});
2027const changeFilter = /*@__PURE__*/Facet.define();
2028const transactionFilter = /*@__PURE__*/Facet.define();
2029const transactionExtender = /*@__PURE__*/Facet.define();
2030const readOnly = /*@__PURE__*/Facet.define({
2031 combine: values => values.length ? values[0] : false
2032});
2033
2034/**
2035Annotations are tagged values that are used to add metadata to
2036transactions in an extensible way. They should be used to model
2037things that effect the entire transaction (such as its [time
2038stamp](https://codemirror.net/6/docs/ref/#state.Transaction^time) or information about its
2039[origin](https://codemirror.net/6/docs/ref/#state.Transaction^userEvent)). For effects that happen
2040_alongside_ the other changes made by the transaction, [state
2041effects](https://codemirror.net/6/docs/ref/#state.StateEffect) are more appropriate.
2042*/
2043class Annotation {
2044 /**
2045 @internal
2046 */
2047 constructor(
2048 /**
2049 The annotation type.
2050 */
2051 type,
2052 /**
2053 The value of this annotation.
2054 */
2055 value) {
2056 this.type = type;
2057 this.value = value;
2058 }
2059 /**
2060 Define a new type of annotation.
2061 */
2062 static define() { return new AnnotationType(); }
2063}
2064/**
2065Marker that identifies a type of [annotation](https://codemirror.net/6/docs/ref/#state.Annotation).
2066*/
2067class AnnotationType {
2068 /**
2069 Create an instance of this annotation.
2070 */
2071 of(value) { return new Annotation(this, value); }
2072}
2073/**
2074Representation of a type of state effect. Defined with
2075[`StateEffect.define`](https://codemirror.net/6/docs/ref/#state.StateEffect^define).
2076*/
2077class StateEffectType {
2078 /**
2079 @internal
2080 */
2081 constructor(
2082 // The `any` types in these function types are there to work
2083 // around TypeScript issue #37631, where the type guard on
2084 // `StateEffect.is` mysteriously stops working when these properly
2085 // have type `Value`.
2086 /**
2087 @internal
2088 */
2089 map) {
2090 this.map = map;
2091 }
2092 /**
2093 Create a [state effect](https://codemirror.net/6/docs/ref/#state.StateEffect) instance of this
2094 type.
2095 */
2096 of(value) { return new StateEffect(this, value); }
2097}
2098/**
2099State effects can be used to represent additional effects
2100associated with a [transaction](https://codemirror.net/6/docs/ref/#state.Transaction.effects). They
2101are often useful to model changes to custom [state
2102fields](https://codemirror.net/6/docs/ref/#state.StateField), when those changes aren't implicit in
2103document or selection changes.
2104*/
2105class StateEffect {
2106 /**
2107 @internal
2108 */
2109 constructor(
2110 /**
2111 @internal
2112 */
2113 type,
2114 /**
2115 The value of this effect.
2116 */
2117 value) {
2118 this.type = type;
2119 this.value = value;
2120 }
2121 /**
2122 Map this effect through a position mapping. Will return
2123 `undefined` when that ends up deleting the effect.
2124 */
2125 map(mapping) {
2126 let mapped = this.type.map(this.value, mapping);
2127 return mapped === undefined ? undefined : mapped == this.value ? this : new StateEffect(this.type, mapped);
2128 }
2129 /**
2130 Tells you whether this effect object is of a given
2131 [type](https://codemirror.net/6/docs/ref/#state.StateEffectType).
2132 */
2133 is(type) { return this.type == type; }
2134 /**
2135 Define a new effect type. The type parameter indicates the type
2136 of values that his effect holds. It should be a type that
2137 doesn't include `undefined`, since that is used in
2138 [mapping](https://codemirror.net/6/docs/ref/#state.StateEffect.map) to indicate that an effect is
2139 removed.
2140 */
2141 static define(spec = {}) {
2142 return new StateEffectType(spec.map || (v => v));
2143 }
2144 /**
2145 Map an array of effects through a change set.
2146 */
2147 static mapEffects(effects, mapping) {
2148 if (!effects.length)
2149 return effects;
2150 let result = [];
2151 for (let effect of effects) {
2152 let mapped = effect.map(mapping);
2153 if (mapped)
2154 result.push(mapped);
2155 }
2156 return result;
2157 }
2158}
2159/**
2160This effect can be used to reconfigure the root extensions of
2161the editor. Doing this will discard any extensions
2162[appended](https://codemirror.net/6/docs/ref/#state.StateEffect^appendConfig), but does not reset
2163the content of [reconfigured](https://codemirror.net/6/docs/ref/#state.Compartment.reconfigure)
2164compartments.
2165*/
2166StateEffect.reconfigure = /*@__PURE__*/StateEffect.define();
2167/**
2168Append extensions to the top-level configuration of the editor.
2169*/
2170StateEffect.appendConfig = /*@__PURE__*/StateEffect.define();
2171/**
2172Changes to the editor state are grouped into transactions.
2173Typically, a user action creates a single transaction, which may
2174contain any number of document changes, may change the selection,
2175or have other effects. Create a transaction by calling
2176[`EditorState.update`](https://codemirror.net/6/docs/ref/#state.EditorState.update), or immediately
2177dispatch one by calling
2178[`EditorView.dispatch`](https://codemirror.net/6/docs/ref/#view.EditorView.dispatch).
2179*/
2180class Transaction {
2181 constructor(
2182 /**
2183 The state from which the transaction starts.
2184 */
2185 startState,
2186 /**
2187 The document changes made by this transaction.
2188 */
2189 changes,
2190 /**
2191 The selection set by this transaction, or undefined if it
2192 doesn't explicitly set a selection.
2193 */
2194 selection,
2195 /**
2196 The effects added to the transaction.
2197 */
2198 effects,
2199 /**
2200 @internal
2201 */
2202 annotations,
2203 /**
2204 Whether the selection should be scrolled into view after this
2205 transaction is dispatched.
2206 */
2207 scrollIntoView) {
2208 this.startState = startState;
2209 this.changes = changes;
2210 this.selection = selection;
2211 this.effects = effects;
2212 this.annotations = annotations;
2213 this.scrollIntoView = scrollIntoView;
2214 /**
2215 @internal
2216 */
2217 this._doc = null;
2218 /**
2219 @internal
2220 */
2221 this._state = null;
2222 if (selection)
2223 checkSelection(selection, changes.newLength);
2224 if (!annotations.some((a) => a.type == Transaction.time))
2225 this.annotations = annotations.concat(Transaction.time.of(Date.now()));
2226 }
2227 /**
2228 @internal
2229 */
2230 static create(startState, changes, selection, effects, annotations, scrollIntoView) {
2231 return new Transaction(startState, changes, selection, effects, annotations, scrollIntoView);
2232 }
2233 /**
2234 The new document produced by the transaction. Contrary to
2235 [`.state`](https://codemirror.net/6/docs/ref/#state.Transaction.state)`.doc`, accessing this won't
2236 force the entire new state to be computed right away, so it is
2237 recommended that [transaction
2238 filters](https://codemirror.net/6/docs/ref/#state.EditorState^transactionFilter) use this getter
2239 when they need to look at the new document.
2240 */
2241 get newDoc() {
2242 return this._doc || (this._doc = this.changes.apply(this.startState.doc));
2243 }
2244 /**
2245 The new selection produced by the transaction. If
2246 [`this.selection`](https://codemirror.net/6/docs/ref/#state.Transaction.selection) is undefined,
2247 this will [map](https://codemirror.net/6/docs/ref/#state.EditorSelection.map) the start state's
2248 current selection through the changes made by the transaction.
2249 */
2250 get newSelection() {
2251 return this.selection || this.startState.selection.map(this.changes);
2252 }
2253 /**
2254 The new state created by the transaction. Computed on demand
2255 (but retained for subsequent access), so it is recommended not to
2256 access it in [transaction
2257 filters](https://codemirror.net/6/docs/ref/#state.EditorState^transactionFilter) when possible.
2258 */
2259 get state() {
2260 if (!this._state)
2261 this.startState.applyTransaction(this);
2262 return this._state;
2263 }
2264 /**
2265 Get the value of the given annotation type, if any.
2266 */
2267 annotation(type) {
2268 for (let ann of this.annotations)
2269 if (ann.type == type)
2270 return ann.value;
2271 return undefined;
2272 }
2273 /**
2274 Indicates whether the transaction changed the document.
2275 */
2276 get docChanged() { return !this.changes.empty; }
2277 /**
2278 Indicates whether this transaction reconfigures the state
2279 (through a [configuration compartment](https://codemirror.net/6/docs/ref/#state.Compartment) or
2280 with a top-level configuration
2281 [effect](https://codemirror.net/6/docs/ref/#state.StateEffect^reconfigure).
2282 */
2283 get reconfigured() { return this.startState.config != this.state.config; }
2284 /**
2285 Returns true if the transaction has a [user
2286 event](https://codemirror.net/6/docs/ref/#state.Transaction^userEvent) annotation that is equal to
2287 or more specific than `event`. For example, if the transaction
2288 has `"select.pointer"` as user event, `"select"` and
2289 `"select.pointer"` will match it.
2290 */
2291 isUserEvent(event) {
2292 let e = this.annotation(Transaction.userEvent);
2293 return !!(e && (e == event || e.length > event.length && e.slice(0, event.length) == event && e[event.length] == "."));
2294 }
2295}
2296/**
2297Annotation used to store transaction timestamps. Automatically
2298added to every transaction, holding `Date.now()`.
2299*/
2300Transaction.time = /*@__PURE__*/Annotation.define();
2301/**
2302Annotation used to associate a transaction with a user interface
2303event. Holds a string identifying the event, using a
2304dot-separated format to support attaching more specific
2305information. The events used by the core libraries are:
2306
2307 - `"input"` when content is entered
2308 - `"input.type"` for typed input
2309 - `"input.type.compose"` for composition
2310 - `"input.paste"` for pasted input
2311 - `"input.drop"` when adding content with drag-and-drop
2312 - `"input.complete"` when autocompleting
2313 - `"delete"` when the user deletes content
2314 - `"delete.selection"` when deleting the selection
2315 - `"delete.forward"` when deleting forward from the selection
2316 - `"delete.backward"` when deleting backward from the selection
2317 - `"delete.cut"` when cutting to the clipboard
2318 - `"move"` when content is moved
2319 - `"move.drop"` when content is moved within the editor through drag-and-drop
2320 - `"select"` when explicitly changing the selection
2321 - `"select.pointer"` when selecting with a mouse or other pointing device
2322 - `"undo"` and `"redo"` for history actions
2323
2324Use [`isUserEvent`](https://codemirror.net/6/docs/ref/#state.Transaction.isUserEvent) to check
2325whether the annotation matches a given event.
2326*/
2327Transaction.userEvent = /*@__PURE__*/Annotation.define();
2328/**
2329Annotation indicating whether a transaction should be added to
2330the undo history or not.
2331*/
2332Transaction.addToHistory = /*@__PURE__*/Annotation.define();
2333/**
2334Annotation indicating (when present and true) that a transaction
2335represents a change made by some other actor, not the user. This
2336is used, for example, to tag other people's changes in
2337collaborative editing.
2338*/
2339Transaction.remote = /*@__PURE__*/Annotation.define();
2340function joinRanges(a, b) {
2341 let result = [];
2342 for (let iA = 0, iB = 0;;) {
2343 let from, to;
2344 if (iA < a.length && (iB == b.length || b[iB] >= a[iA])) {
2345 from = a[iA++];
2346 to = a[iA++];
2347 }
2348 else if (iB < b.length) {
2349 from = b[iB++];
2350 to = b[iB++];
2351 }
2352 else
2353 return result;
2354 if (!result.length || result[result.length - 1] < from)
2355 result.push(from, to);
2356 else if (result[result.length - 1] < to)
2357 result[result.length - 1] = to;
2358 }
2359}
2360function mergeTransaction(a, b, sequential) {
2361 var _a;
2362 let mapForA, mapForB, changes;
2363 if (sequential) {
2364 mapForA = b.changes;
2365 mapForB = ChangeSet.empty(b.changes.length);
2366 changes = a.changes.compose(b.changes);
2367 }
2368 else {
2369 mapForA = b.changes.map(a.changes);
2370 mapForB = a.changes.mapDesc(b.changes, true);
2371 changes = a.changes.compose(mapForA);
2372 }
2373 return {
2374 changes,
2375 selection: b.selection ? b.selection.map(mapForB) : (_a = a.selection) === null || _a === void 0 ? void 0 : _a.map(mapForA),
2376 effects: StateEffect.mapEffects(a.effects, mapForA).concat(StateEffect.mapEffects(b.effects, mapForB)),
2377 annotations: a.annotations.length ? a.annotations.concat(b.annotations) : b.annotations,
2378 scrollIntoView: a.scrollIntoView || b.scrollIntoView
2379 };
2380}
2381function resolveTransactionInner(state, spec, docSize) {
2382 let sel = spec.selection, annotations = asArray(spec.annotations);
2383 if (spec.userEvent)
2384 annotations = annotations.concat(Transaction.userEvent.of(spec.userEvent));
2385 return {
2386 changes: spec.changes instanceof ChangeSet ? spec.changes
2387 : ChangeSet.of(spec.changes || [], docSize, state.facet(lineSeparator)),
2388 selection: sel && (sel instanceof EditorSelection ? sel : EditorSelection.single(sel.anchor, sel.head)),
2389 effects: asArray(spec.effects),
2390 annotations,
2391 scrollIntoView: !!spec.scrollIntoView
2392 };
2393}
2394function resolveTransaction(state, specs, filter) {
2395 let s = resolveTransactionInner(state, specs.length ? specs[0] : {}, state.doc.length);
2396 if (specs.length && specs[0].filter === false)
2397 filter = false;
2398 for (let i = 1; i < specs.length; i++) {
2399 if (specs[i].filter === false)
2400 filter = false;
2401 let seq = !!specs[i].sequential;
2402 s = mergeTransaction(s, resolveTransactionInner(state, specs[i], seq ? s.changes.newLength : state.doc.length), seq);
2403 }
2404 let tr = Transaction.create(state, s.changes, s.selection, s.effects, s.annotations, s.scrollIntoView);
2405 return extendTransaction(filter ? filterTransaction(tr) : tr);
2406}
2407// Finish a transaction by applying filters if necessary.
2408function filterTransaction(tr) {
2409 let state = tr.startState;
2410 // Change filters
2411 let result = true;
2412 for (let filter of state.facet(changeFilter)) {
2413 let value = filter(tr);
2414 if (value === false) {
2415 result = false;
2416 break;
2417 }
2418 if (Array.isArray(value))
2419 result = result === true ? value : joinRanges(result, value);
2420 }
2421 if (result !== true) {
2422 let changes, back;
2423 if (result === false) {
2424 back = tr.changes.invertedDesc;
2425 changes = ChangeSet.empty(state.doc.length);
2426 }
2427 else {
2428 let filtered = tr.changes.filter(result);
2429 changes = filtered.changes;
2430 back = filtered.filtered.mapDesc(filtered.changes).invertedDesc;
2431 }
2432 tr = Transaction.create(state, changes, tr.selection && tr.selection.map(back), StateEffect.mapEffects(tr.effects, back), tr.annotations, tr.scrollIntoView);
2433 }
2434 // Transaction filters
2435 let filters = state.facet(transactionFilter);
2436 for (let i = filters.length - 1; i >= 0; i--) {
2437 let filtered = filters[i](tr);
2438 if (filtered instanceof Transaction)
2439 tr = filtered;
2440 else if (Array.isArray(filtered) && filtered.length == 1 && filtered[0] instanceof Transaction)
2441 tr = filtered[0];
2442 else
2443 tr = resolveTransaction(state, asArray(filtered), false);
2444 }
2445 return tr;
2446}
2447function extendTransaction(tr) {
2448 let state = tr.startState, extenders = state.facet(transactionExtender), spec = tr;
2449 for (let i = extenders.length - 1; i >= 0; i--) {
2450 let extension = extenders[i](tr);
2451 if (extension && Object.keys(extension).length)
2452 spec = mergeTransaction(spec, resolveTransactionInner(state, extension, tr.changes.newLength), true);
2453 }
2454 return spec == tr ? tr : Transaction.create(state, tr.changes, tr.selection, spec.effects, spec.annotations, spec.scrollIntoView);
2455}
2456const none = [];
2457function asArray(value) {
2458 return value == null ? none : Array.isArray(value) ? value : [value];
2459}
2460
2461/**
2462The categories produced by a [character
2463categorizer](https://codemirror.net/6/docs/ref/#state.EditorState.charCategorizer). These are used
2464do things like selecting by word.
2465*/
2466var CharCategory = /*@__PURE__*/(function (CharCategory) {
2467 /**
2468 Word characters.
2469 */
2470 CharCategory[CharCategory["Word"] = 0] = "Word";
2471 /**
2472 Whitespace.
2473 */
2474 CharCategory[CharCategory["Space"] = 1] = "Space";
2475 /**
2476 Anything else.
2477 */
2478 CharCategory[CharCategory["Other"] = 2] = "Other";
2479return CharCategory})(CharCategory || (CharCategory = {}));
2480const nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;
2481let wordChar;
2482try {
2483 wordChar = /*@__PURE__*/new RegExp("[\\p{Alphabetic}\\p{Number}_]", "u");
2484}
2485catch (_) { }
2486function hasWordChar(str) {
2487 if (wordChar)
2488 return wordChar.test(str);
2489 for (let i = 0; i < str.length; i++) {
2490 let ch = str[i];
2491 if (/\w/.test(ch) || ch > "\x80" && (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch)))
2492 return true;
2493 }
2494 return false;
2495}
2496function makeCategorizer(wordChars) {
2497 return (char) => {
2498 if (!/\S/.test(char))
2499 return CharCategory.Space;
2500 if (hasWordChar(char))
2501 return CharCategory.Word;
2502 for (let i = 0; i < wordChars.length; i++)
2503 if (char.indexOf(wordChars[i]) > -1)
2504 return CharCategory.Word;
2505 return CharCategory.Other;
2506 };
2507}
2508
2509/**
2510The editor state class is a persistent (immutable) data structure.
2511To update a state, you [create](https://codemirror.net/6/docs/ref/#state.EditorState.update) a
2512[transaction](https://codemirror.net/6/docs/ref/#state.Transaction), which produces a _new_ state
2513instance, without modifying the original object.
2514
2515As such, _never_ mutate properties of a state directly. That'll
2516just break things.
2517*/
2518class EditorState {
2519 constructor(
2520 /**
2521 @internal
2522 */
2523 config,
2524 /**
2525 The current document.
2526 */
2527 doc,
2528 /**
2529 The current selection.
2530 */
2531 selection,
2532 /**
2533 @internal
2534 */
2535 values, computeSlot, tr) {
2536 this.config = config;
2537 this.doc = doc;
2538 this.selection = selection;
2539 this.values = values;
2540 this.status = config.statusTemplate.slice();
2541 this.computeSlot = computeSlot;
2542 // Fill in the computed state immediately, so that further queries
2543 // for it made during the update return this state
2544 if (tr)
2545 tr._state = this;
2546 for (let i = 0; i < this.config.dynamicSlots.length; i++)
2547 ensureAddr(this, i << 1);
2548 this.computeSlot = null;
2549 }
2550 field(field, require = true) {
2551 let addr = this.config.address[field.id];
2552 if (addr == null) {
2553 if (require)
2554 throw new RangeError("Field is not present in this state");
2555 return undefined;
2556 }
2557 ensureAddr(this, addr);
2558 return getAddr(this, addr);
2559 }
2560 /**
2561 Create a [transaction](https://codemirror.net/6/docs/ref/#state.Transaction) that updates this
2562 state. Any number of [transaction specs](https://codemirror.net/6/docs/ref/#state.TransactionSpec)
2563 can be passed. Unless
2564 [`sequential`](https://codemirror.net/6/docs/ref/#state.TransactionSpec.sequential) is set, the
2565 [changes](https://codemirror.net/6/docs/ref/#state.TransactionSpec.changes) (if any) of each spec
2566 are assumed to start in the _current_ document (not the document
2567 produced by previous specs), and its
2568 [selection](https://codemirror.net/6/docs/ref/#state.TransactionSpec.selection) and
2569 [effects](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects) are assumed to refer
2570 to the document created by its _own_ changes. The resulting
2571 transaction contains the combined effect of all the different
2572 specs. For [selection](https://codemirror.net/6/docs/ref/#state.TransactionSpec.selection), later
2573 specs take precedence over earlier ones.
2574 */
2575 update(...specs) {
2576 return resolveTransaction(this, specs, true);
2577 }
2578 /**
2579 @internal
2580 */
2581 applyTransaction(tr) {
2582 let conf = this.config, { base, compartments } = conf;
2583 for (let effect of tr.effects) {
2584 if (effect.is(Compartment.reconfigure)) {
2585 if (conf) {
2586 compartments = new Map;
2587 conf.compartments.forEach((val, key) => compartments.set(key, val));
2588 conf = null;
2589 }
2590 compartments.set(effect.value.compartment, effect.value.extension);
2591 }
2592 else if (effect.is(StateEffect.reconfigure)) {
2593 conf = null;
2594 base = effect.value;
2595 }
2596 else if (effect.is(StateEffect.appendConfig)) {
2597 conf = null;
2598 base = asArray(base).concat(effect.value);
2599 }
2600 }
2601 let startValues;
2602 if (!conf) {
2603 conf = Configuration.resolve(base, compartments, this);
2604 let intermediateState = new EditorState(conf, this.doc, this.selection, conf.dynamicSlots.map(() => null), (state, slot) => slot.reconfigure(state, this), null);
2605 startValues = intermediateState.values;
2606 }
2607 else {
2608 startValues = tr.startState.values.slice();
2609 }
2610 let selection = tr.startState.facet(allowMultipleSelections) ? tr.newSelection : tr.newSelection.asSingle();
2611 new EditorState(conf, tr.newDoc, selection, startValues, (state, slot) => slot.update(state, tr), tr);
2612 }
2613 /**
2614 Create a [transaction spec](https://codemirror.net/6/docs/ref/#state.TransactionSpec) that
2615 replaces every selection range with the given content.
2616 */
2617 replaceSelection(text) {
2618 if (typeof text == "string")
2619 text = this.toText(text);
2620 return this.changeByRange(range => ({ changes: { from: range.from, to: range.to, insert: text },
2621 range: EditorSelection.cursor(range.from + text.length) }));
2622 }
2623 /**
2624 Create a set of changes and a new selection by running the given
2625 function for each range in the active selection. The function
2626 can return an optional set of changes (in the coordinate space
2627 of the start document), plus an updated range (in the coordinate
2628 space of the document produced by the call's own changes). This
2629 method will merge all the changes and ranges into a single
2630 changeset and selection, and return it as a [transaction
2631 spec](https://codemirror.net/6/docs/ref/#state.TransactionSpec), which can be passed to
2632 [`update`](https://codemirror.net/6/docs/ref/#state.EditorState.update).
2633 */
2634 changeByRange(f) {
2635 let sel = this.selection;
2636 let result1 = f(sel.ranges[0]);
2637 let changes = this.changes(result1.changes), ranges = [result1.range];
2638 let effects = asArray(result1.effects);
2639 for (let i = 1; i < sel.ranges.length; i++) {
2640 let result = f(sel.ranges[i]);
2641 let newChanges = this.changes(result.changes), newMapped = newChanges.map(changes);
2642 for (let j = 0; j < i; j++)
2643 ranges[j] = ranges[j].map(newMapped);
2644 let mapBy = changes.mapDesc(newChanges, true);
2645 ranges.push(result.range.map(mapBy));
2646 changes = changes.compose(newMapped);
2647 effects = StateEffect.mapEffects(effects, newMapped).concat(StateEffect.mapEffects(asArray(result.effects), mapBy));
2648 }
2649 return {
2650 changes,
2651 selection: EditorSelection.create(ranges, sel.mainIndex),
2652 effects
2653 };
2654 }
2655 /**
2656 Create a [change set](https://codemirror.net/6/docs/ref/#state.ChangeSet) from the given change
2657 description, taking the state's document length and line
2658 separator into account.
2659 */
2660 changes(spec = []) {
2661 if (spec instanceof ChangeSet)
2662 return spec;
2663 return ChangeSet.of(spec, this.doc.length, this.facet(EditorState.lineSeparator));
2664 }
2665 /**
2666 Using the state's [line
2667 separator](https://codemirror.net/6/docs/ref/#state.EditorState^lineSeparator), create a
2668 [`Text`](https://codemirror.net/6/docs/ref/#state.Text) instance from the given string.
2669 */
2670 toText(string) {
2671 return Text.of(string.split(this.facet(EditorState.lineSeparator) || DefaultSplit));
2672 }
2673 /**
2674 Return the given range of the document as a string.
2675 */
2676 sliceDoc(from = 0, to = this.doc.length) {
2677 return this.doc.sliceString(from, to, this.lineBreak);
2678 }
2679 /**
2680 Get the value of a state [facet](https://codemirror.net/6/docs/ref/#state.Facet).
2681 */
2682 facet(facet) {
2683 let addr = this.config.address[facet.id];
2684 if (addr == null)
2685 return facet.default;
2686 ensureAddr(this, addr);
2687 return getAddr(this, addr);
2688 }
2689 /**
2690 Convert this state to a JSON-serializable object. When custom
2691 fields should be serialized, you can pass them in as an object
2692 mapping property names (in the resulting object, which should
2693 not use `doc` or `selection`) to fields.
2694 */
2695 toJSON(fields) {
2696 let result = {
2697 doc: this.sliceDoc(),
2698 selection: this.selection.toJSON()
2699 };
2700 if (fields)
2701 for (let prop in fields) {
2702 let value = fields[prop];
2703 if (value instanceof StateField && this.config.address[value.id] != null)
2704 result[prop] = value.spec.toJSON(this.field(fields[prop]), this);
2705 }
2706 return result;
2707 }
2708 /**
2709 Deserialize a state from its JSON representation. When custom
2710 fields should be deserialized, pass the same object you passed
2711 to [`toJSON`](https://codemirror.net/6/docs/ref/#state.EditorState.toJSON) when serializing as
2712 third argument.
2713 */
2714 static fromJSON(json, config = {}, fields) {
2715 if (!json || typeof json.doc != "string")
2716 throw new RangeError("Invalid JSON representation for EditorState");
2717 let fieldInit = [];
2718 if (fields)
2719 for (let prop in fields) {
2720 if (Object.prototype.hasOwnProperty.call(json, prop)) {
2721 let field = fields[prop], value = json[prop];
2722 fieldInit.push(field.init(state => field.spec.fromJSON(value, state)));
2723 }
2724 }
2725 return EditorState.create({
2726 doc: json.doc,
2727 selection: EditorSelection.fromJSON(json.selection),
2728 extensions: config.extensions ? fieldInit.concat([config.extensions]) : fieldInit
2729 });
2730 }
2731 /**
2732 Create a new state. You'll usually only need this when
2733 initializing an editor—updated states are created by applying
2734 transactions.
2735 */
2736 static create(config = {}) {
2737 let configuration = Configuration.resolve(config.extensions || [], new Map);
2738 let doc = config.doc instanceof Text ? config.doc
2739 : Text.of((config.doc || "").split(configuration.staticFacet(EditorState.lineSeparator) || DefaultSplit));
2740 let selection = !config.selection ? EditorSelection.single(0)
2741 : config.selection instanceof EditorSelection ? config.selection
2742 : EditorSelection.single(config.selection.anchor, config.selection.head);
2743 checkSelection(selection, doc.length);
2744 if (!configuration.staticFacet(allowMultipleSelections))
2745 selection = selection.asSingle();
2746 return new EditorState(configuration, doc, selection, configuration.dynamicSlots.map(() => null), (state, slot) => slot.create(state), null);
2747 }
2748 /**
2749 The size (in columns) of a tab in the document, determined by
2750 the [`tabSize`](https://codemirror.net/6/docs/ref/#state.EditorState^tabSize) facet.
2751 */
2752 get tabSize() { return this.facet(EditorState.tabSize); }
2753 /**
2754 Get the proper [line-break](https://codemirror.net/6/docs/ref/#state.EditorState^lineSeparator)
2755 string for this state.
2756 */
2757 get lineBreak() { return this.facet(EditorState.lineSeparator) || "\n"; }
2758 /**
2759 Returns true when the editor is
2760 [configured](https://codemirror.net/6/docs/ref/#state.EditorState^readOnly) to be read-only.
2761 */
2762 get readOnly() { return this.facet(readOnly); }
2763 /**
2764 Look up a translation for the given phrase (via the
2765 [`phrases`](https://codemirror.net/6/docs/ref/#state.EditorState^phrases) facet), or return the
2766 original string if no translation is found.
2767
2768 If additional arguments are passed, they will be inserted in
2769 place of markers like `$1` (for the first value) and `$2`, etc.
2770 A single `$` is equivalent to `$1`, and `$$` will produce a
2771 literal dollar sign.
2772 */
2773 phrase(phrase, ...insert) {
2774 for (let map of this.facet(EditorState.phrases))
2775 if (Object.prototype.hasOwnProperty.call(map, phrase)) {
2776 phrase = map[phrase];
2777 break;
2778 }
2779 if (insert.length)
2780 phrase = phrase.replace(/\$(\$|\d*)/g, (m, i) => {
2781 if (i == "$")
2782 return "$";
2783 let n = +(i || 1);
2784 return !n || n > insert.length ? m : insert[n - 1];
2785 });
2786 return phrase;
2787 }
2788 /**
2789 Find the values for a given language data field, provided by the
2790 the [`languageData`](https://codemirror.net/6/docs/ref/#state.EditorState^languageData) facet.
2791
2792 Examples of language data fields are...
2793
2794 - [`"commentTokens"`](https://codemirror.net/6/docs/ref/#commands.CommentTokens) for specifying
2795 comment syntax.
2796 - [`"autocomplete"`](https://codemirror.net/6/docs/ref/#autocomplete.autocompletion^config.override)
2797 for providing language-specific completion sources.
2798 - [`"wordChars"`](https://codemirror.net/6/docs/ref/#state.EditorState.charCategorizer) for adding
2799 characters that should be considered part of words in this
2800 language.
2801 - [`"closeBrackets"`](https://codemirror.net/6/docs/ref/#autocomplete.CloseBracketConfig) controls
2802 bracket closing behavior.
2803 */
2804 languageDataAt(name, pos, side = -1) {
2805 let values = [];
2806 for (let provider of this.facet(languageData)) {
2807 for (let result of provider(this, pos, side)) {
2808 if (Object.prototype.hasOwnProperty.call(result, name))
2809 values.push(result[name]);
2810 }
2811 }
2812 return values;
2813 }
2814 /**
2815 Return a function that can categorize strings (expected to
2816 represent a single [grapheme cluster](https://codemirror.net/6/docs/ref/#state.findClusterBreak))
2817 into one of:
2818
2819 - Word (contains an alphanumeric character or a character
2820 explicitly listed in the local language's `"wordChars"`
2821 language data, which should be a string)
2822 - Space (contains only whitespace)
2823 - Other (anything else)
2824 */
2825 charCategorizer(at) {
2826 let chars = this.languageDataAt("wordChars", at);
2827 return makeCategorizer(chars.length ? chars[0] : "");
2828 }
2829 /**
2830 Find the word at the given position, meaning the range
2831 containing all [word](https://codemirror.net/6/docs/ref/#state.CharCategory.Word) characters
2832 around it. If no word characters are adjacent to the position,
2833 this returns null.
2834 */
2835 wordAt(pos) {
2836 let { text, from, length } = this.doc.lineAt(pos);
2837 let cat = this.charCategorizer(pos);
2838 let start = pos - from, end = pos - from;
2839 while (start > 0) {
2840 let prev = findClusterBreak(text, start, false);
2841 if (cat(text.slice(prev, start)) != CharCategory.Word)
2842 break;
2843 start = prev;
2844 }
2845 while (end < length) {
2846 let next = findClusterBreak(text, end);
2847 if (cat(text.slice(end, next)) != CharCategory.Word)
2848 break;
2849 end = next;
2850 }
2851 return start == end ? null : EditorSelection.range(start + from, end + from);
2852 }
2853}
2854/**
2855A facet that, when enabled, causes the editor to allow multiple
2856ranges to be selected. Be careful though, because by default the
2857editor relies on the native DOM selection, which cannot handle
2858multiple selections. An extension like
2859[`drawSelection`](https://codemirror.net/6/docs/ref/#view.drawSelection) can be used to make
2860secondary selections visible to the user.
2861*/
2862EditorState.allowMultipleSelections = allowMultipleSelections;
2863/**
2864Configures the tab size to use in this state. The first
2865(highest-precedence) value of the facet is used. If no value is
2866given, this defaults to 4.
2867*/
2868EditorState.tabSize = /*@__PURE__*/Facet.define({
2869 combine: values => values.length ? values[0] : 4
2870});
2871/**
2872The line separator to use. By default, any of `"\n"`, `"\r\n"`
2873and `"\r"` is treated as a separator when splitting lines, and
2874lines are joined with `"\n"`.
2875
2876When you configure a value here, only that precise separator
2877will be used, allowing you to round-trip documents through the
2878editor without normalizing line separators.
2879*/
2880EditorState.lineSeparator = lineSeparator;
2881/**
2882This facet controls the value of the
2883[`readOnly`](https://codemirror.net/6/docs/ref/#state.EditorState.readOnly) getter, which is
2884consulted by commands and extensions that implement editing
2885functionality to determine whether they should apply. It
2886defaults to false, but when its highest-precedence value is
2887`true`, such functionality disables itself.
2888
2889Not to be confused with
2890[`EditorView.editable`](https://codemirror.net/6/docs/ref/#view.EditorView^editable), which
2891controls whether the editor's DOM is set to be editable (and
2892thus focusable).
2893*/
2894EditorState.readOnly = readOnly;
2895/**
2896Registers translation phrases. The
2897[`phrase`](https://codemirror.net/6/docs/ref/#state.EditorState.phrase) method will look through
2898all objects registered with this facet to find translations for
2899its argument.
2900*/
2901EditorState.phrases = /*@__PURE__*/Facet.define({
2902 compare(a, b) {
2903 let kA = Object.keys(a), kB = Object.keys(b);
2904 return kA.length == kB.length && kA.every(k => a[k] == b[k]);
2905 }
2906});
2907/**
2908A facet used to register [language
2909data](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt) providers.
2910*/
2911EditorState.languageData = languageData;
2912/**
2913Facet used to register change filters, which are called for each
2914transaction (unless explicitly
2915[disabled](https://codemirror.net/6/docs/ref/#state.TransactionSpec.filter)), and can suppress
2916part of the transaction's changes.
2917
2918Such a function can return `true` to indicate that it doesn't
2919want to do anything, `false` to completely stop the changes in
2920the transaction, or a set of ranges in which changes should be
2921suppressed. Such ranges are represented as an array of numbers,
2922with each pair of two numbers indicating the start and end of a
2923range. So for example `[10, 20, 100, 110]` suppresses changes
2924between 10 and 20, and between 100 and 110.
2925*/
2926EditorState.changeFilter = changeFilter;
2927/**
2928Facet used to register a hook that gets a chance to update or
2929replace transaction specs before they are applied. This will
2930only be applied for transactions that don't have
2931[`filter`](https://codemirror.net/6/docs/ref/#state.TransactionSpec.filter) set to `false`. You
2932can either return a single transaction spec (possibly the input
2933transaction), or an array of specs (which will be combined in
2934the same way as the arguments to
2935[`EditorState.update`](https://codemirror.net/6/docs/ref/#state.EditorState.update)).
2936
2937When possible, it is recommended to avoid accessing
2938[`Transaction.state`](https://codemirror.net/6/docs/ref/#state.Transaction.state) in a filter,
2939since it will force creation of a state that will then be
2940discarded again, if the transaction is actually filtered.
2941
2942(This functionality should be used with care. Indiscriminately
2943modifying transaction is likely to break something or degrade
2944the user experience.)
2945*/
2946EditorState.transactionFilter = transactionFilter;
2947/**
2948This is a more limited form of
2949[`transactionFilter`](https://codemirror.net/6/docs/ref/#state.EditorState^transactionFilter),
2950which can only add
2951[annotations](https://codemirror.net/6/docs/ref/#state.TransactionSpec.annotations) and
2952[effects](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects). _But_, this type
2953of filter runs even if the transaction has disabled regular
2954[filtering](https://codemirror.net/6/docs/ref/#state.TransactionSpec.filter), making it suitable
2955for effects that don't need to touch the changes or selection,
2956but do want to process every transaction.
2957
2958Extenders run _after_ filters, when both are present.
2959*/
2960EditorState.transactionExtender = transactionExtender;
2961Compartment.reconfigure = /*@__PURE__*/StateEffect.define();
2962
2963/**
2964Utility function for combining behaviors to fill in a config
2965object from an array of provided configs. `defaults` should hold
2966default values for all optional fields in `Config`.
2967
2968The function will, by default, error
2969when a field gets two values that aren't `===`-equal, but you can
2970provide combine functions per field to do something else.
2971*/
2972function combineConfig(configs, defaults, // Should hold only the optional properties of Config, but I haven't managed to express that
2973combine = {}) {
2974 let result = {};
2975 for (let config of configs)
2976 for (let key of Object.keys(config)) {
2977 let value = config[key], current = result[key];
2978 if (current === undefined)
2979 result[key] = value;
2980 else if (current === value || value === undefined) ; // No conflict
2981 else if (Object.hasOwnProperty.call(combine, key))
2982 result[key] = combine[key](current, value);
2983 else
2984 throw new Error("Config merge conflict for field " + key);
2985 }
2986 for (let key in defaults)
2987 if (result[key] === undefined)
2988 result[key] = defaults[key];
2989 return result;
2990}
2991
2992/**
2993Each range is associated with a value, which must inherit from
2994this class.
2995*/
2996class RangeValue {
2997 /**
2998 Compare this value with another value. Used when comparing
2999 rangesets. The default implementation compares by identity.
3000 Unless you are only creating a fixed number of unique instances
3001 of your value type, it is a good idea to implement this
3002 properly.
3003 */
3004 eq(other) { return this == other; }
3005 /**
3006 Create a [range](https://codemirror.net/6/docs/ref/#state.Range) with this value.
3007 */
3008 range(from, to = from) { return Range.create(from, to, this); }
3009}
3010RangeValue.prototype.startSide = RangeValue.prototype.endSide = 0;
3011RangeValue.prototype.point = false;
3012RangeValue.prototype.mapMode = MapMode.TrackDel;
3013function cmpVal(a, b) {
3014 return a == b || a.constructor == b.constructor && a.eq(b);
3015}
3016/**
3017A range associates a value with a range of positions.
3018*/
3019class Range {
3020 constructor(
3021 /**
3022 The range's start position.
3023 */
3024 from,
3025 /**
3026 Its end position.
3027 */
3028 to,
3029 /**
3030 The value associated with this range.
3031 */
3032 value) {
3033 this.from = from;
3034 this.to = to;
3035 this.value = value;
3036 }
3037 /**
3038 @internal
3039 */
3040 static create(from, to, value) {
3041 return new Range(from, to, value);
3042 }
3043}
3044function cmpRange(a, b) {
3045 return a.from - b.from || a.value.startSide - b.value.startSide;
3046}
3047class Chunk {
3048 constructor(from, to, value,
3049 // Chunks are marked with the largest point that occurs
3050 // in them (or -1 for no points), so that scans that are
3051 // only interested in points (such as the
3052 // heightmap-related logic) can skip range-only chunks.
3053 maxPoint) {
3054 this.from = from;
3055 this.to = to;
3056 this.value = value;
3057 this.maxPoint = maxPoint;
3058 }
3059 get length() { return this.to[this.to.length - 1]; }
3060 // Find the index of the given position and side. Use the ranges'
3061 // `from` pos when `end == false`, `to` when `end == true`.
3062 findIndex(pos, side, end, startAt = 0) {
3063 let arr = end ? this.to : this.from;
3064 for (let lo = startAt, hi = arr.length;;) {
3065 if (lo == hi)
3066 return lo;
3067 let mid = (lo + hi) >> 1;
3068 let diff = arr[mid] - pos || (end ? this.value[mid].endSide : this.value[mid].startSide) - side;
3069 if (mid == lo)
3070 return diff >= 0 ? lo : hi;
3071 if (diff >= 0)
3072 hi = mid;
3073 else
3074 lo = mid + 1;
3075 }
3076 }
3077 between(offset, from, to, f) {
3078 for (let i = this.findIndex(from, -1000000000 /* C.Far */, true), e = this.findIndex(to, 1000000000 /* C.Far */, false, i); i < e; i++)
3079 if (f(this.from[i] + offset, this.to[i] + offset, this.value[i]) === false)
3080 return false;
3081 }
3082 map(offset, changes) {
3083 let value = [], from = [], to = [], newPos = -1, maxPoint = -1;
3084 for (let i = 0; i < this.value.length; i++) {
3085 let val = this.value[i], curFrom = this.from[i] + offset, curTo = this.to[i] + offset, newFrom, newTo;
3086 if (curFrom == curTo) {
3087 let mapped = changes.mapPos(curFrom, val.startSide, val.mapMode);
3088 if (mapped == null)
3089 continue;
3090 newFrom = newTo = mapped;
3091 if (val.startSide != val.endSide) {
3092 newTo = changes.mapPos(curFrom, val.endSide);
3093 if (newTo < newFrom)
3094 continue;
3095 }
3096 }
3097 else {
3098 newFrom = changes.mapPos(curFrom, val.startSide);
3099 newTo = changes.mapPos(curTo, val.endSide);
3100 if (newFrom > newTo || newFrom == newTo && val.startSide > 0 && val.endSide <= 0)
3101 continue;
3102 }
3103 if ((newTo - newFrom || val.endSide - val.startSide) < 0)
3104 continue;
3105 if (newPos < 0)
3106 newPos = newFrom;
3107 if (val.point)
3108 maxPoint = Math.max(maxPoint, newTo - newFrom);
3109 value.push(val);
3110 from.push(newFrom - newPos);
3111 to.push(newTo - newPos);
3112 }
3113 return { mapped: value.length ? new Chunk(from, to, value, maxPoint) : null, pos: newPos };
3114 }
3115}
3116/**
3117A range set stores a collection of [ranges](https://codemirror.net/6/docs/ref/#state.Range) in a
3118way that makes them efficient to [map](https://codemirror.net/6/docs/ref/#state.RangeSet.map) and
3119[update](https://codemirror.net/6/docs/ref/#state.RangeSet.update). This is an immutable data
3120structure.
3121*/
3122class RangeSet {
3123 constructor(
3124 /**
3125 @internal
3126 */
3127 chunkPos,
3128 /**
3129 @internal
3130 */
3131 chunk,
3132 /**
3133 @internal
3134 */
3135 nextLayer,
3136 /**
3137 @internal
3138 */
3139 maxPoint) {
3140 this.chunkPos = chunkPos;
3141 this.chunk = chunk;
3142 this.nextLayer = nextLayer;
3143 this.maxPoint = maxPoint;
3144 }
3145 /**
3146 @internal
3147 */
3148 static create(chunkPos, chunk, nextLayer, maxPoint) {
3149 return new RangeSet(chunkPos, chunk, nextLayer, maxPoint);
3150 }
3151 /**
3152 @internal
3153 */
3154 get length() {
3155 let last = this.chunk.length - 1;
3156 return last < 0 ? 0 : Math.max(this.chunkEnd(last), this.nextLayer.length);
3157 }
3158 /**
3159 The number of ranges in the set.
3160 */
3161 get size() {
3162 if (this.isEmpty)
3163 return 0;
3164 let size = this.nextLayer.size;
3165 for (let chunk of this.chunk)
3166 size += chunk.value.length;
3167 return size;
3168 }
3169 /**
3170 @internal
3171 */
3172 chunkEnd(index) {
3173 return this.chunkPos[index] + this.chunk[index].length;
3174 }
3175 /**
3176 Update the range set, optionally adding new ranges or filtering
3177 out existing ones.
3178
3179 (Note: The type parameter is just there as a kludge to work
3180 around TypeScript variance issues that prevented `RangeSet<X>`
3181 from being a subtype of `RangeSet<Y>` when `X` is a subtype of
3182 `Y`.)
3183 */
3184 update(updateSpec) {
3185 let { add = [], sort = false, filterFrom = 0, filterTo = this.length } = updateSpec;
3186 let filter = updateSpec.filter;
3187 if (add.length == 0 && !filter)
3188 return this;
3189 if (sort)
3190 add = add.slice().sort(cmpRange);
3191 if (this.isEmpty)
3192 return add.length ? RangeSet.of(add) : this;
3193 let cur = new LayerCursor(this, null, -1).goto(0), i = 0, spill = [];
3194 let builder = new RangeSetBuilder();
3195 while (cur.value || i < add.length) {
3196 if (i < add.length && (cur.from - add[i].from || cur.startSide - add[i].value.startSide) >= 0) {
3197 let range = add[i++];
3198 if (!builder.addInner(range.from, range.to, range.value))
3199 spill.push(range);
3200 }
3201 else if (cur.rangeIndex == 1 && cur.chunkIndex < this.chunk.length &&
3202 (i == add.length || this.chunkEnd(cur.chunkIndex) < add[i].from) &&
3203 (!filter || filterFrom > this.chunkEnd(cur.chunkIndex) || filterTo < this.chunkPos[cur.chunkIndex]) &&
3204 builder.addChunk(this.chunkPos[cur.chunkIndex], this.chunk[cur.chunkIndex])) {
3205 cur.nextChunk();
3206 }
3207 else {
3208 if (!filter || filterFrom > cur.to || filterTo < cur.from || filter(cur.from, cur.to, cur.value)) {
3209 if (!builder.addInner(cur.from, cur.to, cur.value))
3210 spill.push(Range.create(cur.from, cur.to, cur.value));
3211 }
3212 cur.next();
3213 }
3214 }
3215 return builder.finishInner(this.nextLayer.isEmpty && !spill.length ? RangeSet.empty
3216 : this.nextLayer.update({ add: spill, filter, filterFrom, filterTo }));
3217 }
3218 /**
3219 Map this range set through a set of changes, return the new set.
3220 */
3221 map(changes) {
3222 if (changes.empty || this.isEmpty)
3223 return this;
3224 let chunks = [], chunkPos = [], maxPoint = -1;
3225 for (let i = 0; i < this.chunk.length; i++) {
3226 let start = this.chunkPos[i], chunk = this.chunk[i];
3227 let touch = changes.touchesRange(start, start + chunk.length);
3228 if (touch === false) {
3229 maxPoint = Math.max(maxPoint, chunk.maxPoint);
3230 chunks.push(chunk);
3231 chunkPos.push(changes.mapPos(start));
3232 }
3233 else if (touch === true) {
3234 let { mapped, pos } = chunk.map(start, changes);
3235 if (mapped) {
3236 maxPoint = Math.max(maxPoint, mapped.maxPoint);
3237 chunks.push(mapped);
3238 chunkPos.push(pos);
3239 }
3240 }
3241 }
3242 let next = this.nextLayer.map(changes);
3243 return chunks.length == 0 ? next : new RangeSet(chunkPos, chunks, next || RangeSet.empty, maxPoint);
3244 }
3245 /**
3246 Iterate over the ranges that touch the region `from` to `to`,
3247 calling `f` for each. There is no guarantee that the ranges will
3248 be reported in any specific order. When the callback returns
3249 `false`, iteration stops.
3250 */
3251 between(from, to, f) {
3252 if (this.isEmpty)
3253 return;
3254 for (let i = 0; i < this.chunk.length; i++) {
3255 let start = this.chunkPos[i], chunk = this.chunk[i];
3256 if (to >= start && from <= start + chunk.length &&
3257 chunk.between(start, from - start, to - start, f) === false)
3258 return;
3259 }
3260 this.nextLayer.between(from, to, f);
3261 }
3262 /**
3263 Iterate over the ranges in this set, in order, including all
3264 ranges that end at or after `from`.
3265 */
3266 iter(from = 0) {
3267 return HeapCursor.from([this]).goto(from);
3268 }
3269 /**
3270 @internal
3271 */
3272 get isEmpty() { return this.nextLayer == this; }
3273 /**
3274 Iterate over the ranges in a collection of sets, in order,
3275 starting from `from`.
3276 */
3277 static iter(sets, from = 0) {
3278 return HeapCursor.from(sets).goto(from);
3279 }
3280 /**
3281 Iterate over two groups of sets, calling methods on `comparator`
3282 to notify it of possible differences.
3283 */
3284 static compare(oldSets, newSets,
3285 /**
3286 This indicates how the underlying data changed between these
3287 ranges, and is needed to synchronize the iteration.
3288 */
3289 textDiff, comparator,
3290 /**
3291 Can be used to ignore all non-point ranges, and points below
3292 the given size. When -1, all ranges are compared.
3293 */
3294 minPointSize = -1) {
3295 let a = oldSets.filter(set => set.maxPoint > 0 || !set.isEmpty && set.maxPoint >= minPointSize);
3296 let b = newSets.filter(set => set.maxPoint > 0 || !set.isEmpty && set.maxPoint >= minPointSize);
3297 let sharedChunks = findSharedChunks(a, b, textDiff);
3298 let sideA = new SpanCursor(a, sharedChunks, minPointSize);
3299 let sideB = new SpanCursor(b, sharedChunks, minPointSize);
3300 textDiff.iterGaps((fromA, fromB, length) => compare(sideA, fromA, sideB, fromB, length, comparator));
3301 if (textDiff.empty && textDiff.length == 0)
3302 compare(sideA, 0, sideB, 0, 0, comparator);
3303 }
3304 /**
3305 Compare the contents of two groups of range sets, returning true
3306 if they are equivalent in the given range.
3307 */
3308 static eq(oldSets, newSets, from = 0, to) {
3309 if (to == null)
3310 to = 1000000000 /* C.Far */ - 1;
3311 let a = oldSets.filter(set => !set.isEmpty && newSets.indexOf(set) < 0);
3312 let b = newSets.filter(set => !set.isEmpty && oldSets.indexOf(set) < 0);
3313 if (a.length != b.length)
3314 return false;
3315 if (!a.length)
3316 return true;
3317 let sharedChunks = findSharedChunks(a, b);
3318 let sideA = new SpanCursor(a, sharedChunks, 0).goto(from), sideB = new SpanCursor(b, sharedChunks, 0).goto(from);
3319 for (;;) {
3320 if (sideA.to != sideB.to ||
3321 !sameValues(sideA.active, sideB.active) ||
3322 sideA.point && (!sideB.point || !cmpVal(sideA.point, sideB.point)))
3323 return false;
3324 if (sideA.to > to)
3325 return true;
3326 sideA.next();
3327 sideB.next();
3328 }
3329 }
3330 /**
3331 Iterate over a group of range sets at the same time, notifying
3332 the iterator about the ranges covering every given piece of
3333 content. Returns the open count (see
3334 [`SpanIterator.span`](https://codemirror.net/6/docs/ref/#state.SpanIterator.span)) at the end
3335 of the iteration.
3336 */
3337 static spans(sets, from, to, iterator,
3338 /**
3339 When given and greater than -1, only points of at least this
3340 size are taken into account.
3341 */
3342 minPointSize = -1) {
3343 let cursor = new SpanCursor(sets, null, minPointSize).goto(from), pos = from;
3344 let openRanges = cursor.openStart;
3345 for (;;) {
3346 let curTo = Math.min(cursor.to, to);
3347 if (cursor.point) {
3348 let active = cursor.activeForPoint(cursor.to);
3349 let openCount = cursor.pointFrom < from ? active.length + 1
3350 : cursor.point.startSide < 0 ? active.length
3351 : Math.min(active.length, openRanges);
3352 iterator.point(pos, curTo, cursor.point, active, openCount, cursor.pointRank);
3353 openRanges = Math.min(cursor.openEnd(curTo), active.length);
3354 }
3355 else if (curTo > pos) {
3356 iterator.span(pos, curTo, cursor.active, openRanges);
3357 openRanges = cursor.openEnd(curTo);
3358 }
3359 if (cursor.to > to)
3360 return openRanges + (cursor.point && cursor.to > to ? 1 : 0);
3361 pos = cursor.to;
3362 cursor.next();
3363 }
3364 }
3365 /**
3366 Create a range set for the given range or array of ranges. By
3367 default, this expects the ranges to be _sorted_ (by start
3368 position and, if two start at the same position,
3369 `value.startSide`). You can pass `true` as second argument to
3370 cause the method to sort them.
3371 */
3372 static of(ranges, sort = false) {
3373 let build = new RangeSetBuilder();
3374 for (let range of ranges instanceof Range ? [ranges] : sort ? lazySort(ranges) : ranges)
3375 build.add(range.from, range.to, range.value);
3376 return build.finish();
3377 }
3378 /**
3379 Join an array of range sets into a single set.
3380 */
3381 static join(sets) {
3382 if (!sets.length)
3383 return RangeSet.empty;
3384 let result = sets[sets.length - 1];
3385 for (let i = sets.length - 2; i >= 0; i--) {
3386 for (let layer = sets[i]; layer != RangeSet.empty; layer = layer.nextLayer)
3387 result = new RangeSet(layer.chunkPos, layer.chunk, result, Math.max(layer.maxPoint, result.maxPoint));
3388 }
3389 return result;
3390 }
3391}
3392/**
3393The empty set of ranges.
3394*/
3395RangeSet.empty = /*@__PURE__*/new RangeSet([], [], null, -1);
3396function lazySort(ranges) {
3397 if (ranges.length > 1)
3398 for (let prev = ranges[0], i = 1; i < ranges.length; i++) {
3399 let cur = ranges[i];
3400 if (cmpRange(prev, cur) > 0)
3401 return ranges.slice().sort(cmpRange);
3402 prev = cur;
3403 }
3404 return ranges;
3405}
3406RangeSet.empty.nextLayer = RangeSet.empty;
3407/**
3408A range set builder is a data structure that helps build up a
3409[range set](https://codemirror.net/6/docs/ref/#state.RangeSet) directly, without first allocating
3410an array of [`Range`](https://codemirror.net/6/docs/ref/#state.Range) objects.
3411*/
3412class RangeSetBuilder {
3413 finishChunk(newArrays) {
3414 this.chunks.push(new Chunk(this.from, this.to, this.value, this.maxPoint));
3415 this.chunkPos.push(this.chunkStart);
3416 this.chunkStart = -1;
3417 this.setMaxPoint = Math.max(this.setMaxPoint, this.maxPoint);
3418 this.maxPoint = -1;
3419 if (newArrays) {
3420 this.from = [];
3421 this.to = [];
3422 this.value = [];
3423 }
3424 }
3425 /**
3426 Create an empty builder.
3427 */
3428 constructor() {
3429 this.chunks = [];
3430 this.chunkPos = [];
3431 this.chunkStart = -1;
3432 this.last = null;
3433 this.lastFrom = -1000000000 /* C.Far */;
3434 this.lastTo = -1000000000 /* C.Far */;
3435 this.from = [];
3436 this.to = [];
3437 this.value = [];
3438 this.maxPoint = -1;
3439 this.setMaxPoint = -1;
3440 this.nextLayer = null;
3441 }
3442 /**
3443 Add a range. Ranges should be added in sorted (by `from` and
3444 `value.startSide`) order.
3445 */
3446 add(from, to, value) {
3447 if (!this.addInner(from, to, value))
3448 (this.nextLayer || (this.nextLayer = new RangeSetBuilder)).add(from, to, value);
3449 }
3450 /**
3451 @internal
3452 */
3453 addInner(from, to, value) {
3454 let diff = from - this.lastTo || value.startSide - this.last.endSide;
3455 if (diff <= 0 && (from - this.lastFrom || value.startSide - this.last.startSide) < 0)
3456 throw new Error("Ranges must be added sorted by `from` position and `startSide`");
3457 if (diff < 0)
3458 return false;
3459 if (this.from.length == 250 /* C.ChunkSize */)
3460 this.finishChunk(true);
3461 if (this.chunkStart < 0)
3462 this.chunkStart = from;
3463 this.from.push(from - this.chunkStart);
3464 this.to.push(to - this.chunkStart);
3465 this.last = value;
3466 this.lastFrom = from;
3467 this.lastTo = to;
3468 this.value.push(value);
3469 if (value.point)
3470 this.maxPoint = Math.max(this.maxPoint, to - from);
3471 return true;
3472 }
3473 /**
3474 @internal
3475 */
3476 addChunk(from, chunk) {
3477 if ((from - this.lastTo || chunk.value[0].startSide - this.last.endSide) < 0)
3478 return false;
3479 if (this.from.length)
3480 this.finishChunk(true);
3481 this.setMaxPoint = Math.max(this.setMaxPoint, chunk.maxPoint);
3482 this.chunks.push(chunk);
3483 this.chunkPos.push(from);
3484 let last = chunk.value.length - 1;
3485 this.last = chunk.value[last];
3486 this.lastFrom = chunk.from[last] + from;
3487 this.lastTo = chunk.to[last] + from;
3488 return true;
3489 }
3490 /**
3491 Finish the range set. Returns the new set. The builder can't be
3492 used anymore after this has been called.
3493 */
3494 finish() { return this.finishInner(RangeSet.empty); }
3495 /**
3496 @internal
3497 */
3498 finishInner(next) {
3499 if (this.from.length)
3500 this.finishChunk(false);
3501 if (this.chunks.length == 0)
3502 return next;
3503 let result = RangeSet.create(this.chunkPos, this.chunks, this.nextLayer ? this.nextLayer.finishInner(next) : next, this.setMaxPoint);
3504 this.from = null; // Make sure further `add` calls produce errors
3505 return result;
3506 }
3507}
3508function findSharedChunks(a, b, textDiff) {
3509 let inA = new Map();
3510 for (let set of a)
3511 for (let i = 0; i < set.chunk.length; i++)
3512 if (set.chunk[i].maxPoint <= 0)
3513 inA.set(set.chunk[i], set.chunkPos[i]);
3514 let shared = new Set();
3515 for (let set of b)
3516 for (let i = 0; i < set.chunk.length; i++) {
3517 let known = inA.get(set.chunk[i]);
3518 if (known != null && (textDiff ? textDiff.mapPos(known) : known) == set.chunkPos[i] &&
3519 !(textDiff === null || textDiff === void 0 ? void 0 : textDiff.touchesRange(known, known + set.chunk[i].length)))
3520 shared.add(set.chunk[i]);
3521 }
3522 return shared;
3523}
3524class LayerCursor {
3525 constructor(layer, skip, minPoint, rank = 0) {
3526 this.layer = layer;
3527 this.skip = skip;
3528 this.minPoint = minPoint;
3529 this.rank = rank;
3530 }
3531 get startSide() { return this.value ? this.value.startSide : 0; }
3532 get endSide() { return this.value ? this.value.endSide : 0; }
3533 goto(pos, side = -1000000000 /* C.Far */) {
3534 this.chunkIndex = this.rangeIndex = 0;
3535 this.gotoInner(pos, side, false);
3536 return this;
3537 }
3538 gotoInner(pos, side, forward) {
3539 while (this.chunkIndex < this.layer.chunk.length) {
3540 let next = this.layer.chunk[this.chunkIndex];
3541 if (!(this.skip && this.skip.has(next) ||
3542 this.layer.chunkEnd(this.chunkIndex) < pos ||
3543 next.maxPoint < this.minPoint))
3544 break;
3545 this.chunkIndex++;
3546 forward = false;
3547 }
3548 if (this.chunkIndex < this.layer.chunk.length) {
3549 let rangeIndex = this.layer.chunk[this.chunkIndex].findIndex(pos - this.layer.chunkPos[this.chunkIndex], side, true);
3550 if (!forward || this.rangeIndex < rangeIndex)
3551 this.setRangeIndex(rangeIndex);
3552 }
3553 this.next();
3554 }
3555 forward(pos, side) {
3556 if ((this.to - pos || this.endSide - side) < 0)
3557 this.gotoInner(pos, side, true);
3558 }
3559 next() {
3560 for (;;) {
3561 if (this.chunkIndex == this.layer.chunk.length) {
3562 this.from = this.to = 1000000000 /* C.Far */;
3563 this.value = null;
3564 break;
3565 }
3566 else {
3567 let chunkPos = this.layer.chunkPos[this.chunkIndex], chunk = this.layer.chunk[this.chunkIndex];
3568 let from = chunkPos + chunk.from[this.rangeIndex];
3569 this.from = from;
3570 this.to = chunkPos + chunk.to[this.rangeIndex];
3571 this.value = chunk.value[this.rangeIndex];
3572 this.setRangeIndex(this.rangeIndex + 1);
3573 if (this.minPoint < 0 || this.value.point && this.to - this.from >= this.minPoint)
3574 break;
3575 }
3576 }
3577 }
3578 setRangeIndex(index) {
3579 if (index == this.layer.chunk[this.chunkIndex].value.length) {
3580 this.chunkIndex++;
3581 if (this.skip) {
3582 while (this.chunkIndex < this.layer.chunk.length && this.skip.has(this.layer.chunk[this.chunkIndex]))
3583 this.chunkIndex++;
3584 }
3585 this.rangeIndex = 0;
3586 }
3587 else {
3588 this.rangeIndex = index;
3589 }
3590 }
3591 nextChunk() {
3592 this.chunkIndex++;
3593 this.rangeIndex = 0;
3594 this.next();
3595 }
3596 compare(other) {
3597 return this.from - other.from || this.startSide - other.startSide || this.rank - other.rank ||
3598 this.to - other.to || this.endSide - other.endSide;
3599 }
3600}
3601class HeapCursor {
3602 constructor(heap) {
3603 this.heap = heap;
3604 }
3605 static from(sets, skip = null, minPoint = -1) {
3606 let heap = [];
3607 for (let i = 0; i < sets.length; i++) {
3608 for (let cur = sets[i]; !cur.isEmpty; cur = cur.nextLayer) {
3609 if (cur.maxPoint >= minPoint)
3610 heap.push(new LayerCursor(cur, skip, minPoint, i));
3611 }
3612 }
3613 return heap.length == 1 ? heap[0] : new HeapCursor(heap);
3614 }
3615 get startSide() { return this.value ? this.value.startSide : 0; }
3616 goto(pos, side = -1000000000 /* C.Far */) {
3617 for (let cur of this.heap)
3618 cur.goto(pos, side);
3619 for (let i = this.heap.length >> 1; i >= 0; i--)
3620 heapBubble(this.heap, i);
3621 this.next();
3622 return this;
3623 }
3624 forward(pos, side) {
3625 for (let cur of this.heap)
3626 cur.forward(pos, side);
3627 for (let i = this.heap.length >> 1; i >= 0; i--)
3628 heapBubble(this.heap, i);
3629 if ((this.to - pos || this.value.endSide - side) < 0)
3630 this.next();
3631 }
3632 next() {
3633 if (this.heap.length == 0) {
3634 this.from = this.to = 1000000000 /* C.Far */;
3635 this.value = null;
3636 this.rank = -1;
3637 }
3638 else {
3639 let top = this.heap[0];
3640 this.from = top.from;
3641 this.to = top.to;
3642 this.value = top.value;
3643 this.rank = top.rank;
3644 if (top.value)
3645 top.next();
3646 heapBubble(this.heap, 0);
3647 }
3648 }
3649}
3650function heapBubble(heap, index) {
3651 for (let cur = heap[index];;) {
3652 let childIndex = (index << 1) + 1;
3653 if (childIndex >= heap.length)
3654 break;
3655 let child = heap[childIndex];
3656 if (childIndex + 1 < heap.length && child.compare(heap[childIndex + 1]) >= 0) {
3657 child = heap[childIndex + 1];
3658 childIndex++;
3659 }
3660 if (cur.compare(child) < 0)
3661 break;
3662 heap[childIndex] = cur;
3663 heap[index] = child;
3664 index = childIndex;
3665 }
3666}
3667class SpanCursor {
3668 constructor(sets, skip, minPoint) {
3669 this.minPoint = minPoint;
3670 this.active = [];
3671 this.activeTo = [];
3672 this.activeRank = [];
3673 this.minActive = -1;
3674 // A currently active point range, if any
3675 this.point = null;
3676 this.pointFrom = 0;
3677 this.pointRank = 0;
3678 this.to = -1000000000 /* C.Far */;
3679 this.endSide = 0;
3680 // The amount of open active ranges at the start of the iterator.
3681 // Not including points.
3682 this.openStart = -1;
3683 this.cursor = HeapCursor.from(sets, skip, minPoint);
3684 }
3685 goto(pos, side = -1000000000 /* C.Far */) {
3686 this.cursor.goto(pos, side);
3687 this.active.length = this.activeTo.length = this.activeRank.length = 0;
3688 this.minActive = -1;
3689 this.to = pos;
3690 this.endSide = side;
3691 this.openStart = -1;
3692 this.next();
3693 return this;
3694 }
3695 forward(pos, side) {
3696 while (this.minActive > -1 && (this.activeTo[this.minActive] - pos || this.active[this.minActive].endSide - side) < 0)
3697 this.removeActive(this.minActive);
3698 this.cursor.forward(pos, side);
3699 }
3700 removeActive(index) {
3701 remove(this.active, index);
3702 remove(this.activeTo, index);
3703 remove(this.activeRank, index);
3704 this.minActive = findMinIndex(this.active, this.activeTo);
3705 }
3706 addActive(trackOpen) {
3707 let i = 0, { value, to, rank } = this.cursor;
3708 // Organize active marks by rank first, then by size
3709 while (i < this.activeRank.length && (rank - this.activeRank[i] || to - this.activeTo[i]) > 0)
3710 i++;
3711 insert(this.active, i, value);
3712 insert(this.activeTo, i, to);
3713 insert(this.activeRank, i, rank);
3714 if (trackOpen)
3715 insert(trackOpen, i, this.cursor.from);
3716 this.minActive = findMinIndex(this.active, this.activeTo);
3717 }
3718 // After calling this, if `this.point` != null, the next range is a
3719 // point. Otherwise, it's a regular range, covered by `this.active`.
3720 next() {
3721 let from = this.to, wasPoint = this.point;
3722 this.point = null;
3723 let trackOpen = this.openStart < 0 ? [] : null;
3724 for (;;) {
3725 let a = this.minActive;
3726 if (a > -1 && (this.activeTo[a] - this.cursor.from || this.active[a].endSide - this.cursor.startSide) < 0) {
3727 if (this.activeTo[a] > from) {
3728 this.to = this.activeTo[a];
3729 this.endSide = this.active[a].endSide;
3730 break;
3731 }
3732 this.removeActive(a);
3733 if (trackOpen)
3734 remove(trackOpen, a);
3735 }
3736 else if (!this.cursor.value) {
3737 this.to = this.endSide = 1000000000 /* C.Far */;
3738 break;
3739 }
3740 else if (this.cursor.from > from) {
3741 this.to = this.cursor.from;
3742 this.endSide = this.cursor.startSide;
3743 break;
3744 }
3745 else {
3746 let nextVal = this.cursor.value;
3747 if (!nextVal.point) { // Opening a range
3748 this.addActive(trackOpen);
3749 this.cursor.next();
3750 }
3751 else if (wasPoint && this.cursor.to == this.to && this.cursor.from < this.cursor.to) {
3752 // Ignore any non-empty points that end precisely at the end of the prev point
3753 this.cursor.next();
3754 }
3755 else { // New point
3756 this.point = nextVal;
3757 this.pointFrom = this.cursor.from;
3758 this.pointRank = this.cursor.rank;
3759 this.to = this.cursor.to;
3760 this.endSide = nextVal.endSide;
3761 this.cursor.next();
3762 this.forward(this.to, this.endSide);
3763 break;
3764 }
3765 }
3766 }
3767 if (trackOpen) {
3768 this.openStart = 0;
3769 for (let i = trackOpen.length - 1; i >= 0 && trackOpen[i] < from; i--)
3770 this.openStart++;
3771 }
3772 }
3773 activeForPoint(to) {
3774 if (!this.active.length)
3775 return this.active;
3776 let active = [];
3777 for (let i = this.active.length - 1; i >= 0; i--) {
3778 if (this.activeRank[i] < this.pointRank)
3779 break;
3780 if (this.activeTo[i] > to || this.activeTo[i] == to && this.active[i].endSide >= this.point.endSide)
3781 active.push(this.active[i]);
3782 }
3783 return active.reverse();
3784 }
3785 openEnd(to) {
3786 let open = 0;
3787 for (let i = this.activeTo.length - 1; i >= 0 && this.activeTo[i] > to; i--)
3788 open++;
3789 return open;
3790 }
3791}
3792function compare(a, startA, b, startB, length, comparator) {
3793 a.goto(startA);
3794 b.goto(startB);
3795 let endB = startB + length;
3796 let pos = startB, dPos = startB - startA;
3797 let bounds = !!comparator.boundChange;
3798 for (let boundChange = false;;) {
3799 let dEnd = (a.to + dPos) - b.to, diff = dEnd || a.endSide - b.endSide;
3800 let end = diff < 0 ? a.to + dPos : b.to, clipEnd = Math.min(end, endB);
3801 let point = a.point || b.point;
3802 if (point) {
3803 if (!(a.point && b.point && cmpVal(a.point, b.point) &&
3804 sameValues(a.activeForPoint(a.to), b.activeForPoint(b.to))))
3805 comparator.comparePoint(pos, clipEnd, a.point, b.point);
3806 boundChange = false;
3807 }
3808 else {
3809 if (boundChange)
3810 comparator.boundChange(pos);
3811 if (clipEnd > pos && !sameValues(a.active, b.active))
3812 comparator.compareRange(pos, clipEnd, a.active, b.active);
3813 if (bounds && clipEnd < endB && (dEnd || a.openEnd(end) != b.openEnd(end)))
3814 boundChange = true;
3815 }
3816 if (end > endB)
3817 break;
3818 pos = end;
3819 if (diff <= 0)
3820 a.next();
3821 if (diff >= 0)
3822 b.next();
3823 }
3824}
3825function sameValues(a, b) {
3826 if (a.length != b.length)
3827 return false;
3828 for (let i = 0; i < a.length; i++)
3829 if (a[i] != b[i] && !cmpVal(a[i], b[i]))
3830 return false;
3831 return true;
3832}
3833function remove(array, index) {
3834 for (let i = index, e = array.length - 1; i < e; i++)
3835 array[i] = array[i + 1];
3836 array.pop();
3837}
3838function insert(array, index, value) {
3839 for (let i = array.length - 1; i >= index; i--)
3840 array[i + 1] = array[i];
3841 array[index] = value;
3842}
3843function findMinIndex(value, array) {
3844 let found = -1, foundPos = 1000000000 /* C.Far */;
3845 for (let i = 0; i < array.length; i++)
3846 if ((array[i] - foundPos || value[i].endSide - value[found].endSide) < 0) {
3847 found = i;
3848 foundPos = array[i];
3849 }
3850 return found;
3851}
3852
3853/**
3854Count the column position at the given offset into the string,
3855taking extending characters and tab size into account.
3856*/
3857function countColumn(string, tabSize, to = string.length) {
3858 let n = 0;
3859 for (let i = 0; i < to && i < string.length;) {
3860 if (string.charCodeAt(i) == 9) {
3861 n += tabSize - (n % tabSize);
3862 i++;
3863 }
3864 else {
3865 n++;
3866 i = findClusterBreak(string, i);
3867 }
3868 }
3869 return n;
3870}
3871/**
3872Find the offset that corresponds to the given column position in a
3873string, taking extending characters and tab size into account. By
3874default, the string length is returned when it is too short to
3875reach the column. Pass `strict` true to make it return -1 in that
3876situation.
3877*/
3878function findColumn(string, col, tabSize, strict) {
3879 for (let i = 0, n = 0;;) {
3880 if (n >= col)
3881 return i;
3882 if (i == string.length)
3883 break;
3884 n += string.charCodeAt(i) == 9 ? tabSize - (n % tabSize) : 1;
3885 i = findClusterBreak(string, i);
3886 }
3887 return strict === true ? -1 : string.length;
3888}
3889
3890export { 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 };