Proyectos de Subversion Moodle

Rev

| Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 1
/**
2
The data structure for documents. @nonabstract
3
*/
4
class Text {
5
    /**
6
    Get the line description around the given position.
7
    */
8
    lineAt(pos) {
9
        if (pos < 0 || pos > this.length)
10
            throw new RangeError(`Invalid position ${pos} in document of length ${this.length}`);
11
        return this.lineInner(pos, false, 1, 0);
12
    }
13
    /**
14
    Get the description for the given (1-based) line number.
15
    */
16
    line(n) {
17
        if (n < 1 || n > this.lines)
18
            throw new RangeError(`Invalid line number ${n} in ${this.lines}-line document`);
19
        return this.lineInner(n, true, 1, 0);
20
    }
21
    /**
22
    Replace a range of the text with the given content.
23
    */
24
    replace(from, to, text) {
25
        [from, to] = clip(this, from, to);
26
        let parts = [];
27
        this.decompose(0, from, parts, 2 /* Open.To */);
28
        if (text.length)
29
            text.decompose(0, text.length, parts, 1 /* Open.From */ | 2 /* Open.To */);
30
        this.decompose(to, this.length, parts, 1 /* Open.From */);
31
        return TextNode.from(parts, this.length - (to - from) + text.length);
32
    }
33
    /**
34
    Append another document to this one.
35
    */
36
    append(other) {
37
        return this.replace(this.length, this.length, other);
38
    }
39
    /**
40
    Retrieve the text between the given points.
41
    */
42
    slice(from, to = this.length) {
43
        [from, to] = clip(this, from, to);
44
        let parts = [];
45
        this.decompose(from, to, parts, 0);
46
        return TextNode.from(parts, to - from);
47
    }
48
    /**
49
    Test whether this text is equal to another instance.
50
    */
51
    eq(other) {
52
        if (other == this)
53
            return true;
54
        if (other.length != this.length || other.lines != this.lines)
55
            return false;
56
        let start = this.scanIdentical(other, 1), end = this.length - this.scanIdentical(other, -1);
57
        let a = new RawTextCursor(this), b = new RawTextCursor(other);
58
        for (let skip = start, pos = start;;) {
59
            a.next(skip);
60
            b.next(skip);
61
            skip = 0;
62
            if (a.lineBreak != b.lineBreak || a.done != b.done || a.value != b.value)
63
                return false;
64
            pos += a.value.length;
65
            if (a.done || pos >= end)
66
                return true;
67
        }
68
    }
69
    /**
70
    Iterate over the text. When `dir` is `-1`, iteration happens
71
    from end to start. This will return lines and the breaks between
72
    them as separate strings.
73
    */
74
    iter(dir = 1) { return new RawTextCursor(this, dir); }
75
    /**
76
    Iterate over a range of the text. When `from` > `to`, the
77
    iterator will run in reverse.
78
    */
79
    iterRange(from, to = this.length) { return new PartialTextCursor(this, from, to); }
80
    /**
81
    Return a cursor that iterates over the given range of lines,
82
    _without_ returning the line breaks between, and yielding empty
83
    strings for empty lines.
84
 
85
    When `from` and `to` are given, they should be 1-based line numbers.
86
    */
87
    iterLines(from, to) {
88
        let inner;
89
        if (from == null) {
90
            inner = this.iter();
91
        }
92
        else {
93
            if (to == null)
94
                to = this.lines + 1;
95
            let start = this.line(from).from;
96
            inner = this.iterRange(start, Math.max(start, to == this.lines + 1 ? this.length : to <= 1 ? 0 : this.line(to - 1).to));
97
        }
98
        return new LineCursor(inner);
99
    }
100
    /**
101
    Return the document as a string, using newline characters to
102
    separate lines.
103
    */
104
    toString() { return this.sliceString(0); }
105
    /**
106
    Convert the document to an array of lines (which can be
107
    deserialized again via [`Text.of`](https://codemirror.net/6/docs/ref/#state.Text^of)).
108
    */
109
    toJSON() {
110
        let lines = [];
111
        this.flatten(lines);
112
        return lines;
113
    }
114
    /**
115
    @internal
116
    */
117
    constructor() { }
118
    /**
119
    Create a `Text` instance for the given array of lines.
120
    */
121
    static of(text) {
122
        if (text.length == 0)
123
            throw new RangeError("A document must have at least one line");
124
        if (text.length == 1 && !text[0])
125
            return Text.empty;
126
        return text.length <= 32 /* Tree.Branch */ ? new TextLeaf(text) : TextNode.from(TextLeaf.split(text, []));
127
    }
128
}
129
// Leaves store an array of line strings. There are always line breaks
130
// between these strings. Leaves are limited in size and have to be
131
// contained in TextNode instances for bigger documents.
132
class TextLeaf extends Text {
133
    constructor(text, length = textLength(text)) {
134
        super();
135
        this.text = text;
136
        this.length = length;
137
    }
138
    get lines() { return this.text.length; }
139
    get children() { return null; }
140
    lineInner(target, isLine, line, offset) {
141
        for (let i = 0;; i++) {
142
            let string = this.text[i], end = offset + string.length;
143
            if ((isLine ? line : end) >= target)
144
                return new Line(offset, end, line, string);
145
            offset = end + 1;
146
            line++;
147
        }
148
    }
149
    decompose(from, to, target, open) {
150
        let text = from <= 0 && to >= this.length ? this
151
            : new TextLeaf(sliceText(this.text, from, to), Math.min(to, this.length) - Math.max(0, from));
152
        if (open & 1 /* Open.From */) {
153
            let prev = target.pop();
154
            let joined = appendText(text.text, prev.text.slice(), 0, text.length);
155
            if (joined.length <= 32 /* Tree.Branch */) {
156
                target.push(new TextLeaf(joined, prev.length + text.length));
157
            }
158
            else {
159
                let mid = joined.length >> 1;
160
                target.push(new TextLeaf(joined.slice(0, mid)), new TextLeaf(joined.slice(mid)));
161
            }
162
        }
163
        else {
164
            target.push(text);
165
        }
166
    }
167
    replace(from, to, text) {
168
        if (!(text instanceof TextLeaf))
169
            return super.replace(from, to, text);
170
        [from, to] = clip(this, from, to);
171
        let lines = appendText(this.text, appendText(text.text, sliceText(this.text, 0, from)), to);
172
        let newLen = this.length + text.length - (to - from);
173
        if (lines.length <= 32 /* Tree.Branch */)
174
            return new TextLeaf(lines, newLen);
175
        return TextNode.from(TextLeaf.split(lines, []), newLen);
176
    }
177
    sliceString(from, to = this.length, lineSep = "\n") {
178
        [from, to] = clip(this, from, to);
179
        let result = "";
180
        for (let pos = 0, i = 0; pos <= to && i < this.text.length; i++) {
181
            let line = this.text[i], end = pos + line.length;
182
            if (pos > from && i)
183
                result += lineSep;
184
            if (from < end && to > pos)
185
                result += line.slice(Math.max(0, from - pos), to - pos);
186
            pos = end + 1;
187
        }
188
        return result;
189
    }
190
    flatten(target) {
191
        for (let line of this.text)
192
            target.push(line);
193
    }
194
    scanIdentical() { return 0; }
195
    static split(text, target) {
196
        let part = [], len = -1;
197
        for (let line of text) {
198
            part.push(line);
199
            len += line.length + 1;
200
            if (part.length == 32 /* Tree.Branch */) {
201
                target.push(new TextLeaf(part, len));
202
                part = [];
203
                len = -1;
204
            }
205
        }
206
        if (len > -1)
207
            target.push(new TextLeaf(part, len));
208
        return target;
209
    }
210
}
211
// Nodes provide the tree structure of the `Text` type. They store a
212
// number of other nodes or leaves, taking care to balance themselves
213
// on changes. There are implied line breaks _between_ the children of
214
// a node (but not before the first or after the last child).
215
class TextNode extends Text {
216
    constructor(children, length) {
217
        super();
218
        this.children = children;
219
        this.length = length;
220
        this.lines = 0;
221
        for (let child of children)
222
            this.lines += child.lines;
223
    }
224
    lineInner(target, isLine, line, offset) {
225
        for (let i = 0;; i++) {
226
            let child = this.children[i], end = offset + child.length, endLine = line + child.lines - 1;
227
            if ((isLine ? endLine : end) >= target)
228
                return child.lineInner(target, isLine, line, offset);
229
            offset = end + 1;
230
            line = endLine + 1;
231
        }
232
    }
233
    decompose(from, to, target, open) {
234
        for (let i = 0, pos = 0; pos <= to && i < this.children.length; i++) {
235
            let child = this.children[i], end = pos + child.length;
236
            if (from <= end && to >= pos) {
237
                let childOpen = open & ((pos <= from ? 1 /* Open.From */ : 0) | (end >= to ? 2 /* Open.To */ : 0));
238
                if (pos >= from && end <= to && !childOpen)
239
                    target.push(child);
240
                else
241
                    child.decompose(from - pos, to - pos, target, childOpen);
242
            }
243
            pos = end + 1;
244
        }
245
    }
246
    replace(from, to, text) {
247
        [from, to] = clip(this, from, to);
248
        if (text.lines < this.lines)
249
            for (let i = 0, pos = 0; i < this.children.length; i++) {
250
                let child = this.children[i], end = pos + child.length;
251
                // Fast path: if the change only affects one child and the
252
                // child's size remains in the acceptable range, only update
253
                // that child
254
                if (from >= pos && to <= end) {
255
                    let updated = child.replace(from - pos, to - pos, text);
256
                    let totalLines = this.lines - child.lines + updated.lines;
257
                    if (updated.lines < (totalLines >> (5 /* Tree.BranchShift */ - 1)) &&
258
                        updated.lines > (totalLines >> (5 /* Tree.BranchShift */ + 1))) {
259
                        let copy = this.children.slice();
260
                        copy[i] = updated;
261
                        return new TextNode(copy, this.length - (to - from) + text.length);
262
                    }
263
                    return super.replace(pos, end, updated);
264
                }
265
                pos = end + 1;
266
            }
267
        return super.replace(from, to, text);
268
    }
269
    sliceString(from, to = this.length, lineSep = "\n") {
270
        [from, to] = clip(this, from, to);
271
        let result = "";
272
        for (let i = 0, pos = 0; i < this.children.length && pos <= to; i++) {
273
            let child = this.children[i], end = pos + child.length;
274
            if (pos > from && i)
275
                result += lineSep;
276
            if (from < end && to > pos)
277
                result += child.sliceString(from - pos, to - pos, lineSep);
278
            pos = end + 1;
279
        }
280
        return result;
281
    }
282
    flatten(target) {
283
        for (let child of this.children)
284
            child.flatten(target);
285
    }
286
    scanIdentical(other, dir) {
287
        if (!(other instanceof TextNode))
288
            return 0;
289
        let length = 0;
290
        let [iA, iB, eA, eB] = dir > 0 ? [0, 0, this.children.length, other.children.length]
291
            : [this.children.length - 1, other.children.length - 1, -1, -1];
292
        for (;; iA += dir, iB += dir) {
293
            if (iA == eA || iB == eB)
294
                return length;
295
            let chA = this.children[iA], chB = other.children[iB];
296
            if (chA != chB)
297
                return length + chA.scanIdentical(chB, dir);
298
            length += chA.length + 1;
299
        }
300
    }
301
    static from(children, length = children.reduce((l, ch) => l + ch.length + 1, -1)) {
302
        let lines = 0;
303
        for (let ch of children)
304
            lines += ch.lines;
305
        if (lines < 32 /* Tree.Branch */) {
306
            let flat = [];
307
            for (let ch of children)
308
                ch.flatten(flat);
309
            return new TextLeaf(flat, length);
310
        }
311
        let chunk = Math.max(32 /* Tree.Branch */, lines >> 5 /* Tree.BranchShift */), maxChunk = chunk << 1, minChunk = chunk >> 1;
312
        let chunked = [], currentLines = 0, currentLen = -1, currentChunk = [];
313
        function add(child) {
314
            let last;
315
            if (child.lines > maxChunk && child instanceof TextNode) {
316
                for (let node of child.children)
317
                    add(node);
318
            }
319
            else if (child.lines > minChunk && (currentLines > minChunk || !currentLines)) {
320
                flush();
321
                chunked.push(child);
322
            }
323
            else if (child instanceof TextLeaf && currentLines &&
324
                (last = currentChunk[currentChunk.length - 1]) instanceof TextLeaf &&
325
                child.lines + last.lines <= 32 /* Tree.Branch */) {
326
                currentLines += child.lines;
327
                currentLen += child.length + 1;
328
                currentChunk[currentChunk.length - 1] = new TextLeaf(last.text.concat(child.text), last.length + 1 + child.length);
329
            }
330
            else {
331
                if (currentLines + child.lines > chunk)
332
                    flush();
333
                currentLines += child.lines;
334
                currentLen += child.length + 1;
335
                currentChunk.push(child);
336
            }
337
        }
338
        function flush() {
339
            if (currentLines == 0)
340
                return;
341
            chunked.push(currentChunk.length == 1 ? currentChunk[0] : TextNode.from(currentChunk, currentLen));
342
            currentLen = -1;
343
            currentLines = currentChunk.length = 0;
344
        }
345
        for (let child of children)
346
            add(child);
347
        flush();
348
        return chunked.length == 1 ? chunked[0] : new TextNode(chunked, length);
349
    }
350
}
351
Text.empty = /*@__PURE__*/new TextLeaf([""], 0);
352
function textLength(text) {
353
    let length = -1;
354
    for (let line of text)
355
        length += line.length + 1;
356
    return length;
357
}
358
function appendText(text, target, from = 0, to = 1e9) {
359
    for (let pos = 0, i = 0, first = true; i < text.length && pos <= to; i++) {
360
        let line = text[i], end = pos + line.length;
361
        if (end >= from) {
362
            if (end > to)
363
                line = line.slice(0, to - pos);
364
            if (pos < from)
365
                line = line.slice(from - pos);
366
            if (first) {
367
                target[target.length - 1] += line;
368
                first = false;
369
            }
370
            else
371
                target.push(line);
372
        }
373
        pos = end + 1;
374
    }
375
    return target;
376
}
377
function sliceText(text, from, to) {
378
    return appendText(text, [""], from, to);
379
}
380
class RawTextCursor {
381
    constructor(text, dir = 1) {
382
        this.dir = dir;
383
        this.done = false;
384
        this.lineBreak = false;
385
        this.value = "";
386
        this.nodes = [text];
387
        this.offsets = [dir > 0 ? 1 : (text instanceof TextLeaf ? text.text.length : text.children.length) << 1];
388
    }
389
    nextInner(skip, dir) {
390
        this.done = this.lineBreak = false;
391
        for (;;) {
392
            let last = this.nodes.length - 1;
393
            let top = this.nodes[last], offsetValue = this.offsets[last], offset = offsetValue >> 1;
394
            let size = top instanceof TextLeaf ? top.text.length : top.children.length;
395
            if (offset == (dir > 0 ? size : 0)) {
396
                if (last == 0) {
397
                    this.done = true;
398
                    this.value = "";
399
                    return this;
400
                }
401
                if (dir > 0)
402
                    this.offsets[last - 1]++;
403
                this.nodes.pop();
404
                this.offsets.pop();
405
            }
406
            else if ((offsetValue & 1) == (dir > 0 ? 0 : 1)) {
407
                this.offsets[last] += dir;
408
                if (skip == 0) {
409
                    this.lineBreak = true;
410
                    this.value = "\n";
411
                    return this;
412
                }
413
                skip--;
414
            }
415
            else if (top instanceof TextLeaf) {
416
                // Move to the next string
417
                let next = top.text[offset + (dir < 0 ? -1 : 0)];
418
                this.offsets[last] += dir;
419
                if (next.length > Math.max(0, skip)) {
420
                    this.value = skip == 0 ? next : dir > 0 ? next.slice(skip) : next.slice(0, next.length - skip);
421
                    return this;
422
                }
423
                skip -= next.length;
424
            }
425
            else {
426
                let next = top.children[offset + (dir < 0 ? -1 : 0)];
427
                if (skip > next.length) {
428
                    skip -= next.length;
429
                    this.offsets[last] += dir;
430
                }
431
                else {
432
                    if (dir < 0)
433
                        this.offsets[last]--;
434
                    this.nodes.push(next);
435
                    this.offsets.push(dir > 0 ? 1 : (next instanceof TextLeaf ? next.text.length : next.children.length) << 1);
436
                }
437
            }
438
        }
439
    }
440
    next(skip = 0) {
441
        if (skip < 0) {
442
            this.nextInner(-skip, (-this.dir));
443
            skip = this.value.length;
444
        }
445
        return this.nextInner(skip, this.dir);
446
    }
447
}
448
class PartialTextCursor {
449
    constructor(text, start, end) {
450
        this.value = "";
451
        this.done = false;
452
        this.cursor = new RawTextCursor(text, start > end ? -1 : 1);
453
        this.pos = start > end ? text.length : 0;
454
        this.from = Math.min(start, end);
455
        this.to = Math.max(start, end);
456
    }
457
    nextInner(skip, dir) {
458
        if (dir < 0 ? this.pos <= this.from : this.pos >= this.to) {
459
            this.value = "";
460
            this.done = true;
461
            return this;
462
        }
463
        skip += Math.max(0, dir < 0 ? this.pos - this.to : this.from - this.pos);
464
        let limit = dir < 0 ? this.pos - this.from : this.to - this.pos;
465
        if (skip > limit)
466
            skip = limit;
467
        limit -= skip;
468
        let { value } = this.cursor.next(skip);
469
        this.pos += (value.length + skip) * dir;
470
        this.value = value.length <= limit ? value : dir < 0 ? value.slice(value.length - limit) : value.slice(0, limit);
471
        this.done = !this.value;
472
        return this;
473
    }
474
    next(skip = 0) {
475
        if (skip < 0)
476
            skip = Math.max(skip, this.from - this.pos);
477
        else if (skip > 0)
478
            skip = Math.min(skip, this.to - this.pos);
479
        return this.nextInner(skip, this.cursor.dir);
480
    }
481
    get lineBreak() { return this.cursor.lineBreak && this.value != ""; }
482
}
483
class LineCursor {
484
    constructor(inner) {
485
        this.inner = inner;
486
        this.afterBreak = true;
487
        this.value = "";
488
        this.done = false;
489
    }
490
    next(skip = 0) {
491
        let { done, lineBreak, value } = this.inner.next(skip);
492
        if (done && this.afterBreak) {
493
            this.value = "";
494
            this.afterBreak = false;
495
        }
496
        else if (done) {
497
            this.done = true;
498
            this.value = "";
499
        }
500
        else if (lineBreak) {
501
            if (this.afterBreak) {
502
                this.value = "";
503
            }
504
            else {
505
                this.afterBreak = true;
506
                this.next();
507
            }
508
        }
509
        else {
510
            this.value = value;
511
            this.afterBreak = false;
512
        }
513
        return this;
514
    }
515
    get lineBreak() { return false; }
516
}
517
if (typeof Symbol != "undefined") {
518
    Text.prototype[Symbol.iterator] = function () { return this.iter(); };
519
    RawTextCursor.prototype[Symbol.iterator] = PartialTextCursor.prototype[Symbol.iterator] =
520
        LineCursor.prototype[Symbol.iterator] = function () { return this; };
521
}
522
/**
523
This type describes a line in the document. It is created
524
on-demand when lines are [queried](https://codemirror.net/6/docs/ref/#state.Text.lineAt).
525
*/
526
class Line {
527
    /**
528
    @internal
529
    */
530
    constructor(
531
    /**
532
    The position of the start of the line.
533
    */
534
    from,
535
    /**
536
    The position at the end of the line (_before_ the line break,
537
    or at the end of document for the last line).
538
    */
539
    to,
540
    /**
541
    This line's line number (1-based).
542
    */
543
    number,
544
    /**
545
    The line's content.
546
    */
547
    text) {
548
        this.from = from;
549
        this.to = to;
550
        this.number = number;
551
        this.text = text;
552
    }
553
    /**
554
    The length of the line (not including any line break after it).
555
    */
556
    get length() { return this.to - this.from; }
557
}
558
function clip(text, from, to) {
559
    from = Math.max(0, Math.min(text.length, from));
560
    return [from, Math.max(from, Math.min(text.length, to))];
561
}
562
 
563
// Compressed representation of the Grapheme_Cluster_Break=Extend
564
// information from
565
// http://www.unicode.org/Public/13.0.0/ucd/auxiliary/GraphemeBreakProperty.txt.
566
// Each pair of elements represents a range, as an offet from the
567
// previous range and a length. Numbers are in base-36, with the empty
568
// string being a shorthand for 1.
569
let extend = /*@__PURE__*/"lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,3b,f,,w,1j,,,,4,8,4,,3,7,a,2,t,,1m,,,,2,4,8,,9,,a,2,q,,2,2,1l,,4,2,4,2,2,3,3,,u,2,3,,b,2,1l,,4,5,,2,4,,k,2,m,6,,,1m,,,2,,4,8,,7,3,a,2,u,,1n,,,,c,,9,,14,,3,,1l,3,5,3,,4,7,2,b,2,t,,1m,,2,,2,,3,,5,2,7,2,b,2,s,2,1l,2,,,2,4,8,,9,,a,2,t,,20,,4,,2,3,,,8,,29,,2,7,c,8,2q,,2,9,b,6,22,2,r,,,,,,1j,e,,5,,2,5,b,,10,9,,2u,4,,6,,2,2,2,p,2,4,3,g,4,d,,2,2,6,,f,,jj,3,qa,3,t,3,t,2,u,2,1s,2,,7,8,,2,b,9,,19,3,3b,2,y,,3a,3,4,2,9,,6,3,63,2,2,,1m,,,7,,,,,2,8,6,a,2,,1c,h,1r,4,1c,7,,,5,,14,9,c,2,w,4,2,2,,3,1k,,,2,3,,,3,1m,8,2,2,48,3,,d,,7,4,,6,,3,2,5i,1m,,5,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,p,2,5,,47,2,q,i,d,,12,8,p,b,1a,3,1c,,2,4,2,2,13,,1v,6,2,2,2,2,c,,8,,1b,,1f,,,3,2,2,5,2,,,16,2,8,,6m,,2,,4,,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,ar,2,49,b,4w,,1i,f,1k,3,1d,4,2,2,1x,3,10,5,,8,1q,,c,2,1g,9,a,4,2,,2n,3,2,,,2,6,,4g,,3,8,l,2,1l,2,,,,,m,,e,7,3,5,5f,8,2,3,,,n,,29,,2,6,,,2,,,2,,2,6j,,2,4,6,2,,2,r,2,2d,8,2,,,2,2y,,,,2,6,,,2t,3,2,4,,5,77,9,,2,6t,,a,2,,,4,,40,4,2,2,4,,w,a,14,6,2,4,8,,9,6,2,3,1a,d,,2,ba,7,,6,,,2a,m,2,7,,2,,2,3e,6,3,,,2,,7,,,20,2,3,,,,9n,2,f0b,5,1n,7,t4,,1r,4,29,,f5k,2,43q,,,3,4,5,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,79,7,c5,4,15s,7,31,7,240,5,gx7k,2o,3k,6o".split(",").map(s => s ? parseInt(s, 36) : 1);
570
// Convert offsets into absolute values
571
for (let i = 1; i < extend.length; i++)
572
    extend[i] += extend[i - 1];
573
function isExtendingChar(code) {
574
    for (let i = 1; i < extend.length; i += 2)
575
        if (extend[i] > code)
576
            return extend[i - 1] <= code;
577
    return false;
578
}
579
function isRegionalIndicator(code) {
580
    return code >= 0x1F1E6 && code <= 0x1F1FF;
581
}
582
const ZWJ = 0x200d;
583
/**
584
Returns a next grapheme cluster break _after_ (not equal to)
585
`pos`, if `forward` is true, or before otherwise. Returns `pos`
586
itself if no further cluster break is available in the string.
587
Moves across surrogate pairs, extending characters (when
588
`includeExtending` is true), characters joined with zero-width
589
joiners, and flag emoji.
590
*/
591
function findClusterBreak(str, pos, forward = true, includeExtending = true) {
592
    return (forward ? nextClusterBreak : prevClusterBreak)(str, pos, includeExtending);
593
}
594
function nextClusterBreak(str, pos, includeExtending) {
595
    if (pos == str.length)
596
        return pos;
597
    // If pos is in the middle of a surrogate pair, move to its start
598
    if (pos && surrogateLow(str.charCodeAt(pos)) && surrogateHigh(str.charCodeAt(pos - 1)))
599
        pos--;
600
    let prev = codePointAt(str, pos);
601
    pos += codePointSize(prev);
602
    while (pos < str.length) {
603
        let next = codePointAt(str, pos);
604
        if (prev == ZWJ || next == ZWJ || includeExtending && isExtendingChar(next)) {
605
            pos += codePointSize(next);
606
            prev = next;
607
        }
608
        else if (isRegionalIndicator(next)) {
609
            let countBefore = 0, i = pos - 2;
610
            while (i >= 0 && isRegionalIndicator(codePointAt(str, i))) {
611
                countBefore++;
612
                i -= 2;
613
            }
614
            if (countBefore % 2 == 0)
615
                break;
616
            else
617
                pos += 2;
618
        }
619
        else {
620
            break;
621
        }
622
    }
623
    return pos;
624
}
625
function prevClusterBreak(str, pos, includeExtending) {
626
    while (pos > 0) {
627
        let found = nextClusterBreak(str, pos - 2, includeExtending);
628
        if (found < pos)
629
            return found;
630
        pos--;
631
    }
632
    return 0;
633
}
634
function surrogateLow(ch) { return ch >= 0xDC00 && ch < 0xE000; }
635
function surrogateHigh(ch) { return ch >= 0xD800 && ch < 0xDC00; }
636
/**
637
Find the code point at the given position in a string (like the
638
[`codePointAt`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/codePointAt)
639
string method).
640
*/
641
function codePointAt(str, pos) {
642
    let code0 = str.charCodeAt(pos);
643
    if (!surrogateHigh(code0) || pos + 1 == str.length)
644
        return code0;
645
    let code1 = str.charCodeAt(pos + 1);
646
    if (!surrogateLow(code1))
647
        return code0;
648
    return ((code0 - 0xd800) << 10) + (code1 - 0xdc00) + 0x10000;
649
}
650
/**
651
Given a Unicode codepoint, return the JavaScript string that
652
respresents it (like
653
[`String.fromCodePoint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCodePoint)).
654
*/
655
function fromCodePoint(code) {
656
    if (code <= 0xffff)
657
        return String.fromCharCode(code);
658
    code -= 0x10000;
659
    return String.fromCharCode((code >> 10) + 0xd800, (code & 1023) + 0xdc00);
660
}
661
/**
662
The amount of positions a character takes up a JavaScript string.
663
*/
664
function codePointSize(code) { return code < 0x10000 ? 1 : 2; }
665
 
666
const DefaultSplit = /\r\n?|\n/;
667
/**
668
Distinguishes different ways in which positions can be mapped.
669
*/
670
var MapMode = /*@__PURE__*/(function (MapMode) {
671
    /**
672
    Map a position to a valid new position, even when its context
673
    was deleted.
674
    */
675
    MapMode[MapMode["Simple"] = 0] = "Simple";
676
    /**
677
    Return null if deletion happens across the position.
678
    */
679
    MapMode[MapMode["TrackDel"] = 1] = "TrackDel";
680
    /**
681
    Return null if the character _before_ the position is deleted.
682
    */
683
    MapMode[MapMode["TrackBefore"] = 2] = "TrackBefore";
684
    /**
685
    Return null if the character _after_ the position is deleted.
686
    */
687
    MapMode[MapMode["TrackAfter"] = 3] = "TrackAfter";
688
return MapMode})(MapMode || (MapMode = {}));
689
/**
690
A change description is a variant of [change set](https://codemirror.net/6/docs/ref/#state.ChangeSet)
691
that doesn't store the inserted text. As such, it can't be
692
applied, but is cheaper to store and manipulate.
693
*/
694
class ChangeDesc {
695
    // Sections are encoded as pairs of integers. The first is the
696
    // length in the current document, and the second is -1 for
697
    // unaffected sections, and the length of the replacement content
698
    // otherwise. So an insertion would be (0, n>0), a deletion (n>0,
699
    // 0), and a replacement two positive numbers.
700
    /**
701
    @internal
702
    */
703
    constructor(
704
    /**
705
    @internal
706
    */
707
    sections) {
708
        this.sections = sections;
709
    }
710
    /**
711
    The length of the document before the change.
712
    */
713
    get length() {
714
        let result = 0;
715
        for (let i = 0; i < this.sections.length; i += 2)
716
            result += this.sections[i];
717
        return result;
718
    }
719
    /**
720
    The length of the document after the change.
721
    */
722
    get newLength() {
723
        let result = 0;
724
        for (let i = 0; i < this.sections.length; i += 2) {
725
            let ins = this.sections[i + 1];
726
            result += ins < 0 ? this.sections[i] : ins;
727
        }
728
        return result;
729
    }
730
    /**
731
    False when there are actual changes in this set.
732
    */
733
    get empty() { return this.sections.length == 0 || this.sections.length == 2 && this.sections[1] < 0; }
734
    /**
735
    Iterate over the unchanged parts left by these changes. `posA`
736
    provides the position of the range in the old document, `posB`
737
    the new position in the changed document.
738
    */
739
    iterGaps(f) {
740
        for (let i = 0, posA = 0, posB = 0; i < this.sections.length;) {
741
            let len = this.sections[i++], ins = this.sections[i++];
742
            if (ins < 0) {
743
                f(posA, posB, len);
744
                posB += len;
745
            }
746
            else {
747
                posB += ins;
748
            }
749
            posA += len;
750
        }
751
    }
752
    /**
753
    Iterate over the ranges changed by these changes. (See
754
    [`ChangeSet.iterChanges`](https://codemirror.net/6/docs/ref/#state.ChangeSet.iterChanges) for a
755
    variant that also provides you with the inserted text.)
756
    `fromA`/`toA` provides the extent of the change in the starting
757
    document, `fromB`/`toB` the extent of the replacement in the
758
    changed document.
759
 
760
    When `individual` is true, adjacent changes (which are kept
761
    separate for [position mapping](https://codemirror.net/6/docs/ref/#state.ChangeDesc.mapPos)) are
762
    reported separately.
763
    */
764
    iterChangedRanges(f, individual = false) {
765
        iterChanges(this, f, individual);
766
    }
767
    /**
768
    Get a description of the inverted form of these changes.
769
    */
770
    get invertedDesc() {
771
        let sections = [];
772
        for (let i = 0; i < this.sections.length;) {
773
            let len = this.sections[i++], ins = this.sections[i++];
774
            if (ins < 0)
775
                sections.push(len, ins);
776
            else
777
                sections.push(ins, len);
778
        }
779
        return new ChangeDesc(sections);
780
    }
781
    /**
782
    Compute the combined effect of applying another set of changes
783
    after this one. The length of the document after this set should
784
    match the length before `other`.
785
    */
786
    composeDesc(other) { return this.empty ? other : other.empty ? this : composeSets(this, other); }
787
    /**
788
    Map this description, which should start with the same document
789
    as `other`, over another set of changes, so that it can be
790
    applied after it. When `before` is true, map as if the changes
791
    in `other` happened before the ones in `this`.
792
    */
793
    mapDesc(other, before = false) { return other.empty ? this : mapSet(this, other, before); }
794
    mapPos(pos, assoc = -1, mode = MapMode.Simple) {
795
        let posA = 0, posB = 0;
796
        for (let i = 0; i < this.sections.length;) {
797
            let len = this.sections[i++], ins = this.sections[i++], endA = posA + len;
798
            if (ins < 0) {
799
                if (endA > pos)
800
                    return posB + (pos - posA);
801
                posB += len;
802
            }
803
            else {
804
                if (mode != MapMode.Simple && endA >= pos &&
805
                    (mode == MapMode.TrackDel && posA < pos && endA > pos ||
806
                        mode == MapMode.TrackBefore && posA < pos ||
807
                        mode == MapMode.TrackAfter && endA > pos))
808
                    return null;
809
                if (endA > pos || endA == pos && assoc < 0 && !len)
810
                    return pos == posA || assoc < 0 ? posB : posB + ins;
811
                posB += ins;
812
            }
813
            posA = endA;
814
        }
815
        if (pos > posA)
816
            throw new RangeError(`Position ${pos} is out of range for changeset of length ${posA}`);
817
        return posB;
818
    }
819
    /**
820
    Check whether these changes touch a given range. When one of the
821
    changes entirely covers the range, the string `"cover"` is
822
    returned.
823
    */
824
    touchesRange(from, to = from) {
825
        for (let i = 0, pos = 0; i < this.sections.length && pos <= to;) {
826
            let len = this.sections[i++], ins = this.sections[i++], end = pos + len;
827
            if (ins >= 0 && pos <= to && end >= from)
828
                return pos < from && end > to ? "cover" : true;
829
            pos = end;
830
        }
831
        return false;
832
    }
833
    /**
834
    @internal
835
    */
836
    toString() {
837
        let result = "";
838
        for (let i = 0; i < this.sections.length;) {
839
            let len = this.sections[i++], ins = this.sections[i++];
840
            result += (result ? " " : "") + len + (ins >= 0 ? ":" + ins : "");
841
        }
842
        return result;
843
    }
844
    /**
845
    Serialize this change desc to a JSON-representable value.
846
    */
847
    toJSON() { return this.sections; }
848
    /**
849
    Create a change desc from its JSON representation (as produced
850
    by [`toJSON`](https://codemirror.net/6/docs/ref/#state.ChangeDesc.toJSON).
851
    */
852
    static fromJSON(json) {
853
        if (!Array.isArray(json) || json.length % 2 || json.some(a => typeof a != "number"))
854
            throw new RangeError("Invalid JSON representation of ChangeDesc");
855
        return new ChangeDesc(json);
856
    }
857
    /**
858
    @internal
859
    */
860
    static create(sections) { return new ChangeDesc(sections); }
861
}
862
/**
863
A change set represents a group of modifications to a document. It
864
stores the document length, and can only be applied to documents
865
with exactly that length.
866
*/
867
class ChangeSet extends ChangeDesc {
868
    constructor(sections,
869
    /**
870
    @internal
871
    */
872
    inserted) {
873
        super(sections);
874
        this.inserted = inserted;
875
    }
876
    /**
877
    Apply the changes to a document, returning the modified
878
    document.
879
    */
880
    apply(doc) {
881
        if (this.length != doc.length)
882
            throw new RangeError("Applying change set to a document with the wrong length");
883
        iterChanges(this, (fromA, toA, fromB, _toB, text) => doc = doc.replace(fromB, fromB + (toA - fromA), text), false);
884
        return doc;
885
    }
886
    mapDesc(other, before = false) { return mapSet(this, other, before, true); }
887
    /**
888
    Given the document as it existed _before_ the changes, return a
889
    change set that represents the inverse of this set, which could
890
    be used to go from the document created by the changes back to
891
    the document as it existed before the changes.
892
    */
893
    invert(doc) {
894
        let sections = this.sections.slice(), inserted = [];
895
        for (let i = 0, pos = 0; i < sections.length; i += 2) {
896
            let len = sections[i], ins = sections[i + 1];
897
            if (ins >= 0) {
898
                sections[i] = ins;
899
                sections[i + 1] = len;
900
                let index = i >> 1;
901
                while (inserted.length < index)
902
                    inserted.push(Text.empty);
903
                inserted.push(len ? doc.slice(pos, pos + len) : Text.empty);
904
            }
905
            pos += len;
906
        }
907
        return new ChangeSet(sections, inserted);
908
    }
909
    /**
910
    Combine two subsequent change sets into a single set. `other`
911
    must start in the document produced by `this`. If `this` goes
912
    `docA` → `docB` and `other` represents `docB` → `docC`, the
913
    returned value will represent the change `docA` → `docC`.
914
    */
915
    compose(other) { return this.empty ? other : other.empty ? this : composeSets(this, other, true); }
916
    /**
917
    Given another change set starting in the same document, maps this
918
    change set over the other, producing a new change set that can be
919
    applied to the document produced by applying `other`. When
920
    `before` is `true`, order changes as if `this` comes before
921
    `other`, otherwise (the default) treat `other` as coming first.
922
 
923
    Given two changes `A` and `B`, `A.compose(B.map(A))` and
924
    `B.compose(A.map(B, true))` will produce the same document. This
925
    provides a basic form of [operational
926
    transformation](https://en.wikipedia.org/wiki/Operational_transformation),
927
    and can be used for collaborative editing.
928
    */
929
    map(other, before = false) { return other.empty ? this : mapSet(this, other, before, true); }
930
    /**
931
    Iterate over the changed ranges in the document, calling `f` for
932
    each, with the range in the original document (`fromA`-`toA`)
933
    and the range that replaces it in the new document
934
    (`fromB`-`toB`).
935
 
936
    When `individual` is true, adjacent changes are reported
937
    separately.
938
    */
939
    iterChanges(f, individual = false) {
940
        iterChanges(this, f, individual);
941
    }
942
    /**
943
    Get a [change description](https://codemirror.net/6/docs/ref/#state.ChangeDesc) for this change
944
    set.
945
    */
946
    get desc() { return ChangeDesc.create(this.sections); }
947
    /**
948
    @internal
949
    */
950
    filter(ranges) {
951
        let resultSections = [], resultInserted = [], filteredSections = [];
952
        let iter = new SectionIter(this);
953
        done: for (let i = 0, pos = 0;;) {
954
            let next = i == ranges.length ? 1e9 : ranges[i++];
955
            while (pos < next || pos == next && iter.len == 0) {
956
                if (iter.done)
957
                    break done;
958
                let len = Math.min(iter.len, next - pos);
959
                addSection(filteredSections, len, -1);
960
                let ins = iter.ins == -1 ? -1 : iter.off == 0 ? iter.ins : 0;
961
                addSection(resultSections, len, ins);
962
                if (ins > 0)
963
                    addInsert(resultInserted, resultSections, iter.text);
964
                iter.forward(len);
965
                pos += len;
966
            }
967
            let end = ranges[i++];
968
            while (pos < end) {
969
                if (iter.done)
970
                    break done;
971
                let len = Math.min(iter.len, end - pos);
972
                addSection(resultSections, len, -1);
973
                addSection(filteredSections, len, iter.ins == -1 ? -1 : iter.off == 0 ? iter.ins : 0);
974
                iter.forward(len);
975
                pos += len;
976
            }
977
        }
978
        return { changes: new ChangeSet(resultSections, resultInserted),
979
            filtered: ChangeDesc.create(filteredSections) };
980
    }
981
    /**
982
    Serialize this change set to a JSON-representable value.
983
    */
984
    toJSON() {
985
        let parts = [];
986
        for (let i = 0; i < this.sections.length; i += 2) {
987
            let len = this.sections[i], ins = this.sections[i + 1];
988
            if (ins < 0)
989
                parts.push(len);
990
            else if (ins == 0)
991
                parts.push([len]);
992
            else
993
                parts.push([len].concat(this.inserted[i >> 1].toJSON()));
994
        }
995
        return parts;
996
    }
997
    /**
998
    Create a change set for the given changes, for a document of the
999
    given length, using `lineSep` as line separator.
1000
    */
1001
    static of(changes, length, lineSep) {
1002
        let sections = [], inserted = [], pos = 0;
1003
        let total = null;
1004
        function flush(force = false) {
1005
            if (!force && !sections.length)
1006
                return;
1007
            if (pos < length)
1008
                addSection(sections, length - pos, -1);
1009
            let set = new ChangeSet(sections, inserted);
1010
            total = total ? total.compose(set.map(total)) : set;
1011
            sections = [];
1012
            inserted = [];
1013
            pos = 0;
1014
        }
1015
        function process(spec) {
1016
            if (Array.isArray(spec)) {
1017
                for (let sub of spec)
1018
                    process(sub);
1019
            }
1020
            else if (spec instanceof ChangeSet) {
1021
                if (spec.length != length)
1022
                    throw new RangeError(`Mismatched change set length (got ${spec.length}, expected ${length})`);
1023
                flush();
1024
                total = total ? total.compose(spec.map(total)) : spec;
1025
            }
1026
            else {
1027
                let { from, to = from, insert } = spec;
1028
                if (from > to || from < 0 || to > length)
1029
                    throw new RangeError(`Invalid change range ${from} to ${to} (in doc of length ${length})`);
1030
                let insText = !insert ? Text.empty : typeof insert == "string" ? Text.of(insert.split(lineSep || DefaultSplit)) : insert;
1031
                let insLen = insText.length;
1032
                if (from == to && insLen == 0)
1033
                    return;
1034
                if (from < pos)
1035
                    flush();
1036
                if (from > pos)
1037
                    addSection(sections, from - pos, -1);
1038
                addSection(sections, to - from, insLen);
1039
                addInsert(inserted, sections, insText);
1040
                pos = to;
1041
            }
1042
        }
1043
        process(changes);
1044
        flush(!total);
1045
        return total;
1046
    }
1047
    /**
1048
    Create an empty changeset of the given length.
1049
    */
1050
    static empty(length) {
1051
        return new ChangeSet(length ? [length, -1] : [], []);
1052
    }
1053
    /**
1054
    Create a changeset from its JSON representation (as produced by
1055
    [`toJSON`](https://codemirror.net/6/docs/ref/#state.ChangeSet.toJSON).
1056
    */
1057
    static fromJSON(json) {
1058
        if (!Array.isArray(json))
1059
            throw new RangeError("Invalid JSON representation of ChangeSet");
1060
        let sections = [], inserted = [];
1061
        for (let i = 0; i < json.length; i++) {
1062
            let part = json[i];
1063
            if (typeof part == "number") {
1064
                sections.push(part, -1);
1065
            }
1066
            else if (!Array.isArray(part) || typeof part[0] != "number" || part.some((e, i) => i && typeof e != "string")) {
1067
                throw new RangeError("Invalid JSON representation of ChangeSet");
1068
            }
1069
            else if (part.length == 1) {
1070
                sections.push(part[0], 0);
1071
            }
1072
            else {
1073
                while (inserted.length < i)
1074
                    inserted.push(Text.empty);
1075
                inserted[i] = Text.of(part.slice(1));
1076
                sections.push(part[0], inserted[i].length);
1077
            }
1078
        }
1079
        return new ChangeSet(sections, inserted);
1080
    }
1081
    /**
1082
    @internal
1083
    */
1084
    static createSet(sections, inserted) {
1085
        return new ChangeSet(sections, inserted);
1086
    }
1087
}
1088
function addSection(sections, len, ins, forceJoin = false) {
1089
    if (len == 0 && ins <= 0)
1090
        return;
1091
    let last = sections.length - 2;
1092
    if (last >= 0 && ins <= 0 && ins == sections[last + 1])
1093
        sections[last] += len;
1094
    else if (len == 0 && sections[last] == 0)
1095
        sections[last + 1] += ins;
1096
    else if (forceJoin) {
1097
        sections[last] += len;
1098
        sections[last + 1] += ins;
1099
    }
1100
    else
1101
        sections.push(len, ins);
1102
}
1103
function addInsert(values, sections, value) {
1104
    if (value.length == 0)
1105
        return;
1106
    let index = (sections.length - 2) >> 1;
1107
    if (index < values.length) {
1108
        values[values.length - 1] = values[values.length - 1].append(value);
1109
    }
1110
    else {
1111
        while (values.length < index)
1112
            values.push(Text.empty);
1113
        values.push(value);
1114
    }
1115
}
1116
function iterChanges(desc, f, individual) {
1117
    let inserted = desc.inserted;
1118
    for (let posA = 0, posB = 0, i = 0; i < desc.sections.length;) {
1119
        let len = desc.sections[i++], ins = desc.sections[i++];
1120
        if (ins < 0) {
1121
            posA += len;
1122
            posB += len;
1123
        }
1124
        else {
1125
            let endA = posA, endB = posB, text = Text.empty;
1126
            for (;;) {
1127
                endA += len;
1128
                endB += ins;
1129
                if (ins && inserted)
1130
                    text = text.append(inserted[(i - 2) >> 1]);
1131
                if (individual || i == desc.sections.length || desc.sections[i + 1] < 0)
1132
                    break;
1133
                len = desc.sections[i++];
1134
                ins = desc.sections[i++];
1135
            }
1136
            f(posA, endA, posB, endB, text);
1137
            posA = endA;
1138
            posB = endB;
1139
        }
1140
    }
1141
}
1142
function mapSet(setA, setB, before, mkSet = false) {
1143
    // Produce a copy of setA that applies to the document after setB
1144
    // has been applied (assuming both start at the same document).
1145
    let sections = [], insert = mkSet ? [] : null;
1146
    let a = new SectionIter(setA), b = new SectionIter(setB);
1147
    // Iterate over both sets in parallel. inserted tracks, for changes
1148
    // in A that have to be processed piece-by-piece, whether their
1149
    // content has been inserted already, and refers to the section
1150
    // index.
1151
    for (let inserted = -1;;) {
1152
        if (a.ins == -1 && b.ins == -1) {
1153
            // Move across ranges skipped by both sets.
1154
            let len = Math.min(a.len, b.len);
1155
            addSection(sections, len, -1);
1156
            a.forward(len);
1157
            b.forward(len);
1158
        }
1159
        else if (b.ins >= 0 && (a.ins < 0 || inserted == a.i || a.off == 0 && (b.len < a.len || b.len == a.len && !before))) {
1160
            // If there's a change in B that comes before the next change in
1161
            // A (ordered by start pos, then len, then before flag), skip
1162
            // that (and process any changes in A it covers).
1163
            let len = b.len;
1164
            addSection(sections, b.ins, -1);
1165
            while (len) {
1166
                let piece = Math.min(a.len, len);
1167
                if (a.ins >= 0 && inserted < a.i && a.len <= piece) {
1168
                    addSection(sections, 0, a.ins);
1169
                    if (insert)
1170
                        addInsert(insert, sections, a.text);
1171
                    inserted = a.i;
1172
                }
1173
                a.forward(piece);
1174
                len -= piece;
1175
            }
1176
            b.next();
1177
        }
1178
        else if (a.ins >= 0) {
1179
            // Process the part of a change in A up to the start of the next
1180
            // non-deletion change in B (if overlapping).
1181
            let len = 0, left = a.len;
1182
            while (left) {
1183
                if (b.ins == -1) {
1184
                    let piece = Math.min(left, b.len);
1185
                    len += piece;
1186
                    left -= piece;
1187
                    b.forward(piece);
1188
                }
1189
                else if (b.ins == 0 && b.len < left) {
1190
                    left -= b.len;
1191
                    b.next();
1192
                }
1193
                else {
1194
                    break;
1195
                }
1196
            }
1197
            addSection(sections, len, inserted < a.i ? a.ins : 0);
1198
            if (insert && inserted < a.i)
1199
                addInsert(insert, sections, a.text);
1200
            inserted = a.i;
1201
            a.forward(a.len - left);
1202
        }
1203
        else if (a.done && b.done) {
1204
            return insert ? ChangeSet.createSet(sections, insert) : ChangeDesc.create(sections);
1205
        }
1206
        else {
1207
            throw new Error("Mismatched change set lengths");
1208
        }
1209
    }
1210
}
1211
function composeSets(setA, setB, mkSet = false) {
1212
    let sections = [];
1213
    let insert = mkSet ? [] : null;
1214
    let a = new SectionIter(setA), b = new SectionIter(setB);
1215
    for (let open = false;;) {
1216
        if (a.done && b.done) {
1217
            return insert ? ChangeSet.createSet(sections, insert) : ChangeDesc.create(sections);
1218
        }
1219
        else if (a.ins == 0) { // Deletion in A
1220
            addSection(sections, a.len, 0, open);
1221
            a.next();
1222
        }
1223
        else if (b.len == 0 && !b.done) { // Insertion in B
1224
            addSection(sections, 0, b.ins, open);
1225
            if (insert)
1226
                addInsert(insert, sections, b.text);
1227
            b.next();
1228
        }
1229
        else if (a.done || b.done) {
1230
            throw new Error("Mismatched change set lengths");
1231
        }
1232
        else {
1233
            let len = Math.min(a.len2, b.len), sectionLen = sections.length;
1234
            if (a.ins == -1) {
1235
                let insB = b.ins == -1 ? -1 : b.off ? 0 : b.ins;
1236
                addSection(sections, len, insB, open);
1237
                if (insert && insB)
1238
                    addInsert(insert, sections, b.text);
1239
            }
1240
            else if (b.ins == -1) {
1241
                addSection(sections, a.off ? 0 : a.len, len, open);
1242
                if (insert)
1243
                    addInsert(insert, sections, a.textBit(len));
1244
            }
1245
            else {
1246
                addSection(sections, a.off ? 0 : a.len, b.off ? 0 : b.ins, open);
1247
                if (insert && !b.off)
1248
                    addInsert(insert, sections, b.text);
1249
            }
1250
            open = (a.ins > len || b.ins >= 0 && b.len > len) && (open || sections.length > sectionLen);
1251
            a.forward2(len);
1252
            b.forward(len);
1253
        }
1254
    }
1255
}
1256
class SectionIter {
1257
    constructor(set) {
1258
        this.set = set;
1259
        this.i = 0;
1260
        this.next();
1261
    }
1262
    next() {
1263
        let { sections } = this.set;
1264
        if (this.i < sections.length) {
1265
            this.len = sections[this.i++];
1266
            this.ins = sections[this.i++];
1267
        }
1268
        else {
1269
            this.len = 0;
1270
            this.ins = -2;
1271
        }
1272
        this.off = 0;
1273
    }
1274
    get done() { return this.ins == -2; }
1275
    get len2() { return this.ins < 0 ? this.len : this.ins; }
1276
    get text() {
1277
        let { inserted } = this.set, index = (this.i - 2) >> 1;
1278
        return index >= inserted.length ? Text.empty : inserted[index];
1279
    }
1280
    textBit(len) {
1281
        let { inserted } = this.set, index = (this.i - 2) >> 1;
1282
        return index >= inserted.length && !len ? Text.empty
1283
            : inserted[index].slice(this.off, len == null ? undefined : this.off + len);
1284
    }
1285
    forward(len) {
1286
        if (len == this.len)
1287
            this.next();
1288
        else {
1289
            this.len -= len;
1290
            this.off += len;
1291
        }
1292
    }
1293
    forward2(len) {
1294
        if (this.ins == -1)
1295
            this.forward(len);
1296
        else if (len == this.ins)
1297
            this.next();
1298
        else {
1299
            this.ins -= len;
1300
            this.off += len;
1301
        }
1302
    }
1303
}
1304
 
1305
/**
1306
A single selection range. When
1307
[`allowMultipleSelections`](https://codemirror.net/6/docs/ref/#state.EditorState^allowMultipleSelections)
1308
is enabled, a [selection](https://codemirror.net/6/docs/ref/#state.EditorSelection) may hold
1309
multiple ranges. By default, selections hold exactly one range.
1310
*/
1311
class SelectionRange {
1312
    constructor(
1313
    /**
1314
    The lower boundary of the range.
1315
    */
1316
    from,
1317
    /**
1318
    The upper boundary of the range.
1319
    */
1320
    to, flags) {
1321
        this.from = from;
1322
        this.to = to;
1323
        this.flags = flags;
1324
    }
1325
    /**
1326
    The anchor of the range—the side that doesn't move when you
1327
    extend it.
1328
    */
1329
    get anchor() { return this.flags & 32 /* RangeFlag.Inverted */ ? this.to : this.from; }
1330
    /**
1331
    The head of the range, which is moved when the range is
1332
    [extended](https://codemirror.net/6/docs/ref/#state.SelectionRange.extend).
1333
    */
1334
    get head() { return this.flags & 32 /* RangeFlag.Inverted */ ? this.from : this.to; }
1335
    /**
1336
    True when `anchor` and `head` are at the same position.
1337
    */
1338
    get empty() { return this.from == this.to; }
1339
    /**
1340
    If this is a cursor that is explicitly associated with the
1341
    character on one of its sides, this returns the side. -1 means
1342
    the character before its position, 1 the character after, and 0
1343
    means no association.
1344
    */
1345
    get assoc() { return this.flags & 8 /* RangeFlag.AssocBefore */ ? -1 : this.flags & 16 /* RangeFlag.AssocAfter */ ? 1 : 0; }
1346
    /**
1347
    The bidirectional text level associated with this cursor, if
1348
    any.
1349
    */
1350
    get bidiLevel() {
1351
        let level = this.flags & 7 /* RangeFlag.BidiLevelMask */;
1352
        return level == 7 ? null : level;
1353
    }
1354
    /**
1355
    The goal column (stored vertical offset) associated with a
1356
    cursor. This is used to preserve the vertical position when
1357
    [moving](https://codemirror.net/6/docs/ref/#view.EditorView.moveVertically) across
1358
    lines of different length.
1359
    */
1360
    get goalColumn() {
1361
        let value = this.flags >> 6 /* RangeFlag.GoalColumnOffset */;
1362
        return value == 16777215 /* RangeFlag.NoGoalColumn */ ? undefined : value;
1363
    }
1364
    /**
1365
    Map this range through a change, producing a valid range in the
1366
    updated document.
1367
    */
1368
    map(change, assoc = -1) {
1369
        let from, to;
1370
        if (this.empty) {
1371
            from = to = change.mapPos(this.from, assoc);
1372
        }
1373
        else {
1374
            from = change.mapPos(this.from, 1);
1375
            to = change.mapPos(this.to, -1);
1376
        }
1377
        return from == this.from && to == this.to ? this : new SelectionRange(from, to, this.flags);
1378
    }
1379
    /**
1380
    Extend this range to cover at least `from` to `to`.
1381
    */
1382
    extend(from, to = from) {
1383
        if (from <= this.anchor && to >= this.anchor)
1384
            return EditorSelection.range(from, to);
1385
        let head = Math.abs(from - this.anchor) > Math.abs(to - this.anchor) ? from : to;
1386
        return EditorSelection.range(this.anchor, head);
1387
    }
1388
    /**
1389
    Compare this range to another range.
1390
    */
1391
    eq(other, includeAssoc = false) {
1392
        return this.anchor == other.anchor && this.head == other.head &&
1393
            (!includeAssoc || !this.empty || this.assoc == other.assoc);
1394
    }
1395
    /**
1396
    Return a JSON-serializable object representing the range.
1397
    */
1398
    toJSON() { return { anchor: this.anchor, head: this.head }; }
1399
    /**
1400
    Convert a JSON representation of a range to a `SelectionRange`
1401
    instance.
1402
    */
1403
    static fromJSON(json) {
1404
        if (!json || typeof json.anchor != "number" || typeof json.head != "number")
1405
            throw new RangeError("Invalid JSON representation for SelectionRange");
1406
        return EditorSelection.range(json.anchor, json.head);
1407
    }
1408
    /**
1409
    @internal
1410
    */
1411
    static create(from, to, flags) {
1412
        return new SelectionRange(from, to, flags);
1413
    }
1414
}
1415
/**
1416
An editor selection holds one or more selection ranges.
1417
*/
1418
class EditorSelection {
1419
    constructor(
1420
    /**
1421
    The ranges in the selection, sorted by position. Ranges cannot
1422
    overlap (but they may touch, if they aren't empty).
1423
    */
1424
    ranges,
1425
    /**
1426
    The index of the _main_ range in the selection (which is
1427
    usually the range that was added last).
1428
    */
1429
    mainIndex) {
1430
        this.ranges = ranges;
1431
        this.mainIndex = mainIndex;
1432
    }
1433
    /**
1434
    Map a selection through a change. Used to adjust the selection
1435
    position for changes.
1436
    */
1437
    map(change, assoc = -1) {
1438
        if (change.empty)
1439
            return this;
1440
        return EditorSelection.create(this.ranges.map(r => r.map(change, assoc)), this.mainIndex);
1441
    }
1442
    /**
1443
    Compare this selection to another selection. By default, ranges
1444
    are compared only by position. When `includeAssoc` is true,
1445
    cursor ranges must also have the same
1446
    [`assoc`](https://codemirror.net/6/docs/ref/#state.SelectionRange.assoc) value.
1447
    */
1448
    eq(other, includeAssoc = false) {
1449
        if (this.ranges.length != other.ranges.length ||
1450
            this.mainIndex != other.mainIndex)
1451
            return false;
1452
        for (let i = 0; i < this.ranges.length; i++)
1453
            if (!this.ranges[i].eq(other.ranges[i], includeAssoc))
1454
                return false;
1455
        return true;
1456
    }
1457
    /**
1458
    Get the primary selection range. Usually, you should make sure
1459
    your code applies to _all_ ranges, by using methods like
1460
    [`changeByRange`](https://codemirror.net/6/docs/ref/#state.EditorState.changeByRange).
1461
    */
1462
    get main() { return this.ranges[this.mainIndex]; }
1463
    /**
1464
    Make sure the selection only has one range. Returns a selection
1465
    holding only the main range from this selection.
1466
    */
1467
    asSingle() {
1468
        return this.ranges.length == 1 ? this : new EditorSelection([this.main], 0);
1469
    }
1470
    /**
1471
    Extend this selection with an extra range.
1472
    */
1473
    addRange(range, main = true) {
1474
        return EditorSelection.create([range].concat(this.ranges), main ? 0 : this.mainIndex + 1);
1475
    }
1476
    /**
1477
    Replace a given range with another range, and then normalize the
1478
    selection to merge and sort ranges if necessary.
1479
    */
1480
    replaceRange(range, which = this.mainIndex) {
1481
        let ranges = this.ranges.slice();
1482
        ranges[which] = range;
1483
        return EditorSelection.create(ranges, this.mainIndex);
1484
    }
1485
    /**
1486
    Convert this selection to an object that can be serialized to
1487
    JSON.
1488
    */
1489
    toJSON() {
1490
        return { ranges: this.ranges.map(r => r.toJSON()), main: this.mainIndex };
1491
    }
1492
    /**
1493
    Create a selection from a JSON representation.
1494
    */
1495
    static fromJSON(json) {
1496
        if (!json || !Array.isArray(json.ranges) || typeof json.main != "number" || json.main >= json.ranges.length)
1497
            throw new RangeError("Invalid JSON representation for EditorSelection");
1498
        return new EditorSelection(json.ranges.map((r) => SelectionRange.fromJSON(r)), json.main);
1499
    }
1500
    /**
1501
    Create a selection holding a single range.
1502
    */
1503
    static single(anchor, head = anchor) {
1504
        return new EditorSelection([EditorSelection.range(anchor, head)], 0);
1505
    }
1506
    /**
1507
    Sort and merge the given set of ranges, creating a valid
1508
    selection.
1509
    */
1510
    static create(ranges, mainIndex = 0) {
1511
        if (ranges.length == 0)
1512
            throw new RangeError("A selection needs at least one range");
1513
        for (let pos = 0, i = 0; i < ranges.length; i++) {
1514
            let range = ranges[i];
1515
            if (range.empty ? range.from <= pos : range.from < pos)
1516
                return EditorSelection.normalized(ranges.slice(), mainIndex);
1517
            pos = range.to;
1518
        }
1519
        return new EditorSelection(ranges, mainIndex);
1520
    }
1521
    /**
1522
    Create a cursor selection range at the given position. You can
1523
    safely ignore the optional arguments in most situations.
1524
    */
1525
    static cursor(pos, assoc = 0, bidiLevel, goalColumn) {
1526
        return SelectionRange.create(pos, pos, (assoc == 0 ? 0 : assoc < 0 ? 8 /* RangeFlag.AssocBefore */ : 16 /* RangeFlag.AssocAfter */) |
1527
            (bidiLevel == null ? 7 : Math.min(6, bidiLevel)) |
1528
            ((goalColumn !== null && goalColumn !== void 0 ? goalColumn : 16777215 /* RangeFlag.NoGoalColumn */) << 6 /* RangeFlag.GoalColumnOffset */));
1529
    }
1530
    /**
1531
    Create a selection range.
1532
    */
1533
    static range(anchor, head, goalColumn, bidiLevel) {
1534
        let flags = ((goalColumn !== null && goalColumn !== void 0 ? goalColumn : 16777215 /* RangeFlag.NoGoalColumn */) << 6 /* RangeFlag.GoalColumnOffset */) |
1535
            (bidiLevel == null ? 7 : Math.min(6, bidiLevel));
1536
        return head < anchor ? SelectionRange.create(head, anchor, 32 /* RangeFlag.Inverted */ | 16 /* RangeFlag.AssocAfter */ | flags)
1537
            : SelectionRange.create(anchor, head, (head > anchor ? 8 /* RangeFlag.AssocBefore */ : 0) | flags);
1538
    }
1539
    /**
1540
    @internal
1541
    */
1542
    static normalized(ranges, mainIndex = 0) {
1543
        let main = ranges[mainIndex];
1544
        ranges.sort((a, b) => a.from - b.from);
1545
        mainIndex = ranges.indexOf(main);
1546
        for (let i = 1; i < ranges.length; i++) {
1547
            let range = ranges[i], prev = ranges[i - 1];
1548
            if (range.empty ? range.from <= prev.to : range.from < prev.to) {
1549
                let from = prev.from, to = Math.max(range.to, prev.to);
1550
                if (i <= mainIndex)
1551
                    mainIndex--;
1552
                ranges.splice(--i, 2, range.anchor > range.head ? EditorSelection.range(to, from) : EditorSelection.range(from, to));
1553
            }
1554
        }
1555
        return new EditorSelection(ranges, mainIndex);
1556
    }
1557
}
1558
function checkSelection(selection, docLength) {
1559
    for (let range of selection.ranges)
1560
        if (range.to > docLength)
1561
            throw new RangeError("Selection points outside of document");
1562
}
1563
 
1564
let nextID = 0;
1565
/**
1566
A facet is a labeled value that is associated with an editor
1567
state. It takes inputs from any number of extensions, and combines
1568
those into a single output value.
1569
 
1570
Examples of uses of facets are the [tab
1571
size](https://codemirror.net/6/docs/ref/#state.EditorState^tabSize), [editor
1572
attributes](https://codemirror.net/6/docs/ref/#view.EditorView^editorAttributes), and [update
1573
listeners](https://codemirror.net/6/docs/ref/#view.EditorView^updateListener).
1574
 
1575
Note that `Facet` instances can be used anywhere where
1576
[`FacetReader`](https://codemirror.net/6/docs/ref/#state.FacetReader) is expected.
1577
*/
1578
class Facet {
1579
    constructor(
1580
    /**
1581
    @internal
1582
    */
1583
    combine,
1584
    /**
1585
    @internal
1586
    */
1587
    compareInput,
1588
    /**
1589
    @internal
1590
    */
1591
    compare, isStatic, enables) {
1592
        this.combine = combine;
1593
        this.compareInput = compareInput;
1594
        this.compare = compare;
1595
        this.isStatic = isStatic;
1596
        /**
1597
        @internal
1598
        */
1599
        this.id = nextID++;
1600
        this.default = combine([]);
1601
        this.extensions = typeof enables == "function" ? enables(this) : enables;
1602
    }
1603
    /**
1604
    Returns a facet reader for this facet, which can be used to
1605
    [read](https://codemirror.net/6/docs/ref/#state.EditorState.facet) it but not to define values for it.
1606
    */
1607
    get reader() { return this; }
1608
    /**
1609
    Define a new facet.
1610
    */
1611
    static define(config = {}) {
1612
        return new Facet(config.combine || ((a) => a), config.compareInput || ((a, b) => a === b), config.compare || (!config.combine ? sameArray$1 : (a, b) => a === b), !!config.static, config.enables);
1613
    }
1614
    /**
1615
    Returns an extension that adds the given value to this facet.
1616
    */
1617
    of(value) {
1618
        return new FacetProvider([], this, 0 /* Provider.Static */, value);
1619
    }
1620
    /**
1621
    Create an extension that computes a value for the facet from a
1622
    state. You must take care to declare the parts of the state that
1623
    this value depends on, since your function is only called again
1624
    for a new state when one of those parts changed.
1625
 
1626
    In cases where your value depends only on a single field, you'll
1627
    want to use the [`from`](https://codemirror.net/6/docs/ref/#state.Facet.from) method instead.
1628
    */
1629
    compute(deps, get) {
1630
        if (this.isStatic)
1631
            throw new Error("Can't compute a static facet");
1632
        return new FacetProvider(deps, this, 1 /* Provider.Single */, get);
1633
    }
1634
    /**
1635
    Create an extension that computes zero or more values for this
1636
    facet from a state.
1637
    */
1638
    computeN(deps, get) {
1639
        if (this.isStatic)
1640
            throw new Error("Can't compute a static facet");
1641
        return new FacetProvider(deps, this, 2 /* Provider.Multi */, get);
1642
    }
1643
    from(field, get) {
1644
        if (!get)
1645
            get = x => x;
1646
        return this.compute([field], state => get(state.field(field)));
1647
    }
1648
}
1649
function sameArray$1(a, b) {
1650
    return a == b || a.length == b.length && a.every((e, i) => e === b[i]);
1651
}
1652
class FacetProvider {
1653
    constructor(dependencies, facet, type, value) {
1654
        this.dependencies = dependencies;
1655
        this.facet = facet;
1656
        this.type = type;
1657
        this.value = value;
1658
        this.id = nextID++;
1659
    }
1660
    dynamicSlot(addresses) {
1661
        var _a;
1662
        let getter = this.value;
1663
        let compare = this.facet.compareInput;
1664
        let id = this.id, idx = addresses[id] >> 1, multi = this.type == 2 /* Provider.Multi */;
1665
        let depDoc = false, depSel = false, depAddrs = [];
1666
        for (let dep of this.dependencies) {
1667
            if (dep == "doc")
1668
                depDoc = true;
1669
            else if (dep == "selection")
1670
                depSel = true;
1671
            else if ((((_a = addresses[dep.id]) !== null && _a !== void 0 ? _a : 1) & 1) == 0)
1672
                depAddrs.push(addresses[dep.id]);
1673
        }
1674
        return {
1675
            create(state) {
1676
                state.values[idx] = getter(state);
1677
                return 1 /* SlotStatus.Changed */;
1678
            },
1679
            update(state, tr) {
1680
                if ((depDoc && tr.docChanged) || (depSel && (tr.docChanged || tr.selection)) || ensureAll(state, depAddrs)) {
1681
                    let newVal = getter(state);
1682
                    if (multi ? !compareArray(newVal, state.values[idx], compare) : !compare(newVal, state.values[idx])) {
1683
                        state.values[idx] = newVal;
1684
                        return 1 /* SlotStatus.Changed */;
1685
                    }
1686
                }
1687
                return 0;
1688
            },
1689
            reconfigure: (state, oldState) => {
1690
                let newVal, oldAddr = oldState.config.address[id];
1691
                if (oldAddr != null) {
1692
                    let oldVal = getAddr(oldState, oldAddr);
1693
                    if (this.dependencies.every(dep => {
1694
                        return dep instanceof Facet ? oldState.facet(dep) === state.facet(dep) :
1695
                            dep instanceof StateField ? oldState.field(dep, false) == state.field(dep, false) : true;
1696
                    }) || (multi ? compareArray(newVal = getter(state), oldVal, compare) : compare(newVal = getter(state), oldVal))) {
1697
                        state.values[idx] = oldVal;
1698
                        return 0;
1699
                    }
1700
                }
1701
                else {
1702
                    newVal = getter(state);
1703
                }
1704
                state.values[idx] = newVal;
1705
                return 1 /* SlotStatus.Changed */;
1706
            }
1707
        };
1708
    }
1709
}
1710
function compareArray(a, b, compare) {
1711
    if (a.length != b.length)
1712
        return false;
1713
    for (let i = 0; i < a.length; i++)
1714
        if (!compare(a[i], b[i]))
1715
            return false;
1716
    return true;
1717
}
1718
function ensureAll(state, addrs) {
1719
    let changed = false;
1720
    for (let addr of addrs)
1721
        if (ensureAddr(state, addr) & 1 /* SlotStatus.Changed */)
1722
            changed = true;
1723
    return changed;
1724
}
1725
function dynamicFacetSlot(addresses, facet, providers) {
1726
    let providerAddrs = providers.map(p => addresses[p.id]);
1727
    let providerTypes = providers.map(p => p.type);
1728
    let dynamic = providerAddrs.filter(p => !(p & 1));
1729
    let idx = addresses[facet.id] >> 1;
1730
    function get(state) {
1731
        let values = [];
1732
        for (let i = 0; i < providerAddrs.length; i++) {
1733
            let value = getAddr(state, providerAddrs[i]);
1734
            if (providerTypes[i] == 2 /* Provider.Multi */)
1735
                for (let val of value)
1736
                    values.push(val);
1737
            else
1738
                values.push(value);
1739
        }
1740
        return facet.combine(values);
1741
    }
1742
    return {
1743
        create(state) {
1744
            for (let addr of providerAddrs)
1745
                ensureAddr(state, addr);
1746
            state.values[idx] = get(state);
1747
            return 1 /* SlotStatus.Changed */;
1748
        },
1749
        update(state, tr) {
1750
            if (!ensureAll(state, dynamic))
1751
                return 0;
1752
            let value = get(state);
1753
            if (facet.compare(value, state.values[idx]))
1754
                return 0;
1755
            state.values[idx] = value;
1756
            return 1 /* SlotStatus.Changed */;
1757
        },
1758
        reconfigure(state, oldState) {
1759
            let depChanged = ensureAll(state, providerAddrs);
1760
            let oldProviders = oldState.config.facets[facet.id], oldValue = oldState.facet(facet);
1761
            if (oldProviders && !depChanged && sameArray$1(providers, oldProviders)) {
1762
                state.values[idx] = oldValue;
1763
                return 0;
1764
            }
1765
            let value = get(state);
1766
            if (facet.compare(value, oldValue)) {
1767
                state.values[idx] = oldValue;
1768
                return 0;
1769
            }
1770
            state.values[idx] = value;
1771
            return 1 /* SlotStatus.Changed */;
1772
        }
1773
    };
1774
}
1775
const initField = /*@__PURE__*/Facet.define({ static: true });
1776
/**
1777
Fields can store additional information in an editor state, and
1778
keep it in sync with the rest of the state.
1779
*/
1780
class StateField {
1781
    constructor(
1782
    /**
1783
    @internal
1784
    */
1785
    id, createF, updateF, compareF,
1786
    /**
1787
    @internal
1788
    */
1789
    spec) {
1790
        this.id = id;
1791
        this.createF = createF;
1792
        this.updateF = updateF;
1793
        this.compareF = compareF;
1794
        this.spec = spec;
1795
        /**
1796
        @internal
1797
        */
1798
        this.provides = undefined;
1799
    }
1800
    /**
1801
    Define a state field.
1802
    */
1803
    static define(config) {
1804
        let field = new StateField(nextID++, config.create, config.update, config.compare || ((a, b) => a === b), config);
1805
        if (config.provide)
1806
            field.provides = config.provide(field);
1807
        return field;
1808
    }
1809
    create(state) {
1810
        let init = state.facet(initField).find(i => i.field == this);
1811
        return ((init === null || init === void 0 ? void 0 : init.create) || this.createF)(state);
1812
    }
1813
    /**
1814
    @internal
1815
    */
1816
    slot(addresses) {
1817
        let idx = addresses[this.id] >> 1;
1818
        return {
1819
            create: (state) => {
1820
                state.values[idx] = this.create(state);
1821
                return 1 /* SlotStatus.Changed */;
1822
            },
1823
            update: (state, tr) => {
1824
                let oldVal = state.values[idx];
1825
                let value = this.updateF(oldVal, tr);
1826
                if (this.compareF(oldVal, value))
1827
                    return 0;
1828
                state.values[idx] = value;
1829
                return 1 /* SlotStatus.Changed */;
1830
            },
1831
            reconfigure: (state, oldState) => {
1832
                if (oldState.config.address[this.id] != null) {
1833
                    state.values[idx] = oldState.field(this);
1834
                    return 0;
1835
                }
1836
                state.values[idx] = this.create(state);
1837
                return 1 /* SlotStatus.Changed */;
1838
            }
1839
        };
1840
    }
1841
    /**
1842
    Returns an extension that enables this field and overrides the
1843
    way it is initialized. Can be useful when you need to provide a
1844
    non-default starting value for the field.
1845
    */
1846
    init(create) {
1847
        return [this, initField.of({ field: this, create })];
1848
    }
1849
    /**
1850
    State field instances can be used as
1851
    [`Extension`](https://codemirror.net/6/docs/ref/#state.Extension) values to enable the field in a
1852
    given state.
1853
    */
1854
    get extension() { return this; }
1855
}
1856
const Prec_ = { lowest: 4, low: 3, default: 2, high: 1, highest: 0 };
1857
function prec(value) {
1858
    return (ext) => new PrecExtension(ext, value);
1859
}
1860
/**
1861
By default extensions are registered in the order they are found
1862
in the flattened form of nested array that was provided.
1863
Individual extension values can be assigned a precedence to
1864
override this. Extensions that do not have a precedence set get
1865
the precedence of the nearest parent with a precedence, or
1866
[`default`](https://codemirror.net/6/docs/ref/#state.Prec.default) if there is no such parent. The
1867
final ordering of extensions is determined by first sorting by
1868
precedence and then by order within each precedence.
1869
*/
1870
const Prec = {
1871
    /**
1872
    The highest precedence level, for extensions that should end up
1873
    near the start of the precedence ordering.
1874
    */
1875
    highest: /*@__PURE__*/prec(Prec_.highest),
1876
    /**
1877
    A higher-than-default precedence, for extensions that should
1878
    come before those with default precedence.
1879
    */
1880
    high: /*@__PURE__*/prec(Prec_.high),
1881
    /**
1882
    The default precedence, which is also used for extensions
1883
    without an explicit precedence.
1884
    */
1885
    default: /*@__PURE__*/prec(Prec_.default),
1886
    /**
1887
    A lower-than-default precedence.
1888
    */
1889
    low: /*@__PURE__*/prec(Prec_.low),
1890
    /**
1891
    The lowest precedence level. Meant for things that should end up
1892
    near the end of the extension order.
1893
    */
1894
    lowest: /*@__PURE__*/prec(Prec_.lowest)
1895
};
1896
class PrecExtension {
1897
    constructor(inner, prec) {
1898
        this.inner = inner;
1899
        this.prec = prec;
1900
    }
1901
}
1902
/**
1903
Extension compartments can be used to make a configuration
1904
dynamic. By [wrapping](https://codemirror.net/6/docs/ref/#state.Compartment.of) part of your
1905
configuration in a compartment, you can later
1906
[replace](https://codemirror.net/6/docs/ref/#state.Compartment.reconfigure) that part through a
1907
transaction.
1908
*/
1909
class Compartment {
1910
    /**
1911
    Create an instance of this compartment to add to your [state
1912
    configuration](https://codemirror.net/6/docs/ref/#state.EditorStateConfig.extensions).
1913
    */
1914
    of(ext) { return new CompartmentInstance(this, ext); }
1915
    /**
1916
    Create an [effect](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects) that
1917
    reconfigures this compartment.
1918
    */
1919
    reconfigure(content) {
1920
        return Compartment.reconfigure.of({ compartment: this, extension: content });
1921
    }
1922
    /**
1923
    Get the current content of the compartment in the state, or
1924
    `undefined` if it isn't present.
1925
    */
1926
    get(state) {
1927
        return state.config.compartments.get(this);
1928
    }
1929
}
1930
class CompartmentInstance {
1931
    constructor(compartment, inner) {
1932
        this.compartment = compartment;
1933
        this.inner = inner;
1934
    }
1935
}
1936
class Configuration {
1937
    constructor(base, compartments, dynamicSlots, address, staticValues, facets) {
1938
        this.base = base;
1939
        this.compartments = compartments;
1940
        this.dynamicSlots = dynamicSlots;
1941
        this.address = address;
1942
        this.staticValues = staticValues;
1943
        this.facets = facets;
1944
        this.statusTemplate = [];
1945
        while (this.statusTemplate.length < dynamicSlots.length)
1946
            this.statusTemplate.push(0 /* SlotStatus.Unresolved */);
1947
    }
1948
    staticFacet(facet) {
1949
        let addr = this.address[facet.id];
1950
        return addr == null ? facet.default : this.staticValues[addr >> 1];
1951
    }
1952
    static resolve(base, compartments, oldState) {
1953
        let fields = [];
1954
        let facets = Object.create(null);
1955
        let newCompartments = new Map();
1956
        for (let ext of flatten(base, compartments, newCompartments)) {
1957
            if (ext instanceof StateField)
1958
                fields.push(ext);
1959
            else
1960
                (facets[ext.facet.id] || (facets[ext.facet.id] = [])).push(ext);
1961
        }
1962
        let address = Object.create(null);
1963
        let staticValues = [];
1964
        let dynamicSlots = [];
1965
        for (let field of fields) {
1966
            address[field.id] = dynamicSlots.length << 1;
1967
            dynamicSlots.push(a => field.slot(a));
1968
        }
1969
        let oldFacets = oldState === null || oldState === void 0 ? void 0 : oldState.config.facets;
1970
        for (let id in facets) {
1971
            let providers = facets[id], facet = providers[0].facet;
1972
            let oldProviders = oldFacets && oldFacets[id] || [];
1973
            if (providers.every(p => p.type == 0 /* Provider.Static */)) {
1974
                address[facet.id] = (staticValues.length << 1) | 1;
1975
                if (sameArray$1(oldProviders, providers)) {
1976
                    staticValues.push(oldState.facet(facet));
1977
                }
1978
                else {
1979
                    let value = facet.combine(providers.map(p => p.value));
1980
                    staticValues.push(oldState && facet.compare(value, oldState.facet(facet)) ? oldState.facet(facet) : value);
1981
                }
1982
            }
1983
            else {
1984
                for (let p of providers) {
1985
                    if (p.type == 0 /* Provider.Static */) {
1986
                        address[p.id] = (staticValues.length << 1) | 1;
1987
                        staticValues.push(p.value);
1988
                    }
1989
                    else {
1990
                        address[p.id] = dynamicSlots.length << 1;
1991
                        dynamicSlots.push(a => p.dynamicSlot(a));
1992
                    }
1993
                }
1994
                address[facet.id] = dynamicSlots.length << 1;
1995
                dynamicSlots.push(a => dynamicFacetSlot(a, facet, providers));
1996
            }
1997
        }
1998
        let dynamic = dynamicSlots.map(f => f(address));
1999
        return new Configuration(base, newCompartments, dynamic, address, staticValues, facets);
2000
    }
2001
}
2002
function flatten(extension, compartments, newCompartments) {
2003
    let result = [[], [], [], [], []];
2004
    let seen = new Map();
2005
    function inner(ext, prec) {
2006
        let known = seen.get(ext);
2007
        if (known != null) {
2008
            if (known <= prec)
2009
                return;
2010
            let found = result[known].indexOf(ext);
2011
            if (found > -1)
2012
                result[known].splice(found, 1);
2013
            if (ext instanceof CompartmentInstance)
2014
                newCompartments.delete(ext.compartment);
2015
        }
2016
        seen.set(ext, prec);
2017
        if (Array.isArray(ext)) {
2018
            for (let e of ext)
2019
                inner(e, prec);
2020
        }
2021
        else if (ext instanceof CompartmentInstance) {
2022
            if (newCompartments.has(ext.compartment))
2023
                throw new RangeError(`Duplicate use of compartment in extensions`);
2024
            let content = compartments.get(ext.compartment) || ext.inner;
2025
            newCompartments.set(ext.compartment, content);
2026
            inner(content, prec);
2027
        }
2028
        else if (ext instanceof PrecExtension) {
2029
            inner(ext.inner, ext.prec);
2030
        }
2031
        else if (ext instanceof StateField) {
2032
            result[prec].push(ext);
2033
            if (ext.provides)
2034
                inner(ext.provides, prec);
2035
        }
2036
        else if (ext instanceof FacetProvider) {
2037
            result[prec].push(ext);
2038
            if (ext.facet.extensions)
2039
                inner(ext.facet.extensions, Prec_.default);
2040
        }
2041
        else {
2042
            let content = ext.extension;
2043
            if (!content)
2044
                throw new Error(`Unrecognized extension value in extension set (${ext}). This sometimes happens because multiple instances of @codemirror/state are loaded, breaking instanceof checks.`);
2045
            inner(content, prec);
2046
        }
2047
    }
2048
    inner(extension, Prec_.default);
2049
    return result.reduce((a, b) => a.concat(b));
2050
}
2051
function ensureAddr(state, addr) {
2052
    if (addr & 1)
2053
        return 2 /* SlotStatus.Computed */;
2054
    let idx = addr >> 1;
2055
    let status = state.status[idx];
2056
    if (status == 4 /* SlotStatus.Computing */)
2057
        throw new Error("Cyclic dependency between fields and/or facets");
2058
    if (status & 2 /* SlotStatus.Computed */)
2059
        return status;
2060
    state.status[idx] = 4 /* SlotStatus.Computing */;
2061
    let changed = state.computeSlot(state, state.config.dynamicSlots[idx]);
2062
    return state.status[idx] = 2 /* SlotStatus.Computed */ | changed;
2063
}
2064
function getAddr(state, addr) {
2065
    return addr & 1 ? state.config.staticValues[addr >> 1] : state.values[addr >> 1];
2066
}
2067
 
2068
const languageData = /*@__PURE__*/Facet.define();
2069
const allowMultipleSelections = /*@__PURE__*/Facet.define({
2070
    combine: values => values.some(v => v),
2071
    static: true
2072
});
2073
const lineSeparator = /*@__PURE__*/Facet.define({
2074
    combine: values => values.length ? values[0] : undefined,
2075
    static: true
2076
});
2077
const changeFilter = /*@__PURE__*/Facet.define();
2078
const transactionFilter = /*@__PURE__*/Facet.define();
2079
const transactionExtender = /*@__PURE__*/Facet.define();
2080
const readOnly = /*@__PURE__*/Facet.define({
2081
    combine: values => values.length ? values[0] : false
2082
});
2083
 
2084
/**
2085
Annotations are tagged values that are used to add metadata to
2086
transactions in an extensible way. They should be used to model
2087
things that effect the entire transaction (such as its [time
2088
stamp](https://codemirror.net/6/docs/ref/#state.Transaction^time) or information about its
2089
[origin](https://codemirror.net/6/docs/ref/#state.Transaction^userEvent)). For effects that happen
2090
_alongside_ the other changes made by the transaction, [state
2091
effects](https://codemirror.net/6/docs/ref/#state.StateEffect) are more appropriate.
2092
*/
2093
class Annotation {
2094
    /**
2095
    @internal
2096
    */
2097
    constructor(
2098
    /**
2099
    The annotation type.
2100
    */
2101
    type,
2102
    /**
2103
    The value of this annotation.
2104
    */
2105
    value) {
2106
        this.type = type;
2107
        this.value = value;
2108
    }
2109
    /**
2110
    Define a new type of annotation.
2111
    */
2112
    static define() { return new AnnotationType(); }
2113
}
2114
/**
2115
Marker that identifies a type of [annotation](https://codemirror.net/6/docs/ref/#state.Annotation).
2116
*/
2117
class AnnotationType {
2118
    /**
2119
    Create an instance of this annotation.
2120
    */
2121
    of(value) { return new Annotation(this, value); }
2122
}
2123
/**
2124
Representation of a type of state effect. Defined with
2125
[`StateEffect.define`](https://codemirror.net/6/docs/ref/#state.StateEffect^define).
2126
*/
2127
class StateEffectType {
2128
    /**
2129
    @internal
2130
    */
2131
    constructor(
2132
    // The `any` types in these function types are there to work
2133
    // around TypeScript issue #37631, where the type guard on
2134
    // `StateEffect.is` mysteriously stops working when these properly
2135
    // have type `Value`.
2136
    /**
2137
    @internal
2138
    */
2139
    map) {
2140
        this.map = map;
2141
    }
2142
    /**
2143
    Create a [state effect](https://codemirror.net/6/docs/ref/#state.StateEffect) instance of this
2144
    type.
2145
    */
2146
    of(value) { return new StateEffect(this, value); }
2147
}
2148
/**
2149
State effects can be used to represent additional effects
2150
associated with a [transaction](https://codemirror.net/6/docs/ref/#state.Transaction.effects). They
2151
are often useful to model changes to custom [state
2152
fields](https://codemirror.net/6/docs/ref/#state.StateField), when those changes aren't implicit in
2153
document or selection changes.
2154
*/
2155
class StateEffect {
2156
    /**
2157
    @internal
2158
    */
2159
    constructor(
2160
    /**
2161
    @internal
2162
    */
2163
    type,
2164
    /**
2165
    The value of this effect.
2166
    */
2167
    value) {
2168
        this.type = type;
2169
        this.value = value;
2170
    }
2171
    /**
2172
    Map this effect through a position mapping. Will return
2173
    `undefined` when that ends up deleting the effect.
2174
    */
2175
    map(mapping) {
2176
        let mapped = this.type.map(this.value, mapping);
2177
        return mapped === undefined ? undefined : mapped == this.value ? this : new StateEffect(this.type, mapped);
2178
    }
2179
    /**
2180
    Tells you whether this effect object is of a given
2181
    [type](https://codemirror.net/6/docs/ref/#state.StateEffectType).
2182
    */
2183
    is(type) { return this.type == type; }
2184
    /**
2185
    Define a new effect type. The type parameter indicates the type
2186
    of values that his effect holds. It should be a type that
2187
    doesn't include `undefined`, since that is used in
2188
    [mapping](https://codemirror.net/6/docs/ref/#state.StateEffect.map) to indicate that an effect is
2189
    removed.
2190
    */
2191
    static define(spec = {}) {
2192
        return new StateEffectType(spec.map || (v => v));
2193
    }
2194
    /**
2195
    Map an array of effects through a change set.
2196
    */
2197
    static mapEffects(effects, mapping) {
2198
        if (!effects.length)
2199
            return effects;
2200
        let result = [];
2201
        for (let effect of effects) {
2202
            let mapped = effect.map(mapping);
2203
            if (mapped)
2204
                result.push(mapped);
2205
        }
2206
        return result;
2207
    }
2208
}
2209
/**
2210
This effect can be used to reconfigure the root extensions of
2211
the editor. Doing this will discard any extensions
2212
[appended](https://codemirror.net/6/docs/ref/#state.StateEffect^appendConfig), but does not reset
2213
the content of [reconfigured](https://codemirror.net/6/docs/ref/#state.Compartment.reconfigure)
2214
compartments.
2215
*/
2216
StateEffect.reconfigure = /*@__PURE__*/StateEffect.define();
2217
/**
2218
Append extensions to the top-level configuration of the editor.
2219
*/
2220
StateEffect.appendConfig = /*@__PURE__*/StateEffect.define();
2221
/**
2222
Changes to the editor state are grouped into transactions.
2223
Typically, a user action creates a single transaction, which may
2224
contain any number of document changes, may change the selection,
2225
or have other effects. Create a transaction by calling
2226
[`EditorState.update`](https://codemirror.net/6/docs/ref/#state.EditorState.update), or immediately
2227
dispatch one by calling
2228
[`EditorView.dispatch`](https://codemirror.net/6/docs/ref/#view.EditorView.dispatch).
2229
*/
2230
class Transaction {
2231
    constructor(
2232
    /**
2233
    The state from which the transaction starts.
2234
    */
2235
    startState,
2236
    /**
2237
    The document changes made by this transaction.
2238
    */
2239
    changes,
2240
    /**
2241
    The selection set by this transaction, or undefined if it
2242
    doesn't explicitly set a selection.
2243
    */
2244
    selection,
2245
    /**
2246
    The effects added to the transaction.
2247
    */
2248
    effects,
2249
    /**
2250
    @internal
2251
    */
2252
    annotations,
2253
    /**
2254
    Whether the selection should be scrolled into view after this
2255
    transaction is dispatched.
2256
    */
2257
    scrollIntoView) {
2258
        this.startState = startState;
2259
        this.changes = changes;
2260
        this.selection = selection;
2261
        this.effects = effects;
2262
        this.annotations = annotations;
2263
        this.scrollIntoView = scrollIntoView;
2264
        /**
2265
        @internal
2266
        */
2267
        this._doc = null;
2268
        /**
2269
        @internal
2270
        */
2271
        this._state = null;
2272
        if (selection)
2273
            checkSelection(selection, changes.newLength);
2274
        if (!annotations.some((a) => a.type == Transaction.time))
2275
            this.annotations = annotations.concat(Transaction.time.of(Date.now()));
2276
    }
2277
    /**
2278
    @internal
2279
    */
2280
    static create(startState, changes, selection, effects, annotations, scrollIntoView) {
2281
        return new Transaction(startState, changes, selection, effects, annotations, scrollIntoView);
2282
    }
2283
    /**
2284
    The new document produced by the transaction. Contrary to
2285
    [`.state`](https://codemirror.net/6/docs/ref/#state.Transaction.state)`.doc`, accessing this won't
2286
    force the entire new state to be computed right away, so it is
2287
    recommended that [transaction
2288
    filters](https://codemirror.net/6/docs/ref/#state.EditorState^transactionFilter) use this getter
2289
    when they need to look at the new document.
2290
    */
2291
    get newDoc() {
2292
        return this._doc || (this._doc = this.changes.apply(this.startState.doc));
2293
    }
2294
    /**
2295
    The new selection produced by the transaction. If
2296
    [`this.selection`](https://codemirror.net/6/docs/ref/#state.Transaction.selection) is undefined,
2297
    this will [map](https://codemirror.net/6/docs/ref/#state.EditorSelection.map) the start state's
2298
    current selection through the changes made by the transaction.
2299
    */
2300
    get newSelection() {
2301
        return this.selection || this.startState.selection.map(this.changes);
2302
    }
2303
    /**
2304
    The new state created by the transaction. Computed on demand
2305
    (but retained for subsequent access), so it is recommended not to
2306
    access it in [transaction
2307
    filters](https://codemirror.net/6/docs/ref/#state.EditorState^transactionFilter) when possible.
2308
    */
2309
    get state() {
2310
        if (!this._state)
2311
            this.startState.applyTransaction(this);
2312
        return this._state;
2313
    }
2314
    /**
2315
    Get the value of the given annotation type, if any.
2316
    */
2317
    annotation(type) {
2318
        for (let ann of this.annotations)
2319
            if (ann.type == type)
2320
                return ann.value;
2321
        return undefined;
2322
    }
2323
    /**
2324
    Indicates whether the transaction changed the document.
2325
    */
2326
    get docChanged() { return !this.changes.empty; }
2327
    /**
2328
    Indicates whether this transaction reconfigures the state
2329
    (through a [configuration compartment](https://codemirror.net/6/docs/ref/#state.Compartment) or
2330
    with a top-level configuration
2331
    [effect](https://codemirror.net/6/docs/ref/#state.StateEffect^reconfigure).
2332
    */
2333
    get reconfigured() { return this.startState.config != this.state.config; }
2334
    /**
2335
    Returns true if the transaction has a [user
2336
    event](https://codemirror.net/6/docs/ref/#state.Transaction^userEvent) annotation that is equal to
2337
    or more specific than `event`. For example, if the transaction
2338
    has `"select.pointer"` as user event, `"select"` and
2339
    `"select.pointer"` will match it.
2340
    */
2341
    isUserEvent(event) {
2342
        let e = this.annotation(Transaction.userEvent);
2343
        return !!(e && (e == event || e.length > event.length && e.slice(0, event.length) == event && e[event.length] == "."));
2344
    }
2345
}
2346
/**
2347
Annotation used to store transaction timestamps. Automatically
2348
added to every transaction, holding `Date.now()`.
2349
*/
2350
Transaction.time = /*@__PURE__*/Annotation.define();
2351
/**
2352
Annotation used to associate a transaction with a user interface
2353
event. Holds a string identifying the event, using a
2354
dot-separated format to support attaching more specific
2355
information. The events used by the core libraries are:
2356
 
2357
 - `"input"` when content is entered
2358
   - `"input.type"` for typed input
2359
     - `"input.type.compose"` for composition
2360
   - `"input.paste"` for pasted input
2361
   - `"input.drop"` when adding content with drag-and-drop
2362
   - `"input.complete"` when autocompleting
2363
 - `"delete"` when the user deletes content
2364
   - `"delete.selection"` when deleting the selection
2365
   - `"delete.forward"` when deleting forward from the selection
2366
   - `"delete.backward"` when deleting backward from the selection
2367
   - `"delete.cut"` when cutting to the clipboard
2368
 - `"move"` when content is moved
2369
   - `"move.drop"` when content is moved within the editor through drag-and-drop
2370
 - `"select"` when explicitly changing the selection
2371
   - `"select.pointer"` when selecting with a mouse or other pointing device
2372
 - `"undo"` and `"redo"` for history actions
2373
 
2374
Use [`isUserEvent`](https://codemirror.net/6/docs/ref/#state.Transaction.isUserEvent) to check
2375
whether the annotation matches a given event.
2376
*/
2377
Transaction.userEvent = /*@__PURE__*/Annotation.define();
2378
/**
2379
Annotation indicating whether a transaction should be added to
2380
the undo history or not.
2381
*/
2382
Transaction.addToHistory = /*@__PURE__*/Annotation.define();
2383
/**
2384
Annotation indicating (when present and true) that a transaction
2385
represents a change made by some other actor, not the user. This
2386
is used, for example, to tag other people's changes in
2387
collaborative editing.
2388
*/
2389
Transaction.remote = /*@__PURE__*/Annotation.define();
2390
function joinRanges(a, b) {
2391
    let result = [];
2392
    for (let iA = 0, iB = 0;;) {
2393
        let from, to;
2394
        if (iA < a.length && (iB == b.length || b[iB] >= a[iA])) {
2395
            from = a[iA++];
2396
            to = a[iA++];
2397
        }
2398
        else if (iB < b.length) {
2399
            from = b[iB++];
2400
            to = b[iB++];
2401
        }
2402
        else
2403
            return result;
2404
        if (!result.length || result[result.length - 1] < from)
2405
            result.push(from, to);
2406
        else if (result[result.length - 1] < to)
2407
            result[result.length - 1] = to;
2408
    }
2409
}
2410
function mergeTransaction(a, b, sequential) {
2411
    var _a;
2412
    let mapForA, mapForB, changes;
2413
    if (sequential) {
2414
        mapForA = b.changes;
2415
        mapForB = ChangeSet.empty(b.changes.length);
2416
        changes = a.changes.compose(b.changes);
2417
    }
2418
    else {
2419
        mapForA = b.changes.map(a.changes);
2420
        mapForB = a.changes.mapDesc(b.changes, true);
2421
        changes = a.changes.compose(mapForA);
2422
    }
2423
    return {
2424
        changes,
2425
        selection: b.selection ? b.selection.map(mapForB) : (_a = a.selection) === null || _a === void 0 ? void 0 : _a.map(mapForA),
2426
        effects: StateEffect.mapEffects(a.effects, mapForA).concat(StateEffect.mapEffects(b.effects, mapForB)),
2427
        annotations: a.annotations.length ? a.annotations.concat(b.annotations) : b.annotations,
2428
        scrollIntoView: a.scrollIntoView || b.scrollIntoView
2429
    };
2430
}
2431
function resolveTransactionInner(state, spec, docSize) {
2432
    let sel = spec.selection, annotations = asArray$1(spec.annotations);
2433
    if (spec.userEvent)
2434
        annotations = annotations.concat(Transaction.userEvent.of(spec.userEvent));
2435
    return {
2436
        changes: spec.changes instanceof ChangeSet ? spec.changes
2437
            : ChangeSet.of(spec.changes || [], docSize, state.facet(lineSeparator)),
2438
        selection: sel && (sel instanceof EditorSelection ? sel : EditorSelection.single(sel.anchor, sel.head)),
2439
        effects: asArray$1(spec.effects),
2440
        annotations,
2441
        scrollIntoView: !!spec.scrollIntoView
2442
    };
2443
}
2444
function resolveTransaction(state, specs, filter) {
2445
    let s = resolveTransactionInner(state, specs.length ? specs[0] : {}, state.doc.length);
2446
    if (specs.length && specs[0].filter === false)
2447
        filter = false;
2448
    for (let i = 1; i < specs.length; i++) {
2449
        if (specs[i].filter === false)
2450
            filter = false;
2451
        let seq = !!specs[i].sequential;
2452
        s = mergeTransaction(s, resolveTransactionInner(state, specs[i], seq ? s.changes.newLength : state.doc.length), seq);
2453
    }
2454
    let tr = Transaction.create(state, s.changes, s.selection, s.effects, s.annotations, s.scrollIntoView);
2455
    return extendTransaction(filter ? filterTransaction(tr) : tr);
2456
}
2457
// Finish a transaction by applying filters if necessary.
2458
function filterTransaction(tr) {
2459
    let state = tr.startState;
2460
    // Change filters
2461
    let result = true;
2462
    for (let filter of state.facet(changeFilter)) {
2463
        let value = filter(tr);
2464
        if (value === false) {
2465
            result = false;
2466
            break;
2467
        }
2468
        if (Array.isArray(value))
2469
            result = result === true ? value : joinRanges(result, value);
2470
    }
2471
    if (result !== true) {
2472
        let changes, back;
2473
        if (result === false) {
2474
            back = tr.changes.invertedDesc;
2475
            changes = ChangeSet.empty(state.doc.length);
2476
        }
2477
        else {
2478
            let filtered = tr.changes.filter(result);
2479
            changes = filtered.changes;
2480
            back = filtered.filtered.mapDesc(filtered.changes).invertedDesc;
2481
        }
2482
        tr = Transaction.create(state, changes, tr.selection && tr.selection.map(back), StateEffect.mapEffects(tr.effects, back), tr.annotations, tr.scrollIntoView);
2483
    }
2484
    // Transaction filters
2485
    let filters = state.facet(transactionFilter);
2486
    for (let i = filters.length - 1; i >= 0; i--) {
2487
        let filtered = filters[i](tr);
2488
        if (filtered instanceof Transaction)
2489
            tr = filtered;
2490
        else if (Array.isArray(filtered) && filtered.length == 1 && filtered[0] instanceof Transaction)
2491
            tr = filtered[0];
2492
        else
2493
            tr = resolveTransaction(state, asArray$1(filtered), false);
2494
    }
2495
    return tr;
2496
}
2497
function extendTransaction(tr) {
2498
    let state = tr.startState, extenders = state.facet(transactionExtender), spec = tr;
2499
    for (let i = extenders.length - 1; i >= 0; i--) {
2500
        let extension = extenders[i](tr);
2501
        if (extension && Object.keys(extension).length)
2502
            spec = mergeTransaction(spec, resolveTransactionInner(state, extension, tr.changes.newLength), true);
2503
    }
2504
    return spec == tr ? tr : Transaction.create(state, tr.changes, tr.selection, spec.effects, spec.annotations, spec.scrollIntoView);
2505
}
2506
const none$2 = [];
2507
function asArray$1(value) {
2508
    return value == null ? none$2 : Array.isArray(value) ? value : [value];
2509
}
2510
 
2511
/**
2512
The categories produced by a [character
2513
categorizer](https://codemirror.net/6/docs/ref/#state.EditorState.charCategorizer). These are used
2514
do things like selecting by word.
2515
*/
2516
var CharCategory = /*@__PURE__*/(function (CharCategory) {
2517
    /**
2518
    Word characters.
2519
    */
2520
    CharCategory[CharCategory["Word"] = 0] = "Word";
2521
    /**
2522
    Whitespace.
2523
    */
2524
    CharCategory[CharCategory["Space"] = 1] = "Space";
2525
    /**
2526
    Anything else.
2527
    */
2528
    CharCategory[CharCategory["Other"] = 2] = "Other";
2529
return CharCategory})(CharCategory || (CharCategory = {}));
2530
const nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;
2531
let wordChar;
2532
try {
2533
    wordChar = /*@__PURE__*/new RegExp("[\\p{Alphabetic}\\p{Number}_]", "u");
2534
}
2535
catch (_) { }
2536
function hasWordChar(str) {
2537
    if (wordChar)
2538
        return wordChar.test(str);
2539
    for (let i = 0; i < str.length; i++) {
2540
        let ch = str[i];
2541
        if (/\w/.test(ch) || ch > "\x80" && (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch)))
2542
            return true;
2543
    }
2544
    return false;
2545
}
2546
function makeCategorizer(wordChars) {
2547
    return (char) => {
2548
        if (!/\S/.test(char))
2549
            return CharCategory.Space;
2550
        if (hasWordChar(char))
2551
            return CharCategory.Word;
2552
        for (let i = 0; i < wordChars.length; i++)
2553
            if (char.indexOf(wordChars[i]) > -1)
2554
                return CharCategory.Word;
2555
        return CharCategory.Other;
2556
    };
2557
}
2558
 
2559
/**
2560
The editor state class is a persistent (immutable) data structure.
2561
To update a state, you [create](https://codemirror.net/6/docs/ref/#state.EditorState.update) a
2562
[transaction](https://codemirror.net/6/docs/ref/#state.Transaction), which produces a _new_ state
2563
instance, without modifying the original object.
2564
 
2565
As such, _never_ mutate properties of a state directly. That'll
2566
just break things.
2567
*/
2568
class EditorState {
2569
    constructor(
2570
    /**
2571
    @internal
2572
    */
2573
    config,
2574
    /**
2575
    The current document.
2576
    */
2577
    doc,
2578
    /**
2579
    The current selection.
2580
    */
2581
    selection,
2582
    /**
2583
    @internal
2584
    */
2585
    values, computeSlot, tr) {
2586
        this.config = config;
2587
        this.doc = doc;
2588
        this.selection = selection;
2589
        this.values = values;
2590
        this.status = config.statusTemplate.slice();
2591
        this.computeSlot = computeSlot;
2592
        // Fill in the computed state immediately, so that further queries
2593
        // for it made during the update return this state
2594
        if (tr)
2595
            tr._state = this;
2596
        for (let i = 0; i < this.config.dynamicSlots.length; i++)
2597
            ensureAddr(this, i << 1);
2598
        this.computeSlot = null;
2599
    }
2600
    field(field, require = true) {
2601
        let addr = this.config.address[field.id];
2602
        if (addr == null) {
2603
            if (require)
2604
                throw new RangeError("Field is not present in this state");
2605
            return undefined;
2606
        }
2607
        ensureAddr(this, addr);
2608
        return getAddr(this, addr);
2609
    }
2610
    /**
2611
    Create a [transaction](https://codemirror.net/6/docs/ref/#state.Transaction) that updates this
2612
    state. Any number of [transaction specs](https://codemirror.net/6/docs/ref/#state.TransactionSpec)
2613
    can be passed. Unless
2614
    [`sequential`](https://codemirror.net/6/docs/ref/#state.TransactionSpec.sequential) is set, the
2615
    [changes](https://codemirror.net/6/docs/ref/#state.TransactionSpec.changes) (if any) of each spec
2616
    are assumed to start in the _current_ document (not the document
2617
    produced by previous specs), and its
2618
    [selection](https://codemirror.net/6/docs/ref/#state.TransactionSpec.selection) and
2619
    [effects](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects) are assumed to refer
2620
    to the document created by its _own_ changes. The resulting
2621
    transaction contains the combined effect of all the different
2622
    specs. For [selection](https://codemirror.net/6/docs/ref/#state.TransactionSpec.selection), later
2623
    specs take precedence over earlier ones.
2624
    */
2625
    update(...specs) {
2626
        return resolveTransaction(this, specs, true);
2627
    }
2628
    /**
2629
    @internal
2630
    */
2631
    applyTransaction(tr) {
2632
        let conf = this.config, { base, compartments } = conf;
2633
        for (let effect of tr.effects) {
2634
            if (effect.is(Compartment.reconfigure)) {
2635
                if (conf) {
2636
                    compartments = new Map;
2637
                    conf.compartments.forEach((val, key) => compartments.set(key, val));
2638
                    conf = null;
2639
                }
2640
                compartments.set(effect.value.compartment, effect.value.extension);
2641
            }
2642
            else if (effect.is(StateEffect.reconfigure)) {
2643
                conf = null;
2644
                base = effect.value;
2645
            }
2646
            else if (effect.is(StateEffect.appendConfig)) {
2647
                conf = null;
2648
                base = asArray$1(base).concat(effect.value);
2649
            }
2650
        }
2651
        let startValues;
2652
        if (!conf) {
2653
            conf = Configuration.resolve(base, compartments, this);
2654
            let intermediateState = new EditorState(conf, this.doc, this.selection, conf.dynamicSlots.map(() => null), (state, slot) => slot.reconfigure(state, this), null);
2655
            startValues = intermediateState.values;
2656
        }
2657
        else {
2658
            startValues = tr.startState.values.slice();
2659
        }
2660
        let selection = tr.startState.facet(allowMultipleSelections) ? tr.newSelection : tr.newSelection.asSingle();
2661
        new EditorState(conf, tr.newDoc, selection, startValues, (state, slot) => slot.update(state, tr), tr);
2662
    }
2663
    /**
2664
    Create a [transaction spec](https://codemirror.net/6/docs/ref/#state.TransactionSpec) that
2665
    replaces every selection range with the given content.
2666
    */
2667
    replaceSelection(text) {
2668
        if (typeof text == "string")
2669
            text = this.toText(text);
2670
        return this.changeByRange(range => ({ changes: { from: range.from, to: range.to, insert: text },
2671
            range: EditorSelection.cursor(range.from + text.length) }));
2672
    }
2673
    /**
2674
    Create a set of changes and a new selection by running the given
2675
    function for each range in the active selection. The function
2676
    can return an optional set of changes (in the coordinate space
2677
    of the start document), plus an updated range (in the coordinate
2678
    space of the document produced by the call's own changes). This
2679
    method will merge all the changes and ranges into a single
2680
    changeset and selection, and return it as a [transaction
2681
    spec](https://codemirror.net/6/docs/ref/#state.TransactionSpec), which can be passed to
2682
    [`update`](https://codemirror.net/6/docs/ref/#state.EditorState.update).
2683
    */
2684
    changeByRange(f) {
2685
        let sel = this.selection;
2686
        let result1 = f(sel.ranges[0]);
2687
        let changes = this.changes(result1.changes), ranges = [result1.range];
2688
        let effects = asArray$1(result1.effects);
2689
        for (let i = 1; i < sel.ranges.length; i++) {
2690
            let result = f(sel.ranges[i]);
2691
            let newChanges = this.changes(result.changes), newMapped = newChanges.map(changes);
2692
            for (let j = 0; j < i; j++)
2693
                ranges[j] = ranges[j].map(newMapped);
2694
            let mapBy = changes.mapDesc(newChanges, true);
2695
            ranges.push(result.range.map(mapBy));
2696
            changes = changes.compose(newMapped);
2697
            effects = StateEffect.mapEffects(effects, newMapped).concat(StateEffect.mapEffects(asArray$1(result.effects), mapBy));
2698
        }
2699
        return {
2700
            changes,
2701
            selection: EditorSelection.create(ranges, sel.mainIndex),
2702
            effects
2703
        };
2704
    }
2705
    /**
2706
    Create a [change set](https://codemirror.net/6/docs/ref/#state.ChangeSet) from the given change
2707
    description, taking the state's document length and line
2708
    separator into account.
2709
    */
2710
    changes(spec = []) {
2711
        if (spec instanceof ChangeSet)
2712
            return spec;
2713
        return ChangeSet.of(spec, this.doc.length, this.facet(EditorState.lineSeparator));
2714
    }
2715
    /**
2716
    Using the state's [line
2717
    separator](https://codemirror.net/6/docs/ref/#state.EditorState^lineSeparator), create a
2718
    [`Text`](https://codemirror.net/6/docs/ref/#state.Text) instance from the given string.
2719
    */
2720
    toText(string) {
2721
        return Text.of(string.split(this.facet(EditorState.lineSeparator) || DefaultSplit));
2722
    }
2723
    /**
2724
    Return the given range of the document as a string.
2725
    */
2726
    sliceDoc(from = 0, to = this.doc.length) {
2727
        return this.doc.sliceString(from, to, this.lineBreak);
2728
    }
2729
    /**
2730
    Get the value of a state [facet](https://codemirror.net/6/docs/ref/#state.Facet).
2731
    */
2732
    facet(facet) {
2733
        let addr = this.config.address[facet.id];
2734
        if (addr == null)
2735
            return facet.default;
2736
        ensureAddr(this, addr);
2737
        return getAddr(this, addr);
2738
    }
2739
    /**
2740
    Convert this state to a JSON-serializable object. When custom
2741
    fields should be serialized, you can pass them in as an object
2742
    mapping property names (in the resulting object, which should
2743
    not use `doc` or `selection`) to fields.
2744
    */
2745
    toJSON(fields) {
2746
        let result = {
2747
            doc: this.sliceDoc(),
2748
            selection: this.selection.toJSON()
2749
        };
2750
        if (fields)
2751
            for (let prop in fields) {
2752
                let value = fields[prop];
2753
                if (value instanceof StateField && this.config.address[value.id] != null)
2754
                    result[prop] = value.spec.toJSON(this.field(fields[prop]), this);
2755
            }
2756
        return result;
2757
    }
2758
    /**
2759
    Deserialize a state from its JSON representation. When custom
2760
    fields should be deserialized, pass the same object you passed
2761
    to [`toJSON`](https://codemirror.net/6/docs/ref/#state.EditorState.toJSON) when serializing as
2762
    third argument.
2763
    */
2764
    static fromJSON(json, config = {}, fields) {
2765
        if (!json || typeof json.doc != "string")
2766
            throw new RangeError("Invalid JSON representation for EditorState");
2767
        let fieldInit = [];
2768
        if (fields)
2769
            for (let prop in fields) {
2770
                if (Object.prototype.hasOwnProperty.call(json, prop)) {
2771
                    let field = fields[prop], value = json[prop];
2772
                    fieldInit.push(field.init(state => field.spec.fromJSON(value, state)));
2773
                }
2774
            }
2775
        return EditorState.create({
2776
            doc: json.doc,
2777
            selection: EditorSelection.fromJSON(json.selection),
2778
            extensions: config.extensions ? fieldInit.concat([config.extensions]) : fieldInit
2779
        });
2780
    }
2781
    /**
2782
    Create a new state. You'll usually only need this when
2783
    initializing an editor—updated states are created by applying
2784
    transactions.
2785
    */
2786
    static create(config = {}) {
2787
        let configuration = Configuration.resolve(config.extensions || [], new Map);
2788
        let doc = config.doc instanceof Text ? config.doc
2789
            : Text.of((config.doc || "").split(configuration.staticFacet(EditorState.lineSeparator) || DefaultSplit));
2790
        let selection = !config.selection ? EditorSelection.single(0)
2791
            : config.selection instanceof EditorSelection ? config.selection
2792
                : EditorSelection.single(config.selection.anchor, config.selection.head);
2793
        checkSelection(selection, doc.length);
2794
        if (!configuration.staticFacet(allowMultipleSelections))
2795
            selection = selection.asSingle();
2796
        return new EditorState(configuration, doc, selection, configuration.dynamicSlots.map(() => null), (state, slot) => slot.create(state), null);
2797
    }
2798
    /**
2799
    The size (in columns) of a tab in the document, determined by
2800
    the [`tabSize`](https://codemirror.net/6/docs/ref/#state.EditorState^tabSize) facet.
2801
    */
2802
    get tabSize() { return this.facet(EditorState.tabSize); }
2803
    /**
2804
    Get the proper [line-break](https://codemirror.net/6/docs/ref/#state.EditorState^lineSeparator)
2805
    string for this state.
2806
    */
2807
    get lineBreak() { return this.facet(EditorState.lineSeparator) || "\n"; }
2808
    /**
2809
    Returns true when the editor is
2810
    [configured](https://codemirror.net/6/docs/ref/#state.EditorState^readOnly) to be read-only.
2811
    */
2812
    get readOnly() { return this.facet(readOnly); }
2813
    /**
2814
    Look up a translation for the given phrase (via the
2815
    [`phrases`](https://codemirror.net/6/docs/ref/#state.EditorState^phrases) facet), or return the
2816
    original string if no translation is found.
2817
 
2818
    If additional arguments are passed, they will be inserted in
2819
    place of markers like `$1` (for the first value) and `$2`, etc.
2820
    A single `$` is equivalent to `$1`, and `$$` will produce a
2821
    literal dollar sign.
2822
    */
2823
    phrase(phrase, ...insert) {
2824
        for (let map of this.facet(EditorState.phrases))
2825
            if (Object.prototype.hasOwnProperty.call(map, phrase)) {
2826
                phrase = map[phrase];
2827
                break;
2828
            }
2829
        if (insert.length)
2830
            phrase = phrase.replace(/\$(\$|\d*)/g, (m, i) => {
2831
                if (i == "$")
2832
                    return "$";
2833
                let n = +(i || 1);
2834
                return !n || n > insert.length ? m : insert[n - 1];
2835
            });
2836
        return phrase;
2837
    }
2838
    /**
2839
    Find the values for a given language data field, provided by the
2840
    the [`languageData`](https://codemirror.net/6/docs/ref/#state.EditorState^languageData) facet.
2841
 
2842
    Examples of language data fields are...
2843
 
2844
    - [`"commentTokens"`](https://codemirror.net/6/docs/ref/#commands.CommentTokens) for specifying
2845
      comment syntax.
2846
    - [`"autocomplete"`](https://codemirror.net/6/docs/ref/#autocomplete.autocompletion^config.override)
2847
      for providing language-specific completion sources.
2848
    - [`"wordChars"`](https://codemirror.net/6/docs/ref/#state.EditorState.charCategorizer) for adding
2849
      characters that should be considered part of words in this
2850
      language.
2851
    - [`"closeBrackets"`](https://codemirror.net/6/docs/ref/#autocomplete.CloseBracketConfig) controls
2852
      bracket closing behavior.
2853
    */
2854
    languageDataAt(name, pos, side = -1) {
2855
        let values = [];
2856
        for (let provider of this.facet(languageData)) {
2857
            for (let result of provider(this, pos, side)) {
2858
                if (Object.prototype.hasOwnProperty.call(result, name))
2859
                    values.push(result[name]);
2860
            }
2861
        }
2862
        return values;
2863
    }
2864
    /**
2865
    Return a function that can categorize strings (expected to
2866
    represent a single [grapheme cluster](https://codemirror.net/6/docs/ref/#state.findClusterBreak))
2867
    into one of:
2868
 
2869
     - Word (contains an alphanumeric character or a character
2870
       explicitly listed in the local language's `"wordChars"`
2871
       language data, which should be a string)
2872
     - Space (contains only whitespace)
2873
     - Other (anything else)
2874
    */
2875
    charCategorizer(at) {
2876
        return makeCategorizer(this.languageDataAt("wordChars", at).join(""));
2877
    }
2878
    /**
2879
    Find the word at the given position, meaning the range
2880
    containing all [word](https://codemirror.net/6/docs/ref/#state.CharCategory.Word) characters
2881
    around it. If no word characters are adjacent to the position,
2882
    this returns null.
2883
    */
2884
    wordAt(pos) {
2885
        let { text, from, length } = this.doc.lineAt(pos);
2886
        let cat = this.charCategorizer(pos);
2887
        let start = pos - from, end = pos - from;
2888
        while (start > 0) {
2889
            let prev = findClusterBreak(text, start, false);
2890
            if (cat(text.slice(prev, start)) != CharCategory.Word)
2891
                break;
2892
            start = prev;
2893
        }
2894
        while (end < length) {
2895
            let next = findClusterBreak(text, end);
2896
            if (cat(text.slice(end, next)) != CharCategory.Word)
2897
                break;
2898
            end = next;
2899
        }
2900
        return start == end ? null : EditorSelection.range(start + from, end + from);
2901
    }
2902
}
2903
/**
2904
A facet that, when enabled, causes the editor to allow multiple
2905
ranges to be selected. Be careful though, because by default the
2906
editor relies on the native DOM selection, which cannot handle
2907
multiple selections. An extension like
2908
[`drawSelection`](https://codemirror.net/6/docs/ref/#view.drawSelection) can be used to make
2909
secondary selections visible to the user.
2910
*/
2911
EditorState.allowMultipleSelections = allowMultipleSelections;
2912
/**
2913
Configures the tab size to use in this state. The first
2914
(highest-precedence) value of the facet is used. If no value is
2915
given, this defaults to 4.
2916
*/
2917
EditorState.tabSize = /*@__PURE__*/Facet.define({
2918
    combine: values => values.length ? values[0] : 4
2919
});
2920
/**
2921
The line separator to use. By default, any of `"\n"`, `"\r\n"`
2922
and `"\r"` is treated as a separator when splitting lines, and
2923
lines are joined with `"\n"`.
2924
 
2925
When you configure a value here, only that precise separator
2926
will be used, allowing you to round-trip documents through the
2927
editor without normalizing line separators.
2928
*/
2929
EditorState.lineSeparator = lineSeparator;
2930
/**
2931
This facet controls the value of the
2932
[`readOnly`](https://codemirror.net/6/docs/ref/#state.EditorState.readOnly) getter, which is
2933
consulted by commands and extensions that implement editing
2934
functionality to determine whether they should apply. It
2935
defaults to false, but when its highest-precedence value is
2936
`true`, such functionality disables itself.
2937
 
2938
Not to be confused with
2939
[`EditorView.editable`](https://codemirror.net/6/docs/ref/#view.EditorView^editable), which
2940
controls whether the editor's DOM is set to be editable (and
2941
thus focusable).
2942
*/
2943
EditorState.readOnly = readOnly;
2944
/**
2945
Registers translation phrases. The
2946
[`phrase`](https://codemirror.net/6/docs/ref/#state.EditorState.phrase) method will look through
2947
all objects registered with this facet to find translations for
2948
its argument.
2949
*/
2950
EditorState.phrases = /*@__PURE__*/Facet.define({
2951
    compare(a, b) {
2952
        let kA = Object.keys(a), kB = Object.keys(b);
2953
        return kA.length == kB.length && kA.every(k => a[k] == b[k]);
2954
    }
2955
});
2956
/**
2957
A facet used to register [language
2958
data](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt) providers.
2959
*/
2960
EditorState.languageData = languageData;
2961
/**
2962
Facet used to register change filters, which are called for each
2963
transaction (unless explicitly
2964
[disabled](https://codemirror.net/6/docs/ref/#state.TransactionSpec.filter)), and can suppress
2965
part of the transaction's changes.
2966
 
2967
Such a function can return `true` to indicate that it doesn't
2968
want to do anything, `false` to completely stop the changes in
2969
the transaction, or a set of ranges in which changes should be
2970
suppressed. Such ranges are represented as an array of numbers,
2971
with each pair of two numbers indicating the start and end of a
2972
range. So for example `[10, 20, 100, 110]` suppresses changes
2973
between 10 and 20, and between 100 and 110.
2974
*/
2975
EditorState.changeFilter = changeFilter;
2976
/**
2977
Facet used to register a hook that gets a chance to update or
2978
replace transaction specs before they are applied. This will
2979
only be applied for transactions that don't have
2980
[`filter`](https://codemirror.net/6/docs/ref/#state.TransactionSpec.filter) set to `false`. You
2981
can either return a single transaction spec (possibly the input
2982
transaction), or an array of specs (which will be combined in
2983
the same way as the arguments to
2984
[`EditorState.update`](https://codemirror.net/6/docs/ref/#state.EditorState.update)).
2985
 
2986
When possible, it is recommended to avoid accessing
2987
[`Transaction.state`](https://codemirror.net/6/docs/ref/#state.Transaction.state) in a filter,
2988
since it will force creation of a state that will then be
2989
discarded again, if the transaction is actually filtered.
2990
 
2991
(This functionality should be used with care. Indiscriminately
2992
modifying transaction is likely to break something or degrade
2993
the user experience.)
2994
*/
2995
EditorState.transactionFilter = transactionFilter;
2996
/**
2997
This is a more limited form of
2998
[`transactionFilter`](https://codemirror.net/6/docs/ref/#state.EditorState^transactionFilter),
2999
which can only add
3000
[annotations](https://codemirror.net/6/docs/ref/#state.TransactionSpec.annotations) and
3001
[effects](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects). _But_, this type
3002
of filter runs even if the transaction has disabled regular
3003
[filtering](https://codemirror.net/6/docs/ref/#state.TransactionSpec.filter), making it suitable
3004
for effects that don't need to touch the changes or selection,
3005
but do want to process every transaction.
3006
 
3007
Extenders run _after_ filters, when both are present.
3008
*/
3009
EditorState.transactionExtender = transactionExtender;
3010
Compartment.reconfigure = /*@__PURE__*/StateEffect.define();
3011
 
3012
/**
3013
Utility function for combining behaviors to fill in a config
3014
object from an array of provided configs. `defaults` should hold
3015
default values for all optional fields in `Config`.
3016
 
3017
The function will, by default, error
3018
when a field gets two values that aren't `===`-equal, but you can
3019
provide combine functions per field to do something else.
3020
*/
3021
function combineConfig(configs, defaults, // Should hold only the optional properties of Config, but I haven't managed to express that
3022
combine = {}) {
3023
    let result = {};
3024
    for (let config of configs)
3025
        for (let key of Object.keys(config)) {
3026
            let value = config[key], current = result[key];
3027
            if (current === undefined)
3028
                result[key] = value;
3029
            else if (current === value || value === undefined) ; // No conflict
3030
            else if (Object.hasOwnProperty.call(combine, key))
3031
                result[key] = combine[key](current, value);
3032
            else
3033
                throw new Error("Config merge conflict for field " + key);
3034
        }
3035
    for (let key in defaults)
3036
        if (result[key] === undefined)
3037
            result[key] = defaults[key];
3038
    return result;
3039
}
3040
 
3041
/**
3042
Each range is associated with a value, which must inherit from
3043
this class.
3044
*/
3045
class RangeValue {
3046
    /**
3047
    Compare this value with another value. Used when comparing
3048
    rangesets. The default implementation compares by identity.
3049
    Unless you are only creating a fixed number of unique instances
3050
    of your value type, it is a good idea to implement this
3051
    properly.
3052
    */
3053
    eq(other) { return this == other; }
3054
    /**
3055
    Create a [range](https://codemirror.net/6/docs/ref/#state.Range) with this value.
3056
    */
3057
    range(from, to = from) { return Range$1.create(from, to, this); }
3058
}
3059
RangeValue.prototype.startSide = RangeValue.prototype.endSide = 0;
3060
RangeValue.prototype.point = false;
3061
RangeValue.prototype.mapMode = MapMode.TrackDel;
3062
/**
3063
A range associates a value with a range of positions.
3064
*/
3065
let Range$1 = class Range {
3066
    constructor(
3067
    /**
3068
    The range's start position.
3069
    */
3070
    from,
3071
    /**
3072
    Its end position.
3073
    */
3074
    to,
3075
    /**
3076
    The value associated with this range.
3077
    */
3078
    value) {
3079
        this.from = from;
3080
        this.to = to;
3081
        this.value = value;
3082
    }
3083
    /**
3084
    @internal
3085
    */
3086
    static create(from, to, value) {
3087
        return new Range(from, to, value);
3088
    }
3089
};
3090
function cmpRange(a, b) {
3091
    return a.from - b.from || a.value.startSide - b.value.startSide;
3092
}
3093
class Chunk {
3094
    constructor(from, to, value,
3095
    // Chunks are marked with the largest point that occurs
3096
    // in them (or -1 for no points), so that scans that are
3097
    // only interested in points (such as the
3098
    // heightmap-related logic) can skip range-only chunks.
3099
    maxPoint) {
3100
        this.from = from;
3101
        this.to = to;
3102
        this.value = value;
3103
        this.maxPoint = maxPoint;
3104
    }
3105
    get length() { return this.to[this.to.length - 1]; }
3106
    // Find the index of the given position and side. Use the ranges'
3107
    // `from` pos when `end == false`, `to` when `end == true`.
3108
    findIndex(pos, side, end, startAt = 0) {
3109
        let arr = end ? this.to : this.from;
3110
        for (let lo = startAt, hi = arr.length;;) {
3111
            if (lo == hi)
3112
                return lo;
3113
            let mid = (lo + hi) >> 1;
3114
            let diff = arr[mid] - pos || (end ? this.value[mid].endSide : this.value[mid].startSide) - side;
3115
            if (mid == lo)
3116
                return diff >= 0 ? lo : hi;
3117
            if (diff >= 0)
3118
                hi = mid;
3119
            else
3120
                lo = mid + 1;
3121
        }
3122
    }
3123
    between(offset, from, to, f) {
3124
        for (let i = this.findIndex(from, -1000000000 /* C.Far */, true), e = this.findIndex(to, 1000000000 /* C.Far */, false, i); i < e; i++)
3125
            if (f(this.from[i] + offset, this.to[i] + offset, this.value[i]) === false)
3126
                return false;
3127
    }
3128
    map(offset, changes) {
3129
        let value = [], from = [], to = [], newPos = -1, maxPoint = -1;
3130
        for (let i = 0; i < this.value.length; i++) {
3131
            let val = this.value[i], curFrom = this.from[i] + offset, curTo = this.to[i] + offset, newFrom, newTo;
3132
            if (curFrom == curTo) {
3133
                let mapped = changes.mapPos(curFrom, val.startSide, val.mapMode);
3134
                if (mapped == null)
3135
                    continue;
3136
                newFrom = newTo = mapped;
3137
                if (val.startSide != val.endSide) {
3138
                    newTo = changes.mapPos(curFrom, val.endSide);
3139
                    if (newTo < newFrom)
3140
                        continue;
3141
                }
3142
            }
3143
            else {
3144
                newFrom = changes.mapPos(curFrom, val.startSide);
3145
                newTo = changes.mapPos(curTo, val.endSide);
3146
                if (newFrom > newTo || newFrom == newTo && val.startSide > 0 && val.endSide <= 0)
3147
                    continue;
3148
            }
3149
            if ((newTo - newFrom || val.endSide - val.startSide) < 0)
3150
                continue;
3151
            if (newPos < 0)
3152
                newPos = newFrom;
3153
            if (val.point)
3154
                maxPoint = Math.max(maxPoint, newTo - newFrom);
3155
            value.push(val);
3156
            from.push(newFrom - newPos);
3157
            to.push(newTo - newPos);
3158
        }
3159
        return { mapped: value.length ? new Chunk(from, to, value, maxPoint) : null, pos: newPos };
3160
    }
3161
}
3162
/**
3163
A range set stores a collection of [ranges](https://codemirror.net/6/docs/ref/#state.Range) in a
3164
way that makes them efficient to [map](https://codemirror.net/6/docs/ref/#state.RangeSet.map) and
3165
[update](https://codemirror.net/6/docs/ref/#state.RangeSet.update). This is an immutable data
3166
structure.
3167
*/
3168
class RangeSet {
3169
    constructor(
3170
    /**
3171
    @internal
3172
    */
3173
    chunkPos,
3174
    /**
3175
    @internal
3176
    */
3177
    chunk,
3178
    /**
3179
    @internal
3180
    */
3181
    nextLayer,
3182
    /**
3183
    @internal
3184
    */
3185
    maxPoint) {
3186
        this.chunkPos = chunkPos;
3187
        this.chunk = chunk;
3188
        this.nextLayer = nextLayer;
3189
        this.maxPoint = maxPoint;
3190
    }
3191
    /**
3192
    @internal
3193
    */
3194
    static create(chunkPos, chunk, nextLayer, maxPoint) {
3195
        return new RangeSet(chunkPos, chunk, nextLayer, maxPoint);
3196
    }
3197
    /**
3198
    @internal
3199
    */
3200
    get length() {
3201
        let last = this.chunk.length - 1;
3202
        return last < 0 ? 0 : Math.max(this.chunkEnd(last), this.nextLayer.length);
3203
    }
3204
    /**
3205
    The number of ranges in the set.
3206
    */
3207
    get size() {
3208
        if (this.isEmpty)
3209
            return 0;
3210
        let size = this.nextLayer.size;
3211
        for (let chunk of this.chunk)
3212
            size += chunk.value.length;
3213
        return size;
3214
    }
3215
    /**
3216
    @internal
3217
    */
3218
    chunkEnd(index) {
3219
        return this.chunkPos[index] + this.chunk[index].length;
3220
    }
3221
    /**
3222
    Update the range set, optionally adding new ranges or filtering
3223
    out existing ones.
3224
 
3225
    (Note: The type parameter is just there as a kludge to work
3226
    around TypeScript variance issues that prevented `RangeSet<X>`
3227
    from being a subtype of `RangeSet<Y>` when `X` is a subtype of
3228
    `Y`.)
3229
    */
3230
    update(updateSpec) {
3231
        let { add = [], sort = false, filterFrom = 0, filterTo = this.length } = updateSpec;
3232
        let filter = updateSpec.filter;
3233
        if (add.length == 0 && !filter)
3234
            return this;
3235
        if (sort)
3236
            add = add.slice().sort(cmpRange);
3237
        if (this.isEmpty)
3238
            return add.length ? RangeSet.of(add) : this;
3239
        let cur = new LayerCursor(this, null, -1).goto(0), i = 0, spill = [];
3240
        let builder = new RangeSetBuilder();
3241
        while (cur.value || i < add.length) {
3242
            if (i < add.length && (cur.from - add[i].from || cur.startSide - add[i].value.startSide) >= 0) {
3243
                let range = add[i++];
3244
                if (!builder.addInner(range.from, range.to, range.value))
3245
                    spill.push(range);
3246
            }
3247
            else if (cur.rangeIndex == 1 && cur.chunkIndex < this.chunk.length &&
3248
                (i == add.length || this.chunkEnd(cur.chunkIndex) < add[i].from) &&
3249
                (!filter || filterFrom > this.chunkEnd(cur.chunkIndex) || filterTo < this.chunkPos[cur.chunkIndex]) &&
3250
                builder.addChunk(this.chunkPos[cur.chunkIndex], this.chunk[cur.chunkIndex])) {
3251
                cur.nextChunk();
3252
            }
3253
            else {
3254
                if (!filter || filterFrom > cur.to || filterTo < cur.from || filter(cur.from, cur.to, cur.value)) {
3255
                    if (!builder.addInner(cur.from, cur.to, cur.value))
3256
                        spill.push(Range$1.create(cur.from, cur.to, cur.value));
3257
                }
3258
                cur.next();
3259
            }
3260
        }
3261
        return builder.finishInner(this.nextLayer.isEmpty && !spill.length ? RangeSet.empty
3262
            : this.nextLayer.update({ add: spill, filter, filterFrom, filterTo }));
3263
    }
3264
    /**
3265
    Map this range set through a set of changes, return the new set.
3266
    */
3267
    map(changes) {
3268
        if (changes.empty || this.isEmpty)
3269
            return this;
3270
        let chunks = [], chunkPos = [], maxPoint = -1;
3271
        for (let i = 0; i < this.chunk.length; i++) {
3272
            let start = this.chunkPos[i], chunk = this.chunk[i];
3273
            let touch = changes.touchesRange(start, start + chunk.length);
3274
            if (touch === false) {
3275
                maxPoint = Math.max(maxPoint, chunk.maxPoint);
3276
                chunks.push(chunk);
3277
                chunkPos.push(changes.mapPos(start));
3278
            }
3279
            else if (touch === true) {
3280
                let { mapped, pos } = chunk.map(start, changes);
3281
                if (mapped) {
3282
                    maxPoint = Math.max(maxPoint, mapped.maxPoint);
3283
                    chunks.push(mapped);
3284
                    chunkPos.push(pos);
3285
                }
3286
            }
3287
        }
3288
        let next = this.nextLayer.map(changes);
3289
        return chunks.length == 0 ? next : new RangeSet(chunkPos, chunks, next || RangeSet.empty, maxPoint);
3290
    }
3291
    /**
3292
    Iterate over the ranges that touch the region `from` to `to`,
3293
    calling `f` for each. There is no guarantee that the ranges will
3294
    be reported in any specific order. When the callback returns
3295
    `false`, iteration stops.
3296
    */
3297
    between(from, to, f) {
3298
        if (this.isEmpty)
3299
            return;
3300
        for (let i = 0; i < this.chunk.length; i++) {
3301
            let start = this.chunkPos[i], chunk = this.chunk[i];
3302
            if (to >= start && from <= start + chunk.length &&
3303
                chunk.between(start, from - start, to - start, f) === false)
3304
                return;
3305
        }
3306
        this.nextLayer.between(from, to, f);
3307
    }
3308
    /**
3309
    Iterate over the ranges in this set, in order, including all
3310
    ranges that end at or after `from`.
3311
    */
3312
    iter(from = 0) {
3313
        return HeapCursor.from([this]).goto(from);
3314
    }
3315
    /**
3316
    @internal
3317
    */
3318
    get isEmpty() { return this.nextLayer == this; }
3319
    /**
3320
    Iterate over the ranges in a collection of sets, in order,
3321
    starting from `from`.
3322
    */
3323
    static iter(sets, from = 0) {
3324
        return HeapCursor.from(sets).goto(from);
3325
    }
3326
    /**
3327
    Iterate over two groups of sets, calling methods on `comparator`
3328
    to notify it of possible differences.
3329
    */
3330
    static compare(oldSets, newSets,
3331
    /**
3332
    This indicates how the underlying data changed between these
3333
    ranges, and is needed to synchronize the iteration.
3334
    */
3335
    textDiff, comparator,
3336
    /**
3337
    Can be used to ignore all non-point ranges, and points below
3338
    the given size. When -1, all ranges are compared.
3339
    */
3340
    minPointSize = -1) {
3341
        let a = oldSets.filter(set => set.maxPoint > 0 || !set.isEmpty && set.maxPoint >= minPointSize);
3342
        let b = newSets.filter(set => set.maxPoint > 0 || !set.isEmpty && set.maxPoint >= minPointSize);
3343
        let sharedChunks = findSharedChunks(a, b, textDiff);
3344
        let sideA = new SpanCursor(a, sharedChunks, minPointSize);
3345
        let sideB = new SpanCursor(b, sharedChunks, minPointSize);
3346
        textDiff.iterGaps((fromA, fromB, length) => compare(sideA, fromA, sideB, fromB, length, comparator));
3347
        if (textDiff.empty && textDiff.length == 0)
3348
            compare(sideA, 0, sideB, 0, 0, comparator);
3349
    }
3350
    /**
3351
    Compare the contents of two groups of range sets, returning true
3352
    if they are equivalent in the given range.
3353
    */
3354
    static eq(oldSets, newSets, from = 0, to) {
3355
        if (to == null)
3356
            to = 1000000000 /* C.Far */ - 1;
3357
        let a = oldSets.filter(set => !set.isEmpty && newSets.indexOf(set) < 0);
3358
        let b = newSets.filter(set => !set.isEmpty && oldSets.indexOf(set) < 0);
3359
        if (a.length != b.length)
3360
            return false;
3361
        if (!a.length)
3362
            return true;
3363
        let sharedChunks = findSharedChunks(a, b);
3364
        let sideA = new SpanCursor(a, sharedChunks, 0).goto(from), sideB = new SpanCursor(b, sharedChunks, 0).goto(from);
3365
        for (;;) {
3366
            if (sideA.to != sideB.to ||
3367
                !sameValues(sideA.active, sideB.active) ||
3368
                sideA.point && (!sideB.point || !sideA.point.eq(sideB.point)))
3369
                return false;
3370
            if (sideA.to > to)
3371
                return true;
3372
            sideA.next();
3373
            sideB.next();
3374
        }
3375
    }
3376
    /**
3377
    Iterate over a group of range sets at the same time, notifying
3378
    the iterator about the ranges covering every given piece of
3379
    content. Returns the open count (see
3380
    [`SpanIterator.span`](https://codemirror.net/6/docs/ref/#state.SpanIterator.span)) at the end
3381
    of the iteration.
3382
    */
3383
    static spans(sets, from, to, iterator,
3384
    /**
3385
    When given and greater than -1, only points of at least this
3386
    size are taken into account.
3387
    */
3388
    minPointSize = -1) {
3389
        let cursor = new SpanCursor(sets, null, minPointSize).goto(from), pos = from;
3390
        let openRanges = cursor.openStart;
3391
        for (;;) {
3392
            let curTo = Math.min(cursor.to, to);
3393
            if (cursor.point) {
3394
                let active = cursor.activeForPoint(cursor.to);
3395
                let openCount = cursor.pointFrom < from ? active.length + 1
3396
                    : cursor.point.startSide < 0 ? active.length
3397
                        : Math.min(active.length, openRanges);
3398
                iterator.point(pos, curTo, cursor.point, active, openCount, cursor.pointRank);
3399
                openRanges = Math.min(cursor.openEnd(curTo), active.length);
3400
            }
3401
            else if (curTo > pos) {
3402
                iterator.span(pos, curTo, cursor.active, openRanges);
3403
                openRanges = cursor.openEnd(curTo);
3404
            }
3405
            if (cursor.to > to)
3406
                return openRanges + (cursor.point && cursor.to > to ? 1 : 0);
3407
            pos = cursor.to;
3408
            cursor.next();
3409
        }
3410
    }
3411
    /**
3412
    Create a range set for the given range or array of ranges. By
3413
    default, this expects the ranges to be _sorted_ (by start
3414
    position and, if two start at the same position,
3415
    `value.startSide`). You can pass `true` as second argument to
3416
    cause the method to sort them.
3417
    */
3418
    static of(ranges, sort = false) {
3419
        let build = new RangeSetBuilder();
3420
        for (let range of ranges instanceof Range$1 ? [ranges] : sort ? lazySort(ranges) : ranges)
3421
            build.add(range.from, range.to, range.value);
3422
        return build.finish();
3423
    }
3424
    /**
3425
    Join an array of range sets into a single set.
3426
    */
3427
    static join(sets) {
3428
        if (!sets.length)
3429
            return RangeSet.empty;
3430
        let result = sets[sets.length - 1];
3431
        for (let i = sets.length - 2; i >= 0; i--) {
3432
            for (let layer = sets[i]; layer != RangeSet.empty; layer = layer.nextLayer)
3433
                result = new RangeSet(layer.chunkPos, layer.chunk, result, Math.max(layer.maxPoint, result.maxPoint));
3434
        }
3435
        return result;
3436
    }
3437
}
3438
/**
3439
The empty set of ranges.
3440
*/
3441
RangeSet.empty = /*@__PURE__*/new RangeSet([], [], null, -1);
3442
function lazySort(ranges) {
3443
    if (ranges.length > 1)
3444
        for (let prev = ranges[0], i = 1; i < ranges.length; i++) {
3445
            let cur = ranges[i];
3446
            if (cmpRange(prev, cur) > 0)
3447
                return ranges.slice().sort(cmpRange);
3448
            prev = cur;
3449
        }
3450
    return ranges;
3451
}
3452
RangeSet.empty.nextLayer = RangeSet.empty;
3453
/**
3454
A range set builder is a data structure that helps build up a
3455
[range set](https://codemirror.net/6/docs/ref/#state.RangeSet) directly, without first allocating
3456
an array of [`Range`](https://codemirror.net/6/docs/ref/#state.Range) objects.
3457
*/
3458
class RangeSetBuilder {
3459
    finishChunk(newArrays) {
3460
        this.chunks.push(new Chunk(this.from, this.to, this.value, this.maxPoint));
3461
        this.chunkPos.push(this.chunkStart);
3462
        this.chunkStart = -1;
3463
        this.setMaxPoint = Math.max(this.setMaxPoint, this.maxPoint);
3464
        this.maxPoint = -1;
3465
        if (newArrays) {
3466
            this.from = [];
3467
            this.to = [];
3468
            this.value = [];
3469
        }
3470
    }
3471
    /**
3472
    Create an empty builder.
3473
    */
3474
    constructor() {
3475
        this.chunks = [];
3476
        this.chunkPos = [];
3477
        this.chunkStart = -1;
3478
        this.last = null;
3479
        this.lastFrom = -1000000000 /* C.Far */;
3480
        this.lastTo = -1000000000 /* C.Far */;
3481
        this.from = [];
3482
        this.to = [];
3483
        this.value = [];
3484
        this.maxPoint = -1;
3485
        this.setMaxPoint = -1;
3486
        this.nextLayer = null;
3487
    }
3488
    /**
3489
    Add a range. Ranges should be added in sorted (by `from` and
3490
    `value.startSide`) order.
3491
    */
3492
    add(from, to, value) {
3493
        if (!this.addInner(from, to, value))
3494
            (this.nextLayer || (this.nextLayer = new RangeSetBuilder)).add(from, to, value);
3495
    }
3496
    /**
3497
    @internal
3498
    */
3499
    addInner(from, to, value) {
3500
        let diff = from - this.lastTo || value.startSide - this.last.endSide;
3501
        if (diff <= 0 && (from - this.lastFrom || value.startSide - this.last.startSide) < 0)
3502
            throw new Error("Ranges must be added sorted by `from` position and `startSide`");
3503
        if (diff < 0)
3504
            return false;
3505
        if (this.from.length == 250 /* C.ChunkSize */)
3506
            this.finishChunk(true);
3507
        if (this.chunkStart < 0)
3508
            this.chunkStart = from;
3509
        this.from.push(from - this.chunkStart);
3510
        this.to.push(to - this.chunkStart);
3511
        this.last = value;
3512
        this.lastFrom = from;
3513
        this.lastTo = to;
3514
        this.value.push(value);
3515
        if (value.point)
3516
            this.maxPoint = Math.max(this.maxPoint, to - from);
3517
        return true;
3518
    }
3519
    /**
3520
    @internal
3521
    */
3522
    addChunk(from, chunk) {
3523
        if ((from - this.lastTo || chunk.value[0].startSide - this.last.endSide) < 0)
3524
            return false;
3525
        if (this.from.length)
3526
            this.finishChunk(true);
3527
        this.setMaxPoint = Math.max(this.setMaxPoint, chunk.maxPoint);
3528
        this.chunks.push(chunk);
3529
        this.chunkPos.push(from);
3530
        let last = chunk.value.length - 1;
3531
        this.last = chunk.value[last];
3532
        this.lastFrom = chunk.from[last] + from;
3533
        this.lastTo = chunk.to[last] + from;
3534
        return true;
3535
    }
3536
    /**
3537
    Finish the range set. Returns the new set. The builder can't be
3538
    used anymore after this has been called.
3539
    */
3540
    finish() { return this.finishInner(RangeSet.empty); }
3541
    /**
3542
    @internal
3543
    */
3544
    finishInner(next) {
3545
        if (this.from.length)
3546
            this.finishChunk(false);
3547
        if (this.chunks.length == 0)
3548
            return next;
3549
        let result = RangeSet.create(this.chunkPos, this.chunks, this.nextLayer ? this.nextLayer.finishInner(next) : next, this.setMaxPoint);
3550
        this.from = null; // Make sure further `add` calls produce errors
3551
        return result;
3552
    }
3553
}
3554
function findSharedChunks(a, b, textDiff) {
3555
    let inA = new Map();
3556
    for (let set of a)
3557
        for (let i = 0; i < set.chunk.length; i++)
3558
            if (set.chunk[i].maxPoint <= 0)
3559
                inA.set(set.chunk[i], set.chunkPos[i]);
3560
    let shared = new Set();
3561
    for (let set of b)
3562
        for (let i = 0; i < set.chunk.length; i++) {
3563
            let known = inA.get(set.chunk[i]);
3564
            if (known != null && (textDiff ? textDiff.mapPos(known) : known) == set.chunkPos[i] &&
3565
                !(textDiff === null || textDiff === void 0 ? void 0 : textDiff.touchesRange(known, known + set.chunk[i].length)))
3566
                shared.add(set.chunk[i]);
3567
        }
3568
    return shared;
3569
}
3570
class LayerCursor {
3571
    constructor(layer, skip, minPoint, rank = 0) {
3572
        this.layer = layer;
3573
        this.skip = skip;
3574
        this.minPoint = minPoint;
3575
        this.rank = rank;
3576
    }
3577
    get startSide() { return this.value ? this.value.startSide : 0; }
3578
    get endSide() { return this.value ? this.value.endSide : 0; }
3579
    goto(pos, side = -1000000000 /* C.Far */) {
3580
        this.chunkIndex = this.rangeIndex = 0;
3581
        this.gotoInner(pos, side, false);
3582
        return this;
3583
    }
3584
    gotoInner(pos, side, forward) {
3585
        while (this.chunkIndex < this.layer.chunk.length) {
3586
            let next = this.layer.chunk[this.chunkIndex];
3587
            if (!(this.skip && this.skip.has(next) ||
3588
                this.layer.chunkEnd(this.chunkIndex) < pos ||
3589
                next.maxPoint < this.minPoint))
3590
                break;
3591
            this.chunkIndex++;
3592
            forward = false;
3593
        }
3594
        if (this.chunkIndex < this.layer.chunk.length) {
3595
            let rangeIndex = this.layer.chunk[this.chunkIndex].findIndex(pos - this.layer.chunkPos[this.chunkIndex], side, true);
3596
            if (!forward || this.rangeIndex < rangeIndex)
3597
                this.setRangeIndex(rangeIndex);
3598
        }
3599
        this.next();
3600
    }
3601
    forward(pos, side) {
3602
        if ((this.to - pos || this.endSide - side) < 0)
3603
            this.gotoInner(pos, side, true);
3604
    }
3605
    next() {
3606
        for (;;) {
3607
            if (this.chunkIndex == this.layer.chunk.length) {
3608
                this.from = this.to = 1000000000 /* C.Far */;
3609
                this.value = null;
3610
                break;
3611
            }
3612
            else {
3613
                let chunkPos = this.layer.chunkPos[this.chunkIndex], chunk = this.layer.chunk[this.chunkIndex];
3614
                let from = chunkPos + chunk.from[this.rangeIndex];
3615
                this.from = from;
3616
                this.to = chunkPos + chunk.to[this.rangeIndex];
3617
                this.value = chunk.value[this.rangeIndex];
3618
                this.setRangeIndex(this.rangeIndex + 1);
3619
                if (this.minPoint < 0 || this.value.point && this.to - this.from >= this.minPoint)
3620
                    break;
3621
            }
3622
        }
3623
    }
3624
    setRangeIndex(index) {
3625
        if (index == this.layer.chunk[this.chunkIndex].value.length) {
3626
            this.chunkIndex++;
3627
            if (this.skip) {
3628
                while (this.chunkIndex < this.layer.chunk.length && this.skip.has(this.layer.chunk[this.chunkIndex]))
3629
                    this.chunkIndex++;
3630
            }
3631
            this.rangeIndex = 0;
3632
        }
3633
        else {
3634
            this.rangeIndex = index;
3635
        }
3636
    }
3637
    nextChunk() {
3638
        this.chunkIndex++;
3639
        this.rangeIndex = 0;
3640
        this.next();
3641
    }
3642
    compare(other) {
3643
        return this.from - other.from || this.startSide - other.startSide || this.rank - other.rank ||
3644
            this.to - other.to || this.endSide - other.endSide;
3645
    }
3646
}
3647
class HeapCursor {
3648
    constructor(heap) {
3649
        this.heap = heap;
3650
    }
3651
    static from(sets, skip = null, minPoint = -1) {
3652
        let heap = [];
3653
        for (let i = 0; i < sets.length; i++) {
3654
            for (let cur = sets[i]; !cur.isEmpty; cur = cur.nextLayer) {
3655
                if (cur.maxPoint >= minPoint)
3656
                    heap.push(new LayerCursor(cur, skip, minPoint, i));
3657
            }
3658
        }
3659
        return heap.length == 1 ? heap[0] : new HeapCursor(heap);
3660
    }
3661
    get startSide() { return this.value ? this.value.startSide : 0; }
3662
    goto(pos, side = -1000000000 /* C.Far */) {
3663
        for (let cur of this.heap)
3664
            cur.goto(pos, side);
3665
        for (let i = this.heap.length >> 1; i >= 0; i--)
3666
            heapBubble(this.heap, i);
3667
        this.next();
3668
        return this;
3669
    }
3670
    forward(pos, side) {
3671
        for (let cur of this.heap)
3672
            cur.forward(pos, side);
3673
        for (let i = this.heap.length >> 1; i >= 0; i--)
3674
            heapBubble(this.heap, i);
3675
        if ((this.to - pos || this.value.endSide - side) < 0)
3676
            this.next();
3677
    }
3678
    next() {
3679
        if (this.heap.length == 0) {
3680
            this.from = this.to = 1000000000 /* C.Far */;
3681
            this.value = null;
3682
            this.rank = -1;
3683
        }
3684
        else {
3685
            let top = this.heap[0];
3686
            this.from = top.from;
3687
            this.to = top.to;
3688
            this.value = top.value;
3689
            this.rank = top.rank;
3690
            if (top.value)
3691
                top.next();
3692
            heapBubble(this.heap, 0);
3693
        }
3694
    }
3695
}
3696
function heapBubble(heap, index) {
3697
    for (let cur = heap[index];;) {
3698
        let childIndex = (index << 1) + 1;
3699
        if (childIndex >= heap.length)
3700
            break;
3701
        let child = heap[childIndex];
3702
        if (childIndex + 1 < heap.length && child.compare(heap[childIndex + 1]) >= 0) {
3703
            child = heap[childIndex + 1];
3704
            childIndex++;
3705
        }
3706
        if (cur.compare(child) < 0)
3707
            break;
3708
        heap[childIndex] = cur;
3709
        heap[index] = child;
3710
        index = childIndex;
3711
    }
3712
}
3713
class SpanCursor {
3714
    constructor(sets, skip, minPoint) {
3715
        this.minPoint = minPoint;
3716
        this.active = [];
3717
        this.activeTo = [];
3718
        this.activeRank = [];
3719
        this.minActive = -1;
3720
        // A currently active point range, if any
3721
        this.point = null;
3722
        this.pointFrom = 0;
3723
        this.pointRank = 0;
3724
        this.to = -1000000000 /* C.Far */;
3725
        this.endSide = 0;
3726
        // The amount of open active ranges at the start of the iterator.
3727
        // Not including points.
3728
        this.openStart = -1;
3729
        this.cursor = HeapCursor.from(sets, skip, minPoint);
3730
    }
3731
    goto(pos, side = -1000000000 /* C.Far */) {
3732
        this.cursor.goto(pos, side);
3733
        this.active.length = this.activeTo.length = this.activeRank.length = 0;
3734
        this.minActive = -1;
3735
        this.to = pos;
3736
        this.endSide = side;
3737
        this.openStart = -1;
3738
        this.next();
3739
        return this;
3740
    }
3741
    forward(pos, side) {
3742
        while (this.minActive > -1 && (this.activeTo[this.minActive] - pos || this.active[this.minActive].endSide - side) < 0)
3743
            this.removeActive(this.minActive);
3744
        this.cursor.forward(pos, side);
3745
    }
3746
    removeActive(index) {
3747
        remove(this.active, index);
3748
        remove(this.activeTo, index);
3749
        remove(this.activeRank, index);
3750
        this.minActive = findMinIndex(this.active, this.activeTo);
3751
    }
3752
    addActive(trackOpen) {
3753
        let i = 0, { value, to, rank } = this.cursor;
3754
        // Organize active marks by rank first, then by size
3755
        while (i < this.activeRank.length && (rank - this.activeRank[i] || to - this.activeTo[i]) > 0)
3756
            i++;
3757
        insert(this.active, i, value);
3758
        insert(this.activeTo, i, to);
3759
        insert(this.activeRank, i, rank);
3760
        if (trackOpen)
3761
            insert(trackOpen, i, this.cursor.from);
3762
        this.minActive = findMinIndex(this.active, this.activeTo);
3763
    }
3764
    // After calling this, if `this.point` != null, the next range is a
3765
    // point. Otherwise, it's a regular range, covered by `this.active`.
3766
    next() {
3767
        let from = this.to, wasPoint = this.point;
3768
        this.point = null;
3769
        let trackOpen = this.openStart < 0 ? [] : null;
3770
        for (;;) {
3771
            let a = this.minActive;
3772
            if (a > -1 && (this.activeTo[a] - this.cursor.from || this.active[a].endSide - this.cursor.startSide) < 0) {
3773
                if (this.activeTo[a] > from) {
3774
                    this.to = this.activeTo[a];
3775
                    this.endSide = this.active[a].endSide;
3776
                    break;
3777
                }
3778
                this.removeActive(a);
3779
                if (trackOpen)
3780
                    remove(trackOpen, a);
3781
            }
3782
            else if (!this.cursor.value) {
3783
                this.to = this.endSide = 1000000000 /* C.Far */;
3784
                break;
3785
            }
3786
            else if (this.cursor.from > from) {
3787
                this.to = this.cursor.from;
3788
                this.endSide = this.cursor.startSide;
3789
                break;
3790
            }
3791
            else {
3792
                let nextVal = this.cursor.value;
3793
                if (!nextVal.point) { // Opening a range
3794
                    this.addActive(trackOpen);
3795
                    this.cursor.next();
3796
                }
3797
                else if (wasPoint && this.cursor.to == this.to && this.cursor.from < this.cursor.to) {
3798
                    // Ignore any non-empty points that end precisely at the end of the prev point
3799
                    this.cursor.next();
3800
                }
3801
                else { // New point
3802
                    this.point = nextVal;
3803
                    this.pointFrom = this.cursor.from;
3804
                    this.pointRank = this.cursor.rank;
3805
                    this.to = this.cursor.to;
3806
                    this.endSide = nextVal.endSide;
3807
                    this.cursor.next();
3808
                    this.forward(this.to, this.endSide);
3809
                    break;
3810
                }
3811
            }
3812
        }
3813
        if (trackOpen) {
3814
            this.openStart = 0;
3815
            for (let i = trackOpen.length - 1; i >= 0 && trackOpen[i] < from; i--)
3816
                this.openStart++;
3817
        }
3818
    }
3819
    activeForPoint(to) {
3820
        if (!this.active.length)
3821
            return this.active;
3822
        let active = [];
3823
        for (let i = this.active.length - 1; i >= 0; i--) {
3824
            if (this.activeRank[i] < this.pointRank)
3825
                break;
3826
            if (this.activeTo[i] > to || this.activeTo[i] == to && this.active[i].endSide >= this.point.endSide)
3827
                active.push(this.active[i]);
3828
        }
3829
        return active.reverse();
3830
    }
3831
    openEnd(to) {
3832
        let open = 0;
3833
        for (let i = this.activeTo.length - 1; i >= 0 && this.activeTo[i] > to; i--)
3834
            open++;
3835
        return open;
3836
    }
3837
}
3838
function compare(a, startA, b, startB, length, comparator) {
3839
    a.goto(startA);
3840
    b.goto(startB);
3841
    let endB = startB + length;
3842
    let pos = startB, dPos = startB - startA;
3843
    for (;;) {
3844
        let diff = (a.to + dPos) - b.to || a.endSide - b.endSide;
3845
        let end = diff < 0 ? a.to + dPos : b.to, clipEnd = Math.min(end, endB);
3846
        if (a.point || b.point) {
3847
            if (!(a.point && b.point && (a.point == b.point || a.point.eq(b.point)) &&
3848
                sameValues(a.activeForPoint(a.to), b.activeForPoint(b.to))))
3849
                comparator.comparePoint(pos, clipEnd, a.point, b.point);
3850
        }
3851
        else {
3852
            if (clipEnd > pos && !sameValues(a.active, b.active))
3853
                comparator.compareRange(pos, clipEnd, a.active, b.active);
3854
        }
3855
        if (end > endB)
3856
            break;
3857
        pos = end;
3858
        if (diff <= 0)
3859
            a.next();
3860
        if (diff >= 0)
3861
            b.next();
3862
    }
3863
}
3864
function sameValues(a, b) {
3865
    if (a.length != b.length)
3866
        return false;
3867
    for (let i = 0; i < a.length; i++)
3868
        if (a[i] != b[i] && !a[i].eq(b[i]))
3869
            return false;
3870
    return true;
3871
}
3872
function remove(array, index) {
3873
    for (let i = index, e = array.length - 1; i < e; i++)
3874
        array[i] = array[i + 1];
3875
    array.pop();
3876
}
3877
function insert(array, index, value) {
3878
    for (let i = array.length - 1; i >= index; i--)
3879
        array[i + 1] = array[i];
3880
    array[index] = value;
3881
}
3882
function findMinIndex(value, array) {
3883
    let found = -1, foundPos = 1000000000 /* C.Far */;
3884
    for (let i = 0; i < array.length; i++)
3885
        if ((array[i] - foundPos || value[i].endSide - value[found].endSide) < 0) {
3886
            found = i;
3887
            foundPos = array[i];
3888
        }
3889
    return found;
3890
}
3891
 
3892
/**
3893
Count the column position at the given offset into the string,
3894
taking extending characters and tab size into account.
3895
*/
3896
function countColumn(string, tabSize, to = string.length) {
3897
    let n = 0;
3898
    for (let i = 0; i < to;) {
3899
        if (string.charCodeAt(i) == 9) {
3900
            n += tabSize - (n % tabSize);
3901
            i++;
3902
        }
3903
        else {
3904
            n++;
3905
            i = findClusterBreak(string, i);
3906
        }
3907
    }
3908
    return n;
3909
}
3910
/**
3911
Find the offset that corresponds to the given column position in a
3912
string, taking extending characters and tab size into account. By
3913
default, the string length is returned when it is too short to
3914
reach the column. Pass `strict` true to make it return -1 in that
3915
situation.
3916
*/
3917
function findColumn(string, col, tabSize, strict) {
3918
    for (let i = 0, n = 0;;) {
3919
        if (n >= col)
3920
            return i;
3921
        if (i == string.length)
3922
            break;
3923
        n += string.charCodeAt(i) == 9 ? tabSize - (n % tabSize) : 1;
3924
        i = findClusterBreak(string, i);
3925
    }
3926
    return strict === true ? -1 : string.length;
3927
}
3928
 
3929
const C = "\u037c";
3930
const COUNT = typeof Symbol == "undefined" ? "__" + C : Symbol.for(C);
3931
const SET = typeof Symbol == "undefined" ? "__styleSet" + Math.floor(Math.random() * 1e8) : Symbol("styleSet");
3932
const top = typeof globalThis != "undefined" ? globalThis : typeof window != "undefined" ? window : {};
3933
 
3934
// :: - Style modules encapsulate a set of CSS rules defined from
3935
// JavaScript. Their definitions are only available in a given DOM
3936
// root after it has been _mounted_ there with `StyleModule.mount`.
3937
//
3938
// Style modules should be created once and stored somewhere, as
3939
// opposed to re-creating them every time you need them. The amount of
3940
// CSS rules generated for a given DOM root is bounded by the amount
3941
// of style modules that were used. So to avoid leaking rules, don't
3942
// create these dynamically, but treat them as one-time allocations.
3943
class StyleModule {
3944
  // :: (Object<Style>, ?{finish: ?(string) → string})
3945
  // Create a style module from the given spec.
3946
  //
3947
  // When `finish` is given, it is called on regular (non-`@`)
3948
  // selectors (after `&` expansion) to compute the final selector.
3949
  constructor(spec, options) {
3950
    this.rules = [];
3951
    let {finish} = options || {};
3952
 
3953
    function splitSelector(selector) {
3954
      return /^@/.test(selector) ? [selector] : selector.split(/,\s*/)
3955
    }
3956
 
3957
    function render(selectors, spec, target, isKeyframes) {
3958
      let local = [], isAt = /^@(\w+)\b/.exec(selectors[0]), keyframes = isAt && isAt[1] == "keyframes";
3959
      if (isAt && spec == null) return target.push(selectors[0] + ";")
3960
      for (let prop in spec) {
3961
        let value = spec[prop];
3962
        if (/&/.test(prop)) {
3963
          render(prop.split(/,\s*/).map(part => selectors.map(sel => part.replace(/&/, sel))).reduce((a, b) => a.concat(b)),
3964
                 value, target);
3965
        } else if (value && typeof value == "object") {
3966
          if (!isAt) throw new RangeError("The value of a property (" + prop + ") should be a primitive value.")
3967
          render(splitSelector(prop), value, local, keyframes);
3968
        } else if (value != null) {
3969
          local.push(prop.replace(/_.*/, "").replace(/[A-Z]/g, l => "-" + l.toLowerCase()) + ": " + value + ";");
3970
        }
3971
      }
3972
      if (local.length || keyframes) {
3973
        target.push((finish && !isAt && !isKeyframes ? selectors.map(finish) : selectors).join(", ") +
3974
                    " {" + local.join(" ") + "}");
3975
      }
3976
    }
3977
 
3978
    for (let prop in spec) render(splitSelector(prop), spec[prop], this.rules);
3979
  }
3980
 
3981
  // :: () → string
3982
  // Returns a string containing the module's CSS rules.
3983
  getRules() { return this.rules.join("\n") }
3984
 
3985
  // :: () → string
3986
  // Generate a new unique CSS class name.
3987
  static newName() {
3988
    let id = top[COUNT] || 1;
3989
    top[COUNT] = id + 1;
3990
    return C + id.toString(36)
3991
  }
3992
 
3993
  // :: (union<Document, ShadowRoot>, union<[StyleModule], StyleModule>, ?{nonce: ?string})
3994
  //
3995
  // Mount the given set of modules in the given DOM root, which ensures
3996
  // that the CSS rules defined by the module are available in that
3997
  // context.
3998
  //
3999
  // Rules are only added to the document once per root.
4000
  //
4001
  // Rule order will follow the order of the modules, so that rules from
4002
  // modules later in the array take precedence of those from earlier
4003
  // modules. If you call this function multiple times for the same root
4004
  // in a way that changes the order of already mounted modules, the old
4005
  // order will be changed.
4006
  //
4007
  // If a Content Security Policy nonce is provided, it is added to
4008
  // the `<style>` tag generated by the library.
4009
  static mount(root, modules, options) {
4010
    let set = root[SET], nonce = options && options.nonce;
4011
    if (!set) set = new StyleSet(root, nonce);
4012
    else if (nonce) set.setNonce(nonce);
4013
    set.mount(Array.isArray(modules) ? modules : [modules], root);
4014
  }
4015
}
4016
 
4017
let adoptedSet = new Map; //<Document, StyleSet>
4018
 
4019
class StyleSet {
4020
  constructor(root, nonce) {
4021
    let doc = root.ownerDocument || root, win = doc.defaultView;
4022
    if (!root.head && root.adoptedStyleSheets && win.CSSStyleSheet) {
4023
      let adopted = adoptedSet.get(doc);
4024
      if (adopted) return root[SET] = adopted
4025
      this.sheet = new win.CSSStyleSheet;
4026
      adoptedSet.set(doc, this);
4027
    } else {
4028
      this.styleTag = doc.createElement("style");
4029
      if (nonce) this.styleTag.setAttribute("nonce", nonce);
4030
    }
4031
    this.modules = [];
4032
    root[SET] = this;
4033
  }
4034
 
4035
  mount(modules, root) {
4036
    let sheet = this.sheet;
4037
    let pos = 0 /* Current rule offset */, j = 0; /* Index into this.modules */
4038
    for (let i = 0; i < modules.length; i++) {
4039
      let mod = modules[i], index = this.modules.indexOf(mod);
4040
      if (index < j && index > -1) { // Ordering conflict
4041
        this.modules.splice(index, 1);
4042
        j--;
4043
        index = -1;
4044
      }
4045
      if (index == -1) {
4046
        this.modules.splice(j++, 0, mod);
4047
        if (sheet) for (let k = 0; k < mod.rules.length; k++)
4048
          sheet.insertRule(mod.rules[k], pos++);
4049
      } else {
4050
        while (j < index) pos += this.modules[j++].rules.length;
4051
        pos += mod.rules.length;
4052
        j++;
4053
      }
4054
    }
4055
 
4056
    if (sheet) {
4057
      if (root.adoptedStyleSheets.indexOf(this.sheet) < 0)
4058
        root.adoptedStyleSheets = [this.sheet, ...root.adoptedStyleSheets];
4059
    } else {
4060
      let text = "";
4061
      for (let i = 0; i < this.modules.length; i++)
4062
        text += this.modules[i].getRules() + "\n";
4063
      this.styleTag.textContent = text;
4064
      let target = root.head || root;
4065
      if (this.styleTag.parentNode != target)
4066
        target.insertBefore(this.styleTag, target.firstChild);
4067
    }
4068
  }
4069
 
4070
  setNonce(nonce) {
4071
    if (this.styleTag && this.styleTag.getAttribute("nonce") != nonce)
4072
      this.styleTag.setAttribute("nonce", nonce);
4073
  }
4074
}
4075
 
4076
// Style::Object<union<Style,string>>
4077
//
4078
// A style is an object that, in the simple case, maps CSS property
4079
// names to strings holding their values, as in `{color: "red",
4080
// fontWeight: "bold"}`. The property names can be given in
4081
// camel-case—the library will insert a dash before capital letters
4082
// when converting them to CSS.
4083
//
4084
// If you include an underscore in a property name, it and everything
4085
// after it will be removed from the output, which can be useful when
4086
// providing a property multiple times, for browser compatibility
4087
// reasons.
4088
//
4089
// A property in a style object can also be a sub-selector, which
4090
// extends the current context to add a pseudo-selector or a child
4091
// selector. Such a property should contain a `&` character, which
4092
// will be replaced by the current selector. For example `{"&:before":
4093
// {content: '"hi"'}}`. Sub-selectors and regular properties can
4094
// freely be mixed in a given object. Any property containing a `&` is
4095
// assumed to be a sub-selector.
4096
//
4097
// Finally, a property can specify an @-block to be wrapped around the
4098
// styles defined inside the object that's the property's value. For
4099
// example to create a media query you can do `{"@media screen and
4100
// (min-width: 400px)": {...}}`.
4101
 
4102
var base = {
4103
  8: "Backspace",
4104
  9: "Tab",
4105
  10: "Enter",
4106
  12: "NumLock",
4107
  13: "Enter",
4108
  16: "Shift",
4109
  17: "Control",
4110
  18: "Alt",
4111
  20: "CapsLock",
4112
  27: "Escape",
4113
  32: " ",
4114
  33: "PageUp",
4115
  34: "PageDown",
4116
  35: "End",
4117
  36: "Home",
4118
  37: "ArrowLeft",
4119
  38: "ArrowUp",
4120
  39: "ArrowRight",
4121
  40: "ArrowDown",
4122
  44: "PrintScreen",
4123
  45: "Insert",
4124
  46: "Delete",
4125
  59: ";",
4126
  61: "=",
4127
  91: "Meta",
4128
  92: "Meta",
4129
  106: "*",
4130
  107: "+",
4131
  108: ",",
4132
  109: "-",
4133
  110: ".",
4134
  111: "/",
4135
  144: "NumLock",
4136
  145: "ScrollLock",
4137
  160: "Shift",
4138
  161: "Shift",
4139
  162: "Control",
4140
  163: "Control",
4141
  164: "Alt",
4142
  165: "Alt",
4143
  173: "-",
4144
  186: ";",
4145
  187: "=",
4146
  188: ",",
4147
  189: "-",
4148
  190: ".",
4149
  191: "/",
4150
  192: "`",
4151
  219: "[",
4152
  220: "\\",
4153
  221: "]",
4154
  222: "'"
4155
};
4156
 
4157
var shift = {
4158
  48: ")",
4159
  49: "!",
4160
  50: "@",
4161
  51: "#",
4162
  52: "$",
4163
  53: "%",
4164
  54: "^",
4165
  55: "&",
4166
  56: "*",
4167
  57: "(",
4168
  59: ":",
4169
  61: "+",
4170
  173: "_",
4171
  186: ":",
4172
  187: "+",
4173
  188: "<",
4174
  189: "_",
4175
  190: ">",
4176
  191: "?",
4177
  192: "~",
4178
  219: "{",
4179
  220: "|",
4180
  221: "}",
4181
  222: "\""
4182
};
4183
 
4184
var mac = typeof navigator != "undefined" && /Mac/.test(navigator.platform);
4185
var ie$1 = typeof navigator != "undefined" && /MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);
4186
 
4187
// Fill in the digit keys
4188
for (var i = 0; i < 10; i++) base[48 + i] = base[96 + i] = String(i);
4189
 
4190
// The function keys
4191
for (var i = 1; i <= 24; i++) base[i + 111] = "F" + i;
4192
 
4193
// And the alphabetic keys
4194
for (var i = 65; i <= 90; i++) {
4195
  base[i] = String.fromCharCode(i + 32);
4196
  shift[i] = String.fromCharCode(i);
4197
}
4198
 
4199
// For each code that doesn't have a shift-equivalent, copy the base name
4200
for (var code in base) if (!shift.hasOwnProperty(code)) shift[code] = base[code];
4201
 
4202
function keyName(event) {
4203
  // On macOS, keys held with Shift and Cmd don't reflect the effect of Shift in `.key`.
4204
  // On IE, shift effect is never included in `.key`.
4205
  var ignoreKey = mac && event.metaKey && event.shiftKey && !event.ctrlKey && !event.altKey ||
4206
      ie$1 && event.shiftKey && event.key && event.key.length == 1 ||
4207
      event.key == "Unidentified";
4208
  var name = (!ignoreKey && event.key) ||
4209
    (event.shiftKey ? shift : base)[event.keyCode] ||
4210
    event.key || "Unidentified";
4211
  // Edge sometimes produces wrong names (Issue #3)
4212
  if (name == "Esc") name = "Escape";
4213
  if (name == "Del") name = "Delete";
4214
  // https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/8860571/
4215
  if (name == "Left") name = "ArrowLeft";
4216
  if (name == "Up") name = "ArrowUp";
4217
  if (name == "Right") name = "ArrowRight";
4218
  if (name == "Down") name = "ArrowDown";
4219
  return name
4220
}
4221
 
4222
function getSelection(root) {
4223
    let target;
4224
    // Browsers differ on whether shadow roots have a getSelection
4225
    // method. If it exists, use that, otherwise, call it on the
4226
    // document.
4227
    if (root.nodeType == 11) { // Shadow root
4228
        target = root.getSelection ? root : root.ownerDocument;
4229
    }
4230
    else {
4231
        target = root;
4232
    }
4233
    return target.getSelection();
4234
}
4235
function contains(dom, node) {
4236
    return node ? dom == node || dom.contains(node.nodeType != 1 ? node.parentNode : node) : false;
4237
}
4238
function deepActiveElement(doc) {
4239
    let elt = doc.activeElement;
4240
    while (elt && elt.shadowRoot)
4241
        elt = elt.shadowRoot.activeElement;
4242
    return elt;
4243
}
4244
function hasSelection(dom, selection) {
4245
    if (!selection.anchorNode)
4246
        return false;
4247
    try {
4248
        // Firefox will raise 'permission denied' errors when accessing
4249
        // properties of `sel.anchorNode` when it's in a generated CSS
4250
        // element.
4251
        return contains(dom, selection.anchorNode);
4252
    }
4253
    catch (_) {
4254
        return false;
4255
    }
4256
}
4257
function clientRectsFor(dom) {
4258
    if (dom.nodeType == 3)
4259
        return textRange(dom, 0, dom.nodeValue.length).getClientRects();
4260
    else if (dom.nodeType == 1)
4261
        return dom.getClientRects();
4262
    else
4263
        return [];
4264
}
4265
// Scans forward and backward through DOM positions equivalent to the
4266
// given one to see if the two are in the same place (i.e. after a
4267
// text node vs at the end of that text node)
4268
function isEquivalentPosition(node, off, targetNode, targetOff) {
4269
    return targetNode ? (scanFor(node, off, targetNode, targetOff, -1) ||
4270
        scanFor(node, off, targetNode, targetOff, 1)) : false;
4271
}
4272
function domIndex(node) {
4273
    for (var index = 0;; index++) {
4274
        node = node.previousSibling;
4275
        if (!node)
4276
            return index;
4277
    }
4278
}
4279
function isBlockElement(node) {
4280
    return node.nodeType == 1 && /^(DIV|P|LI|UL|OL|BLOCKQUOTE|DD|DT|H\d|SECTION|PRE)$/.test(node.nodeName);
4281
}
4282
function scanFor(node, off, targetNode, targetOff, dir) {
4283
    for (;;) {
4284
        if (node == targetNode && off == targetOff)
4285
            return true;
4286
        if (off == (dir < 0 ? 0 : maxOffset(node))) {
4287
            if (node.nodeName == "DIV")
4288
                return false;
4289
            let parent = node.parentNode;
4290
            if (!parent || parent.nodeType != 1)
4291
                return false;
4292
            off = domIndex(node) + (dir < 0 ? 0 : 1);
4293
            node = parent;
4294
        }
4295
        else if (node.nodeType == 1) {
4296
            node = node.childNodes[off + (dir < 0 ? -1 : 0)];
4297
            if (node.nodeType == 1 && node.contentEditable == "false")
4298
                return false;
4299
            off = dir < 0 ? maxOffset(node) : 0;
4300
        }
4301
        else {
4302
            return false;
4303
        }
4304
    }
4305
}
4306
function maxOffset(node) {
4307
    return node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length;
4308
}
4309
function flattenRect(rect, left) {
4310
    let x = left ? rect.left : rect.right;
4311
    return { left: x, right: x, top: rect.top, bottom: rect.bottom };
4312
}
4313
function windowRect(win) {
4314
    let vp = win.visualViewport;
4315
    if (vp)
4316
        return {
4317
            left: 0, right: vp.width,
4318
            top: 0, bottom: vp.height
4319
        };
4320
    return { left: 0, right: win.innerWidth,
4321
        top: 0, bottom: win.innerHeight };
4322
}
4323
function getScale(elt, rect) {
4324
    let scaleX = rect.width / elt.offsetWidth;
4325
    let scaleY = rect.height / elt.offsetHeight;
4326
    if (scaleX > 0.995 && scaleX < 1.005 || !isFinite(scaleX) || Math.abs(rect.width - elt.offsetWidth) < 1)
4327
        scaleX = 1;
4328
    if (scaleY > 0.995 && scaleY < 1.005 || !isFinite(scaleY) || Math.abs(rect.height - elt.offsetHeight) < 1)
4329
        scaleY = 1;
4330
    return { scaleX, scaleY };
4331
}
4332
function scrollRectIntoView(dom, rect, side, x, y, xMargin, yMargin, ltr) {
4333
    let doc = dom.ownerDocument, win = doc.defaultView || window;
4334
    for (let cur = dom, stop = false; cur && !stop;) {
4335
        if (cur.nodeType == 1) { // Element
4336
            let bounding, top = cur == doc.body;
4337
            let scaleX = 1, scaleY = 1;
4338
            if (top) {
4339
                bounding = windowRect(win);
4340
            }
4341
            else {
4342
                if (/^(fixed|sticky)$/.test(getComputedStyle(cur).position))
4343
                    stop = true;
4344
                if (cur.scrollHeight <= cur.clientHeight && cur.scrollWidth <= cur.clientWidth) {
4345
                    cur = cur.assignedSlot || cur.parentNode;
4346
                    continue;
4347
                }
4348
                let rect = cur.getBoundingClientRect();
4349
                ({ scaleX, scaleY } = getScale(cur, rect));
4350
                // Make sure scrollbar width isn't included in the rectangle
4351
                bounding = { left: rect.left, right: rect.left + cur.clientWidth * scaleX,
4352
                    top: rect.top, bottom: rect.top + cur.clientHeight * scaleY };
4353
            }
4354
            let moveX = 0, moveY = 0;
4355
            if (y == "nearest") {
4356
                if (rect.top < bounding.top) {
4357
                    moveY = -(bounding.top - rect.top + yMargin);
4358
                    if (side > 0 && rect.bottom > bounding.bottom + moveY)
4359
                        moveY = rect.bottom - bounding.bottom + moveY + yMargin;
4360
                }
4361
                else if (rect.bottom > bounding.bottom) {
4362
                    moveY = rect.bottom - bounding.bottom + yMargin;
4363
                    if (side < 0 && (rect.top - moveY) < bounding.top)
4364
                        moveY = -(bounding.top + moveY - rect.top + yMargin);
4365
                }
4366
            }
4367
            else {
4368
                let rectHeight = rect.bottom - rect.top, boundingHeight = bounding.bottom - bounding.top;
4369
                let targetTop = y == "center" && rectHeight <= boundingHeight ? rect.top + rectHeight / 2 - boundingHeight / 2 :
4370
                    y == "start" || y == "center" && side < 0 ? rect.top - yMargin :
4371
                        rect.bottom - boundingHeight + yMargin;
4372
                moveY = targetTop - bounding.top;
4373
            }
4374
            if (x == "nearest") {
4375
                if (rect.left < bounding.left) {
4376
                    moveX = -(bounding.left - rect.left + xMargin);
4377
                    if (side > 0 && rect.right > bounding.right + moveX)
4378
                        moveX = rect.right - bounding.right + moveX + xMargin;
4379
                }
4380
                else if (rect.right > bounding.right) {
4381
                    moveX = rect.right - bounding.right + xMargin;
4382
                    if (side < 0 && rect.left < bounding.left + moveX)
4383
                        moveX = -(bounding.left + moveX - rect.left + xMargin);
4384
                }
4385
            }
4386
            else {
4387
                let targetLeft = x == "center" ? rect.left + (rect.right - rect.left) / 2 - (bounding.right - bounding.left) / 2 :
4388
                    (x == "start") == ltr ? rect.left - xMargin :
4389
                        rect.right - (bounding.right - bounding.left) + xMargin;
4390
                moveX = targetLeft - bounding.left;
4391
            }
4392
            if (moveX || moveY) {
4393
                if (top) {
4394
                    win.scrollBy(moveX, moveY);
4395
                }
4396
                else {
4397
                    let movedX = 0, movedY = 0;
4398
                    if (moveY) {
4399
                        let start = cur.scrollTop;
4400
                        cur.scrollTop += moveY / scaleY;
4401
                        movedY = (cur.scrollTop - start) * scaleY;
4402
                    }
4403
                    if (moveX) {
4404
                        let start = cur.scrollLeft;
4405
                        cur.scrollLeft += moveX / scaleX;
4406
                        movedX = (cur.scrollLeft - start) * scaleX;
4407
                    }
4408
                    rect = { left: rect.left - movedX, top: rect.top - movedY,
4409
                        right: rect.right - movedX, bottom: rect.bottom - movedY };
4410
                    if (movedX && Math.abs(movedX - moveX) < 1)
4411
                        x = "nearest";
4412
                    if (movedY && Math.abs(movedY - moveY) < 1)
4413
                        y = "nearest";
4414
                }
4415
            }
4416
            if (top)
4417
                break;
4418
            cur = cur.assignedSlot || cur.parentNode;
4419
        }
4420
        else if (cur.nodeType == 11) { // A shadow root
4421
            cur = cur.host;
4422
        }
4423
        else {
4424
            break;
4425
        }
4426
    }
4427
}
4428
function scrollableParent(dom) {
4429
    let doc = dom.ownerDocument;
4430
    for (let cur = dom.parentNode; cur;) {
4431
        if (cur == doc.body) {
4432
            break;
4433
        }
4434
        else if (cur.nodeType == 1) {
4435
            if (cur.scrollHeight > cur.clientHeight || cur.scrollWidth > cur.clientWidth)
4436
                return cur;
4437
            cur = cur.assignedSlot || cur.parentNode;
4438
        }
4439
        else if (cur.nodeType == 11) {
4440
            cur = cur.host;
4441
        }
4442
        else {
4443
            break;
4444
        }
4445
    }
4446
    return null;
4447
}
4448
class DOMSelectionState {
4449
    constructor() {
4450
        this.anchorNode = null;
4451
        this.anchorOffset = 0;
4452
        this.focusNode = null;
4453
        this.focusOffset = 0;
4454
    }
4455
    eq(domSel) {
4456
        return this.anchorNode == domSel.anchorNode && this.anchorOffset == domSel.anchorOffset &&
4457
            this.focusNode == domSel.focusNode && this.focusOffset == domSel.focusOffset;
4458
    }
4459
    setRange(range) {
4460
        let { anchorNode, focusNode } = range;
4461
        // Clip offsets to node size to avoid crashes when Safari reports bogus offsets (#1152)
4462
        this.set(anchorNode, Math.min(range.anchorOffset, anchorNode ? maxOffset(anchorNode) : 0), focusNode, Math.min(range.focusOffset, focusNode ? maxOffset(focusNode) : 0));
4463
    }
4464
    set(anchorNode, anchorOffset, focusNode, focusOffset) {
4465
        this.anchorNode = anchorNode;
4466
        this.anchorOffset = anchorOffset;
4467
        this.focusNode = focusNode;
4468
        this.focusOffset = focusOffset;
4469
    }
4470
}
4471
let preventScrollSupported = null;
4472
// Feature-detects support for .focus({preventScroll: true}), and uses
4473
// a fallback kludge when not supported.
4474
function focusPreventScroll(dom) {
4475
    if (dom.setActive)
4476
        return dom.setActive(); // in IE
4477
    if (preventScrollSupported)
4478
        return dom.focus(preventScrollSupported);
4479
    let stack = [];
4480
    for (let cur = dom; cur; cur = cur.parentNode) {
4481
        stack.push(cur, cur.scrollTop, cur.scrollLeft);
4482
        if (cur == cur.ownerDocument)
4483
            break;
4484
    }
4485
    dom.focus(preventScrollSupported == null ? {
4486
        get preventScroll() {
4487
            preventScrollSupported = { preventScroll: true };
4488
            return true;
4489
        }
4490
    } : undefined);
4491
    if (!preventScrollSupported) {
4492
        preventScrollSupported = false;
4493
        for (let i = 0; i < stack.length;) {
4494
            let elt = stack[i++], top = stack[i++], left = stack[i++];
4495
            if (elt.scrollTop != top)
4496
                elt.scrollTop = top;
4497
            if (elt.scrollLeft != left)
4498
                elt.scrollLeft = left;
4499
        }
4500
    }
4501
}
4502
let scratchRange;
4503
function textRange(node, from, to = from) {
4504
    let range = scratchRange || (scratchRange = document.createRange());
4505
    range.setEnd(node, to);
4506
    range.setStart(node, from);
4507
    return range;
4508
}
4509
function dispatchKey(elt, name, code, mods) {
4510
    let options = { key: name, code: name, keyCode: code, which: code, cancelable: true };
4511
    if (mods)
4512
        ({ altKey: options.altKey, ctrlKey: options.ctrlKey, shiftKey: options.shiftKey, metaKey: options.metaKey } = mods);
4513
    let down = new KeyboardEvent("keydown", options);
4514
    down.synthetic = true;
4515
    elt.dispatchEvent(down);
4516
    let up = new KeyboardEvent("keyup", options);
4517
    up.synthetic = true;
4518
    elt.dispatchEvent(up);
4519
    return down.defaultPrevented || up.defaultPrevented;
4520
}
4521
function getRoot(node) {
4522
    while (node) {
4523
        if (node && (node.nodeType == 9 || node.nodeType == 11 && node.host))
4524
            return node;
4525
        node = node.assignedSlot || node.parentNode;
4526
    }
4527
    return null;
4528
}
4529
function clearAttributes(node) {
4530
    while (node.attributes.length)
4531
        node.removeAttributeNode(node.attributes[0]);
4532
}
4533
function atElementStart(doc, selection) {
4534
    let node = selection.focusNode, offset = selection.focusOffset;
4535
    if (!node || selection.anchorNode != node || selection.anchorOffset != offset)
4536
        return false;
4537
    // Safari can report bogus offsets (#1152)
4538
    offset = Math.min(offset, maxOffset(node));
4539
    for (;;) {
4540
        if (offset) {
4541
            if (node.nodeType != 1)
4542
                return false;
4543
            let prev = node.childNodes[offset - 1];
4544
            if (prev.contentEditable == "false")
4545
                offset--;
4546
            else {
4547
                node = prev;
4548
                offset = maxOffset(node);
4549
            }
4550
        }
4551
        else if (node == doc) {
4552
            return true;
4553
        }
4554
        else {
4555
            offset = domIndex(node);
4556
            node = node.parentNode;
4557
        }
4558
    }
4559
}
4560
function isScrolledToBottom(elt) {
4561
    return elt.scrollTop > Math.max(1, elt.scrollHeight - elt.clientHeight - 4);
4562
}
4563
function textNodeBefore(startNode, startOffset) {
4564
    for (let node = startNode, offset = startOffset;;) {
4565
        if (node.nodeType == 3 && offset > 0) {
4566
            return { node: node, offset: offset };
4567
        }
4568
        else if (node.nodeType == 1 && offset > 0) {
4569
            if (node.contentEditable == "false")
4570
                return null;
4571
            node = node.childNodes[offset - 1];
4572
            offset = maxOffset(node);
4573
        }
4574
        else if (node.parentNode && !isBlockElement(node)) {
4575
            offset = domIndex(node);
4576
            node = node.parentNode;
4577
        }
4578
        else {
4579
            return null;
4580
        }
4581
    }
4582
}
4583
function textNodeAfter(startNode, startOffset) {
4584
    for (let node = startNode, offset = startOffset;;) {
4585
        if (node.nodeType == 3 && offset < node.nodeValue.length) {
4586
            return { node: node, offset: offset };
4587
        }
4588
        else if (node.nodeType == 1 && offset < node.childNodes.length) {
4589
            if (node.contentEditable == "false")
4590
                return null;
4591
            node = node.childNodes[offset];
4592
            offset = 0;
4593
        }
4594
        else if (node.parentNode && !isBlockElement(node)) {
4595
            offset = domIndex(node) + 1;
4596
            node = node.parentNode;
4597
        }
4598
        else {
4599
            return null;
4600
        }
4601
    }
4602
}
4603
 
4604
class DOMPos {
4605
    constructor(node, offset, precise = true) {
4606
        this.node = node;
4607
        this.offset = offset;
4608
        this.precise = precise;
4609
    }
4610
    static before(dom, precise) { return new DOMPos(dom.parentNode, domIndex(dom), precise); }
4611
    static after(dom, precise) { return new DOMPos(dom.parentNode, domIndex(dom) + 1, precise); }
4612
}
4613
const noChildren = [];
4614
class ContentView {
4615
    constructor() {
4616
        this.parent = null;
4617
        this.dom = null;
4618
        this.flags = 2 /* ViewFlag.NodeDirty */;
4619
    }
4620
    get overrideDOMText() { return null; }
4621
    get posAtStart() {
4622
        return this.parent ? this.parent.posBefore(this) : 0;
4623
    }
4624
    get posAtEnd() {
4625
        return this.posAtStart + this.length;
4626
    }
4627
    posBefore(view) {
4628
        let pos = this.posAtStart;
4629
        for (let child of this.children) {
4630
            if (child == view)
4631
                return pos;
4632
            pos += child.length + child.breakAfter;
4633
        }
4634
        throw new RangeError("Invalid child in posBefore");
4635
    }
4636
    posAfter(view) {
4637
        return this.posBefore(view) + view.length;
4638
    }
4639
    sync(view, track) {
4640
        if (this.flags & 2 /* ViewFlag.NodeDirty */) {
4641
            let parent = this.dom;
4642
            let prev = null, next;
4643
            for (let child of this.children) {
4644
                if (child.flags & 7 /* ViewFlag.Dirty */) {
4645
                    if (!child.dom && (next = prev ? prev.nextSibling : parent.firstChild)) {
4646
                        let contentView = ContentView.get(next);
4647
                        if (!contentView || !contentView.parent && contentView.canReuseDOM(child))
4648
                            child.reuseDOM(next);
4649
                    }
4650
                    child.sync(view, track);
4651
                    child.flags &= ~7 /* ViewFlag.Dirty */;
4652
                }
4653
                next = prev ? prev.nextSibling : parent.firstChild;
4654
                if (track && !track.written && track.node == parent && next != child.dom)
4655
                    track.written = true;
4656
                if (child.dom.parentNode == parent) {
4657
                    while (next && next != child.dom)
4658
                        next = rm$1(next);
4659
                }
4660
                else {
4661
                    parent.insertBefore(child.dom, next);
4662
                }
4663
                prev = child.dom;
4664
            }
4665
            next = prev ? prev.nextSibling : parent.firstChild;
4666
            if (next && track && track.node == parent)
4667
                track.written = true;
4668
            while (next)
4669
                next = rm$1(next);
4670
        }
4671
        else if (this.flags & 1 /* ViewFlag.ChildDirty */) {
4672
            for (let child of this.children)
4673
                if (child.flags & 7 /* ViewFlag.Dirty */) {
4674
                    child.sync(view, track);
4675
                    child.flags &= ~7 /* ViewFlag.Dirty */;
4676
                }
4677
        }
4678
    }
4679
    reuseDOM(_dom) { }
4680
    localPosFromDOM(node, offset) {
4681
        let after;
4682
        if (node == this.dom) {
4683
            after = this.dom.childNodes[offset];
4684
        }
4685
        else {
4686
            let bias = maxOffset(node) == 0 ? 0 : offset == 0 ? -1 : 1;
4687
            for (;;) {
4688
                let parent = node.parentNode;
4689
                if (parent == this.dom)
4690
                    break;
4691
                if (bias == 0 && parent.firstChild != parent.lastChild) {
4692
                    if (node == parent.firstChild)
4693
                        bias = -1;
4694
                    else
4695
                        bias = 1;
4696
                }
4697
                node = parent;
4698
            }
4699
            if (bias < 0)
4700
                after = node;
4701
            else
4702
                after = node.nextSibling;
4703
        }
4704
        if (after == this.dom.firstChild)
4705
            return 0;
4706
        while (after && !ContentView.get(after))
4707
            after = after.nextSibling;
4708
        if (!after)
4709
            return this.length;
4710
        for (let i = 0, pos = 0;; i++) {
4711
            let child = this.children[i];
4712
            if (child.dom == after)
4713
                return pos;
4714
            pos += child.length + child.breakAfter;
4715
        }
4716
    }
4717
    domBoundsAround(from, to, offset = 0) {
4718
        let fromI = -1, fromStart = -1, toI = -1, toEnd = -1;
4719
        for (let i = 0, pos = offset, prevEnd = offset; i < this.children.length; i++) {
4720
            let child = this.children[i], end = pos + child.length;
4721
            if (pos < from && end > to)
4722
                return child.domBoundsAround(from, to, pos);
4723
            if (end >= from && fromI == -1) {
4724
                fromI = i;
4725
                fromStart = pos;
4726
            }
4727
            if (pos > to && child.dom.parentNode == this.dom) {
4728
                toI = i;
4729
                toEnd = prevEnd;
4730
                break;
4731
            }
4732
            prevEnd = end;
4733
            pos = end + child.breakAfter;
4734
        }
4735
        return { from: fromStart, to: toEnd < 0 ? offset + this.length : toEnd,
4736
            startDOM: (fromI ? this.children[fromI - 1].dom.nextSibling : null) || this.dom.firstChild,
4737
            endDOM: toI < this.children.length && toI >= 0 ? this.children[toI].dom : null };
4738
    }
4739
    markDirty(andParent = false) {
4740
        this.flags |= 2 /* ViewFlag.NodeDirty */;
4741
        this.markParentsDirty(andParent);
4742
    }
4743
    markParentsDirty(childList) {
4744
        for (let parent = this.parent; parent; parent = parent.parent) {
4745
            if (childList)
4746
                parent.flags |= 2 /* ViewFlag.NodeDirty */;
4747
            if (parent.flags & 1 /* ViewFlag.ChildDirty */)
4748
                return;
4749
            parent.flags |= 1 /* ViewFlag.ChildDirty */;
4750
            childList = false;
4751
        }
4752
    }
4753
    setParent(parent) {
4754
        if (this.parent != parent) {
4755
            this.parent = parent;
4756
            if (this.flags & 7 /* ViewFlag.Dirty */)
4757
                this.markParentsDirty(true);
4758
        }
4759
    }
4760
    setDOM(dom) {
4761
        if (this.dom == dom)
4762
            return;
4763
        if (this.dom)
4764
            this.dom.cmView = null;
4765
        this.dom = dom;
4766
        dom.cmView = this;
4767
    }
4768
    get rootView() {
4769
        for (let v = this;;) {
4770
            let parent = v.parent;
4771
            if (!parent)
4772
                return v;
4773
            v = parent;
4774
        }
4775
    }
4776
    replaceChildren(from, to, children = noChildren) {
4777
        this.markDirty();
4778
        for (let i = from; i < to; i++) {
4779
            let child = this.children[i];
4780
            if (child.parent == this && children.indexOf(child) < 0)
4781
                child.destroy();
4782
        }
4783
        this.children.splice(from, to - from, ...children);
4784
        for (let i = 0; i < children.length; i++)
4785
            children[i].setParent(this);
4786
    }
4787
    ignoreMutation(_rec) { return false; }
4788
    ignoreEvent(_event) { return false; }
4789
    childCursor(pos = this.length) {
4790
        return new ChildCursor(this.children, pos, this.children.length);
4791
    }
4792
    childPos(pos, bias = 1) {
4793
        return this.childCursor().findPos(pos, bias);
4794
    }
4795
    toString() {
4796
        let name = this.constructor.name.replace("View", "");
4797
        return name + (this.children.length ? "(" + this.children.join() + ")" :
4798
            this.length ? "[" + (name == "Text" ? this.text : this.length) + "]" : "") +
4799
            (this.breakAfter ? "#" : "");
4800
    }
4801
    static get(node) { return node.cmView; }
4802
    get isEditable() { return true; }
4803
    get isWidget() { return false; }
4804
    get isHidden() { return false; }
4805
    merge(from, to, source, hasStart, openStart, openEnd) {
4806
        return false;
4807
    }
4808
    become(other) { return false; }
4809
    canReuseDOM(other) {
4810
        return other.constructor == this.constructor && !((this.flags | other.flags) & 8 /* ViewFlag.Composition */);
4811
    }
4812
    // When this is a zero-length view with a side, this should return a
4813
    // number <= 0 to indicate it is before its position, or a
4814
    // number > 0 when after its position.
4815
    getSide() { return 0; }
4816
    destroy() {
4817
        for (let child of this.children)
4818
            if (child.parent == this)
4819
                child.destroy();
4820
        this.parent = null;
4821
    }
4822
}
4823
ContentView.prototype.breakAfter = 0;
4824
// Remove a DOM node and return its next sibling.
4825
function rm$1(dom) {
4826
    let next = dom.nextSibling;
4827
    dom.parentNode.removeChild(dom);
4828
    return next;
4829
}
4830
class ChildCursor {
4831
    constructor(children, pos, i) {
4832
        this.children = children;
4833
        this.pos = pos;
4834
        this.i = i;
4835
        this.off = 0;
4836
    }
4837
    findPos(pos, bias = 1) {
4838
        for (;;) {
4839
            if (pos > this.pos || pos == this.pos &&
4840
                (bias > 0 || this.i == 0 || this.children[this.i - 1].breakAfter)) {
4841
                this.off = pos - this.pos;
4842
                return this;
4843
            }
4844
            let next = this.children[--this.i];
4845
            this.pos -= next.length + next.breakAfter;
4846
        }
4847
    }
4848
}
4849
function replaceRange(parent, fromI, fromOff, toI, toOff, insert, breakAtStart, openStart, openEnd) {
4850
    let { children } = parent;
4851
    let before = children.length ? children[fromI] : null;
4852
    let last = insert.length ? insert[insert.length - 1] : null;
4853
    let breakAtEnd = last ? last.breakAfter : breakAtStart;
4854
    // Change within a single child
4855
    if (fromI == toI && before && !breakAtStart && !breakAtEnd && insert.length < 2 &&
4856
        before.merge(fromOff, toOff, insert.length ? last : null, fromOff == 0, openStart, openEnd))
4857
        return;
4858
    if (toI < children.length) {
4859
        let after = children[toI];
4860
        // Make sure the end of the child after the update is preserved in `after`
4861
        if (after && (toOff < after.length || after.breakAfter && (last === null || last === void 0 ? void 0 : last.breakAfter))) {
4862
            // If we're splitting a child, separate part of it to avoid that
4863
            // being mangled when updating the child before the update.
4864
            if (fromI == toI) {
4865
                after = after.split(toOff);
4866
                toOff = 0;
4867
            }
4868
            // If the element after the replacement should be merged with
4869
            // the last replacing element, update `content`
4870
            if (!breakAtEnd && last && after.merge(0, toOff, last, true, 0, openEnd)) {
4871
                insert[insert.length - 1] = after;
4872
            }
4873
            else {
4874
                // Remove the start of the after element, if necessary, and
4875
                // add it to `content`.
4876
                if (toOff || after.children.length && !after.children[0].length)
4877
                    after.merge(0, toOff, null, false, 0, openEnd);
4878
                insert.push(after);
4879
            }
4880
        }
4881
        else if (after === null || after === void 0 ? void 0 : after.breakAfter) {
4882
            // The element at `toI` is entirely covered by this range.
4883
            // Preserve its line break, if any.
4884
            if (last)
4885
                last.breakAfter = 1;
4886
            else
4887
                breakAtStart = 1;
4888
        }
4889
        // Since we've handled the next element from the current elements
4890
        // now, make sure `toI` points after that.
4891
        toI++;
4892
    }
4893
    if (before) {
4894
        before.breakAfter = breakAtStart;
4895
        if (fromOff > 0) {
4896
            if (!breakAtStart && insert.length && before.merge(fromOff, before.length, insert[0], false, openStart, 0)) {
4897
                before.breakAfter = insert.shift().breakAfter;
4898
            }
4899
            else if (fromOff < before.length || before.children.length && before.children[before.children.length - 1].length == 0) {
4900
                before.merge(fromOff, before.length, null, false, openStart, 0);
4901
            }
4902
            fromI++;
4903
        }
4904
    }
4905
    // Try to merge widgets on the boundaries of the replacement
4906
    while (fromI < toI && insert.length) {
4907
        if (children[toI - 1].become(insert[insert.length - 1])) {
4908
            toI--;
4909
            insert.pop();
4910
            openEnd = insert.length ? 0 : openStart;
4911
        }
4912
        else if (children[fromI].become(insert[0])) {
4913
            fromI++;
4914
            insert.shift();
4915
            openStart = insert.length ? 0 : openEnd;
4916
        }
4917
        else {
4918
            break;
4919
        }
4920
    }
4921
    if (!insert.length && fromI && toI < children.length && !children[fromI - 1].breakAfter &&
4922
        children[toI].merge(0, 0, children[fromI - 1], false, openStart, openEnd))
4923
        fromI--;
4924
    if (fromI < toI || insert.length)
4925
        parent.replaceChildren(fromI, toI, insert);
4926
}
4927
function mergeChildrenInto(parent, from, to, insert, openStart, openEnd) {
4928
    let cur = parent.childCursor();
4929
    let { i: toI, off: toOff } = cur.findPos(to, 1);
4930
    let { i: fromI, off: fromOff } = cur.findPos(from, -1);
4931
    let dLen = from - to;
4932
    for (let view of insert)
4933
        dLen += view.length;
4934
    parent.length += dLen;
4935
    replaceRange(parent, fromI, fromOff, toI, toOff, insert, 0, openStart, openEnd);
4936
}
4937
 
4938
let nav = typeof navigator != "undefined" ? navigator : { userAgent: "", vendor: "", platform: "" };
4939
let doc = typeof document != "undefined" ? document : { documentElement: { style: {} } };
4940
const ie_edge = /*@__PURE__*//Edge\/(\d+)/.exec(nav.userAgent);
4941
const ie_upto10 = /*@__PURE__*//MSIE \d/.test(nav.userAgent);
4942
const ie_11up = /*@__PURE__*//Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(nav.userAgent);
4943
const ie = !!(ie_upto10 || ie_11up || ie_edge);
4944
const gecko = !ie && /*@__PURE__*//gecko\/(\d+)/i.test(nav.userAgent);
4945
const chrome = !ie && /*@__PURE__*//Chrome\/(\d+)/.exec(nav.userAgent);
4946
const webkit = "webkitFontSmoothing" in doc.documentElement.style;
4947
const safari = !ie && /*@__PURE__*//Apple Computer/.test(nav.vendor);
4948
const ios = safari && (/*@__PURE__*//Mobile\/\w+/.test(nav.userAgent) || nav.maxTouchPoints > 2);
4949
var browser = {
4950
    mac: ios || /*@__PURE__*//Mac/.test(nav.platform),
4951
    windows: /*@__PURE__*//Win/.test(nav.platform),
4952
    linux: /*@__PURE__*//Linux|X11/.test(nav.platform),
4953
    ie,
4954
    ie_version: ie_upto10 ? doc.documentMode || 6 : ie_11up ? +ie_11up[1] : ie_edge ? +ie_edge[1] : 0,
4955
    gecko,
4956
    gecko_version: gecko ? +(/*@__PURE__*//Firefox\/(\d+)/.exec(nav.userAgent) || [0, 0])[1] : 0,
4957
    chrome: !!chrome,
4958
    chrome_version: chrome ? +chrome[1] : 0,
4959
    ios,
4960
    android: /*@__PURE__*//Android\b/.test(nav.userAgent),
4961
    webkit,
4962
    safari,
4963
    webkit_version: webkit ? +(/*@__PURE__*//\bAppleWebKit\/(\d+)/.exec(navigator.userAgent) || [0, 0])[1] : 0,
4964
    tabSize: doc.documentElement.style.tabSize != null ? "tab-size" : "-moz-tab-size"
4965
};
4966
 
4967
const MaxJoinLen = 256;
4968
class TextView extends ContentView {
4969
    constructor(text) {
4970
        super();
4971
        this.text = text;
4972
    }
4973
    get length() { return this.text.length; }
4974
    createDOM(textDOM) {
4975
        this.setDOM(textDOM || document.createTextNode(this.text));
4976
    }
4977
    sync(view, track) {
4978
        if (!this.dom)
4979
            this.createDOM();
4980
        if (this.dom.nodeValue != this.text) {
4981
            if (track && track.node == this.dom)
4982
                track.written = true;
4983
            this.dom.nodeValue = this.text;
4984
        }
4985
    }
4986
    reuseDOM(dom) {
4987
        if (dom.nodeType == 3)
4988
            this.createDOM(dom);
4989
    }
4990
    merge(from, to, source) {
4991
        if ((this.flags & 8 /* ViewFlag.Composition */) ||
4992
            source && (!(source instanceof TextView) ||
4993
                this.length - (to - from) + source.length > MaxJoinLen ||
4994
                (source.flags & 8 /* ViewFlag.Composition */)))
4995
            return false;
4996
        this.text = this.text.slice(0, from) + (source ? source.text : "") + this.text.slice(to);
4997
        this.markDirty();
4998
        return true;
4999
    }
5000
    split(from) {
5001
        let result = new TextView(this.text.slice(from));
5002
        this.text = this.text.slice(0, from);
5003
        this.markDirty();
5004
        result.flags |= this.flags & 8 /* ViewFlag.Composition */;
5005
        return result;
5006
    }
5007
    localPosFromDOM(node, offset) {
5008
        return node == this.dom ? offset : offset ? this.text.length : 0;
5009
    }
5010
    domAtPos(pos) { return new DOMPos(this.dom, pos); }
5011
    domBoundsAround(_from, _to, offset) {
5012
        return { from: offset, to: offset + this.length, startDOM: this.dom, endDOM: this.dom.nextSibling };
5013
    }
5014
    coordsAt(pos, side) {
5015
        return textCoords(this.dom, pos, side);
5016
    }
5017
}
5018
class MarkView extends ContentView {
5019
    constructor(mark, children = [], length = 0) {
5020
        super();
5021
        this.mark = mark;
5022
        this.children = children;
5023
        this.length = length;
5024
        for (let ch of children)
5025
            ch.setParent(this);
5026
    }
5027
    setAttrs(dom) {
5028
        clearAttributes(dom);
5029
        if (this.mark.class)
5030
            dom.className = this.mark.class;
5031
        if (this.mark.attrs)
5032
            for (let name in this.mark.attrs)
5033
                dom.setAttribute(name, this.mark.attrs[name]);
5034
        return dom;
5035
    }
5036
    canReuseDOM(other) {
5037
        return super.canReuseDOM(other) && !((this.flags | other.flags) & 8 /* ViewFlag.Composition */);
5038
    }
5039
    reuseDOM(node) {
5040
        if (node.nodeName == this.mark.tagName.toUpperCase()) {
5041
            this.setDOM(node);
5042
            this.flags |= 4 /* ViewFlag.AttrsDirty */ | 2 /* ViewFlag.NodeDirty */;
5043
        }
5044
    }
5045
    sync(view, track) {
5046
        if (!this.dom)
5047
            this.setDOM(this.setAttrs(document.createElement(this.mark.tagName)));
5048
        else if (this.flags & 4 /* ViewFlag.AttrsDirty */)
5049
            this.setAttrs(this.dom);
5050
        super.sync(view, track);
5051
    }
5052
    merge(from, to, source, _hasStart, openStart, openEnd) {
5053
        if (source && (!(source instanceof MarkView && source.mark.eq(this.mark)) ||
5054
            (from && openStart <= 0) || (to < this.length && openEnd <= 0)))
5055
            return false;
5056
        mergeChildrenInto(this, from, to, source ? source.children.slice() : [], openStart - 1, openEnd - 1);
5057
        this.markDirty();
5058
        return true;
5059
    }
5060
    split(from) {
5061
        let result = [], off = 0, detachFrom = -1, i = 0;
5062
        for (let elt of this.children) {
5063
            let end = off + elt.length;
5064
            if (end > from)
5065
                result.push(off < from ? elt.split(from - off) : elt);
5066
            if (detachFrom < 0 && off >= from)
5067
                detachFrom = i;
5068
            off = end;
5069
            i++;
5070
        }
5071
        let length = this.length - from;
5072
        this.length = from;
5073
        if (detachFrom > -1) {
5074
            this.children.length = detachFrom;
5075
            this.markDirty();
5076
        }
5077
        return new MarkView(this.mark, result, length);
5078
    }
5079
    domAtPos(pos) {
5080
        return inlineDOMAtPos(this, pos);
5081
    }
5082
    coordsAt(pos, side) {
5083
        return coordsInChildren(this, pos, side);
5084
    }
5085
}
5086
function textCoords(text, pos, side) {
5087
    let length = text.nodeValue.length;
5088
    if (pos > length)
5089
        pos = length;
5090
    let from = pos, to = pos, flatten = 0;
5091
    if (pos == 0 && side < 0 || pos == length && side >= 0) {
5092
        if (!(browser.chrome || browser.gecko)) { // These browsers reliably return valid rectangles for empty ranges
5093
            if (pos) {
5094
                from--;
5095
                flatten = 1;
5096
            } // FIXME this is wrong in RTL text
5097
            else if (to < length) {
5098
                to++;
5099
                flatten = -1;
5100
            }
5101
        }
5102
    }
5103
    else {
5104
        if (side < 0)
5105
            from--;
5106
        else if (to < length)
5107
            to++;
5108
    }
5109
    let rects = textRange(text, from, to).getClientRects();
5110
    if (!rects.length)
5111
        return null;
5112
    let rect = rects[(flatten ? flatten < 0 : side >= 0) ? 0 : rects.length - 1];
5113
    if (browser.safari && !flatten && rect.width == 0)
5114
        rect = Array.prototype.find.call(rects, r => r.width) || rect;
5115
    return flatten ? flattenRect(rect, flatten < 0) : rect || null;
5116
}
5117
// Also used for collapsed ranges that don't have a placeholder widget!
5118
class WidgetView extends ContentView {
5119
    static create(widget, length, side) {
5120
        return new WidgetView(widget, length, side);
5121
    }
5122
    constructor(widget, length, side) {
5123
        super();
5124
        this.widget = widget;
5125
        this.length = length;
5126
        this.side = side;
5127
        this.prevWidget = null;
5128
    }
5129
    split(from) {
5130
        let result = WidgetView.create(this.widget, this.length - from, this.side);
5131
        this.length -= from;
5132
        return result;
5133
    }
5134
    sync(view) {
5135
        if (!this.dom || !this.widget.updateDOM(this.dom, view)) {
5136
            if (this.dom && this.prevWidget)
5137
                this.prevWidget.destroy(this.dom);
5138
            this.prevWidget = null;
5139
            this.setDOM(this.widget.toDOM(view));
5140
            if (!this.widget.editable)
5141
                this.dom.contentEditable = "false";
5142
        }
5143
    }
5144
    getSide() { return this.side; }
5145
    merge(from, to, source, hasStart, openStart, openEnd) {
5146
        if (source && (!(source instanceof WidgetView) || !this.widget.compare(source.widget) ||
5147
            from > 0 && openStart <= 0 || to < this.length && openEnd <= 0))
5148
            return false;
5149
        this.length = from + (source ? source.length : 0) + (this.length - to);
5150
        return true;
5151
    }
5152
    become(other) {
5153
        if (other instanceof WidgetView && other.side == this.side &&
5154
            this.widget.constructor == other.widget.constructor) {
5155
            if (!this.widget.compare(other.widget))
5156
                this.markDirty(true);
5157
            if (this.dom && !this.prevWidget)
5158
                this.prevWidget = this.widget;
5159
            this.widget = other.widget;
5160
            this.length = other.length;
5161
            return true;
5162
        }
5163
        return false;
5164
    }
5165
    ignoreMutation() { return true; }
5166
    ignoreEvent(event) { return this.widget.ignoreEvent(event); }
5167
    get overrideDOMText() {
5168
        if (this.length == 0)
5169
            return Text.empty;
5170
        let top = this;
5171
        while (top.parent)
5172
            top = top.parent;
5173
        let { view } = top, text = view && view.state.doc, start = this.posAtStart;
5174
        return text ? text.slice(start, start + this.length) : Text.empty;
5175
    }
5176
    domAtPos(pos) {
5177
        return (this.length ? pos == 0 : this.side > 0)
5178
            ? DOMPos.before(this.dom)
5179
            : DOMPos.after(this.dom, pos == this.length);
5180
    }
5181
    domBoundsAround() { return null; }
5182
    coordsAt(pos, side) {
5183
        let custom = this.widget.coordsAt(this.dom, pos, side);
5184
        if (custom)
5185
            return custom;
5186
        let rects = this.dom.getClientRects(), rect = null;
5187
        if (!rects.length)
5188
            return null;
5189
        let fromBack = this.side ? this.side < 0 : pos > 0;
5190
        for (let i = fromBack ? rects.length - 1 : 0;; i += (fromBack ? -1 : 1)) {
5191
            rect = rects[i];
5192
            if (pos > 0 ? i == 0 : i == rects.length - 1 || rect.top < rect.bottom)
5193
                break;
5194
        }
5195
        return flattenRect(rect, !fromBack);
5196
    }
5197
    get isEditable() { return false; }
5198
    get isWidget() { return true; }
5199
    get isHidden() { return this.widget.isHidden; }
5200
    destroy() {
5201
        super.destroy();
5202
        if (this.dom)
5203
            this.widget.destroy(this.dom);
5204
    }
5205
}
5206
// These are drawn around uneditable widgets to avoid a number of
5207
// browser bugs that show up when the cursor is directly next to
5208
// uneditable inline content.
5209
class WidgetBufferView extends ContentView {
5210
    constructor(side) {
5211
        super();
5212
        this.side = side;
5213
    }
5214
    get length() { return 0; }
5215
    merge() { return false; }
5216
    become(other) {
5217
        return other instanceof WidgetBufferView && other.side == this.side;
5218
    }
5219
    split() { return new WidgetBufferView(this.side); }
5220
    sync() {
5221
        if (!this.dom) {
5222
            let dom = document.createElement("img");
5223
            dom.className = "cm-widgetBuffer";
5224
            dom.setAttribute("aria-hidden", "true");
5225
            this.setDOM(dom);
5226
        }
5227
    }
5228
    getSide() { return this.side; }
5229
    domAtPos(pos) { return this.side > 0 ? DOMPos.before(this.dom) : DOMPos.after(this.dom); }
5230
    localPosFromDOM() { return 0; }
5231
    domBoundsAround() { return null; }
5232
    coordsAt(pos) {
5233
        return this.dom.getBoundingClientRect();
5234
    }
5235
    get overrideDOMText() {
5236
        return Text.empty;
5237
    }
5238
    get isHidden() { return true; }
5239
}
5240
TextView.prototype.children = WidgetView.prototype.children = WidgetBufferView.prototype.children = noChildren;
5241
function inlineDOMAtPos(parent, pos) {
5242
    let dom = parent.dom, { children } = parent, i = 0;
5243
    for (let off = 0; i < children.length; i++) {
5244
        let child = children[i], end = off + child.length;
5245
        if (end == off && child.getSide() <= 0)
5246
            continue;
5247
        if (pos > off && pos < end && child.dom.parentNode == dom)
5248
            return child.domAtPos(pos - off);
5249
        if (pos <= off)
5250
            break;
5251
        off = end;
5252
    }
5253
    for (let j = i; j > 0; j--) {
5254
        let prev = children[j - 1];
5255
        if (prev.dom.parentNode == dom)
5256
            return prev.domAtPos(prev.length);
5257
    }
5258
    for (let j = i; j < children.length; j++) {
5259
        let next = children[j];
5260
        if (next.dom.parentNode == dom)
5261
            return next.domAtPos(0);
5262
    }
5263
    return new DOMPos(dom, 0);
5264
}
5265
// Assumes `view`, if a mark view, has precisely 1 child.
5266
function joinInlineInto(parent, view, open) {
5267
    let last, { children } = parent;
5268
    if (open > 0 && view instanceof MarkView && children.length &&
5269
        (last = children[children.length - 1]) instanceof MarkView && last.mark.eq(view.mark)) {
5270
        joinInlineInto(last, view.children[0], open - 1);
5271
    }
5272
    else {
5273
        children.push(view);
5274
        view.setParent(parent);
5275
    }
5276
    parent.length += view.length;
5277
}
5278
function coordsInChildren(view, pos, side) {
5279
    let before = null, beforePos = -1, after = null, afterPos = -1;
5280
    function scan(view, pos) {
5281
        for (let i = 0, off = 0; i < view.children.length && off <= pos; i++) {
5282
            let child = view.children[i], end = off + child.length;
5283
            if (end >= pos) {
5284
                if (child.children.length) {
5285
                    scan(child, pos - off);
5286
                }
5287
                else if ((!after || after.isHidden && side > 0) &&
5288
                    (end > pos || off == end && child.getSide() > 0)) {
5289
                    after = child;
5290
                    afterPos = pos - off;
5291
                }
5292
                else if (off < pos || (off == end && child.getSide() < 0) && !child.isHidden) {
5293
                    before = child;
5294
                    beforePos = pos - off;
5295
                }
5296
            }
5297
            off = end;
5298
        }
5299
    }
5300
    scan(view, pos);
5301
    let target = (side < 0 ? before : after) || before || after;
5302
    if (target)
5303
        return target.coordsAt(Math.max(0, target == before ? beforePos : afterPos), side);
5304
    return fallbackRect(view);
5305
}
5306
function fallbackRect(view) {
5307
    let last = view.dom.lastChild;
5308
    if (!last)
5309
        return view.dom.getBoundingClientRect();
5310
    let rects = clientRectsFor(last);
5311
    return rects[rects.length - 1] || null;
5312
}
5313
 
5314
function combineAttrs(source, target) {
5315
    for (let name in source) {
5316
        if (name == "class" && target.class)
5317
            target.class += " " + source.class;
5318
        else if (name == "style" && target.style)
5319
            target.style += ";" + source.style;
5320
        else
5321
            target[name] = source[name];
5322
    }
5323
    return target;
5324
}
5325
const noAttrs = /*@__PURE__*/Object.create(null);
5326
function attrsEq(a, b, ignore) {
5327
    if (a == b)
5328
        return true;
5329
    if (!a)
5330
        a = noAttrs;
5331
    if (!b)
5332
        b = noAttrs;
5333
    let keysA = Object.keys(a), keysB = Object.keys(b);
5334
    if (keysA.length - (ignore && keysA.indexOf(ignore) > -1 ? 1 : 0) !=
5335
        keysB.length - (ignore && keysB.indexOf(ignore) > -1 ? 1 : 0))
5336
        return false;
5337
    for (let key of keysA) {
5338
        if (key != ignore && (keysB.indexOf(key) == -1 || a[key] !== b[key]))
5339
            return false;
5340
    }
5341
    return true;
5342
}
5343
function updateAttrs(dom, prev, attrs) {
5344
    let changed = false;
5345
    if (prev)
5346
        for (let name in prev)
5347
            if (!(attrs && name in attrs)) {
5348
                changed = true;
5349
                if (name == "style")
5350
                    dom.style.cssText = "";
5351
                else
5352
                    dom.removeAttribute(name);
5353
            }
5354
    if (attrs)
5355
        for (let name in attrs)
5356
            if (!(prev && prev[name] == attrs[name])) {
5357
                changed = true;
5358
                if (name == "style")
5359
                    dom.style.cssText = attrs[name];
5360
                else
5361
                    dom.setAttribute(name, attrs[name]);
5362
            }
5363
    return changed;
5364
}
5365
function getAttrs$1(dom) {
5366
    let attrs = Object.create(null);
5367
    for (let i = 0; i < dom.attributes.length; i++) {
5368
        let attr = dom.attributes[i];
5369
        attrs[attr.name] = attr.value;
5370
    }
5371
    return attrs;
5372
}
5373
 
5374
class LineView extends ContentView {
5375
    constructor() {
5376
        super(...arguments);
5377
        this.children = [];
5378
        this.length = 0;
5379
        this.prevAttrs = undefined;
5380
        this.attrs = null;
5381
        this.breakAfter = 0;
5382
    }
5383
    // Consumes source
5384
    merge(from, to, source, hasStart, openStart, openEnd) {
5385
        if (source) {
5386
            if (!(source instanceof LineView))
5387
                return false;
5388
            if (!this.dom)
5389
                source.transferDOM(this); // Reuse source.dom when appropriate
5390
        }
5391
        if (hasStart)
5392
            this.setDeco(source ? source.attrs : null);
5393
        mergeChildrenInto(this, from, to, source ? source.children.slice() : [], openStart, openEnd);
5394
        return true;
5395
    }
5396
    split(at) {
5397
        let end = new LineView;
5398
        end.breakAfter = this.breakAfter;
5399
        if (this.length == 0)
5400
            return end;
5401
        let { i, off } = this.childPos(at);
5402
        if (off) {
5403
            end.append(this.children[i].split(off), 0);
5404
            this.children[i].merge(off, this.children[i].length, null, false, 0, 0);
5405
            i++;
5406
        }
5407
        for (let j = i; j < this.children.length; j++)
5408
            end.append(this.children[j], 0);
5409
        while (i > 0 && this.children[i - 1].length == 0)
5410
            this.children[--i].destroy();
5411
        this.children.length = i;
5412
        this.markDirty();
5413
        this.length = at;
5414
        return end;
5415
    }
5416
    transferDOM(other) {
5417
        if (!this.dom)
5418
            return;
5419
        this.markDirty();
5420
        other.setDOM(this.dom);
5421
        other.prevAttrs = this.prevAttrs === undefined ? this.attrs : this.prevAttrs;
5422
        this.prevAttrs = undefined;
5423
        this.dom = null;
5424
    }
5425
    setDeco(attrs) {
5426
        if (!attrsEq(this.attrs, attrs)) {
5427
            if (this.dom) {
5428
                this.prevAttrs = this.attrs;
5429
                this.markDirty();
5430
            }
5431
            this.attrs = attrs;
5432
        }
5433
    }
5434
    append(child, openStart) {
5435
        joinInlineInto(this, child, openStart);
5436
    }
5437
    // Only called when building a line view in ContentBuilder
5438
    addLineDeco(deco) {
5439
        let attrs = deco.spec.attributes, cls = deco.spec.class;
5440
        if (attrs)
5441
            this.attrs = combineAttrs(attrs, this.attrs || {});
5442
        if (cls)
5443
            this.attrs = combineAttrs({ class: cls }, this.attrs || {});
5444
    }
5445
    domAtPos(pos) {
5446
        return inlineDOMAtPos(this, pos);
5447
    }
5448
    reuseDOM(node) {
5449
        if (node.nodeName == "DIV") {
5450
            this.setDOM(node);
5451
            this.flags |= 4 /* ViewFlag.AttrsDirty */ | 2 /* ViewFlag.NodeDirty */;
5452
        }
5453
    }
5454
    sync(view, track) {
5455
        var _a;
5456
        if (!this.dom) {
5457
            this.setDOM(document.createElement("div"));
5458
            this.dom.className = "cm-line";
5459
            this.prevAttrs = this.attrs ? null : undefined;
5460
        }
5461
        else if (this.flags & 4 /* ViewFlag.AttrsDirty */) {
5462
            clearAttributes(this.dom);
5463
            this.dom.className = "cm-line";
5464
            this.prevAttrs = this.attrs ? null : undefined;
5465
        }
5466
        if (this.prevAttrs !== undefined) {
5467
            updateAttrs(this.dom, this.prevAttrs, this.attrs);
5468
            this.dom.classList.add("cm-line");
5469
            this.prevAttrs = undefined;
5470
        }
5471
        super.sync(view, track);
5472
        let last = this.dom.lastChild;
5473
        while (last && ContentView.get(last) instanceof MarkView)
5474
            last = last.lastChild;
5475
        if (!last || !this.length ||
5476
            last.nodeName != "BR" && ((_a = ContentView.get(last)) === null || _a === void 0 ? void 0 : _a.isEditable) == false &&
5477
                (!browser.ios || !this.children.some(ch => ch instanceof TextView))) {
5478
            let hack = document.createElement("BR");
5479
            hack.cmIgnore = true;
5480
            this.dom.appendChild(hack);
5481
        }
5482
    }
5483
    measureTextSize() {
5484
        if (this.children.length == 0 || this.length > 20)
5485
            return null;
5486
        let totalWidth = 0, textHeight;
5487
        for (let child of this.children) {
5488
            if (!(child instanceof TextView) || /[^ -~]/.test(child.text))
5489
                return null;
5490
            let rects = clientRectsFor(child.dom);
5491
            if (rects.length != 1)
5492
                return null;
5493
            totalWidth += rects[0].width;
5494
            textHeight = rects[0].height;
5495
        }
5496
        return !totalWidth ? null : {
5497
            lineHeight: this.dom.getBoundingClientRect().height,
5498
            charWidth: totalWidth / this.length,
5499
            textHeight
5500
        };
5501
    }
5502
    coordsAt(pos, side) {
5503
        let rect = coordsInChildren(this, pos, side);
5504
        // Correct rectangle height for empty lines when the returned
5505
        // height is larger than the text height.
5506
        if (!this.children.length && rect && this.parent) {
5507
            let { heightOracle } = this.parent.view.viewState, height = rect.bottom - rect.top;
5508
            if (Math.abs(height - heightOracle.lineHeight) < 2 && heightOracle.textHeight < height) {
5509
                let dist = (height - heightOracle.textHeight) / 2;
5510
                return { top: rect.top + dist, bottom: rect.bottom - dist, left: rect.left, right: rect.left };
5511
            }
5512
        }
5513
        return rect;
5514
    }
5515
    become(_other) { return false; }
5516
    covers() { return true; }
5517
    static find(docView, pos) {
5518
        for (let i = 0, off = 0; i < docView.children.length; i++) {
5519
            let block = docView.children[i], end = off + block.length;
5520
            if (end >= pos) {
5521
                if (block instanceof LineView)
5522
                    return block;
5523
                if (end > pos)
5524
                    break;
5525
            }
5526
            off = end + block.breakAfter;
5527
        }
5528
        return null;
5529
    }
5530
}
5531
class BlockWidgetView extends ContentView {
5532
    constructor(widget, length, deco) {
5533
        super();
5534
        this.widget = widget;
5535
        this.length = length;
5536
        this.deco = deco;
5537
        this.breakAfter = 0;
5538
        this.prevWidget = null;
5539
    }
5540
    merge(from, to, source, _takeDeco, openStart, openEnd) {
5541
        if (source && (!(source instanceof BlockWidgetView) || !this.widget.compare(source.widget) ||
5542
            from > 0 && openStart <= 0 || to < this.length && openEnd <= 0))
5543
            return false;
5544
        this.length = from + (source ? source.length : 0) + (this.length - to);
5545
        return true;
5546
    }
5547
    domAtPos(pos) {
5548
        return pos == 0 ? DOMPos.before(this.dom) : DOMPos.after(this.dom, pos == this.length);
5549
    }
5550
    split(at) {
5551
        let len = this.length - at;
5552
        this.length = at;
5553
        let end = new BlockWidgetView(this.widget, len, this.deco);
5554
        end.breakAfter = this.breakAfter;
5555
        return end;
5556
    }
5557
    get children() { return noChildren; }
5558
    sync(view) {
5559
        if (!this.dom || !this.widget.updateDOM(this.dom, view)) {
5560
            if (this.dom && this.prevWidget)
5561
                this.prevWidget.destroy(this.dom);
5562
            this.prevWidget = null;
5563
            this.setDOM(this.widget.toDOM(view));
5564
            if (!this.widget.editable)
5565
                this.dom.contentEditable = "false";
5566
        }
5567
    }
5568
    get overrideDOMText() {
5569
        return this.parent ? this.parent.view.state.doc.slice(this.posAtStart, this.posAtEnd) : Text.empty;
5570
    }
5571
    domBoundsAround() { return null; }
5572
    become(other) {
5573
        if (other instanceof BlockWidgetView &&
5574
            other.widget.constructor == this.widget.constructor) {
5575
            if (!other.widget.compare(this.widget))
5576
                this.markDirty(true);
5577
            if (this.dom && !this.prevWidget)
5578
                this.prevWidget = this.widget;
5579
            this.widget = other.widget;
5580
            this.length = other.length;
5581
            this.deco = other.deco;
5582
            this.breakAfter = other.breakAfter;
5583
            return true;
5584
        }
5585
        return false;
5586
    }
5587
    ignoreMutation() { return true; }
5588
    ignoreEvent(event) { return this.widget.ignoreEvent(event); }
5589
    get isEditable() { return false; }
5590
    get isWidget() { return true; }
5591
    coordsAt(pos, side) {
5592
        return this.widget.coordsAt(this.dom, pos, side);
5593
    }
5594
    destroy() {
5595
        super.destroy();
5596
        if (this.dom)
5597
            this.widget.destroy(this.dom);
5598
    }
5599
    covers(side) {
5600
        let { startSide, endSide } = this.deco;
5601
        return startSide == endSide ? false : side < 0 ? startSide < 0 : endSide > 0;
5602
    }
5603
}
5604
 
5605
/**
5606
Widgets added to the content are described by subclasses of this
5607
class. Using a description object like that makes it possible to
5608
delay creating of the DOM structure for a widget until it is
5609
needed, and to avoid redrawing widgets even if the decorations
5610
that define them are recreated.
5611
*/
5612
class WidgetType {
5613
    /**
5614
    Compare this instance to another instance of the same type.
5615
    (TypeScript can't express this, but only instances of the same
5616
    specific class will be passed to this method.) This is used to
5617
    avoid redrawing widgets when they are replaced by a new
5618
    decoration of the same type. The default implementation just
5619
    returns `false`, which will cause new instances of the widget to
5620
    always be redrawn.
5621
    */
5622
    eq(widget) { return false; }
5623
    /**
5624
    Update a DOM element created by a widget of the same type (but
5625
    different, non-`eq` content) to reflect this widget. May return
5626
    true to indicate that it could update, false to indicate it
5627
    couldn't (in which case the widget will be redrawn). The default
5628
    implementation just returns false.
5629
    */
5630
    updateDOM(dom, view) { return false; }
5631
    /**
5632
    @internal
5633
    */
5634
    compare(other) {
5635
        return this == other || this.constructor == other.constructor && this.eq(other);
5636
    }
5637
    /**
5638
    The estimated height this widget will have, to be used when
5639
    estimating the height of content that hasn't been drawn. May
5640
    return -1 to indicate you don't know. The default implementation
5641
    returns -1.
5642
    */
5643
    get estimatedHeight() { return -1; }
5644
    /**
5645
    For inline widgets that are displayed inline (as opposed to
5646
    `inline-block`) and introduce line breaks (through `<br>` tags
5647
    or textual newlines), this must indicate the amount of line
5648
    breaks they introduce. Defaults to 0.
5649
    */
5650
    get lineBreaks() { return 0; }
5651
    /**
5652
    Can be used to configure which kinds of events inside the widget
5653
    should be ignored by the editor. The default is to ignore all
5654
    events.
5655
    */
5656
    ignoreEvent(event) { return true; }
5657
    /**
5658
    Override the way screen coordinates for positions at/in the
5659
    widget are found. `pos` will be the offset into the widget, and
5660
    `side` the side of the position that is being queried—less than
5661
    zero for before, greater than zero for after, and zero for
5662
    directly at that position.
5663
    */
5664
    coordsAt(dom, pos, side) { return null; }
5665
    /**
5666
    @internal
5667
    */
5668
    get isHidden() { return false; }
5669
    /**
5670
    @internal
5671
    */
5672
    get editable() { return false; }
5673
    /**
5674
    This is called when the an instance of the widget is removed
5675
    from the editor view.
5676
    */
5677
    destroy(dom) { }
5678
}
5679
/**
5680
The different types of blocks that can occur in an editor view.
5681
*/
5682
var BlockType = /*@__PURE__*/(function (BlockType) {
5683
    /**
5684
    A line of text.
5685
    */
5686
    BlockType[BlockType["Text"] = 0] = "Text";
5687
    /**
5688
    A block widget associated with the position after it.
5689
    */
5690
    BlockType[BlockType["WidgetBefore"] = 1] = "WidgetBefore";
5691
    /**
5692
    A block widget associated with the position before it.
5693
    */
5694
    BlockType[BlockType["WidgetAfter"] = 2] = "WidgetAfter";
5695
    /**
5696
    A block widget [replacing](https://codemirror.net/6/docs/ref/#view.Decoration^replace) a range of content.
5697
    */
5698
    BlockType[BlockType["WidgetRange"] = 3] = "WidgetRange";
5699
return BlockType})(BlockType || (BlockType = {}));
5700
/**
5701
A decoration provides information on how to draw or style a piece
5702
of content. You'll usually use it wrapped in a
5703
[`Range`](https://codemirror.net/6/docs/ref/#state.Range), which adds a start and end position.
5704
@nonabstract
5705
*/
5706
class Decoration extends RangeValue {
5707
    constructor(
5708
    /**
5709
    @internal
5710
    */
5711
    startSide,
5712
    /**
5713
    @internal
5714
    */
5715
    endSide,
5716
    /**
5717
    @internal
5718
    */
5719
    widget,
5720
    /**
5721
    The config object used to create this decoration. You can
5722
    include additional properties in there to store metadata about
5723
    your decoration.
5724
    */
5725
    spec) {
5726
        super();
5727
        this.startSide = startSide;
5728
        this.endSide = endSide;
5729
        this.widget = widget;
5730
        this.spec = spec;
5731
    }
5732
    /**
5733
    @internal
5734
    */
5735
    get heightRelevant() { return false; }
5736
    /**
5737
    Create a mark decoration, which influences the styling of the
5738
    content in its range. Nested mark decorations will cause nested
5739
    DOM elements to be created. Nesting order is determined by
5740
    precedence of the [facet](https://codemirror.net/6/docs/ref/#view.EditorView^decorations), with
5741
    the higher-precedence decorations creating the inner DOM nodes.
5742
    Such elements are split on line boundaries and on the boundaries
5743
    of lower-precedence decorations.
5744
    */
5745
    static mark(spec) {
5746
        return new MarkDecoration(spec);
5747
    }
5748
    /**
5749
    Create a widget decoration, which displays a DOM element at the
5750
    given position.
5751
    */
5752
    static widget(spec) {
5753
        let side = Math.max(-10000, Math.min(10000, spec.side || 0)), block = !!spec.block;
5754
        side += (block && !spec.inlineOrder)
5755
            ? (side > 0 ? 300000000 /* Side.BlockAfter */ : -400000000 /* Side.BlockBefore */)
5756
            : (side > 0 ? 100000000 /* Side.InlineAfter */ : -100000000 /* Side.InlineBefore */);
5757
        return new PointDecoration(spec, side, side, block, spec.widget || null, false);
5758
    }
5759
    /**
5760
    Create a replace decoration which replaces the given range with
5761
    a widget, or simply hides it.
5762
    */
5763
    static replace(spec) {
5764
        let block = !!spec.block, startSide, endSide;
5765
        if (spec.isBlockGap) {
5766
            startSide = -500000000 /* Side.GapStart */;
5767
            endSide = 400000000 /* Side.GapEnd */;
5768
        }
5769
        else {
5770
            let { start, end } = getInclusive(spec, block);
5771
            startSide = (start ? (block ? -300000000 /* Side.BlockIncStart */ : -1 /* Side.InlineIncStart */) : 500000000 /* Side.NonIncStart */) - 1;
5772
            endSide = (end ? (block ? 200000000 /* Side.BlockIncEnd */ : 1 /* Side.InlineIncEnd */) : -600000000 /* Side.NonIncEnd */) + 1;
5773
        }
5774
        return new PointDecoration(spec, startSide, endSide, block, spec.widget || null, true);
5775
    }
5776
    /**
5777
    Create a line decoration, which can add DOM attributes to the
5778
    line starting at the given position.
5779
    */
5780
    static line(spec) {
5781
        return new LineDecoration(spec);
5782
    }
5783
    /**
5784
    Build a [`DecorationSet`](https://codemirror.net/6/docs/ref/#view.DecorationSet) from the given
5785
    decorated range or ranges. If the ranges aren't already sorted,
5786
    pass `true` for `sort` to make the library sort them for you.
5787
    */
5788
    static set(of, sort = false) {
5789
        return RangeSet.of(of, sort);
5790
    }
5791
    /**
5792
    @internal
5793
    */
5794
    hasHeight() { return this.widget ? this.widget.estimatedHeight > -1 : false; }
5795
}
5796
/**
5797
The empty set of decorations.
5798
*/
5799
Decoration.none = RangeSet.empty;
5800
class MarkDecoration extends Decoration {
5801
    constructor(spec) {
5802
        let { start, end } = getInclusive(spec);
5803
        super(start ? -1 /* Side.InlineIncStart */ : 500000000 /* Side.NonIncStart */, end ? 1 /* Side.InlineIncEnd */ : -600000000 /* Side.NonIncEnd */, null, spec);
5804
        this.tagName = spec.tagName || "span";
5805
        this.class = spec.class || "";
5806
        this.attrs = spec.attributes || null;
5807
    }
5808
    eq(other) {
5809
        var _a, _b;
5810
        return this == other ||
5811
            other instanceof MarkDecoration &&
5812
                this.tagName == other.tagName &&
5813
                (this.class || ((_a = this.attrs) === null || _a === void 0 ? void 0 : _a.class)) == (other.class || ((_b = other.attrs) === null || _b === void 0 ? void 0 : _b.class)) &&
5814
                attrsEq(this.attrs, other.attrs, "class");
5815
    }
5816
    range(from, to = from) {
5817
        if (from >= to)
5818
            throw new RangeError("Mark decorations may not be empty");
5819
        return super.range(from, to);
5820
    }
5821
}
5822
MarkDecoration.prototype.point = false;
5823
class LineDecoration extends Decoration {
5824
    constructor(spec) {
5825
        super(-200000000 /* Side.Line */, -200000000 /* Side.Line */, null, spec);
5826
    }
5827
    eq(other) {
5828
        return other instanceof LineDecoration &&
5829
            this.spec.class == other.spec.class &&
5830
            attrsEq(this.spec.attributes, other.spec.attributes);
5831
    }
5832
    range(from, to = from) {
5833
        if (to != from)
5834
            throw new RangeError("Line decoration ranges must be zero-length");
5835
        return super.range(from, to);
5836
    }
5837
}
5838
LineDecoration.prototype.mapMode = MapMode.TrackBefore;
5839
LineDecoration.prototype.point = true;
5840
class PointDecoration extends Decoration {
5841
    constructor(spec, startSide, endSide, block, widget, isReplace) {
5842
        super(startSide, endSide, widget, spec);
5843
        this.block = block;
5844
        this.isReplace = isReplace;
5845
        this.mapMode = !block ? MapMode.TrackDel : startSide <= 0 ? MapMode.TrackBefore : MapMode.TrackAfter;
5846
    }
5847
    // Only relevant when this.block == true
5848
    get type() {
5849
        return this.startSide != this.endSide ? BlockType.WidgetRange
5850
            : this.startSide <= 0 ? BlockType.WidgetBefore : BlockType.WidgetAfter;
5851
    }
5852
    get heightRelevant() {
5853
        return this.block || !!this.widget && (this.widget.estimatedHeight >= 5 || this.widget.lineBreaks > 0);
5854
    }
5855
    eq(other) {
5856
        return other instanceof PointDecoration &&
5857
            widgetsEq(this.widget, other.widget) &&
5858
            this.block == other.block &&
5859
            this.startSide == other.startSide && this.endSide == other.endSide;
5860
    }
5861
    range(from, to = from) {
5862
        if (this.isReplace && (from > to || (from == to && this.startSide > 0 && this.endSide <= 0)))
5863
            throw new RangeError("Invalid range for replacement decoration");
5864
        if (!this.isReplace && to != from)
5865
            throw new RangeError("Widget decorations can only have zero-length ranges");
5866
        return super.range(from, to);
5867
    }
5868
}
5869
PointDecoration.prototype.point = true;
5870
function getInclusive(spec, block = false) {
5871
    let { inclusiveStart: start, inclusiveEnd: end } = spec;
5872
    if (start == null)
5873
        start = spec.inclusive;
5874
    if (end == null)
5875
        end = spec.inclusive;
5876
    return { start: start !== null && start !== void 0 ? start : block, end: end !== null && end !== void 0 ? end : block };
5877
}
5878
function widgetsEq(a, b) {
5879
    return a == b || !!(a && b && a.compare(b));
5880
}
5881
function addRange(from, to, ranges, margin = 0) {
5882
    let last = ranges.length - 1;
5883
    if (last >= 0 && ranges[last] + margin >= from)
5884
        ranges[last] = Math.max(ranges[last], to);
5885
    else
5886
        ranges.push(from, to);
5887
}
5888
 
5889
class ContentBuilder {
5890
    constructor(doc, pos, end, disallowBlockEffectsFor) {
5891
        this.doc = doc;
5892
        this.pos = pos;
5893
        this.end = end;
5894
        this.disallowBlockEffectsFor = disallowBlockEffectsFor;
5895
        this.content = [];
5896
        this.curLine = null;
5897
        this.breakAtStart = 0;
5898
        this.pendingBuffer = 0 /* Buf.No */;
5899
        this.bufferMarks = [];
5900
        // Set to false directly after a widget that covers the position after it
5901
        this.atCursorPos = true;
5902
        this.openStart = -1;
5903
        this.openEnd = -1;
5904
        this.text = "";
5905
        this.textOff = 0;
5906
        this.cursor = doc.iter();
5907
        this.skip = pos;
5908
    }
5909
    posCovered() {
5910
        if (this.content.length == 0)
5911
            return !this.breakAtStart && this.doc.lineAt(this.pos).from != this.pos;
5912
        let last = this.content[this.content.length - 1];
5913
        return !(last.breakAfter || last instanceof BlockWidgetView && last.deco.endSide < 0);
5914
    }
5915
    getLine() {
5916
        if (!this.curLine) {
5917
            this.content.push(this.curLine = new LineView);
5918
            this.atCursorPos = true;
5919
        }
5920
        return this.curLine;
5921
    }
5922
    flushBuffer(active = this.bufferMarks) {
5923
        if (this.pendingBuffer) {
5924
            this.curLine.append(wrapMarks(new WidgetBufferView(-1), active), active.length);
5925
            this.pendingBuffer = 0 /* Buf.No */;
5926
        }
5927
    }
5928
    addBlockWidget(view) {
5929
        this.flushBuffer();
5930
        this.curLine = null;
5931
        this.content.push(view);
5932
    }
5933
    finish(openEnd) {
5934
        if (this.pendingBuffer && openEnd <= this.bufferMarks.length)
5935
            this.flushBuffer();
5936
        else
5937
            this.pendingBuffer = 0 /* Buf.No */;
5938
        if (!this.posCovered() &&
5939
            !(openEnd && this.content.length && this.content[this.content.length - 1] instanceof BlockWidgetView))
5940
            this.getLine();
5941
    }
5942
    buildText(length, active, openStart) {
5943
        while (length > 0) {
5944
            if (this.textOff == this.text.length) {
5945
                let { value, lineBreak, done } = this.cursor.next(this.skip);
5946
                this.skip = 0;
5947
                if (done)
5948
                    throw new Error("Ran out of text content when drawing inline views");
5949
                if (lineBreak) {
5950
                    if (!this.posCovered())
5951
                        this.getLine();
5952
                    if (this.content.length)
5953
                        this.content[this.content.length - 1].breakAfter = 1;
5954
                    else
5955
                        this.breakAtStart = 1;
5956
                    this.flushBuffer();
5957
                    this.curLine = null;
5958
                    this.atCursorPos = true;
5959
                    length--;
5960
                    continue;
5961
                }
5962
                else {
5963
                    this.text = value;
5964
                    this.textOff = 0;
5965
                }
5966
            }
5967
            let take = Math.min(this.text.length - this.textOff, length, 512 /* T.Chunk */);
5968
            this.flushBuffer(active.slice(active.length - openStart));
5969
            this.getLine().append(wrapMarks(new TextView(this.text.slice(this.textOff, this.textOff + take)), active), openStart);
5970
            this.atCursorPos = true;
5971
            this.textOff += take;
5972
            length -= take;
5973
            openStart = 0;
5974
        }
5975
    }
5976
    span(from, to, active, openStart) {
5977
        this.buildText(to - from, active, openStart);
5978
        this.pos = to;
5979
        if (this.openStart < 0)
5980
            this.openStart = openStart;
5981
    }
5982
    point(from, to, deco, active, openStart, index) {
5983
        if (this.disallowBlockEffectsFor[index] && deco instanceof PointDecoration) {
5984
            if (deco.block)
5985
                throw new RangeError("Block decorations may not be specified via plugins");
5986
            if (to > this.doc.lineAt(this.pos).to)
5987
                throw new RangeError("Decorations that replace line breaks may not be specified via plugins");
5988
        }
5989
        let len = to - from;
5990
        if (deco instanceof PointDecoration) {
5991
            if (deco.block) {
5992
                if (deco.startSide > 0 && !this.posCovered())
5993
                    this.getLine();
5994
                this.addBlockWidget(new BlockWidgetView(deco.widget || NullWidget.block, len, deco));
5995
            }
5996
            else {
5997
                let view = WidgetView.create(deco.widget || NullWidget.inline, len, len ? 0 : deco.startSide);
5998
                let cursorBefore = this.atCursorPos && !view.isEditable && openStart <= active.length &&
5999
                    (from < to || deco.startSide > 0);
6000
                let cursorAfter = !view.isEditable && (from < to || openStart > active.length || deco.startSide <= 0);
6001
                let line = this.getLine();
6002
                if (this.pendingBuffer == 2 /* Buf.IfCursor */ && !cursorBefore && !view.isEditable)
6003
                    this.pendingBuffer = 0 /* Buf.No */;
6004
                this.flushBuffer(active);
6005
                if (cursorBefore) {
6006
                    line.append(wrapMarks(new WidgetBufferView(1), active), openStart);
6007
                    openStart = active.length + Math.max(0, openStart - active.length);
6008
                }
6009
                line.append(wrapMarks(view, active), openStart);
6010
                this.atCursorPos = cursorAfter;
6011
                this.pendingBuffer = !cursorAfter ? 0 /* Buf.No */ : from < to || openStart > active.length ? 1 /* Buf.Yes */ : 2 /* Buf.IfCursor */;
6012
                if (this.pendingBuffer)
6013
                    this.bufferMarks = active.slice();
6014
            }
6015
        }
6016
        else if (this.doc.lineAt(this.pos).from == this.pos) { // Line decoration
6017
            this.getLine().addLineDeco(deco);
6018
        }
6019
        if (len) {
6020
            // Advance the iterator past the replaced content
6021
            if (this.textOff + len <= this.text.length) {
6022
                this.textOff += len;
6023
            }
6024
            else {
6025
                this.skip += len - (this.text.length - this.textOff);
6026
                this.text = "";
6027
                this.textOff = 0;
6028
            }
6029
            this.pos = to;
6030
        }
6031
        if (this.openStart < 0)
6032
            this.openStart = openStart;
6033
    }
6034
    static build(text, from, to, decorations, dynamicDecorationMap) {
6035
        let builder = new ContentBuilder(text, from, to, dynamicDecorationMap);
6036
        builder.openEnd = RangeSet.spans(decorations, from, to, builder);
6037
        if (builder.openStart < 0)
6038
            builder.openStart = builder.openEnd;
6039
        builder.finish(builder.openEnd);
6040
        return builder;
6041
    }
6042
}
6043
function wrapMarks(view, active) {
6044
    for (let mark of active)
6045
        view = new MarkView(mark, [view], view.length);
6046
    return view;
6047
}
6048
class NullWidget extends WidgetType {
6049
    constructor(tag) {
6050
        super();
6051
        this.tag = tag;
6052
    }
6053
    eq(other) { return other.tag == this.tag; }
6054
    toDOM() { return document.createElement(this.tag); }
6055
    updateDOM(elt) { return elt.nodeName.toLowerCase() == this.tag; }
6056
    get isHidden() { return true; }
6057
}
6058
NullWidget.inline = /*@__PURE__*/new NullWidget("span");
6059
NullWidget.block = /*@__PURE__*/new NullWidget("div");
6060
 
6061
/**
6062
Used to indicate [text direction](https://codemirror.net/6/docs/ref/#view.EditorView.textDirection).
6063
*/
6064
var Direction = /*@__PURE__*/(function (Direction) {
6065
    // (These are chosen to match the base levels, in bidi algorithm
6066
    // terms, of spans in that direction.)
6067
    /**
6068
    Left-to-right.
6069
    */
6070
    Direction[Direction["LTR"] = 0] = "LTR";
6071
    /**
6072
    Right-to-left.
6073
    */
6074
    Direction[Direction["RTL"] = 1] = "RTL";
6075
return Direction})(Direction || (Direction = {}));
6076
const LTR = Direction.LTR, RTL = Direction.RTL;
6077
// Decode a string with each type encoded as log2(type)
6078
function dec(str) {
6079
    let result = [];
6080
    for (let i = 0; i < str.length; i++)
6081
        result.push(1 << +str[i]);
6082
    return result;
6083
}
6084
// Character types for codepoints 0 to 0xf8
6085
const LowTypes = /*@__PURE__*/dec("88888888888888888888888888888888888666888888787833333333337888888000000000000000000000000008888880000000000000000000000000088888888888888888888888888888888888887866668888088888663380888308888800000000000000000000000800000000000000000000000000000008");
6086
// Character types for codepoints 0x600 to 0x6f9
6087
const ArabicTypes = /*@__PURE__*/dec("4444448826627288999999999992222222222222222222222222222222222222222222222229999999999999999999994444444444644222822222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222999999949999999229989999223333333333");
6088
const Brackets = /*@__PURE__*/Object.create(null), BracketStack = [];
6089
// There's a lot more in
6090
// https://www.unicode.org/Public/UCD/latest/ucd/BidiBrackets.txt,
6091
// which are left out to keep code size down.
6092
for (let p of ["()", "[]", "{}"]) {
6093
    let l = /*@__PURE__*/p.charCodeAt(0), r = /*@__PURE__*/p.charCodeAt(1);
6094
    Brackets[l] = r;
6095
    Brackets[r] = -l;
6096
}
6097
function charType(ch) {
6098
    return ch <= 0xf7 ? LowTypes[ch] :
6099
        0x590 <= ch && ch <= 0x5f4 ? 2 /* T.R */ :
6100
            0x600 <= ch && ch <= 0x6f9 ? ArabicTypes[ch - 0x600] :
6101
                0x6ee <= ch && ch <= 0x8ac ? 4 /* T.AL */ :
6102
                    0x2000 <= ch && ch <= 0x200c ? 256 /* T.NI */ :
6103
                        0xfb50 <= ch && ch <= 0xfdff ? 4 /* T.AL */ : 1 /* T.L */;
6104
}
6105
const BidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac\ufb50-\ufdff]/;
6106
/**
6107
Represents a contiguous range of text that has a single direction
6108
(as in left-to-right or right-to-left).
6109
*/
6110
class BidiSpan {
6111
    /**
6112
    The direction of this span.
6113
    */
6114
    get dir() { return this.level % 2 ? RTL : LTR; }
6115
    /**
6116
    @internal
6117
    */
6118
    constructor(
6119
    /**
6120
    The start of the span (relative to the start of the line).
6121
    */
6122
    from,
6123
    /**
6124
    The end of the span.
6125
    */
6126
    to,
6127
    /**
6128
    The ["bidi
6129
    level"](https://unicode.org/reports/tr9/#Basic_Display_Algorithm)
6130
    of the span (in this context, 0 means
6131
    left-to-right, 1 means right-to-left, 2 means left-to-right
6132
    number inside right-to-left text).
6133
    */
6134
    level) {
6135
        this.from = from;
6136
        this.to = to;
6137
        this.level = level;
6138
    }
6139
    /**
6140
    @internal
6141
    */
6142
    side(end, dir) { return (this.dir == dir) == end ? this.to : this.from; }
6143
    /**
6144
    @internal
6145
    */
6146
    forward(forward, dir) { return forward == (this.dir == dir); }
6147
    /**
6148
    @internal
6149
    */
6150
    static find(order, index, level, assoc) {
6151
        let maybe = -1;
6152
        for (let i = 0; i < order.length; i++) {
6153
            let span = order[i];
6154
            if (span.from <= index && span.to >= index) {
6155
                if (span.level == level)
6156
                    return i;
6157
                // When multiple spans match, if assoc != 0, take the one that
6158
                // covers that side, otherwise take the one with the minimum
6159
                // level.
6160
                if (maybe < 0 || (assoc != 0 ? (assoc < 0 ? span.from < index : span.to > index) : order[maybe].level > span.level))
6161
                    maybe = i;
6162
            }
6163
        }
6164
        if (maybe < 0)
6165
            throw new RangeError("Index out of range");
6166
        return maybe;
6167
    }
6168
}
6169
function isolatesEq(a, b) {
6170
    if (a.length != b.length)
6171
        return false;
6172
    for (let i = 0; i < a.length; i++) {
6173
        let iA = a[i], iB = b[i];
6174
        if (iA.from != iB.from || iA.to != iB.to || iA.direction != iB.direction || !isolatesEq(iA.inner, iB.inner))
6175
            return false;
6176
    }
6177
    return true;
6178
}
6179
// Reused array of character types
6180
const types = [];
6181
// Fill in the character types (in `types`) from `from` to `to` and
6182
// apply W normalization rules.
6183
function computeCharTypes(line, rFrom, rTo, isolates, outerType) {
6184
    for (let iI = 0; iI <= isolates.length; iI++) {
6185
        let from = iI ? isolates[iI - 1].to : rFrom, to = iI < isolates.length ? isolates[iI].from : rTo;
6186
        let prevType = iI ? 256 /* T.NI */ : outerType;
6187
        // W1. Examine each non-spacing mark (NSM) in the level run, and
6188
        // change the type of the NSM to the type of the previous
6189
        // character. If the NSM is at the start of the level run, it will
6190
        // get the type of sor.
6191
        // W2. Search backwards from each instance of a European number
6192
        // until the first strong type (R, L, AL, or sor) is found. If an
6193
        // AL is found, change the type of the European number to Arabic
6194
        // number.
6195
        // W3. Change all ALs to R.
6196
        // (Left after this: L, R, EN, AN, ET, CS, NI)
6197
        for (let i = from, prev = prevType, prevStrong = prevType; i < to; i++) {
6198
            let type = charType(line.charCodeAt(i));
6199
            if (type == 512 /* T.NSM */)
6200
                type = prev;
6201
            else if (type == 8 /* T.EN */ && prevStrong == 4 /* T.AL */)
6202
                type = 16 /* T.AN */;
6203
            types[i] = type == 4 /* T.AL */ ? 2 /* T.R */ : type;
6204
            if (type & 7 /* T.Strong */)
6205
                prevStrong = type;
6206
            prev = type;
6207
        }
6208
        // W5. A sequence of European terminators adjacent to European
6209
        // numbers changes to all European numbers.
6210
        // W6. Otherwise, separators and terminators change to Other
6211
        // Neutral.
6212
        // W7. Search backwards from each instance of a European number
6213
        // until the first strong type (R, L, or sor) is found. If an L is
6214
        // found, then change the type of the European number to L.
6215
        // (Left after this: L, R, EN+AN, NI)
6216
        for (let i = from, prev = prevType, prevStrong = prevType; i < to; i++) {
6217
            let type = types[i];
6218
            if (type == 128 /* T.CS */) {
6219
                if (i < to - 1 && prev == types[i + 1] && (prev & 24 /* T.Num */))
6220
                    type = types[i] = prev;
6221
                else
6222
                    types[i] = 256 /* T.NI */;
6223
            }
6224
            else if (type == 64 /* T.ET */) {
6225
                let end = i + 1;
6226
                while (end < to && types[end] == 64 /* T.ET */)
6227
                    end++;
6228
                let replace = (i && prev == 8 /* T.EN */) || (end < rTo && types[end] == 8 /* T.EN */) ? (prevStrong == 1 /* T.L */ ? 1 /* T.L */ : 8 /* T.EN */) : 256 /* T.NI */;
6229
                for (let j = i; j < end; j++)
6230
                    types[j] = replace;
6231
                i = end - 1;
6232
            }
6233
            else if (type == 8 /* T.EN */ && prevStrong == 1 /* T.L */) {
6234
                types[i] = 1 /* T.L */;
6235
            }
6236
            prev = type;
6237
            if (type & 7 /* T.Strong */)
6238
                prevStrong = type;
6239
        }
6240
    }
6241
}
6242
// Process brackets throughout a run sequence.
6243
function processBracketPairs(line, rFrom, rTo, isolates, outerType) {
6244
    let oppositeType = outerType == 1 /* T.L */ ? 2 /* T.R */ : 1 /* T.L */;
6245
    for (let iI = 0, sI = 0, context = 0; iI <= isolates.length; iI++) {
6246
        let from = iI ? isolates[iI - 1].to : rFrom, to = iI < isolates.length ? isolates[iI].from : rTo;
6247
        // N0. Process bracket pairs in an isolating run sequence
6248
        // sequentially in the logical order of the text positions of the
6249
        // opening paired brackets using the logic given below. Within this
6250
        // scope, bidirectional types EN and AN are treated as R.
6251
        for (let i = from, ch, br, type; i < to; i++) {
6252
            // Keeps [startIndex, type, strongSeen] triples for each open
6253
            // bracket on BracketStack.
6254
            if (br = Brackets[ch = line.charCodeAt(i)]) {
6255
                if (br < 0) { // Closing bracket
6256
                    for (let sJ = sI - 3; sJ >= 0; sJ -= 3) {
6257
                        if (BracketStack[sJ + 1] == -br) {
6258
                            let flags = BracketStack[sJ + 2];
6259
                            let type = (flags & 2 /* Bracketed.EmbedInside */) ? outerType :
6260
                                !(flags & 4 /* Bracketed.OppositeInside */) ? 0 :
6261
                                    (flags & 1 /* Bracketed.OppositeBefore */) ? oppositeType : outerType;
6262
                            if (type)
6263
                                types[i] = types[BracketStack[sJ]] = type;
6264
                            sI = sJ;
6265
                            break;
6266
                        }
6267
                    }
6268
                }
6269
                else if (BracketStack.length == 189 /* Bracketed.MaxDepth */) {
6270
                    break;
6271
                }
6272
                else {
6273
                    BracketStack[sI++] = i;
6274
                    BracketStack[sI++] = ch;
6275
                    BracketStack[sI++] = context;
6276
                }
6277
            }
6278
            else if ((type = types[i]) == 2 /* T.R */ || type == 1 /* T.L */) {
6279
                let embed = type == outerType;
6280
                context = embed ? 0 : 1 /* Bracketed.OppositeBefore */;
6281
                for (let sJ = sI - 3; sJ >= 0; sJ -= 3) {
6282
                    let cur = BracketStack[sJ + 2];
6283
                    if (cur & 2 /* Bracketed.EmbedInside */)
6284
                        break;
6285
                    if (embed) {
6286
                        BracketStack[sJ + 2] |= 2 /* Bracketed.EmbedInside */;
6287
                    }
6288
                    else {
6289
                        if (cur & 4 /* Bracketed.OppositeInside */)
6290
                            break;
6291
                        BracketStack[sJ + 2] |= 4 /* Bracketed.OppositeInside */;
6292
                    }
6293
                }
6294
            }
6295
        }
6296
    }
6297
}
6298
function processNeutrals(rFrom, rTo, isolates, outerType) {
6299
    for (let iI = 0, prev = outerType; iI <= isolates.length; iI++) {
6300
        let from = iI ? isolates[iI - 1].to : rFrom, to = iI < isolates.length ? isolates[iI].from : rTo;
6301
        // N1. A sequence of neutrals takes the direction of the
6302
        // surrounding strong text if the text on both sides has the same
6303
        // direction. European and Arabic numbers act as if they were R in
6304
        // terms of their influence on neutrals. Start-of-level-run (sor)
6305
        // and end-of-level-run (eor) are used at level run boundaries.
6306
        // N2. Any remaining neutrals take the embedding direction.
6307
        // (Left after this: L, R, EN+AN)
6308
        for (let i = from; i < to;) {
6309
            let type = types[i];
6310
            if (type == 256 /* T.NI */) {
6311
                let end = i + 1;
6312
                for (;;) {
6313
                    if (end == to) {
6314
                        if (iI == isolates.length)
6315
                            break;
6316
                        end = isolates[iI++].to;
6317
                        to = iI < isolates.length ? isolates[iI].from : rTo;
6318
                    }
6319
                    else if (types[end] == 256 /* T.NI */) {
6320
                        end++;
6321
                    }
6322
                    else {
6323
                        break;
6324
                    }
6325
                }
6326
                let beforeL = prev == 1 /* T.L */;
6327
                let afterL = (end < rTo ? types[end] : outerType) == 1 /* T.L */;
6328
                let replace = beforeL == afterL ? (beforeL ? 1 /* T.L */ : 2 /* T.R */) : outerType;
6329
                for (let j = end, jI = iI, fromJ = jI ? isolates[jI - 1].to : rFrom; j > i;) {
6330
                    if (j == fromJ) {
6331
                        j = isolates[--jI].from;
6332
                        fromJ = jI ? isolates[jI - 1].to : rFrom;
6333
                    }
6334
                    types[--j] = replace;
6335
                }
6336
                i = end;
6337
            }
6338
            else {
6339
                prev = type;
6340
                i++;
6341
            }
6342
        }
6343
    }
6344
}
6345
// Find the contiguous ranges of character types in a given range, and
6346
// emit spans for them. Flip the order of the spans as appropriate
6347
// based on the level, and call through to compute the spans for
6348
// isolates at the proper point.
6349
function emitSpans(line, from, to, level, baseLevel, isolates, order) {
6350
    let ourType = level % 2 ? 2 /* T.R */ : 1 /* T.L */;
6351
    if ((level % 2) == (baseLevel % 2)) { // Same dir as base direction, don't flip
6352
        for (let iCh = from, iI = 0; iCh < to;) {
6353
            // Scan a section of characters in direction ourType, unless
6354
            // there's another type of char right after iCh, in which case
6355
            // we scan a section of other characters (which, if ourType ==
6356
            // T.L, may contain both T.R and T.AN chars).
6357
            let sameDir = true, isNum = false;
6358
            if (iI == isolates.length || iCh < isolates[iI].from) {
6359
                let next = types[iCh];
6360
                if (next != ourType) {
6361
                    sameDir = false;
6362
                    isNum = next == 16 /* T.AN */;
6363
                }
6364
            }
6365
            // Holds an array of isolates to pass to a recursive call if we
6366
            // must recurse (to distinguish T.AN inside an RTL section in
6367
            // LTR text), null if we can emit directly
6368
            let recurse = !sameDir && ourType == 1 /* T.L */ ? [] : null;
6369
            let localLevel = sameDir ? level : level + 1;
6370
            let iScan = iCh;
6371
            run: for (;;) {
6372
                if (iI < isolates.length && iScan == isolates[iI].from) {
6373
                    if (isNum)
6374
                        break run;
6375
                    let iso = isolates[iI];
6376
                    // Scan ahead to verify that there is another char in this dir after the isolate(s)
6377
                    if (!sameDir)
6378
                        for (let upto = iso.to, jI = iI + 1;;) {
6379
                            if (upto == to)
6380
                                break run;
6381
                            if (jI < isolates.length && isolates[jI].from == upto)
6382
                                upto = isolates[jI++].to;
6383
                            else if (types[upto] == ourType)
6384
                                break run;
6385
                            else
6386
                                break;
6387
                        }
6388
                    iI++;
6389
                    if (recurse) {
6390
                        recurse.push(iso);
6391
                    }
6392
                    else {
6393
                        if (iso.from > iCh)
6394
                            order.push(new BidiSpan(iCh, iso.from, localLevel));
6395
                        let dirSwap = (iso.direction == LTR) != !(localLevel % 2);
6396
                        computeSectionOrder(line, dirSwap ? level + 1 : level, baseLevel, iso.inner, iso.from, iso.to, order);
6397
                        iCh = iso.to;
6398
                    }
6399
                    iScan = iso.to;
6400
                }
6401
                else if (iScan == to || (sameDir ? types[iScan] != ourType : types[iScan] == ourType)) {
6402
                    break;
6403
                }
6404
                else {
6405
                    iScan++;
6406
                }
6407
            }
6408
            if (recurse)
6409
                emitSpans(line, iCh, iScan, level + 1, baseLevel, recurse, order);
6410
            else if (iCh < iScan)
6411
                order.push(new BidiSpan(iCh, iScan, localLevel));
6412
            iCh = iScan;
6413
        }
6414
    }
6415
    else {
6416
        // Iterate in reverse to flip the span order. Same code again, but
6417
        // going from the back of the section to the front
6418
        for (let iCh = to, iI = isolates.length; iCh > from;) {
6419
            let sameDir = true, isNum = false;
6420
            if (!iI || iCh > isolates[iI - 1].to) {
6421
                let next = types[iCh - 1];
6422
                if (next != ourType) {
6423
                    sameDir = false;
6424
                    isNum = next == 16 /* T.AN */;
6425
                }
6426
            }
6427
            let recurse = !sameDir && ourType == 1 /* T.L */ ? [] : null;
6428
            let localLevel = sameDir ? level : level + 1;
6429
            let iScan = iCh;
6430
            run: for (;;) {
6431
                if (iI && iScan == isolates[iI - 1].to) {
6432
                    if (isNum)
6433
                        break run;
6434
                    let iso = isolates[--iI];
6435
                    // Scan ahead to verify that there is another char in this dir after the isolate(s)
6436
                    if (!sameDir)
6437
                        for (let upto = iso.from, jI = iI;;) {
6438
                            if (upto == from)
6439
                                break run;
6440
                            if (jI && isolates[jI - 1].to == upto)
6441
                                upto = isolates[--jI].from;
6442
                            else if (types[upto - 1] == ourType)
6443
                                break run;
6444
                            else
6445
                                break;
6446
                        }
6447
                    if (recurse) {
6448
                        recurse.push(iso);
6449
                    }
6450
                    else {
6451
                        if (iso.to < iCh)
6452
                            order.push(new BidiSpan(iso.to, iCh, localLevel));
6453
                        let dirSwap = (iso.direction == LTR) != !(localLevel % 2);
6454
                        computeSectionOrder(line, dirSwap ? level + 1 : level, baseLevel, iso.inner, iso.from, iso.to, order);
6455
                        iCh = iso.from;
6456
                    }
6457
                    iScan = iso.from;
6458
                }
6459
                else if (iScan == from || (sameDir ? types[iScan - 1] != ourType : types[iScan - 1] == ourType)) {
6460
                    break;
6461
                }
6462
                else {
6463
                    iScan--;
6464
                }
6465
            }
6466
            if (recurse)
6467
                emitSpans(line, iScan, iCh, level + 1, baseLevel, recurse, order);
6468
            else if (iScan < iCh)
6469
                order.push(new BidiSpan(iScan, iCh, localLevel));
6470
            iCh = iScan;
6471
        }
6472
    }
6473
}
6474
function computeSectionOrder(line, level, baseLevel, isolates, from, to, order) {
6475
    let outerType = (level % 2 ? 2 /* T.R */ : 1 /* T.L */);
6476
    computeCharTypes(line, from, to, isolates, outerType);
6477
    processBracketPairs(line, from, to, isolates, outerType);
6478
    processNeutrals(from, to, isolates, outerType);
6479
    emitSpans(line, from, to, level, baseLevel, isolates, order);
6480
}
6481
function computeOrder(line, direction, isolates) {
6482
    if (!line)
6483
        return [new BidiSpan(0, 0, direction == RTL ? 1 : 0)];
6484
    if (direction == LTR && !isolates.length && !BidiRE.test(line))
6485
        return trivialOrder(line.length);
6486
    if (isolates.length)
6487
        while (line.length > types.length)
6488
            types[types.length] = 256 /* T.NI */; // Make sure types array has no gaps
6489
    let order = [], level = direction == LTR ? 0 : 1;
6490
    computeSectionOrder(line, level, level, isolates, 0, line.length, order);
6491
    return order;
6492
}
6493
function trivialOrder(length) {
6494
    return [new BidiSpan(0, length, 0)];
6495
}
6496
let movedOver = "";
6497
// This implementation moves strictly visually, without concern for a
6498
// traversal visiting every logical position in the string. It will
6499
// still do so for simple input, but situations like multiple isolates
6500
// with the same level next to each other, or text going against the
6501
// main dir at the end of the line, will make some positions
6502
// unreachable with this motion. Each visible cursor position will
6503
// correspond to the lower-level bidi span that touches it.
6504
//
6505
// The alternative would be to solve an order globally for a given
6506
// line, making sure that it includes every position, but that would
6507
// require associating non-canonical (higher bidi span level)
6508
// positions with a given visual position, which is likely to confuse
6509
// people. (And would generally be a lot more complicated.)
6510
function moveVisually(line, order, dir, start, forward) {
6511
    var _a;
6512
    let startIndex = start.head - line.from;
6513
    let spanI = BidiSpan.find(order, startIndex, (_a = start.bidiLevel) !== null && _a !== void 0 ? _a : -1, start.assoc);
6514
    let span = order[spanI], spanEnd = span.side(forward, dir);
6515
    // End of span
6516
    if (startIndex == spanEnd) {
6517
        let nextI = spanI += forward ? 1 : -1;
6518
        if (nextI < 0 || nextI >= order.length)
6519
            return null;
6520
        span = order[spanI = nextI];
6521
        startIndex = span.side(!forward, dir);
6522
        spanEnd = span.side(forward, dir);
6523
    }
6524
    let nextIndex = findClusterBreak(line.text, startIndex, span.forward(forward, dir));
6525
    if (nextIndex < span.from || nextIndex > span.to)
6526
        nextIndex = spanEnd;
6527
    movedOver = line.text.slice(Math.min(startIndex, nextIndex), Math.max(startIndex, nextIndex));
6528
    let nextSpan = spanI == (forward ? order.length - 1 : 0) ? null : order[spanI + (forward ? 1 : -1)];
6529
    if (nextSpan && nextIndex == spanEnd && nextSpan.level + (forward ? 0 : 1) < span.level)
6530
        return EditorSelection.cursor(nextSpan.side(!forward, dir) + line.from, nextSpan.forward(forward, dir) ? 1 : -1, nextSpan.level);
6531
    return EditorSelection.cursor(nextIndex + line.from, span.forward(forward, dir) ? -1 : 1, span.level);
6532
}
6533
function autoDirection(text, from, to) {
6534
    for (let i = from; i < to; i++) {
6535
        let type = charType(text.charCodeAt(i));
6536
        if (type == 1 /* T.L */)
6537
            return LTR;
6538
        if (type == 2 /* T.R */ || type == 4 /* T.AL */)
6539
            return RTL;
6540
    }
6541
    return LTR;
6542
}
6543
 
6544
const clickAddsSelectionRange = /*@__PURE__*/Facet.define();
6545
const dragMovesSelection$1 = /*@__PURE__*/Facet.define();
6546
const mouseSelectionStyle = /*@__PURE__*/Facet.define();
6547
const exceptionSink = /*@__PURE__*/Facet.define();
6548
const updateListener = /*@__PURE__*/Facet.define();
6549
const inputHandler$1 = /*@__PURE__*/Facet.define();
6550
const focusChangeEffect = /*@__PURE__*/Facet.define();
6551
const perLineTextDirection = /*@__PURE__*/Facet.define({
6552
    combine: values => values.some(x => x)
6553
});
6554
const nativeSelectionHidden = /*@__PURE__*/Facet.define({
6555
    combine: values => values.some(x => x)
6556
});
6557
const scrollHandler = /*@__PURE__*/Facet.define();
6558
class ScrollTarget {
6559
    constructor(range, y = "nearest", x = "nearest", yMargin = 5, xMargin = 5,
6560
    // This data structure is abused to also store precise scroll
6561
    // snapshots, instead of a `scrollIntoView` request. When this
6562
    // flag is `true`, `range` points at a position in the reference
6563
    // line, `yMargin` holds the difference between the top of that
6564
    // line and the top of the editor, and `xMargin` holds the
6565
    // editor's `scrollLeft`.
6566
    isSnapshot = false) {
6567
        this.range = range;
6568
        this.y = y;
6569
        this.x = x;
6570
        this.yMargin = yMargin;
6571
        this.xMargin = xMargin;
6572
        this.isSnapshot = isSnapshot;
6573
    }
6574
    map(changes) {
6575
        return changes.empty ? this :
6576
            new ScrollTarget(this.range.map(changes), this.y, this.x, this.yMargin, this.xMargin, this.isSnapshot);
6577
    }
6578
    clip(state) {
6579
        return this.range.to <= state.doc.length ? this :
6580
            new ScrollTarget(EditorSelection.cursor(state.doc.length), this.y, this.x, this.yMargin, this.xMargin, this.isSnapshot);
6581
    }
6582
}
6583
const scrollIntoView$1 = /*@__PURE__*/StateEffect.define({ map: (t, ch) => t.map(ch) });
6584
/**
6585
Log or report an unhandled exception in client code. Should
6586
probably only be used by extension code that allows client code to
6587
provide functions, and calls those functions in a context where an
6588
exception can't be propagated to calling code in a reasonable way
6589
(for example when in an event handler).
6590
 
6591
Either calls a handler registered with
6592
[`EditorView.exceptionSink`](https://codemirror.net/6/docs/ref/#view.EditorView^exceptionSink),
6593
`window.onerror`, if defined, or `console.error` (in which case
6594
it'll pass `context`, when given, as first argument).
6595
*/
6596
function logException(state, exception, context) {
6597
    let handler = state.facet(exceptionSink);
6598
    if (handler.length)
6599
        handler[0](exception);
6600
    else if (window.onerror)
6601
        window.onerror(String(exception), context, undefined, undefined, exception);
6602
    else if (context)
6603
        console.error(context + ":", exception);
6604
    else
6605
        console.error(exception);
6606
}
6607
const editable = /*@__PURE__*/Facet.define({ combine: values => values.length ? values[0] : true });
6608
let nextPluginID = 0;
6609
const viewPlugin = /*@__PURE__*/Facet.define();
6610
/**
6611
View plugins associate stateful values with a view. They can
6612
influence the way the content is drawn, and are notified of things
6613
that happen in the view.
6614
*/
6615
class ViewPlugin {
6616
    constructor(
6617
    /**
6618
    @internal
6619
    */
6620
    id,
6621
    /**
6622
    @internal
6623
    */
6624
    create,
6625
    /**
6626
    @internal
6627
    */
6628
    domEventHandlers,
6629
    /**
6630
    @internal
6631
    */
6632
    domEventObservers, buildExtensions) {
6633
        this.id = id;
6634
        this.create = create;
6635
        this.domEventHandlers = domEventHandlers;
6636
        this.domEventObservers = domEventObservers;
6637
        this.extension = buildExtensions(this);
6638
    }
6639
    /**
6640
    Define a plugin from a constructor function that creates the
6641
    plugin's value, given an editor view.
6642
    */
6643
    static define(create, spec) {
6644
        const { eventHandlers, eventObservers, provide, decorations: deco } = spec || {};
6645
        return new ViewPlugin(nextPluginID++, create, eventHandlers, eventObservers, plugin => {
6646
            let ext = [viewPlugin.of(plugin)];
6647
            if (deco)
6648
                ext.push(decorations.of(view => {
6649
                    let pluginInst = view.plugin(plugin);
6650
                    return pluginInst ? deco(pluginInst) : Decoration.none;
6651
                }));
6652
            if (provide)
6653
                ext.push(provide(plugin));
6654
            return ext;
6655
        });
6656
    }
6657
    /**
6658
    Create a plugin for a class whose constructor takes a single
6659
    editor view as argument.
6660
    */
6661
    static fromClass(cls, spec) {
6662
        return ViewPlugin.define(view => new cls(view), spec);
6663
    }
6664
}
6665
class PluginInstance {
6666
    constructor(spec) {
6667
        this.spec = spec;
6668
        // When starting an update, all plugins have this field set to the
6669
        // update object, indicating they need to be updated. When finished
6670
        // updating, it is set to `false`. Retrieving a plugin that needs to
6671
        // be updated with `view.plugin` forces an eager update.
6672
        this.mustUpdate = null;
6673
        // This is null when the plugin is initially created, but
6674
        // initialized on the first update.
6675
        this.value = null;
6676
    }
6677
    update(view) {
6678
        if (!this.value) {
6679
            if (this.spec) {
6680
                try {
6681
                    this.value = this.spec.create(view);
6682
                }
6683
                catch (e) {
6684
                    logException(view.state, e, "CodeMirror plugin crashed");
6685
                    this.deactivate();
6686
                }
6687
            }
6688
        }
6689
        else if (this.mustUpdate) {
6690
            let update = this.mustUpdate;
6691
            this.mustUpdate = null;
6692
            if (this.value.update) {
6693
                try {
6694
                    this.value.update(update);
6695
                }
6696
                catch (e) {
6697
                    logException(update.state, e, "CodeMirror plugin crashed");
6698
                    if (this.value.destroy)
6699
                        try {
6700
                            this.value.destroy();
6701
                        }
6702
                        catch (_) { }
6703
                    this.deactivate();
6704
                }
6705
            }
6706
        }
6707
        return this;
6708
    }
6709
    destroy(view) {
6710
        var _a;
6711
        if ((_a = this.value) === null || _a === void 0 ? void 0 : _a.destroy) {
6712
            try {
6713
                this.value.destroy();
6714
            }
6715
            catch (e) {
6716
                logException(view.state, e, "CodeMirror plugin crashed");
6717
            }
6718
        }
6719
    }
6720
    deactivate() {
6721
        this.spec = this.value = null;
6722
    }
6723
}
6724
const editorAttributes = /*@__PURE__*/Facet.define();
6725
const contentAttributes = /*@__PURE__*/Facet.define();
6726
// Provide decorations
6727
const decorations = /*@__PURE__*/Facet.define();
6728
const outerDecorations = /*@__PURE__*/Facet.define();
6729
const atomicRanges = /*@__PURE__*/Facet.define();
6730
const bidiIsolatedRanges = /*@__PURE__*/Facet.define();
6731
function getIsolatedRanges(view, line) {
6732
    let isolates = view.state.facet(bidiIsolatedRanges);
6733
    if (!isolates.length)
6734
        return isolates;
6735
    let sets = isolates.map(i => i instanceof Function ? i(view) : i);
6736
    let result = [];
6737
    RangeSet.spans(sets, line.from, line.to, {
6738
        point() { },
6739
        span(fromDoc, toDoc, active, open) {
6740
            let from = fromDoc - line.from, to = toDoc - line.from;
6741
            let level = result;
6742
            for (let i = active.length - 1; i >= 0; i--, open--) {
6743
                let direction = active[i].spec.bidiIsolate, update;
6744
                if (direction == null)
6745
                    direction = autoDirection(line.text, from, to);
6746
                if (open > 0 && level.length &&
6747
                    (update = level[level.length - 1]).to == from && update.direction == direction) {
6748
                    update.to = to;
6749
                    level = update.inner;
6750
                }
6751
                else {
6752
                    let add = { from, to, direction, inner: [] };
6753
                    level.push(add);
6754
                    level = add.inner;
6755
                }
6756
            }
6757
        }
6758
    });
6759
    return result;
6760
}
6761
const scrollMargins = /*@__PURE__*/Facet.define();
6762
function getScrollMargins(view) {
6763
    let left = 0, right = 0, top = 0, bottom = 0;
6764
    for (let source of view.state.facet(scrollMargins)) {
6765
        let m = source(view);
6766
        if (m) {
6767
            if (m.left != null)
6768
                left = Math.max(left, m.left);
6769
            if (m.right != null)
6770
                right = Math.max(right, m.right);
6771
            if (m.top != null)
6772
                top = Math.max(top, m.top);
6773
            if (m.bottom != null)
6774
                bottom = Math.max(bottom, m.bottom);
6775
        }
6776
    }
6777
    return { left, right, top, bottom };
6778
}
6779
const styleModule = /*@__PURE__*/Facet.define();
6780
class ChangedRange {
6781
    constructor(fromA, toA, fromB, toB) {
6782
        this.fromA = fromA;
6783
        this.toA = toA;
6784
        this.fromB = fromB;
6785
        this.toB = toB;
6786
    }
6787
    join(other) {
6788
        return new ChangedRange(Math.min(this.fromA, other.fromA), Math.max(this.toA, other.toA), Math.min(this.fromB, other.fromB), Math.max(this.toB, other.toB));
6789
    }
6790
    addToSet(set) {
6791
        let i = set.length, me = this;
6792
        for (; i > 0; i--) {
6793
            let range = set[i - 1];
6794
            if (range.fromA > me.toA)
6795
                continue;
6796
            if (range.toA < me.fromA)
6797
                break;
6798
            me = me.join(range);
6799
            set.splice(i - 1, 1);
6800
        }
6801
        set.splice(i, 0, me);
6802
        return set;
6803
    }
6804
    static extendWithRanges(diff, ranges) {
6805
        if (ranges.length == 0)
6806
            return diff;
6807
        let result = [];
6808
        for (let dI = 0, rI = 0, posA = 0, posB = 0;; dI++) {
6809
            let next = dI == diff.length ? null : diff[dI], off = posA - posB;
6810
            let end = next ? next.fromB : 1e9;
6811
            while (rI < ranges.length && ranges[rI] < end) {
6812
                let from = ranges[rI], to = ranges[rI + 1];
6813
                let fromB = Math.max(posB, from), toB = Math.min(end, to);
6814
                if (fromB <= toB)
6815
                    new ChangedRange(fromB + off, toB + off, fromB, toB).addToSet(result);
6816
                if (to > end)
6817
                    break;
6818
                else
6819
                    rI += 2;
6820
            }
6821
            if (!next)
6822
                return result;
6823
            new ChangedRange(next.fromA, next.toA, next.fromB, next.toB).addToSet(result);
6824
            posA = next.toA;
6825
            posB = next.toB;
6826
        }
6827
    }
6828
}
6829
/**
6830
View [plugins](https://codemirror.net/6/docs/ref/#view.ViewPlugin) are given instances of this
6831
class, which describe what happened, whenever the view is updated.
6832
*/
6833
class ViewUpdate {
6834
    constructor(
6835
    /**
6836
    The editor view that the update is associated with.
6837
    */
6838
    view,
6839
    /**
6840
    The new editor state.
6841
    */
6842
    state,
6843
    /**
6844
    The transactions involved in the update. May be empty.
6845
    */
6846
    transactions) {
6847
        this.view = view;
6848
        this.state = state;
6849
        this.transactions = transactions;
6850
        /**
6851
        @internal
6852
        */
6853
        this.flags = 0;
6854
        this.startState = view.state;
6855
        this.changes = ChangeSet.empty(this.startState.doc.length);
6856
        for (let tr of transactions)
6857
            this.changes = this.changes.compose(tr.changes);
6858
        let changedRanges = [];
6859
        this.changes.iterChangedRanges((fromA, toA, fromB, toB) => changedRanges.push(new ChangedRange(fromA, toA, fromB, toB)));
6860
        this.changedRanges = changedRanges;
6861
    }
6862
    /**
6863
    @internal
6864
    */
6865
    static create(view, state, transactions) {
6866
        return new ViewUpdate(view, state, transactions);
6867
    }
6868
    /**
6869
    Tells you whether the [viewport](https://codemirror.net/6/docs/ref/#view.EditorView.viewport) or
6870
    [visible ranges](https://codemirror.net/6/docs/ref/#view.EditorView.visibleRanges) changed in this
6871
    update.
6872
    */
6873
    get viewportChanged() {
6874
        return (this.flags & 4 /* UpdateFlag.Viewport */) > 0;
6875
    }
6876
    /**
6877
    Indicates whether the height of a block element in the editor
6878
    changed in this update.
6879
    */
6880
    get heightChanged() {
6881
        return (this.flags & 2 /* UpdateFlag.Height */) > 0;
6882
    }
6883
    /**
6884
    Returns true when the document was modified or the size of the
6885
    editor, or elements within the editor, changed.
6886
    */
6887
    get geometryChanged() {
6888
        return this.docChanged || (this.flags & (8 /* UpdateFlag.Geometry */ | 2 /* UpdateFlag.Height */)) > 0;
6889
    }
6890
    /**
6891
    True when this update indicates a focus change.
6892
    */
6893
    get focusChanged() {
6894
        return (this.flags & 1 /* UpdateFlag.Focus */) > 0;
6895
    }
6896
    /**
6897
    Whether the document changed in this update.
6898
    */
6899
    get docChanged() {
6900
        return !this.changes.empty;
6901
    }
6902
    /**
6903
    Whether the selection was explicitly set in this update.
6904
    */
6905
    get selectionSet() {
6906
        return this.transactions.some(tr => tr.selection);
6907
    }
6908
    /**
6909
    @internal
6910
    */
6911
    get empty() { return this.flags == 0 && this.transactions.length == 0; }
6912
}
6913
 
6914
class DocView extends ContentView {
6915
    get length() { return this.view.state.doc.length; }
6916
    constructor(view) {
6917
        super();
6918
        this.view = view;
6919
        this.decorations = [];
6920
        this.dynamicDecorationMap = [];
6921
        this.domChanged = null;
6922
        this.hasComposition = null;
6923
        this.markedForComposition = new Set;
6924
        this.lastCompositionAfterCursor = false;
6925
        // Track a minimum width for the editor. When measuring sizes in
6926
        // measureVisibleLineHeights, this is updated to point at the width
6927
        // of a given element and its extent in the document. When a change
6928
        // happens in that range, these are reset. That way, once we've seen
6929
        // a line/element of a given length, we keep the editor wide enough
6930
        // to fit at least that element, until it is changed, at which point
6931
        // we forget it again.
6932
        this.minWidth = 0;
6933
        this.minWidthFrom = 0;
6934
        this.minWidthTo = 0;
6935
        // Track whether the DOM selection was set in a lossy way, so that
6936
        // we don't mess it up when reading it back it
6937
        this.impreciseAnchor = null;
6938
        this.impreciseHead = null;
6939
        this.forceSelection = false;
6940
        // Used by the resize observer to ignore resizes that we caused
6941
        // ourselves
6942
        this.lastUpdate = Date.now();
6943
        this.setDOM(view.contentDOM);
6944
        this.children = [new LineView];
6945
        this.children[0].setParent(this);
6946
        this.updateDeco();
6947
        this.updateInner([new ChangedRange(0, 0, 0, view.state.doc.length)], 0, null);
6948
    }
6949
    // Update the document view to a given state.
6950
    update(update) {
6951
        var _a;
6952
        let changedRanges = update.changedRanges;
6953
        if (this.minWidth > 0 && changedRanges.length) {
6954
            if (!changedRanges.every(({ fromA, toA }) => toA < this.minWidthFrom || fromA > this.minWidthTo)) {
6955
                this.minWidth = this.minWidthFrom = this.minWidthTo = 0;
6956
            }
6957
            else {
6958
                this.minWidthFrom = update.changes.mapPos(this.minWidthFrom, 1);
6959
                this.minWidthTo = update.changes.mapPos(this.minWidthTo, 1);
6960
            }
6961
        }
6962
        let readCompositionAt = -1;
6963
        if (this.view.inputState.composing >= 0) {
6964
            if ((_a = this.domChanged) === null || _a === void 0 ? void 0 : _a.newSel)
6965
                readCompositionAt = this.domChanged.newSel.head;
6966
            else if (!touchesComposition(update.changes, this.hasComposition) && !update.selectionSet)
6967
                readCompositionAt = update.state.selection.main.head;
6968
        }
6969
        let composition = readCompositionAt > -1 ? findCompositionRange(this.view, update.changes, readCompositionAt) : null;
6970
        this.domChanged = null;
6971
        if (this.hasComposition) {
6972
            this.markedForComposition.clear();
6973
            let { from, to } = this.hasComposition;
6974
            changedRanges = new ChangedRange(from, to, update.changes.mapPos(from, -1), update.changes.mapPos(to, 1))
6975
                .addToSet(changedRanges.slice());
6976
        }
6977
        this.hasComposition = composition ? { from: composition.range.fromB, to: composition.range.toB } : null;
6978
        // When the DOM nodes around the selection are moved to another
6979
        // parent, Chrome sometimes reports a different selection through
6980
        // getSelection than the one that it actually shows to the user.
6981
        // This forces a selection update when lines are joined to work
6982
        // around that. Issue #54
6983
        if ((browser.ie || browser.chrome) && !composition && update &&
6984
            update.state.doc.lines != update.startState.doc.lines)
6985
            this.forceSelection = true;
6986
        let prevDeco = this.decorations, deco = this.updateDeco();
6987
        let decoDiff = findChangedDeco(prevDeco, deco, update.changes);
6988
        changedRanges = ChangedRange.extendWithRanges(changedRanges, decoDiff);
6989
        if (!(this.flags & 7 /* ViewFlag.Dirty */) && changedRanges.length == 0) {
6990
            return false;
6991
        }
6992
        else {
6993
            this.updateInner(changedRanges, update.startState.doc.length, composition);
6994
            if (update.transactions.length)
6995
                this.lastUpdate = Date.now();
6996
            return true;
6997
        }
6998
    }
6999
    // Used by update and the constructor do perform the actual DOM
7000
    // update
7001
    updateInner(changes, oldLength, composition) {
7002
        this.view.viewState.mustMeasureContent = true;
7003
        this.updateChildren(changes, oldLength, composition);
7004
        let { observer } = this.view;
7005
        observer.ignore(() => {
7006
            // Lock the height during redrawing, since Chrome sometimes
7007
            // messes with the scroll position during DOM mutation (though
7008
            // no relayout is triggered and I cannot imagine how it can
7009
            // recompute the scroll position without a layout)
7010
            this.dom.style.height = this.view.viewState.contentHeight / this.view.scaleY + "px";
7011
            this.dom.style.flexBasis = this.minWidth ? this.minWidth + "px" : "";
7012
            // Chrome will sometimes, when DOM mutations occur directly
7013
            // around the selection, get confused and report a different
7014
            // selection from the one it displays (issue #218). This tries
7015
            // to detect that situation.
7016
            let track = browser.chrome || browser.ios ? { node: observer.selectionRange.focusNode, written: false } : undefined;
7017
            this.sync(this.view, track);
7018
            this.flags &= ~7 /* ViewFlag.Dirty */;
7019
            if (track && (track.written || observer.selectionRange.focusNode != track.node))
7020
                this.forceSelection = true;
7021
            this.dom.style.height = "";
7022
        });
7023
        this.markedForComposition.forEach(cView => cView.flags &= ~8 /* ViewFlag.Composition */);
7024
        let gaps = [];
7025
        if (this.view.viewport.from || this.view.viewport.to < this.view.state.doc.length)
7026
            for (let child of this.children)
7027
                if (child instanceof BlockWidgetView && child.widget instanceof BlockGapWidget)
7028
                    gaps.push(child.dom);
7029
        observer.updateGaps(gaps);
7030
    }
7031
    updateChildren(changes, oldLength, composition) {
7032
        let ranges = composition ? composition.range.addToSet(changes.slice()) : changes;
7033
        let cursor = this.childCursor(oldLength);
7034
        for (let i = ranges.length - 1;; i--) {
7035
            let next = i >= 0 ? ranges[i] : null;
7036
            if (!next)
7037
                break;
7038
            let { fromA, toA, fromB, toB } = next, content, breakAtStart, openStart, openEnd;
7039
            if (composition && composition.range.fromB < toB && composition.range.toB > fromB) {
7040
                let before = ContentBuilder.build(this.view.state.doc, fromB, composition.range.fromB, this.decorations, this.dynamicDecorationMap);
7041
                let after = ContentBuilder.build(this.view.state.doc, composition.range.toB, toB, this.decorations, this.dynamicDecorationMap);
7042
                breakAtStart = before.breakAtStart;
7043
                openStart = before.openStart;
7044
                openEnd = after.openEnd;
7045
                let compLine = this.compositionView(composition);
7046
                if (after.breakAtStart) {
7047
                    compLine.breakAfter = 1;
7048
                }
7049
                else if (after.content.length &&
7050
                    compLine.merge(compLine.length, compLine.length, after.content[0], false, after.openStart, 0)) {
7051
                    compLine.breakAfter = after.content[0].breakAfter;
7052
                    after.content.shift();
7053
                }
7054
                if (before.content.length &&
7055
                    compLine.merge(0, 0, before.content[before.content.length - 1], true, 0, before.openEnd)) {
7056
                    before.content.pop();
7057
                }
7058
                content = before.content.concat(compLine).concat(after.content);
7059
            }
7060
            else {
7061
                ({ content, breakAtStart, openStart, openEnd } =
7062
                    ContentBuilder.build(this.view.state.doc, fromB, toB, this.decorations, this.dynamicDecorationMap));
7063
            }
7064
            let { i: toI, off: toOff } = cursor.findPos(toA, 1);
7065
            let { i: fromI, off: fromOff } = cursor.findPos(fromA, -1);
7066
            replaceRange(this, fromI, fromOff, toI, toOff, content, breakAtStart, openStart, openEnd);
7067
        }
7068
        if (composition)
7069
            this.fixCompositionDOM(composition);
7070
    }
7071
    compositionView(composition) {
7072
        let cur = new TextView(composition.text.nodeValue);
7073
        cur.flags |= 8 /* ViewFlag.Composition */;
7074
        for (let { deco } of composition.marks)
7075
            cur = new MarkView(deco, [cur], cur.length);
7076
        let line = new LineView;
7077
        line.append(cur, 0);
7078
        return line;
7079
    }
7080
    fixCompositionDOM(composition) {
7081
        let fix = (dom, cView) => {
7082
            cView.flags |= 8 /* ViewFlag.Composition */ | (cView.children.some(c => c.flags & 7 /* ViewFlag.Dirty */) ? 1 /* ViewFlag.ChildDirty */ : 0);
7083
            this.markedForComposition.add(cView);
7084
            let prev = ContentView.get(dom);
7085
            if (prev && prev != cView)
7086
                prev.dom = null;
7087
            cView.setDOM(dom);
7088
        };
7089
        let pos = this.childPos(composition.range.fromB, 1);
7090
        let cView = this.children[pos.i];
7091
        fix(composition.line, cView);
7092
        for (let i = composition.marks.length - 1; i >= -1; i--) {
7093
            pos = cView.childPos(pos.off, 1);
7094
            cView = cView.children[pos.i];
7095
            fix(i >= 0 ? composition.marks[i].node : composition.text, cView);
7096
        }
7097
    }
7098
    // Sync the DOM selection to this.state.selection
7099
    updateSelection(mustRead = false, fromPointer = false) {
7100
        if (mustRead || !this.view.observer.selectionRange.focusNode)
7101
            this.view.observer.readSelectionRange();
7102
        let activeElt = this.view.root.activeElement, focused = activeElt == this.dom;
7103
        let selectionNotFocus = !focused &&
7104
            hasSelection(this.dom, this.view.observer.selectionRange) && !(activeElt && this.dom.contains(activeElt));
7105
        if (!(focused || fromPointer || selectionNotFocus))
7106
            return;
7107
        let force = this.forceSelection;
7108
        this.forceSelection = false;
7109
        let main = this.view.state.selection.main;
7110
        let anchor = this.moveToLine(this.domAtPos(main.anchor));
7111
        let head = main.empty ? anchor : this.moveToLine(this.domAtPos(main.head));
7112
        // Always reset on Firefox when next to an uneditable node to
7113
        // avoid invisible cursor bugs (#111)
7114
        if (browser.gecko && main.empty && !this.hasComposition && betweenUneditable(anchor)) {
7115
            let dummy = document.createTextNode("");
7116
            this.view.observer.ignore(() => anchor.node.insertBefore(dummy, anchor.node.childNodes[anchor.offset] || null));
7117
            anchor = head = new DOMPos(dummy, 0);
7118
            force = true;
7119
        }
7120
        let domSel = this.view.observer.selectionRange;
7121
        // If the selection is already here, or in an equivalent position, don't touch it
7122
        if (force || !domSel.focusNode || (!isEquivalentPosition(anchor.node, anchor.offset, domSel.anchorNode, domSel.anchorOffset) ||
7123
            !isEquivalentPosition(head.node, head.offset, domSel.focusNode, domSel.focusOffset)) && !this.suppressWidgetCursorChange(domSel, main)) {
7124
            this.view.observer.ignore(() => {
7125
                // Chrome Android will hide the virtual keyboard when tapping
7126
                // inside an uneditable node, and not bring it back when we
7127
                // move the cursor to its proper position. This tries to
7128
                // restore the keyboard by cycling focus.
7129
                if (browser.android && browser.chrome && this.dom.contains(domSel.focusNode) &&
7130
                    inUneditable(domSel.focusNode, this.dom)) {
7131
                    this.dom.blur();
7132
                    this.dom.focus({ preventScroll: true });
7133
                }
7134
                let rawSel = getSelection(this.view.root);
7135
                if (!rawSel) ;
7136
                else if (main.empty) {
7137
                    // Work around https://bugzilla.mozilla.org/show_bug.cgi?id=1612076
7138
                    if (browser.gecko) {
7139
                        let nextTo = nextToUneditable(anchor.node, anchor.offset);
7140
                        if (nextTo && nextTo != (1 /* NextTo.Before */ | 2 /* NextTo.After */)) {
7141
                            let text = (nextTo == 1 /* NextTo.Before */ ? textNodeBefore : textNodeAfter)(anchor.node, anchor.offset);
7142
                            if (text)
7143
                                anchor = new DOMPos(text.node, text.offset);
7144
                        }
7145
                    }
7146
                    rawSel.collapse(anchor.node, anchor.offset);
7147
                    if (main.bidiLevel != null && rawSel.caretBidiLevel !== undefined)
7148
                        rawSel.caretBidiLevel = main.bidiLevel;
7149
                }
7150
                else if (rawSel.extend) {
7151
                    // Selection.extend can be used to create an 'inverted' selection
7152
                    // (one where the focus is before the anchor), but not all
7153
                    // browsers support it yet.
7154
                    rawSel.collapse(anchor.node, anchor.offset);
7155
                    // Safari will ignore the call above when the editor is
7156
                    // hidden, and then raise an error on the call to extend
7157
                    // (#940).
7158
                    try {
7159
                        rawSel.extend(head.node, head.offset);
7160
                    }
7161
                    catch (_) { }
7162
                }
7163
                else {
7164
                    // Primitive (IE) way
7165
                    let range = document.createRange();
7166
                    if (main.anchor > main.head)
7167
                        [anchor, head] = [head, anchor];
7168
                    range.setEnd(head.node, head.offset);
7169
                    range.setStart(anchor.node, anchor.offset);
7170
                    rawSel.removeAllRanges();
7171
                    rawSel.addRange(range);
7172
                }
7173
                if (selectionNotFocus && this.view.root.activeElement == this.dom) {
7174
                    this.dom.blur();
7175
                    if (activeElt)
7176
                        activeElt.focus();
7177
                }
7178
            });
7179
            this.view.observer.setSelectionRange(anchor, head);
7180
        }
7181
        this.impreciseAnchor = anchor.precise ? null : new DOMPos(domSel.anchorNode, domSel.anchorOffset);
7182
        this.impreciseHead = head.precise ? null : new DOMPos(domSel.focusNode, domSel.focusOffset);
7183
    }
7184
    // If a zero-length widget is inserted next to the cursor during
7185
    // composition, avoid moving it across it and disrupting the
7186
    // composition.
7187
    suppressWidgetCursorChange(sel, cursor) {
7188
        return this.hasComposition && cursor.empty &&
7189
            isEquivalentPosition(sel.focusNode, sel.focusOffset, sel.anchorNode, sel.anchorOffset) &&
7190
            this.posFromDOM(sel.focusNode, sel.focusOffset) == cursor.head;
7191
    }
7192
    enforceCursorAssoc() {
7193
        if (this.hasComposition)
7194
            return;
7195
        let { view } = this, cursor = view.state.selection.main;
7196
        let sel = getSelection(view.root);
7197
        let { anchorNode, anchorOffset } = view.observer.selectionRange;
7198
        if (!sel || !cursor.empty || !cursor.assoc || !sel.modify)
7199
            return;
7200
        let line = LineView.find(this, cursor.head);
7201
        if (!line)
7202
            return;
7203
        let lineStart = line.posAtStart;
7204
        if (cursor.head == lineStart || cursor.head == lineStart + line.length)
7205
            return;
7206
        let before = this.coordsAt(cursor.head, -1), after = this.coordsAt(cursor.head, 1);
7207
        if (!before || !after || before.bottom > after.top)
7208
            return;
7209
        let dom = this.domAtPos(cursor.head + cursor.assoc);
7210
        sel.collapse(dom.node, dom.offset);
7211
        sel.modify("move", cursor.assoc < 0 ? "forward" : "backward", "lineboundary");
7212
        // This can go wrong in corner cases like single-character lines,
7213
        // so check and reset if necessary.
7214
        view.observer.readSelectionRange();
7215
        let newRange = view.observer.selectionRange;
7216
        if (view.docView.posFromDOM(newRange.anchorNode, newRange.anchorOffset) != cursor.from)
7217
            sel.collapse(anchorNode, anchorOffset);
7218
    }
7219
    // If a position is in/near a block widget, move it to a nearby text
7220
    // line, since we don't want the cursor inside a block widget.
7221
    moveToLine(pos) {
7222
        // Block widgets will return positions before/after them, which
7223
        // are thus directly in the document DOM element.
7224
        let dom = this.dom, newPos;
7225
        if (pos.node != dom)
7226
            return pos;
7227
        for (let i = pos.offset; !newPos && i < dom.childNodes.length; i++) {
7228
            let view = ContentView.get(dom.childNodes[i]);
7229
            if (view instanceof LineView)
7230
                newPos = view.domAtPos(0);
7231
        }
7232
        for (let i = pos.offset - 1; !newPos && i >= 0; i--) {
7233
            let view = ContentView.get(dom.childNodes[i]);
7234
            if (view instanceof LineView)
7235
                newPos = view.domAtPos(view.length);
7236
        }
7237
        return newPos ? new DOMPos(newPos.node, newPos.offset, true) : pos;
7238
    }
7239
    nearest(dom) {
7240
        for (let cur = dom; cur;) {
7241
            let domView = ContentView.get(cur);
7242
            if (domView && domView.rootView == this)
7243
                return domView;
7244
            cur = cur.parentNode;
7245
        }
7246
        return null;
7247
    }
7248
    posFromDOM(node, offset) {
7249
        let view = this.nearest(node);
7250
        if (!view)
7251
            throw new RangeError("Trying to find position for a DOM position outside of the document");
7252
        return view.localPosFromDOM(node, offset) + view.posAtStart;
7253
    }
7254
    domAtPos(pos) {
7255
        let { i, off } = this.childCursor().findPos(pos, -1);
7256
        for (; i < this.children.length - 1;) {
7257
            let child = this.children[i];
7258
            if (off < child.length || child instanceof LineView)
7259
                break;
7260
            i++;
7261
            off = 0;
7262
        }
7263
        return this.children[i].domAtPos(off);
7264
    }
7265
    coordsAt(pos, side) {
7266
        let best = null, bestPos = 0;
7267
        for (let off = this.length, i = this.children.length - 1; i >= 0; i--) {
7268
            let child = this.children[i], end = off - child.breakAfter, start = end - child.length;
7269
            if (end < pos)
7270
                break;
7271
            if (start <= pos && (start < pos || child.covers(-1)) && (end > pos || child.covers(1)) &&
7272
                (!best || child instanceof LineView && !(best instanceof LineView && side >= 0))) {
7273
                best = child;
7274
                bestPos = start;
7275
            }
7276
            off = start;
7277
        }
7278
        return best ? best.coordsAt(pos - bestPos, side) : null;
7279
    }
7280
    coordsForChar(pos) {
7281
        let { i, off } = this.childPos(pos, 1), child = this.children[i];
7282
        if (!(child instanceof LineView))
7283
            return null;
7284
        while (child.children.length) {
7285
            let { i, off: childOff } = child.childPos(off, 1);
7286
            for (;; i++) {
7287
                if (i == child.children.length)
7288
                    return null;
7289
                if ((child = child.children[i]).length)
7290
                    break;
7291
            }
7292
            off = childOff;
7293
        }
7294
        if (!(child instanceof TextView))
7295
            return null;
7296
        let end = findClusterBreak(child.text, off);
7297
        if (end == off)
7298
            return null;
7299
        let rects = textRange(child.dom, off, end).getClientRects();
7300
        for (let i = 0; i < rects.length; i++) {
7301
            let rect = rects[i];
7302
            if (i == rects.length - 1 || rect.top < rect.bottom && rect.left < rect.right)
7303
                return rect;
7304
        }
7305
        return null;
7306
    }
7307
    measureVisibleLineHeights(viewport) {
7308
        let result = [], { from, to } = viewport;
7309
        let contentWidth = this.view.contentDOM.clientWidth;
7310
        let isWider = contentWidth > Math.max(this.view.scrollDOM.clientWidth, this.minWidth) + 1;
7311
        let widest = -1, ltr = this.view.textDirection == Direction.LTR;
7312
        for (let pos = 0, i = 0; i < this.children.length; i++) {
7313
            let child = this.children[i], end = pos + child.length;
7314
            if (end > to)
7315
                break;
7316
            if (pos >= from) {
7317
                let childRect = child.dom.getBoundingClientRect();
7318
                result.push(childRect.height);
7319
                if (isWider) {
7320
                    let last = child.dom.lastChild;
7321
                    let rects = last ? clientRectsFor(last) : [];
7322
                    if (rects.length) {
7323
                        let rect = rects[rects.length - 1];
7324
                        let width = ltr ? rect.right - childRect.left : childRect.right - rect.left;
7325
                        if (width > widest) {
7326
                            widest = width;
7327
                            this.minWidth = contentWidth;
7328
                            this.minWidthFrom = pos;
7329
                            this.minWidthTo = end;
7330
                        }
7331
                    }
7332
                }
7333
            }
7334
            pos = end + child.breakAfter;
7335
        }
7336
        return result;
7337
    }
7338
    textDirectionAt(pos) {
7339
        let { i } = this.childPos(pos, 1);
7340
        return getComputedStyle(this.children[i].dom).direction == "rtl" ? Direction.RTL : Direction.LTR;
7341
    }
7342
    measureTextSize() {
7343
        for (let child of this.children) {
7344
            if (child instanceof LineView) {
7345
                let measure = child.measureTextSize();
7346
                if (measure)
7347
                    return measure;
7348
            }
7349
        }
7350
        // If no workable line exists, force a layout of a measurable element
7351
        let dummy = document.createElement("div"), lineHeight, charWidth, textHeight;
7352
        dummy.className = "cm-line";
7353
        dummy.style.width = "99999px";
7354
        dummy.style.position = "absolute";
7355
        dummy.textContent = "abc def ghi jkl mno pqr stu";
7356
        this.view.observer.ignore(() => {
7357
            this.dom.appendChild(dummy);
7358
            let rect = clientRectsFor(dummy.firstChild)[0];
7359
            lineHeight = dummy.getBoundingClientRect().height;
7360
            charWidth = rect ? rect.width / 27 : 7;
7361
            textHeight = rect ? rect.height : lineHeight;
7362
            dummy.remove();
7363
        });
7364
        return { lineHeight, charWidth, textHeight };
7365
    }
7366
    childCursor(pos = this.length) {
7367
        // Move back to start of last element when possible, so that
7368
        // `ChildCursor.findPos` doesn't have to deal with the edge case
7369
        // of being after the last element.
7370
        let i = this.children.length;
7371
        if (i)
7372
            pos -= this.children[--i].length;
7373
        return new ChildCursor(this.children, pos, i);
7374
    }
7375
    computeBlockGapDeco() {
7376
        let deco = [], vs = this.view.viewState;
7377
        for (let pos = 0, i = 0;; i++) {
7378
            let next = i == vs.viewports.length ? null : vs.viewports[i];
7379
            let end = next ? next.from - 1 : this.length;
7380
            if (end > pos) {
7381
                let height = (vs.lineBlockAt(end).bottom - vs.lineBlockAt(pos).top) / this.view.scaleY;
7382
                deco.push(Decoration.replace({
7383
                    widget: new BlockGapWidget(height),
7384
                    block: true,
7385
                    inclusive: true,
7386
                    isBlockGap: true,
7387
                }).range(pos, end));
7388
            }
7389
            if (!next)
7390
                break;
7391
            pos = next.to + 1;
7392
        }
7393
        return Decoration.set(deco);
7394
    }
7395
    updateDeco() {
7396
        let i = 0;
7397
        let allDeco = this.view.state.facet(decorations).map(d => {
7398
            let dynamic = this.dynamicDecorationMap[i++] = typeof d == "function";
7399
            return dynamic ? d(this.view) : d;
7400
        });
7401
        let dynamicOuter = false, outerDeco = this.view.state.facet(outerDecorations).map((d, i) => {
7402
            let dynamic = typeof d == "function";
7403
            if (dynamic)
7404
                dynamicOuter = true;
7405
            return dynamic ? d(this.view) : d;
7406
        });
7407
        if (outerDeco.length) {
7408
            this.dynamicDecorationMap[i++] = dynamicOuter;
7409
            allDeco.push(RangeSet.join(outerDeco));
7410
        }
7411
        this.decorations = [
7412
            ...allDeco,
7413
            this.computeBlockGapDeco(),
7414
            this.view.viewState.lineGapDeco
7415
        ];
7416
        while (i < this.decorations.length)
7417
            this.dynamicDecorationMap[i++] = false;
7418
        return this.decorations;
7419
    }
7420
    scrollIntoView(target) {
7421
        if (target.isSnapshot) {
7422
            let ref = this.view.viewState.lineBlockAt(target.range.head);
7423
            this.view.scrollDOM.scrollTop = ref.top - target.yMargin;
7424
            this.view.scrollDOM.scrollLeft = target.xMargin;
7425
            return;
7426
        }
7427
        for (let handler of this.view.state.facet(scrollHandler)) {
7428
            try {
7429
                if (handler(this.view, target.range, target))
7430
                    return true;
7431
            }
7432
            catch (e) {
7433
                logException(this.view.state, e, "scroll handler");
7434
            }
7435
        }
7436
        let { range } = target;
7437
        let rect = this.coordsAt(range.head, range.empty ? range.assoc : range.head > range.anchor ? -1 : 1), other;
7438
        if (!rect)
7439
            return;
7440
        if (!range.empty && (other = this.coordsAt(range.anchor, range.anchor > range.head ? -1 : 1)))
7441
            rect = { left: Math.min(rect.left, other.left), top: Math.min(rect.top, other.top),
7442
                right: Math.max(rect.right, other.right), bottom: Math.max(rect.bottom, other.bottom) };
7443
        let margins = getScrollMargins(this.view);
7444
        let targetRect = {
7445
            left: rect.left - margins.left, top: rect.top - margins.top,
7446
            right: rect.right + margins.right, bottom: rect.bottom + margins.bottom
7447
        };
7448
        let { offsetWidth, offsetHeight } = this.view.scrollDOM;
7449
        scrollRectIntoView(this.view.scrollDOM, targetRect, range.head < range.anchor ? -1 : 1, target.x, target.y, Math.max(Math.min(target.xMargin, offsetWidth), -offsetWidth), Math.max(Math.min(target.yMargin, offsetHeight), -offsetHeight), this.view.textDirection == Direction.LTR);
7450
    }
7451
}
7452
function betweenUneditable(pos) {
7453
    return pos.node.nodeType == 1 && pos.node.firstChild &&
7454
        (pos.offset == 0 || pos.node.childNodes[pos.offset - 1].contentEditable == "false") &&
7455
        (pos.offset == pos.node.childNodes.length || pos.node.childNodes[pos.offset].contentEditable == "false");
7456
}
7457
class BlockGapWidget extends WidgetType {
7458
    constructor(height) {
7459
        super();
7460
        this.height = height;
7461
    }
7462
    toDOM() {
7463
        let elt = document.createElement("div");
7464
        elt.className = "cm-gap";
7465
        this.updateDOM(elt);
7466
        return elt;
7467
    }
7468
    eq(other) { return other.height == this.height; }
7469
    updateDOM(elt) {
7470
        elt.style.height = this.height + "px";
7471
        return true;
7472
    }
7473
    get editable() { return true; }
7474
    get estimatedHeight() { return this.height; }
7475
    ignoreEvent() { return false; }
7476
}
7477
function findCompositionNode(view, headPos) {
7478
    let sel = view.observer.selectionRange;
7479
    if (!sel.focusNode)
7480
        return null;
7481
    let textBefore = textNodeBefore(sel.focusNode, sel.focusOffset);
7482
    let textAfter = textNodeAfter(sel.focusNode, sel.focusOffset);
7483
    let textNode = textBefore || textAfter;
7484
    if (textAfter && textBefore && textAfter.node != textBefore.node) {
7485
        let descAfter = ContentView.get(textAfter.node);
7486
        if (!descAfter || descAfter instanceof TextView && descAfter.text != textAfter.node.nodeValue) {
7487
            textNode = textAfter;
7488
        }
7489
        else if (view.docView.lastCompositionAfterCursor) {
7490
            let descBefore = ContentView.get(textBefore.node);
7491
            if (!(!descBefore || descBefore instanceof TextView && descBefore.text != textBefore.node.nodeValue))
7492
                textNode = textAfter;
7493
        }
7494
    }
7495
    view.docView.lastCompositionAfterCursor = textNode != textBefore;
7496
    if (!textNode)
7497
        return null;
7498
    let from = headPos - textNode.offset;
7499
    return { from, to: from + textNode.node.nodeValue.length, node: textNode.node };
7500
}
7501
function findCompositionRange(view, changes, headPos) {
7502
    let found = findCompositionNode(view, headPos);
7503
    if (!found)
7504
        return null;
7505
    let { node: textNode, from, to } = found, text = textNode.nodeValue;
7506
    // Don't try to preserve multi-line compositions
7507
    if (/[\n\r]/.test(text))
7508
        return null;
7509
    if (view.state.doc.sliceString(found.from, found.to) != text)
7510
        return null;
7511
    let inv = changes.invertedDesc;
7512
    let range = new ChangedRange(inv.mapPos(from), inv.mapPos(to), from, to);
7513
    let marks = [];
7514
    for (let parent = textNode.parentNode;; parent = parent.parentNode) {
7515
        let parentView = ContentView.get(parent);
7516
        if (parentView instanceof MarkView)
7517
            marks.push({ node: parent, deco: parentView.mark });
7518
        else if (parentView instanceof LineView || parent.nodeName == "DIV" && parent.parentNode == view.contentDOM)
7519
            return { range, text: textNode, marks, line: parent };
7520
        else if (parent != view.contentDOM)
7521
            marks.push({ node: parent, deco: new MarkDecoration({
7522
                    inclusive: true,
7523
                    attributes: getAttrs$1(parent),
7524
                    tagName: parent.tagName.toLowerCase()
7525
                }) });
7526
        else
7527
            return null;
7528
    }
7529
}
7530
function nextToUneditable(node, offset) {
7531
    if (node.nodeType != 1)
7532
        return 0;
7533
    return (offset && node.childNodes[offset - 1].contentEditable == "false" ? 1 /* NextTo.Before */ : 0) |
7534
        (offset < node.childNodes.length && node.childNodes[offset].contentEditable == "false" ? 2 /* NextTo.After */ : 0);
7535
}
7536
let DecorationComparator$1 = class DecorationComparator {
7537
    constructor() {
7538
        this.changes = [];
7539
    }
7540
    compareRange(from, to) { addRange(from, to, this.changes); }
7541
    comparePoint(from, to) { addRange(from, to, this.changes); }
7542
};
7543
function findChangedDeco(a, b, diff) {
7544
    let comp = new DecorationComparator$1;
7545
    RangeSet.compare(a, b, diff, comp);
7546
    return comp.changes;
7547
}
7548
function inUneditable(node, inside) {
7549
    for (let cur = node; cur && cur != inside; cur = cur.assignedSlot || cur.parentNode) {
7550
        if (cur.nodeType == 1 && cur.contentEditable == 'false') {
7551
            return true;
7552
        }
7553
    }
7554
    return false;
7555
}
7556
function touchesComposition(changes, composition) {
7557
    let touched = false;
7558
    if (composition)
7559
        changes.iterChangedRanges((from, to) => {
7560
            if (from < composition.to && to > composition.from)
7561
                touched = true;
7562
        });
7563
    return touched;
7564
}
7565
 
7566
function groupAt(state, pos, bias = 1) {
7567
    let categorize = state.charCategorizer(pos);
7568
    let line = state.doc.lineAt(pos), linePos = pos - line.from;
7569
    if (line.length == 0)
7570
        return EditorSelection.cursor(pos);
7571
    if (linePos == 0)
7572
        bias = 1;
7573
    else if (linePos == line.length)
7574
        bias = -1;
7575
    let from = linePos, to = linePos;
7576
    if (bias < 0)
7577
        from = findClusterBreak(line.text, linePos, false);
7578
    else
7579
        to = findClusterBreak(line.text, linePos);
7580
    let cat = categorize(line.text.slice(from, to));
7581
    while (from > 0) {
7582
        let prev = findClusterBreak(line.text, from, false);
7583
        if (categorize(line.text.slice(prev, from)) != cat)
7584
            break;
7585
        from = prev;
7586
    }
7587
    while (to < line.length) {
7588
        let next = findClusterBreak(line.text, to);
7589
        if (categorize(line.text.slice(to, next)) != cat)
7590
            break;
7591
        to = next;
7592
    }
7593
    return EditorSelection.range(from + line.from, to + line.from);
7594
}
7595
// Search the DOM for the {node, offset} position closest to the given
7596
// coordinates. Very inefficient and crude, but can usually be avoided
7597
// by calling caret(Position|Range)FromPoint instead.
7598
function getdx(x, rect) {
7599
    return rect.left > x ? rect.left - x : Math.max(0, x - rect.right);
7600
}
7601
function getdy(y, rect) {
7602
    return rect.top > y ? rect.top - y : Math.max(0, y - rect.bottom);
7603
}
7604
function yOverlap(a, b) {
7605
    return a.top < b.bottom - 1 && a.bottom > b.top + 1;
7606
}
7607
function upTop(rect, top) {
7608
    return top < rect.top ? { top, left: rect.left, right: rect.right, bottom: rect.bottom } : rect;
7609
}
7610
function upBot(rect, bottom) {
7611
    return bottom > rect.bottom ? { top: rect.top, left: rect.left, right: rect.right, bottom } : rect;
7612
}
7613
function domPosAtCoords(parent, x, y) {
7614
    let closest, closestRect, closestX, closestY, closestOverlap = false;
7615
    let above, below, aboveRect, belowRect;
7616
    for (let child = parent.firstChild; child; child = child.nextSibling) {
7617
        let rects = clientRectsFor(child);
7618
        for (let i = 0; i < rects.length; i++) {
7619
            let rect = rects[i];
7620
            if (closestRect && yOverlap(closestRect, rect))
7621
                rect = upTop(upBot(rect, closestRect.bottom), closestRect.top);
7622
            let dx = getdx(x, rect), dy = getdy(y, rect);
7623
            if (dx == 0 && dy == 0)
7624
                return child.nodeType == 3 ? domPosInText(child, x, y) : domPosAtCoords(child, x, y);
7625
            if (!closest || closestY > dy || closestY == dy && closestX > dx) {
7626
                closest = child;
7627
                closestRect = rect;
7628
                closestX = dx;
7629
                closestY = dy;
7630
                let side = dy ? (y < rect.top ? -1 : 1) : dx ? (x < rect.left ? -1 : 1) : 0;
7631
                closestOverlap = !side || (side > 0 ? i < rects.length - 1 : i > 0);
7632
            }
7633
            if (dx == 0) {
7634
                if (y > rect.bottom && (!aboveRect || aboveRect.bottom < rect.bottom)) {
7635
                    above = child;
7636
                    aboveRect = rect;
7637
                }
7638
                else if (y < rect.top && (!belowRect || belowRect.top > rect.top)) {
7639
                    below = child;
7640
                    belowRect = rect;
7641
                }
7642
            }
7643
            else if (aboveRect && yOverlap(aboveRect, rect)) {
7644
                aboveRect = upBot(aboveRect, rect.bottom);
7645
            }
7646
            else if (belowRect && yOverlap(belowRect, rect)) {
7647
                belowRect = upTop(belowRect, rect.top);
7648
            }
7649
        }
7650
    }
7651
    if (aboveRect && aboveRect.bottom >= y) {
7652
        closest = above;
7653
        closestRect = aboveRect;
7654
    }
7655
    else if (belowRect && belowRect.top <= y) {
7656
        closest = below;
7657
        closestRect = belowRect;
7658
    }
7659
    if (!closest)
7660
        return { node: parent, offset: 0 };
7661
    let clipX = Math.max(closestRect.left, Math.min(closestRect.right, x));
7662
    if (closest.nodeType == 3)
7663
        return domPosInText(closest, clipX, y);
7664
    if (closestOverlap && closest.contentEditable != "false")
7665
        return domPosAtCoords(closest, clipX, y);
7666
    let offset = Array.prototype.indexOf.call(parent.childNodes, closest) +
7667
        (x >= (closestRect.left + closestRect.right) / 2 ? 1 : 0);
7668
    return { node: parent, offset };
7669
}
7670
function domPosInText(node, x, y) {
7671
    let len = node.nodeValue.length;
7672
    let closestOffset = -1, closestDY = 1e9, generalSide = 0;
7673
    for (let i = 0; i < len; i++) {
7674
        let rects = textRange(node, i, i + 1).getClientRects();
7675
        for (let j = 0; j < rects.length; j++) {
7676
            let rect = rects[j];
7677
            if (rect.top == rect.bottom)
7678
                continue;
7679
            if (!generalSide)
7680
                generalSide = x - rect.left;
7681
            let dy = (rect.top > y ? rect.top - y : y - rect.bottom) - 1;
7682
            if (rect.left - 1 <= x && rect.right + 1 >= x && dy < closestDY) {
7683
                let right = x >= (rect.left + rect.right) / 2, after = right;
7684
                if (browser.chrome || browser.gecko) {
7685
                    // Check for RTL on browsers that support getting client
7686
                    // rects for empty ranges.
7687
                    let rectBefore = textRange(node, i).getBoundingClientRect();
7688
                    if (rectBefore.left == rect.right)
7689
                        after = !right;
7690
                }
7691
                if (dy <= 0)
7692
                    return { node, offset: i + (after ? 1 : 0) };
7693
                closestOffset = i + (after ? 1 : 0);
7694
                closestDY = dy;
7695
            }
7696
        }
7697
    }
7698
    return { node, offset: closestOffset > -1 ? closestOffset : generalSide > 0 ? node.nodeValue.length : 0 };
7699
}
7700
function posAtCoords(view, coords, precise, bias = -1) {
7701
    var _a, _b;
7702
    let content = view.contentDOM.getBoundingClientRect(), docTop = content.top + view.viewState.paddingTop;
7703
    let block, { docHeight } = view.viewState;
7704
    let { x, y } = coords, yOffset = y - docTop;
7705
    if (yOffset < 0)
7706
        return 0;
7707
    if (yOffset > docHeight)
7708
        return view.state.doc.length;
7709
    // Scan for a text block near the queried y position
7710
    for (let halfLine = view.viewState.heightOracle.textHeight / 2, bounced = false;;) {
7711
        block = view.elementAtHeight(yOffset);
7712
        if (block.type == BlockType.Text)
7713
            break;
7714
        for (;;) {
7715
            // Move the y position out of this block
7716
            yOffset = bias > 0 ? block.bottom + halfLine : block.top - halfLine;
7717
            if (yOffset >= 0 && yOffset <= docHeight)
7718
                break;
7719
            // If the document consists entirely of replaced widgets, we
7720
            // won't find a text block, so return 0
7721
            if (bounced)
7722
                return precise ? null : 0;
7723
            bounced = true;
7724
            bias = -bias;
7725
        }
7726
    }
7727
    y = docTop + yOffset;
7728
    let lineStart = block.from;
7729
    // If this is outside of the rendered viewport, we can't determine a position
7730
    if (lineStart < view.viewport.from)
7731
        return view.viewport.from == 0 ? 0 : precise ? null : posAtCoordsImprecise(view, content, block, x, y);
7732
    if (lineStart > view.viewport.to)
7733
        return view.viewport.to == view.state.doc.length ? view.state.doc.length :
7734
            precise ? null : posAtCoordsImprecise(view, content, block, x, y);
7735
    // Prefer ShadowRootOrDocument.elementFromPoint if present, fall back to document if not
7736
    let doc = view.dom.ownerDocument;
7737
    let root = view.root.elementFromPoint ? view.root : doc;
7738
    let element = root.elementFromPoint(x, y);
7739
    if (element && !view.contentDOM.contains(element))
7740
        element = null;
7741
    // If the element is unexpected, clip x at the sides of the content area and try again
7742
    if (!element) {
7743
        x = Math.max(content.left + 1, Math.min(content.right - 1, x));
7744
        element = root.elementFromPoint(x, y);
7745
        if (element && !view.contentDOM.contains(element))
7746
            element = null;
7747
    }
7748
    // There's visible editor content under the point, so we can try
7749
    // using caret(Position|Range)FromPoint as a shortcut
7750
    let node, offset = -1;
7751
    if (element && ((_a = view.docView.nearest(element)) === null || _a === void 0 ? void 0 : _a.isEditable) != false) {
7752
        if (doc.caretPositionFromPoint) {
7753
            let pos = doc.caretPositionFromPoint(x, y);
7754
            if (pos)
7755
                ({ offsetNode: node, offset } = pos);
7756
        }
7757
        else if (doc.caretRangeFromPoint) {
7758
            let range = doc.caretRangeFromPoint(x, y);
7759
            if (range) {
7760
                ({ startContainer: node, startOffset: offset } = range);
7761
                if (!view.contentDOM.contains(node) ||
7762
                    browser.safari && isSuspiciousSafariCaretResult(node, offset, x) ||
7763
                    browser.chrome && isSuspiciousChromeCaretResult(node, offset, x))
7764
                    node = undefined;
7765
            }
7766
        }
7767
    }
7768
    // No luck, do our own (potentially expensive) search
7769
    if (!node || !view.docView.dom.contains(node)) {
7770
        let line = LineView.find(view.docView, lineStart);
7771
        if (!line)
7772
            return yOffset > block.top + block.height / 2 ? block.to : block.from;
7773
        ({ node, offset } = domPosAtCoords(line.dom, x, y));
7774
    }
7775
    let nearest = view.docView.nearest(node);
7776
    if (!nearest)
7777
        return null;
7778
    if (nearest.isWidget && ((_b = nearest.dom) === null || _b === void 0 ? void 0 : _b.nodeType) == 1) {
7779
        let rect = nearest.dom.getBoundingClientRect();
7780
        return coords.y < rect.top || coords.y <= rect.bottom && coords.x <= (rect.left + rect.right) / 2
7781
            ? nearest.posAtStart : nearest.posAtEnd;
7782
    }
7783
    else {
7784
        return nearest.localPosFromDOM(node, offset) + nearest.posAtStart;
7785
    }
7786
}
7787
function posAtCoordsImprecise(view, contentRect, block, x, y) {
7788
    let into = Math.round((x - contentRect.left) * view.defaultCharacterWidth);
7789
    if (view.lineWrapping && block.height > view.defaultLineHeight * 1.5) {
7790
        let textHeight = view.viewState.heightOracle.textHeight;
7791
        let line = Math.floor((y - block.top - (view.defaultLineHeight - textHeight) * 0.5) / textHeight);
7792
        into += line * view.viewState.heightOracle.lineLength;
7793
    }
7794
    let content = view.state.sliceDoc(block.from, block.to);
7795
    return block.from + findColumn(content, into, view.state.tabSize);
7796
}
7797
// In case of a high line height, Safari's caretRangeFromPoint treats
7798
// the space between lines as belonging to the last character of the
7799
// line before. This is used to detect such a result so that it can be
7800
// ignored (issue #401).
7801
function isSuspiciousSafariCaretResult(node, offset, x) {
7802
    let len;
7803
    if (node.nodeType != 3 || offset != (len = node.nodeValue.length))
7804
        return false;
7805
    for (let next = node.nextSibling; next; next = next.nextSibling)
7806
        if (next.nodeType != 1 || next.nodeName != "BR")
7807
            return false;
7808
    return textRange(node, len - 1, len).getBoundingClientRect().left > x;
7809
}
7810
// Chrome will move positions between lines to the start of the next line
7811
function isSuspiciousChromeCaretResult(node, offset, x) {
7812
    if (offset != 0)
7813
        return false;
7814
    for (let cur = node;;) {
7815
        let parent = cur.parentNode;
7816
        if (!parent || parent.nodeType != 1 || parent.firstChild != cur)
7817
            return false;
7818
        if (parent.classList.contains("cm-line"))
7819
            break;
7820
        cur = parent;
7821
    }
7822
    let rect = node.nodeType == 1 ? node.getBoundingClientRect()
7823
        : textRange(node, 0, Math.max(node.nodeValue.length, 1)).getBoundingClientRect();
7824
    return x - rect.left > 5;
7825
}
7826
function blockAt(view, pos) {
7827
    let line = view.lineBlockAt(pos);
7828
    if (Array.isArray(line.type))
7829
        for (let l of line.type) {
7830
            if (l.to > pos || l.to == pos && (l.to == line.to || l.type == BlockType.Text))
7831
                return l;
7832
        }
7833
    return line;
7834
}
7835
function moveToLineBoundary(view, start, forward, includeWrap) {
7836
    let line = blockAt(view, start.head);
7837
    let coords = !includeWrap || line.type != BlockType.Text || !(view.lineWrapping || line.widgetLineBreaks) ? null
7838
        : view.coordsAtPos(start.assoc < 0 && start.head > line.from ? start.head - 1 : start.head);
7839
    if (coords) {
7840
        let editorRect = view.dom.getBoundingClientRect();
7841
        let direction = view.textDirectionAt(line.from);
7842
        let pos = view.posAtCoords({ x: forward == (direction == Direction.LTR) ? editorRect.right - 1 : editorRect.left + 1,
7843
            y: (coords.top + coords.bottom) / 2 });
7844
        if (pos != null)
7845
            return EditorSelection.cursor(pos, forward ? -1 : 1);
7846
    }
7847
    return EditorSelection.cursor(forward ? line.to : line.from, forward ? -1 : 1);
7848
}
7849
function moveByChar(view, start, forward, by) {
7850
    let line = view.state.doc.lineAt(start.head), spans = view.bidiSpans(line);
7851
    let direction = view.textDirectionAt(line.from);
7852
    for (let cur = start, check = null;;) {
7853
        let next = moveVisually(line, spans, direction, cur, forward), char = movedOver;
7854
        if (!next) {
7855
            if (line.number == (forward ? view.state.doc.lines : 1))
7856
                return cur;
7857
            char = "\n";
7858
            line = view.state.doc.line(line.number + (forward ? 1 : -1));
7859
            spans = view.bidiSpans(line);
7860
            next = view.visualLineSide(line, !forward);
7861
        }
7862
        if (!check) {
7863
            if (!by)
7864
                return next;
7865
            check = by(char);
7866
        }
7867
        else if (!check(char)) {
7868
            return cur;
7869
        }
7870
        cur = next;
7871
    }
7872
}
7873
function byGroup(view, pos, start) {
7874
    let categorize = view.state.charCategorizer(pos);
7875
    let cat = categorize(start);
7876
    return (next) => {
7877
        let nextCat = categorize(next);
7878
        if (cat == CharCategory.Space)
7879
            cat = nextCat;
7880
        return cat == nextCat;
7881
    };
7882
}
7883
function moveVertically(view, start, forward, distance) {
7884
    let startPos = start.head, dir = forward ? 1 : -1;
7885
    if (startPos == (forward ? view.state.doc.length : 0))
7886
        return EditorSelection.cursor(startPos, start.assoc);
7887
    let goal = start.goalColumn, startY;
7888
    let rect = view.contentDOM.getBoundingClientRect();
7889
    let startCoords = view.coordsAtPos(startPos, start.assoc || -1), docTop = view.documentTop;
7890
    if (startCoords) {
7891
        if (goal == null)
7892
            goal = startCoords.left - rect.left;
7893
        startY = dir < 0 ? startCoords.top : startCoords.bottom;
7894
    }
7895
    else {
7896
        let line = view.viewState.lineBlockAt(startPos);
7897
        if (goal == null)
7898
            goal = Math.min(rect.right - rect.left, view.defaultCharacterWidth * (startPos - line.from));
7899
        startY = (dir < 0 ? line.top : line.bottom) + docTop;
7900
    }
7901
    let resolvedGoal = rect.left + goal;
7902
    let dist = distance !== null && distance !== void 0 ? distance : (view.viewState.heightOracle.textHeight >> 1);
7903
    for (let extra = 0;; extra += 10) {
7904
        let curY = startY + (dist + extra) * dir;
7905
        let pos = posAtCoords(view, { x: resolvedGoal, y: curY }, false, dir);
7906
        if (curY < rect.top || curY > rect.bottom || (dir < 0 ? pos < startPos : pos > startPos)) {
7907
            let charRect = view.docView.coordsForChar(pos);
7908
            let assoc = !charRect || curY < charRect.top ? -1 : 1;
7909
            return EditorSelection.cursor(pos, assoc, undefined, goal);
7910
        }
7911
    }
7912
}
7913
function skipAtomicRanges(atoms, pos, bias) {
7914
    for (;;) {
7915
        let moved = 0;
7916
        for (let set of atoms) {
7917
            set.between(pos - 1, pos + 1, (from, to, value) => {
7918
                if (pos > from && pos < to) {
7919
                    let side = moved || bias || (pos - from < to - pos ? -1 : 1);
7920
                    pos = side < 0 ? from : to;
7921
                    moved = side;
7922
                }
7923
            });
7924
        }
7925
        if (!moved)
7926
            return pos;
7927
    }
7928
}
7929
function skipAtoms(view, oldPos, pos) {
7930
    let newPos = skipAtomicRanges(view.state.facet(atomicRanges).map(f => f(view)), pos.from, oldPos.head > pos.from ? -1 : 1);
7931
    return newPos == pos.from ? pos : EditorSelection.cursor(newPos, newPos < pos.from ? 1 : -1);
7932
}
7933
 
7934
// This will also be where dragging info and such goes
7935
class InputState {
7936
    setSelectionOrigin(origin) {
7937
        this.lastSelectionOrigin = origin;
7938
        this.lastSelectionTime = Date.now();
7939
    }
7940
    constructor(view) {
7941
        this.view = view;
7942
        this.lastKeyCode = 0;
7943
        this.lastKeyTime = 0;
7944
        this.lastTouchTime = 0;
7945
        this.lastFocusTime = 0;
7946
        this.lastScrollTop = 0;
7947
        this.lastScrollLeft = 0;
7948
        // On iOS, some keys need to have their default behavior happen
7949
        // (after which we retroactively handle them and reset the DOM) to
7950
        // avoid messing up the virtual keyboard state.
7951
        this.pendingIOSKey = undefined;
7952
        this.lastSelectionOrigin = null;
7953
        this.lastSelectionTime = 0;
7954
        this.lastEscPress = 0;
7955
        this.lastContextMenu = 0;
7956
        this.scrollHandlers = [];
7957
        this.handlers = Object.create(null);
7958
        // -1 means not in a composition. Otherwise, this counts the number
7959
        // of changes made during the composition. The count is used to
7960
        // avoid treating the start state of the composition, before any
7961
        // changes have been made, as part of the composition.
7962
        this.composing = -1;
7963
        // Tracks whether the next change should be marked as starting the
7964
        // composition (null means no composition, true means next is the
7965
        // first, false means first has already been marked for this
7966
        // composition)
7967
        this.compositionFirstChange = null;
7968
        // End time of the previous composition
7969
        this.compositionEndedAt = 0;
7970
        // Used in a kludge to detect when an Enter keypress should be
7971
        // considered part of the composition on Safari, which fires events
7972
        // in the wrong order
7973
        this.compositionPendingKey = false;
7974
        // Used to categorize changes as part of a composition, even when
7975
        // the mutation events fire shortly after the compositionend event
7976
        this.compositionPendingChange = false;
7977
        this.mouseSelection = null;
7978
        // When a drag from the editor is active, this points at the range
7979
        // being dragged.
7980
        this.draggedContent = null;
7981
        this.handleEvent = this.handleEvent.bind(this);
7982
        this.notifiedFocused = view.hasFocus;
7983
        // On Safari adding an input event handler somehow prevents an
7984
        // issue where the composition vanishes when you press enter.
7985
        if (browser.safari)
7986
            view.contentDOM.addEventListener("input", () => null);
7987
        if (browser.gecko)
7988
            firefoxCopyCutHack(view.contentDOM.ownerDocument);
7989
    }
7990
    handleEvent(event) {
7991
        if (!eventBelongsToEditor(this.view, event) || this.ignoreDuringComposition(event))
7992
            return;
7993
        if (event.type == "keydown" && this.keydown(event))
7994
            return;
7995
        this.runHandlers(event.type, event);
7996
    }
7997
    runHandlers(type, event) {
7998
        let handlers = this.handlers[type];
7999
        if (handlers) {
8000
            for (let observer of handlers.observers)
8001
                observer(this.view, event);
8002
            for (let handler of handlers.handlers) {
8003
                if (event.defaultPrevented)
8004
                    break;
8005
                if (handler(this.view, event)) {
8006
                    event.preventDefault();
8007
                    break;
8008
                }
8009
            }
8010
        }
8011
    }
8012
    ensureHandlers(plugins) {
8013
        let handlers = computeHandlers(plugins), prev = this.handlers, dom = this.view.contentDOM;
8014
        for (let type in handlers)
8015
            if (type != "scroll") {
8016
                let passive = !handlers[type].handlers.length;
8017
                let exists = prev[type];
8018
                if (exists && passive != !exists.handlers.length) {
8019
                    dom.removeEventListener(type, this.handleEvent);
8020
                    exists = null;
8021
                }
8022
                if (!exists)
8023
                    dom.addEventListener(type, this.handleEvent, { passive });
8024
            }
8025
        for (let type in prev)
8026
            if (type != "scroll" && !handlers[type])
8027
                dom.removeEventListener(type, this.handleEvent);
8028
        this.handlers = handlers;
8029
    }
8030
    keydown(event) {
8031
        // Must always run, even if a custom handler handled the event
8032
        this.lastKeyCode = event.keyCode;
8033
        this.lastKeyTime = Date.now();
8034
        if (event.keyCode == 9 && Date.now() < this.lastEscPress + 2000)
8035
            return true;
8036
        if (event.keyCode != 27 && modifierCodes.indexOf(event.keyCode) < 0)
8037
            this.view.inputState.lastEscPress = 0;
8038
        // Chrome for Android usually doesn't fire proper key events, but
8039
        // occasionally does, usually surrounded by a bunch of complicated
8040
        // composition changes. When an enter or backspace key event is
8041
        // seen, hold off on handling DOM events for a bit, and then
8042
        // dispatch it.
8043
        if (browser.android && browser.chrome && !event.synthetic &&
8044
            (event.keyCode == 13 || event.keyCode == 8)) {
8045
            this.view.observer.delayAndroidKey(event.key, event.keyCode);
8046
            return true;
8047
        }
8048
        // Preventing the default behavior of Enter on iOS makes the
8049
        // virtual keyboard get stuck in the wrong (lowercase)
8050
        // state. So we let it go through, and then, in
8051
        // applyDOMChange, notify key handlers of it and reset to
8052
        // the state they produce.
8053
        let pending;
8054
        if (browser.ios && !event.synthetic && !event.altKey && !event.metaKey &&
8055
            ((pending = PendingKeys.find(key => key.keyCode == event.keyCode)) && !event.ctrlKey ||
8056
                EmacsyPendingKeys.indexOf(event.key) > -1 && event.ctrlKey && !event.shiftKey)) {
8057
            this.pendingIOSKey = pending || event;
8058
            setTimeout(() => this.flushIOSKey(), 250);
8059
            return true;
8060
        }
8061
        if (event.keyCode != 229)
8062
            this.view.observer.forceFlush();
8063
        return false;
8064
    }
8065
    flushIOSKey(change) {
8066
        let key = this.pendingIOSKey;
8067
        if (!key)
8068
            return false;
8069
        // This looks like an autocorrection before Enter
8070
        if (key.key == "Enter" && change && change.from < change.to && /^\S+$/.test(change.insert.toString()))
8071
            return false;
8072
        this.pendingIOSKey = undefined;
8073
        return dispatchKey(this.view.contentDOM, key.key, key.keyCode, key instanceof KeyboardEvent ? key : undefined);
8074
    }
8075
    ignoreDuringComposition(event) {
8076
        if (!/^key/.test(event.type))
8077
            return false;
8078
        if (this.composing > 0)
8079
            return true;
8080
        // See https://www.stum.de/2016/06/24/handling-ime-events-in-javascript/.
8081
        // On some input method editors (IMEs), the Enter key is used to
8082
        // confirm character selection. On Safari, when Enter is pressed,
8083
        // compositionend and keydown events are sometimes emitted in the
8084
        // wrong order. The key event should still be ignored, even when
8085
        // it happens after the compositionend event.
8086
        if (browser.safari && !browser.ios && this.compositionPendingKey && Date.now() - this.compositionEndedAt < 100) {
8087
            this.compositionPendingKey = false;
8088
            return true;
8089
        }
8090
        return false;
8091
    }
8092
    startMouseSelection(mouseSelection) {
8093
        if (this.mouseSelection)
8094
            this.mouseSelection.destroy();
8095
        this.mouseSelection = mouseSelection;
8096
    }
8097
    update(update) {
8098
        if (this.mouseSelection)
8099
            this.mouseSelection.update(update);
8100
        if (this.draggedContent && update.docChanged)
8101
            this.draggedContent = this.draggedContent.map(update.changes);
8102
        if (update.transactions.length)
8103
            this.lastKeyCode = this.lastSelectionTime = 0;
8104
    }
8105
    destroy() {
8106
        if (this.mouseSelection)
8107
            this.mouseSelection.destroy();
8108
    }
8109
}
8110
function bindHandler(plugin, handler) {
8111
    return (view, event) => {
8112
        try {
8113
            return handler.call(plugin, event, view);
8114
        }
8115
        catch (e) {
8116
            logException(view.state, e);
8117
        }
8118
    };
8119
}
8120
function computeHandlers(plugins) {
8121
    let result = Object.create(null);
8122
    function record(type) {
8123
        return result[type] || (result[type] = { observers: [], handlers: [] });
8124
    }
8125
    for (let plugin of plugins) {
8126
        let spec = plugin.spec;
8127
        if (spec && spec.domEventHandlers)
8128
            for (let type in spec.domEventHandlers) {
8129
                let f = spec.domEventHandlers[type];
8130
                if (f)
8131
                    record(type).handlers.push(bindHandler(plugin.value, f));
8132
            }
8133
        if (spec && spec.domEventObservers)
8134
            for (let type in spec.domEventObservers) {
8135
                let f = spec.domEventObservers[type];
8136
                if (f)
8137
                    record(type).observers.push(bindHandler(plugin.value, f));
8138
            }
8139
    }
8140
    for (let type in handlers)
8141
        record(type).handlers.push(handlers[type]);
8142
    for (let type in observers)
8143
        record(type).observers.push(observers[type]);
8144
    return result;
8145
}
8146
const PendingKeys = [
8147
    { key: "Backspace", keyCode: 8, inputType: "deleteContentBackward" },
8148
    { key: "Enter", keyCode: 13, inputType: "insertParagraph" },
8149
    { key: "Enter", keyCode: 13, inputType: "insertLineBreak" },
8150
    { key: "Delete", keyCode: 46, inputType: "deleteContentForward" }
8151
];
8152
const EmacsyPendingKeys = "dthko";
8153
// Key codes for modifier keys
8154
const modifierCodes = [16, 17, 18, 20, 91, 92, 224, 225];
8155
const dragScrollMargin = 6;
8156
function dragScrollSpeed(dist) {
8157
    return Math.max(0, dist) * 0.7 + 8;
8158
}
8159
function dist(a, b) {
8160
    return Math.max(Math.abs(a.clientX - b.clientX), Math.abs(a.clientY - b.clientY));
8161
}
8162
class MouseSelection {
8163
    constructor(view, startEvent, style, mustSelect) {
8164
        this.view = view;
8165
        this.startEvent = startEvent;
8166
        this.style = style;
8167
        this.mustSelect = mustSelect;
8168
        this.scrollSpeed = { x: 0, y: 0 };
8169
        this.scrolling = -1;
8170
        this.lastEvent = startEvent;
8171
        this.scrollParent = scrollableParent(view.contentDOM);
8172
        this.atoms = view.state.facet(atomicRanges).map(f => f(view));
8173
        let doc = view.contentDOM.ownerDocument;
8174
        doc.addEventListener("mousemove", this.move = this.move.bind(this));
8175
        doc.addEventListener("mouseup", this.up = this.up.bind(this));
8176
        this.extend = startEvent.shiftKey;
8177
        this.multiple = view.state.facet(EditorState.allowMultipleSelections) && addsSelectionRange(view, startEvent);
8178
        this.dragging = isInPrimarySelection(view, startEvent) && getClickType(startEvent) == 1 ? null : false;
8179
    }
8180
    start(event) {
8181
        // When clicking outside of the selection, immediately apply the
8182
        // effect of starting the selection
8183
        if (this.dragging === false)
8184
            this.select(event);
8185
    }
8186
    move(event) {
8187
        var _a;
8188
        if (event.buttons == 0)
8189
            return this.destroy();
8190
        if (this.dragging || this.dragging == null && dist(this.startEvent, event) < 10)
8191
            return;
8192
        this.select(this.lastEvent = event);
8193
        let sx = 0, sy = 0;
8194
        let rect = ((_a = this.scrollParent) === null || _a === void 0 ? void 0 : _a.getBoundingClientRect())
8195
            || { left: 0, top: 0, right: this.view.win.innerWidth, bottom: this.view.win.innerHeight };
8196
        let margins = getScrollMargins(this.view);
8197
        if (event.clientX - margins.left <= rect.left + dragScrollMargin)
8198
            sx = -dragScrollSpeed(rect.left - event.clientX);
8199
        else if (event.clientX + margins.right >= rect.right - dragScrollMargin)
8200
            sx = dragScrollSpeed(event.clientX - rect.right);
8201
        if (event.clientY - margins.top <= rect.top + dragScrollMargin)
8202
            sy = -dragScrollSpeed(rect.top - event.clientY);
8203
        else if (event.clientY + margins.bottom >= rect.bottom - dragScrollMargin)
8204
            sy = dragScrollSpeed(event.clientY - rect.bottom);
8205
        this.setScrollSpeed(sx, sy);
8206
    }
8207
    up(event) {
8208
        if (this.dragging == null)
8209
            this.select(this.lastEvent);
8210
        if (!this.dragging)
8211
            event.preventDefault();
8212
        this.destroy();
8213
    }
8214
    destroy() {
8215
        this.setScrollSpeed(0, 0);
8216
        let doc = this.view.contentDOM.ownerDocument;
8217
        doc.removeEventListener("mousemove", this.move);
8218
        doc.removeEventListener("mouseup", this.up);
8219
        this.view.inputState.mouseSelection = this.view.inputState.draggedContent = null;
8220
    }
8221
    setScrollSpeed(sx, sy) {
8222
        this.scrollSpeed = { x: sx, y: sy };
8223
        if (sx || sy) {
8224
            if (this.scrolling < 0)
8225
                this.scrolling = setInterval(() => this.scroll(), 50);
8226
        }
8227
        else if (this.scrolling > -1) {
8228
            clearInterval(this.scrolling);
8229
            this.scrolling = -1;
8230
        }
8231
    }
8232
    scroll() {
8233
        if (this.scrollParent) {
8234
            this.scrollParent.scrollLeft += this.scrollSpeed.x;
8235
            this.scrollParent.scrollTop += this.scrollSpeed.y;
8236
        }
8237
        else {
8238
            this.view.win.scrollBy(this.scrollSpeed.x, this.scrollSpeed.y);
8239
        }
8240
        if (this.dragging === false)
8241
            this.select(this.lastEvent);
8242
    }
8243
    skipAtoms(sel) {
8244
        let ranges = null;
8245
        for (let i = 0; i < sel.ranges.length; i++) {
8246
            let range = sel.ranges[i], updated = null;
8247
            if (range.empty) {
8248
                let pos = skipAtomicRanges(this.atoms, range.from, 0);
8249
                if (pos != range.from)
8250
                    updated = EditorSelection.cursor(pos, -1);
8251
            }
8252
            else {
8253
                let from = skipAtomicRanges(this.atoms, range.from, -1);
8254
                let to = skipAtomicRanges(this.atoms, range.to, 1);
8255
                if (from != range.from || to != range.to)
8256
                    updated = EditorSelection.range(range.from == range.anchor ? from : to, range.from == range.head ? from : to);
8257
            }
8258
            if (updated) {
8259
                if (!ranges)
8260
                    ranges = sel.ranges.slice();
8261
                ranges[i] = updated;
8262
            }
8263
        }
8264
        return ranges ? EditorSelection.create(ranges, sel.mainIndex) : sel;
8265
    }
8266
    select(event) {
8267
        let { view } = this, selection = this.skipAtoms(this.style.get(event, this.extend, this.multiple));
8268
        if (this.mustSelect || !selection.eq(view.state.selection, this.dragging === false))
8269
            this.view.dispatch({
8270
                selection,
8271
                userEvent: "select.pointer"
8272
            });
8273
        this.mustSelect = false;
8274
    }
8275
    update(update) {
8276
        if (this.style.update(update))
8277
            setTimeout(() => this.select(this.lastEvent), 20);
8278
    }
8279
}
8280
function addsSelectionRange(view, event) {
8281
    let facet = view.state.facet(clickAddsSelectionRange);
8282
    return facet.length ? facet[0](event) : browser.mac ? event.metaKey : event.ctrlKey;
8283
}
8284
function dragMovesSelection(view, event) {
8285
    let facet = view.state.facet(dragMovesSelection$1);
8286
    return facet.length ? facet[0](event) : browser.mac ? !event.altKey : !event.ctrlKey;
8287
}
8288
function isInPrimarySelection(view, event) {
8289
    let { main } = view.state.selection;
8290
    if (main.empty)
8291
        return false;
8292
    // On boundary clicks, check whether the coordinates are inside the
8293
    // selection's client rectangles
8294
    let sel = getSelection(view.root);
8295
    if (!sel || sel.rangeCount == 0)
8296
        return true;
8297
    let rects = sel.getRangeAt(0).getClientRects();
8298
    for (let i = 0; i < rects.length; i++) {
8299
        let rect = rects[i];
8300
        if (rect.left <= event.clientX && rect.right >= event.clientX &&
8301
            rect.top <= event.clientY && rect.bottom >= event.clientY)
8302
            return true;
8303
    }
8304
    return false;
8305
}
8306
function eventBelongsToEditor(view, event) {
8307
    if (!event.bubbles)
8308
        return true;
8309
    if (event.defaultPrevented)
8310
        return false;
8311
    for (let node = event.target, cView; node != view.contentDOM; node = node.parentNode)
8312
        if (!node || node.nodeType == 11 || ((cView = ContentView.get(node)) && cView.ignoreEvent(event)))
8313
            return false;
8314
    return true;
8315
}
8316
const handlers = /*@__PURE__*/Object.create(null);
8317
const observers = /*@__PURE__*/Object.create(null);
8318
// This is very crude, but unfortunately both these browsers _pretend_
8319
// that they have a clipboard API—all the objects and methods are
8320
// there, they just don't work, and they are hard to test.
8321
const brokenClipboardAPI = (browser.ie && browser.ie_version < 15) ||
8322
    (browser.ios && browser.webkit_version < 604);
8323
function capturePaste(view) {
8324
    let parent = view.dom.parentNode;
8325
    if (!parent)
8326
        return;
8327
    let target = parent.appendChild(document.createElement("textarea"));
8328
    target.style.cssText = "position: fixed; left: -10000px; top: 10px";
8329
    target.focus();
8330
    setTimeout(() => {
8331
        view.focus();
8332
        target.remove();
8333
        doPaste(view, target.value);
8334
    }, 50);
8335
}
8336
function doPaste(view, input) {
8337
    let { state } = view, changes, i = 1, text = state.toText(input);
8338
    let byLine = text.lines == state.selection.ranges.length;
8339
    let linewise = lastLinewiseCopy != null && state.selection.ranges.every(r => r.empty) && lastLinewiseCopy == text.toString();
8340
    if (linewise) {
8341
        let lastLine = -1;
8342
        changes = state.changeByRange(range => {
8343
            let line = state.doc.lineAt(range.from);
8344
            if (line.from == lastLine)
8345
                return { range };
8346
            lastLine = line.from;
8347
            let insert = state.toText((byLine ? text.line(i++).text : input) + state.lineBreak);
8348
            return { changes: { from: line.from, insert },
8349
                range: EditorSelection.cursor(range.from + insert.length) };
8350
        });
8351
    }
8352
    else if (byLine) {
8353
        changes = state.changeByRange(range => {
8354
            let line = text.line(i++);
8355
            return { changes: { from: range.from, to: range.to, insert: line.text },
8356
                range: EditorSelection.cursor(range.from + line.length) };
8357
        });
8358
    }
8359
    else {
8360
        changes = state.replaceSelection(text);
8361
    }
8362
    view.dispatch(changes, {
8363
        userEvent: "input.paste",
8364
        scrollIntoView: true
8365
    });
8366
}
8367
observers.scroll = view => {
8368
    view.inputState.lastScrollTop = view.scrollDOM.scrollTop;
8369
    view.inputState.lastScrollLeft = view.scrollDOM.scrollLeft;
8370
};
8371
handlers.keydown = (view, event) => {
8372
    view.inputState.setSelectionOrigin("select");
8373
    if (event.keyCode == 27)
8374
        view.inputState.lastEscPress = Date.now();
8375
    return false;
8376
};
8377
observers.touchstart = (view, e) => {
8378
    view.inputState.lastTouchTime = Date.now();
8379
    view.inputState.setSelectionOrigin("select.pointer");
8380
};
8381
observers.touchmove = view => {
8382
    view.inputState.setSelectionOrigin("select.pointer");
8383
};
8384
handlers.mousedown = (view, event) => {
8385
    view.observer.flush();
8386
    if (view.inputState.lastTouchTime > Date.now() - 2000)
8387
        return false; // Ignore touch interaction
8388
    let style = null;
8389
    for (let makeStyle of view.state.facet(mouseSelectionStyle)) {
8390
        style = makeStyle(view, event);
8391
        if (style)
8392
            break;
8393
    }
8394
    if (!style && event.button == 0)
8395
        style = basicMouseSelection(view, event);
8396
    if (style) {
8397
        let mustFocus = !view.hasFocus;
8398
        view.inputState.startMouseSelection(new MouseSelection(view, event, style, mustFocus));
8399
        if (mustFocus)
8400
            view.observer.ignore(() => focusPreventScroll(view.contentDOM));
8401
        let mouseSel = view.inputState.mouseSelection;
8402
        if (mouseSel) {
8403
            mouseSel.start(event);
8404
            return mouseSel.dragging === false;
8405
        }
8406
    }
8407
    return false;
8408
};
8409
function rangeForClick(view, pos, bias, type) {
8410
    if (type == 1) { // Single click
8411
        return EditorSelection.cursor(pos, bias);
8412
    }
8413
    else if (type == 2) { // Double click
8414
        return groupAt(view.state, pos, bias);
8415
    }
8416
    else { // Triple click
8417
        let visual = LineView.find(view.docView, pos), line = view.state.doc.lineAt(visual ? visual.posAtEnd : pos);
8418
        let from = visual ? visual.posAtStart : line.from, to = visual ? visual.posAtEnd : line.to;
8419
        if (to < view.state.doc.length && to == line.to)
8420
            to++;
8421
        return EditorSelection.range(from, to);
8422
    }
8423
}
8424
let insideY = (y, rect) => y >= rect.top && y <= rect.bottom;
8425
let inside = (x, y, rect) => insideY(y, rect) && x >= rect.left && x <= rect.right;
8426
// Try to determine, for the given coordinates, associated with the
8427
// given position, whether they are related to the element before or
8428
// the element after the position.
8429
function findPositionSide(view, pos, x, y) {
8430
    let line = LineView.find(view.docView, pos);
8431
    if (!line)
8432
        return 1;
8433
    let off = pos - line.posAtStart;
8434
    // Line boundaries point into the line
8435
    if (off == 0)
8436
        return 1;
8437
    if (off == line.length)
8438
        return -1;
8439
    // Positions on top of an element point at that element
8440
    let before = line.coordsAt(off, -1);
8441
    if (before && inside(x, y, before))
8442
        return -1;
8443
    let after = line.coordsAt(off, 1);
8444
    if (after && inside(x, y, after))
8445
        return 1;
8446
    // This is probably a line wrap point. Pick before if the point is
8447
    // beside it.
8448
    return before && insideY(y, before) ? -1 : 1;
8449
}
8450
function queryPos(view, event) {
8451
    let pos = view.posAtCoords({ x: event.clientX, y: event.clientY }, false);
8452
    return { pos, bias: findPositionSide(view, pos, event.clientX, event.clientY) };
8453
}
8454
const BadMouseDetail = browser.ie && browser.ie_version <= 11;
8455
let lastMouseDown = null, lastMouseDownCount = 0, lastMouseDownTime = 0;
8456
function getClickType(event) {
8457
    if (!BadMouseDetail)
8458
        return event.detail;
8459
    let last = lastMouseDown, lastTime = lastMouseDownTime;
8460
    lastMouseDown = event;
8461
    lastMouseDownTime = Date.now();
8462
    return lastMouseDownCount = !last || (lastTime > Date.now() - 400 && Math.abs(last.clientX - event.clientX) < 2 &&
8463
        Math.abs(last.clientY - event.clientY) < 2) ? (lastMouseDownCount + 1) % 3 : 1;
8464
}
8465
function basicMouseSelection(view, event) {
8466
    let start = queryPos(view, event), type = getClickType(event);
8467
    let startSel = view.state.selection;
8468
    return {
8469
        update(update) {
8470
            if (update.docChanged) {
8471
                start.pos = update.changes.mapPos(start.pos);
8472
                startSel = startSel.map(update.changes);
8473
            }
8474
        },
8475
        get(event, extend, multiple) {
8476
            let cur = queryPos(view, event), removed;
8477
            let range = rangeForClick(view, cur.pos, cur.bias, type);
8478
            if (start.pos != cur.pos && !extend) {
8479
                let startRange = rangeForClick(view, start.pos, start.bias, type);
8480
                let from = Math.min(startRange.from, range.from), to = Math.max(startRange.to, range.to);
8481
                range = from < range.from ? EditorSelection.range(from, to) : EditorSelection.range(to, from);
8482
            }
8483
            if (extend)
8484
                return startSel.replaceRange(startSel.main.extend(range.from, range.to));
8485
            else if (multiple && type == 1 && startSel.ranges.length > 1 && (removed = removeRangeAround(startSel, cur.pos)))
8486
                return removed;
8487
            else if (multiple)
8488
                return startSel.addRange(range);
8489
            else
8490
                return EditorSelection.create([range]);
8491
        }
8492
    };
8493
}
8494
function removeRangeAround(sel, pos) {
8495
    for (let i = 0; i < sel.ranges.length; i++) {
8496
        let { from, to } = sel.ranges[i];
8497
        if (from <= pos && to >= pos)
8498
            return EditorSelection.create(sel.ranges.slice(0, i).concat(sel.ranges.slice(i + 1)), sel.mainIndex == i ? 0 : sel.mainIndex - (sel.mainIndex > i ? 1 : 0));
8499
    }
8500
    return null;
8501
}
8502
handlers.dragstart = (view, event) => {
8503
    let { selection: { main: range } } = view.state;
8504
    if (event.target.draggable) {
8505
        let cView = view.docView.nearest(event.target);
8506
        if (cView && cView.isWidget) {
8507
            let from = cView.posAtStart, to = from + cView.length;
8508
            if (from >= range.to || to <= range.from)
8509
                range = EditorSelection.range(from, to);
8510
        }
8511
    }
8512
    let { inputState } = view;
8513
    if (inputState.mouseSelection)
8514
        inputState.mouseSelection.dragging = true;
8515
    inputState.draggedContent = range;
8516
    if (event.dataTransfer) {
8517
        event.dataTransfer.setData("Text", view.state.sliceDoc(range.from, range.to));
8518
        event.dataTransfer.effectAllowed = "copyMove";
8519
    }
8520
    return false;
8521
};
8522
handlers.dragend = view => {
8523
    view.inputState.draggedContent = null;
8524
    return false;
8525
};
8526
function dropText(view, event, text, direct) {
8527
    if (!text)
8528
        return;
8529
    let dropPos = view.posAtCoords({ x: event.clientX, y: event.clientY }, false);
8530
    let { draggedContent } = view.inputState;
8531
    let del = direct && draggedContent && dragMovesSelection(view, event)
8532
        ? { from: draggedContent.from, to: draggedContent.to } : null;
8533
    let ins = { from: dropPos, insert: text };
8534
    let changes = view.state.changes(del ? [del, ins] : ins);
8535
    view.focus();
8536
    view.dispatch({
8537
        changes,
8538
        selection: { anchor: changes.mapPos(dropPos, -1), head: changes.mapPos(dropPos, 1) },
8539
        userEvent: del ? "move.drop" : "input.drop"
8540
    });
8541
    view.inputState.draggedContent = null;
8542
}
8543
handlers.drop = (view, event) => {
8544
    if (!event.dataTransfer)
8545
        return false;
8546
    if (view.state.readOnly)
8547
        return true;
8548
    let files = event.dataTransfer.files;
8549
    if (files && files.length) { // For a file drop, read the file's text.
8550
        let text = Array(files.length), read = 0;
8551
        let finishFile = () => {
8552
            if (++read == files.length)
8553
                dropText(view, event, text.filter(s => s != null).join(view.state.lineBreak), false);
8554
        };
8555
        for (let i = 0; i < files.length; i++) {
8556
            let reader = new FileReader;
8557
            reader.onerror = finishFile;
8558
            reader.onload = () => {
8559
                if (!/[\x00-\x08\x0e-\x1f]{2}/.test(reader.result))
8560
                    text[i] = reader.result;
8561
                finishFile();
8562
            };
8563
            reader.readAsText(files[i]);
8564
        }
8565
        return true;
8566
    }
8567
    else {
8568
        let text = event.dataTransfer.getData("Text");
8569
        if (text) {
8570
            dropText(view, event, text, true);
8571
            return true;
8572
        }
8573
    }
8574
    return false;
8575
};
8576
handlers.paste = (view, event) => {
8577
    if (view.state.readOnly)
8578
        return true;
8579
    view.observer.flush();
8580
    let data = brokenClipboardAPI ? null : event.clipboardData;
8581
    if (data) {
8582
        doPaste(view, data.getData("text/plain") || data.getData("text/uri-list"));
8583
        return true;
8584
    }
8585
    else {
8586
        capturePaste(view);
8587
        return false;
8588
    }
8589
};
8590
function captureCopy(view, text) {
8591
    // The extra wrapper is somehow necessary on IE/Edge to prevent the
8592
    // content from being mangled when it is put onto the clipboard
8593
    let parent = view.dom.parentNode;
8594
    if (!parent)
8595
        return;
8596
    let target = parent.appendChild(document.createElement("textarea"));
8597
    target.style.cssText = "position: fixed; left: -10000px; top: 10px";
8598
    target.value = text;
8599
    target.focus();
8600
    target.selectionEnd = text.length;
8601
    target.selectionStart = 0;
8602
    setTimeout(() => {
8603
        target.remove();
8604
        view.focus();
8605
    }, 50);
8606
}
8607
function copiedRange(state) {
8608
    let content = [], ranges = [], linewise = false;
8609
    for (let range of state.selection.ranges)
8610
        if (!range.empty) {
8611
            content.push(state.sliceDoc(range.from, range.to));
8612
            ranges.push(range);
8613
        }
8614
    if (!content.length) {
8615
        // Nothing selected, do a line-wise copy
8616
        let upto = -1;
8617
        for (let { from } of state.selection.ranges) {
8618
            let line = state.doc.lineAt(from);
8619
            if (line.number > upto) {
8620
                content.push(line.text);
8621
                ranges.push({ from: line.from, to: Math.min(state.doc.length, line.to + 1) });
8622
            }
8623
            upto = line.number;
8624
        }
8625
        linewise = true;
8626
    }
8627
    return { text: content.join(state.lineBreak), ranges, linewise };
8628
}
8629
let lastLinewiseCopy = null;
8630
handlers.copy = handlers.cut = (view, event) => {
8631
    let { text, ranges, linewise } = copiedRange(view.state);
8632
    if (!text && !linewise)
8633
        return false;
8634
    lastLinewiseCopy = linewise ? text : null;
8635
    if (event.type == "cut" && !view.state.readOnly)
8636
        view.dispatch({
8637
            changes: ranges,
8638
            scrollIntoView: true,
8639
            userEvent: "delete.cut"
8640
        });
8641
    let data = brokenClipboardAPI ? null : event.clipboardData;
8642
    if (data) {
8643
        data.clearData();
8644
        data.setData("text/plain", text);
8645
        return true;
8646
    }
8647
    else {
8648
        captureCopy(view, text);
8649
        return false;
8650
    }
8651
};
8652
const isFocusChange = /*@__PURE__*/Annotation.define();
8653
function focusChangeTransaction(state, focus) {
8654
    let effects = [];
8655
    for (let getEffect of state.facet(focusChangeEffect)) {
8656
        let effect = getEffect(state, focus);
8657
        if (effect)
8658
            effects.push(effect);
8659
    }
8660
    return effects ? state.update({ effects, annotations: isFocusChange.of(true) }) : null;
8661
}
8662
function updateForFocusChange(view) {
8663
    setTimeout(() => {
8664
        let focus = view.hasFocus;
8665
        if (focus != view.inputState.notifiedFocused) {
8666
            let tr = focusChangeTransaction(view.state, focus);
8667
            if (tr)
8668
                view.dispatch(tr);
8669
            else
8670
                view.update([]);
8671
        }
8672
    }, 10);
8673
}
8674
observers.focus = view => {
8675
    view.inputState.lastFocusTime = Date.now();
8676
    // When focusing reset the scroll position, move it back to where it was
8677
    if (!view.scrollDOM.scrollTop && (view.inputState.lastScrollTop || view.inputState.lastScrollLeft)) {
8678
        view.scrollDOM.scrollTop = view.inputState.lastScrollTop;
8679
        view.scrollDOM.scrollLeft = view.inputState.lastScrollLeft;
8680
    }
8681
    updateForFocusChange(view);
8682
};
8683
observers.blur = view => {
8684
    view.observer.clearSelectionRange();
8685
    updateForFocusChange(view);
8686
};
8687
observers.compositionstart = observers.compositionupdate = view => {
8688
    if (view.inputState.compositionFirstChange == null)
8689
        view.inputState.compositionFirstChange = true;
8690
    if (view.inputState.composing < 0) {
8691
        // FIXME possibly set a timeout to clear it again on Android
8692
        view.inputState.composing = 0;
8693
    }
8694
};
8695
observers.compositionend = view => {
8696
    view.inputState.composing = -1;
8697
    view.inputState.compositionEndedAt = Date.now();
8698
    view.inputState.compositionPendingKey = true;
8699
    view.inputState.compositionPendingChange = view.observer.pendingRecords().length > 0;
8700
    view.inputState.compositionFirstChange = null;
8701
    if (browser.chrome && browser.android) {
8702
        // Delay flushing for a bit on Android because it'll often fire a
8703
        // bunch of contradictory changes in a row at end of compositon
8704
        view.observer.flushSoon();
8705
    }
8706
    else if (view.inputState.compositionPendingChange) {
8707
        // If we found pending records, schedule a flush.
8708
        Promise.resolve().then(() => view.observer.flush());
8709
    }
8710
    else {
8711
        // Otherwise, make sure that, if no changes come in soon, the
8712
        // composition view is cleared.
8713
        setTimeout(() => {
8714
            if (view.inputState.composing < 0 && view.docView.hasComposition)
8715
                view.update([]);
8716
        }, 50);
8717
    }
8718
};
8719
observers.contextmenu = view => {
8720
    view.inputState.lastContextMenu = Date.now();
8721
};
8722
handlers.beforeinput = (view, event) => {
8723
    var _a;
8724
    // Because Chrome Android doesn't fire useful key events, use
8725
    // beforeinput to detect backspace (and possibly enter and delete,
8726
    // but those usually don't even seem to fire beforeinput events at
8727
    // the moment) and fake a key event for it.
8728
    //
8729
    // (preventDefault on beforeinput, though supported in the spec,
8730
    // seems to do nothing at all on Chrome).
8731
    let pending;
8732
    if (browser.chrome && browser.android && (pending = PendingKeys.find(key => key.inputType == event.inputType))) {
8733
        view.observer.delayAndroidKey(pending.key, pending.keyCode);
8734
        if (pending.key == "Backspace" || pending.key == "Delete") {
8735
            let startViewHeight = ((_a = window.visualViewport) === null || _a === void 0 ? void 0 : _a.height) || 0;
8736
            setTimeout(() => {
8737
                var _a;
8738
                // Backspacing near uneditable nodes on Chrome Android sometimes
8739
                // closes the virtual keyboard. This tries to crudely detect
8740
                // that and refocus to get it back.
8741
                if ((((_a = window.visualViewport) === null || _a === void 0 ? void 0 : _a.height) || 0) > startViewHeight + 10 && view.hasFocus) {
8742
                    view.contentDOM.blur();
8743
                    view.focus();
8744
                }
8745
            }, 100);
8746
        }
8747
    }
8748
    if (browser.ios && event.inputType == "deleteContentForward") {
8749
        // For some reason, DOM changes (and beforeinput) happen _before_
8750
        // the key event for ctrl-d on iOS when using an external
8751
        // keyboard.
8752
        view.observer.flushSoon();
8753
    }
8754
    // Safari will occasionally forget to fire compositionend at the end of a dead-key composition
8755
    if (browser.safari && event.inputType == "insertText" && view.inputState.composing >= 0) {
8756
        setTimeout(() => observers.compositionend(view, event), 20);
8757
    }
8758
    return false;
8759
};
8760
const appliedFirefoxHack = /*@__PURE__*/new Set;
8761
// In Firefox, when cut/copy handlers are added to the document, that
8762
// somehow avoids a bug where those events aren't fired when the
8763
// selection is empty. See https://github.com/codemirror/dev/issues/1082
8764
// and https://bugzilla.mozilla.org/show_bug.cgi?id=995961
8765
function firefoxCopyCutHack(doc) {
8766
    if (!appliedFirefoxHack.has(doc)) {
8767
        appliedFirefoxHack.add(doc);
8768
        doc.addEventListener("copy", () => { });
8769
        doc.addEventListener("cut", () => { });
8770
    }
8771
}
8772
 
8773
const wrappingWhiteSpace = ["pre-wrap", "normal", "pre-line", "break-spaces"];
8774
class HeightOracle {
8775
    constructor(lineWrapping) {
8776
        this.lineWrapping = lineWrapping;
8777
        this.doc = Text.empty;
8778
        this.heightSamples = {};
8779
        this.lineHeight = 14; // The height of an entire line (line-height)
8780
        this.charWidth = 7;
8781
        this.textHeight = 14; // The height of the actual font (font-size)
8782
        this.lineLength = 30;
8783
        // Used to track, during updateHeight, if any actual heights changed
8784
        this.heightChanged = false;
8785
    }
8786
    heightForGap(from, to) {
8787
        let lines = this.doc.lineAt(to).number - this.doc.lineAt(from).number + 1;
8788
        if (this.lineWrapping)
8789
            lines += Math.max(0, Math.ceil(((to - from) - (lines * this.lineLength * 0.5)) / this.lineLength));
8790
        return this.lineHeight * lines;
8791
    }
8792
    heightForLine(length) {
8793
        if (!this.lineWrapping)
8794
            return this.lineHeight;
8795
        let lines = 1 + Math.max(0, Math.ceil((length - this.lineLength) / (this.lineLength - 5)));
8796
        return lines * this.lineHeight;
8797
    }
8798
    setDoc(doc) { this.doc = doc; return this; }
8799
    mustRefreshForWrapping(whiteSpace) {
8800
        return (wrappingWhiteSpace.indexOf(whiteSpace) > -1) != this.lineWrapping;
8801
    }
8802
    mustRefreshForHeights(lineHeights) {
8803
        let newHeight = false;
8804
        for (let i = 0; i < lineHeights.length; i++) {
8805
            let h = lineHeights[i];
8806
            if (h < 0) {
8807
                i++;
8808
            }
8809
            else if (!this.heightSamples[Math.floor(h * 10)]) { // Round to .1 pixels
8810
                newHeight = true;
8811
                this.heightSamples[Math.floor(h * 10)] = true;
8812
            }
8813
        }
8814
        return newHeight;
8815
    }
8816
    refresh(whiteSpace, lineHeight, charWidth, textHeight, lineLength, knownHeights) {
8817
        let lineWrapping = wrappingWhiteSpace.indexOf(whiteSpace) > -1;
8818
        let changed = Math.round(lineHeight) != Math.round(this.lineHeight) || this.lineWrapping != lineWrapping;
8819
        this.lineWrapping = lineWrapping;
8820
        this.lineHeight = lineHeight;
8821
        this.charWidth = charWidth;
8822
        this.textHeight = textHeight;
8823
        this.lineLength = lineLength;
8824
        if (changed) {
8825
            this.heightSamples = {};
8826
            for (let i = 0; i < knownHeights.length; i++) {
8827
                let h = knownHeights[i];
8828
                if (h < 0)
8829
                    i++;
8830
                else
8831
                    this.heightSamples[Math.floor(h * 10)] = true;
8832
            }
8833
        }
8834
        return changed;
8835
    }
8836
}
8837
// This object is used by `updateHeight` to make DOM measurements
8838
// arrive at the right nides. The `heights` array is a sequence of
8839
// block heights, starting from position `from`.
8840
class MeasuredHeights {
8841
    constructor(from, heights) {
8842
        this.from = from;
8843
        this.heights = heights;
8844
        this.index = 0;
8845
    }
8846
    get more() { return this.index < this.heights.length; }
8847
}
8848
/**
8849
Record used to represent information about a block-level element
8850
in the editor view.
8851
*/
8852
class BlockInfo {
8853
    /**
8854
    @internal
8855
    */
8856
    constructor(
8857
    /**
8858
    The start of the element in the document.
8859
    */
8860
    from,
8861
    /**
8862
    The length of the element.
8863
    */
8864
    length,
8865
    /**
8866
    The top position of the element (relative to the top of the
8867
    document).
8868
    */
8869
    top,
8870
    /**
8871
    Its height.
8872
    */
8873
    height,
8874
    /**
8875
    @internal Weird packed field that holds an array of children
8876
    for composite blocks, a decoration for block widgets, and a
8877
    number indicating the amount of widget-create line breaks for
8878
    text blocks.
8879
    */
8880
    _content) {
8881
        this.from = from;
8882
        this.length = length;
8883
        this.top = top;
8884
        this.height = height;
8885
        this._content = _content;
8886
    }
8887
    /**
8888
    The type of element this is. When querying lines, this may be
8889
    an array of all the blocks that make up the line.
8890
    */
8891
    get type() {
8892
        return typeof this._content == "number" ? BlockType.Text :
8893
            Array.isArray(this._content) ? this._content : this._content.type;
8894
    }
8895
    /**
8896
    The end of the element as a document position.
8897
    */
8898
    get to() { return this.from + this.length; }
8899
    /**
8900
    The bottom position of the element.
8901
    */
8902
    get bottom() { return this.top + this.height; }
8903
    /**
8904
    If this is a widget block, this will return the widget
8905
    associated with it.
8906
    */
8907
    get widget() {
8908
        return this._content instanceof PointDecoration ? this._content.widget : null;
8909
    }
8910
    /**
8911
    If this is a textblock, this holds the number of line breaks
8912
    that appear in widgets inside the block.
8913
    */
8914
    get widgetLineBreaks() {
8915
        return typeof this._content == "number" ? this._content : 0;
8916
    }
8917
    /**
8918
    @internal
8919
    */
8920
    join(other) {
8921
        let content = (Array.isArray(this._content) ? this._content : [this])
8922
            .concat(Array.isArray(other._content) ? other._content : [other]);
8923
        return new BlockInfo(this.from, this.length + other.length, this.top, this.height + other.height, content);
8924
    }
8925
}
8926
var QueryType$1 = /*@__PURE__*/(function (QueryType) {
8927
    QueryType[QueryType["ByPos"] = 0] = "ByPos";
8928
    QueryType[QueryType["ByHeight"] = 1] = "ByHeight";
8929
    QueryType[QueryType["ByPosNoHeight"] = 2] = "ByPosNoHeight";
8930
return QueryType})(QueryType$1 || (QueryType$1 = {}));
8931
const Epsilon = 1e-3;
8932
class HeightMap {
8933
    constructor(length, // The number of characters covered
8934
    height, // Height of this part of the document
8935
    flags = 2 /* Flag.Outdated */) {
8936
        this.length = length;
8937
        this.height = height;
8938
        this.flags = flags;
8939
    }
8940
    get outdated() { return (this.flags & 2 /* Flag.Outdated */) > 0; }
8941
    set outdated(value) { this.flags = (value ? 2 /* Flag.Outdated */ : 0) | (this.flags & ~2 /* Flag.Outdated */); }
8942
    setHeight(oracle, height) {
8943
        if (this.height != height) {
8944
            if (Math.abs(this.height - height) > Epsilon)
8945
                oracle.heightChanged = true;
8946
            this.height = height;
8947
        }
8948
    }
8949
    // Base case is to replace a leaf node, which simply builds a tree
8950
    // from the new nodes and returns that (HeightMapBranch and
8951
    // HeightMapGap override this to actually use from/to)
8952
    replace(_from, _to, nodes) {
8953
        return HeightMap.of(nodes);
8954
    }
8955
    // Again, these are base cases, and are overridden for branch and gap nodes.
8956
    decomposeLeft(_to, result) { result.push(this); }
8957
    decomposeRight(_from, result) { result.push(this); }
8958
    applyChanges(decorations, oldDoc, oracle, changes) {
8959
        let me = this, doc = oracle.doc;
8960
        for (let i = changes.length - 1; i >= 0; i--) {
8961
            let { fromA, toA, fromB, toB } = changes[i];
8962
            let start = me.lineAt(fromA, QueryType$1.ByPosNoHeight, oracle.setDoc(oldDoc), 0, 0);
8963
            let end = start.to >= toA ? start : me.lineAt(toA, QueryType$1.ByPosNoHeight, oracle, 0, 0);
8964
            toB += end.to - toA;
8965
            toA = end.to;
8966
            while (i > 0 && start.from <= changes[i - 1].toA) {
8967
                fromA = changes[i - 1].fromA;
8968
                fromB = changes[i - 1].fromB;
8969
                i--;
8970
                if (fromA < start.from)
8971
                    start = me.lineAt(fromA, QueryType$1.ByPosNoHeight, oracle, 0, 0);
8972
            }
8973
            fromB += start.from - fromA;
8974
            fromA = start.from;
8975
            let nodes = NodeBuilder.build(oracle.setDoc(doc), decorations, fromB, toB);
8976
            me = me.replace(fromA, toA, nodes);
8977
        }
8978
        return me.updateHeight(oracle, 0);
8979
    }
8980
    static empty() { return new HeightMapText(0, 0); }
8981
    // nodes uses null values to indicate the position of line breaks.
8982
    // There are never line breaks at the start or end of the array, or
8983
    // two line breaks next to each other, and the array isn't allowed
8984
    // to be empty (same restrictions as return value from the builder).
8985
    static of(nodes) {
8986
        if (nodes.length == 1)
8987
            return nodes[0];
8988
        let i = 0, j = nodes.length, before = 0, after = 0;
8989
        for (;;) {
8990
            if (i == j) {
8991
                if (before > after * 2) {
8992
                    let split = nodes[i - 1];
8993
                    if (split.break)
8994
                        nodes.splice(--i, 1, split.left, null, split.right);
8995
                    else
8996
                        nodes.splice(--i, 1, split.left, split.right);
8997
                    j += 1 + split.break;
8998
                    before -= split.size;
8999
                }
9000
                else if (after > before * 2) {
9001
                    let split = nodes[j];
9002
                    if (split.break)
9003
                        nodes.splice(j, 1, split.left, null, split.right);
9004
                    else
9005
                        nodes.splice(j, 1, split.left, split.right);
9006
                    j += 2 + split.break;
9007
                    after -= split.size;
9008
                }
9009
                else {
9010
                    break;
9011
                }
9012
            }
9013
            else if (before < after) {
9014
                let next = nodes[i++];
9015
                if (next)
9016
                    before += next.size;
9017
            }
9018
            else {
9019
                let next = nodes[--j];
9020
                if (next)
9021
                    after += next.size;
9022
            }
9023
        }
9024
        let brk = 0;
9025
        if (nodes[i - 1] == null) {
9026
            brk = 1;
9027
            i--;
9028
        }
9029
        else if (nodes[i] == null) {
9030
            brk = 1;
9031
            j++;
9032
        }
9033
        return new HeightMapBranch(HeightMap.of(nodes.slice(0, i)), brk, HeightMap.of(nodes.slice(j)));
9034
    }
9035
}
9036
HeightMap.prototype.size = 1;
9037
class HeightMapBlock extends HeightMap {
9038
    constructor(length, height, deco) {
9039
        super(length, height);
9040
        this.deco = deco;
9041
    }
9042
    blockAt(_height, _oracle, top, offset) {
9043
        return new BlockInfo(offset, this.length, top, this.height, this.deco || 0);
9044
    }
9045
    lineAt(_value, _type, oracle, top, offset) {
9046
        return this.blockAt(0, oracle, top, offset);
9047
    }
9048
    forEachLine(from, to, oracle, top, offset, f) {
9049
        if (from <= offset + this.length && to >= offset)
9050
            f(this.blockAt(0, oracle, top, offset));
9051
    }
9052
    updateHeight(oracle, offset = 0, _force = false, measured) {
9053
        if (measured && measured.from <= offset && measured.more)
9054
            this.setHeight(oracle, measured.heights[measured.index++]);
9055
        this.outdated = false;
9056
        return this;
9057
    }
9058
    toString() { return `block(${this.length})`; }
9059
}
9060
class HeightMapText extends HeightMapBlock {
9061
    constructor(length, height) {
9062
        super(length, height, null);
9063
        this.collapsed = 0; // Amount of collapsed content in the line
9064
        this.widgetHeight = 0; // Maximum inline widget height
9065
        this.breaks = 0; // Number of widget-introduced line breaks on the line
9066
    }
9067
    blockAt(_height, _oracle, top, offset) {
9068
        return new BlockInfo(offset, this.length, top, this.height, this.breaks);
9069
    }
9070
    replace(_from, _to, nodes) {
9071
        let node = nodes[0];
9072
        if (nodes.length == 1 && (node instanceof HeightMapText || node instanceof HeightMapGap && (node.flags & 4 /* Flag.SingleLine */)) &&
9073
            Math.abs(this.length - node.length) < 10) {
9074
            if (node instanceof HeightMapGap)
9075
                node = new HeightMapText(node.length, this.height);
9076
            else
9077
                node.height = this.height;
9078
            if (!this.outdated)
9079
                node.outdated = false;
9080
            return node;
9081
        }
9082
        else {
9083
            return HeightMap.of(nodes);
9084
        }
9085
    }
9086
    updateHeight(oracle, offset = 0, force = false, measured) {
9087
        if (measured && measured.from <= offset && measured.more)
9088
            this.setHeight(oracle, measured.heights[measured.index++]);
9089
        else if (force || this.outdated)
9090
            this.setHeight(oracle, Math.max(this.widgetHeight, oracle.heightForLine(this.length - this.collapsed)) +
9091
                this.breaks * oracle.lineHeight);
9092
        this.outdated = false;
9093
        return this;
9094
    }
9095
    toString() {
9096
        return `line(${this.length}${this.collapsed ? -this.collapsed : ""}${this.widgetHeight ? ":" + this.widgetHeight : ""})`;
9097
    }
9098
}
9099
class HeightMapGap extends HeightMap {
9100
    constructor(length) { super(length, 0); }
9101
    heightMetrics(oracle, offset) {
9102
        let firstLine = oracle.doc.lineAt(offset).number, lastLine = oracle.doc.lineAt(offset + this.length).number;
9103
        let lines = lastLine - firstLine + 1;
9104
        let perLine, perChar = 0;
9105
        if (oracle.lineWrapping) {
9106
            let totalPerLine = Math.min(this.height, oracle.lineHeight * lines);
9107
            perLine = totalPerLine / lines;
9108
            if (this.length > lines + 1)
9109
                perChar = (this.height - totalPerLine) / (this.length - lines - 1);
9110
        }
9111
        else {
9112
            perLine = this.height / lines;
9113
        }
9114
        return { firstLine, lastLine, perLine, perChar };
9115
    }
9116
    blockAt(height, oracle, top, offset) {
9117
        let { firstLine, lastLine, perLine, perChar } = this.heightMetrics(oracle, offset);
9118
        if (oracle.lineWrapping) {
9119
            let guess = offset + (height < oracle.lineHeight ? 0
9120
                : Math.round(Math.max(0, Math.min(1, (height - top) / this.height)) * this.length));
9121
            let line = oracle.doc.lineAt(guess), lineHeight = perLine + line.length * perChar;
9122
            let lineTop = Math.max(top, height - lineHeight / 2);
9123
            return new BlockInfo(line.from, line.length, lineTop, lineHeight, 0);
9124
        }
9125
        else {
9126
            let line = Math.max(0, Math.min(lastLine - firstLine, Math.floor((height - top) / perLine)));
9127
            let { from, length } = oracle.doc.line(firstLine + line);
9128
            return new BlockInfo(from, length, top + perLine * line, perLine, 0);
9129
        }
9130
    }
9131
    lineAt(value, type, oracle, top, offset) {
9132
        if (type == QueryType$1.ByHeight)
9133
            return this.blockAt(value, oracle, top, offset);
9134
        if (type == QueryType$1.ByPosNoHeight) {
9135
            let { from, to } = oracle.doc.lineAt(value);
9136
            return new BlockInfo(from, to - from, 0, 0, 0);
9137
        }
9138
        let { firstLine, perLine, perChar } = this.heightMetrics(oracle, offset);
9139
        let line = oracle.doc.lineAt(value), lineHeight = perLine + line.length * perChar;
9140
        let linesAbove = line.number - firstLine;
9141
        let lineTop = top + perLine * linesAbove + perChar * (line.from - offset - linesAbove);
9142
        return new BlockInfo(line.from, line.length, Math.max(top, Math.min(lineTop, top + this.height - lineHeight)), lineHeight, 0);
9143
    }
9144
    forEachLine(from, to, oracle, top, offset, f) {
9145
        from = Math.max(from, offset);
9146
        to = Math.min(to, offset + this.length);
9147
        let { firstLine, perLine, perChar } = this.heightMetrics(oracle, offset);
9148
        for (let pos = from, lineTop = top; pos <= to;) {
9149
            let line = oracle.doc.lineAt(pos);
9150
            if (pos == from) {
9151
                let linesAbove = line.number - firstLine;
9152
                lineTop += perLine * linesAbove + perChar * (from - offset - linesAbove);
9153
            }
9154
            let lineHeight = perLine + perChar * line.length;
9155
            f(new BlockInfo(line.from, line.length, lineTop, lineHeight, 0));
9156
            lineTop += lineHeight;
9157
            pos = line.to + 1;
9158
        }
9159
    }
9160
    replace(from, to, nodes) {
9161
        let after = this.length - to;
9162
        if (after > 0) {
9163
            let last = nodes[nodes.length - 1];
9164
            if (last instanceof HeightMapGap)
9165
                nodes[nodes.length - 1] = new HeightMapGap(last.length + after);
9166
            else
9167
                nodes.push(null, new HeightMapGap(after - 1));
9168
        }
9169
        if (from > 0) {
9170
            let first = nodes[0];
9171
            if (first instanceof HeightMapGap)
9172
                nodes[0] = new HeightMapGap(from + first.length);
9173
            else
9174
                nodes.unshift(new HeightMapGap(from - 1), null);
9175
        }
9176
        return HeightMap.of(nodes);
9177
    }
9178
    decomposeLeft(to, result) {
9179
        result.push(new HeightMapGap(to - 1), null);
9180
    }
9181
    decomposeRight(from, result) {
9182
        result.push(null, new HeightMapGap(this.length - from - 1));
9183
    }
9184
    updateHeight(oracle, offset = 0, force = false, measured) {
9185
        let end = offset + this.length;
9186
        if (measured && measured.from <= offset + this.length && measured.more) {
9187
            // Fill in part of this gap with measured lines. We know there
9188
            // can't be widgets or collapsed ranges in those lines, because
9189
            // they would already have been added to the heightmap (gaps
9190
            // only contain plain text).
9191
            let nodes = [], pos = Math.max(offset, measured.from), singleHeight = -1;
9192
            if (measured.from > offset)
9193
                nodes.push(new HeightMapGap(measured.from - offset - 1).updateHeight(oracle, offset));
9194
            while (pos <= end && measured.more) {
9195
                let len = oracle.doc.lineAt(pos).length;
9196
                if (nodes.length)
9197
                    nodes.push(null);
9198
                let height = measured.heights[measured.index++];
9199
                if (singleHeight == -1)
9200
                    singleHeight = height;
9201
                else if (Math.abs(height - singleHeight) >= Epsilon)
9202
                    singleHeight = -2;
9203
                let line = new HeightMapText(len, height);
9204
                line.outdated = false;
9205
                nodes.push(line);
9206
                pos += len + 1;
9207
            }
9208
            if (pos <= end)
9209
                nodes.push(null, new HeightMapGap(end - pos).updateHeight(oracle, pos));
9210
            let result = HeightMap.of(nodes);
9211
            if (singleHeight < 0 || Math.abs(result.height - this.height) >= Epsilon ||
9212
                Math.abs(singleHeight - this.heightMetrics(oracle, offset).perLine) >= Epsilon)
9213
                oracle.heightChanged = true;
9214
            return result;
9215
        }
9216
        else if (force || this.outdated) {
9217
            this.setHeight(oracle, oracle.heightForGap(offset, offset + this.length));
9218
            this.outdated = false;
9219
        }
9220
        return this;
9221
    }
9222
    toString() { return `gap(${this.length})`; }
9223
}
9224
class HeightMapBranch extends HeightMap {
9225
    constructor(left, brk, right) {
9226
        super(left.length + brk + right.length, left.height + right.height, brk | (left.outdated || right.outdated ? 2 /* Flag.Outdated */ : 0));
9227
        this.left = left;
9228
        this.right = right;
9229
        this.size = left.size + right.size;
9230
    }
9231
    get break() { return this.flags & 1 /* Flag.Break */; }
9232
    blockAt(height, oracle, top, offset) {
9233
        let mid = top + this.left.height;
9234
        return height < mid ? this.left.blockAt(height, oracle, top, offset)
9235
            : this.right.blockAt(height, oracle, mid, offset + this.left.length + this.break);
9236
    }
9237
    lineAt(value, type, oracle, top, offset) {
9238
        let rightTop = top + this.left.height, rightOffset = offset + this.left.length + this.break;
9239
        let left = type == QueryType$1.ByHeight ? value < rightTop : value < rightOffset;
9240
        let base = left ? this.left.lineAt(value, type, oracle, top, offset)
9241
            : this.right.lineAt(value, type, oracle, rightTop, rightOffset);
9242
        if (this.break || (left ? base.to < rightOffset : base.from > rightOffset))
9243
            return base;
9244
        let subQuery = type == QueryType$1.ByPosNoHeight ? QueryType$1.ByPosNoHeight : QueryType$1.ByPos;
9245
        if (left)
9246
            return base.join(this.right.lineAt(rightOffset, subQuery, oracle, rightTop, rightOffset));
9247
        else
9248
            return this.left.lineAt(rightOffset, subQuery, oracle, top, offset).join(base);
9249
    }
9250
    forEachLine(from, to, oracle, top, offset, f) {
9251
        let rightTop = top + this.left.height, rightOffset = offset + this.left.length + this.break;
9252
        if (this.break) {
9253
            if (from < rightOffset)
9254
                this.left.forEachLine(from, to, oracle, top, offset, f);
9255
            if (to >= rightOffset)
9256
                this.right.forEachLine(from, to, oracle, rightTop, rightOffset, f);
9257
        }
9258
        else {
9259
            let mid = this.lineAt(rightOffset, QueryType$1.ByPos, oracle, top, offset);
9260
            if (from < mid.from)
9261
                this.left.forEachLine(from, mid.from - 1, oracle, top, offset, f);
9262
            if (mid.to >= from && mid.from <= to)
9263
                f(mid);
9264
            if (to > mid.to)
9265
                this.right.forEachLine(mid.to + 1, to, oracle, rightTop, rightOffset, f);
9266
        }
9267
    }
9268
    replace(from, to, nodes) {
9269
        let rightStart = this.left.length + this.break;
9270
        if (to < rightStart)
9271
            return this.balanced(this.left.replace(from, to, nodes), this.right);
9272
        if (from > this.left.length)
9273
            return this.balanced(this.left, this.right.replace(from - rightStart, to - rightStart, nodes));
9274
        let result = [];
9275
        if (from > 0)
9276
            this.decomposeLeft(from, result);
9277
        let left = result.length;
9278
        for (let node of nodes)
9279
            result.push(node);
9280
        if (from > 0)
9281
            mergeGaps(result, left - 1);
9282
        if (to < this.length) {
9283
            let right = result.length;
9284
            this.decomposeRight(to, result);
9285
            mergeGaps(result, right);
9286
        }
9287
        return HeightMap.of(result);
9288
    }
9289
    decomposeLeft(to, result) {
9290
        let left = this.left.length;
9291
        if (to <= left)
9292
            return this.left.decomposeLeft(to, result);
9293
        result.push(this.left);
9294
        if (this.break) {
9295
            left++;
9296
            if (to >= left)
9297
                result.push(null);
9298
        }
9299
        if (to > left)
9300
            this.right.decomposeLeft(to - left, result);
9301
    }
9302
    decomposeRight(from, result) {
9303
        let left = this.left.length, right = left + this.break;
9304
        if (from >= right)
9305
            return this.right.decomposeRight(from - right, result);
9306
        if (from < left)
9307
            this.left.decomposeRight(from, result);
9308
        if (this.break && from < right)
9309
            result.push(null);
9310
        result.push(this.right);
9311
    }
9312
    balanced(left, right) {
9313
        if (left.size > 2 * right.size || right.size > 2 * left.size)
9314
            return HeightMap.of(this.break ? [left, null, right] : [left, right]);
9315
        this.left = left;
9316
        this.right = right;
9317
        this.height = left.height + right.height;
9318
        this.outdated = left.outdated || right.outdated;
9319
        this.size = left.size + right.size;
9320
        this.length = left.length + this.break + right.length;
9321
        return this;
9322
    }
9323
    updateHeight(oracle, offset = 0, force = false, measured) {
9324
        let { left, right } = this, rightStart = offset + left.length + this.break, rebalance = null;
9325
        if (measured && measured.from <= offset + left.length && measured.more)
9326
            rebalance = left = left.updateHeight(oracle, offset, force, measured);
9327
        else
9328
            left.updateHeight(oracle, offset, force);
9329
        if (measured && measured.from <= rightStart + right.length && measured.more)
9330
            rebalance = right = right.updateHeight(oracle, rightStart, force, measured);
9331
        else
9332
            right.updateHeight(oracle, rightStart, force);
9333
        if (rebalance)
9334
            return this.balanced(left, right);
9335
        this.height = this.left.height + this.right.height;
9336
        this.outdated = false;
9337
        return this;
9338
    }
9339
    toString() { return this.left + (this.break ? " " : "-") + this.right; }
9340
}
9341
function mergeGaps(nodes, around) {
9342
    let before, after;
9343
    if (nodes[around] == null &&
9344
        (before = nodes[around - 1]) instanceof HeightMapGap &&
9345
        (after = nodes[around + 1]) instanceof HeightMapGap)
9346
        nodes.splice(around - 1, 3, new HeightMapGap(before.length + 1 + after.length));
9347
}
9348
const relevantWidgetHeight = 5;
9349
class NodeBuilder {
9350
    constructor(pos, oracle) {
9351
        this.pos = pos;
9352
        this.oracle = oracle;
9353
        this.nodes = [];
9354
        this.lineStart = -1;
9355
        this.lineEnd = -1;
9356
        this.covering = null;
9357
        this.writtenTo = pos;
9358
    }
9359
    get isCovered() {
9360
        return this.covering && this.nodes[this.nodes.length - 1] == this.covering;
9361
    }
9362
    span(_from, to) {
9363
        if (this.lineStart > -1) {
9364
            let end = Math.min(to, this.lineEnd), last = this.nodes[this.nodes.length - 1];
9365
            if (last instanceof HeightMapText)
9366
                last.length += end - this.pos;
9367
            else if (end > this.pos || !this.isCovered)
9368
                this.nodes.push(new HeightMapText(end - this.pos, -1));
9369
            this.writtenTo = end;
9370
            if (to > end) {
9371
                this.nodes.push(null);
9372
                this.writtenTo++;
9373
                this.lineStart = -1;
9374
            }
9375
        }
9376
        this.pos = to;
9377
    }
9378
    point(from, to, deco) {
9379
        if (from < to || deco.heightRelevant) {
9380
            let height = deco.widget ? deco.widget.estimatedHeight : 0;
9381
            let breaks = deco.widget ? deco.widget.lineBreaks : 0;
9382
            if (height < 0)
9383
                height = this.oracle.lineHeight;
9384
            let len = to - from;
9385
            if (deco.block) {
9386
                this.addBlock(new HeightMapBlock(len, height, deco));
9387
            }
9388
            else if (len || breaks || height >= relevantWidgetHeight) {
9389
                this.addLineDeco(height, breaks, len);
9390
            }
9391
        }
9392
        else if (to > from) {
9393
            this.span(from, to);
9394
        }
9395
        if (this.lineEnd > -1 && this.lineEnd < this.pos)
9396
            this.lineEnd = this.oracle.doc.lineAt(this.pos).to;
9397
    }
9398
    enterLine() {
9399
        if (this.lineStart > -1)
9400
            return;
9401
        let { from, to } = this.oracle.doc.lineAt(this.pos);
9402
        this.lineStart = from;
9403
        this.lineEnd = to;
9404
        if (this.writtenTo < from) {
9405
            if (this.writtenTo < from - 1 || this.nodes[this.nodes.length - 1] == null)
9406
                this.nodes.push(this.blankContent(this.writtenTo, from - 1));
9407
            this.nodes.push(null);
9408
        }
9409
        if (this.pos > from)
9410
            this.nodes.push(new HeightMapText(this.pos - from, -1));
9411
        this.writtenTo = this.pos;
9412
    }
9413
    blankContent(from, to) {
9414
        let gap = new HeightMapGap(to - from);
9415
        if (this.oracle.doc.lineAt(from).to == to)
9416
            gap.flags |= 4 /* Flag.SingleLine */;
9417
        return gap;
9418
    }
9419
    ensureLine() {
9420
        this.enterLine();
9421
        let last = this.nodes.length ? this.nodes[this.nodes.length - 1] : null;
9422
        if (last instanceof HeightMapText)
9423
            return last;
9424
        let line = new HeightMapText(0, -1);
9425
        this.nodes.push(line);
9426
        return line;
9427
    }
9428
    addBlock(block) {
9429
        this.enterLine();
9430
        let deco = block.deco;
9431
        if (deco && deco.startSide > 0 && !this.isCovered)
9432
            this.ensureLine();
9433
        this.nodes.push(block);
9434
        this.writtenTo = this.pos = this.pos + block.length;
9435
        if (deco && deco.endSide > 0)
9436
            this.covering = block;
9437
    }
9438
    addLineDeco(height, breaks, length) {
9439
        let line = this.ensureLine();
9440
        line.length += length;
9441
        line.collapsed += length;
9442
        line.widgetHeight = Math.max(line.widgetHeight, height);
9443
        line.breaks += breaks;
9444
        this.writtenTo = this.pos = this.pos + length;
9445
    }
9446
    finish(from) {
9447
        let last = this.nodes.length == 0 ? null : this.nodes[this.nodes.length - 1];
9448
        if (this.lineStart > -1 && !(last instanceof HeightMapText) && !this.isCovered)
9449
            this.nodes.push(new HeightMapText(0, -1));
9450
        else if (this.writtenTo < this.pos || last == null)
9451
            this.nodes.push(this.blankContent(this.writtenTo, this.pos));
9452
        let pos = from;
9453
        for (let node of this.nodes) {
9454
            if (node instanceof HeightMapText)
9455
                node.updateHeight(this.oracle, pos);
9456
            pos += node ? node.length : 1;
9457
        }
9458
        return this.nodes;
9459
    }
9460
    // Always called with a region that on both sides either stretches
9461
    // to a line break or the end of the document.
9462
    // The returned array uses null to indicate line breaks, but never
9463
    // starts or ends in a line break, or has multiple line breaks next
9464
    // to each other.
9465
    static build(oracle, decorations, from, to) {
9466
        let builder = new NodeBuilder(from, oracle);
9467
        RangeSet.spans(decorations, from, to, builder, 0);
9468
        return builder.finish(from);
9469
    }
9470
}
9471
function heightRelevantDecoChanges(a, b, diff) {
9472
    let comp = new DecorationComparator;
9473
    RangeSet.compare(a, b, diff, comp, 0);
9474
    return comp.changes;
9475
}
9476
class DecorationComparator {
9477
    constructor() {
9478
        this.changes = [];
9479
    }
9480
    compareRange() { }
9481
    comparePoint(from, to, a, b) {
9482
        if (from < to || a && a.heightRelevant || b && b.heightRelevant)
9483
            addRange(from, to, this.changes, 5);
9484
    }
9485
}
9486
 
9487
function visiblePixelRange(dom, paddingTop) {
9488
    let rect = dom.getBoundingClientRect();
9489
    let doc = dom.ownerDocument, win = doc.defaultView || window;
9490
    let left = Math.max(0, rect.left), right = Math.min(win.innerWidth, rect.right);
9491
    let top = Math.max(0, rect.top), bottom = Math.min(win.innerHeight, rect.bottom);
9492
    for (let parent = dom.parentNode; parent && parent != doc.body;) {
9493
        if (parent.nodeType == 1) {
9494
            let elt = parent;
9495
            let style = window.getComputedStyle(elt);
9496
            if ((elt.scrollHeight > elt.clientHeight || elt.scrollWidth > elt.clientWidth) &&
9497
                style.overflow != "visible") {
9498
                let parentRect = elt.getBoundingClientRect();
9499
                left = Math.max(left, parentRect.left);
9500
                right = Math.min(right, parentRect.right);
9501
                top = Math.max(top, parentRect.top);
9502
                bottom = parent == dom.parentNode ? parentRect.bottom : Math.min(bottom, parentRect.bottom);
9503
            }
9504
            parent = style.position == "absolute" || style.position == "fixed" ? elt.offsetParent : elt.parentNode;
9505
        }
9506
        else if (parent.nodeType == 11) { // Shadow root
9507
            parent = parent.host;
9508
        }
9509
        else {
9510
            break;
9511
        }
9512
    }
9513
    return { left: left - rect.left, right: Math.max(left, right) - rect.left,
9514
        top: top - (rect.top + paddingTop), bottom: Math.max(top, bottom) - (rect.top + paddingTop) };
9515
}
9516
function fullPixelRange(dom, paddingTop) {
9517
    let rect = dom.getBoundingClientRect();
9518
    return { left: 0, right: rect.right - rect.left,
9519
        top: paddingTop, bottom: rect.bottom - (rect.top + paddingTop) };
9520
}
9521
// Line gaps are placeholder widgets used to hide pieces of overlong
9522
// lines within the viewport, as a kludge to keep the editor
9523
// responsive when a ridiculously long line is loaded into it.
9524
class LineGap {
9525
    constructor(from, to, size) {
9526
        this.from = from;
9527
        this.to = to;
9528
        this.size = size;
9529
    }
9530
    static same(a, b) {
9531
        if (a.length != b.length)
9532
            return false;
9533
        for (let i = 0; i < a.length; i++) {
9534
            let gA = a[i], gB = b[i];
9535
            if (gA.from != gB.from || gA.to != gB.to || gA.size != gB.size)
9536
                return false;
9537
        }
9538
        return true;
9539
    }
9540
    draw(viewState, wrapping) {
9541
        return Decoration.replace({
9542
            widget: new LineGapWidget(this.size * (wrapping ? viewState.scaleY : viewState.scaleX), wrapping)
9543
        }).range(this.from, this.to);
9544
    }
9545
}
9546
class LineGapWidget extends WidgetType {
9547
    constructor(size, vertical) {
9548
        super();
9549
        this.size = size;
9550
        this.vertical = vertical;
9551
    }
9552
    eq(other) { return other.size == this.size && other.vertical == this.vertical; }
9553
    toDOM() {
9554
        let elt = document.createElement("div");
9555
        if (this.vertical) {
9556
            elt.style.height = this.size + "px";
9557
        }
9558
        else {
9559
            elt.style.width = this.size + "px";
9560
            elt.style.height = "2px";
9561
            elt.style.display = "inline-block";
9562
        }
9563
        return elt;
9564
    }
9565
    get estimatedHeight() { return this.vertical ? this.size : -1; }
9566
}
9567
class ViewState {
9568
    constructor(state) {
9569
        this.state = state;
9570
        // These are contentDOM-local coordinates
9571
        this.pixelViewport = { left: 0, right: window.innerWidth, top: 0, bottom: 0 };
9572
        this.inView = true;
9573
        this.paddingTop = 0; // Padding above the document, scaled
9574
        this.paddingBottom = 0; // Padding below the document, scaled
9575
        this.contentDOMWidth = 0; // contentDOM.getBoundingClientRect().width
9576
        this.contentDOMHeight = 0; // contentDOM.getBoundingClientRect().height
9577
        this.editorHeight = 0; // scrollDOM.clientHeight, unscaled
9578
        this.editorWidth = 0; // scrollDOM.clientWidth, unscaled
9579
        this.scrollTop = 0; // Last seen scrollDOM.scrollTop, scaled
9580
        this.scrolledToBottom = true;
9581
        // The CSS-transformation scale of the editor (transformed size /
9582
        // concrete size)
9583
        this.scaleX = 1;
9584
        this.scaleY = 1;
9585
        // The vertical position (document-relative) to which to anchor the
9586
        // scroll position. -1 means anchor to the end of the document.
9587
        this.scrollAnchorPos = 0;
9588
        // The height at the anchor position. Set by the DOM update phase.
9589
        // -1 means no height available.
9590
        this.scrollAnchorHeight = -1;
9591
        // See VP.MaxDOMHeight
9592
        this.scaler = IdScaler;
9593
        this.scrollTarget = null;
9594
        // Briefly set to true when printing, to disable viewport limiting
9595
        this.printing = false;
9596
        // Flag set when editor content was redrawn, so that the next
9597
        // measure stage knows it must read DOM layout
9598
        this.mustMeasureContent = true;
9599
        this.defaultTextDirection = Direction.LTR;
9600
        this.visibleRanges = [];
9601
        // Cursor 'assoc' is only significant when the cursor is on a line
9602
        // wrap point, where it must stick to the character that it is
9603
        // associated with. Since browsers don't provide a reasonable
9604
        // interface to set or query this, when a selection is set that
9605
        // might cause this to be significant, this flag is set. The next
9606
        // measure phase will check whether the cursor is on a line-wrapping
9607
        // boundary and, if so, reset it to make sure it is positioned in
9608
        // the right place.
9609
        this.mustEnforceCursorAssoc = false;
9610
        let guessWrapping = state.facet(contentAttributes).some(v => typeof v != "function" && v.class == "cm-lineWrapping");
9611
        this.heightOracle = new HeightOracle(guessWrapping);
9612
        this.stateDeco = state.facet(decorations).filter(d => typeof d != "function");
9613
        this.heightMap = HeightMap.empty().applyChanges(this.stateDeco, Text.empty, this.heightOracle.setDoc(state.doc), [new ChangedRange(0, 0, 0, state.doc.length)]);
9614
        this.viewport = this.getViewport(0, null);
9615
        this.updateViewportLines();
9616
        this.updateForViewport();
9617
        this.lineGaps = this.ensureLineGaps([]);
9618
        this.lineGapDeco = Decoration.set(this.lineGaps.map(gap => gap.draw(this, false)));
9619
        this.computeVisibleRanges();
9620
    }
9621
    updateForViewport() {
9622
        let viewports = [this.viewport], { main } = this.state.selection;
9623
        for (let i = 0; i <= 1; i++) {
9624
            let pos = i ? main.head : main.anchor;
9625
            if (!viewports.some(({ from, to }) => pos >= from && pos <= to)) {
9626
                let { from, to } = this.lineBlockAt(pos);
9627
                viewports.push(new Viewport(from, to));
9628
            }
9629
        }
9630
        this.viewports = viewports.sort((a, b) => a.from - b.from);
9631
        this.scaler = this.heightMap.height <= 7000000 /* VP.MaxDOMHeight */ ? IdScaler :
9632
            new BigScaler(this.heightOracle, this.heightMap, this.viewports);
9633
    }
9634
    updateViewportLines() {
9635
        this.viewportLines = [];
9636
        this.heightMap.forEachLine(this.viewport.from, this.viewport.to, this.heightOracle.setDoc(this.state.doc), 0, 0, block => {
9637
            this.viewportLines.push(this.scaler.scale == 1 ? block : scaleBlock(block, this.scaler));
9638
        });
9639
    }
9640
    update(update, scrollTarget = null) {
9641
        this.state = update.state;
9642
        let prevDeco = this.stateDeco;
9643
        this.stateDeco = this.state.facet(decorations).filter(d => typeof d != "function");
9644
        let contentChanges = update.changedRanges;
9645
        let heightChanges = ChangedRange.extendWithRanges(contentChanges, heightRelevantDecoChanges(prevDeco, this.stateDeco, update ? update.changes : ChangeSet.empty(this.state.doc.length)));
9646
        let prevHeight = this.heightMap.height;
9647
        let scrollAnchor = this.scrolledToBottom ? null : this.scrollAnchorAt(this.scrollTop);
9648
        this.heightMap = this.heightMap.applyChanges(this.stateDeco, update.startState.doc, this.heightOracle.setDoc(this.state.doc), heightChanges);
9649
        if (this.heightMap.height != prevHeight)
9650
            update.flags |= 2 /* UpdateFlag.Height */;
9651
        if (scrollAnchor) {
9652
            this.scrollAnchorPos = update.changes.mapPos(scrollAnchor.from, -1);
9653
            this.scrollAnchorHeight = scrollAnchor.top;
9654
        }
9655
        else {
9656
            this.scrollAnchorPos = -1;
9657
            this.scrollAnchorHeight = this.heightMap.height;
9658
        }
9659
        let viewport = heightChanges.length ? this.mapViewport(this.viewport, update.changes) : this.viewport;
9660
        if (scrollTarget && (scrollTarget.range.head < viewport.from || scrollTarget.range.head > viewport.to) ||
9661
            !this.viewportIsAppropriate(viewport))
9662
            viewport = this.getViewport(0, scrollTarget);
9663
        let updateLines = !update.changes.empty || (update.flags & 2 /* UpdateFlag.Height */) ||
9664
            viewport.from != this.viewport.from || viewport.to != this.viewport.to;
9665
        this.viewport = viewport;
9666
        this.updateForViewport();
9667
        if (updateLines)
9668
            this.updateViewportLines();
9669
        if (this.lineGaps.length || this.viewport.to - this.viewport.from > (2000 /* LG.Margin */ << 1))
9670
            this.updateLineGaps(this.ensureLineGaps(this.mapLineGaps(this.lineGaps, update.changes)));
9671
        update.flags |= this.computeVisibleRanges();
9672
        if (scrollTarget)
9673
            this.scrollTarget = scrollTarget;
9674
        if (!this.mustEnforceCursorAssoc && update.selectionSet && update.view.lineWrapping &&
9675
            update.state.selection.main.empty && update.state.selection.main.assoc &&
9676
            !update.state.facet(nativeSelectionHidden))
9677
            this.mustEnforceCursorAssoc = true;
9678
    }
9679
    measure(view) {
9680
        let dom = view.contentDOM, style = window.getComputedStyle(dom);
9681
        let oracle = this.heightOracle;
9682
        let whiteSpace = style.whiteSpace;
9683
        this.defaultTextDirection = style.direction == "rtl" ? Direction.RTL : Direction.LTR;
9684
        let refresh = this.heightOracle.mustRefreshForWrapping(whiteSpace);
9685
        let domRect = dom.getBoundingClientRect();
9686
        let measureContent = refresh || this.mustMeasureContent || this.contentDOMHeight != domRect.height;
9687
        this.contentDOMHeight = domRect.height;
9688
        this.mustMeasureContent = false;
9689
        let result = 0, bias = 0;
9690
        if (domRect.width && domRect.height) {
9691
            let { scaleX, scaleY } = getScale(dom, domRect);
9692
            if (scaleX > .005 && Math.abs(this.scaleX - scaleX) > .005 ||
9693
                scaleY > .005 && Math.abs(this.scaleY - scaleY) > .005) {
9694
                this.scaleX = scaleX;
9695
                this.scaleY = scaleY;
9696
                result |= 8 /* UpdateFlag.Geometry */;
9697
                refresh = measureContent = true;
9698
            }
9699
        }
9700
        // Vertical padding
9701
        let paddingTop = (parseInt(style.paddingTop) || 0) * this.scaleY;
9702
        let paddingBottom = (parseInt(style.paddingBottom) || 0) * this.scaleY;
9703
        if (this.paddingTop != paddingTop || this.paddingBottom != paddingBottom) {
9704
            this.paddingTop = paddingTop;
9705
            this.paddingBottom = paddingBottom;
9706
            result |= 8 /* UpdateFlag.Geometry */ | 2 /* UpdateFlag.Height */;
9707
        }
9708
        if (this.editorWidth != view.scrollDOM.clientWidth) {
9709
            if (oracle.lineWrapping)
9710
                measureContent = true;
9711
            this.editorWidth = view.scrollDOM.clientWidth;
9712
            result |= 8 /* UpdateFlag.Geometry */;
9713
        }
9714
        let scrollTop = view.scrollDOM.scrollTop * this.scaleY;
9715
        if (this.scrollTop != scrollTop) {
9716
            this.scrollAnchorHeight = -1;
9717
            this.scrollTop = scrollTop;
9718
        }
9719
        this.scrolledToBottom = isScrolledToBottom(view.scrollDOM);
9720
        // Pixel viewport
9721
        let pixelViewport = (this.printing ? fullPixelRange : visiblePixelRange)(dom, this.paddingTop);
9722
        let dTop = pixelViewport.top - this.pixelViewport.top, dBottom = pixelViewport.bottom - this.pixelViewport.bottom;
9723
        this.pixelViewport = pixelViewport;
9724
        let inView = this.pixelViewport.bottom > this.pixelViewport.top && this.pixelViewport.right > this.pixelViewport.left;
9725
        if (inView != this.inView) {
9726
            this.inView = inView;
9727
            if (inView)
9728
                measureContent = true;
9729
        }
9730
        if (!this.inView && !this.scrollTarget)
9731
            return 0;
9732
        let contentWidth = domRect.width;
9733
        if (this.contentDOMWidth != contentWidth || this.editorHeight != view.scrollDOM.clientHeight) {
9734
            this.contentDOMWidth = domRect.width;
9735
            this.editorHeight = view.scrollDOM.clientHeight;
9736
            result |= 8 /* UpdateFlag.Geometry */;
9737
        }
9738
        if (measureContent) {
9739
            let lineHeights = view.docView.measureVisibleLineHeights(this.viewport);
9740
            if (oracle.mustRefreshForHeights(lineHeights))
9741
                refresh = true;
9742
            if (refresh || oracle.lineWrapping && Math.abs(contentWidth - this.contentDOMWidth) > oracle.charWidth) {
9743
                let { lineHeight, charWidth, textHeight } = view.docView.measureTextSize();
9744
                refresh = lineHeight > 0 && oracle.refresh(whiteSpace, lineHeight, charWidth, textHeight, contentWidth / charWidth, lineHeights);
9745
                if (refresh) {
9746
                    view.docView.minWidth = 0;
9747
                    result |= 8 /* UpdateFlag.Geometry */;
9748
                }
9749
            }
9750
            if (dTop > 0 && dBottom > 0)
9751
                bias = Math.max(dTop, dBottom);
9752
            else if (dTop < 0 && dBottom < 0)
9753
                bias = Math.min(dTop, dBottom);
9754
            oracle.heightChanged = false;
9755
            for (let vp of this.viewports) {
9756
                let heights = vp.from == this.viewport.from ? lineHeights : view.docView.measureVisibleLineHeights(vp);
9757
                this.heightMap = (refresh ? HeightMap.empty().applyChanges(this.stateDeco, Text.empty, this.heightOracle, [new ChangedRange(0, 0, 0, view.state.doc.length)]) : this.heightMap).updateHeight(oracle, 0, refresh, new MeasuredHeights(vp.from, heights));
9758
            }
9759
            if (oracle.heightChanged)
9760
                result |= 2 /* UpdateFlag.Height */;
9761
        }
9762
        let viewportChange = !this.viewportIsAppropriate(this.viewport, bias) ||
9763
            this.scrollTarget && (this.scrollTarget.range.head < this.viewport.from ||
9764
                this.scrollTarget.range.head > this.viewport.to);
9765
        if (viewportChange)
9766
            this.viewport = this.getViewport(bias, this.scrollTarget);
9767
        this.updateForViewport();
9768
        if ((result & 2 /* UpdateFlag.Height */) || viewportChange)
9769
            this.updateViewportLines();
9770
        if (this.lineGaps.length || this.viewport.to - this.viewport.from > (2000 /* LG.Margin */ << 1))
9771
            this.updateLineGaps(this.ensureLineGaps(refresh ? [] : this.lineGaps, view));
9772
        result |= this.computeVisibleRanges();
9773
        if (this.mustEnforceCursorAssoc) {
9774
            this.mustEnforceCursorAssoc = false;
9775
            // This is done in the read stage, because moving the selection
9776
            // to a line end is going to trigger a layout anyway, so it
9777
            // can't be a pure write. It should be rare that it does any
9778
            // writing.
9779
            view.docView.enforceCursorAssoc();
9780
        }
9781
        return result;
9782
    }
9783
    get visibleTop() { return this.scaler.fromDOM(this.pixelViewport.top); }
9784
    get visibleBottom() { return this.scaler.fromDOM(this.pixelViewport.bottom); }
9785
    getViewport(bias, scrollTarget) {
9786
        // This will divide VP.Margin between the top and the
9787
        // bottom, depending on the bias (the change in viewport position
9788
        // since the last update). It'll hold a number between 0 and 1
9789
        let marginTop = 0.5 - Math.max(-0.5, Math.min(0.5, bias / 1000 /* VP.Margin */ / 2));
9790
        let map = this.heightMap, oracle = this.heightOracle;
9791
        let { visibleTop, visibleBottom } = this;
9792
        let viewport = new Viewport(map.lineAt(visibleTop - marginTop * 1000 /* VP.Margin */, QueryType$1.ByHeight, oracle, 0, 0).from, map.lineAt(visibleBottom + (1 - marginTop) * 1000 /* VP.Margin */, QueryType$1.ByHeight, oracle, 0, 0).to);
9793
        // If scrollTarget is given, make sure the viewport includes that position
9794
        if (scrollTarget) {
9795
            let { head } = scrollTarget.range;
9796
            if (head < viewport.from || head > viewport.to) {
9797
                let viewHeight = Math.min(this.editorHeight, this.pixelViewport.bottom - this.pixelViewport.top);
9798
                let block = map.lineAt(head, QueryType$1.ByPos, oracle, 0, 0), topPos;
9799
                if (scrollTarget.y == "center")
9800
                    topPos = (block.top + block.bottom) / 2 - viewHeight / 2;
9801
                else if (scrollTarget.y == "start" || scrollTarget.y == "nearest" && head < viewport.from)
9802
                    topPos = block.top;
9803
                else
9804
                    topPos = block.bottom - viewHeight;
9805
                viewport = new Viewport(map.lineAt(topPos - 1000 /* VP.Margin */ / 2, QueryType$1.ByHeight, oracle, 0, 0).from, map.lineAt(topPos + viewHeight + 1000 /* VP.Margin */ / 2, QueryType$1.ByHeight, oracle, 0, 0).to);
9806
            }
9807
        }
9808
        return viewport;
9809
    }
9810
    mapViewport(viewport, changes) {
9811
        let from = changes.mapPos(viewport.from, -1), to = changes.mapPos(viewport.to, 1);
9812
        return new Viewport(this.heightMap.lineAt(from, QueryType$1.ByPos, this.heightOracle, 0, 0).from, this.heightMap.lineAt(to, QueryType$1.ByPos, this.heightOracle, 0, 0).to);
9813
    }
9814
    // Checks if a given viewport covers the visible part of the
9815
    // document and not too much beyond that.
9816
    viewportIsAppropriate({ from, to }, bias = 0) {
9817
        if (!this.inView)
9818
            return true;
9819
        let { top } = this.heightMap.lineAt(from, QueryType$1.ByPos, this.heightOracle, 0, 0);
9820
        let { bottom } = this.heightMap.lineAt(to, QueryType$1.ByPos, this.heightOracle, 0, 0);
9821
        let { visibleTop, visibleBottom } = this;
9822
        return (from == 0 || top <= visibleTop - Math.max(10 /* VP.MinCoverMargin */, Math.min(-bias, 250 /* VP.MaxCoverMargin */))) &&
9823
            (to == this.state.doc.length ||
9824
                bottom >= visibleBottom + Math.max(10 /* VP.MinCoverMargin */, Math.min(bias, 250 /* VP.MaxCoverMargin */))) &&
9825
            (top > visibleTop - 2 * 1000 /* VP.Margin */ && bottom < visibleBottom + 2 * 1000 /* VP.Margin */);
9826
    }
9827
    mapLineGaps(gaps, changes) {
9828
        if (!gaps.length || changes.empty)
9829
            return gaps;
9830
        let mapped = [];
9831
        for (let gap of gaps)
9832
            if (!changes.touchesRange(gap.from, gap.to))
9833
                mapped.push(new LineGap(changes.mapPos(gap.from), changes.mapPos(gap.to), gap.size));
9834
        return mapped;
9835
    }
9836
    // Computes positions in the viewport where the start or end of a
9837
    // line should be hidden, trying to reuse existing line gaps when
9838
    // appropriate to avoid unneccesary redraws.
9839
    // Uses crude character-counting for the positioning and sizing,
9840
    // since actual DOM coordinates aren't always available and
9841
    // predictable. Relies on generous margins (see LG.Margin) to hide
9842
    // the artifacts this might produce from the user.
9843
    ensureLineGaps(current, mayMeasure) {
9844
        let wrapping = this.heightOracle.lineWrapping;
9845
        let margin = wrapping ? 10000 /* LG.MarginWrap */ : 2000 /* LG.Margin */, halfMargin = margin >> 1, doubleMargin = margin << 1;
9846
        // The non-wrapping logic won't work at all in predominantly right-to-left text.
9847
        if (this.defaultTextDirection != Direction.LTR && !wrapping)
9848
            return [];
9849
        let gaps = [];
9850
        let addGap = (from, to, line, structure) => {
9851
            if (to - from < halfMargin)
9852
                return;
9853
            let sel = this.state.selection.main, avoid = [sel.from];
9854
            if (!sel.empty)
9855
                avoid.push(sel.to);
9856
            for (let pos of avoid) {
9857
                if (pos > from && pos < to) {
9858
                    addGap(from, pos - 10 /* LG.SelectionMargin */, line, structure);
9859
                    addGap(pos + 10 /* LG.SelectionMargin */, to, line, structure);
9860
                    return;
9861
                }
9862
            }
9863
            let gap = find(current, gap => gap.from >= line.from && gap.to <= line.to &&
9864
                Math.abs(gap.from - from) < halfMargin && Math.abs(gap.to - to) < halfMargin &&
9865
                !avoid.some(pos => gap.from < pos && gap.to > pos));
9866
            if (!gap) {
9867
                // When scrolling down, snap gap ends to line starts to avoid shifts in wrapping
9868
                if (to < line.to && mayMeasure && wrapping &&
9869
                    mayMeasure.visibleRanges.some(r => r.from <= to && r.to >= to)) {
9870
                    let lineStart = mayMeasure.moveToLineBoundary(EditorSelection.cursor(to), false, true).head;
9871
                    if (lineStart > from)
9872
                        to = lineStart;
9873
                }
9874
                gap = new LineGap(from, to, this.gapSize(line, from, to, structure));
9875
            }
9876
            gaps.push(gap);
9877
        };
9878
        for (let line of this.viewportLines) {
9879
            if (line.length < doubleMargin)
9880
                continue;
9881
            let structure = lineStructure(line.from, line.to, this.stateDeco);
9882
            if (structure.total < doubleMargin)
9883
                continue;
9884
            let target = this.scrollTarget ? this.scrollTarget.range.head : null;
9885
            let viewFrom, viewTo;
9886
            if (wrapping) {
9887
                let marginHeight = (margin / this.heightOracle.lineLength) * this.heightOracle.lineHeight;
9888
                let top, bot;
9889
                if (target != null) {
9890
                    let targetFrac = findFraction(structure, target);
9891
                    let spaceFrac = ((this.visibleBottom - this.visibleTop) / 2 + marginHeight) / line.height;
9892
                    top = targetFrac - spaceFrac;
9893
                    bot = targetFrac + spaceFrac;
9894
                }
9895
                else {
9896
                    top = (this.visibleTop - line.top - marginHeight) / line.height;
9897
                    bot = (this.visibleBottom - line.top + marginHeight) / line.height;
9898
                }
9899
                viewFrom = findPosition(structure, top);
9900
                viewTo = findPosition(structure, bot);
9901
            }
9902
            else {
9903
                let totalWidth = structure.total * this.heightOracle.charWidth;
9904
                let marginWidth = margin * this.heightOracle.charWidth;
9905
                let left, right;
9906
                if (target != null) {
9907
                    let targetFrac = findFraction(structure, target);
9908
                    let spaceFrac = ((this.pixelViewport.right - this.pixelViewport.left) / 2 + marginWidth) / totalWidth;
9909
                    left = targetFrac - spaceFrac;
9910
                    right = targetFrac + spaceFrac;
9911
                }
9912
                else {
9913
                    left = (this.pixelViewport.left - marginWidth) / totalWidth;
9914
                    right = (this.pixelViewport.right + marginWidth) / totalWidth;
9915
                }
9916
                viewFrom = findPosition(structure, left);
9917
                viewTo = findPosition(structure, right);
9918
            }
9919
            if (viewFrom > line.from)
9920
                addGap(line.from, viewFrom, line, structure);
9921
            if (viewTo < line.to)
9922
                addGap(viewTo, line.to, line, structure);
9923
        }
9924
        return gaps;
9925
    }
9926
    gapSize(line, from, to, structure) {
9927
        let fraction = findFraction(structure, to) - findFraction(structure, from);
9928
        if (this.heightOracle.lineWrapping) {
9929
            return line.height * fraction;
9930
        }
9931
        else {
9932
            return structure.total * this.heightOracle.charWidth * fraction;
9933
        }
9934
    }
9935
    updateLineGaps(gaps) {
9936
        if (!LineGap.same(gaps, this.lineGaps)) {
9937
            this.lineGaps = gaps;
9938
            this.lineGapDeco = Decoration.set(gaps.map(gap => gap.draw(this, this.heightOracle.lineWrapping)));
9939
        }
9940
    }
9941
    computeVisibleRanges() {
9942
        let deco = this.stateDeco;
9943
        if (this.lineGaps.length)
9944
            deco = deco.concat(this.lineGapDeco);
9945
        let ranges = [];
9946
        RangeSet.spans(deco, this.viewport.from, this.viewport.to, {
9947
            span(from, to) { ranges.push({ from, to }); },
9948
            point() { }
9949
        }, 20);
9950
        let changed = ranges.length != this.visibleRanges.length ||
9951
            this.visibleRanges.some((r, i) => r.from != ranges[i].from || r.to != ranges[i].to);
9952
        this.visibleRanges = ranges;
9953
        return changed ? 4 /* UpdateFlag.Viewport */ : 0;
9954
    }
9955
    lineBlockAt(pos) {
9956
        return (pos >= this.viewport.from && pos <= this.viewport.to && this.viewportLines.find(b => b.from <= pos && b.to >= pos)) ||
9957
            scaleBlock(this.heightMap.lineAt(pos, QueryType$1.ByPos, this.heightOracle, 0, 0), this.scaler);
9958
    }
9959
    lineBlockAtHeight(height) {
9960
        return scaleBlock(this.heightMap.lineAt(this.scaler.fromDOM(height), QueryType$1.ByHeight, this.heightOracle, 0, 0), this.scaler);
9961
    }
9962
    scrollAnchorAt(scrollTop) {
9963
        let block = this.lineBlockAtHeight(scrollTop + 8);
9964
        return block.from >= this.viewport.from || this.viewportLines[0].top - scrollTop > 200 ? block : this.viewportLines[0];
9965
    }
9966
    elementAtHeight(height) {
9967
        return scaleBlock(this.heightMap.blockAt(this.scaler.fromDOM(height), this.heightOracle, 0, 0), this.scaler);
9968
    }
9969
    get docHeight() {
9970
        return this.scaler.toDOM(this.heightMap.height);
9971
    }
9972
    get contentHeight() {
9973
        return this.docHeight + this.paddingTop + this.paddingBottom;
9974
    }
9975
}
9976
class Viewport {
9977
    constructor(from, to) {
9978
        this.from = from;
9979
        this.to = to;
9980
    }
9981
}
9982
function lineStructure(from, to, stateDeco) {
9983
    let ranges = [], pos = from, total = 0;
9984
    RangeSet.spans(stateDeco, from, to, {
9985
        span() { },
9986
        point(from, to) {
9987
            if (from > pos) {
9988
                ranges.push({ from: pos, to: from });
9989
                total += from - pos;
9990
            }
9991
            pos = to;
9992
        }
9993
    }, 20); // We're only interested in collapsed ranges of a significant size
9994
    if (pos < to) {
9995
        ranges.push({ from: pos, to });
9996
        total += to - pos;
9997
    }
9998
    return { total, ranges };
9999
}
10000
function findPosition({ total, ranges }, ratio) {
10001
    if (ratio <= 0)
10002
        return ranges[0].from;
10003
    if (ratio >= 1)
10004
        return ranges[ranges.length - 1].to;
10005
    let dist = Math.floor(total * ratio);
10006
    for (let i = 0;; i++) {
10007
        let { from, to } = ranges[i], size = to - from;
10008
        if (dist <= size)
10009
            return from + dist;
10010
        dist -= size;
10011
    }
10012
}
10013
function findFraction(structure, pos) {
10014
    let counted = 0;
10015
    for (let { from, to } of structure.ranges) {
10016
        if (pos <= to) {
10017
            counted += pos - from;
10018
            break;
10019
        }
10020
        counted += to - from;
10021
    }
10022
    return counted / structure.total;
10023
}
10024
function find(array, f) {
10025
    for (let val of array)
10026
        if (f(val))
10027
            return val;
10028
    return undefined;
10029
}
10030
// Don't scale when the document height is within the range of what
10031
// the DOM can handle.
10032
const IdScaler = {
10033
    toDOM(n) { return n; },
10034
    fromDOM(n) { return n; },
10035
    scale: 1
10036
};
10037
// When the height is too big (> VP.MaxDOMHeight), scale down the
10038
// regions outside the viewports so that the total height is
10039
// VP.MaxDOMHeight.
10040
class BigScaler {
10041
    constructor(oracle, heightMap, viewports) {
10042
        let vpHeight = 0, base = 0, domBase = 0;
10043
        this.viewports = viewports.map(({ from, to }) => {
10044
            let top = heightMap.lineAt(from, QueryType$1.ByPos, oracle, 0, 0).top;
10045
            let bottom = heightMap.lineAt(to, QueryType$1.ByPos, oracle, 0, 0).bottom;
10046
            vpHeight += bottom - top;
10047
            return { from, to, top, bottom, domTop: 0, domBottom: 0 };
10048
        });
10049
        this.scale = (7000000 /* VP.MaxDOMHeight */ - vpHeight) / (heightMap.height - vpHeight);
10050
        for (let obj of this.viewports) {
10051
            obj.domTop = domBase + (obj.top - base) * this.scale;
10052
            domBase = obj.domBottom = obj.domTop + (obj.bottom - obj.top);
10053
            base = obj.bottom;
10054
        }
10055
    }
10056
    toDOM(n) {
10057
        for (let i = 0, base = 0, domBase = 0;; i++) {
10058
            let vp = i < this.viewports.length ? this.viewports[i] : null;
10059
            if (!vp || n < vp.top)
10060
                return domBase + (n - base) * this.scale;
10061
            if (n <= vp.bottom)
10062
                return vp.domTop + (n - vp.top);
10063
            base = vp.bottom;
10064
            domBase = vp.domBottom;
10065
        }
10066
    }
10067
    fromDOM(n) {
10068
        for (let i = 0, base = 0, domBase = 0;; i++) {
10069
            let vp = i < this.viewports.length ? this.viewports[i] : null;
10070
            if (!vp || n < vp.domTop)
10071
                return base + (n - domBase) / this.scale;
10072
            if (n <= vp.domBottom)
10073
                return vp.top + (n - vp.domTop);
10074
            base = vp.bottom;
10075
            domBase = vp.domBottom;
10076
        }
10077
    }
10078
}
10079
function scaleBlock(block, scaler) {
10080
    if (scaler.scale == 1)
10081
        return block;
10082
    let bTop = scaler.toDOM(block.top), bBottom = scaler.toDOM(block.bottom);
10083
    return new BlockInfo(block.from, block.length, bTop, bBottom - bTop, Array.isArray(block._content) ? block._content.map(b => scaleBlock(b, scaler)) : block._content);
10084
}
10085
 
10086
const theme = /*@__PURE__*/Facet.define({ combine: strs => strs.join(" ") });
10087
const darkTheme = /*@__PURE__*/Facet.define({ combine: values => values.indexOf(true) > -1 });
10088
const baseThemeID = /*@__PURE__*/StyleModule.newName(), baseLightID = /*@__PURE__*/StyleModule.newName(), baseDarkID = /*@__PURE__*/StyleModule.newName();
10089
const lightDarkIDs = { "&light": "." + baseLightID, "&dark": "." + baseDarkID };
10090
function buildTheme(main, spec, scopes) {
10091
    return new StyleModule(spec, {
10092
        finish(sel) {
10093
            return /&/.test(sel) ? sel.replace(/&\w*/, m => {
10094
                if (m == "&")
10095
                    return main;
10096
                if (!scopes || !scopes[m])
10097
                    throw new RangeError(`Unsupported selector: ${m}`);
10098
                return scopes[m];
10099
            }) : main + " " + sel;
10100
        }
10101
    });
10102
}
10103
const baseTheme$1$3 = /*@__PURE__*/buildTheme("." + baseThemeID, {
10104
    "&": {
10105
        position: "relative !important",
10106
        boxSizing: "border-box",
10107
        "&.cm-focused": {
10108
            // Provide a simple default outline to make sure a focused
10109
            // editor is visually distinct. Can't leave the default behavior
10110
            // because that will apply to the content element, which is
10111
            // inside the scrollable container and doesn't include the
10112
            // gutters. We also can't use an 'auto' outline, since those
10113
            // are, for some reason, drawn behind the element content, which
10114
            // will cause things like the active line background to cover
10115
            // the outline (#297).
10116
            outline: "1px dotted #212121"
10117
        },
10118
        display: "flex !important",
10119
        flexDirection: "column"
10120
    },
10121
    ".cm-scroller": {
10122
        display: "flex !important",
10123
        alignItems: "flex-start !important",
10124
        fontFamily: "monospace",
10125
        lineHeight: 1.4,
10126
        height: "100%",
10127
        overflowX: "auto",
10128
        position: "relative",
10129
        zIndex: 0
10130
    },
10131
    ".cm-content": {
10132
        margin: 0,
10133
        flexGrow: 2,
10134
        flexShrink: 0,
10135
        display: "block",
10136
        whiteSpace: "pre",
10137
        wordWrap: "normal", // https://github.com/codemirror/dev/issues/456
10138
        boxSizing: "border-box",
10139
        minHeight: "100%",
10140
        padding: "4px 0",
10141
        outline: "none",
10142
        "&[contenteditable=true]": {
10143
            WebkitUserModify: "read-write-plaintext-only",
10144
        }
10145
    },
10146
    ".cm-lineWrapping": {
10147
        whiteSpace_fallback: "pre-wrap", // For IE
10148
        whiteSpace: "break-spaces",
10149
        wordBreak: "break-word", // For Safari, which doesn't support overflow-wrap: anywhere
10150
        overflowWrap: "anywhere",
10151
        flexShrink: 1
10152
    },
10153
    "&light .cm-content": { caretColor: "black" },
10154
    "&dark .cm-content": { caretColor: "white" },
10155
    ".cm-line": {
10156
        display: "block",
10157
        padding: "0 2px 0 6px"
10158
    },
10159
    ".cm-layer": {
10160
        position: "absolute",
10161
        left: 0,
10162
        top: 0,
10163
        contain: "size style",
10164
        "& > *": {
10165
            position: "absolute"
10166
        }
10167
    },
10168
    "&light .cm-selectionBackground": {
10169
        background: "#d9d9d9"
10170
    },
10171
    "&dark .cm-selectionBackground": {
10172
        background: "#222"
10173
    },
10174
    "&light.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground": {
10175
        background: "#d7d4f0"
10176
    },
10177
    "&dark.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground": {
10178
        background: "#233"
10179
    },
10180
    ".cm-cursorLayer": {
10181
        pointerEvents: "none"
10182
    },
10183
    "&.cm-focused > .cm-scroller > .cm-cursorLayer": {
10184
        animation: "steps(1) cm-blink 1.2s infinite"
10185
    },
10186
    // Two animations defined so that we can switch between them to
10187
    // restart the animation without forcing another style
10188
    // recomputation.
10189
    "@keyframes cm-blink": { "0%": {}, "50%": { opacity: 0 }, "100%": {} },
10190
    "@keyframes cm-blink2": { "0%": {}, "50%": { opacity: 0 }, "100%": {} },
10191
    ".cm-cursor, .cm-dropCursor": {
10192
        borderLeft: "1.2px solid black",
10193
        marginLeft: "-0.6px",
10194
        pointerEvents: "none",
10195
    },
10196
    ".cm-cursor": {
10197
        display: "none"
10198
    },
10199
    "&dark .cm-cursor": {
10200
        borderLeftColor: "#444"
10201
    },
10202
    ".cm-dropCursor": {
10203
        position: "absolute"
10204
    },
10205
    "&.cm-focused > .cm-scroller > .cm-cursorLayer .cm-cursor": {
10206
        display: "block"
10207
    },
10208
    ".cm-iso": {
10209
        unicodeBidi: "isolate"
10210
    },
10211
    ".cm-announced": {
10212
        position: "fixed",
10213
        top: "-10000px"
10214
    },
10215
    "@media print": {
10216
        ".cm-announced": { display: "none" }
10217
    },
10218
    "&light .cm-activeLine": { backgroundColor: "#cceeff44" },
10219
    "&dark .cm-activeLine": { backgroundColor: "#99eeff33" },
10220
    "&light .cm-specialChar": { color: "red" },
10221
    "&dark .cm-specialChar": { color: "#f78" },
10222
    ".cm-gutters": {
10223
        flexShrink: 0,
10224
        display: "flex",
10225
        height: "100%",
10226
        boxSizing: "border-box",
10227
        insetInlineStart: 0,
10228
        zIndex: 200
10229
    },
10230
    "&light .cm-gutters": {
10231
        backgroundColor: "#f5f5f5",
10232
        color: "#6c6c6c",
10233
        borderRight: "1px solid #ddd"
10234
    },
10235
    "&dark .cm-gutters": {
10236
        backgroundColor: "#333338",
10237
        color: "#ccc"
10238
    },
10239
    ".cm-gutter": {
10240
        display: "flex !important", // Necessary -- prevents margin collapsing
10241
        flexDirection: "column",
10242
        flexShrink: 0,
10243
        boxSizing: "border-box",
10244
        minHeight: "100%",
10245
        overflow: "hidden"
10246
    },
10247
    ".cm-gutterElement": {
10248
        boxSizing: "border-box"
10249
    },
10250
    ".cm-lineNumbers .cm-gutterElement": {
10251
        padding: "0 3px 0 5px",
10252
        minWidth: "20px",
10253
        textAlign: "right",
10254
        whiteSpace: "nowrap"
10255
    },
10256
    "&light .cm-activeLineGutter": {
10257
        backgroundColor: "#e2f2ff"
10258
    },
10259
    "&dark .cm-activeLineGutter": {
10260
        backgroundColor: "#222227"
10261
    },
10262
    ".cm-panels": {
10263
        boxSizing: "border-box",
10264
        position: "sticky",
10265
        left: 0,
10266
        right: 0
10267
    },
10268
    "&light .cm-panels": {
10269
        backgroundColor: "#f5f5f5",
10270
        color: "black"
10271
    },
10272
    "&light .cm-panels-top": {
10273
        borderBottom: "1px solid #ddd"
10274
    },
10275
    "&light .cm-panels-bottom": {
10276
        borderTop: "1px solid #ddd"
10277
    },
10278
    "&dark .cm-panels": {
10279
        backgroundColor: "#333338",
10280
        color: "white"
10281
    },
10282
    ".cm-tab": {
10283
        display: "inline-block",
10284
        overflow: "hidden",
10285
        verticalAlign: "bottom"
10286
    },
10287
    ".cm-widgetBuffer": {
10288
        verticalAlign: "text-top",
10289
        height: "1em",
10290
        width: 0,
10291
        display: "inline"
10292
    },
10293
    ".cm-placeholder": {
10294
        color: "#888",
10295
        display: "inline-block",
10296
        verticalAlign: "top",
10297
    },
10298
    ".cm-highlightSpace:before": {
10299
        content: "attr(data-display)",
10300
        position: "absolute",
10301
        pointerEvents: "none",
10302
        color: "#888"
10303
    },
10304
    ".cm-highlightTab": {
10305
        backgroundImage: `url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="200" height="20"><path stroke="%23888" stroke-width="1" fill="none" d="M1 10H196L190 5M190 15L196 10M197 4L197 16"/></svg>')`,
10306
        backgroundSize: "auto 100%",
10307
        backgroundPosition: "right 90%",
10308
        backgroundRepeat: "no-repeat"
10309
    },
10310
    ".cm-trailingSpace": {
10311
        backgroundColor: "#ff332255"
10312
    },
10313
    ".cm-button": {
10314
        verticalAlign: "middle",
10315
        color: "inherit",
10316
        fontSize: "70%",
10317
        padding: ".2em 1em",
10318
        borderRadius: "1px"
10319
    },
10320
    "&light .cm-button": {
10321
        backgroundImage: "linear-gradient(#eff1f5, #d9d9df)",
10322
        border: "1px solid #888",
10323
        "&:active": {
10324
            backgroundImage: "linear-gradient(#b4b4b4, #d0d3d6)"
10325
        }
10326
    },
10327
    "&dark .cm-button": {
10328
        backgroundImage: "linear-gradient(#393939, #111)",
10329
        border: "1px solid #888",
10330
        "&:active": {
10331
            backgroundImage: "linear-gradient(#111, #333)"
10332
        }
10333
    },
10334
    ".cm-textfield": {
10335
        verticalAlign: "middle",
10336
        color: "inherit",
10337
        fontSize: "70%",
10338
        border: "1px solid silver",
10339
        padding: ".2em .5em"
10340
    },
10341
    "&light .cm-textfield": {
10342
        backgroundColor: "white"
10343
    },
10344
    "&dark .cm-textfield": {
10345
        border: "1px solid #555",
10346
        backgroundColor: "inherit"
10347
    }
10348
}, lightDarkIDs);
10349
 
10350
const LineBreakPlaceholder = "\uffff";
10351
class DOMReader {
10352
    constructor(points, state) {
10353
        this.points = points;
10354
        this.text = "";
10355
        this.lineSeparator = state.facet(EditorState.lineSeparator);
10356
    }
10357
    append(text) {
10358
        this.text += text;
10359
    }
10360
    lineBreak() {
10361
        this.text += LineBreakPlaceholder;
10362
    }
10363
    readRange(start, end) {
10364
        if (!start)
10365
            return this;
10366
        let parent = start.parentNode;
10367
        for (let cur = start;;) {
10368
            this.findPointBefore(parent, cur);
10369
            let oldLen = this.text.length;
10370
            this.readNode(cur);
10371
            let next = cur.nextSibling;
10372
            if (next == end)
10373
                break;
10374
            let view = ContentView.get(cur), nextView = ContentView.get(next);
10375
            if (view && nextView ? view.breakAfter :
10376
                (view ? view.breakAfter : isBlockElement(cur)) ||
10377
                    (isBlockElement(next) && (cur.nodeName != "BR" || cur.cmIgnore) && this.text.length > oldLen))
10378
                this.lineBreak();
10379
            cur = next;
10380
        }
10381
        this.findPointBefore(parent, end);
10382
        return this;
10383
    }
10384
    readTextNode(node) {
10385
        let text = node.nodeValue;
10386
        for (let point of this.points)
10387
            if (point.node == node)
10388
                point.pos = this.text.length + Math.min(point.offset, text.length);
10389
        for (let off = 0, re = this.lineSeparator ? null : /\r\n?|\n/g;;) {
10390
            let nextBreak = -1, breakSize = 1, m;
10391
            if (this.lineSeparator) {
10392
                nextBreak = text.indexOf(this.lineSeparator, off);
10393
                breakSize = this.lineSeparator.length;
10394
            }
10395
            else if (m = re.exec(text)) {
10396
                nextBreak = m.index;
10397
                breakSize = m[0].length;
10398
            }
10399
            this.append(text.slice(off, nextBreak < 0 ? text.length : nextBreak));
10400
            if (nextBreak < 0)
10401
                break;
10402
            this.lineBreak();
10403
            if (breakSize > 1)
10404
                for (let point of this.points)
10405
                    if (point.node == node && point.pos > this.text.length)
10406
                        point.pos -= breakSize - 1;
10407
            off = nextBreak + breakSize;
10408
        }
10409
    }
10410
    readNode(node) {
10411
        if (node.cmIgnore)
10412
            return;
10413
        let view = ContentView.get(node);
10414
        let fromView = view && view.overrideDOMText;
10415
        if (fromView != null) {
10416
            this.findPointInside(node, fromView.length);
10417
            for (let i = fromView.iter(); !i.next().done;) {
10418
                if (i.lineBreak)
10419
                    this.lineBreak();
10420
                else
10421
                    this.append(i.value);
10422
            }
10423
        }
10424
        else if (node.nodeType == 3) {
10425
            this.readTextNode(node);
10426
        }
10427
        else if (node.nodeName == "BR") {
10428
            if (node.nextSibling)
10429
                this.lineBreak();
10430
        }
10431
        else if (node.nodeType == 1) {
10432
            this.readRange(node.firstChild, null);
10433
        }
10434
    }
10435
    findPointBefore(node, next) {
10436
        for (let point of this.points)
10437
            if (point.node == node && node.childNodes[point.offset] == next)
10438
                point.pos = this.text.length;
10439
    }
10440
    findPointInside(node, length) {
10441
        for (let point of this.points)
10442
            if (node.nodeType == 3 ? point.node == node : node.contains(point.node))
10443
                point.pos = this.text.length + (isAtEnd(node, point.node, point.offset) ? length : 0);
10444
    }
10445
}
10446
function isAtEnd(parent, node, offset) {
10447
    for (;;) {
10448
        if (!node || offset < maxOffset(node))
10449
            return false;
10450
        if (node == parent)
10451
            return true;
10452
        offset = domIndex(node) + 1;
10453
        node = node.parentNode;
10454
    }
10455
}
10456
class DOMPoint {
10457
    constructor(node, offset) {
10458
        this.node = node;
10459
        this.offset = offset;
10460
        this.pos = -1;
10461
    }
10462
}
10463
 
10464
class DOMChange {
10465
    constructor(view, start, end, typeOver) {
10466
        this.typeOver = typeOver;
10467
        this.bounds = null;
10468
        this.text = "";
10469
        let { impreciseHead: iHead, impreciseAnchor: iAnchor } = view.docView;
10470
        if (view.state.readOnly && start > -1) {
10471
            // Ignore changes when the editor is read-only
10472
            this.newSel = null;
10473
        }
10474
        else if (start > -1 && (this.bounds = view.docView.domBoundsAround(start, end, 0))) {
10475
            let selPoints = iHead || iAnchor ? [] : selectionPoints(view);
10476
            let reader = new DOMReader(selPoints, view.state);
10477
            reader.readRange(this.bounds.startDOM, this.bounds.endDOM);
10478
            this.text = reader.text;
10479
            this.newSel = selectionFromPoints(selPoints, this.bounds.from);
10480
        }
10481
        else {
10482
            let domSel = view.observer.selectionRange;
10483
            let head = iHead && iHead.node == domSel.focusNode && iHead.offset == domSel.focusOffset ||
10484
                !contains(view.contentDOM, domSel.focusNode)
10485
                ? view.state.selection.main.head
10486
                : view.docView.posFromDOM(domSel.focusNode, domSel.focusOffset);
10487
            let anchor = iAnchor && iAnchor.node == domSel.anchorNode && iAnchor.offset == domSel.anchorOffset ||
10488
                !contains(view.contentDOM, domSel.anchorNode)
10489
                ? view.state.selection.main.anchor
10490
                : view.docView.posFromDOM(domSel.anchorNode, domSel.anchorOffset);
10491
            // iOS will refuse to select the block gaps when doing
10492
            // select-all.
10493
            // Chrome will put the selection *inside* them, confusing
10494
            // posFromDOM
10495
            let vp = view.viewport;
10496
            if ((browser.ios || browser.chrome) && view.state.selection.main.empty && head != anchor &&
10497
                (vp.from > 0 || vp.to < view.state.doc.length)) {
10498
                let from = Math.min(head, anchor), to = Math.max(head, anchor);
10499
                let offFrom = vp.from - from, offTo = vp.to - to;
10500
                if ((offFrom == 0 || offFrom == 1 || from == 0) && (offTo == 0 || offTo == -1 || to == view.state.doc.length)) {
10501
                    head = 0;
10502
                    anchor = view.state.doc.length;
10503
                }
10504
            }
10505
            this.newSel = EditorSelection.single(anchor, head);
10506
        }
10507
    }
10508
}
10509
function applyDOMChange(view, domChange) {
10510
    let change;
10511
    let { newSel } = domChange, sel = view.state.selection.main;
10512
    let lastKey = view.inputState.lastKeyTime > Date.now() - 100 ? view.inputState.lastKeyCode : -1;
10513
    if (domChange.bounds) {
10514
        let { from, to } = domChange.bounds;
10515
        let preferredPos = sel.from, preferredSide = null;
10516
        // Prefer anchoring to end when Backspace is pressed (or, on
10517
        // Android, when something was deleted)
10518
        if (lastKey === 8 || browser.android && domChange.text.length < to - from) {
10519
            preferredPos = sel.to;
10520
            preferredSide = "end";
10521
        }
10522
        let diff = findDiff(view.state.doc.sliceString(from, to, LineBreakPlaceholder), domChange.text, preferredPos - from, preferredSide);
10523
        if (diff) {
10524
            // Chrome inserts two newlines when pressing shift-enter at the
10525
            // end of a line. DomChange drops one of those.
10526
            if (browser.chrome && lastKey == 13 &&
10527
                diff.toB == diff.from + 2 && domChange.text.slice(diff.from, diff.toB) == LineBreakPlaceholder + LineBreakPlaceholder)
10528
                diff.toB--;
10529
            change = { from: from + diff.from, to: from + diff.toA,
10530
                insert: Text.of(domChange.text.slice(diff.from, diff.toB).split(LineBreakPlaceholder)) };
10531
        }
10532
    }
10533
    else if (newSel && (!view.hasFocus && view.state.facet(editable) || newSel.main.eq(sel))) {
10534
        newSel = null;
10535
    }
10536
    if (!change && !newSel)
10537
        return false;
10538
    if (!change && domChange.typeOver && !sel.empty && newSel && newSel.main.empty) {
10539
        // Heuristic to notice typing over a selected character
10540
        change = { from: sel.from, to: sel.to, insert: view.state.doc.slice(sel.from, sel.to) };
10541
    }
10542
    else if (change && change.from >= sel.from && change.to <= sel.to &&
10543
        (change.from != sel.from || change.to != sel.to) &&
10544
        (sel.to - sel.from) - (change.to - change.from) <= 4) {
10545
        // If the change is inside the selection and covers most of it,
10546
        // assume it is a selection replace (with identical characters at
10547
        // the start/end not included in the diff)
10548
        change = {
10549
            from: sel.from, to: sel.to,
10550
            insert: view.state.doc.slice(sel.from, change.from).append(change.insert).append(view.state.doc.slice(change.to, sel.to))
10551
        };
10552
    }
10553
    else if ((browser.mac || browser.android) && change && change.from == change.to && change.from == sel.head - 1 &&
10554
        /^\. ?$/.test(change.insert.toString()) && view.contentDOM.getAttribute("autocorrect") == "off") {
10555
        // Detect insert-period-on-double-space Mac and Android behavior,
10556
        // and transform it into a regular space insert.
10557
        if (newSel && change.insert.length == 2)
10558
            newSel = EditorSelection.single(newSel.main.anchor - 1, newSel.main.head - 1);
10559
        change = { from: sel.from, to: sel.to, insert: Text.of([" "]) };
10560
    }
10561
    else if (browser.chrome && change && change.from == change.to && change.from == sel.head &&
10562
        change.insert.toString() == "\n " && view.lineWrapping) {
10563
        // In Chrome, if you insert a space at the start of a wrapped
10564
        // line, it will actually insert a newline and a space, causing a
10565
        // bogus new line to be created in CodeMirror (#968)
10566
        if (newSel)
10567
            newSel = EditorSelection.single(newSel.main.anchor - 1, newSel.main.head - 1);
10568
        change = { from: sel.from, to: sel.to, insert: Text.of([" "]) };
10569
    }
10570
    if (change) {
10571
        if (browser.ios && view.inputState.flushIOSKey(change))
10572
            return true;
10573
        // Android browsers don't fire reasonable key events for enter,
10574
        // backspace, or delete. So this detects changes that look like
10575
        // they're caused by those keys, and reinterprets them as key
10576
        // events. (Some of these keys are also handled by beforeinput
10577
        // events and the pendingAndroidKey mechanism, but that's not
10578
        // reliable in all situations.)
10579
        if (browser.android &&
10580
            ((change.to == sel.to &&
10581
                // GBoard will sometimes remove a space it just inserted
10582
                // after a completion when you press enter
10583
                (change.from == sel.from || change.from == sel.from - 1 && view.state.sliceDoc(change.from, sel.from) == " ") &&
10584
                change.insert.length == 1 && change.insert.lines == 2 &&
10585
                dispatchKey(view.contentDOM, "Enter", 13)) ||
10586
                ((change.from == sel.from - 1 && change.to == sel.to && change.insert.length == 0 ||
10587
                    lastKey == 8 && change.insert.length < change.to - change.from && change.to > sel.head) &&
10588
                    dispatchKey(view.contentDOM, "Backspace", 8)) ||
10589
                (change.from == sel.from && change.to == sel.to + 1 && change.insert.length == 0 &&
10590
                    dispatchKey(view.contentDOM, "Delete", 46))))
10591
            return true;
10592
        let text = change.insert.toString();
10593
        if (view.inputState.composing >= 0)
10594
            view.inputState.composing++;
10595
        let defaultTr;
10596
        let defaultInsert = () => defaultTr || (defaultTr = applyDefaultInsert(view, change, newSel));
10597
        if (!view.state.facet(inputHandler$1).some(h => h(view, change.from, change.to, text, defaultInsert)))
10598
            view.dispatch(defaultInsert());
10599
        return true;
10600
    }
10601
    else if (newSel && !newSel.main.eq(sel)) {
10602
        let scrollIntoView = false, userEvent = "select";
10603
        if (view.inputState.lastSelectionTime > Date.now() - 50) {
10604
            if (view.inputState.lastSelectionOrigin == "select")
10605
                scrollIntoView = true;
10606
            userEvent = view.inputState.lastSelectionOrigin;
10607
        }
10608
        view.dispatch({ selection: newSel, scrollIntoView, userEvent });
10609
        return true;
10610
    }
10611
    else {
10612
        return false;
10613
    }
10614
}
10615
function applyDefaultInsert(view, change, newSel) {
10616
    let tr, startState = view.state, sel = startState.selection.main;
10617
    if (change.from >= sel.from && change.to <= sel.to && change.to - change.from >= (sel.to - sel.from) / 3 &&
10618
        (!newSel || newSel.main.empty && newSel.main.from == change.from + change.insert.length) &&
10619
        view.inputState.composing < 0) {
10620
        let before = sel.from < change.from ? startState.sliceDoc(sel.from, change.from) : "";
10621
        let after = sel.to > change.to ? startState.sliceDoc(change.to, sel.to) : "";
10622
        tr = startState.replaceSelection(view.state.toText(before + change.insert.sliceString(0, undefined, view.state.lineBreak) + after));
10623
    }
10624
    else {
10625
        let changes = startState.changes(change);
10626
        let mainSel = newSel && newSel.main.to <= changes.newLength ? newSel.main : undefined;
10627
        // Try to apply a composition change to all cursors
10628
        if (startState.selection.ranges.length > 1 && view.inputState.composing >= 0 &&
10629
            change.to <= sel.to && change.to >= sel.to - 10) {
10630
            let replaced = view.state.sliceDoc(change.from, change.to);
10631
            let compositionRange, composition = newSel && findCompositionNode(view, newSel.main.head);
10632
            if (composition) {
10633
                let dLen = change.insert.length - (change.to - change.from);
10634
                compositionRange = { from: composition.from, to: composition.to - dLen };
10635
            }
10636
            else {
10637
                compositionRange = view.state.doc.lineAt(sel.head);
10638
            }
10639
            let offset = sel.to - change.to, size = sel.to - sel.from;
10640
            tr = startState.changeByRange(range => {
10641
                if (range.from == sel.from && range.to == sel.to)
10642
                    return { changes, range: mainSel || range.map(changes) };
10643
                let to = range.to - offset, from = to - replaced.length;
10644
                if (range.to - range.from != size || view.state.sliceDoc(from, to) != replaced ||
10645
                    // Unfortunately, there's no way to make multiple
10646
                    // changes in the same node work without aborting
10647
                    // composition, so cursors in the composition range are
10648
                    // ignored.
10649
                    range.to >= compositionRange.from && range.from <= compositionRange.to)
10650
                    return { range };
10651
                let rangeChanges = startState.changes({ from, to, insert: change.insert }), selOff = range.to - sel.to;
10652
                return {
10653
                    changes: rangeChanges,
10654
                    range: !mainSel ? range.map(rangeChanges) :
10655
                        EditorSelection.range(Math.max(0, mainSel.anchor + selOff), Math.max(0, mainSel.head + selOff))
10656
                };
10657
            });
10658
        }
10659
        else {
10660
            tr = {
10661
                changes,
10662
                selection: mainSel && startState.selection.replaceRange(mainSel)
10663
            };
10664
        }
10665
    }
10666
    let userEvent = "input.type";
10667
    if (view.composing ||
10668
        view.inputState.compositionPendingChange && view.inputState.compositionEndedAt > Date.now() - 50) {
10669
        view.inputState.compositionPendingChange = false;
10670
        userEvent += ".compose";
10671
        if (view.inputState.compositionFirstChange) {
10672
            userEvent += ".start";
10673
            view.inputState.compositionFirstChange = false;
10674
        }
10675
    }
10676
    return startState.update(tr, { userEvent, scrollIntoView: true });
10677
}
10678
function findDiff(a, b, preferredPos, preferredSide) {
10679
    let minLen = Math.min(a.length, b.length);
10680
    let from = 0;
10681
    while (from < minLen && a.charCodeAt(from) == b.charCodeAt(from))
10682
        from++;
10683
    if (from == minLen && a.length == b.length)
10684
        return null;
10685
    let toA = a.length, toB = b.length;
10686
    while (toA > 0 && toB > 0 && a.charCodeAt(toA - 1) == b.charCodeAt(toB - 1)) {
10687
        toA--;
10688
        toB--;
10689
    }
10690
    if (preferredSide == "end") {
10691
        let adjust = Math.max(0, from - Math.min(toA, toB));
10692
        preferredPos -= toA + adjust - from;
10693
    }
10694
    if (toA < from && a.length < b.length) {
10695
        let move = preferredPos <= from && preferredPos >= toA ? from - preferredPos : 0;
10696
        from -= move;
10697
        toB = from + (toB - toA);
10698
        toA = from;
10699
    }
10700
    else if (toB < from) {
10701
        let move = preferredPos <= from && preferredPos >= toB ? from - preferredPos : 0;
10702
        from -= move;
10703
        toA = from + (toA - toB);
10704
        toB = from;
10705
    }
10706
    return { from, toA, toB };
10707
}
10708
function selectionPoints(view) {
10709
    let result = [];
10710
    if (view.root.activeElement != view.contentDOM)
10711
        return result;
10712
    let { anchorNode, anchorOffset, focusNode, focusOffset } = view.observer.selectionRange;
10713
    if (anchorNode) {
10714
        result.push(new DOMPoint(anchorNode, anchorOffset));
10715
        if (focusNode != anchorNode || focusOffset != anchorOffset)
10716
            result.push(new DOMPoint(focusNode, focusOffset));
10717
    }
10718
    return result;
10719
}
10720
function selectionFromPoints(points, base) {
10721
    if (points.length == 0)
10722
        return null;
10723
    let anchor = points[0].pos, head = points.length == 2 ? points[1].pos : anchor;
10724
    return anchor > -1 && head > -1 ? EditorSelection.single(anchor + base, head + base) : null;
10725
}
10726
 
10727
const observeOptions = {
10728
    childList: true,
10729
    characterData: true,
10730
    subtree: true,
10731
    attributes: true,
10732
    characterDataOldValue: true
10733
};
10734
// IE11 has very broken mutation observers, so we also listen to
10735
// DOMCharacterDataModified there
10736
const useCharData = browser.ie && browser.ie_version <= 11;
10737
class DOMObserver {
10738
    constructor(view) {
10739
        this.view = view;
10740
        this.active = false;
10741
        // The known selection. Kept in our own object, as opposed to just
10742
        // directly accessing the selection because:
10743
        //  - Safari doesn't report the right selection in shadow DOM
10744
        //  - Reading from the selection forces a DOM layout
10745
        //  - This way, we can ignore selectionchange events if we have
10746
        //    already seen the 'new' selection
10747
        this.selectionRange = new DOMSelectionState;
10748
        // Set when a selection change is detected, cleared on flush
10749
        this.selectionChanged = false;
10750
        this.delayedFlush = -1;
10751
        this.resizeTimeout = -1;
10752
        this.queue = [];
10753
        this.delayedAndroidKey = null;
10754
        this.flushingAndroidKey = -1;
10755
        this.lastChange = 0;
10756
        this.scrollTargets = [];
10757
        this.intersection = null;
10758
        this.resizeScroll = null;
10759
        this.intersecting = false;
10760
        this.gapIntersection = null;
10761
        this.gaps = [];
10762
        this.printQuery = null;
10763
        // Timeout for scheduling check of the parents that need scroll handlers
10764
        this.parentCheck = -1;
10765
        this.dom = view.contentDOM;
10766
        this.observer = new MutationObserver(mutations => {
10767
            for (let mut of mutations)
10768
                this.queue.push(mut);
10769
            // IE11 will sometimes (on typing over a selection or
10770
            // backspacing out a single character text node) call the
10771
            // observer callback before actually updating the DOM.
10772
            //
10773
            // Unrelatedly, iOS Safari will, when ending a composition,
10774
            // sometimes first clear it, deliver the mutations, and then
10775
            // reinsert the finished text. CodeMirror's handling of the
10776
            // deletion will prevent the reinsertion from happening,
10777
            // breaking composition.
10778
            if ((browser.ie && browser.ie_version <= 11 || browser.ios && view.composing) &&
10779
                mutations.some(m => m.type == "childList" && m.removedNodes.length ||
10780
                    m.type == "characterData" && m.oldValue.length > m.target.nodeValue.length))
10781
                this.flushSoon();
10782
            else
10783
                this.flush();
10784
        });
10785
        if (useCharData)
10786
            this.onCharData = (event) => {
10787
                this.queue.push({ target: event.target,
10788
                    type: "characterData",
10789
                    oldValue: event.prevValue });
10790
                this.flushSoon();
10791
            };
10792
        this.onSelectionChange = this.onSelectionChange.bind(this);
10793
        this.onResize = this.onResize.bind(this);
10794
        this.onPrint = this.onPrint.bind(this);
10795
        this.onScroll = this.onScroll.bind(this);
10796
        if (window.matchMedia)
10797
            this.printQuery = window.matchMedia("print");
10798
        if (typeof ResizeObserver == "function") {
10799
            this.resizeScroll = new ResizeObserver(() => {
10800
                var _a;
10801
                if (((_a = this.view.docView) === null || _a === void 0 ? void 0 : _a.lastUpdate) < Date.now() - 75)
10802
                    this.onResize();
10803
            });
10804
            this.resizeScroll.observe(view.scrollDOM);
10805
        }
10806
        this.addWindowListeners(this.win = view.win);
10807
        this.start();
10808
        if (typeof IntersectionObserver == "function") {
10809
            this.intersection = new IntersectionObserver(entries => {
10810
                if (this.parentCheck < 0)
10811
                    this.parentCheck = setTimeout(this.listenForScroll.bind(this), 1000);
10812
                if (entries.length > 0 && (entries[entries.length - 1].intersectionRatio > 0) != this.intersecting) {
10813
                    this.intersecting = !this.intersecting;
10814
                    if (this.intersecting != this.view.inView)
10815
                        this.onScrollChanged(document.createEvent("Event"));
10816
                }
10817
            }, { threshold: [0, .001] });
10818
            this.intersection.observe(this.dom);
10819
            this.gapIntersection = new IntersectionObserver(entries => {
10820
                if (entries.length > 0 && entries[entries.length - 1].intersectionRatio > 0)
10821
                    this.onScrollChanged(document.createEvent("Event"));
10822
            }, {});
10823
        }
10824
        this.listenForScroll();
10825
        this.readSelectionRange();
10826
    }
10827
    onScrollChanged(e) {
10828
        this.view.inputState.runHandlers("scroll", e);
10829
        if (this.intersecting)
10830
            this.view.measure();
10831
    }
10832
    onScroll(e) {
10833
        if (this.intersecting)
10834
            this.flush(false);
10835
        this.onScrollChanged(e);
10836
    }
10837
    onResize() {
10838
        if (this.resizeTimeout < 0)
10839
            this.resizeTimeout = setTimeout(() => {
10840
                this.resizeTimeout = -1;
10841
                this.view.requestMeasure();
10842
            }, 50);
10843
    }
10844
    onPrint(event) {
10845
        if (event.type == "change" && !event.matches)
10846
            return;
10847
        this.view.viewState.printing = true;
10848
        this.view.measure();
10849
        setTimeout(() => {
10850
            this.view.viewState.printing = false;
10851
            this.view.requestMeasure();
10852
        }, 500);
10853
    }
10854
    updateGaps(gaps) {
10855
        if (this.gapIntersection && (gaps.length != this.gaps.length || this.gaps.some((g, i) => g != gaps[i]))) {
10856
            this.gapIntersection.disconnect();
10857
            for (let gap of gaps)
10858
                this.gapIntersection.observe(gap);
10859
            this.gaps = gaps;
10860
        }
10861
    }
10862
    onSelectionChange(event) {
10863
        let wasChanged = this.selectionChanged;
10864
        if (!this.readSelectionRange() || this.delayedAndroidKey)
10865
            return;
10866
        let { view } = this, sel = this.selectionRange;
10867
        if (view.state.facet(editable) ? view.root.activeElement != this.dom : !hasSelection(view.dom, sel))
10868
            return;
10869
        let context = sel.anchorNode && view.docView.nearest(sel.anchorNode);
10870
        if (context && context.ignoreEvent(event)) {
10871
            if (!wasChanged)
10872
                this.selectionChanged = false;
10873
            return;
10874
        }
10875
        // Deletions on IE11 fire their events in the wrong order, giving
10876
        // us a selection change event before the DOM changes are
10877
        // reported.
10878
        // Chrome Android has a similar issue when backspacing out a
10879
        // selection (#645).
10880
        if ((browser.ie && browser.ie_version <= 11 || browser.android && browser.chrome) && !view.state.selection.main.empty &&
10881
            // (Selection.isCollapsed isn't reliable on IE)
10882
            sel.focusNode && isEquivalentPosition(sel.focusNode, sel.focusOffset, sel.anchorNode, sel.anchorOffset))
10883
            this.flushSoon();
10884
        else
10885
            this.flush(false);
10886
    }
10887
    readSelectionRange() {
10888
        let { view } = this;
10889
        // The Selection object is broken in shadow roots in Safari. See
10890
        // https://github.com/codemirror/dev/issues/414
10891
        let selection = getSelection(view.root);
10892
        if (!selection)
10893
            return false;
10894
        let range = browser.safari && view.root.nodeType == 11 &&
10895
            deepActiveElement(this.dom.ownerDocument) == this.dom &&
10896
            safariSelectionRangeHack(this.view, selection) || selection;
10897
        if (!range || this.selectionRange.eq(range))
10898
            return false;
10899
        let local = hasSelection(this.dom, range);
10900
        // Detect the situation where the browser has, on focus, moved the
10901
        // selection to the start of the content element. Reset it to the
10902
        // position from the editor state.
10903
        if (local && !this.selectionChanged &&
10904
            view.inputState.lastFocusTime > Date.now() - 200 &&
10905
            view.inputState.lastTouchTime < Date.now() - 300 &&
10906
            atElementStart(this.dom, range)) {
10907
            this.view.inputState.lastFocusTime = 0;
10908
            view.docView.updateSelection();
10909
            return false;
10910
        }
10911
        this.selectionRange.setRange(range);
10912
        if (local)
10913
            this.selectionChanged = true;
10914
        return true;
10915
    }
10916
    setSelectionRange(anchor, head) {
10917
        this.selectionRange.set(anchor.node, anchor.offset, head.node, head.offset);
10918
        this.selectionChanged = false;
10919
    }
10920
    clearSelectionRange() {
10921
        this.selectionRange.set(null, 0, null, 0);
10922
    }
10923
    listenForScroll() {
10924
        this.parentCheck = -1;
10925
        let i = 0, changed = null;
10926
        for (let dom = this.dom; dom;) {
10927
            if (dom.nodeType == 1) {
10928
                if (!changed && i < this.scrollTargets.length && this.scrollTargets[i] == dom)
10929
                    i++;
10930
                else if (!changed)
10931
                    changed = this.scrollTargets.slice(0, i);
10932
                if (changed)
10933
                    changed.push(dom);
10934
                dom = dom.assignedSlot || dom.parentNode;
10935
            }
10936
            else if (dom.nodeType == 11) { // Shadow root
10937
                dom = dom.host;
10938
            }
10939
            else {
10940
                break;
10941
            }
10942
        }
10943
        if (i < this.scrollTargets.length && !changed)
10944
            changed = this.scrollTargets.slice(0, i);
10945
        if (changed) {
10946
            for (let dom of this.scrollTargets)
10947
                dom.removeEventListener("scroll", this.onScroll);
10948
            for (let dom of this.scrollTargets = changed)
10949
                dom.addEventListener("scroll", this.onScroll);
10950
        }
10951
    }
10952
    ignore(f) {
10953
        if (!this.active)
10954
            return f();
10955
        try {
10956
            this.stop();
10957
            return f();
10958
        }
10959
        finally {
10960
            this.start();
10961
            this.clear();
10962
        }
10963
    }
10964
    start() {
10965
        if (this.active)
10966
            return;
10967
        this.observer.observe(this.dom, observeOptions);
10968
        if (useCharData)
10969
            this.dom.addEventListener("DOMCharacterDataModified", this.onCharData);
10970
        this.active = true;
10971
    }
10972
    stop() {
10973
        if (!this.active)
10974
            return;
10975
        this.active = false;
10976
        this.observer.disconnect();
10977
        if (useCharData)
10978
            this.dom.removeEventListener("DOMCharacterDataModified", this.onCharData);
10979
    }
10980
    // Throw away any pending changes
10981
    clear() {
10982
        this.processRecords();
10983
        this.queue.length = 0;
10984
        this.selectionChanged = false;
10985
    }
10986
    // Chrome Android, especially in combination with GBoard, not only
10987
    // doesn't reliably fire regular key events, but also often
10988
    // surrounds the effect of enter or backspace with a bunch of
10989
    // composition events that, when interrupted, cause text duplication
10990
    // or other kinds of corruption. This hack makes the editor back off
10991
    // from handling DOM changes for a moment when such a key is
10992
    // detected (via beforeinput or keydown), and then tries to flush
10993
    // them or, if that has no effect, dispatches the given key.
10994
    delayAndroidKey(key, keyCode) {
10995
        var _a;
10996
        if (!this.delayedAndroidKey) {
10997
            let flush = () => {
10998
                let key = this.delayedAndroidKey;
10999
                if (key) {
11000
                    this.clearDelayedAndroidKey();
11001
                    this.view.inputState.lastKeyCode = key.keyCode;
11002
                    this.view.inputState.lastKeyTime = Date.now();
11003
                    let flushed = this.flush();
11004
                    if (!flushed && key.force)
11005
                        dispatchKey(this.dom, key.key, key.keyCode);
11006
                }
11007
            };
11008
            this.flushingAndroidKey = this.view.win.requestAnimationFrame(flush);
11009
        }
11010
        // Since backspace beforeinput is sometimes signalled spuriously,
11011
        // Enter always takes precedence.
11012
        if (!this.delayedAndroidKey || key == "Enter")
11013
            this.delayedAndroidKey = {
11014
                key, keyCode,
11015
                // Only run the key handler when no changes are detected if
11016
                // this isn't coming right after another change, in which case
11017
                // it is probably part of a weird chain of updates, and should
11018
                // be ignored if it returns the DOM to its previous state.
11019
                force: this.lastChange < Date.now() - 50 || !!((_a = this.delayedAndroidKey) === null || _a === void 0 ? void 0 : _a.force)
11020
            };
11021
    }
11022
    clearDelayedAndroidKey() {
11023
        this.win.cancelAnimationFrame(this.flushingAndroidKey);
11024
        this.delayedAndroidKey = null;
11025
        this.flushingAndroidKey = -1;
11026
    }
11027
    flushSoon() {
11028
        if (this.delayedFlush < 0)
11029
            this.delayedFlush = this.view.win.requestAnimationFrame(() => { this.delayedFlush = -1; this.flush(); });
11030
    }
11031
    forceFlush() {
11032
        if (this.delayedFlush >= 0) {
11033
            this.view.win.cancelAnimationFrame(this.delayedFlush);
11034
            this.delayedFlush = -1;
11035
        }
11036
        this.flush();
11037
    }
11038
    pendingRecords() {
11039
        for (let mut of this.observer.takeRecords())
11040
            this.queue.push(mut);
11041
        return this.queue;
11042
    }
11043
    processRecords() {
11044
        let records = this.pendingRecords();
11045
        if (records.length)
11046
            this.queue = [];
11047
        let from = -1, to = -1, typeOver = false;
11048
        for (let record of records) {
11049
            let range = this.readMutation(record);
11050
            if (!range)
11051
                continue;
11052
            if (range.typeOver)
11053
                typeOver = true;
11054
            if (from == -1) {
11055
                ({ from, to } = range);
11056
            }
11057
            else {
11058
                from = Math.min(range.from, from);
11059
                to = Math.max(range.to, to);
11060
            }
11061
        }
11062
        return { from, to, typeOver };
11063
    }
11064
    readChange() {
11065
        let { from, to, typeOver } = this.processRecords();
11066
        let newSel = this.selectionChanged && hasSelection(this.dom, this.selectionRange);
11067
        if (from < 0 && !newSel)
11068
            return null;
11069
        if (from > -1)
11070
            this.lastChange = Date.now();
11071
        this.view.inputState.lastFocusTime = 0;
11072
        this.selectionChanged = false;
11073
        let change = new DOMChange(this.view, from, to, typeOver);
11074
        this.view.docView.domChanged = { newSel: change.newSel ? change.newSel.main : null };
11075
        return change;
11076
    }
11077
    // Apply pending changes, if any
11078
    flush(readSelection = true) {
11079
        // Completely hold off flushing when pending keys are set—the code
11080
        // managing those will make sure processRecords is called and the
11081
        // view is resynchronized after
11082
        if (this.delayedFlush >= 0 || this.delayedAndroidKey)
11083
            return false;
11084
        if (readSelection)
11085
            this.readSelectionRange();
11086
        let domChange = this.readChange();
11087
        if (!domChange) {
11088
            this.view.requestMeasure();
11089
            return false;
11090
        }
11091
        let startState = this.view.state;
11092
        let handled = applyDOMChange(this.view, domChange);
11093
        // The view wasn't updated
11094
        if (this.view.state == startState)
11095
            this.view.update([]);
11096
        return handled;
11097
    }
11098
    readMutation(rec) {
11099
        let cView = this.view.docView.nearest(rec.target);
11100
        if (!cView || cView.ignoreMutation(rec))
11101
            return null;
11102
        cView.markDirty(rec.type == "attributes");
11103
        if (rec.type == "attributes")
11104
            cView.flags |= 4 /* ViewFlag.AttrsDirty */;
11105
        if (rec.type == "childList") {
11106
            let childBefore = findChild(cView, rec.previousSibling || rec.target.previousSibling, -1);
11107
            let childAfter = findChild(cView, rec.nextSibling || rec.target.nextSibling, 1);
11108
            return { from: childBefore ? cView.posAfter(childBefore) : cView.posAtStart,
11109
                to: childAfter ? cView.posBefore(childAfter) : cView.posAtEnd, typeOver: false };
11110
        }
11111
        else if (rec.type == "characterData") {
11112
            return { from: cView.posAtStart, to: cView.posAtEnd, typeOver: rec.target.nodeValue == rec.oldValue };
11113
        }
11114
        else {
11115
            return null;
11116
        }
11117
    }
11118
    setWindow(win) {
11119
        if (win != this.win) {
11120
            this.removeWindowListeners(this.win);
11121
            this.win = win;
11122
            this.addWindowListeners(this.win);
11123
        }
11124
    }
11125
    addWindowListeners(win) {
11126
        win.addEventListener("resize", this.onResize);
11127
        if (this.printQuery)
11128
            this.printQuery.addEventListener("change", this.onPrint);
11129
        else
11130
            win.addEventListener("beforeprint", this.onPrint);
11131
        win.addEventListener("scroll", this.onScroll);
11132
        win.document.addEventListener("selectionchange", this.onSelectionChange);
11133
    }
11134
    removeWindowListeners(win) {
11135
        win.removeEventListener("scroll", this.onScroll);
11136
        win.removeEventListener("resize", this.onResize);
11137
        if (this.printQuery)
11138
            this.printQuery.removeEventListener("change", this.onPrint);
11139
        else
11140
            win.removeEventListener("beforeprint", this.onPrint);
11141
        win.document.removeEventListener("selectionchange", this.onSelectionChange);
11142
    }
11143
    destroy() {
11144
        var _a, _b, _c;
11145
        this.stop();
11146
        (_a = this.intersection) === null || _a === void 0 ? void 0 : _a.disconnect();
11147
        (_b = this.gapIntersection) === null || _b === void 0 ? void 0 : _b.disconnect();
11148
        (_c = this.resizeScroll) === null || _c === void 0 ? void 0 : _c.disconnect();
11149
        for (let dom of this.scrollTargets)
11150
            dom.removeEventListener("scroll", this.onScroll);
11151
        this.removeWindowListeners(this.win);
11152
        clearTimeout(this.parentCheck);
11153
        clearTimeout(this.resizeTimeout);
11154
        this.win.cancelAnimationFrame(this.delayedFlush);
11155
        this.win.cancelAnimationFrame(this.flushingAndroidKey);
11156
    }
11157
}
11158
function findChild(cView, dom, dir) {
11159
    while (dom) {
11160
        let curView = ContentView.get(dom);
11161
        if (curView && curView.parent == cView)
11162
            return curView;
11163
        let parent = dom.parentNode;
11164
        dom = parent != cView.dom ? parent : dir > 0 ? dom.nextSibling : dom.previousSibling;
11165
    }
11166
    return null;
11167
}
11168
function buildSelectionRangeFromRange(view, range) {
11169
    let anchorNode = range.startContainer, anchorOffset = range.startOffset;
11170
    let focusNode = range.endContainer, focusOffset = range.endOffset;
11171
    let curAnchor = view.docView.domAtPos(view.state.selection.main.anchor);
11172
    // Since such a range doesn't distinguish between anchor and head,
11173
    // use a heuristic that flips it around if its end matches the
11174
    // current anchor.
11175
    if (isEquivalentPosition(curAnchor.node, curAnchor.offset, focusNode, focusOffset))
11176
        [anchorNode, anchorOffset, focusNode, focusOffset] = [focusNode, focusOffset, anchorNode, anchorOffset];
11177
    return { anchorNode, anchorOffset, focusNode, focusOffset };
11178
}
11179
// Used to work around a Safari Selection/shadow DOM bug (#414)
11180
function safariSelectionRangeHack(view, selection) {
11181
    if (selection.getComposedRanges) {
11182
        let range = selection.getComposedRanges(view.root)[0];
11183
        if (range)
11184
            return buildSelectionRangeFromRange(view, range);
11185
    }
11186
    let found = null;
11187
    // Because Safari (at least in 2018-2021) doesn't provide regular
11188
    // access to the selection inside a shadowroot, we have to perform a
11189
    // ridiculous hack to get at it—using `execCommand` to trigger a
11190
    // `beforeInput` event so that we can read the target range from the
11191
    // event.
11192
    function read(event) {
11193
        event.preventDefault();
11194
        event.stopImmediatePropagation();
11195
        found = event.getTargetRanges()[0];
11196
    }
11197
    view.contentDOM.addEventListener("beforeinput", read, true);
11198
    view.dom.ownerDocument.execCommand("indent");
11199
    view.contentDOM.removeEventListener("beforeinput", read, true);
11200
    return found ? buildSelectionRangeFromRange(view, found) : null;
11201
}
11202
 
11203
// The editor's update state machine looks something like this:
11204
//
11205
//     Idle → Updating ⇆ Idle (unchecked) → Measuring → Idle
11206
//                                         ↑      ↓
11207
//                                         Updating (measure)
11208
//
11209
// The difference between 'Idle' and 'Idle (unchecked)' lies in
11210
// whether a layout check has been scheduled. A regular update through
11211
// the `update` method updates the DOM in a write-only fashion, and
11212
// relies on a check (scheduled with `requestAnimationFrame`) to make
11213
// sure everything is where it should be and the viewport covers the
11214
// visible code. That check continues to measure and then optionally
11215
// update until it reaches a coherent state.
11216
/**
11217
An editor view represents the editor's user interface. It holds
11218
the editable DOM surface, and possibly other elements such as the
11219
line number gutter. It handles events and dispatches state
11220
transactions for editing actions.
11221
*/
11222
class EditorView {
11223
    /**
11224
    The current editor state.
11225
    */
11226
    get state() { return this.viewState.state; }
11227
    /**
11228
    To be able to display large documents without consuming too much
11229
    memory or overloading the browser, CodeMirror only draws the
11230
    code that is visible (plus a margin around it) to the DOM. This
11231
    property tells you the extent of the current drawn viewport, in
11232
    document positions.
11233
    */
11234
    get viewport() { return this.viewState.viewport; }
11235
    /**
11236
    When there are, for example, large collapsed ranges in the
11237
    viewport, its size can be a lot bigger than the actual visible
11238
    content. Thus, if you are doing something like styling the
11239
    content in the viewport, it is preferable to only do so for
11240
    these ranges, which are the subset of the viewport that is
11241
    actually drawn.
11242
    */
11243
    get visibleRanges() { return this.viewState.visibleRanges; }
11244
    /**
11245
    Returns false when the editor is entirely scrolled out of view
11246
    or otherwise hidden.
11247
    */
11248
    get inView() { return this.viewState.inView; }
11249
    /**
11250
    Indicates whether the user is currently composing text via
11251
    [IME](https://en.wikipedia.org/wiki/Input_method), and at least
11252
    one change has been made in the current composition.
11253
    */
11254
    get composing() { return this.inputState.composing > 0; }
11255
    /**
11256
    Indicates whether the user is currently in composing state. Note
11257
    that on some platforms, like Android, this will be the case a
11258
    lot, since just putting the cursor on a word starts a
11259
    composition there.
11260
    */
11261
    get compositionStarted() { return this.inputState.composing >= 0; }
11262
    /**
11263
    The document or shadow root that the view lives in.
11264
    */
11265
    get root() { return this._root; }
11266
    /**
11267
    @internal
11268
    */
11269
    get win() { return this.dom.ownerDocument.defaultView || window; }
11270
    /**
11271
    Construct a new view. You'll want to either provide a `parent`
11272
    option, or put `view.dom` into your document after creating a
11273
    view, so that the user can see the editor.
11274
    */
11275
    constructor(config = {}) {
11276
        this.plugins = [];
11277
        this.pluginMap = new Map;
11278
        this.editorAttrs = {};
11279
        this.contentAttrs = {};
11280
        this.bidiCache = [];
11281
        this.destroyed = false;
11282
        /**
11283
        @internal
11284
        */
11285
        this.updateState = 2 /* UpdateState.Updating */;
11286
        /**
11287
        @internal
11288
        */
11289
        this.measureScheduled = -1;
11290
        /**
11291
        @internal
11292
        */
11293
        this.measureRequests = [];
11294
        this.contentDOM = document.createElement("div");
11295
        this.scrollDOM = document.createElement("div");
11296
        this.scrollDOM.tabIndex = -1;
11297
        this.scrollDOM.className = "cm-scroller";
11298
        this.scrollDOM.appendChild(this.contentDOM);
11299
        this.announceDOM = document.createElement("div");
11300
        this.announceDOM.className = "cm-announced";
11301
        this.announceDOM.setAttribute("aria-live", "polite");
11302
        this.dom = document.createElement("div");
11303
        this.dom.appendChild(this.announceDOM);
11304
        this.dom.appendChild(this.scrollDOM);
11305
        if (config.parent)
11306
            config.parent.appendChild(this.dom);
11307
        let { dispatch } = config;
11308
        this.dispatchTransactions = config.dispatchTransactions ||
11309
            (dispatch && ((trs) => trs.forEach(tr => dispatch(tr, this)))) ||
11310
            ((trs) => this.update(trs));
11311
        this.dispatch = this.dispatch.bind(this);
11312
        this._root = (config.root || getRoot(config.parent) || document);
11313
        this.viewState = new ViewState(config.state || EditorState.create(config));
11314
        if (config.scrollTo && config.scrollTo.is(scrollIntoView$1))
11315
            this.viewState.scrollTarget = config.scrollTo.value.clip(this.viewState.state);
11316
        this.plugins = this.state.facet(viewPlugin).map(spec => new PluginInstance(spec));
11317
        for (let plugin of this.plugins)
11318
            plugin.update(this);
11319
        this.observer = new DOMObserver(this);
11320
        this.inputState = new InputState(this);
11321
        this.inputState.ensureHandlers(this.plugins);
11322
        this.docView = new DocView(this);
11323
        this.mountStyles();
11324
        this.updateAttrs();
11325
        this.updateState = 0 /* UpdateState.Idle */;
11326
        this.requestMeasure();
11327
    }
11328
    dispatch(...input) {
11329
        let trs = input.length == 1 && input[0] instanceof Transaction ? input
11330
            : input.length == 1 && Array.isArray(input[0]) ? input[0]
11331
                : [this.state.update(...input)];
11332
        this.dispatchTransactions(trs, this);
11333
    }
11334
    /**
11335
    Update the view for the given array of transactions. This will
11336
    update the visible document and selection to match the state
11337
    produced by the transactions, and notify view plugins of the
11338
    change. You should usually call
11339
    [`dispatch`](https://codemirror.net/6/docs/ref/#view.EditorView.dispatch) instead, which uses this
11340
    as a primitive.
11341
    */
11342
    update(transactions) {
11343
        if (this.updateState != 0 /* UpdateState.Idle */)
11344
            throw new Error("Calls to EditorView.update are not allowed while an update is in progress");
11345
        let redrawn = false, attrsChanged = false, update;
11346
        let state = this.state;
11347
        for (let tr of transactions) {
11348
            if (tr.startState != state)
11349
                throw new RangeError("Trying to update state with a transaction that doesn't start from the previous state.");
11350
            state = tr.state;
11351
        }
11352
        if (this.destroyed) {
11353
            this.viewState.state = state;
11354
            return;
11355
        }
11356
        let focus = this.hasFocus, focusFlag = 0, dispatchFocus = null;
11357
        if (transactions.some(tr => tr.annotation(isFocusChange))) {
11358
            this.inputState.notifiedFocused = focus;
11359
            // If a focus-change transaction is being dispatched, set this update flag.
11360
            focusFlag = 1 /* UpdateFlag.Focus */;
11361
        }
11362
        else if (focus != this.inputState.notifiedFocused) {
11363
            this.inputState.notifiedFocused = focus;
11364
            // Schedule a separate focus transaction if necessary, otherwise
11365
            // add a flag to this update
11366
            dispatchFocus = focusChangeTransaction(state, focus);
11367
            if (!dispatchFocus)
11368
                focusFlag = 1 /* UpdateFlag.Focus */;
11369
        }
11370
        // If there was a pending DOM change, eagerly read it and try to
11371
        // apply it after the given transactions.
11372
        let pendingKey = this.observer.delayedAndroidKey, domChange = null;
11373
        if (pendingKey) {
11374
            this.observer.clearDelayedAndroidKey();
11375
            domChange = this.observer.readChange();
11376
            // Only try to apply DOM changes if the transactions didn't
11377
            // change the doc or selection.
11378
            if (domChange && !this.state.doc.eq(state.doc) || !this.state.selection.eq(state.selection))
11379
                domChange = null;
11380
        }
11381
        else {
11382
            this.observer.clear();
11383
        }
11384
        // When the phrases change, redraw the editor
11385
        if (state.facet(EditorState.phrases) != this.state.facet(EditorState.phrases))
11386
            return this.setState(state);
11387
        update = ViewUpdate.create(this, state, transactions);
11388
        update.flags |= focusFlag;
11389
        let scrollTarget = this.viewState.scrollTarget;
11390
        try {
11391
            this.updateState = 2 /* UpdateState.Updating */;
11392
            for (let tr of transactions) {
11393
                if (scrollTarget)
11394
                    scrollTarget = scrollTarget.map(tr.changes);
11395
                if (tr.scrollIntoView) {
11396
                    let { main } = tr.state.selection;
11397
                    scrollTarget = new ScrollTarget(main.empty ? main : EditorSelection.cursor(main.head, main.head > main.anchor ? -1 : 1));
11398
                }
11399
                for (let e of tr.effects)
11400
                    if (e.is(scrollIntoView$1))
11401
                        scrollTarget = e.value.clip(this.state);
11402
            }
11403
            this.viewState.update(update, scrollTarget);
11404
            this.bidiCache = CachedOrder.update(this.bidiCache, update.changes);
11405
            if (!update.empty) {
11406
                this.updatePlugins(update);
11407
                this.inputState.update(update);
11408
            }
11409
            redrawn = this.docView.update(update);
11410
            if (this.state.facet(styleModule) != this.styleModules)
11411
                this.mountStyles();
11412
            attrsChanged = this.updateAttrs();
11413
            this.showAnnouncements(transactions);
11414
            this.docView.updateSelection(redrawn, transactions.some(tr => tr.isUserEvent("select.pointer")));
11415
        }
11416
        finally {
11417
            this.updateState = 0 /* UpdateState.Idle */;
11418
        }
11419
        if (update.startState.facet(theme) != update.state.facet(theme))
11420
            this.viewState.mustMeasureContent = true;
11421
        if (redrawn || attrsChanged || scrollTarget || this.viewState.mustEnforceCursorAssoc || this.viewState.mustMeasureContent)
11422
            this.requestMeasure();
11423
        if (redrawn)
11424
            this.docViewUpdate();
11425
        if (!update.empty)
11426
            for (let listener of this.state.facet(updateListener)) {
11427
                try {
11428
                    listener(update);
11429
                }
11430
                catch (e) {
11431
                    logException(this.state, e, "update listener");
11432
                }
11433
            }
11434
        if (dispatchFocus || domChange)
11435
            Promise.resolve().then(() => {
11436
                if (dispatchFocus && this.state == dispatchFocus.startState)
11437
                    this.dispatch(dispatchFocus);
11438
                if (domChange) {
11439
                    if (!applyDOMChange(this, domChange) && pendingKey.force)
11440
                        dispatchKey(this.contentDOM, pendingKey.key, pendingKey.keyCode);
11441
                }
11442
            });
11443
    }
11444
    /**
11445
    Reset the view to the given state. (This will cause the entire
11446
    document to be redrawn and all view plugins to be reinitialized,
11447
    so you should probably only use it when the new state isn't
11448
    derived from the old state. Otherwise, use
11449
    [`dispatch`](https://codemirror.net/6/docs/ref/#view.EditorView.dispatch) instead.)
11450
    */
11451
    setState(newState) {
11452
        if (this.updateState != 0 /* UpdateState.Idle */)
11453
            throw new Error("Calls to EditorView.setState are not allowed while an update is in progress");
11454
        if (this.destroyed) {
11455
            this.viewState.state = newState;
11456
            return;
11457
        }
11458
        this.updateState = 2 /* UpdateState.Updating */;
11459
        let hadFocus = this.hasFocus;
11460
        try {
11461
            for (let plugin of this.plugins)
11462
                plugin.destroy(this);
11463
            this.viewState = new ViewState(newState);
11464
            this.plugins = newState.facet(viewPlugin).map(spec => new PluginInstance(spec));
11465
            this.pluginMap.clear();
11466
            for (let plugin of this.plugins)
11467
                plugin.update(this);
11468
            this.docView.destroy();
11469
            this.docView = new DocView(this);
11470
            this.inputState.ensureHandlers(this.plugins);
11471
            this.mountStyles();
11472
            this.updateAttrs();
11473
            this.bidiCache = [];
11474
        }
11475
        finally {
11476
            this.updateState = 0 /* UpdateState.Idle */;
11477
        }
11478
        if (hadFocus)
11479
            this.focus();
11480
        this.requestMeasure();
11481
    }
11482
    updatePlugins(update) {
11483
        let prevSpecs = update.startState.facet(viewPlugin), specs = update.state.facet(viewPlugin);
11484
        if (prevSpecs != specs) {
11485
            let newPlugins = [];
11486
            for (let spec of specs) {
11487
                let found = prevSpecs.indexOf(spec);
11488
                if (found < 0) {
11489
                    newPlugins.push(new PluginInstance(spec));
11490
                }
11491
                else {
11492
                    let plugin = this.plugins[found];
11493
                    plugin.mustUpdate = update;
11494
                    newPlugins.push(plugin);
11495
                }
11496
            }
11497
            for (let plugin of this.plugins)
11498
                if (plugin.mustUpdate != update)
11499
                    plugin.destroy(this);
11500
            this.plugins = newPlugins;
11501
            this.pluginMap.clear();
11502
        }
11503
        else {
11504
            for (let p of this.plugins)
11505
                p.mustUpdate = update;
11506
        }
11507
        for (let i = 0; i < this.plugins.length; i++)
11508
            this.plugins[i].update(this);
11509
        if (prevSpecs != specs)
11510
            this.inputState.ensureHandlers(this.plugins);
11511
    }
11512
    docViewUpdate() {
11513
        for (let plugin of this.plugins) {
11514
            let val = plugin.value;
11515
            if (val && val.docViewUpdate) {
11516
                try {
11517
                    val.docViewUpdate(this);
11518
                }
11519
                catch (e) {
11520
                    logException(this.state, e, "doc view update listener");
11521
                }
11522
            }
11523
        }
11524
    }
11525
    /**
11526
    @internal
11527
    */
11528
    measure(flush = true) {
11529
        if (this.destroyed)
11530
            return;
11531
        if (this.measureScheduled > -1)
11532
            this.win.cancelAnimationFrame(this.measureScheduled);
11533
        if (this.observer.delayedAndroidKey) {
11534
            this.measureScheduled = -1;
11535
            this.requestMeasure();
11536
            return;
11537
        }
11538
        this.measureScheduled = 0; // Prevent requestMeasure calls from scheduling another animation frame
11539
        if (flush)
11540
            this.observer.forceFlush();
11541
        let updated = null;
11542
        let sDOM = this.scrollDOM, scrollTop = sDOM.scrollTop * this.scaleY;
11543
        let { scrollAnchorPos, scrollAnchorHeight } = this.viewState;
11544
        if (Math.abs(scrollTop - this.viewState.scrollTop) > 1)
11545
            scrollAnchorHeight = -1;
11546
        this.viewState.scrollAnchorHeight = -1;
11547
        try {
11548
            for (let i = 0;; i++) {
11549
                if (scrollAnchorHeight < 0) {
11550
                    if (isScrolledToBottom(sDOM)) {
11551
                        scrollAnchorPos = -1;
11552
                        scrollAnchorHeight = this.viewState.heightMap.height;
11553
                    }
11554
                    else {
11555
                        let block = this.viewState.scrollAnchorAt(scrollTop);
11556
                        scrollAnchorPos = block.from;
11557
                        scrollAnchorHeight = block.top;
11558
                    }
11559
                }
11560
                this.updateState = 1 /* UpdateState.Measuring */;
11561
                let changed = this.viewState.measure(this);
11562
                if (!changed && !this.measureRequests.length && this.viewState.scrollTarget == null)
11563
                    break;
11564
                if (i > 5) {
11565
                    console.warn(this.measureRequests.length
11566
                        ? "Measure loop restarted more than 5 times"
11567
                        : "Viewport failed to stabilize");
11568
                    break;
11569
                }
11570
                let measuring = [];
11571
                // Only run measure requests in this cycle when the viewport didn't change
11572
                if (!(changed & 4 /* UpdateFlag.Viewport */))
11573
                    [this.measureRequests, measuring] = [measuring, this.measureRequests];
11574
                let measured = measuring.map(m => {
11575
                    try {
11576
                        return m.read(this);
11577
                    }
11578
                    catch (e) {
11579
                        logException(this.state, e);
11580
                        return BadMeasure;
11581
                    }
11582
                });
11583
                let update = ViewUpdate.create(this, this.state, []), redrawn = false;
11584
                update.flags |= changed;
11585
                if (!updated)
11586
                    updated = update;
11587
                else
11588
                    updated.flags |= changed;
11589
                this.updateState = 2 /* UpdateState.Updating */;
11590
                if (!update.empty) {
11591
                    this.updatePlugins(update);
11592
                    this.inputState.update(update);
11593
                    this.updateAttrs();
11594
                    redrawn = this.docView.update(update);
11595
                    if (redrawn)
11596
                        this.docViewUpdate();
11597
                }
11598
                for (let i = 0; i < measuring.length; i++)
11599
                    if (measured[i] != BadMeasure) {
11600
                        try {
11601
                            let m = measuring[i];
11602
                            if (m.write)
11603
                                m.write(measured[i], this);
11604
                        }
11605
                        catch (e) {
11606
                            logException(this.state, e);
11607
                        }
11608
                    }
11609
                if (redrawn)
11610
                    this.docView.updateSelection(true);
11611
                if (!update.viewportChanged && this.measureRequests.length == 0) {
11612
                    if (this.viewState.editorHeight) {
11613
                        if (this.viewState.scrollTarget) {
11614
                            this.docView.scrollIntoView(this.viewState.scrollTarget);
11615
                            this.viewState.scrollTarget = null;
11616
                            scrollAnchorHeight = -1;
11617
                            continue;
11618
                        }
11619
                        else {
11620
                            let newAnchorHeight = scrollAnchorPos < 0 ? this.viewState.heightMap.height :
11621
                                this.viewState.lineBlockAt(scrollAnchorPos).top;
11622
                            let diff = newAnchorHeight - scrollAnchorHeight;
11623
                            if (diff > 1 || diff < -1) {
11624
                                scrollTop = scrollTop + diff;
11625
                                sDOM.scrollTop = scrollTop / this.scaleY;
11626
                                scrollAnchorHeight = -1;
11627
                                continue;
11628
                            }
11629
                        }
11630
                    }
11631
                    break;
11632
                }
11633
            }
11634
        }
11635
        finally {
11636
            this.updateState = 0 /* UpdateState.Idle */;
11637
            this.measureScheduled = -1;
11638
        }
11639
        if (updated && !updated.empty)
11640
            for (let listener of this.state.facet(updateListener))
11641
                listener(updated);
11642
    }
11643
    /**
11644
    Get the CSS classes for the currently active editor themes.
11645
    */
11646
    get themeClasses() {
11647
        return baseThemeID + " " +
11648
            (this.state.facet(darkTheme) ? baseDarkID : baseLightID) + " " +
11649
            this.state.facet(theme);
11650
    }
11651
    updateAttrs() {
11652
        let editorAttrs = attrsFromFacet(this, editorAttributes, {
11653
            class: "cm-editor" + (this.hasFocus ? " cm-focused " : " ") + this.themeClasses
11654
        });
11655
        let contentAttrs = {
11656
            spellcheck: "false",
11657
            autocorrect: "off",
11658
            autocapitalize: "off",
11659
            translate: "no",
11660
            contenteditable: !this.state.facet(editable) ? "false" : "true",
11661
            class: "cm-content",
11662
            style: `${browser.tabSize}: ${this.state.tabSize}`,
11663
            role: "textbox",
11664
            "aria-multiline": "true"
11665
        };
11666
        if (this.state.readOnly)
11667
            contentAttrs["aria-readonly"] = "true";
11668
        attrsFromFacet(this, contentAttributes, contentAttrs);
11669
        let changed = this.observer.ignore(() => {
11670
            let changedContent = updateAttrs(this.contentDOM, this.contentAttrs, contentAttrs);
11671
            let changedEditor = updateAttrs(this.dom, this.editorAttrs, editorAttrs);
11672
            return changedContent || changedEditor;
11673
        });
11674
        this.editorAttrs = editorAttrs;
11675
        this.contentAttrs = contentAttrs;
11676
        return changed;
11677
    }
11678
    showAnnouncements(trs) {
11679
        let first = true;
11680
        for (let tr of trs)
11681
            for (let effect of tr.effects)
11682
                if (effect.is(EditorView.announce)) {
11683
                    if (first)
11684
                        this.announceDOM.textContent = "";
11685
                    first = false;
11686
                    let div = this.announceDOM.appendChild(document.createElement("div"));
11687
                    div.textContent = effect.value;
11688
                }
11689
    }
11690
    mountStyles() {
11691
        this.styleModules = this.state.facet(styleModule);
11692
        let nonce = this.state.facet(EditorView.cspNonce);
11693
        StyleModule.mount(this.root, this.styleModules.concat(baseTheme$1$3).reverse(), nonce ? { nonce } : undefined);
11694
    }
11695
    readMeasured() {
11696
        if (this.updateState == 2 /* UpdateState.Updating */)
11697
            throw new Error("Reading the editor layout isn't allowed during an update");
11698
        if (this.updateState == 0 /* UpdateState.Idle */ && this.measureScheduled > -1)
11699
            this.measure(false);
11700
    }
11701
    /**
11702
    Schedule a layout measurement, optionally providing callbacks to
11703
    do custom DOM measuring followed by a DOM write phase. Using
11704
    this is preferable reading DOM layout directly from, for
11705
    example, an event handler, because it'll make sure measuring and
11706
    drawing done by other components is synchronized, avoiding
11707
    unnecessary DOM layout computations.
11708
    */
11709
    requestMeasure(request) {
11710
        if (this.measureScheduled < 0)
11711
            this.measureScheduled = this.win.requestAnimationFrame(() => this.measure());
11712
        if (request) {
11713
            if (this.measureRequests.indexOf(request) > -1)
11714
                return;
11715
            if (request.key != null)
11716
                for (let i = 0; i < this.measureRequests.length; i++) {
11717
                    if (this.measureRequests[i].key === request.key) {
11718
                        this.measureRequests[i] = request;
11719
                        return;
11720
                    }
11721
                }
11722
            this.measureRequests.push(request);
11723
        }
11724
    }
11725
    /**
11726
    Get the value of a specific plugin, if present. Note that
11727
    plugins that crash can be dropped from a view, so even when you
11728
    know you registered a given plugin, it is recommended to check
11729
    the return value of this method.
11730
    */
11731
    plugin(plugin) {
11732
        let known = this.pluginMap.get(plugin);
11733
        if (known === undefined || known && known.spec != plugin)
11734
            this.pluginMap.set(plugin, known = this.plugins.find(p => p.spec == plugin) || null);
11735
        return known && known.update(this).value;
11736
    }
11737
    /**
11738
    The top position of the document, in screen coordinates. This
11739
    may be negative when the editor is scrolled down. Points
11740
    directly to the top of the first line, not above the padding.
11741
    */
11742
    get documentTop() {
11743
        return this.contentDOM.getBoundingClientRect().top + this.viewState.paddingTop;
11744
    }
11745
    /**
11746
    Reports the padding above and below the document.
11747
    */
11748
    get documentPadding() {
11749
        return { top: this.viewState.paddingTop, bottom: this.viewState.paddingBottom };
11750
    }
11751
    /**
11752
    If the editor is transformed with CSS, this provides the scale
11753
    along the X axis. Otherwise, it will just be 1. Note that
11754
    transforms other than translation and scaling are not supported.
11755
    */
11756
    get scaleX() { return this.viewState.scaleX; }
11757
    /**
11758
    Provide the CSS transformed scale along the Y axis.
11759
    */
11760
    get scaleY() { return this.viewState.scaleY; }
11761
    /**
11762
    Find the text line or block widget at the given vertical
11763
    position (which is interpreted as relative to the [top of the
11764
    document](https://codemirror.net/6/docs/ref/#view.EditorView.documentTop)).
11765
    */
11766
    elementAtHeight(height) {
11767
        this.readMeasured();
11768
        return this.viewState.elementAtHeight(height);
11769
    }
11770
    /**
11771
    Find the line block (see
11772
    [`lineBlockAt`](https://codemirror.net/6/docs/ref/#view.EditorView.lineBlockAt) at the given
11773
    height, again interpreted relative to the [top of the
11774
    document](https://codemirror.net/6/docs/ref/#view.EditorView.documentTop).
11775
    */
11776
    lineBlockAtHeight(height) {
11777
        this.readMeasured();
11778
        return this.viewState.lineBlockAtHeight(height);
11779
    }
11780
    /**
11781
    Get the extent and vertical position of all [line
11782
    blocks](https://codemirror.net/6/docs/ref/#view.EditorView.lineBlockAt) in the viewport. Positions
11783
    are relative to the [top of the
11784
    document](https://codemirror.net/6/docs/ref/#view.EditorView.documentTop);
11785
    */
11786
    get viewportLineBlocks() {
11787
        return this.viewState.viewportLines;
11788
    }
11789
    /**
11790
    Find the line block around the given document position. A line
11791
    block is a range delimited on both sides by either a
11792
    non-[hidden](https://codemirror.net/6/docs/ref/#view.Decoration^replace) line breaks, or the
11793
    start/end of the document. It will usually just hold a line of
11794
    text, but may be broken into multiple textblocks by block
11795
    widgets.
11796
    */
11797
    lineBlockAt(pos) {
11798
        return this.viewState.lineBlockAt(pos);
11799
    }
11800
    /**
11801
    The editor's total content height.
11802
    */
11803
    get contentHeight() {
11804
        return this.viewState.contentHeight;
11805
    }
11806
    /**
11807
    Move a cursor position by [grapheme
11808
    cluster](https://codemirror.net/6/docs/ref/#state.findClusterBreak). `forward` determines whether
11809
    the motion is away from the line start, or towards it. In
11810
    bidirectional text, the line is traversed in visual order, using
11811
    the editor's [text direction](https://codemirror.net/6/docs/ref/#view.EditorView.textDirection).
11812
    When the start position was the last one on the line, the
11813
    returned position will be across the line break. If there is no
11814
    further line, the original position is returned.
11815
 
11816
    By default, this method moves over a single cluster. The
11817
    optional `by` argument can be used to move across more. It will
11818
    be called with the first cluster as argument, and should return
11819
    a predicate that determines, for each subsequent cluster,
11820
    whether it should also be moved over.
11821
    */
11822
    moveByChar(start, forward, by) {
11823
        return skipAtoms(this, start, moveByChar(this, start, forward, by));
11824
    }
11825
    /**
11826
    Move a cursor position across the next group of either
11827
    [letters](https://codemirror.net/6/docs/ref/#state.EditorState.charCategorizer) or non-letter
11828
    non-whitespace characters.
11829
    */
11830
    moveByGroup(start, forward) {
11831
        return skipAtoms(this, start, moveByChar(this, start, forward, initial => byGroup(this, start.head, initial)));
11832
    }
11833
    /**
11834
    Get the cursor position visually at the start or end of a line.
11835
    Note that this may differ from the _logical_ position at its
11836
    start or end (which is simply at `line.from`/`line.to`) if text
11837
    at the start or end goes against the line's base text direction.
11838
    */
11839
    visualLineSide(line, end) {
11840
        let order = this.bidiSpans(line), dir = this.textDirectionAt(line.from);
11841
        let span = order[end ? order.length - 1 : 0];
11842
        return EditorSelection.cursor(span.side(end, dir) + line.from, span.forward(!end, dir) ? 1 : -1);
11843
    }
11844
    /**
11845
    Move to the next line boundary in the given direction. If
11846
    `includeWrap` is true, line wrapping is on, and there is a
11847
    further wrap point on the current line, the wrap point will be
11848
    returned. Otherwise this function will return the start or end
11849
    of the line.
11850
    */
11851
    moveToLineBoundary(start, forward, includeWrap = true) {
11852
        return moveToLineBoundary(this, start, forward, includeWrap);
11853
    }
11854
    /**
11855
    Move a cursor position vertically. When `distance` isn't given,
11856
    it defaults to moving to the next line (including wrapped
11857
    lines). Otherwise, `distance` should provide a positive distance
11858
    in pixels.
11859
 
11860
    When `start` has a
11861
    [`goalColumn`](https://codemirror.net/6/docs/ref/#state.SelectionRange.goalColumn), the vertical
11862
    motion will use that as a target horizontal position. Otherwise,
11863
    the cursor's own horizontal position is used. The returned
11864
    cursor will have its goal column set to whichever column was
11865
    used.
11866
    */
11867
    moveVertically(start, forward, distance) {
11868
        return skipAtoms(this, start, moveVertically(this, start, forward, distance));
11869
    }
11870
    /**
11871
    Find the DOM parent node and offset (child offset if `node` is
11872
    an element, character offset when it is a text node) at the
11873
    given document position.
11874
 
11875
    Note that for positions that aren't currently in
11876
    `visibleRanges`, the resulting DOM position isn't necessarily
11877
    meaningful (it may just point before or after a placeholder
11878
    element).
11879
    */
11880
    domAtPos(pos) {
11881
        return this.docView.domAtPos(pos);
11882
    }
11883
    /**
11884
    Find the document position at the given DOM node. Can be useful
11885
    for associating positions with DOM events. Will raise an error
11886
    when `node` isn't part of the editor content.
11887
    */
11888
    posAtDOM(node, offset = 0) {
11889
        return this.docView.posFromDOM(node, offset);
11890
    }
11891
    posAtCoords(coords, precise = true) {
11892
        this.readMeasured();
11893
        return posAtCoords(this, coords, precise);
11894
    }
11895
    /**
11896
    Get the screen coordinates at the given document position.
11897
    `side` determines whether the coordinates are based on the
11898
    element before (-1) or after (1) the position (if no element is
11899
    available on the given side, the method will transparently use
11900
    another strategy to get reasonable coordinates).
11901
    */
11902
    coordsAtPos(pos, side = 1) {
11903
        this.readMeasured();
11904
        let rect = this.docView.coordsAt(pos, side);
11905
        if (!rect || rect.left == rect.right)
11906
            return rect;
11907
        let line = this.state.doc.lineAt(pos), order = this.bidiSpans(line);
11908
        let span = order[BidiSpan.find(order, pos - line.from, -1, side)];
11909
        return flattenRect(rect, (span.dir == Direction.LTR) == (side > 0));
11910
    }
11911
    /**
11912
    Return the rectangle around a given character. If `pos` does not
11913
    point in front of a character that is in the viewport and
11914
    rendered (i.e. not replaced, not a line break), this will return
11915
    null. For space characters that are a line wrap point, this will
11916
    return the position before the line break.
11917
    */
11918
    coordsForChar(pos) {
11919
        this.readMeasured();
11920
        return this.docView.coordsForChar(pos);
11921
    }
11922
    /**
11923
    The default width of a character in the editor. May not
11924
    accurately reflect the width of all characters (given variable
11925
    width fonts or styling of invididual ranges).
11926
    */
11927
    get defaultCharacterWidth() { return this.viewState.heightOracle.charWidth; }
11928
    /**
11929
    The default height of a line in the editor. May not be accurate
11930
    for all lines.
11931
    */
11932
    get defaultLineHeight() { return this.viewState.heightOracle.lineHeight; }
11933
    /**
11934
    The text direction
11935
    ([`direction`](https://developer.mozilla.org/en-US/docs/Web/CSS/direction)
11936
    CSS property) of the editor's content element.
11937
    */
11938
    get textDirection() { return this.viewState.defaultTextDirection; }
11939
    /**
11940
    Find the text direction of the block at the given position, as
11941
    assigned by CSS. If
11942
    [`perLineTextDirection`](https://codemirror.net/6/docs/ref/#view.EditorView^perLineTextDirection)
11943
    isn't enabled, or the given position is outside of the viewport,
11944
    this will always return the same as
11945
    [`textDirection`](https://codemirror.net/6/docs/ref/#view.EditorView.textDirection). Note that
11946
    this may trigger a DOM layout.
11947
    */
11948
    textDirectionAt(pos) {
11949
        let perLine = this.state.facet(perLineTextDirection);
11950
        if (!perLine || pos < this.viewport.from || pos > this.viewport.to)
11951
            return this.textDirection;
11952
        this.readMeasured();
11953
        return this.docView.textDirectionAt(pos);
11954
    }
11955
    /**
11956
    Whether this editor [wraps lines](https://codemirror.net/6/docs/ref/#view.EditorView.lineWrapping)
11957
    (as determined by the
11958
    [`white-space`](https://developer.mozilla.org/en-US/docs/Web/CSS/white-space)
11959
    CSS property of its content element).
11960
    */
11961
    get lineWrapping() { return this.viewState.heightOracle.lineWrapping; }
11962
    /**
11963
    Returns the bidirectional text structure of the given line
11964
    (which should be in the current document) as an array of span
11965
    objects. The order of these spans matches the [text
11966
    direction](https://codemirror.net/6/docs/ref/#view.EditorView.textDirection)—if that is
11967
    left-to-right, the leftmost spans come first, otherwise the
11968
    rightmost spans come first.
11969
    */
11970
    bidiSpans(line) {
11971
        if (line.length > MaxBidiLine)
11972
            return trivialOrder(line.length);
11973
        let dir = this.textDirectionAt(line.from), isolates;
11974
        for (let entry of this.bidiCache) {
11975
            if (entry.from == line.from && entry.dir == dir &&
11976
                (entry.fresh || isolatesEq(entry.isolates, isolates = getIsolatedRanges(this, line))))
11977
                return entry.order;
11978
        }
11979
        if (!isolates)
11980
            isolates = getIsolatedRanges(this, line);
11981
        let order = computeOrder(line.text, dir, isolates);
11982
        this.bidiCache.push(new CachedOrder(line.from, line.to, dir, isolates, true, order));
11983
        return order;
11984
    }
11985
    /**
11986
    Check whether the editor has focus.
11987
    */
11988
    get hasFocus() {
11989
        var _a;
11990
        // Safari return false for hasFocus when the context menu is open
11991
        // or closing, which leads us to ignore selection changes from the
11992
        // context menu because it looks like the editor isn't focused.
11993
        // This kludges around that.
11994
        return (this.dom.ownerDocument.hasFocus() || browser.safari && ((_a = this.inputState) === null || _a === void 0 ? void 0 : _a.lastContextMenu) > Date.now() - 3e4) &&
11995
            this.root.activeElement == this.contentDOM;
11996
    }
11997
    /**
11998
    Put focus on the editor.
11999
    */
12000
    focus() {
12001
        this.observer.ignore(() => {
12002
            focusPreventScroll(this.contentDOM);
12003
            this.docView.updateSelection();
12004
        });
12005
    }
12006
    /**
12007
    Update the [root](https://codemirror.net/6/docs/ref/##view.EditorViewConfig.root) in which the editor lives. This is only
12008
    necessary when moving the editor's existing DOM to a new window or shadow root.
12009
    */
12010
    setRoot(root) {
12011
        if (this._root != root) {
12012
            this._root = root;
12013
            this.observer.setWindow((root.nodeType == 9 ? root : root.ownerDocument).defaultView || window);
12014
            this.mountStyles();
12015
        }
12016
    }
12017
    /**
12018
    Clean up this editor view, removing its element from the
12019
    document, unregistering event handlers, and notifying
12020
    plugins. The view instance can no longer be used after
12021
    calling this.
12022
    */
12023
    destroy() {
12024
        for (let plugin of this.plugins)
12025
            plugin.destroy(this);
12026
        this.plugins = [];
12027
        this.inputState.destroy();
12028
        this.docView.destroy();
12029
        this.dom.remove();
12030
        this.observer.destroy();
12031
        if (this.measureScheduled > -1)
12032
            this.win.cancelAnimationFrame(this.measureScheduled);
12033
        this.destroyed = true;
12034
    }
12035
    /**
12036
    Returns an effect that can be
12037
    [added](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects) to a transaction to
12038
    cause it to scroll the given position or range into view.
12039
    */
12040
    static scrollIntoView(pos, options = {}) {
12041
        return scrollIntoView$1.of(new ScrollTarget(typeof pos == "number" ? EditorSelection.cursor(pos) : pos, options.y, options.x, options.yMargin, options.xMargin));
12042
    }
12043
    /**
12044
    Return an effect that resets the editor to its current (at the
12045
    time this method was called) scroll position. Note that this
12046
    only affects the editor's own scrollable element, not parents.
12047
    See also
12048
    [`EditorViewConfig.scrollTo`](https://codemirror.net/6/docs/ref/#view.EditorViewConfig.scrollTo).
12049
 
12050
    The effect should be used with a document identical to the one
12051
    it was created for. Failing to do so is not an error, but may
12052
    not scroll to the expected position. You can
12053
    [map](https://codemirror.net/6/docs/ref/#state.StateEffect.map) the effect to account for changes.
12054
    */
12055
    scrollSnapshot() {
12056
        let { scrollTop, scrollLeft } = this.scrollDOM;
12057
        let ref = this.viewState.scrollAnchorAt(scrollTop);
12058
        return scrollIntoView$1.of(new ScrollTarget(EditorSelection.cursor(ref.from), "start", "start", ref.top - scrollTop, scrollLeft, true));
12059
    }
12060
    /**
12061
    Returns an extension that can be used to add DOM event handlers.
12062
    The value should be an object mapping event names to handler
12063
    functions. For any given event, such functions are ordered by
12064
    extension precedence, and the first handler to return true will
12065
    be assumed to have handled that event, and no other handlers or
12066
    built-in behavior will be activated for it. These are registered
12067
    on the [content element](https://codemirror.net/6/docs/ref/#view.EditorView.contentDOM), except
12068
    for `scroll` handlers, which will be called any time the
12069
    editor's [scroll element](https://codemirror.net/6/docs/ref/#view.EditorView.scrollDOM) or one of
12070
    its parent nodes is scrolled.
12071
    */
12072
    static domEventHandlers(handlers) {
12073
        return ViewPlugin.define(() => ({}), { eventHandlers: handlers });
12074
    }
12075
    /**
12076
    Create an extension that registers DOM event observers. Contrary
12077
    to event [handlers](https://codemirror.net/6/docs/ref/#view.EditorView^domEventHandlers),
12078
    observers can't be prevented from running by a higher-precedence
12079
    handler returning true. They also don't prevent other handlers
12080
    and observers from running when they return true, and should not
12081
    call `preventDefault`.
12082
    */
12083
    static domEventObservers(observers) {
12084
        return ViewPlugin.define(() => ({}), { eventObservers: observers });
12085
    }
12086
    /**
12087
    Create a theme extension. The first argument can be a
12088
    [`style-mod`](https://github.com/marijnh/style-mod#documentation)
12089
    style spec providing the styles for the theme. These will be
12090
    prefixed with a generated class for the style.
12091
 
12092
    Because the selectors will be prefixed with a scope class, rule
12093
    that directly match the editor's [wrapper
12094
    element](https://codemirror.net/6/docs/ref/#view.EditorView.dom)—to which the scope class will be
12095
    added—need to be explicitly differentiated by adding an `&` to
12096
    the selector for that element—for example
12097
    `&.cm-focused`.
12098
 
12099
    When `dark` is set to true, the theme will be marked as dark,
12100
    which will cause the `&dark` rules from [base
12101
    themes](https://codemirror.net/6/docs/ref/#view.EditorView^baseTheme) to be used (as opposed to
12102
    `&light` when a light theme is active).
12103
    */
12104
    static theme(spec, options) {
12105
        let prefix = StyleModule.newName();
12106
        let result = [theme.of(prefix), styleModule.of(buildTheme(`.${prefix}`, spec))];
12107
        if (options && options.dark)
12108
            result.push(darkTheme.of(true));
12109
        return result;
12110
    }
12111
    /**
12112
    Create an extension that adds styles to the base theme. Like
12113
    with [`theme`](https://codemirror.net/6/docs/ref/#view.EditorView^theme), use `&` to indicate the
12114
    place of the editor wrapper element when directly targeting
12115
    that. You can also use `&dark` or `&light` instead to only
12116
    target editors with a dark or light theme.
12117
    */
12118
    static baseTheme(spec) {
12119
        return Prec.lowest(styleModule.of(buildTheme("." + baseThemeID, spec, lightDarkIDs)));
12120
    }
12121
    /**
12122
    Retrieve an editor view instance from the view's DOM
12123
    representation.
12124
    */
12125
    static findFromDOM(dom) {
12126
        var _a;
12127
        let content = dom.querySelector(".cm-content");
12128
        let cView = content && ContentView.get(content) || ContentView.get(dom);
12129
        return ((_a = cView === null || cView === void 0 ? void 0 : cView.rootView) === null || _a === void 0 ? void 0 : _a.view) || null;
12130
    }
12131
}
12132
/**
12133
Facet to add a [style
12134
module](https://github.com/marijnh/style-mod#documentation) to
12135
an editor view. The view will ensure that the module is
12136
mounted in its [document
12137
root](https://codemirror.net/6/docs/ref/#view.EditorView.constructor^config.root).
12138
*/
12139
EditorView.styleModule = styleModule;
12140
/**
12141
An input handler can override the way changes to the editable
12142
DOM content are handled. Handlers are passed the document
12143
positions between which the change was found, and the new
12144
content. When one returns true, no further input handlers are
12145
called and the default behavior is prevented.
12146
 
12147
The `insert` argument can be used to get the default transaction
12148
that would be applied for this input. This can be useful when
12149
dispatching the custom behavior as a separate transaction.
12150
*/
12151
EditorView.inputHandler = inputHandler$1;
12152
/**
12153
Scroll handlers can override how things are scrolled into view.
12154
If they return `true`, no further handling happens for the
12155
scrolling. If they return false, the default scroll behavior is
12156
applied. Scroll handlers should never initiate editor updates.
12157
*/
12158
EditorView.scrollHandler = scrollHandler;
12159
/**
12160
This facet can be used to provide functions that create effects
12161
to be dispatched when the editor's focus state changes.
12162
*/
12163
EditorView.focusChangeEffect = focusChangeEffect;
12164
/**
12165
By default, the editor assumes all its content has the same
12166
[text direction](https://codemirror.net/6/docs/ref/#view.Direction). Configure this with a `true`
12167
value to make it read the text direction of every (rendered)
12168
line separately.
12169
*/
12170
EditorView.perLineTextDirection = perLineTextDirection;
12171
/**
12172
Allows you to provide a function that should be called when the
12173
library catches an exception from an extension (mostly from view
12174
plugins, but may be used by other extensions to route exceptions
12175
from user-code-provided callbacks). This is mostly useful for
12176
debugging and logging. See [`logException`](https://codemirror.net/6/docs/ref/#view.logException).
12177
*/
12178
EditorView.exceptionSink = exceptionSink;
12179
/**
12180
A facet that can be used to register a function to be called
12181
every time the view updates.
12182
*/
12183
EditorView.updateListener = updateListener;
12184
/**
12185
Facet that controls whether the editor content DOM is editable.
12186
When its highest-precedence value is `false`, the element will
12187
not have its `contenteditable` attribute set. (Note that this
12188
doesn't affect API calls that change the editor content, even
12189
when those are bound to keys or buttons. See the
12190
[`readOnly`](https://codemirror.net/6/docs/ref/#state.EditorState.readOnly) facet for that.)
12191
*/
12192
EditorView.editable = editable;
12193
/**
12194
Allows you to influence the way mouse selection happens. The
12195
functions in this facet will be called for a `mousedown` event
12196
on the editor, and can return an object that overrides the way a
12197
selection is computed from that mouse click or drag.
12198
*/
12199
EditorView.mouseSelectionStyle = mouseSelectionStyle;
12200
/**
12201
Facet used to configure whether a given selection drag event
12202
should move or copy the selection. The given predicate will be
12203
called with the `mousedown` event, and can return `true` when
12204
the drag should move the content.
12205
*/
12206
EditorView.dragMovesSelection = dragMovesSelection$1;
12207
/**
12208
Facet used to configure whether a given selecting click adds a
12209
new range to the existing selection or replaces it entirely. The
12210
default behavior is to check `event.metaKey` on macOS, and
12211
`event.ctrlKey` elsewhere.
12212
*/
12213
EditorView.clickAddsSelectionRange = clickAddsSelectionRange;
12214
/**
12215
A facet that determines which [decorations](https://codemirror.net/6/docs/ref/#view.Decoration)
12216
are shown in the view. Decorations can be provided in two
12217
ways—directly, or via a function that takes an editor view.
12218
 
12219
Only decoration sets provided directly are allowed to influence
12220
the editor's vertical layout structure. The ones provided as
12221
functions are called _after_ the new viewport has been computed,
12222
and thus **must not** introduce block widgets or replacing
12223
decorations that cover line breaks.
12224
 
12225
If you want decorated ranges to behave like atomic units for
12226
cursor motion and deletion purposes, also provide the range set
12227
containing the decorations to
12228
[`EditorView.atomicRanges`](https://codemirror.net/6/docs/ref/#view.EditorView^atomicRanges).
12229
*/
12230
EditorView.decorations = decorations;
12231
/**
12232
Facet that works much like
12233
[`decorations`](https://codemirror.net/6/docs/ref/#view.EditorView^decorations), but puts its
12234
inputs at the very bottom of the precedence stack, meaning mark
12235
decorations provided here will only be split by other, partially
12236
overlapping \`outerDecorations\` ranges, and wrap around all
12237
regular decorations. Use this for mark elements that should, as
12238
much as possible, remain in one piece.
12239
*/
12240
EditorView.outerDecorations = outerDecorations;
12241
/**
12242
Used to provide ranges that should be treated as atoms as far as
12243
cursor motion is concerned. This causes methods like
12244
[`moveByChar`](https://codemirror.net/6/docs/ref/#view.EditorView.moveByChar) and
12245
[`moveVertically`](https://codemirror.net/6/docs/ref/#view.EditorView.moveVertically) (and the
12246
commands built on top of them) to skip across such regions when
12247
a selection endpoint would enter them. This does _not_ prevent
12248
direct programmatic [selection
12249
updates](https://codemirror.net/6/docs/ref/#state.TransactionSpec.selection) from moving into such
12250
regions.
12251
*/
12252
EditorView.atomicRanges = atomicRanges;
12253
/**
12254
When range decorations add a `unicode-bidi: isolate` style, they
12255
should also include a
12256
[`bidiIsolate`](https://codemirror.net/6/docs/ref/#view.MarkDecorationSpec.bidiIsolate) property
12257
in their decoration spec, and be exposed through this facet, so
12258
that the editor can compute the proper text order. (Other values
12259
for `unicode-bidi`, except of course `normal`, are not
12260
supported.)
12261
*/
12262
EditorView.bidiIsolatedRanges = bidiIsolatedRanges;
12263
/**
12264
Facet that allows extensions to provide additional scroll
12265
margins (space around the sides of the scrolling element that
12266
should be considered invisible). This can be useful when the
12267
plugin introduces elements that cover part of that element (for
12268
example a horizontally fixed gutter).
12269
*/
12270
EditorView.scrollMargins = scrollMargins;
12271
/**
12272
This facet records whether a dark theme is active. The extension
12273
returned by [`theme`](https://codemirror.net/6/docs/ref/#view.EditorView^theme) automatically
12274
includes an instance of this when the `dark` option is set to
12275
true.
12276
*/
12277
EditorView.darkTheme = darkTheme;
12278
/**
12279
Provides a Content Security Policy nonce to use when creating
12280
the style sheets for the editor. Holds the empty string when no
12281
nonce has been provided.
12282
*/
12283
EditorView.cspNonce = /*@__PURE__*/Facet.define({ combine: values => values.length ? values[0] : "" });
12284
/**
12285
Facet that provides additional DOM attributes for the editor's
12286
editable DOM element.
12287
*/
12288
EditorView.contentAttributes = contentAttributes;
12289
/**
12290
Facet that provides DOM attributes for the editor's outer
12291
element.
12292
*/
12293
EditorView.editorAttributes = editorAttributes;
12294
/**
12295
An extension that enables line wrapping in the editor (by
12296
setting CSS `white-space` to `pre-wrap` in the content).
12297
*/
12298
EditorView.lineWrapping = /*@__PURE__*/EditorView.contentAttributes.of({ "class": "cm-lineWrapping" });
12299
/**
12300
State effect used to include screen reader announcements in a
12301
transaction. These will be added to the DOM in a visually hidden
12302
element with `aria-live="polite"` set, and should be used to
12303
describe effects that are visually obvious but may not be
12304
noticed by screen reader users (such as moving to the next
12305
search match).
12306
*/
12307
EditorView.announce = /*@__PURE__*/StateEffect.define();
12308
// Maximum line length for which we compute accurate bidi info
12309
const MaxBidiLine = 4096;
12310
const BadMeasure = {};
12311
class CachedOrder {
12312
    constructor(from, to, dir, isolates, fresh, order) {
12313
        this.from = from;
12314
        this.to = to;
12315
        this.dir = dir;
12316
        this.isolates = isolates;
12317
        this.fresh = fresh;
12318
        this.order = order;
12319
    }
12320
    static update(cache, changes) {
12321
        if (changes.empty && !cache.some(c => c.fresh))
12322
            return cache;
12323
        let result = [], lastDir = cache.length ? cache[cache.length - 1].dir : Direction.LTR;
12324
        for (let i = Math.max(0, cache.length - 10); i < cache.length; i++) {
12325
            let entry = cache[i];
12326
            if (entry.dir == lastDir && !changes.touchesRange(entry.from, entry.to))
12327
                result.push(new CachedOrder(changes.mapPos(entry.from, 1), changes.mapPos(entry.to, -1), entry.dir, entry.isolates, false, entry.order));
12328
        }
12329
        return result;
12330
    }
12331
}
12332
function attrsFromFacet(view, facet, base) {
12333
    for (let sources = view.state.facet(facet), i = sources.length - 1; i >= 0; i--) {
12334
        let source = sources[i], value = typeof source == "function" ? source(view) : source;
12335
        if (value)
12336
            combineAttrs(value, base);
12337
    }
12338
    return base;
12339
}
12340
 
12341
const currentPlatform = browser.mac ? "mac" : browser.windows ? "win" : browser.linux ? "linux" : "key";
12342
function normalizeKeyName(name, platform) {
12343
    const parts = name.split(/-(?!$)/);
12344
    let result = parts[parts.length - 1];
12345
    if (result == "Space")
12346
        result = " ";
12347
    let alt, ctrl, shift, meta;
12348
    for (let i = 0; i < parts.length - 1; ++i) {
12349
        const mod = parts[i];
12350
        if (/^(cmd|meta|m)$/i.test(mod))
12351
            meta = true;
12352
        else if (/^a(lt)?$/i.test(mod))
12353
            alt = true;
12354
        else if (/^(c|ctrl|control)$/i.test(mod))
12355
            ctrl = true;
12356
        else if (/^s(hift)?$/i.test(mod))
12357
            shift = true;
12358
        else if (/^mod$/i.test(mod)) {
12359
            if (platform == "mac")
12360
                meta = true;
12361
            else
12362
                ctrl = true;
12363
        }
12364
        else
12365
            throw new Error("Unrecognized modifier name: " + mod);
12366
    }
12367
    if (alt)
12368
        result = "Alt-" + result;
12369
    if (ctrl)
12370
        result = "Ctrl-" + result;
12371
    if (meta)
12372
        result = "Meta-" + result;
12373
    if (shift)
12374
        result = "Shift-" + result;
12375
    return result;
12376
}
12377
function modifiers(name, event, shift) {
12378
    if (event.altKey)
12379
        name = "Alt-" + name;
12380
    if (event.ctrlKey)
12381
        name = "Ctrl-" + name;
12382
    if (event.metaKey)
12383
        name = "Meta-" + name;
12384
    if (shift !== false && event.shiftKey)
12385
        name = "Shift-" + name;
12386
    return name;
12387
}
12388
const handleKeyEvents = /*@__PURE__*/Prec.default(/*@__PURE__*/EditorView.domEventHandlers({
12389
    keydown(event, view) {
12390
        return runHandlers(getKeymap(view.state), event, view, "editor");
12391
    }
12392
}));
12393
/**
12394
Facet used for registering keymaps.
12395
 
12396
You can add multiple keymaps to an editor. Their priorities
12397
determine their precedence (the ones specified early or with high
12398
priority get checked first). When a handler has returned `true`
12399
for a given key, no further handlers are called.
12400
*/
12401
const keymap = /*@__PURE__*/Facet.define({ enables: handleKeyEvents });
12402
const Keymaps = /*@__PURE__*/new WeakMap();
12403
// This is hidden behind an indirection, rather than directly computed
12404
// by the facet, to keep internal types out of the facet's type.
12405
function getKeymap(state) {
12406
    let bindings = state.facet(keymap);
12407
    let map = Keymaps.get(bindings);
12408
    if (!map)
12409
        Keymaps.set(bindings, map = buildKeymap(bindings.reduce((a, b) => a.concat(b), [])));
12410
    return map;
12411
}
12412
/**
12413
Run the key handlers registered for a given scope. The event
12414
object should be a `"keydown"` event. Returns true if any of the
12415
handlers handled it.
12416
*/
12417
function runScopeHandlers(view, event, scope) {
12418
    return runHandlers(getKeymap(view.state), event, view, scope);
12419
}
12420
let storedPrefix = null;
12421
const PrefixTimeout = 4000;
12422
function buildKeymap(bindings, platform = currentPlatform) {
12423
    let bound = Object.create(null);
12424
    let isPrefix = Object.create(null);
12425
    let checkPrefix = (name, is) => {
12426
        let current = isPrefix[name];
12427
        if (current == null)
12428
            isPrefix[name] = is;
12429
        else if (current != is)
12430
            throw new Error("Key binding " + name + " is used both as a regular binding and as a multi-stroke prefix");
12431
    };
12432
    let add = (scope, key, command, preventDefault, stopPropagation) => {
12433
        var _a, _b;
12434
        let scopeObj = bound[scope] || (bound[scope] = Object.create(null));
12435
        let parts = key.split(/ (?!$)/).map(k => normalizeKeyName(k, platform));
12436
        for (let i = 1; i < parts.length; i++) {
12437
            let prefix = parts.slice(0, i).join(" ");
12438
            checkPrefix(prefix, true);
12439
            if (!scopeObj[prefix])
12440
                scopeObj[prefix] = {
12441
                    preventDefault: true,
12442
                    stopPropagation: false,
12443
                    run: [(view) => {
12444
                            let ourObj = storedPrefix = { view, prefix, scope };
12445
                            setTimeout(() => { if (storedPrefix == ourObj)
12446
                                storedPrefix = null; }, PrefixTimeout);
12447
                            return true;
12448
                        }]
12449
                };
12450
        }
12451
        let full = parts.join(" ");
12452
        checkPrefix(full, false);
12453
        let binding = scopeObj[full] || (scopeObj[full] = {
12454
            preventDefault: false,
12455
            stopPropagation: false,
12456
            run: ((_b = (_a = scopeObj._any) === null || _a === void 0 ? void 0 : _a.run) === null || _b === void 0 ? void 0 : _b.slice()) || []
12457
        });
12458
        if (command)
12459
            binding.run.push(command);
12460
        if (preventDefault)
12461
            binding.preventDefault = true;
12462
        if (stopPropagation)
12463
            binding.stopPropagation = true;
12464
    };
12465
    for (let b of bindings) {
12466
        let scopes = b.scope ? b.scope.split(" ") : ["editor"];
12467
        if (b.any)
12468
            for (let scope of scopes) {
12469
                let scopeObj = bound[scope] || (bound[scope] = Object.create(null));
12470
                if (!scopeObj._any)
12471
                    scopeObj._any = { preventDefault: false, stopPropagation: false, run: [] };
12472
                for (let key in scopeObj)
12473
                    scopeObj[key].run.push(b.any);
12474
            }
12475
        let name = b[platform] || b.key;
12476
        if (!name)
12477
            continue;
12478
        for (let scope of scopes) {
12479
            add(scope, name, b.run, b.preventDefault, b.stopPropagation);
12480
            if (b.shift)
12481
                add(scope, "Shift-" + name, b.shift, b.preventDefault, b.stopPropagation);
12482
        }
12483
    }
12484
    return bound;
12485
}
12486
function runHandlers(map, event, view, scope) {
12487
    let name = keyName(event);
12488
    let charCode = codePointAt(name, 0), isChar = codePointSize(charCode) == name.length && name != " ";
12489
    let prefix = "", handled = false, prevented = false, stopPropagation = false;
12490
    if (storedPrefix && storedPrefix.view == view && storedPrefix.scope == scope) {
12491
        prefix = storedPrefix.prefix + " ";
12492
        if (modifierCodes.indexOf(event.keyCode) < 0) {
12493
            prevented = true;
12494
            storedPrefix = null;
12495
        }
12496
    }
12497
    let ran = new Set;
12498
    let runFor = (binding) => {
12499
        if (binding) {
12500
            for (let cmd of binding.run)
12501
                if (!ran.has(cmd)) {
12502
                    ran.add(cmd);
12503
                    if (cmd(view, event)) {
12504
                        if (binding.stopPropagation)
12505
                            stopPropagation = true;
12506
                        return true;
12507
                    }
12508
                }
12509
            if (binding.preventDefault) {
12510
                if (binding.stopPropagation)
12511
                    stopPropagation = true;
12512
                prevented = true;
12513
            }
12514
        }
12515
        return false;
12516
    };
12517
    let scopeObj = map[scope], baseName, shiftName;
12518
    if (scopeObj) {
12519
        if (runFor(scopeObj[prefix + modifiers(name, event, !isChar)])) {
12520
            handled = true;
12521
        }
12522
        else if (isChar && (event.altKey || event.metaKey || event.ctrlKey) &&
12523
            // Ctrl-Alt may be used for AltGr on Windows
12524
            !(browser.windows && event.ctrlKey && event.altKey) &&
12525
            (baseName = base[event.keyCode]) && baseName != name) {
12526
            if (runFor(scopeObj[prefix + modifiers(baseName, event, true)])) {
12527
                handled = true;
12528
            }
12529
            else if (event.shiftKey && (shiftName = shift[event.keyCode]) != name && shiftName != baseName &&
12530
                runFor(scopeObj[prefix + modifiers(shiftName, event, false)])) {
12531
                handled = true;
12532
            }
12533
        }
12534
        else if (isChar && event.shiftKey &&
12535
            runFor(scopeObj[prefix + modifiers(name, event, true)])) {
12536
            handled = true;
12537
        }
12538
        if (!handled && runFor(scopeObj._any))
12539
            handled = true;
12540
    }
12541
    if (prevented)
12542
        handled = true;
12543
    if (handled && stopPropagation)
12544
        event.stopPropagation();
12545
    return handled;
12546
}
12547
 
12548
/**
12549
Implementation of [`LayerMarker`](https://codemirror.net/6/docs/ref/#view.LayerMarker) that creates
12550
a rectangle at a given set of coordinates.
12551
*/
12552
class RectangleMarker {
12553
    /**
12554
    Create a marker with the given class and dimensions. If `width`
12555
    is null, the DOM element will get no width style.
12556
    */
12557
    constructor(className,
12558
    /**
12559
    The left position of the marker (in pixels, document-relative).
12560
    */
12561
    left,
12562
    /**
12563
    The top position of the marker.
12564
    */
12565
    top,
12566
    /**
12567
    The width of the marker, or null if it shouldn't get a width assigned.
12568
    */
12569
    width,
12570
    /**
12571
    The height of the marker.
12572
    */
12573
    height) {
12574
        this.className = className;
12575
        this.left = left;
12576
        this.top = top;
12577
        this.width = width;
12578
        this.height = height;
12579
    }
12580
    draw() {
12581
        let elt = document.createElement("div");
12582
        elt.className = this.className;
12583
        this.adjust(elt);
12584
        return elt;
12585
    }
12586
    update(elt, prev) {
12587
        if (prev.className != this.className)
12588
            return false;
12589
        this.adjust(elt);
12590
        return true;
12591
    }
12592
    adjust(elt) {
12593
        elt.style.left = this.left + "px";
12594
        elt.style.top = this.top + "px";
12595
        if (this.width != null)
12596
            elt.style.width = this.width + "px";
12597
        elt.style.height = this.height + "px";
12598
    }
12599
    eq(p) {
12600
        return this.left == p.left && this.top == p.top && this.width == p.width && this.height == p.height &&
12601
            this.className == p.className;
12602
    }
12603
    /**
12604
    Create a set of rectangles for the given selection range,
12605
    assigning them theclass`className`. Will create a single
12606
    rectangle for empty ranges, and a set of selection-style
12607
    rectangles covering the range's content (in a bidi-aware
12608
    way) for non-empty ones.
12609
    */
12610
    static forRange(view, className, range) {
12611
        if (range.empty) {
12612
            let pos = view.coordsAtPos(range.head, range.assoc || 1);
12613
            if (!pos)
12614
                return [];
12615
            let base = getBase(view);
12616
            return [new RectangleMarker(className, pos.left - base.left, pos.top - base.top, null, pos.bottom - pos.top)];
12617
        }
12618
        else {
12619
            return rectanglesForRange(view, className, range);
12620
        }
12621
    }
12622
}
12623
function getBase(view) {
12624
    let rect = view.scrollDOM.getBoundingClientRect();
12625
    let left = view.textDirection == Direction.LTR ? rect.left : rect.right - view.scrollDOM.clientWidth * view.scaleX;
12626
    return { left: left - view.scrollDOM.scrollLeft * view.scaleX, top: rect.top - view.scrollDOM.scrollTop * view.scaleY };
12627
}
12628
function wrappedLine(view, pos, inside) {
12629
    let range = EditorSelection.cursor(pos);
12630
    return { from: Math.max(inside.from, view.moveToLineBoundary(range, false, true).from),
12631
        to: Math.min(inside.to, view.moveToLineBoundary(range, true, true).from),
12632
        type: BlockType.Text };
12633
}
12634
function rectanglesForRange(view, className, range) {
12635
    if (range.to <= view.viewport.from || range.from >= view.viewport.to)
12636
        return [];
12637
    let from = Math.max(range.from, view.viewport.from), to = Math.min(range.to, view.viewport.to);
12638
    let ltr = view.textDirection == Direction.LTR;
12639
    let content = view.contentDOM, contentRect = content.getBoundingClientRect(), base = getBase(view);
12640
    let lineElt = content.querySelector(".cm-line"), lineStyle = lineElt && window.getComputedStyle(lineElt);
12641
    let leftSide = contentRect.left +
12642
        (lineStyle ? parseInt(lineStyle.paddingLeft) + Math.min(0, parseInt(lineStyle.textIndent)) : 0);
12643
    let rightSide = contentRect.right - (lineStyle ? parseInt(lineStyle.paddingRight) : 0);
12644
    let startBlock = blockAt(view, from), endBlock = blockAt(view, to);
12645
    let visualStart = startBlock.type == BlockType.Text ? startBlock : null;
12646
    let visualEnd = endBlock.type == BlockType.Text ? endBlock : null;
12647
    if (visualStart && (view.lineWrapping || startBlock.widgetLineBreaks))
12648
        visualStart = wrappedLine(view, from, visualStart);
12649
    if (visualEnd && (view.lineWrapping || endBlock.widgetLineBreaks))
12650
        visualEnd = wrappedLine(view, to, visualEnd);
12651
    if (visualStart && visualEnd && visualStart.from == visualEnd.from) {
12652
        return pieces(drawForLine(range.from, range.to, visualStart));
12653
    }
12654
    else {
12655
        let top = visualStart ? drawForLine(range.from, null, visualStart) : drawForWidget(startBlock, false);
12656
        let bottom = visualEnd ? drawForLine(null, range.to, visualEnd) : drawForWidget(endBlock, true);
12657
        let between = [];
12658
        if ((visualStart || startBlock).to < (visualEnd || endBlock).from - (visualStart && visualEnd ? 1 : 0) ||
12659
            startBlock.widgetLineBreaks > 1 && top.bottom + view.defaultLineHeight / 2 < bottom.top)
12660
            between.push(piece(leftSide, top.bottom, rightSide, bottom.top));
12661
        else if (top.bottom < bottom.top && view.elementAtHeight((top.bottom + bottom.top) / 2).type == BlockType.Text)
12662
            top.bottom = bottom.top = (top.bottom + bottom.top) / 2;
12663
        return pieces(top).concat(between).concat(pieces(bottom));
12664
    }
12665
    function piece(left, top, right, bottom) {
12666
        return new RectangleMarker(className, left - base.left, top - base.top - 0.01 /* C.Epsilon */, right - left, bottom - top + 0.01 /* C.Epsilon */);
12667
    }
12668
    function pieces({ top, bottom, horizontal }) {
12669
        let pieces = [];
12670
        for (let i = 0; i < horizontal.length; i += 2)
12671
            pieces.push(piece(horizontal[i], top, horizontal[i + 1], bottom));
12672
        return pieces;
12673
    }
12674
    // Gets passed from/to in line-local positions
12675
    function drawForLine(from, to, line) {
12676
        let top = 1e9, bottom = -1e9, horizontal = [];
12677
        function addSpan(from, fromOpen, to, toOpen, dir) {
12678
            // Passing 2/-2 is a kludge to force the view to return
12679
            // coordinates on the proper side of block widgets, since
12680
            // normalizing the side there, though appropriate for most
12681
            // coordsAtPos queries, would break selection drawing.
12682
            let fromCoords = view.coordsAtPos(from, (from == line.to ? -2 : 2));
12683
            let toCoords = view.coordsAtPos(to, (to == line.from ? 2 : -2));
12684
            if (!fromCoords || !toCoords)
12685
                return;
12686
            top = Math.min(fromCoords.top, toCoords.top, top);
12687
            bottom = Math.max(fromCoords.bottom, toCoords.bottom, bottom);
12688
            if (dir == Direction.LTR)
12689
                horizontal.push(ltr && fromOpen ? leftSide : fromCoords.left, ltr && toOpen ? rightSide : toCoords.right);
12690
            else
12691
                horizontal.push(!ltr && toOpen ? leftSide : toCoords.left, !ltr && fromOpen ? rightSide : fromCoords.right);
12692
        }
12693
        let start = from !== null && from !== void 0 ? from : line.from, end = to !== null && to !== void 0 ? to : line.to;
12694
        // Split the range by visible range and document line
12695
        for (let r of view.visibleRanges)
12696
            if (r.to > start && r.from < end) {
12697
                for (let pos = Math.max(r.from, start), endPos = Math.min(r.to, end);;) {
12698
                    let docLine = view.state.doc.lineAt(pos);
12699
                    for (let span of view.bidiSpans(docLine)) {
12700
                        let spanFrom = span.from + docLine.from, spanTo = span.to + docLine.from;
12701
                        if (spanFrom >= endPos)
12702
                            break;
12703
                        if (spanTo > pos)
12704
                            addSpan(Math.max(spanFrom, pos), from == null && spanFrom <= start, Math.min(spanTo, endPos), to == null && spanTo >= end, span.dir);
12705
                    }
12706
                    pos = docLine.to + 1;
12707
                    if (pos >= endPos)
12708
                        break;
12709
                }
12710
            }
12711
        if (horizontal.length == 0)
12712
            addSpan(start, from == null, end, to == null, view.textDirection);
12713
        return { top, bottom, horizontal };
12714
    }
12715
    function drawForWidget(block, top) {
12716
        let y = contentRect.top + (top ? block.top : block.bottom);
12717
        return { top: y, bottom: y, horizontal: [] };
12718
    }
12719
}
12720
function sameMarker(a, b) {
12721
    return a.constructor == b.constructor && a.eq(b);
12722
}
12723
class LayerView {
12724
    constructor(view, layer) {
12725
        this.view = view;
12726
        this.layer = layer;
12727
        this.drawn = [];
12728
        this.scaleX = 1;
12729
        this.scaleY = 1;
12730
        this.measureReq = { read: this.measure.bind(this), write: this.draw.bind(this) };
12731
        this.dom = view.scrollDOM.appendChild(document.createElement("div"));
12732
        this.dom.classList.add("cm-layer");
12733
        if (layer.above)
12734
            this.dom.classList.add("cm-layer-above");
12735
        if (layer.class)
12736
            this.dom.classList.add(layer.class);
12737
        this.scale();
12738
        this.dom.setAttribute("aria-hidden", "true");
12739
        this.setOrder(view.state);
12740
        view.requestMeasure(this.measureReq);
12741
        if (layer.mount)
12742
            layer.mount(this.dom, view);
12743
    }
12744
    update(update) {
12745
        if (update.startState.facet(layerOrder) != update.state.facet(layerOrder))
12746
            this.setOrder(update.state);
12747
        if (this.layer.update(update, this.dom) || update.geometryChanged) {
12748
            this.scale();
12749
            update.view.requestMeasure(this.measureReq);
12750
        }
12751
    }
12752
    docViewUpdate(view) {
12753
        if (this.layer.updateOnDocViewUpdate !== false)
12754
            view.requestMeasure(this.measureReq);
12755
    }
12756
    setOrder(state) {
12757
        let pos = 0, order = state.facet(layerOrder);
12758
        while (pos < order.length && order[pos] != this.layer)
12759
            pos++;
12760
        this.dom.style.zIndex = String((this.layer.above ? 150 : -1) - pos);
12761
    }
12762
    measure() {
12763
        return this.layer.markers(this.view);
12764
    }
12765
    scale() {
12766
        let { scaleX, scaleY } = this.view;
12767
        if (scaleX != this.scaleX || scaleY != this.scaleY) {
12768
            this.scaleX = scaleX;
12769
            this.scaleY = scaleY;
12770
            this.dom.style.transform = `scale(${1 / scaleX}, ${1 / scaleY})`;
12771
        }
12772
    }
12773
    draw(markers) {
12774
        if (markers.length != this.drawn.length || markers.some((p, i) => !sameMarker(p, this.drawn[i]))) {
12775
            let old = this.dom.firstChild, oldI = 0;
12776
            for (let marker of markers) {
12777
                if (marker.update && old && marker.constructor && this.drawn[oldI].constructor &&
12778
                    marker.update(old, this.drawn[oldI])) {
12779
                    old = old.nextSibling;
12780
                    oldI++;
12781
                }
12782
                else {
12783
                    this.dom.insertBefore(marker.draw(), old);
12784
                }
12785
            }
12786
            while (old) {
12787
                let next = old.nextSibling;
12788
                old.remove();
12789
                old = next;
12790
            }
12791
            this.drawn = markers;
12792
        }
12793
    }
12794
    destroy() {
12795
        if (this.layer.destroy)
12796
            this.layer.destroy(this.dom, this.view);
12797
        this.dom.remove();
12798
    }
12799
}
12800
const layerOrder = /*@__PURE__*/Facet.define();
12801
/**
12802
Define a layer.
12803
*/
12804
function layer(config) {
12805
    return [
12806
        ViewPlugin.define(v => new LayerView(v, config)),
12807
        layerOrder.of(config)
12808
    ];
12809
}
12810
 
12811
const CanHidePrimary = !browser.ios; // FIXME test IE
12812
const selectionConfig = /*@__PURE__*/Facet.define({
12813
    combine(configs) {
12814
        return combineConfig(configs, {
12815
            cursorBlinkRate: 1200,
12816
            drawRangeCursor: true
12817
        }, {
12818
            cursorBlinkRate: (a, b) => Math.min(a, b),
12819
            drawRangeCursor: (a, b) => a || b
12820
        });
12821
    }
12822
});
12823
/**
12824
Returns an extension that hides the browser's native selection and
12825
cursor, replacing the selection with a background behind the text
12826
(with the `cm-selectionBackground` class), and the
12827
cursors with elements overlaid over the code (using
12828
`cm-cursor-primary` and `cm-cursor-secondary`).
12829
 
12830
This allows the editor to display secondary selection ranges, and
12831
tends to produce a type of selection more in line with that users
12832
expect in a text editor (the native selection styling will often
12833
leave gaps between lines and won't fill the horizontal space after
12834
a line when the selection continues past it).
12835
 
12836
It does have a performance cost, in that it requires an extra DOM
12837
layout cycle for many updates (the selection is drawn based on DOM
12838
layout information that's only available after laying out the
12839
content).
12840
*/
12841
function drawSelection(config = {}) {
12842
    return [
12843
        selectionConfig.of(config),
12844
        cursorLayer,
12845
        selectionLayer,
12846
        hideNativeSelection,
12847
        nativeSelectionHidden.of(true)
12848
    ];
12849
}
12850
function configChanged(update) {
12851
    return update.startState.facet(selectionConfig) != update.state.facet(selectionConfig);
12852
}
12853
const cursorLayer = /*@__PURE__*/layer({
12854
    above: true,
12855
    markers(view) {
12856
        let { state } = view, conf = state.facet(selectionConfig);
12857
        let cursors = [];
12858
        for (let r of state.selection.ranges) {
12859
            let prim = r == state.selection.main;
12860
            if (r.empty ? !prim || CanHidePrimary : conf.drawRangeCursor) {
12861
                let className = prim ? "cm-cursor cm-cursor-primary" : "cm-cursor cm-cursor-secondary";
12862
                let cursor = r.empty ? r : EditorSelection.cursor(r.head, r.head > r.anchor ? -1 : 1);
12863
                for (let piece of RectangleMarker.forRange(view, className, cursor))
12864
                    cursors.push(piece);
12865
            }
12866
        }
12867
        return cursors;
12868
    },
12869
    update(update, dom) {
12870
        if (update.transactions.some(tr => tr.selection))
12871
            dom.style.animationName = dom.style.animationName == "cm-blink" ? "cm-blink2" : "cm-blink";
12872
        let confChange = configChanged(update);
12873
        if (confChange)
12874
            setBlinkRate(update.state, dom);
12875
        return update.docChanged || update.selectionSet || confChange;
12876
    },
12877
    mount(dom, view) {
12878
        setBlinkRate(view.state, dom);
12879
    },
12880
    class: "cm-cursorLayer"
12881
});
12882
function setBlinkRate(state, dom) {
12883
    dom.style.animationDuration = state.facet(selectionConfig).cursorBlinkRate + "ms";
12884
}
12885
const selectionLayer = /*@__PURE__*/layer({
12886
    above: false,
12887
    markers(view) {
12888
        return view.state.selection.ranges.map(r => r.empty ? [] : RectangleMarker.forRange(view, "cm-selectionBackground", r))
12889
            .reduce((a, b) => a.concat(b));
12890
    },
12891
    update(update, dom) {
12892
        return update.docChanged || update.selectionSet || update.viewportChanged || configChanged(update);
12893
    },
12894
    class: "cm-selectionLayer"
12895
});
12896
const themeSpec = {
12897
    ".cm-line": {
12898
        "& ::selection": { backgroundColor: "transparent !important" },
12899
        "&::selection": { backgroundColor: "transparent !important" }
12900
    }
12901
};
12902
if (CanHidePrimary) {
12903
    themeSpec[".cm-line"].caretColor = "transparent !important";
12904
    themeSpec[".cm-content"] = { caretColor: "transparent !important" };
12905
}
12906
const hideNativeSelection = /*@__PURE__*/Prec.highest(/*@__PURE__*/EditorView.theme(themeSpec));
12907
 
12908
const setDropCursorPos = /*@__PURE__*/StateEffect.define({
12909
    map(pos, mapping) { return pos == null ? null : mapping.mapPos(pos); }
12910
});
12911
const dropCursorPos = /*@__PURE__*/StateField.define({
12912
    create() { return null; },
12913
    update(pos, tr) {
12914
        if (pos != null)
12915
            pos = tr.changes.mapPos(pos);
12916
        return tr.effects.reduce((pos, e) => e.is(setDropCursorPos) ? e.value : pos, pos);
12917
    }
12918
});
12919
const drawDropCursor = /*@__PURE__*/ViewPlugin.fromClass(class {
12920
    constructor(view) {
12921
        this.view = view;
12922
        this.cursor = null;
12923
        this.measureReq = { read: this.readPos.bind(this), write: this.drawCursor.bind(this) };
12924
    }
12925
    update(update) {
12926
        var _a;
12927
        let cursorPos = update.state.field(dropCursorPos);
12928
        if (cursorPos == null) {
12929
            if (this.cursor != null) {
12930
                (_a = this.cursor) === null || _a === void 0 ? void 0 : _a.remove();
12931
                this.cursor = null;
12932
            }
12933
        }
12934
        else {
12935
            if (!this.cursor) {
12936
                this.cursor = this.view.scrollDOM.appendChild(document.createElement("div"));
12937
                this.cursor.className = "cm-dropCursor";
12938
            }
12939
            if (update.startState.field(dropCursorPos) != cursorPos || update.docChanged || update.geometryChanged)
12940
                this.view.requestMeasure(this.measureReq);
12941
        }
12942
    }
12943
    readPos() {
12944
        let { view } = this;
12945
        let pos = view.state.field(dropCursorPos);
12946
        let rect = pos != null && view.coordsAtPos(pos);
12947
        if (!rect)
12948
            return null;
12949
        let outer = view.scrollDOM.getBoundingClientRect();
12950
        return {
12951
            left: rect.left - outer.left + view.scrollDOM.scrollLeft * view.scaleX,
12952
            top: rect.top - outer.top + view.scrollDOM.scrollTop * view.scaleY,
12953
            height: rect.bottom - rect.top
12954
        };
12955
    }
12956
    drawCursor(pos) {
12957
        if (this.cursor) {
12958
            let { scaleX, scaleY } = this.view;
12959
            if (pos) {
12960
                this.cursor.style.left = pos.left / scaleX + "px";
12961
                this.cursor.style.top = pos.top / scaleY + "px";
12962
                this.cursor.style.height = pos.height / scaleY + "px";
12963
            }
12964
            else {
12965
                this.cursor.style.left = "-100000px";
12966
            }
12967
        }
12968
    }
12969
    destroy() {
12970
        if (this.cursor)
12971
            this.cursor.remove();
12972
    }
12973
    setDropPos(pos) {
12974
        if (this.view.state.field(dropCursorPos) != pos)
12975
            this.view.dispatch({ effects: setDropCursorPos.of(pos) });
12976
    }
12977
}, {
12978
    eventObservers: {
12979
        dragover(event) {
12980
            this.setDropPos(this.view.posAtCoords({ x: event.clientX, y: event.clientY }));
12981
        },
12982
        dragleave(event) {
12983
            if (event.target == this.view.contentDOM || !this.view.contentDOM.contains(event.relatedTarget))
12984
                this.setDropPos(null);
12985
        },
12986
        dragend() {
12987
            this.setDropPos(null);
12988
        },
12989
        drop() {
12990
            this.setDropPos(null);
12991
        }
12992
    }
12993
});
12994
/**
12995
Draws a cursor at the current drop position when something is
12996
dragged over the editor.
12997
*/
12998
function dropCursor() {
12999
    return [dropCursorPos, drawDropCursor];
13000
}
13001
 
13002
function iterMatches(doc, re, from, to, f) {
13003
    re.lastIndex = 0;
13004
    for (let cursor = doc.iterRange(from, to), pos = from, m; !cursor.next().done; pos += cursor.value.length) {
13005
        if (!cursor.lineBreak)
13006
            while (m = re.exec(cursor.value))
13007
                f(pos + m.index, m);
13008
    }
13009
}
13010
function matchRanges(view, maxLength) {
13011
    let visible = view.visibleRanges;
13012
    if (visible.length == 1 && visible[0].from == view.viewport.from &&
13013
        visible[0].to == view.viewport.to)
13014
        return visible;
13015
    let result = [];
13016
    for (let { from, to } of visible) {
13017
        from = Math.max(view.state.doc.lineAt(from).from, from - maxLength);
13018
        to = Math.min(view.state.doc.lineAt(to).to, to + maxLength);
13019
        if (result.length && result[result.length - 1].to >= from)
13020
            result[result.length - 1].to = to;
13021
        else
13022
            result.push({ from, to });
13023
    }
13024
    return result;
13025
}
13026
/**
13027
Helper class used to make it easier to maintain decorations on
13028
visible code that matches a given regular expression. To be used
13029
in a [view plugin](https://codemirror.net/6/docs/ref/#view.ViewPlugin). Instances of this object
13030
represent a matching configuration.
13031
*/
13032
class MatchDecorator {
13033
    /**
13034
    Create a decorator.
13035
    */
13036
    constructor(config) {
13037
        const { regexp, decoration, decorate, boundary, maxLength = 1000 } = config;
13038
        if (!regexp.global)
13039
            throw new RangeError("The regular expression given to MatchDecorator should have its 'g' flag set");
13040
        this.regexp = regexp;
13041
        if (decorate) {
13042
            this.addMatch = (match, view, from, add) => decorate(add, from, from + match[0].length, match, view);
13043
        }
13044
        else if (typeof decoration == "function") {
13045
            this.addMatch = (match, view, from, add) => {
13046
                let deco = decoration(match, view, from);
13047
                if (deco)
13048
                    add(from, from + match[0].length, deco);
13049
            };
13050
        }
13051
        else if (decoration) {
13052
            this.addMatch = (match, _view, from, add) => add(from, from + match[0].length, decoration);
13053
        }
13054
        else {
13055
            throw new RangeError("Either 'decorate' or 'decoration' should be provided to MatchDecorator");
13056
        }
13057
        this.boundary = boundary;
13058
        this.maxLength = maxLength;
13059
    }
13060
    /**
13061
    Compute the full set of decorations for matches in the given
13062
    view's viewport. You'll want to call this when initializing your
13063
    plugin.
13064
    */
13065
    createDeco(view) {
13066
        let build = new RangeSetBuilder(), add = build.add.bind(build);
13067
        for (let { from, to } of matchRanges(view, this.maxLength))
13068
            iterMatches(view.state.doc, this.regexp, from, to, (from, m) => this.addMatch(m, view, from, add));
13069
        return build.finish();
13070
    }
13071
    /**
13072
    Update a set of decorations for a view update. `deco` _must_ be
13073
    the set of decorations produced by _this_ `MatchDecorator` for
13074
    the view state before the update.
13075
    */
13076
    updateDeco(update, deco) {
13077
        let changeFrom = 1e9, changeTo = -1;
13078
        if (update.docChanged)
13079
            update.changes.iterChanges((_f, _t, from, to) => {
13080
                if (to > update.view.viewport.from && from < update.view.viewport.to) {
13081
                    changeFrom = Math.min(from, changeFrom);
13082
                    changeTo = Math.max(to, changeTo);
13083
                }
13084
            });
13085
        if (update.viewportChanged || changeTo - changeFrom > 1000)
13086
            return this.createDeco(update.view);
13087
        if (changeTo > -1)
13088
            return this.updateRange(update.view, deco.map(update.changes), changeFrom, changeTo);
13089
        return deco;
13090
    }
13091
    updateRange(view, deco, updateFrom, updateTo) {
13092
        for (let r of view.visibleRanges) {
13093
            let from = Math.max(r.from, updateFrom), to = Math.min(r.to, updateTo);
13094
            if (to > from) {
13095
                let fromLine = view.state.doc.lineAt(from), toLine = fromLine.to < to ? view.state.doc.lineAt(to) : fromLine;
13096
                let start = Math.max(r.from, fromLine.from), end = Math.min(r.to, toLine.to);
13097
                if (this.boundary) {
13098
                    for (; from > fromLine.from; from--)
13099
                        if (this.boundary.test(fromLine.text[from - 1 - fromLine.from])) {
13100
                            start = from;
13101
                            break;
13102
                        }
13103
                    for (; to < toLine.to; to++)
13104
                        if (this.boundary.test(toLine.text[to - toLine.from])) {
13105
                            end = to;
13106
                            break;
13107
                        }
13108
                }
13109
                let ranges = [], m;
13110
                let add = (from, to, deco) => ranges.push(deco.range(from, to));
13111
                if (fromLine == toLine) {
13112
                    this.regexp.lastIndex = start - fromLine.from;
13113
                    while ((m = this.regexp.exec(fromLine.text)) && m.index < end - fromLine.from)
13114
                        this.addMatch(m, view, m.index + fromLine.from, add);
13115
                }
13116
                else {
13117
                    iterMatches(view.state.doc, this.regexp, start, end, (from, m) => this.addMatch(m, view, from, add));
13118
                }
13119
                deco = deco.update({ filterFrom: start, filterTo: end, filter: (from, to) => from < start || to > end, add: ranges });
13120
            }
13121
        }
13122
        return deco;
13123
    }
13124
}
13125
 
13126
const UnicodeRegexpSupport = /x/.unicode != null ? "gu" : "g";
13127
const Specials = /*@__PURE__*/new RegExp("[\u0000-\u0008\u000a-\u001f\u007f-\u009f\u00ad\u061c\u200b\u200e\u200f\u2028\u2029\u202d\u202e\u2066\u2067\u2069\ufeff\ufff9-\ufffc]", UnicodeRegexpSupport);
13128
const Names = {
13129
    0: "null",
13130
    7: "bell",
13131
    8: "backspace",
13132
    10: "newline",
13133
    11: "vertical tab",
13134
    13: "carriage return",
13135
    27: "escape",
13136
    8203: "zero width space",
13137
    8204: "zero width non-joiner",
13138
    8205: "zero width joiner",
13139
    8206: "left-to-right mark",
13140
    8207: "right-to-left mark",
13141
    8232: "line separator",
13142
    8237: "left-to-right override",
13143
    8238: "right-to-left override",
13144
    8294: "left-to-right isolate",
13145
    8295: "right-to-left isolate",
13146
    8297: "pop directional isolate",
13147
    8233: "paragraph separator",
13148
    65279: "zero width no-break space",
13149
    65532: "object replacement"
13150
};
13151
let _supportsTabSize = null;
13152
function supportsTabSize() {
13153
    var _a;
13154
    if (_supportsTabSize == null && typeof document != "undefined" && document.body) {
13155
        let styles = document.body.style;
13156
        _supportsTabSize = ((_a = styles.tabSize) !== null && _a !== void 0 ? _a : styles.MozTabSize) != null;
13157
    }
13158
    return _supportsTabSize || false;
13159
}
13160
const specialCharConfig = /*@__PURE__*/Facet.define({
13161
    combine(configs) {
13162
        let config = combineConfig(configs, {
13163
            render: null,
13164
            specialChars: Specials,
13165
            addSpecialChars: null
13166
        });
13167
        if (config.replaceTabs = !supportsTabSize())
13168
            config.specialChars = new RegExp("\t|" + config.specialChars.source, UnicodeRegexpSupport);
13169
        if (config.addSpecialChars)
13170
            config.specialChars = new RegExp(config.specialChars.source + "|" + config.addSpecialChars.source, UnicodeRegexpSupport);
13171
        return config;
13172
    }
13173
});
13174
/**
13175
Returns an extension that installs highlighting of special
13176
characters.
13177
*/
13178
function highlightSpecialChars(
13179
/**
13180
Configuration options.
13181
*/
13182
config = {}) {
13183
    return [specialCharConfig.of(config), specialCharPlugin()];
13184
}
13185
let _plugin = null;
13186
function specialCharPlugin() {
13187
    return _plugin || (_plugin = ViewPlugin.fromClass(class {
13188
        constructor(view) {
13189
            this.view = view;
13190
            this.decorations = Decoration.none;
13191
            this.decorationCache = Object.create(null);
13192
            this.decorator = this.makeDecorator(view.state.facet(specialCharConfig));
13193
            this.decorations = this.decorator.createDeco(view);
13194
        }
13195
        makeDecorator(conf) {
13196
            return new MatchDecorator({
13197
                regexp: conf.specialChars,
13198
                decoration: (m, view, pos) => {
13199
                    let { doc } = view.state;
13200
                    let code = codePointAt(m[0], 0);
13201
                    if (code == 9) {
13202
                        let line = doc.lineAt(pos);
13203
                        let size = view.state.tabSize, col = countColumn(line.text, size, pos - line.from);
13204
                        return Decoration.replace({
13205
                            widget: new TabWidget((size - (col % size)) * this.view.defaultCharacterWidth / this.view.scaleX)
13206
                        });
13207
                    }
13208
                    return this.decorationCache[code] ||
13209
                        (this.decorationCache[code] = Decoration.replace({ widget: new SpecialCharWidget(conf, code) }));
13210
                },
13211
                boundary: conf.replaceTabs ? undefined : /[^]/
13212
            });
13213
        }
13214
        update(update) {
13215
            let conf = update.state.facet(specialCharConfig);
13216
            if (update.startState.facet(specialCharConfig) != conf) {
13217
                this.decorator = this.makeDecorator(conf);
13218
                this.decorations = this.decorator.createDeco(update.view);
13219
            }
13220
            else {
13221
                this.decorations = this.decorator.updateDeco(update, this.decorations);
13222
            }
13223
        }
13224
    }, {
13225
        decorations: v => v.decorations
13226
    }));
13227
}
13228
const DefaultPlaceholder = "\u2022";
13229
// Assigns placeholder characters from the Control Pictures block to
13230
// ASCII control characters
13231
function placeholder$1(code) {
13232
    if (code >= 32)
13233
        return DefaultPlaceholder;
13234
    if (code == 10)
13235
        return "\u2424";
13236
    return String.fromCharCode(9216 + code);
13237
}
13238
class SpecialCharWidget extends WidgetType {
13239
    constructor(options, code) {
13240
        super();
13241
        this.options = options;
13242
        this.code = code;
13243
    }
13244
    eq(other) { return other.code == this.code; }
13245
    toDOM(view) {
13246
        let ph = placeholder$1(this.code);
13247
        let desc = view.state.phrase("Control character") + " " + (Names[this.code] || "0x" + this.code.toString(16));
13248
        let custom = this.options.render && this.options.render(this.code, desc, ph);
13249
        if (custom)
13250
            return custom;
13251
        let span = document.createElement("span");
13252
        span.textContent = ph;
13253
        span.title = desc;
13254
        span.setAttribute("aria-label", desc);
13255
        span.className = "cm-specialChar";
13256
        return span;
13257
    }
13258
    ignoreEvent() { return false; }
13259
}
13260
class TabWidget extends WidgetType {
13261
    constructor(width) {
13262
        super();
13263
        this.width = width;
13264
    }
13265
    eq(other) { return other.width == this.width; }
13266
    toDOM() {
13267
        let span = document.createElement("span");
13268
        span.textContent = "\t";
13269
        span.className = "cm-tab";
13270
        span.style.width = this.width + "px";
13271
        return span;
13272
    }
13273
    ignoreEvent() { return false; }
13274
}
13275
 
13276
/**
13277
Mark lines that have a cursor on them with the `"cm-activeLine"`
13278
DOM class.
13279
*/
13280
function highlightActiveLine() {
13281
    return activeLineHighlighter;
13282
}
13283
const lineDeco = /*@__PURE__*/Decoration.line({ class: "cm-activeLine" });
13284
const activeLineHighlighter = /*@__PURE__*/ViewPlugin.fromClass(class {
13285
    constructor(view) {
13286
        this.decorations = this.getDeco(view);
13287
    }
13288
    update(update) {
13289
        if (update.docChanged || update.selectionSet)
13290
            this.decorations = this.getDeco(update.view);
13291
    }
13292
    getDeco(view) {
13293
        let lastLineStart = -1, deco = [];
13294
        for (let r of view.state.selection.ranges) {
13295
            let line = view.lineBlockAt(r.head);
13296
            if (line.from > lastLineStart) {
13297
                deco.push(lineDeco.range(line.from));
13298
                lastLineStart = line.from;
13299
            }
13300
        }
13301
        return Decoration.set(deco);
13302
    }
13303
}, {
13304
    decorations: v => v.decorations
13305
});
13306
 
13307
// Don't compute precise column positions for line offsets above this
13308
// (since it could get expensive). Assume offset==column for them.
13309
const MaxOff = 2000;
13310
function rectangleFor(state, a, b) {
13311
    let startLine = Math.min(a.line, b.line), endLine = Math.max(a.line, b.line);
13312
    let ranges = [];
13313
    if (a.off > MaxOff || b.off > MaxOff || a.col < 0 || b.col < 0) {
13314
        let startOff = Math.min(a.off, b.off), endOff = Math.max(a.off, b.off);
13315
        for (let i = startLine; i <= endLine; i++) {
13316
            let line = state.doc.line(i);
13317
            if (line.length <= endOff)
13318
                ranges.push(EditorSelection.range(line.from + startOff, line.to + endOff));
13319
        }
13320
    }
13321
    else {
13322
        let startCol = Math.min(a.col, b.col), endCol = Math.max(a.col, b.col);
13323
        for (let i = startLine; i <= endLine; i++) {
13324
            let line = state.doc.line(i);
13325
            let start = findColumn(line.text, startCol, state.tabSize, true);
13326
            if (start < 0) {
13327
                ranges.push(EditorSelection.cursor(line.to));
13328
            }
13329
            else {
13330
                let end = findColumn(line.text, endCol, state.tabSize);
13331
                ranges.push(EditorSelection.range(line.from + start, line.from + end));
13332
            }
13333
        }
13334
    }
13335
    return ranges;
13336
}
13337
function absoluteColumn(view, x) {
13338
    let ref = view.coordsAtPos(view.viewport.from);
13339
    return ref ? Math.round(Math.abs((ref.left - x) / view.defaultCharacterWidth)) : -1;
13340
}
13341
function getPos(view, event) {
13342
    let offset = view.posAtCoords({ x: event.clientX, y: event.clientY }, false);
13343
    let line = view.state.doc.lineAt(offset), off = offset - line.from;
13344
    let col = off > MaxOff ? -1
13345
        : off == line.length ? absoluteColumn(view, event.clientX)
13346
            : countColumn(line.text, view.state.tabSize, offset - line.from);
13347
    return { line: line.number, col, off };
13348
}
13349
function rectangleSelectionStyle(view, event) {
13350
    let start = getPos(view, event), startSel = view.state.selection;
13351
    if (!start)
13352
        return null;
13353
    return {
13354
        update(update) {
13355
            if (update.docChanged) {
13356
                let newStart = update.changes.mapPos(update.startState.doc.line(start.line).from);
13357
                let newLine = update.state.doc.lineAt(newStart);
13358
                start = { line: newLine.number, col: start.col, off: Math.min(start.off, newLine.length) };
13359
                startSel = startSel.map(update.changes);
13360
            }
13361
        },
13362
        get(event, _extend, multiple) {
13363
            let cur = getPos(view, event);
13364
            if (!cur)
13365
                return startSel;
13366
            let ranges = rectangleFor(view.state, start, cur);
13367
            if (!ranges.length)
13368
                return startSel;
13369
            if (multiple)
13370
                return EditorSelection.create(ranges.concat(startSel.ranges));
13371
            else
13372
                return EditorSelection.create(ranges);
13373
        }
13374
    };
13375
}
13376
/**
13377
Create an extension that enables rectangular selections. By
13378
default, it will react to left mouse drag with the Alt key held
13379
down. When such a selection occurs, the text within the rectangle
13380
that was dragged over will be selected, as one selection
13381
[range](https://codemirror.net/6/docs/ref/#state.SelectionRange) per line.
13382
*/
13383
function rectangularSelection(options) {
13384
    let filter = (options === null || options === void 0 ? void 0 : options.eventFilter) || (e => e.altKey && e.button == 0);
13385
    return EditorView.mouseSelectionStyle.of((view, event) => filter(event) ? rectangleSelectionStyle(view, event) : null);
13386
}
13387
const keys = {
13388
    Alt: [18, e => !!e.altKey],
13389
    Control: [17, e => !!e.ctrlKey],
13390
    Shift: [16, e => !!e.shiftKey],
13391
    Meta: [91, e => !!e.metaKey]
13392
};
13393
const showCrosshair = { style: "cursor: crosshair" };
13394
/**
13395
Returns an extension that turns the pointer cursor into a
13396
crosshair when a given modifier key, defaulting to Alt, is held
13397
down. Can serve as a visual hint that rectangular selection is
13398
going to happen when paired with
13399
[`rectangularSelection`](https://codemirror.net/6/docs/ref/#view.rectangularSelection).
13400
*/
13401
function crosshairCursor(options = {}) {
13402
    let [code, getter] = keys[options.key || "Alt"];
13403
    let plugin = ViewPlugin.fromClass(class {
13404
        constructor(view) {
13405
            this.view = view;
13406
            this.isDown = false;
13407
        }
13408
        set(isDown) {
13409
            if (this.isDown != isDown) {
13410
                this.isDown = isDown;
13411
                this.view.update([]);
13412
            }
13413
        }
13414
    }, {
13415
        eventObservers: {
13416
            keydown(e) {
13417
                this.set(e.keyCode == code || getter(e));
13418
            },
13419
            keyup(e) {
13420
                if (e.keyCode == code || !getter(e))
13421
                    this.set(false);
13422
            },
13423
            mousemove(e) {
13424
                this.set(getter(e));
13425
            }
13426
        }
13427
    });
13428
    return [
13429
        plugin,
13430
        EditorView.contentAttributes.of(view => { var _a; return ((_a = view.plugin(plugin)) === null || _a === void 0 ? void 0 : _a.isDown) ? showCrosshair : null; })
13431
    ];
13432
}
13433
 
13434
const Outside = "-10000px";
13435
class TooltipViewManager {
13436
    constructor(view, facet, createTooltipView, removeTooltipView) {
13437
        this.facet = facet;
13438
        this.createTooltipView = createTooltipView;
13439
        this.removeTooltipView = removeTooltipView;
13440
        this.input = view.state.facet(facet);
13441
        this.tooltips = this.input.filter(t => t);
13442
        let prev = null;
13443
        this.tooltipViews = this.tooltips.map(t => prev = createTooltipView(t, prev));
13444
    }
13445
    update(update, above) {
13446
        var _a;
13447
        let input = update.state.facet(this.facet);
13448
        let tooltips = input.filter(x => x);
13449
        if (input === this.input) {
13450
            for (let t of this.tooltipViews)
13451
                if (t.update)
13452
                    t.update(update);
13453
            return false;
13454
        }
13455
        let tooltipViews = [], newAbove = above ? [] : null;
13456
        for (let i = 0; i < tooltips.length; i++) {
13457
            let tip = tooltips[i], known = -1;
13458
            if (!tip)
13459
                continue;
13460
            for (let i = 0; i < this.tooltips.length; i++) {
13461
                let other = this.tooltips[i];
13462
                if (other && other.create == tip.create)
13463
                    known = i;
13464
            }
13465
            if (known < 0) {
13466
                tooltipViews[i] = this.createTooltipView(tip, i ? tooltipViews[i - 1] : null);
13467
                if (newAbove)
13468
                    newAbove[i] = !!tip.above;
13469
            }
13470
            else {
13471
                let tooltipView = tooltipViews[i] = this.tooltipViews[known];
13472
                if (newAbove)
13473
                    newAbove[i] = above[known];
13474
                if (tooltipView.update)
13475
                    tooltipView.update(update);
13476
            }
13477
        }
13478
        for (let t of this.tooltipViews)
13479
            if (tooltipViews.indexOf(t) < 0) {
13480
                this.removeTooltipView(t);
13481
                (_a = t.destroy) === null || _a === void 0 ? void 0 : _a.call(t);
13482
            }
13483
        if (above) {
13484
            newAbove.forEach((val, i) => above[i] = val);
13485
            above.length = newAbove.length;
13486
        }
13487
        this.input = input;
13488
        this.tooltips = tooltips;
13489
        this.tooltipViews = tooltipViews;
13490
        return true;
13491
    }
13492
}
13493
function windowSpace(view) {
13494
    let { win } = view;
13495
    return { top: 0, left: 0, bottom: win.innerHeight, right: win.innerWidth };
13496
}
13497
const tooltipConfig = /*@__PURE__*/Facet.define({
13498
    combine: values => {
13499
        var _a, _b, _c;
13500
        return ({
13501
            position: browser.ios ? "absolute" : ((_a = values.find(conf => conf.position)) === null || _a === void 0 ? void 0 : _a.position) || "fixed",
13502
            parent: ((_b = values.find(conf => conf.parent)) === null || _b === void 0 ? void 0 : _b.parent) || null,
13503
            tooltipSpace: ((_c = values.find(conf => conf.tooltipSpace)) === null || _c === void 0 ? void 0 : _c.tooltipSpace) || windowSpace,
13504
        });
13505
    }
13506
});
13507
const knownHeight = /*@__PURE__*/new WeakMap();
13508
const tooltipPlugin = /*@__PURE__*/ViewPlugin.fromClass(class {
13509
    constructor(view) {
13510
        this.view = view;
13511
        this.above = [];
13512
        this.inView = true;
13513
        this.madeAbsolute = false;
13514
        this.lastTransaction = 0;
13515
        this.measureTimeout = -1;
13516
        let config = view.state.facet(tooltipConfig);
13517
        this.position = config.position;
13518
        this.parent = config.parent;
13519
        this.classes = view.themeClasses;
13520
        this.createContainer();
13521
        this.measureReq = { read: this.readMeasure.bind(this), write: this.writeMeasure.bind(this), key: this };
13522
        this.resizeObserver = typeof ResizeObserver == "function" ? new ResizeObserver(() => this.measureSoon()) : null;
13523
        this.manager = new TooltipViewManager(view, showTooltip, (t, p) => this.createTooltip(t, p), t => {
13524
            if (this.resizeObserver)
13525
                this.resizeObserver.unobserve(t.dom);
13526
            t.dom.remove();
13527
        });
13528
        this.above = this.manager.tooltips.map(t => !!t.above);
13529
        this.intersectionObserver = typeof IntersectionObserver == "function" ? new IntersectionObserver(entries => {
13530
            if (Date.now() > this.lastTransaction - 50 &&
13531
                entries.length > 0 && entries[entries.length - 1].intersectionRatio < 1)
13532
                this.measureSoon();
13533
        }, { threshold: [1] }) : null;
13534
        this.observeIntersection();
13535
        view.win.addEventListener("resize", this.measureSoon = this.measureSoon.bind(this));
13536
        this.maybeMeasure();
13537
    }
13538
    createContainer() {
13539
        if (this.parent) {
13540
            this.container = document.createElement("div");
13541
            this.container.style.position = "relative";
13542
            this.container.className = this.view.themeClasses;
13543
            this.parent.appendChild(this.container);
13544
        }
13545
        else {
13546
            this.container = this.view.dom;
13547
        }
13548
    }
13549
    observeIntersection() {
13550
        if (this.intersectionObserver) {
13551
            this.intersectionObserver.disconnect();
13552
            for (let tooltip of this.manager.tooltipViews)
13553
                this.intersectionObserver.observe(tooltip.dom);
13554
        }
13555
    }
13556
    measureSoon() {
13557
        if (this.measureTimeout < 0)
13558
            this.measureTimeout = setTimeout(() => {
13559
                this.measureTimeout = -1;
13560
                this.maybeMeasure();
13561
            }, 50);
13562
    }
13563
    update(update) {
13564
        if (update.transactions.length)
13565
            this.lastTransaction = Date.now();
13566
        let updated = this.manager.update(update, this.above);
13567
        if (updated)
13568
            this.observeIntersection();
13569
        let shouldMeasure = updated || update.geometryChanged;
13570
        let newConfig = update.state.facet(tooltipConfig);
13571
        if (newConfig.position != this.position && !this.madeAbsolute) {
13572
            this.position = newConfig.position;
13573
            for (let t of this.manager.tooltipViews)
13574
                t.dom.style.position = this.position;
13575
            shouldMeasure = true;
13576
        }
13577
        if (newConfig.parent != this.parent) {
13578
            if (this.parent)
13579
                this.container.remove();
13580
            this.parent = newConfig.parent;
13581
            this.createContainer();
13582
            for (let t of this.manager.tooltipViews)
13583
                this.container.appendChild(t.dom);
13584
            shouldMeasure = true;
13585
        }
13586
        else if (this.parent && this.view.themeClasses != this.classes) {
13587
            this.classes = this.container.className = this.view.themeClasses;
13588
        }
13589
        if (shouldMeasure)
13590
            this.maybeMeasure();
13591
    }
13592
    createTooltip(tooltip, prev) {
13593
        let tooltipView = tooltip.create(this.view);
13594
        let before = prev ? prev.dom : null;
13595
        tooltipView.dom.classList.add("cm-tooltip");
13596
        if (tooltip.arrow && !tooltipView.dom.querySelector(".cm-tooltip > .cm-tooltip-arrow")) {
13597
            let arrow = document.createElement("div");
13598
            arrow.className = "cm-tooltip-arrow";
13599
            tooltipView.dom.insertBefore(arrow, before);
13600
        }
13601
        tooltipView.dom.style.position = this.position;
13602
        tooltipView.dom.style.top = Outside;
13603
        tooltipView.dom.style.left = "0px";
13604
        this.container.insertBefore(tooltipView.dom, before);
13605
        if (tooltipView.mount)
13606
            tooltipView.mount(this.view);
13607
        if (this.resizeObserver)
13608
            this.resizeObserver.observe(tooltipView.dom);
13609
        return tooltipView;
13610
    }
13611
    destroy() {
13612
        var _a, _b, _c;
13613
        this.view.win.removeEventListener("resize", this.measureSoon);
13614
        for (let tooltipView of this.manager.tooltipViews) {
13615
            tooltipView.dom.remove();
13616
            (_a = tooltipView.destroy) === null || _a === void 0 ? void 0 : _a.call(tooltipView);
13617
        }
13618
        if (this.parent)
13619
            this.container.remove();
13620
        (_b = this.resizeObserver) === null || _b === void 0 ? void 0 : _b.disconnect();
13621
        (_c = this.intersectionObserver) === null || _c === void 0 ? void 0 : _c.disconnect();
13622
        clearTimeout(this.measureTimeout);
13623
    }
13624
    readMeasure() {
13625
        let editor = this.view.dom.getBoundingClientRect();
13626
        let scaleX = 1, scaleY = 1, makeAbsolute = false;
13627
        if (this.position == "fixed" && this.manager.tooltipViews.length) {
13628
            let { dom } = this.manager.tooltipViews[0];
13629
            if (browser.gecko) {
13630
                // Firefox sets the element's `offsetParent` to the
13631
                // transformed element when a transform interferes with fixed
13632
                // positioning.
13633
                makeAbsolute = dom.offsetParent != this.container.ownerDocument.body;
13634
            }
13635
            else if (dom.style.top == Outside && dom.style.left == "0px") {
13636
                // On other browsers, we have to awkwardly try and use other
13637
                // information to detect a transform.
13638
                let rect = dom.getBoundingClientRect();
13639
                makeAbsolute = Math.abs(rect.top + 10000) > 1 || Math.abs(rect.left) > 1;
13640
            }
13641
        }
13642
        if (makeAbsolute || this.position == "absolute") {
13643
            if (this.parent) {
13644
                let rect = this.parent.getBoundingClientRect();
13645
                if (rect.width && rect.height) {
13646
                    scaleX = rect.width / this.parent.offsetWidth;
13647
                    scaleY = rect.height / this.parent.offsetHeight;
13648
                }
13649
            }
13650
            else {
13651
                ({ scaleX, scaleY } = this.view.viewState);
13652
            }
13653
        }
13654
        return {
13655
            editor,
13656
            parent: this.parent ? this.container.getBoundingClientRect() : editor,
13657
            pos: this.manager.tooltips.map((t, i) => {
13658
                let tv = this.manager.tooltipViews[i];
13659
                return tv.getCoords ? tv.getCoords(t.pos) : this.view.coordsAtPos(t.pos);
13660
            }),
13661
            size: this.manager.tooltipViews.map(({ dom }) => dom.getBoundingClientRect()),
13662
            space: this.view.state.facet(tooltipConfig).tooltipSpace(this.view),
13663
            scaleX, scaleY, makeAbsolute
13664
        };
13665
    }
13666
    writeMeasure(measured) {
13667
        var _a;
13668
        if (measured.makeAbsolute) {
13669
            this.madeAbsolute = true;
13670
            this.position = "absolute";
13671
            for (let t of this.manager.tooltipViews)
13672
                t.dom.style.position = "absolute";
13673
        }
13674
        let { editor, space, scaleX, scaleY } = measured;
13675
        let others = [];
13676
        for (let i = 0; i < this.manager.tooltips.length; i++) {
13677
            let tooltip = this.manager.tooltips[i], tView = this.manager.tooltipViews[i], { dom } = tView;
13678
            let pos = measured.pos[i], size = measured.size[i];
13679
            // Hide tooltips that are outside of the editor.
13680
            if (!pos || pos.bottom <= Math.max(editor.top, space.top) ||
13681
                pos.top >= Math.min(editor.bottom, space.bottom) ||
13682
                pos.right < Math.max(editor.left, space.left) - .1 ||
13683
                pos.left > Math.min(editor.right, space.right) + .1) {
13684
                dom.style.top = Outside;
13685
                continue;
13686
            }
13687
            let arrow = tooltip.arrow ? tView.dom.querySelector(".cm-tooltip-arrow") : null;
13688
            let arrowHeight = arrow ? 7 /* Arrow.Size */ : 0;
13689
            let width = size.right - size.left, height = (_a = knownHeight.get(tView)) !== null && _a !== void 0 ? _a : size.bottom - size.top;
13690
            let offset = tView.offset || noOffset, ltr = this.view.textDirection == Direction.LTR;
13691
            let left = size.width > space.right - space.left ? (ltr ? space.left : space.right - size.width)
13692
                : ltr ? Math.min(pos.left - (arrow ? 14 /* Arrow.Offset */ : 0) + offset.x, space.right - width)
13693
                    : Math.max(space.left, pos.left - width + (arrow ? 14 /* Arrow.Offset */ : 0) - offset.x);
13694
            let above = this.above[i];
13695
            if (!tooltip.strictSide && (above
13696
                ? pos.top - (size.bottom - size.top) - offset.y < space.top
13697
                : pos.bottom + (size.bottom - size.top) + offset.y > space.bottom) &&
13698
                above == (space.bottom - pos.bottom > pos.top - space.top))
13699
                above = this.above[i] = !above;
13700
            let spaceVert = (above ? pos.top - space.top : space.bottom - pos.bottom) - arrowHeight;
13701
            if (spaceVert < height && tView.resize !== false) {
13702
                if (spaceVert < this.view.defaultLineHeight) {
13703
                    dom.style.top = Outside;
13704
                    continue;
13705
                }
13706
                knownHeight.set(tView, height);
13707
                dom.style.height = (height = spaceVert) / scaleY + "px";
13708
            }
13709
            else if (dom.style.height) {
13710
                dom.style.height = "";
13711
            }
13712
            let top = above ? pos.top - height - arrowHeight - offset.y : pos.bottom + arrowHeight + offset.y;
13713
            let right = left + width;
13714
            if (tView.overlap !== true)
13715
                for (let r of others)
13716
                    if (r.left < right && r.right > left && r.top < top + height && r.bottom > top)
13717
                        top = above ? r.top - height - 2 - arrowHeight : r.bottom + arrowHeight + 2;
13718
            if (this.position == "absolute") {
13719
                dom.style.top = (top - measured.parent.top) / scaleY + "px";
13720
                dom.style.left = (left - measured.parent.left) / scaleX + "px";
13721
            }
13722
            else {
13723
                dom.style.top = top / scaleY + "px";
13724
                dom.style.left = left / scaleX + "px";
13725
            }
13726
            if (arrow) {
13727
                let arrowLeft = pos.left + (ltr ? offset.x : -offset.x) - (left + 14 /* Arrow.Offset */ - 7 /* Arrow.Size */);
13728
                arrow.style.left = arrowLeft / scaleX + "px";
13729
            }
13730
            if (tView.overlap !== true)
13731
                others.push({ left, top, right, bottom: top + height });
13732
            dom.classList.toggle("cm-tooltip-above", above);
13733
            dom.classList.toggle("cm-tooltip-below", !above);
13734
            if (tView.positioned)
13735
                tView.positioned(measured.space);
13736
        }
13737
    }
13738
    maybeMeasure() {
13739
        if (this.manager.tooltips.length) {
13740
            if (this.view.inView)
13741
                this.view.requestMeasure(this.measureReq);
13742
            if (this.inView != this.view.inView) {
13743
                this.inView = this.view.inView;
13744
                if (!this.inView)
13745
                    for (let tv of this.manager.tooltipViews)
13746
                        tv.dom.style.top = Outside;
13747
            }
13748
        }
13749
    }
13750
}, {
13751
    eventObservers: {
13752
        scroll() { this.maybeMeasure(); }
13753
    }
13754
});
13755
const baseTheme$4 = /*@__PURE__*/EditorView.baseTheme({
13756
    ".cm-tooltip": {
13757
        zIndex: 100,
13758
        boxSizing: "border-box"
13759
    },
13760
    "&light .cm-tooltip": {
13761
        border: "1px solid #bbb",
13762
        backgroundColor: "#f5f5f5"
13763
    },
13764
    "&light .cm-tooltip-section:not(:first-child)": {
13765
        borderTop: "1px solid #bbb",
13766
    },
13767
    "&dark .cm-tooltip": {
13768
        backgroundColor: "#333338",
13769
        color: "white"
13770
    },
13771
    ".cm-tooltip-arrow": {
13772
        height: `${7 /* Arrow.Size */}px`,
13773
        width: `${7 /* Arrow.Size */ * 2}px`,
13774
        position: "absolute",
13775
        zIndex: -1,
13776
        overflow: "hidden",
13777
        "&:before, &:after": {
13778
            content: "''",
13779
            position: "absolute",
13780
            width: 0,
13781
            height: 0,
13782
            borderLeft: `${7 /* Arrow.Size */}px solid transparent`,
13783
            borderRight: `${7 /* Arrow.Size */}px solid transparent`,
13784
        },
13785
        ".cm-tooltip-above &": {
13786
            bottom: `-${7 /* Arrow.Size */}px`,
13787
            "&:before": {
13788
                borderTop: `${7 /* Arrow.Size */}px solid #bbb`,
13789
            },
13790
            "&:after": {
13791
                borderTop: `${7 /* Arrow.Size */}px solid #f5f5f5`,
13792
                bottom: "1px"
13793
            }
13794
        },
13795
        ".cm-tooltip-below &": {
13796
            top: `-${7 /* Arrow.Size */}px`,
13797
            "&:before": {
13798
                borderBottom: `${7 /* Arrow.Size */}px solid #bbb`,
13799
            },
13800
            "&:after": {
13801
                borderBottom: `${7 /* Arrow.Size */}px solid #f5f5f5`,
13802
                top: "1px"
13803
            }
13804
        },
13805
    },
13806
    "&dark .cm-tooltip .cm-tooltip-arrow": {
13807
        "&:before": {
13808
            borderTopColor: "#333338",
13809
            borderBottomColor: "#333338"
13810
        },
13811
        "&:after": {
13812
            borderTopColor: "transparent",
13813
            borderBottomColor: "transparent"
13814
        }
13815
    }
13816
});
13817
const noOffset = { x: 0, y: 0 };
13818
/**
13819
Facet to which an extension can add a value to show a tooltip.
13820
*/
13821
const showTooltip = /*@__PURE__*/Facet.define({
13822
    enables: [tooltipPlugin, baseTheme$4]
13823
});
13824
const showHoverTooltip = /*@__PURE__*/Facet.define({
13825
    combine: inputs => inputs.reduce((a, i) => a.concat(i), [])
13826
});
13827
class HoverTooltipHost {
13828
    // Needs to be static so that host tooltip instances always match
13829
    static create(view) {
13830
        return new HoverTooltipHost(view);
13831
    }
13832
    constructor(view) {
13833
        this.view = view;
13834
        this.mounted = false;
13835
        this.dom = document.createElement("div");
13836
        this.dom.classList.add("cm-tooltip-hover");
13837
        this.manager = new TooltipViewManager(view, showHoverTooltip, (t, p) => this.createHostedView(t, p), t => t.dom.remove());
13838
    }
13839
    createHostedView(tooltip, prev) {
13840
        let hostedView = tooltip.create(this.view);
13841
        hostedView.dom.classList.add("cm-tooltip-section");
13842
        this.dom.insertBefore(hostedView.dom, prev ? prev.dom.nextSibling : this.dom.firstChild);
13843
        if (this.mounted && hostedView.mount)
13844
            hostedView.mount(this.view);
13845
        return hostedView;
13846
    }
13847
    mount(view) {
13848
        for (let hostedView of this.manager.tooltipViews) {
13849
            if (hostedView.mount)
13850
                hostedView.mount(view);
13851
        }
13852
        this.mounted = true;
13853
    }
13854
    positioned(space) {
13855
        for (let hostedView of this.manager.tooltipViews) {
13856
            if (hostedView.positioned)
13857
                hostedView.positioned(space);
13858
        }
13859
    }
13860
    update(update) {
13861
        this.manager.update(update);
13862
    }
13863
    destroy() {
13864
        var _a;
13865
        for (let t of this.manager.tooltipViews)
13866
            (_a = t.destroy) === null || _a === void 0 ? void 0 : _a.call(t);
13867
    }
13868
    passProp(name) {
13869
        let value = undefined;
13870
        for (let view of this.manager.tooltipViews) {
13871
            let given = view[name];
13872
            if (given !== undefined) {
13873
                if (value === undefined)
13874
                    value = given;
13875
                else if (value !== given)
13876
                    return undefined;
13877
            }
13878
        }
13879
        return value;
13880
    }
13881
    get offset() { return this.passProp("offset"); }
13882
    get getCoords() { return this.passProp("getCoords"); }
13883
    get overlap() { return this.passProp("overlap"); }
13884
    get resize() { return this.passProp("resize"); }
13885
}
13886
const showHoverTooltipHost = /*@__PURE__*/showTooltip.compute([showHoverTooltip], state => {
13887
    let tooltips = state.facet(showHoverTooltip);
13888
    if (tooltips.length === 0)
13889
        return null;
13890
    return {
13891
        pos: Math.min(...tooltips.map(t => t.pos)),
13892
        end: Math.max(...tooltips.map(t => { var _a; return (_a = t.end) !== null && _a !== void 0 ? _a : t.pos; })),
13893
        create: HoverTooltipHost.create,
13894
        above: tooltips[0].above,
13895
        arrow: tooltips.some(t => t.arrow),
13896
    };
13897
});
13898
class HoverPlugin {
13899
    constructor(view, source, field, setHover, hoverTime) {
13900
        this.view = view;
13901
        this.source = source;
13902
        this.field = field;
13903
        this.setHover = setHover;
13904
        this.hoverTime = hoverTime;
13905
        this.hoverTimeout = -1;
13906
        this.restartTimeout = -1;
13907
        this.pending = null;
13908
        this.lastMove = { x: 0, y: 0, target: view.dom, time: 0 };
13909
        this.checkHover = this.checkHover.bind(this);
13910
        view.dom.addEventListener("mouseleave", this.mouseleave = this.mouseleave.bind(this));
13911
        view.dom.addEventListener("mousemove", this.mousemove = this.mousemove.bind(this));
13912
    }
13913
    update() {
13914
        if (this.pending) {
13915
            this.pending = null;
13916
            clearTimeout(this.restartTimeout);
13917
            this.restartTimeout = setTimeout(() => this.startHover(), 20);
13918
        }
13919
    }
13920
    get active() {
13921
        return this.view.state.field(this.field);
13922
    }
13923
    checkHover() {
13924
        this.hoverTimeout = -1;
13925
        if (this.active.length)
13926
            return;
13927
        let hovered = Date.now() - this.lastMove.time;
13928
        if (hovered < this.hoverTime)
13929
            this.hoverTimeout = setTimeout(this.checkHover, this.hoverTime - hovered);
13930
        else
13931
            this.startHover();
13932
    }
13933
    startHover() {
13934
        clearTimeout(this.restartTimeout);
13935
        let { view, lastMove } = this;
13936
        let desc = view.docView.nearest(lastMove.target);
13937
        if (!desc)
13938
            return;
13939
        let pos, side = 1;
13940
        if (desc instanceof WidgetView) {
13941
            pos = desc.posAtStart;
13942
        }
13943
        else {
13944
            pos = view.posAtCoords(lastMove);
13945
            if (pos == null)
13946
                return;
13947
            let posCoords = view.coordsAtPos(pos);
13948
            if (!posCoords ||
13949
                lastMove.y < posCoords.top || lastMove.y > posCoords.bottom ||
13950
                lastMove.x < posCoords.left - view.defaultCharacterWidth ||
13951
                lastMove.x > posCoords.right + view.defaultCharacterWidth)
13952
                return;
13953
            let bidi = view.bidiSpans(view.state.doc.lineAt(pos)).find(s => s.from <= pos && s.to >= pos);
13954
            let rtl = bidi && bidi.dir == Direction.RTL ? -1 : 1;
13955
            side = (lastMove.x < posCoords.left ? -rtl : rtl);
13956
        }
13957
        let open = this.source(view, pos, side);
13958
        if (open === null || open === void 0 ? void 0 : open.then) {
13959
            let pending = this.pending = { pos };
13960
            open.then(result => {
13961
                if (this.pending == pending) {
13962
                    this.pending = null;
13963
                    if (result && !(Array.isArray(result) && !result.length))
13964
                        view.dispatch({ effects: this.setHover.of(Array.isArray(result) ? result : [result]) });
13965
                }
13966
            }, e => logException(view.state, e, "hover tooltip"));
13967
        }
13968
        else if (open && !(Array.isArray(open) && !open.length)) {
13969
            view.dispatch({ effects: this.setHover.of(Array.isArray(open) ? open : [open]) });
13970
        }
13971
    }
13972
    get tooltip() {
13973
        let plugin = this.view.plugin(tooltipPlugin);
13974
        let index = plugin ? plugin.manager.tooltips.findIndex(t => t.create == HoverTooltipHost.create) : -1;
13975
        return index > -1 ? plugin.manager.tooltipViews[index] : null;
13976
    }
13977
    mousemove(event) {
13978
        var _a, _b;
13979
        this.lastMove = { x: event.clientX, y: event.clientY, target: event.target, time: Date.now() };
13980
        if (this.hoverTimeout < 0)
13981
            this.hoverTimeout = setTimeout(this.checkHover, this.hoverTime);
13982
        let { active, tooltip } = this;
13983
        if (active.length && tooltip && !isInTooltip(tooltip.dom, event) || this.pending) {
13984
            let { pos } = active[0] || this.pending, end = (_b = (_a = active[0]) === null || _a === void 0 ? void 0 : _a.end) !== null && _b !== void 0 ? _b : pos;
13985
            if ((pos == end ? this.view.posAtCoords(this.lastMove) != pos
13986
                : !isOverRange(this.view, pos, end, event.clientX, event.clientY))) {
13987
                this.view.dispatch({ effects: this.setHover.of([]) });
13988
                this.pending = null;
13989
            }
13990
        }
13991
    }
13992
    mouseleave(event) {
13993
        clearTimeout(this.hoverTimeout);
13994
        this.hoverTimeout = -1;
13995
        let { active } = this;
13996
        if (active.length) {
13997
            let { tooltip } = this;
13998
            let inTooltip = tooltip && tooltip.dom.contains(event.relatedTarget);
13999
            if (!inTooltip)
14000
                this.view.dispatch({ effects: this.setHover.of([]) });
14001
            else
14002
                this.watchTooltipLeave(tooltip.dom);
14003
        }
14004
    }
14005
    watchTooltipLeave(tooltip) {
14006
        let watch = (event) => {
14007
            tooltip.removeEventListener("mouseleave", watch);
14008
            if (this.active.length && !this.view.dom.contains(event.relatedTarget))
14009
                this.view.dispatch({ effects: this.setHover.of([]) });
14010
        };
14011
        tooltip.addEventListener("mouseleave", watch);
14012
    }
14013
    destroy() {
14014
        clearTimeout(this.hoverTimeout);
14015
        this.view.dom.removeEventListener("mouseleave", this.mouseleave);
14016
        this.view.dom.removeEventListener("mousemove", this.mousemove);
14017
    }
14018
}
14019
const tooltipMargin = 4;
14020
function isInTooltip(tooltip, event) {
14021
    let rect = tooltip.getBoundingClientRect();
14022
    return event.clientX >= rect.left - tooltipMargin && event.clientX <= rect.right + tooltipMargin &&
14023
        event.clientY >= rect.top - tooltipMargin && event.clientY <= rect.bottom + tooltipMargin;
14024
}
14025
function isOverRange(view, from, to, x, y, margin) {
14026
    let rect = view.scrollDOM.getBoundingClientRect();
14027
    let docBottom = view.documentTop + view.documentPadding.top + view.contentHeight;
14028
    if (rect.left > x || rect.right < x || rect.top > y || Math.min(rect.bottom, docBottom) < y)
14029
        return false;
14030
    let pos = view.posAtCoords({ x, y }, false);
14031
    return pos >= from && pos <= to;
14032
}
14033
/**
14034
Set up a hover tooltip, which shows up when the pointer hovers
14035
over ranges of text. The callback is called when the mouse hovers
14036
over the document text. It should, if there is a tooltip
14037
associated with position `pos`, return the tooltip description
14038
(either directly or in a promise). The `side` argument indicates
14039
on which side of the position the pointer is—it will be -1 if the
14040
pointer is before the position, 1 if after the position.
14041
 
14042
Note that all hover tooltips are hosted within a single tooltip
14043
container element. This allows multiple tooltips over the same
14044
range to be "merged" together without overlapping.
14045
*/
14046
function hoverTooltip(source, options = {}) {
14047
    let setHover = StateEffect.define();
14048
    let hoverState = StateField.define({
14049
        create() { return []; },
14050
        update(value, tr) {
14051
            if (value.length) {
14052
                if (options.hideOnChange && (tr.docChanged || tr.selection))
14053
                    value = [];
14054
                else if (options.hideOn)
14055
                    value = value.filter(v => !options.hideOn(tr, v));
14056
                if (tr.docChanged) {
14057
                    let mapped = [];
14058
                    for (let tooltip of value) {
14059
                        let newPos = tr.changes.mapPos(tooltip.pos, -1, MapMode.TrackDel);
14060
                        if (newPos != null) {
14061
                            let copy = Object.assign(Object.create(null), tooltip);
14062
                            copy.pos = newPos;
14063
                            if (copy.end != null)
14064
                                copy.end = tr.changes.mapPos(copy.end);
14065
                            mapped.push(copy);
14066
                        }
14067
                    }
14068
                    value = mapped;
14069
                }
14070
            }
14071
            for (let effect of tr.effects) {
14072
                if (effect.is(setHover))
14073
                    value = effect.value;
14074
                if (effect.is(closeHoverTooltipEffect))
14075
                    value = [];
14076
            }
14077
            return value;
14078
        },
14079
        provide: f => showHoverTooltip.from(f)
14080
    });
14081
    return [
14082
        hoverState,
14083
        ViewPlugin.define(view => new HoverPlugin(view, source, hoverState, setHover, options.hoverTime || 300 /* Hover.Time */)),
14084
        showHoverTooltipHost
14085
    ];
14086
}
14087
/**
14088
Get the active tooltip view for a given tooltip, if available.
14089
*/
14090
function getTooltip(view, tooltip) {
14091
    let plugin = view.plugin(tooltipPlugin);
14092
    if (!plugin)
14093
        return null;
14094
    let found = plugin.manager.tooltips.indexOf(tooltip);
14095
    return found < 0 ? null : plugin.manager.tooltipViews[found];
14096
}
14097
const closeHoverTooltipEffect = /*@__PURE__*/StateEffect.define();
14098
 
14099
const panelConfig = /*@__PURE__*/Facet.define({
14100
    combine(configs) {
14101
        let topContainer, bottomContainer;
14102
        for (let c of configs) {
14103
            topContainer = topContainer || c.topContainer;
14104
            bottomContainer = bottomContainer || c.bottomContainer;
14105
        }
14106
        return { topContainer, bottomContainer };
14107
    }
14108
});
14109
/**
14110
Get the active panel created by the given constructor, if any.
14111
This can be useful when you need access to your panels' DOM
14112
structure.
14113
*/
14114
function getPanel(view, panel) {
14115
    let plugin = view.plugin(panelPlugin);
14116
    let index = plugin ? plugin.specs.indexOf(panel) : -1;
14117
    return index > -1 ? plugin.panels[index] : null;
14118
}
14119
const panelPlugin = /*@__PURE__*/ViewPlugin.fromClass(class {
14120
    constructor(view) {
14121
        this.input = view.state.facet(showPanel);
14122
        this.specs = this.input.filter(s => s);
14123
        this.panels = this.specs.map(spec => spec(view));
14124
        let conf = view.state.facet(panelConfig);
14125
        this.top = new PanelGroup(view, true, conf.topContainer);
14126
        this.bottom = new PanelGroup(view, false, conf.bottomContainer);
14127
        this.top.sync(this.panels.filter(p => p.top));
14128
        this.bottom.sync(this.panels.filter(p => !p.top));
14129
        for (let p of this.panels) {
14130
            p.dom.classList.add("cm-panel");
14131
            if (p.mount)
14132
                p.mount();
14133
        }
14134
    }
14135
    update(update) {
14136
        let conf = update.state.facet(panelConfig);
14137
        if (this.top.container != conf.topContainer) {
14138
            this.top.sync([]);
14139
            this.top = new PanelGroup(update.view, true, conf.topContainer);
14140
        }
14141
        if (this.bottom.container != conf.bottomContainer) {
14142
            this.bottom.sync([]);
14143
            this.bottom = new PanelGroup(update.view, false, conf.bottomContainer);
14144
        }
14145
        this.top.syncClasses();
14146
        this.bottom.syncClasses();
14147
        let input = update.state.facet(showPanel);
14148
        if (input != this.input) {
14149
            let specs = input.filter(x => x);
14150
            let panels = [], top = [], bottom = [], mount = [];
14151
            for (let spec of specs) {
14152
                let known = this.specs.indexOf(spec), panel;
14153
                if (known < 0) {
14154
                    panel = spec(update.view);
14155
                    mount.push(panel);
14156
                }
14157
                else {
14158
                    panel = this.panels[known];
14159
                    if (panel.update)
14160
                        panel.update(update);
14161
                }
14162
                panels.push(panel);
14163
                (panel.top ? top : bottom).push(panel);
14164
            }
14165
            this.specs = specs;
14166
            this.panels = panels;
14167
            this.top.sync(top);
14168
            this.bottom.sync(bottom);
14169
            for (let p of mount) {
14170
                p.dom.classList.add("cm-panel");
14171
                if (p.mount)
14172
                    p.mount();
14173
            }
14174
        }
14175
        else {
14176
            for (let p of this.panels)
14177
                if (p.update)
14178
                    p.update(update);
14179
        }
14180
    }
14181
    destroy() {
14182
        this.top.sync([]);
14183
        this.bottom.sync([]);
14184
    }
14185
}, {
14186
    provide: plugin => EditorView.scrollMargins.of(view => {
14187
        let value = view.plugin(plugin);
14188
        return value && { top: value.top.scrollMargin(), bottom: value.bottom.scrollMargin() };
14189
    })
14190
});
14191
class PanelGroup {
14192
    constructor(view, top, container) {
14193
        this.view = view;
14194
        this.top = top;
14195
        this.container = container;
14196
        this.dom = undefined;
14197
        this.classes = "";
14198
        this.panels = [];
14199
        this.syncClasses();
14200
    }
14201
    sync(panels) {
14202
        for (let p of this.panels)
14203
            if (p.destroy && panels.indexOf(p) < 0)
14204
                p.destroy();
14205
        this.panels = panels;
14206
        this.syncDOM();
14207
    }
14208
    syncDOM() {
14209
        if (this.panels.length == 0) {
14210
            if (this.dom) {
14211
                this.dom.remove();
14212
                this.dom = undefined;
14213
            }
14214
            return;
14215
        }
14216
        if (!this.dom) {
14217
            this.dom = document.createElement("div");
14218
            this.dom.className = this.top ? "cm-panels cm-panels-top" : "cm-panels cm-panels-bottom";
14219
            this.dom.style[this.top ? "top" : "bottom"] = "0";
14220
            let parent = this.container || this.view.dom;
14221
            parent.insertBefore(this.dom, this.top ? parent.firstChild : null);
14222
        }
14223
        let curDOM = this.dom.firstChild;
14224
        for (let panel of this.panels) {
14225
            if (panel.dom.parentNode == this.dom) {
14226
                while (curDOM != panel.dom)
14227
                    curDOM = rm(curDOM);
14228
                curDOM = curDOM.nextSibling;
14229
            }
14230
            else {
14231
                this.dom.insertBefore(panel.dom, curDOM);
14232
            }
14233
        }
14234
        while (curDOM)
14235
            curDOM = rm(curDOM);
14236
    }
14237
    scrollMargin() {
14238
        return !this.dom || this.container ? 0
14239
            : Math.max(0, this.top ?
14240
                this.dom.getBoundingClientRect().bottom - Math.max(0, this.view.scrollDOM.getBoundingClientRect().top) :
14241
                Math.min(innerHeight, this.view.scrollDOM.getBoundingClientRect().bottom) - this.dom.getBoundingClientRect().top);
14242
    }
14243
    syncClasses() {
14244
        if (!this.container || this.classes == this.view.themeClasses)
14245
            return;
14246
        for (let cls of this.classes.split(" "))
14247
            if (cls)
14248
                this.container.classList.remove(cls);
14249
        for (let cls of (this.classes = this.view.themeClasses).split(" "))
14250
            if (cls)
14251
                this.container.classList.add(cls);
14252
    }
14253
}
14254
function rm(node) {
14255
    let next = node.nextSibling;
14256
    node.remove();
14257
    return next;
14258
}
14259
/**
14260
Opening a panel is done by providing a constructor function for
14261
the panel through this facet. (The panel is closed again when its
14262
constructor is no longer provided.) Values of `null` are ignored.
14263
*/
14264
const showPanel = /*@__PURE__*/Facet.define({
14265
    enables: panelPlugin
14266
});
14267
 
14268
/**
14269
A gutter marker represents a bit of information attached to a line
14270
in a specific gutter. Your own custom markers have to extend this
14271
class.
14272
*/
14273
class GutterMarker extends RangeValue {
14274
    /**
14275
    @internal
14276
    */
14277
    compare(other) {
14278
        return this == other || this.constructor == other.constructor && this.eq(other);
14279
    }
14280
    /**
14281
    Compare this marker to another marker of the same type.
14282
    */
14283
    eq(other) { return false; }
14284
    /**
14285
    Called if the marker has a `toDOM` method and its representation
14286
    was removed from a gutter.
14287
    */
14288
    destroy(dom) { }
14289
}
14290
GutterMarker.prototype.elementClass = "";
14291
GutterMarker.prototype.toDOM = undefined;
14292
GutterMarker.prototype.mapMode = MapMode.TrackBefore;
14293
GutterMarker.prototype.startSide = GutterMarker.prototype.endSide = -1;
14294
GutterMarker.prototype.point = true;
14295
/**
14296
Facet used to add a class to all gutter elements for a given line.
14297
Markers given to this facet should _only_ define an
14298
[`elementclass`](https://codemirror.net/6/docs/ref/#view.GutterMarker.elementClass), not a
14299
[`toDOM`](https://codemirror.net/6/docs/ref/#view.GutterMarker.toDOM) (or the marker will appear
14300
in all gutters for the line).
14301
*/
14302
const gutterLineClass = /*@__PURE__*/Facet.define();
14303
const defaults$1 = {
14304
    class: "",
14305
    renderEmptyElements: false,
14306
    elementStyle: "",
14307
    markers: () => RangeSet.empty,
14308
    lineMarker: () => null,
14309
    widgetMarker: () => null,
14310
    lineMarkerChange: null,
14311
    initialSpacer: null,
14312
    updateSpacer: null,
14313
    domEventHandlers: {}
14314
};
14315
const activeGutters = /*@__PURE__*/Facet.define();
14316
/**
14317
Define an editor gutter. The order in which the gutters appear is
14318
determined by their extension priority.
14319
*/
14320
function gutter(config) {
14321
    return [gutters(), activeGutters.of(Object.assign(Object.assign({}, defaults$1), config))];
14322
}
14323
const unfixGutters = /*@__PURE__*/Facet.define({
14324
    combine: values => values.some(x => x)
14325
});
14326
/**
14327
The gutter-drawing plugin is automatically enabled when you add a
14328
gutter, but you can use this function to explicitly configure it.
14329
 
14330
Unless `fixed` is explicitly set to `false`, the gutters are
14331
fixed, meaning they don't scroll along with the content
14332
horizontally (except on Internet Explorer, which doesn't support
14333
CSS [`position:
14334
sticky`](https://developer.mozilla.org/en-US/docs/Web/CSS/position#sticky)).
14335
*/
14336
function gutters(config) {
14337
    let result = [
14338
        gutterView,
14339
    ];
14340
    if (config && config.fixed === false)
14341
        result.push(unfixGutters.of(true));
14342
    return result;
14343
}
14344
const gutterView = /*@__PURE__*/ViewPlugin.fromClass(class {
14345
    constructor(view) {
14346
        this.view = view;
14347
        this.prevViewport = view.viewport;
14348
        this.dom = document.createElement("div");
14349
        this.dom.className = "cm-gutters";
14350
        this.dom.setAttribute("aria-hidden", "true");
14351
        this.dom.style.minHeight = (this.view.contentHeight / this.view.scaleY) + "px";
14352
        this.gutters = view.state.facet(activeGutters).map(conf => new SingleGutterView(view, conf));
14353
        for (let gutter of this.gutters)
14354
            this.dom.appendChild(gutter.dom);
14355
        this.fixed = !view.state.facet(unfixGutters);
14356
        if (this.fixed) {
14357
            // FIXME IE11 fallback, which doesn't support position: sticky,
14358
            // by using position: relative + event handlers that realign the
14359
            // gutter (or just force fixed=false on IE11?)
14360
            this.dom.style.position = "sticky";
14361
        }
14362
        this.syncGutters(false);
14363
        view.scrollDOM.insertBefore(this.dom, view.contentDOM);
14364
    }
14365
    update(update) {
14366
        if (this.updateGutters(update)) {
14367
            // Detach during sync when the viewport changed significantly
14368
            // (such as during scrolling), since for large updates that is
14369
            // faster.
14370
            let vpA = this.prevViewport, vpB = update.view.viewport;
14371
            let vpOverlap = Math.min(vpA.to, vpB.to) - Math.max(vpA.from, vpB.from);
14372
            this.syncGutters(vpOverlap < (vpB.to - vpB.from) * 0.8);
14373
        }
14374
        if (update.geometryChanged) {
14375
            this.dom.style.minHeight = (this.view.contentHeight / this.view.scaleY) + "px";
14376
        }
14377
        if (this.view.state.facet(unfixGutters) != !this.fixed) {
14378
            this.fixed = !this.fixed;
14379
            this.dom.style.position = this.fixed ? "sticky" : "";
14380
        }
14381
        this.prevViewport = update.view.viewport;
14382
    }
14383
    syncGutters(detach) {
14384
        let after = this.dom.nextSibling;
14385
        if (detach)
14386
            this.dom.remove();
14387
        let lineClasses = RangeSet.iter(this.view.state.facet(gutterLineClass), this.view.viewport.from);
14388
        let classSet = [];
14389
        let contexts = this.gutters.map(gutter => new UpdateContext(gutter, this.view.viewport, -this.view.documentPadding.top));
14390
        for (let line of this.view.viewportLineBlocks) {
14391
            if (classSet.length)
14392
                classSet = [];
14393
            if (Array.isArray(line.type)) {
14394
                let first = true;
14395
                for (let b of line.type) {
14396
                    if (b.type == BlockType.Text && first) {
14397
                        advanceCursor(lineClasses, classSet, b.from);
14398
                        for (let cx of contexts)
14399
                            cx.line(this.view, b, classSet);
14400
                        first = false;
14401
                    }
14402
                    else if (b.widget) {
14403
                        for (let cx of contexts)
14404
                            cx.widget(this.view, b);
14405
                    }
14406
                }
14407
            }
14408
            else if (line.type == BlockType.Text) {
14409
                advanceCursor(lineClasses, classSet, line.from);
14410
                for (let cx of contexts)
14411
                    cx.line(this.view, line, classSet);
14412
            }
14413
            else if (line.widget) {
14414
                for (let cx of contexts)
14415
                    cx.widget(this.view, line);
14416
            }
14417
        }
14418
        for (let cx of contexts)
14419
            cx.finish();
14420
        if (detach)
14421
            this.view.scrollDOM.insertBefore(this.dom, after);
14422
    }
14423
    updateGutters(update) {
14424
        let prev = update.startState.facet(activeGutters), cur = update.state.facet(activeGutters);
14425
        let change = update.docChanged || update.heightChanged || update.viewportChanged ||
14426
            !RangeSet.eq(update.startState.facet(gutterLineClass), update.state.facet(gutterLineClass), update.view.viewport.from, update.view.viewport.to);
14427
        if (prev == cur) {
14428
            for (let gutter of this.gutters)
14429
                if (gutter.update(update))
14430
                    change = true;
14431
        }
14432
        else {
14433
            change = true;
14434
            let gutters = [];
14435
            for (let conf of cur) {
14436
                let known = prev.indexOf(conf);
14437
                if (known < 0) {
14438
                    gutters.push(new SingleGutterView(this.view, conf));
14439
                }
14440
                else {
14441
                    this.gutters[known].update(update);
14442
                    gutters.push(this.gutters[known]);
14443
                }
14444
            }
14445
            for (let g of this.gutters) {
14446
                g.dom.remove();
14447
                if (gutters.indexOf(g) < 0)
14448
                    g.destroy();
14449
            }
14450
            for (let g of gutters)
14451
                this.dom.appendChild(g.dom);
14452
            this.gutters = gutters;
14453
        }
14454
        return change;
14455
    }
14456
    destroy() {
14457
        for (let view of this.gutters)
14458
            view.destroy();
14459
        this.dom.remove();
14460
    }
14461
}, {
14462
    provide: plugin => EditorView.scrollMargins.of(view => {
14463
        let value = view.plugin(plugin);
14464
        if (!value || value.gutters.length == 0 || !value.fixed)
14465
            return null;
14466
        return view.textDirection == Direction.LTR
14467
            ? { left: value.dom.offsetWidth * view.scaleX }
14468
            : { right: value.dom.offsetWidth * view.scaleX };
14469
    })
14470
});
14471
function asArray(val) { return (Array.isArray(val) ? val : [val]); }
14472
function advanceCursor(cursor, collect, pos) {
14473
    while (cursor.value && cursor.from <= pos) {
14474
        if (cursor.from == pos)
14475
            collect.push(cursor.value);
14476
        cursor.next();
14477
    }
14478
}
14479
class UpdateContext {
14480
    constructor(gutter, viewport, height) {
14481
        this.gutter = gutter;
14482
        this.height = height;
14483
        this.i = 0;
14484
        this.cursor = RangeSet.iter(gutter.markers, viewport.from);
14485
    }
14486
    addElement(view, block, markers) {
14487
        let { gutter } = this, above = (block.top - this.height) / view.scaleY, height = block.height / view.scaleY;
14488
        if (this.i == gutter.elements.length) {
14489
            let newElt = new GutterElement(view, height, above, markers);
14490
            gutter.elements.push(newElt);
14491
            gutter.dom.appendChild(newElt.dom);
14492
        }
14493
        else {
14494
            gutter.elements[this.i].update(view, height, above, markers);
14495
        }
14496
        this.height = block.bottom;
14497
        this.i++;
14498
    }
14499
    line(view, line, extraMarkers) {
14500
        let localMarkers = [];
14501
        advanceCursor(this.cursor, localMarkers, line.from);
14502
        if (extraMarkers.length)
14503
            localMarkers = localMarkers.concat(extraMarkers);
14504
        let forLine = this.gutter.config.lineMarker(view, line, localMarkers);
14505
        if (forLine)
14506
            localMarkers.unshift(forLine);
14507
        let gutter = this.gutter;
14508
        if (localMarkers.length == 0 && !gutter.config.renderEmptyElements)
14509
            return;
14510
        this.addElement(view, line, localMarkers);
14511
    }
14512
    widget(view, block) {
14513
        let marker = this.gutter.config.widgetMarker(view, block.widget, block);
14514
        if (marker)
14515
            this.addElement(view, block, [marker]);
14516
    }
14517
    finish() {
14518
        let gutter = this.gutter;
14519
        while (gutter.elements.length > this.i) {
14520
            let last = gutter.elements.pop();
14521
            gutter.dom.removeChild(last.dom);
14522
            last.destroy();
14523
        }
14524
    }
14525
}
14526
class SingleGutterView {
14527
    constructor(view, config) {
14528
        this.view = view;
14529
        this.config = config;
14530
        this.elements = [];
14531
        this.spacer = null;
14532
        this.dom = document.createElement("div");
14533
        this.dom.className = "cm-gutter" + (this.config.class ? " " + this.config.class : "");
14534
        for (let prop in config.domEventHandlers) {
14535
            this.dom.addEventListener(prop, (event) => {
14536
                let target = event.target, y;
14537
                if (target != this.dom && this.dom.contains(target)) {
14538
                    while (target.parentNode != this.dom)
14539
                        target = target.parentNode;
14540
                    let rect = target.getBoundingClientRect();
14541
                    y = (rect.top + rect.bottom) / 2;
14542
                }
14543
                else {
14544
                    y = event.clientY;
14545
                }
14546
                let line = view.lineBlockAtHeight(y - view.documentTop);
14547
                if (config.domEventHandlers[prop](view, line, event))
14548
                    event.preventDefault();
14549
            });
14550
        }
14551
        this.markers = asArray(config.markers(view));
14552
        if (config.initialSpacer) {
14553
            this.spacer = new GutterElement(view, 0, 0, [config.initialSpacer(view)]);
14554
            this.dom.appendChild(this.spacer.dom);
14555
            this.spacer.dom.style.cssText += "visibility: hidden; pointer-events: none";
14556
        }
14557
    }
14558
    update(update) {
14559
        let prevMarkers = this.markers;
14560
        this.markers = asArray(this.config.markers(update.view));
14561
        if (this.spacer && this.config.updateSpacer) {
14562
            let updated = this.config.updateSpacer(this.spacer.markers[0], update);
14563
            if (updated != this.spacer.markers[0])
14564
                this.spacer.update(update.view, 0, 0, [updated]);
14565
        }
14566
        let vp = update.view.viewport;
14567
        return !RangeSet.eq(this.markers, prevMarkers, vp.from, vp.to) ||
14568
            (this.config.lineMarkerChange ? this.config.lineMarkerChange(update) : false);
14569
    }
14570
    destroy() {
14571
        for (let elt of this.elements)
14572
            elt.destroy();
14573
    }
14574
}
14575
class GutterElement {
14576
    constructor(view, height, above, markers) {
14577
        this.height = -1;
14578
        this.above = 0;
14579
        this.markers = [];
14580
        this.dom = document.createElement("div");
14581
        this.dom.className = "cm-gutterElement";
14582
        this.update(view, height, above, markers);
14583
    }
14584
    update(view, height, above, markers) {
14585
        if (this.height != height) {
14586
            this.height = height;
14587
            this.dom.style.height = height + "px";
14588
        }
14589
        if (this.above != above)
14590
            this.dom.style.marginTop = (this.above = above) ? above + "px" : "";
14591
        if (!sameMarkers(this.markers, markers))
14592
            this.setMarkers(view, markers);
14593
    }
14594
    setMarkers(view, markers) {
14595
        let cls = "cm-gutterElement", domPos = this.dom.firstChild;
14596
        for (let iNew = 0, iOld = 0;;) {
14597
            let skipTo = iOld, marker = iNew < markers.length ? markers[iNew++] : null, matched = false;
14598
            if (marker) {
14599
                let c = marker.elementClass;
14600
                if (c)
14601
                    cls += " " + c;
14602
                for (let i = iOld; i < this.markers.length; i++)
14603
                    if (this.markers[i].compare(marker)) {
14604
                        skipTo = i;
14605
                        matched = true;
14606
                        break;
14607
                    }
14608
            }
14609
            else {
14610
                skipTo = this.markers.length;
14611
            }
14612
            while (iOld < skipTo) {
14613
                let next = this.markers[iOld++];
14614
                if (next.toDOM) {
14615
                    next.destroy(domPos);
14616
                    let after = domPos.nextSibling;
14617
                    domPos.remove();
14618
                    domPos = after;
14619
                }
14620
            }
14621
            if (!marker)
14622
                break;
14623
            if (marker.toDOM) {
14624
                if (matched)
14625
                    domPos = domPos.nextSibling;
14626
                else
14627
                    this.dom.insertBefore(marker.toDOM(view), domPos);
14628
            }
14629
            if (matched)
14630
                iOld++;
14631
        }
14632
        this.dom.className = cls;
14633
        this.markers = markers;
14634
    }
14635
    destroy() {
14636
        this.setMarkers(null, []); // First argument not used unless creating markers
14637
    }
14638
}
14639
function sameMarkers(a, b) {
14640
    if (a.length != b.length)
14641
        return false;
14642
    for (let i = 0; i < a.length; i++)
14643
        if (!a[i].compare(b[i]))
14644
            return false;
14645
    return true;
14646
}
14647
/**
14648
Facet used to provide markers to the line number gutter.
14649
*/
14650
const lineNumberMarkers = /*@__PURE__*/Facet.define();
14651
const lineNumberConfig = /*@__PURE__*/Facet.define({
14652
    combine(values) {
14653
        return combineConfig(values, { formatNumber: String, domEventHandlers: {} }, {
14654
            domEventHandlers(a, b) {
14655
                let result = Object.assign({}, a);
14656
                for (let event in b) {
14657
                    let exists = result[event], add = b[event];
14658
                    result[event] = exists ? (view, line, event) => exists(view, line, event) || add(view, line, event) : add;
14659
                }
14660
                return result;
14661
            }
14662
        });
14663
    }
14664
});
14665
class NumberMarker extends GutterMarker {
14666
    constructor(number) {
14667
        super();
14668
        this.number = number;
14669
    }
14670
    eq(other) { return this.number == other.number; }
14671
    toDOM() { return document.createTextNode(this.number); }
14672
}
14673
function formatNumber(view, number) {
14674
    return view.state.facet(lineNumberConfig).formatNumber(number, view.state);
14675
}
14676
const lineNumberGutter = /*@__PURE__*/activeGutters.compute([lineNumberConfig], state => ({
14677
    class: "cm-lineNumbers",
14678
    renderEmptyElements: false,
14679
    markers(view) { return view.state.facet(lineNumberMarkers); },
14680
    lineMarker(view, line, others) {
14681
        if (others.some(m => m.toDOM))
14682
            return null;
14683
        return new NumberMarker(formatNumber(view, view.state.doc.lineAt(line.from).number));
14684
    },
14685
    widgetMarker: () => null,
14686
    lineMarkerChange: update => update.startState.facet(lineNumberConfig) != update.state.facet(lineNumberConfig),
14687
    initialSpacer(view) {
14688
        return new NumberMarker(formatNumber(view, maxLineNumber(view.state.doc.lines)));
14689
    },
14690
    updateSpacer(spacer, update) {
14691
        let max = formatNumber(update.view, maxLineNumber(update.view.state.doc.lines));
14692
        return max == spacer.number ? spacer : new NumberMarker(max);
14693
    },
14694
    domEventHandlers: state.facet(lineNumberConfig).domEventHandlers
14695
}));
14696
/**
14697
Create a line number gutter extension.
14698
*/
14699
function lineNumbers(config = {}) {
14700
    return [
14701
        lineNumberConfig.of(config),
14702
        gutters(),
14703
        lineNumberGutter
14704
    ];
14705
}
14706
function maxLineNumber(lines) {
14707
    let last = 9;
14708
    while (last < lines)
14709
        last = last * 10 + 9;
14710
    return last;
14711
}
14712
const activeLineGutterMarker = /*@__PURE__*/new class extends GutterMarker {
14713
    constructor() {
14714
        super(...arguments);
14715
        this.elementClass = "cm-activeLineGutter";
14716
    }
14717
};
14718
const activeLineGutterHighlighter = /*@__PURE__*/gutterLineClass.compute(["selection"], state => {
14719
    let marks = [], last = -1;
14720
    for (let range of state.selection.ranges) {
14721
        let linePos = state.doc.lineAt(range.head).from;
14722
        if (linePos > last) {
14723
            last = linePos;
14724
            marks.push(activeLineGutterMarker.range(linePos));
14725
        }
14726
    }
14727
    return RangeSet.of(marks);
14728
});
14729
/**
14730
Returns an extension that adds a `cm-activeLineGutter` class to
14731
all gutter elements on the [active
14732
line](https://codemirror.net/6/docs/ref/#view.highlightActiveLine).
14733
*/
14734
function highlightActiveLineGutter() {
14735
    return activeLineGutterHighlighter;
14736
}
14737
 
14738
/**
14739
The default maximum length of a `TreeBuffer` node.
14740
*/
14741
const DefaultBufferLength = 1024;
14742
let nextPropID = 0;
14743
class Range {
14744
    constructor(from, to) {
14745
        this.from = from;
14746
        this.to = to;
14747
    }
14748
}
14749
/**
14750
Each [node type](#common.NodeType) or [individual tree](#common.Tree)
14751
can have metadata associated with it in props. Instances of this
14752
class represent prop names.
14753
*/
14754
class NodeProp {
14755
    /**
14756
    Create a new node prop type.
14757
    */
14758
    constructor(config = {}) {
14759
        this.id = nextPropID++;
14760
        this.perNode = !!config.perNode;
14761
        this.deserialize = config.deserialize || (() => {
14762
            throw new Error("This node type doesn't define a deserialize function");
14763
        });
14764
    }
14765
    /**
14766
    This is meant to be used with
14767
    [`NodeSet.extend`](#common.NodeSet.extend) or
14768
    [`LRParser.configure`](#lr.ParserConfig.props) to compute
14769
    prop values for each node type in the set. Takes a [match
14770
    object](#common.NodeType^match) or function that returns undefined
14771
    if the node type doesn't get this prop, and the prop's value if
14772
    it does.
14773
    */
14774
    add(match) {
14775
        if (this.perNode)
14776
            throw new RangeError("Can't add per-node props to node types");
14777
        if (typeof match != "function")
14778
            match = NodeType.match(match);
14779
        return (type) => {
14780
            let result = match(type);
14781
            return result === undefined ? null : [this, result];
14782
        };
14783
    }
14784
}
14785
/**
14786
Prop that is used to describe matching delimiters. For opening
14787
delimiters, this holds an array of node names (written as a
14788
space-separated string when declaring this prop in a grammar)
14789
for the node types of closing delimiters that match it.
14790
*/
14791
NodeProp.closedBy = new NodeProp({ deserialize: str => str.split(" ") });
14792
/**
14793
The inverse of [`closedBy`](#common.NodeProp^closedBy). This is
14794
attached to closing delimiters, holding an array of node names
14795
of types of matching opening delimiters.
14796
*/
14797
NodeProp.openedBy = new NodeProp({ deserialize: str => str.split(" ") });
14798
/**
14799
Used to assign node types to groups (for example, all node
14800
types that represent an expression could be tagged with an
14801
`"Expression"` group).
14802
*/
14803
NodeProp.group = new NodeProp({ deserialize: str => str.split(" ") });
14804
/**
14805
Attached to nodes to indicate these should be
14806
[displayed](https://codemirror.net/docs/ref/#language.syntaxTree)
14807
in a bidirectional text isolate, so that direction-neutral
14808
characters on their sides don't incorrectly get associated with
14809
surrounding text. You'll generally want to set this for nodes
14810
that contain arbitrary text, like strings and comments, and for
14811
nodes that appear _inside_ arbitrary text, like HTML tags. When
14812
not given a value, in a grammar declaration, defaults to
14813
`"auto"`.
14814
*/
14815
NodeProp.isolate = new NodeProp({ deserialize: value => {
14816
        if (value && value != "rtl" && value != "ltr" && value != "auto")
14817
            throw new RangeError("Invalid value for isolate: " + value);
14818
        return value || "auto";
14819
    } });
14820
/**
14821
The hash of the [context](#lr.ContextTracker.constructor)
14822
that the node was parsed in, if any. Used to limit reuse of
14823
contextual nodes.
14824
*/
14825
NodeProp.contextHash = new NodeProp({ perNode: true });
14826
/**
14827
The distance beyond the end of the node that the tokenizer
14828
looked ahead for any of the tokens inside the node. (The LR
14829
parser only stores this when it is larger than 25, for
14830
efficiency reasons.)
14831
*/
14832
NodeProp.lookAhead = new NodeProp({ perNode: true });
14833
/**
14834
This per-node prop is used to replace a given node, or part of a
14835
node, with another tree. This is useful to include trees from
14836
different languages in mixed-language parsers.
14837
*/
14838
NodeProp.mounted = new NodeProp({ perNode: true });
14839
/**
14840
A mounted tree, which can be [stored](#common.NodeProp^mounted) on
14841
a tree node to indicate that parts of its content are
14842
represented by another tree.
14843
*/
14844
class MountedTree {
14845
    constructor(
14846
    /**
14847
    The inner tree.
14848
    */
14849
    tree,
14850
    /**
14851
    If this is null, this tree replaces the entire node (it will
14852
    be included in the regular iteration instead of its host
14853
    node). If not, only the given ranges are considered to be
14854
    covered by this tree. This is used for trees that are mixed in
14855
    a way that isn't strictly hierarchical. Such mounted trees are
14856
    only entered by [`resolveInner`](#common.Tree.resolveInner)
14857
    and [`enter`](#common.SyntaxNode.enter).
14858
    */
14859
    overlay,
14860
    /**
14861
    The parser used to create this subtree.
14862
    */
14863
    parser) {
14864
        this.tree = tree;
14865
        this.overlay = overlay;
14866
        this.parser = parser;
14867
    }
14868
    /**
14869
    @internal
14870
    */
14871
    static get(tree) {
14872
        return tree && tree.props && tree.props[NodeProp.mounted.id];
14873
    }
14874
}
14875
const noProps = Object.create(null);
14876
/**
14877
Each node in a syntax tree has a node type associated with it.
14878
*/
14879
class NodeType {
14880
    /**
14881
    @internal
14882
    */
14883
    constructor(
14884
    /**
14885
    The name of the node type. Not necessarily unique, but if the
14886
    grammar was written properly, different node types with the
14887
    same name within a node set should play the same semantic
14888
    role.
14889
    */
14890
    name,
14891
    /**
14892
    @internal
14893
    */
14894
    props,
14895
    /**
14896
    The id of this node in its set. Corresponds to the term ids
14897
    used in the parser.
14898
    */
14899
    id,
14900
    /**
14901
    @internal
14902
    */
14903
    flags = 0) {
14904
        this.name = name;
14905
        this.props = props;
14906
        this.id = id;
14907
        this.flags = flags;
14908
    }
14909
    /**
14910
    Define a node type.
14911
    */
14912
    static define(spec) {
14913
        let props = spec.props && spec.props.length ? Object.create(null) : noProps;
14914
        let flags = (spec.top ? 1 /* NodeFlag.Top */ : 0) | (spec.skipped ? 2 /* NodeFlag.Skipped */ : 0) |
14915
            (spec.error ? 4 /* NodeFlag.Error */ : 0) | (spec.name == null ? 8 /* NodeFlag.Anonymous */ : 0);
14916
        let type = new NodeType(spec.name || "", props, spec.id, flags);
14917
        if (spec.props)
14918
            for (let src of spec.props) {
14919
                if (!Array.isArray(src))
14920
                    src = src(type);
14921
                if (src) {
14922
                    if (src[0].perNode)
14923
                        throw new RangeError("Can't store a per-node prop on a node type");
14924
                    props[src[0].id] = src[1];
14925
                }
14926
            }
14927
        return type;
14928
    }
14929
    /**
14930
    Retrieves a node prop for this type. Will return `undefined` if
14931
    the prop isn't present on this node.
14932
    */
14933
    prop(prop) { return this.props[prop.id]; }
14934
    /**
14935
    True when this is the top node of a grammar.
14936
    */
14937
    get isTop() { return (this.flags & 1 /* NodeFlag.Top */) > 0; }
14938
    /**
14939
    True when this node is produced by a skip rule.
14940
    */
14941
    get isSkipped() { return (this.flags & 2 /* NodeFlag.Skipped */) > 0; }
14942
    /**
14943
    Indicates whether this is an error node.
14944
    */
14945
    get isError() { return (this.flags & 4 /* NodeFlag.Error */) > 0; }
14946
    /**
14947
    When true, this node type doesn't correspond to a user-declared
14948
    named node, for example because it is used to cache repetition.
14949
    */
14950
    get isAnonymous() { return (this.flags & 8 /* NodeFlag.Anonymous */) > 0; }
14951
    /**
14952
    Returns true when this node's name or one of its
14953
    [groups](#common.NodeProp^group) matches the given string.
14954
    */
14955
    is(name) {
14956
        if (typeof name == 'string') {
14957
            if (this.name == name)
14958
                return true;
14959
            let group = this.prop(NodeProp.group);
14960
            return group ? group.indexOf(name) > -1 : false;
14961
        }
14962
        return this.id == name;
14963
    }
14964
    /**
14965
    Create a function from node types to arbitrary values by
14966
    specifying an object whose property names are node or
14967
    [group](#common.NodeProp^group) names. Often useful with
14968
    [`NodeProp.add`](#common.NodeProp.add). You can put multiple
14969
    names, separated by spaces, in a single property name to map
14970
    multiple node names to a single value.
14971
    */
14972
    static match(map) {
14973
        let direct = Object.create(null);
14974
        for (let prop in map)
14975
            for (let name of prop.split(" "))
14976
                direct[name] = map[prop];
14977
        return (node) => {
14978
            for (let groups = node.prop(NodeProp.group), i = -1; i < (groups ? groups.length : 0); i++) {
14979
                let found = direct[i < 0 ? node.name : groups[i]];
14980
                if (found)
14981
                    return found;
14982
            }
14983
        };
14984
    }
14985
}
14986
/**
14987
An empty dummy node type to use when no actual type is available.
14988
*/
14989
NodeType.none = new NodeType("", Object.create(null), 0, 8 /* NodeFlag.Anonymous */);
14990
/**
14991
A node set holds a collection of node types. It is used to
14992
compactly represent trees by storing their type ids, rather than a
14993
full pointer to the type object, in a numeric array. Each parser
14994
[has](#lr.LRParser.nodeSet) a node set, and [tree
14995
buffers](#common.TreeBuffer) can only store collections of nodes
14996
from the same set. A set can have a maximum of 2**16 (65536) node
14997
types in it, so that the ids fit into 16-bit typed array slots.
14998
*/
14999
class NodeSet {
15000
    /**
15001
    Create a set with the given types. The `id` property of each
15002
    type should correspond to its position within the array.
15003
    */
15004
    constructor(
15005
    /**
15006
    The node types in this set, by id.
15007
    */
15008
    types) {
15009
        this.types = types;
15010
        for (let i = 0; i < types.length; i++)
15011
            if (types[i].id != i)
15012
                throw new RangeError("Node type ids should correspond to array positions when creating a node set");
15013
    }
15014
    /**
15015
    Create a copy of this set with some node properties added. The
15016
    arguments to this method can be created with
15017
    [`NodeProp.add`](#common.NodeProp.add).
15018
    */
15019
    extend(...props) {
15020
        let newTypes = [];
15021
        for (let type of this.types) {
15022
            let newProps = null;
15023
            for (let source of props) {
15024
                let add = source(type);
15025
                if (add) {
15026
                    if (!newProps)
15027
                        newProps = Object.assign({}, type.props);
15028
                    newProps[add[0].id] = add[1];
15029
                }
15030
            }
15031
            newTypes.push(newProps ? new NodeType(type.name, newProps, type.id, type.flags) : type);
15032
        }
15033
        return new NodeSet(newTypes);
15034
    }
15035
}
15036
const CachedNode = new WeakMap(), CachedInnerNode = new WeakMap();
15037
/**
15038
Options that control iteration. Can be combined with the `|`
15039
operator to enable multiple ones.
15040
*/
15041
var IterMode;
15042
(function (IterMode) {
15043
    /**
15044
    When enabled, iteration will only visit [`Tree`](#common.Tree)
15045
    objects, not nodes packed into
15046
    [`TreeBuffer`](#common.TreeBuffer)s.
15047
    */
15048
    IterMode[IterMode["ExcludeBuffers"] = 1] = "ExcludeBuffers";
15049
    /**
15050
    Enable this to make iteration include anonymous nodes (such as
15051
    the nodes that wrap repeated grammar constructs into a balanced
15052
    tree).
15053
    */
15054
    IterMode[IterMode["IncludeAnonymous"] = 2] = "IncludeAnonymous";
15055
    /**
15056
    By default, regular [mounted](#common.NodeProp^mounted) nodes
15057
    replace their base node in iteration. Enable this to ignore them
15058
    instead.
15059
    */
15060
    IterMode[IterMode["IgnoreMounts"] = 4] = "IgnoreMounts";
15061
    /**
15062
    This option only applies in
15063
    [`enter`](#common.SyntaxNode.enter)-style methods. It tells the
15064
    library to not enter mounted overlays if one covers the given
15065
    position.
15066
    */
15067
    IterMode[IterMode["IgnoreOverlays"] = 8] = "IgnoreOverlays";
15068
})(IterMode || (IterMode = {}));
15069
/**
15070
A piece of syntax tree. There are two ways to approach these
15071
trees: the way they are actually stored in memory, and the
15072
convenient way.
15073
 
15074
Syntax trees are stored as a tree of `Tree` and `TreeBuffer`
15075
objects. By packing detail information into `TreeBuffer` leaf
15076
nodes, the representation is made a lot more memory-efficient.
15077
 
15078
However, when you want to actually work with tree nodes, this
15079
representation is very awkward, so most client code will want to
15080
use the [`TreeCursor`](#common.TreeCursor) or
15081
[`SyntaxNode`](#common.SyntaxNode) interface instead, which provides
15082
a view on some part of this data structure, and can be used to
15083
move around to adjacent nodes.
15084
*/
15085
class Tree {
15086
    /**
15087
    Construct a new tree. See also [`Tree.build`](#common.Tree^build).
15088
    */
15089
    constructor(
15090
    /**
15091
    The type of the top node.
15092
    */
15093
    type,
15094
    /**
15095
    This node's child nodes.
15096
    */
15097
    children,
15098
    /**
15099
    The positions (offsets relative to the start of this tree) of
15100
    the children.
15101
    */
15102
    positions,
15103
    /**
15104
    The total length of this tree
15105
    */
15106
    length,
15107
    /**
15108
    Per-node [node props](#common.NodeProp) to associate with this node.
15109
    */
15110
    props) {
15111
        this.type = type;
15112
        this.children = children;
15113
        this.positions = positions;
15114
        this.length = length;
15115
        /**
15116
        @internal
15117
        */
15118
        this.props = null;
15119
        if (props && props.length) {
15120
            this.props = Object.create(null);
15121
            for (let [prop, value] of props)
15122
                this.props[typeof prop == "number" ? prop : prop.id] = value;
15123
        }
15124
    }
15125
    /**
15126
    @internal
15127
    */
15128
    toString() {
15129
        let mounted = MountedTree.get(this);
15130
        if (mounted && !mounted.overlay)
15131
            return mounted.tree.toString();
15132
        let children = "";
15133
        for (let ch of this.children) {
15134
            let str = ch.toString();
15135
            if (str) {
15136
                if (children)
15137
                    children += ",";
15138
                children += str;
15139
            }
15140
        }
15141
        return !this.type.name ? children :
15142
            (/\W/.test(this.type.name) && !this.type.isError ? JSON.stringify(this.type.name) : this.type.name) +
15143
                (children.length ? "(" + children + ")" : "");
15144
    }
15145
    /**
15146
    Get a [tree cursor](#common.TreeCursor) positioned at the top of
15147
    the tree. Mode can be used to [control](#common.IterMode) which
15148
    nodes the cursor visits.
15149
    */
15150
    cursor(mode = 0) {
15151
        return new TreeCursor(this.topNode, mode);
15152
    }
15153
    /**
15154
    Get a [tree cursor](#common.TreeCursor) pointing into this tree
15155
    at the given position and side (see
15156
    [`moveTo`](#common.TreeCursor.moveTo).
15157
    */
15158
    cursorAt(pos, side = 0, mode = 0) {
15159
        let scope = CachedNode.get(this) || this.topNode;
15160
        let cursor = new TreeCursor(scope);
15161
        cursor.moveTo(pos, side);
15162
        CachedNode.set(this, cursor._tree);
15163
        return cursor;
15164
    }
15165
    /**
15166
    Get a [syntax node](#common.SyntaxNode) object for the top of the
15167
    tree.
15168
    */
15169
    get topNode() {
15170
        return new TreeNode(this, 0, 0, null);
15171
    }
15172
    /**
15173
    Get the [syntax node](#common.SyntaxNode) at the given position.
15174
    If `side` is -1, this will move into nodes that end at the
15175
    position. If 1, it'll move into nodes that start at the
15176
    position. With 0, it'll only enter nodes that cover the position
15177
    from both sides.
15178
 
15179
    Note that this will not enter
15180
    [overlays](#common.MountedTree.overlay), and you often want
15181
    [`resolveInner`](#common.Tree.resolveInner) instead.
15182
    */
15183
    resolve(pos, side = 0) {
15184
        let node = resolveNode(CachedNode.get(this) || this.topNode, pos, side, false);
15185
        CachedNode.set(this, node);
15186
        return node;
15187
    }
15188
    /**
15189
    Like [`resolve`](#common.Tree.resolve), but will enter
15190
    [overlaid](#common.MountedTree.overlay) nodes, producing a syntax node
15191
    pointing into the innermost overlaid tree at the given position
15192
    (with parent links going through all parent structure, including
15193
    the host trees).
15194
    */
15195
    resolveInner(pos, side = 0) {
15196
        let node = resolveNode(CachedInnerNode.get(this) || this.topNode, pos, side, true);
15197
        CachedInnerNode.set(this, node);
15198
        return node;
15199
    }
15200
    /**
15201
    In some situations, it can be useful to iterate through all
15202
    nodes around a position, including those in overlays that don't
15203
    directly cover the position. This method gives you an iterator
15204
    that will produce all nodes, from small to big, around the given
15205
    position.
15206
    */
15207
    resolveStack(pos, side = 0) {
15208
        return stackIterator(this, pos, side);
15209
    }
15210
    /**
15211
    Iterate over the tree and its children, calling `enter` for any
15212
    node that touches the `from`/`to` region (if given) before
15213
    running over such a node's children, and `leave` (if given) when
15214
    leaving the node. When `enter` returns `false`, that node will
15215
    not have its children iterated over (or `leave` called).
15216
    */
15217
    iterate(spec) {
15218
        let { enter, leave, from = 0, to = this.length } = spec;
15219
        let mode = spec.mode || 0, anon = (mode & IterMode.IncludeAnonymous) > 0;
15220
        for (let c = this.cursor(mode | IterMode.IncludeAnonymous);;) {
15221
            let entered = false;
15222
            if (c.from <= to && c.to >= from && (!anon && c.type.isAnonymous || enter(c) !== false)) {
15223
                if (c.firstChild())
15224
                    continue;
15225
                entered = true;
15226
            }
15227
            for (;;) {
15228
                if (entered && leave && (anon || !c.type.isAnonymous))
15229
                    leave(c);
15230
                if (c.nextSibling())
15231
                    break;
15232
                if (!c.parent())
15233
                    return;
15234
                entered = true;
15235
            }
15236
        }
15237
    }
15238
    /**
15239
    Get the value of the given [node prop](#common.NodeProp) for this
15240
    node. Works with both per-node and per-type props.
15241
    */
15242
    prop(prop) {
15243
        return !prop.perNode ? this.type.prop(prop) : this.props ? this.props[prop.id] : undefined;
15244
    }
15245
    /**
15246
    Returns the node's [per-node props](#common.NodeProp.perNode) in a
15247
    format that can be passed to the [`Tree`](#common.Tree)
15248
    constructor.
15249
    */
15250
    get propValues() {
15251
        let result = [];
15252
        if (this.props)
15253
            for (let id in this.props)
15254
                result.push([+id, this.props[id]]);
15255
        return result;
15256
    }
15257
    /**
15258
    Balance the direct children of this tree, producing a copy of
15259
    which may have children grouped into subtrees with type
15260
    [`NodeType.none`](#common.NodeType^none).
15261
    */
15262
    balance(config = {}) {
15263
        return this.children.length <= 8 /* Balance.BranchFactor */ ? this :
15264
            balanceRange(NodeType.none, this.children, this.positions, 0, this.children.length, 0, this.length, (children, positions, length) => new Tree(this.type, children, positions, length, this.propValues), config.makeTree || ((children, positions, length) => new Tree(NodeType.none, children, positions, length)));
15265
    }
15266
    /**
15267
    Build a tree from a postfix-ordered buffer of node information,
15268
    or a cursor over such a buffer.
15269
    */
15270
    static build(data) { return buildTree(data); }
15271
}
15272
/**
15273
The empty tree
15274
*/
15275
Tree.empty = new Tree(NodeType.none, [], [], 0);
15276
class FlatBufferCursor {
15277
    constructor(buffer, index) {
15278
        this.buffer = buffer;
15279
        this.index = index;
15280
    }
15281
    get id() { return this.buffer[this.index - 4]; }
15282
    get start() { return this.buffer[this.index - 3]; }
15283
    get end() { return this.buffer[this.index - 2]; }
15284
    get size() { return this.buffer[this.index - 1]; }
15285
    get pos() { return this.index; }
15286
    next() { this.index -= 4; }
15287
    fork() { return new FlatBufferCursor(this.buffer, this.index); }
15288
}
15289
/**
15290
Tree buffers contain (type, start, end, endIndex) quads for each
15291
node. In such a buffer, nodes are stored in prefix order (parents
15292
before children, with the endIndex of the parent indicating which
15293
children belong to it).
15294
*/
15295
class TreeBuffer {
15296
    /**
15297
    Create a tree buffer.
15298
    */
15299
    constructor(
15300
    /**
15301
    The buffer's content.
15302
    */
15303
    buffer,
15304
    /**
15305
    The total length of the group of nodes in the buffer.
15306
    */
15307
    length,
15308
    /**
15309
    The node set used in this buffer.
15310
    */
15311
    set) {
15312
        this.buffer = buffer;
15313
        this.length = length;
15314
        this.set = set;
15315
    }
15316
    /**
15317
    @internal
15318
    */
15319
    get type() { return NodeType.none; }
15320
    /**
15321
    @internal
15322
    */
15323
    toString() {
15324
        let result = [];
15325
        for (let index = 0; index < this.buffer.length;) {
15326
            result.push(this.childString(index));
15327
            index = this.buffer[index + 3];
15328
        }
15329
        return result.join(",");
15330
    }
15331
    /**
15332
    @internal
15333
    */
15334
    childString(index) {
15335
        let id = this.buffer[index], endIndex = this.buffer[index + 3];
15336
        let type = this.set.types[id], result = type.name;
15337
        if (/\W/.test(result) && !type.isError)
15338
            result = JSON.stringify(result);
15339
        index += 4;
15340
        if (endIndex == index)
15341
            return result;
15342
        let children = [];
15343
        while (index < endIndex) {
15344
            children.push(this.childString(index));
15345
            index = this.buffer[index + 3];
15346
        }
15347
        return result + "(" + children.join(",") + ")";
15348
    }
15349
    /**
15350
    @internal
15351
    */
15352
    findChild(startIndex, endIndex, dir, pos, side) {
15353
        let { buffer } = this, pick = -1;
15354
        for (let i = startIndex; i != endIndex; i = buffer[i + 3]) {
15355
            if (checkSide(side, pos, buffer[i + 1], buffer[i + 2])) {
15356
                pick = i;
15357
                if (dir > 0)
15358
                    break;
15359
            }
15360
        }
15361
        return pick;
15362
    }
15363
    /**
15364
    @internal
15365
    */
15366
    slice(startI, endI, from) {
15367
        let b = this.buffer;
15368
        let copy = new Uint16Array(endI - startI), len = 0;
15369
        for (let i = startI, j = 0; i < endI;) {
15370
            copy[j++] = b[i++];
15371
            copy[j++] = b[i++] - from;
15372
            let to = copy[j++] = b[i++] - from;
15373
            copy[j++] = b[i++] - startI;
15374
            len = Math.max(len, to);
15375
        }
15376
        return new TreeBuffer(copy, len, this.set);
15377
    }
15378
}
15379
function checkSide(side, pos, from, to) {
15380
    switch (side) {
15381
        case -2 /* Side.Before */: return from < pos;
15382
        case -1 /* Side.AtOrBefore */: return to >= pos && from < pos;
15383
        case 0 /* Side.Around */: return from < pos && to > pos;
15384
        case 1 /* Side.AtOrAfter */: return from <= pos && to > pos;
15385
        case 2 /* Side.After */: return to > pos;
15386
        case 4 /* Side.DontCare */: return true;
15387
    }
15388
}
15389
function resolveNode(node, pos, side, overlays) {
15390
    var _a;
15391
    // Move up to a node that actually holds the position, if possible
15392
    while (node.from == node.to ||
15393
        (side < 1 ? node.from >= pos : node.from > pos) ||
15394
        (side > -1 ? node.to <= pos : node.to < pos)) {
15395
        let parent = !overlays && node instanceof TreeNode && node.index < 0 ? null : node.parent;
15396
        if (!parent)
15397
            return node;
15398
        node = parent;
15399
    }
15400
    let mode = overlays ? 0 : IterMode.IgnoreOverlays;
15401
    // Must go up out of overlays when those do not overlap with pos
15402
    if (overlays)
15403
        for (let scan = node, parent = scan.parent; parent; scan = parent, parent = scan.parent) {
15404
            if (scan instanceof TreeNode && scan.index < 0 && ((_a = parent.enter(pos, side, mode)) === null || _a === void 0 ? void 0 : _a.from) != scan.from)
15405
                node = parent;
15406
        }
15407
    for (;;) {
15408
        let inner = node.enter(pos, side, mode);
15409
        if (!inner)
15410
            return node;
15411
        node = inner;
15412
    }
15413
}
15414
class BaseNode {
15415
    cursor(mode = 0) { return new TreeCursor(this, mode); }
15416
    getChild(type, before = null, after = null) {
15417
        let r = getChildren(this, type, before, after);
15418
        return r.length ? r[0] : null;
15419
    }
15420
    getChildren(type, before = null, after = null) {
15421
        return getChildren(this, type, before, after);
15422
    }
15423
    resolve(pos, side = 0) {
15424
        return resolveNode(this, pos, side, false);
15425
    }
15426
    resolveInner(pos, side = 0) {
15427
        return resolveNode(this, pos, side, true);
15428
    }
15429
    matchContext(context) {
15430
        return matchNodeContext(this, context);
15431
    }
15432
    enterUnfinishedNodesBefore(pos) {
15433
        let scan = this.childBefore(pos), node = this;
15434
        while (scan) {
15435
            let last = scan.lastChild;
15436
            if (!last || last.to != scan.to)
15437
                break;
15438
            if (last.type.isError && last.from == last.to) {
15439
                node = scan;
15440
                scan = last.prevSibling;
15441
            }
15442
            else {
15443
                scan = last;
15444
            }
15445
        }
15446
        return node;
15447
    }
15448
    get node() { return this; }
15449
    get next() { return this.parent; }
15450
}
15451
class TreeNode extends BaseNode {
15452
    constructor(_tree, from,
15453
    // Index in parent node, set to -1 if the node is not a direct child of _parent.node (overlay)
15454
    index, _parent) {
15455
        super();
15456
        this._tree = _tree;
15457
        this.from = from;
15458
        this.index = index;
15459
        this._parent = _parent;
15460
    }
15461
    get type() { return this._tree.type; }
15462
    get name() { return this._tree.type.name; }
15463
    get to() { return this.from + this._tree.length; }
15464
    nextChild(i, dir, pos, side, mode = 0) {
15465
        for (let parent = this;;) {
15466
            for (let { children, positions } = parent._tree, e = dir > 0 ? children.length : -1; i != e; i += dir) {
15467
                let next = children[i], start = positions[i] + parent.from;
15468
                if (!checkSide(side, pos, start, start + next.length))
15469
                    continue;
15470
                if (next instanceof TreeBuffer) {
15471
                    if (mode & IterMode.ExcludeBuffers)
15472
                        continue;
15473
                    let index = next.findChild(0, next.buffer.length, dir, pos - start, side);
15474
                    if (index > -1)
15475
                        return new BufferNode(new BufferContext(parent, next, i, start), null, index);
15476
                }
15477
                else if ((mode & IterMode.IncludeAnonymous) || (!next.type.isAnonymous || hasChild(next))) {
15478
                    let mounted;
15479
                    if (!(mode & IterMode.IgnoreMounts) && (mounted = MountedTree.get(next)) && !mounted.overlay)
15480
                        return new TreeNode(mounted.tree, start, i, parent);
15481
                    let inner = new TreeNode(next, start, i, parent);
15482
                    return (mode & IterMode.IncludeAnonymous) || !inner.type.isAnonymous ? inner
15483
                        : inner.nextChild(dir < 0 ? next.children.length - 1 : 0, dir, pos, side);
15484
                }
15485
            }
15486
            if ((mode & IterMode.IncludeAnonymous) || !parent.type.isAnonymous)
15487
                return null;
15488
            if (parent.index >= 0)
15489
                i = parent.index + dir;
15490
            else
15491
                i = dir < 0 ? -1 : parent._parent._tree.children.length;
15492
            parent = parent._parent;
15493
            if (!parent)
15494
                return null;
15495
        }
15496
    }
15497
    get firstChild() { return this.nextChild(0, 1, 0, 4 /* Side.DontCare */); }
15498
    get lastChild() { return this.nextChild(this._tree.children.length - 1, -1, 0, 4 /* Side.DontCare */); }
15499
    childAfter(pos) { return this.nextChild(0, 1, pos, 2 /* Side.After */); }
15500
    childBefore(pos) { return this.nextChild(this._tree.children.length - 1, -1, pos, -2 /* Side.Before */); }
15501
    enter(pos, side, mode = 0) {
15502
        let mounted;
15503
        if (!(mode & IterMode.IgnoreOverlays) && (mounted = MountedTree.get(this._tree)) && mounted.overlay) {
15504
            let rPos = pos - this.from;
15505
            for (let { from, to } of mounted.overlay) {
15506
                if ((side > 0 ? from <= rPos : from < rPos) &&
15507
                    (side < 0 ? to >= rPos : to > rPos))
15508
                    return new TreeNode(mounted.tree, mounted.overlay[0].from + this.from, -1, this);
15509
            }
15510
        }
15511
        return this.nextChild(0, 1, pos, side, mode);
15512
    }
15513
    nextSignificantParent() {
15514
        let val = this;
15515
        while (val.type.isAnonymous && val._parent)
15516
            val = val._parent;
15517
        return val;
15518
    }
15519
    get parent() {
15520
        return this._parent ? this._parent.nextSignificantParent() : null;
15521
    }
15522
    get nextSibling() {
15523
        return this._parent && this.index >= 0 ? this._parent.nextChild(this.index + 1, 1, 0, 4 /* Side.DontCare */) : null;
15524
    }
15525
    get prevSibling() {
15526
        return this._parent && this.index >= 0 ? this._parent.nextChild(this.index - 1, -1, 0, 4 /* Side.DontCare */) : null;
15527
    }
15528
    get tree() { return this._tree; }
15529
    toTree() { return this._tree; }
15530
    /**
15531
    @internal
15532
    */
15533
    toString() { return this._tree.toString(); }
15534
}
15535
function getChildren(node, type, before, after) {
15536
    let cur = node.cursor(), result = [];
15537
    if (!cur.firstChild())
15538
        return result;
15539
    if (before != null)
15540
        for (let found = false; !found;) {
15541
            found = cur.type.is(before);
15542
            if (!cur.nextSibling())
15543
                return result;
15544
        }
15545
    for (;;) {
15546
        if (after != null && cur.type.is(after))
15547
            return result;
15548
        if (cur.type.is(type))
15549
            result.push(cur.node);
15550
        if (!cur.nextSibling())
15551
            return after == null ? result : [];
15552
    }
15553
}
15554
function matchNodeContext(node, context, i = context.length - 1) {
15555
    for (let p = node.parent; i >= 0; p = p.parent) {
15556
        if (!p)
15557
            return false;
15558
        if (!p.type.isAnonymous) {
15559
            if (context[i] && context[i] != p.name)
15560
                return false;
15561
            i--;
15562
        }
15563
    }
15564
    return true;
15565
}
15566
class BufferContext {
15567
    constructor(parent, buffer, index, start) {
15568
        this.parent = parent;
15569
        this.buffer = buffer;
15570
        this.index = index;
15571
        this.start = start;
15572
    }
15573
}
15574
class BufferNode extends BaseNode {
15575
    get name() { return this.type.name; }
15576
    get from() { return this.context.start + this.context.buffer.buffer[this.index + 1]; }
15577
    get to() { return this.context.start + this.context.buffer.buffer[this.index + 2]; }
15578
    constructor(context, _parent, index) {
15579
        super();
15580
        this.context = context;
15581
        this._parent = _parent;
15582
        this.index = index;
15583
        this.type = context.buffer.set.types[context.buffer.buffer[index]];
15584
    }
15585
    child(dir, pos, side) {
15586
        let { buffer } = this.context;
15587
        let index = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], dir, pos - this.context.start, side);
15588
        return index < 0 ? null : new BufferNode(this.context, this, index);
15589
    }
15590
    get firstChild() { return this.child(1, 0, 4 /* Side.DontCare */); }
15591
    get lastChild() { return this.child(-1, 0, 4 /* Side.DontCare */); }
15592
    childAfter(pos) { return this.child(1, pos, 2 /* Side.After */); }
15593
    childBefore(pos) { return this.child(-1, pos, -2 /* Side.Before */); }
15594
    enter(pos, side, mode = 0) {
15595
        if (mode & IterMode.ExcludeBuffers)
15596
            return null;
15597
        let { buffer } = this.context;
15598
        let index = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], side > 0 ? 1 : -1, pos - this.context.start, side);
15599
        return index < 0 ? null : new BufferNode(this.context, this, index);
15600
    }
15601
    get parent() {
15602
        return this._parent || this.context.parent.nextSignificantParent();
15603
    }
15604
    externalSibling(dir) {
15605
        return this._parent ? null : this.context.parent.nextChild(this.context.index + dir, dir, 0, 4 /* Side.DontCare */);
15606
    }
15607
    get nextSibling() {
15608
        let { buffer } = this.context;
15609
        let after = buffer.buffer[this.index + 3];
15610
        if (after < (this._parent ? buffer.buffer[this._parent.index + 3] : buffer.buffer.length))
15611
            return new BufferNode(this.context, this._parent, after);
15612
        return this.externalSibling(1);
15613
    }
15614
    get prevSibling() {
15615
        let { buffer } = this.context;
15616
        let parentStart = this._parent ? this._parent.index + 4 : 0;
15617
        if (this.index == parentStart)
15618
            return this.externalSibling(-1);
15619
        return new BufferNode(this.context, this._parent, buffer.findChild(parentStart, this.index, -1, 0, 4 /* Side.DontCare */));
15620
    }
15621
    get tree() { return null; }
15622
    toTree() {
15623
        let children = [], positions = [];
15624
        let { buffer } = this.context;
15625
        let startI = this.index + 4, endI = buffer.buffer[this.index + 3];
15626
        if (endI > startI) {
15627
            let from = buffer.buffer[this.index + 1];
15628
            children.push(buffer.slice(startI, endI, from));
15629
            positions.push(0);
15630
        }
15631
        return new Tree(this.type, children, positions, this.to - this.from);
15632
    }
15633
    /**
15634
    @internal
15635
    */
15636
    toString() { return this.context.buffer.childString(this.index); }
15637
}
15638
function iterStack(heads) {
15639
    if (!heads.length)
15640
        return null;
15641
    let pick = 0, picked = heads[0];
15642
    for (let i = 1; i < heads.length; i++) {
15643
        let node = heads[i];
15644
        if (node.from > picked.from || node.to < picked.to) {
15645
            picked = node;
15646
            pick = i;
15647
        }
15648
    }
15649
    let next = picked instanceof TreeNode && picked.index < 0 ? null : picked.parent;
15650
    let newHeads = heads.slice();
15651
    if (next)
15652
        newHeads[pick] = next;
15653
    else
15654
        newHeads.splice(pick, 1);
15655
    return new StackIterator(newHeads, picked);
15656
}
15657
class StackIterator {
15658
    constructor(heads, node) {
15659
        this.heads = heads;
15660
        this.node = node;
15661
    }
15662
    get next() { return iterStack(this.heads); }
15663
}
15664
function stackIterator(tree, pos, side) {
15665
    let inner = tree.resolveInner(pos, side), layers = null;
15666
    for (let scan = inner instanceof TreeNode ? inner : inner.context.parent; scan; scan = scan.parent) {
15667
        if (scan.index < 0) { // This is an overlay root
15668
            let parent = scan.parent;
15669
            (layers || (layers = [inner])).push(parent.resolve(pos, side));
15670
            scan = parent;
15671
        }
15672
        else {
15673
            let mount = MountedTree.get(scan.tree);
15674
            // Relevant overlay branching off
15675
            if (mount && mount.overlay && mount.overlay[0].from <= pos && mount.overlay[mount.overlay.length - 1].to >= pos) {
15676
                let root = new TreeNode(mount.tree, mount.overlay[0].from + scan.from, -1, scan);
15677
                (layers || (layers = [inner])).push(resolveNode(root, pos, side, false));
15678
            }
15679
        }
15680
    }
15681
    return layers ? iterStack(layers) : inner;
15682
}
15683
/**
15684
A tree cursor object focuses on a given node in a syntax tree, and
15685
allows you to move to adjacent nodes.
15686
*/
15687
class TreeCursor {
15688
    /**
15689
    Shorthand for `.type.name`.
15690
    */
15691
    get name() { return this.type.name; }
15692
    /**
15693
    @internal
15694
    */
15695
    constructor(node,
15696
    /**
15697
    @internal
15698
    */
15699
    mode = 0) {
15700
        this.mode = mode;
15701
        /**
15702
        @internal
15703
        */
15704
        this.buffer = null;
15705
        this.stack = [];
15706
        /**
15707
        @internal
15708
        */
15709
        this.index = 0;
15710
        this.bufferNode = null;
15711
        if (node instanceof TreeNode) {
15712
            this.yieldNode(node);
15713
        }
15714
        else {
15715
            this._tree = node.context.parent;
15716
            this.buffer = node.context;
15717
            for (let n = node._parent; n; n = n._parent)
15718
                this.stack.unshift(n.index);
15719
            this.bufferNode = node;
15720
            this.yieldBuf(node.index);
15721
        }
15722
    }
15723
    yieldNode(node) {
15724
        if (!node)
15725
            return false;
15726
        this._tree = node;
15727
        this.type = node.type;
15728
        this.from = node.from;
15729
        this.to = node.to;
15730
        return true;
15731
    }
15732
    yieldBuf(index, type) {
15733
        this.index = index;
15734
        let { start, buffer } = this.buffer;
15735
        this.type = type || buffer.set.types[buffer.buffer[index]];
15736
        this.from = start + buffer.buffer[index + 1];
15737
        this.to = start + buffer.buffer[index + 2];
15738
        return true;
15739
    }
15740
    /**
15741
    @internal
15742
    */
15743
    yield(node) {
15744
        if (!node)
15745
            return false;
15746
        if (node instanceof TreeNode) {
15747
            this.buffer = null;
15748
            return this.yieldNode(node);
15749
        }
15750
        this.buffer = node.context;
15751
        return this.yieldBuf(node.index, node.type);
15752
    }
15753
    /**
15754
    @internal
15755
    */
15756
    toString() {
15757
        return this.buffer ? this.buffer.buffer.childString(this.index) : this._tree.toString();
15758
    }
15759
    /**
15760
    @internal
15761
    */
15762
    enterChild(dir, pos, side) {
15763
        if (!this.buffer)
15764
            return this.yield(this._tree.nextChild(dir < 0 ? this._tree._tree.children.length - 1 : 0, dir, pos, side, this.mode));
15765
        let { buffer } = this.buffer;
15766
        let index = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], dir, pos - this.buffer.start, side);
15767
        if (index < 0)
15768
            return false;
15769
        this.stack.push(this.index);
15770
        return this.yieldBuf(index);
15771
    }
15772
    /**
15773
    Move the cursor to this node's first child. When this returns
15774
    false, the node has no child, and the cursor has not been moved.
15775
    */
15776
    firstChild() { return this.enterChild(1, 0, 4 /* Side.DontCare */); }
15777
    /**
15778
    Move the cursor to this node's last child.
15779
    */
15780
    lastChild() { return this.enterChild(-1, 0, 4 /* Side.DontCare */); }
15781
    /**
15782
    Move the cursor to the first child that ends after `pos`.
15783
    */
15784
    childAfter(pos) { return this.enterChild(1, pos, 2 /* Side.After */); }
15785
    /**
15786
    Move to the last child that starts before `pos`.
15787
    */
15788
    childBefore(pos) { return this.enterChild(-1, pos, -2 /* Side.Before */); }
15789
    /**
15790
    Move the cursor to the child around `pos`. If side is -1 the
15791
    child may end at that position, when 1 it may start there. This
15792
    will also enter [overlaid](#common.MountedTree.overlay)
15793
    [mounted](#common.NodeProp^mounted) trees unless `overlays` is
15794
    set to false.
15795
    */
15796
    enter(pos, side, mode = this.mode) {
15797
        if (!this.buffer)
15798
            return this.yield(this._tree.enter(pos, side, mode));
15799
        return mode & IterMode.ExcludeBuffers ? false : this.enterChild(1, pos, side);
15800
    }
15801
    /**
15802
    Move to the node's parent node, if this isn't the top node.
15803
    */
15804
    parent() {
15805
        if (!this.buffer)
15806
            return this.yieldNode((this.mode & IterMode.IncludeAnonymous) ? this._tree._parent : this._tree.parent);
15807
        if (this.stack.length)
15808
            return this.yieldBuf(this.stack.pop());
15809
        let parent = (this.mode & IterMode.IncludeAnonymous) ? this.buffer.parent : this.buffer.parent.nextSignificantParent();
15810
        this.buffer = null;
15811
        return this.yieldNode(parent);
15812
    }
15813
    /**
15814
    @internal
15815
    */
15816
    sibling(dir) {
15817
        if (!this.buffer)
15818
            return !this._tree._parent ? false
15819
                : this.yield(this._tree.index < 0 ? null
15820
                    : this._tree._parent.nextChild(this._tree.index + dir, dir, 0, 4 /* Side.DontCare */, this.mode));
15821
        let { buffer } = this.buffer, d = this.stack.length - 1;
15822
        if (dir < 0) {
15823
            let parentStart = d < 0 ? 0 : this.stack[d] + 4;
15824
            if (this.index != parentStart)
15825
                return this.yieldBuf(buffer.findChild(parentStart, this.index, -1, 0, 4 /* Side.DontCare */));
15826
        }
15827
        else {
15828
            let after = buffer.buffer[this.index + 3];
15829
            if (after < (d < 0 ? buffer.buffer.length : buffer.buffer[this.stack[d] + 3]))
15830
                return this.yieldBuf(after);
15831
        }
15832
        return d < 0 ? this.yield(this.buffer.parent.nextChild(this.buffer.index + dir, dir, 0, 4 /* Side.DontCare */, this.mode)) : false;
15833
    }
15834
    /**
15835
    Move to this node's next sibling, if any.
15836
    */
15837
    nextSibling() { return this.sibling(1); }
15838
    /**
15839
    Move to this node's previous sibling, if any.
15840
    */
15841
    prevSibling() { return this.sibling(-1); }
15842
    atLastNode(dir) {
15843
        let index, parent, { buffer } = this;
15844
        if (buffer) {
15845
            if (dir > 0) {
15846
                if (this.index < buffer.buffer.buffer.length)
15847
                    return false;
15848
            }
15849
            else {
15850
                for (let i = 0; i < this.index; i++)
15851
                    if (buffer.buffer.buffer[i + 3] < this.index)
15852
                        return false;
15853
            }
15854
            ({ index, parent } = buffer);
15855
        }
15856
        else {
15857
            ({ index, _parent: parent } = this._tree);
15858
        }
15859
        for (; parent; { index, _parent: parent } = parent) {
15860
            if (index > -1)
15861
                for (let i = index + dir, e = dir < 0 ? -1 : parent._tree.children.length; i != e; i += dir) {
15862
                    let child = parent._tree.children[i];
15863
                    if ((this.mode & IterMode.IncludeAnonymous) ||
15864
                        child instanceof TreeBuffer ||
15865
                        !child.type.isAnonymous ||
15866
                        hasChild(child))
15867
                        return false;
15868
                }
15869
        }
15870
        return true;
15871
    }
15872
    move(dir, enter) {
15873
        if (enter && this.enterChild(dir, 0, 4 /* Side.DontCare */))
15874
            return true;
15875
        for (;;) {
15876
            if (this.sibling(dir))
15877
                return true;
15878
            if (this.atLastNode(dir) || !this.parent())
15879
                return false;
15880
        }
15881
    }
15882
    /**
15883
    Move to the next node in a
15884
    [pre-order](https://en.wikipedia.org/wiki/Tree_traversal#Pre-order,_NLR)
15885
    traversal, going from a node to its first child or, if the
15886
    current node is empty or `enter` is false, its next sibling or
15887
    the next sibling of the first parent node that has one.
15888
    */
15889
    next(enter = true) { return this.move(1, enter); }
15890
    /**
15891
    Move to the next node in a last-to-first pre-order traveral. A
15892
    node is followed by its last child or, if it has none, its
15893
    previous sibling or the previous sibling of the first parent
15894
    node that has one.
15895
    */
15896
    prev(enter = true) { return this.move(-1, enter); }
15897
    /**
15898
    Move the cursor to the innermost node that covers `pos`. If
15899
    `side` is -1, it will enter nodes that end at `pos`. If it is 1,
15900
    it will enter nodes that start at `pos`.
15901
    */
15902
    moveTo(pos, side = 0) {
15903
        // Move up to a node that actually holds the position, if possible
15904
        while (this.from == this.to ||
15905
            (side < 1 ? this.from >= pos : this.from > pos) ||
15906
            (side > -1 ? this.to <= pos : this.to < pos))
15907
            if (!this.parent())
15908
                break;
15909
        // Then scan down into child nodes as far as possible
15910
        while (this.enterChild(1, pos, side)) { }
15911
        return this;
15912
    }
15913
    /**
15914
    Get a [syntax node](#common.SyntaxNode) at the cursor's current
15915
    position.
15916
    */
15917
    get node() {
15918
        if (!this.buffer)
15919
            return this._tree;
15920
        let cache = this.bufferNode, result = null, depth = 0;
15921
        if (cache && cache.context == this.buffer) {
15922
            scan: for (let index = this.index, d = this.stack.length; d >= 0;) {
15923
                for (let c = cache; c; c = c._parent)
15924
                    if (c.index == index) {
15925
                        if (index == this.index)
15926
                            return c;
15927
                        result = c;
15928
                        depth = d + 1;
15929
                        break scan;
15930
                    }
15931
                index = this.stack[--d];
15932
            }
15933
        }
15934
        for (let i = depth; i < this.stack.length; i++)
15935
            result = new BufferNode(this.buffer, result, this.stack[i]);
15936
        return this.bufferNode = new BufferNode(this.buffer, result, this.index);
15937
    }
15938
    /**
15939
    Get the [tree](#common.Tree) that represents the current node, if
15940
    any. Will return null when the node is in a [tree
15941
    buffer](#common.TreeBuffer).
15942
    */
15943
    get tree() {
15944
        return this.buffer ? null : this._tree._tree;
15945
    }
15946
    /**
15947
    Iterate over the current node and all its descendants, calling
15948
    `enter` when entering a node and `leave`, if given, when leaving
15949
    one. When `enter` returns `false`, any children of that node are
15950
    skipped, and `leave` isn't called for it.
15951
    */
15952
    iterate(enter, leave) {
15953
        for (let depth = 0;;) {
15954
            let mustLeave = false;
15955
            if (this.type.isAnonymous || enter(this) !== false) {
15956
                if (this.firstChild()) {
15957
                    depth++;
15958
                    continue;
15959
                }
15960
                if (!this.type.isAnonymous)
15961
                    mustLeave = true;
15962
            }
15963
            for (;;) {
15964
                if (mustLeave && leave)
15965
                    leave(this);
15966
                mustLeave = this.type.isAnonymous;
15967
                if (this.nextSibling())
15968
                    break;
15969
                if (!depth)
15970
                    return;
15971
                this.parent();
15972
                depth--;
15973
                mustLeave = true;
15974
            }
15975
        }
15976
    }
15977
    /**
15978
    Test whether the current node matches a given context—a sequence
15979
    of direct parent node names. Empty strings in the context array
15980
    are treated as wildcards.
15981
    */
15982
    matchContext(context) {
15983
        if (!this.buffer)
15984
            return matchNodeContext(this.node, context);
15985
        let { buffer } = this.buffer, { types } = buffer.set;
15986
        for (let i = context.length - 1, d = this.stack.length - 1; i >= 0; d--) {
15987
            if (d < 0)
15988
                return matchNodeContext(this.node, context, i);
15989
            let type = types[buffer.buffer[this.stack[d]]];
15990
            if (!type.isAnonymous) {
15991
                if (context[i] && context[i] != type.name)
15992
                    return false;
15993
                i--;
15994
            }
15995
        }
15996
        return true;
15997
    }
15998
}
15999
function hasChild(tree) {
16000
    return tree.children.some(ch => ch instanceof TreeBuffer || !ch.type.isAnonymous || hasChild(ch));
16001
}
16002
function buildTree(data) {
16003
    var _a;
16004
    let { buffer, nodeSet, maxBufferLength = DefaultBufferLength, reused = [], minRepeatType = nodeSet.types.length } = data;
16005
    let cursor = Array.isArray(buffer) ? new FlatBufferCursor(buffer, buffer.length) : buffer;
16006
    let types = nodeSet.types;
16007
    let contextHash = 0, lookAhead = 0;
16008
    function takeNode(parentStart, minPos, children, positions, inRepeat, depth) {
16009
        let { id, start, end, size } = cursor;
16010
        let lookAheadAtStart = lookAhead;
16011
        while (size < 0) {
16012
            cursor.next();
16013
            if (size == -1 /* SpecialRecord.Reuse */) {
16014
                let node = reused[id];
16015
                children.push(node);
16016
                positions.push(start - parentStart);
16017
                return;
16018
            }
16019
            else if (size == -3 /* SpecialRecord.ContextChange */) { // Context change
16020
                contextHash = id;
16021
                return;
16022
            }
16023
            else if (size == -4 /* SpecialRecord.LookAhead */) {
16024
                lookAhead = id;
16025
                return;
16026
            }
16027
            else {
16028
                throw new RangeError(`Unrecognized record size: ${size}`);
16029
            }
16030
        }
16031
        let type = types[id], node, buffer;
16032
        let startPos = start - parentStart;
16033
        if (end - start <= maxBufferLength && (buffer = findBufferSize(cursor.pos - minPos, inRepeat))) {
16034
            // Small enough for a buffer, and no reused nodes inside
16035
            let data = new Uint16Array(buffer.size - buffer.skip);
16036
            let endPos = cursor.pos - buffer.size, index = data.length;
16037
            while (cursor.pos > endPos)
16038
                index = copyToBuffer(buffer.start, data, index);
16039
            node = new TreeBuffer(data, end - buffer.start, nodeSet);
16040
            startPos = buffer.start - parentStart;
16041
        }
16042
        else { // Make it a node
16043
            let endPos = cursor.pos - size;
16044
            cursor.next();
16045
            let localChildren = [], localPositions = [];
16046
            let localInRepeat = id >= minRepeatType ? id : -1;
16047
            let lastGroup = 0, lastEnd = end;
16048
            while (cursor.pos > endPos) {
16049
                if (localInRepeat >= 0 && cursor.id == localInRepeat && cursor.size >= 0) {
16050
                    if (cursor.end <= lastEnd - maxBufferLength) {
16051
                        makeRepeatLeaf(localChildren, localPositions, start, lastGroup, cursor.end, lastEnd, localInRepeat, lookAheadAtStart);
16052
                        lastGroup = localChildren.length;
16053
                        lastEnd = cursor.end;
16054
                    }
16055
                    cursor.next();
16056
                }
16057
                else if (depth > 2500 /* CutOff.Depth */) {
16058
                    takeFlatNode(start, endPos, localChildren, localPositions);
16059
                }
16060
                else {
16061
                    takeNode(start, endPos, localChildren, localPositions, localInRepeat, depth + 1);
16062
                }
16063
            }
16064
            if (localInRepeat >= 0 && lastGroup > 0 && lastGroup < localChildren.length)
16065
                makeRepeatLeaf(localChildren, localPositions, start, lastGroup, start, lastEnd, localInRepeat, lookAheadAtStart);
16066
            localChildren.reverse();
16067
            localPositions.reverse();
16068
            if (localInRepeat > -1 && lastGroup > 0) {
16069
                let make = makeBalanced(type);
16070
                node = balanceRange(type, localChildren, localPositions, 0, localChildren.length, 0, end - start, make, make);
16071
            }
16072
            else {
16073
                node = makeTree(type, localChildren, localPositions, end - start, lookAheadAtStart - end);
16074
            }
16075
        }
16076
        children.push(node);
16077
        positions.push(startPos);
16078
    }
16079
    function takeFlatNode(parentStart, minPos, children, positions) {
16080
        let nodes = []; // Temporary, inverted array of leaf nodes found, with absolute positions
16081
        let nodeCount = 0, stopAt = -1;
16082
        while (cursor.pos > minPos) {
16083
            let { id, start, end, size } = cursor;
16084
            if (size > 4) { // Not a leaf
16085
                cursor.next();
16086
            }
16087
            else if (stopAt > -1 && start < stopAt) {
16088
                break;
16089
            }
16090
            else {
16091
                if (stopAt < 0)
16092
                    stopAt = end - maxBufferLength;
16093
                nodes.push(id, start, end);
16094
                nodeCount++;
16095
                cursor.next();
16096
            }
16097
        }
16098
        if (nodeCount) {
16099
            let buffer = new Uint16Array(nodeCount * 4);
16100
            let start = nodes[nodes.length - 2];
16101
            for (let i = nodes.length - 3, j = 0; i >= 0; i -= 3) {
16102
                buffer[j++] = nodes[i];
16103
                buffer[j++] = nodes[i + 1] - start;
16104
                buffer[j++] = nodes[i + 2] - start;
16105
                buffer[j++] = j;
16106
            }
16107
            children.push(new TreeBuffer(buffer, nodes[2] - start, nodeSet));
16108
            positions.push(start - parentStart);
16109
        }
16110
    }
16111
    function makeBalanced(type) {
16112
        return (children, positions, length) => {
16113
            let lookAhead = 0, lastI = children.length - 1, last, lookAheadProp;
16114
            if (lastI >= 0 && (last = children[lastI]) instanceof Tree) {
16115
                if (!lastI && last.type == type && last.length == length)
16116
                    return last;
16117
                if (lookAheadProp = last.prop(NodeProp.lookAhead))
16118
                    lookAhead = positions[lastI] + last.length + lookAheadProp;
16119
            }
16120
            return makeTree(type, children, positions, length, lookAhead);
16121
        };
16122
    }
16123
    function makeRepeatLeaf(children, positions, base, i, from, to, type, lookAhead) {
16124
        let localChildren = [], localPositions = [];
16125
        while (children.length > i) {
16126
            localChildren.push(children.pop());
16127
            localPositions.push(positions.pop() + base - from);
16128
        }
16129
        children.push(makeTree(nodeSet.types[type], localChildren, localPositions, to - from, lookAhead - to));
16130
        positions.push(from - base);
16131
    }
16132
    function makeTree(type, children, positions, length, lookAhead = 0, props) {
16133
        if (contextHash) {
16134
            let pair = [NodeProp.contextHash, contextHash];
16135
            props = props ? [pair].concat(props) : [pair];
16136
        }
16137
        if (lookAhead > 25) {
16138
            let pair = [NodeProp.lookAhead, lookAhead];
16139
            props = props ? [pair].concat(props) : [pair];
16140
        }
16141
        return new Tree(type, children, positions, length, props);
16142
    }
16143
    function findBufferSize(maxSize, inRepeat) {
16144
        // Scan through the buffer to find previous siblings that fit
16145
        // together in a TreeBuffer, and don't contain any reused nodes
16146
        // (which can't be stored in a buffer).
16147
        // If `inRepeat` is > -1, ignore node boundaries of that type for
16148
        // nesting, but make sure the end falls either at the start
16149
        // (`maxSize`) or before such a node.
16150
        let fork = cursor.fork();
16151
        let size = 0, start = 0, skip = 0, minStart = fork.end - maxBufferLength;
16152
        let result = { size: 0, start: 0, skip: 0 };
16153
        scan: for (let minPos = fork.pos - maxSize; fork.pos > minPos;) {
16154
            let nodeSize = fork.size;
16155
            // Pretend nested repeat nodes of the same type don't exist
16156
            if (fork.id == inRepeat && nodeSize >= 0) {
16157
                // Except that we store the current state as a valid return
16158
                // value.
16159
                result.size = size;
16160
                result.start = start;
16161
                result.skip = skip;
16162
                skip += 4;
16163
                size += 4;
16164
                fork.next();
16165
                continue;
16166
            }
16167
            let startPos = fork.pos - nodeSize;
16168
            if (nodeSize < 0 || startPos < minPos || fork.start < minStart)
16169
                break;
16170
            let localSkipped = fork.id >= minRepeatType ? 4 : 0;
16171
            let nodeStart = fork.start;
16172
            fork.next();
16173
            while (fork.pos > startPos) {
16174
                if (fork.size < 0) {
16175
                    if (fork.size == -3 /* SpecialRecord.ContextChange */)
16176
                        localSkipped += 4;
16177
                    else
16178
                        break scan;
16179
                }
16180
                else if (fork.id >= minRepeatType) {
16181
                    localSkipped += 4;
16182
                }
16183
                fork.next();
16184
            }
16185
            start = nodeStart;
16186
            size += nodeSize;
16187
            skip += localSkipped;
16188
        }
16189
        if (inRepeat < 0 || size == maxSize) {
16190
            result.size = size;
16191
            result.start = start;
16192
            result.skip = skip;
16193
        }
16194
        return result.size > 4 ? result : undefined;
16195
    }
16196
    function copyToBuffer(bufferStart, buffer, index) {
16197
        let { id, start, end, size } = cursor;
16198
        cursor.next();
16199
        if (size >= 0 && id < minRepeatType) {
16200
            let startIndex = index;
16201
            if (size > 4) {
16202
                let endPos = cursor.pos - (size - 4);
16203
                while (cursor.pos > endPos)
16204
                    index = copyToBuffer(bufferStart, buffer, index);
16205
            }
16206
            buffer[--index] = startIndex;
16207
            buffer[--index] = end - bufferStart;
16208
            buffer[--index] = start - bufferStart;
16209
            buffer[--index] = id;
16210
        }
16211
        else if (size == -3 /* SpecialRecord.ContextChange */) {
16212
            contextHash = id;
16213
        }
16214
        else if (size == -4 /* SpecialRecord.LookAhead */) {
16215
            lookAhead = id;
16216
        }
16217
        return index;
16218
    }
16219
    let children = [], positions = [];
16220
    while (cursor.pos > 0)
16221
        takeNode(data.start || 0, data.bufferStart || 0, children, positions, -1, 0);
16222
    let length = (_a = data.length) !== null && _a !== void 0 ? _a : (children.length ? positions[0] + children[0].length : 0);
16223
    return new Tree(types[data.topID], children.reverse(), positions.reverse(), length);
16224
}
16225
const nodeSizeCache = new WeakMap;
16226
function nodeSize(balanceType, node) {
16227
    if (!balanceType.isAnonymous || node instanceof TreeBuffer || node.type != balanceType)
16228
        return 1;
16229
    let size = nodeSizeCache.get(node);
16230
    if (size == null) {
16231
        size = 1;
16232
        for (let child of node.children) {
16233
            if (child.type != balanceType || !(child instanceof Tree)) {
16234
                size = 1;
16235
                break;
16236
            }
16237
            size += nodeSize(balanceType, child);
16238
        }
16239
        nodeSizeCache.set(node, size);
16240
    }
16241
    return size;
16242
}
16243
function balanceRange(
16244
// The type the balanced tree's inner nodes.
16245
balanceType,
16246
// The direct children and their positions
16247
children, positions,
16248
// The index range in children/positions to use
16249
from, to,
16250
// The start position of the nodes, relative to their parent.
16251
start,
16252
// Length of the outer node
16253
length,
16254
// Function to build the top node of the balanced tree
16255
mkTop,
16256
// Function to build internal nodes for the balanced tree
16257
mkTree) {
16258
    let total = 0;
16259
    for (let i = from; i < to; i++)
16260
        total += nodeSize(balanceType, children[i]);
16261
    let maxChild = Math.ceil((total * 1.5) / 8 /* Balance.BranchFactor */);
16262
    let localChildren = [], localPositions = [];
16263
    function divide(children, positions, from, to, offset) {
16264
        for (let i = from; i < to;) {
16265
            let groupFrom = i, groupStart = positions[i], groupSize = nodeSize(balanceType, children[i]);
16266
            i++;
16267
            for (; i < to; i++) {
16268
                let nextSize = nodeSize(balanceType, children[i]);
16269
                if (groupSize + nextSize >= maxChild)
16270
                    break;
16271
                groupSize += nextSize;
16272
            }
16273
            if (i == groupFrom + 1) {
16274
                if (groupSize > maxChild) {
16275
                    let only = children[groupFrom]; // Only trees can have a size > 1
16276
                    divide(only.children, only.positions, 0, only.children.length, positions[groupFrom] + offset);
16277
                    continue;
16278
                }
16279
                localChildren.push(children[groupFrom]);
16280
            }
16281
            else {
16282
                let length = positions[i - 1] + children[i - 1].length - groupStart;
16283
                localChildren.push(balanceRange(balanceType, children, positions, groupFrom, i, groupStart, length, null, mkTree));
16284
            }
16285
            localPositions.push(groupStart + offset - start);
16286
        }
16287
    }
16288
    divide(children, positions, from, to, 0);
16289
    return (mkTop || mkTree)(localChildren, localPositions, length);
16290
}
16291
/**
16292
Provides a way to associate values with pieces of trees. As long
16293
as that part of the tree is reused, the associated values can be
16294
retrieved from an updated tree.
16295
*/
16296
class NodeWeakMap {
16297
    constructor() {
16298
        this.map = new WeakMap();
16299
    }
16300
    setBuffer(buffer, index, value) {
16301
        let inner = this.map.get(buffer);
16302
        if (!inner)
16303
            this.map.set(buffer, inner = new Map);
16304
        inner.set(index, value);
16305
    }
16306
    getBuffer(buffer, index) {
16307
        let inner = this.map.get(buffer);
16308
        return inner && inner.get(index);
16309
    }
16310
    /**
16311
    Set the value for this syntax node.
16312
    */
16313
    set(node, value) {
16314
        if (node instanceof BufferNode)
16315
            this.setBuffer(node.context.buffer, node.index, value);
16316
        else if (node instanceof TreeNode)
16317
            this.map.set(node.tree, value);
16318
    }
16319
    /**
16320
    Retrieve value for this syntax node, if it exists in the map.
16321
    */
16322
    get(node) {
16323
        return node instanceof BufferNode ? this.getBuffer(node.context.buffer, node.index)
16324
            : node instanceof TreeNode ? this.map.get(node.tree) : undefined;
16325
    }
16326
    /**
16327
    Set the value for the node that a cursor currently points to.
16328
    */
16329
    cursorSet(cursor, value) {
16330
        if (cursor.buffer)
16331
            this.setBuffer(cursor.buffer.buffer, cursor.index, value);
16332
        else
16333
            this.map.set(cursor.tree, value);
16334
    }
16335
    /**
16336
    Retrieve the value for the node that a cursor currently points
16337
    to.
16338
    */
16339
    cursorGet(cursor) {
16340
        return cursor.buffer ? this.getBuffer(cursor.buffer.buffer, cursor.index) : this.map.get(cursor.tree);
16341
    }
16342
}
16343
 
16344
/**
16345
Tree fragments are used during [incremental
16346
parsing](#common.Parser.startParse) to track parts of old trees
16347
that can be reused in a new parse. An array of fragments is used
16348
to track regions of an old tree whose nodes might be reused in new
16349
parses. Use the static
16350
[`applyChanges`](#common.TreeFragment^applyChanges) method to
16351
update fragments for document changes.
16352
*/
16353
class TreeFragment {
16354
    /**
16355
    Construct a tree fragment. You'll usually want to use
16356
    [`addTree`](#common.TreeFragment^addTree) and
16357
    [`applyChanges`](#common.TreeFragment^applyChanges) instead of
16358
    calling this directly.
16359
    */
16360
    constructor(
16361
    /**
16362
    The start of the unchanged range pointed to by this fragment.
16363
    This refers to an offset in the _updated_ document (as opposed
16364
    to the original tree).
16365
    */
16366
    from,
16367
    /**
16368
    The end of the unchanged range.
16369
    */
16370
    to,
16371
    /**
16372
    The tree that this fragment is based on.
16373
    */
16374
    tree,
16375
    /**
16376
    The offset between the fragment's tree and the document that
16377
    this fragment can be used against. Add this when going from
16378
    document to tree positions, subtract it to go from tree to
16379
    document positions.
16380
    */
16381
    offset, openStart = false, openEnd = false) {
16382
        this.from = from;
16383
        this.to = to;
16384
        this.tree = tree;
16385
        this.offset = offset;
16386
        this.open = (openStart ? 1 /* Open.Start */ : 0) | (openEnd ? 2 /* Open.End */ : 0);
16387
    }
16388
    /**
16389
    Whether the start of the fragment represents the start of a
16390
    parse, or the end of a change. (In the second case, it may not
16391
    be safe to reuse some nodes at the start, depending on the
16392
    parsing algorithm.)
16393
    */
16394
    get openStart() { return (this.open & 1 /* Open.Start */) > 0; }
16395
    /**
16396
    Whether the end of the fragment represents the end of a
16397
    full-document parse, or the start of a change.
16398
    */
16399
    get openEnd() { return (this.open & 2 /* Open.End */) > 0; }
16400
    /**
16401
    Create a set of fragments from a freshly parsed tree, or update
16402
    an existing set of fragments by replacing the ones that overlap
16403
    with a tree with content from the new tree. When `partial` is
16404
    true, the parse is treated as incomplete, and the resulting
16405
    fragment has [`openEnd`](#common.TreeFragment.openEnd) set to
16406
    true.
16407
    */
16408
    static addTree(tree, fragments = [], partial = false) {
16409
        let result = [new TreeFragment(0, tree.length, tree, 0, false, partial)];
16410
        for (let f of fragments)
16411
            if (f.to > tree.length)
16412
                result.push(f);
16413
        return result;
16414
    }
16415
    /**
16416
    Apply a set of edits to an array of fragments, removing or
16417
    splitting fragments as necessary to remove edited ranges, and
16418
    adjusting offsets for fragments that moved.
16419
    */
16420
    static applyChanges(fragments, changes, minGap = 128) {
16421
        if (!changes.length)
16422
            return fragments;
16423
        let result = [];
16424
        let fI = 1, nextF = fragments.length ? fragments[0] : null;
16425
        for (let cI = 0, pos = 0, off = 0;; cI++) {
16426
            let nextC = cI < changes.length ? changes[cI] : null;
16427
            let nextPos = nextC ? nextC.fromA : 1e9;
16428
            if (nextPos - pos >= minGap)
16429
                while (nextF && nextF.from < nextPos) {
16430
                    let cut = nextF;
16431
                    if (pos >= cut.from || nextPos <= cut.to || off) {
16432
                        let fFrom = Math.max(cut.from, pos) - off, fTo = Math.min(cut.to, nextPos) - off;
16433
                        cut = fFrom >= fTo ? null : new TreeFragment(fFrom, fTo, cut.tree, cut.offset + off, cI > 0, !!nextC);
16434
                    }
16435
                    if (cut)
16436
                        result.push(cut);
16437
                    if (nextF.to > nextPos)
16438
                        break;
16439
                    nextF = fI < fragments.length ? fragments[fI++] : null;
16440
                }
16441
            if (!nextC)
16442
                break;
16443
            pos = nextC.toA;
16444
            off = nextC.toA - nextC.toB;
16445
        }
16446
        return result;
16447
    }
16448
}
16449
/**
16450
A superclass that parsers should extend.
16451
*/
16452
class Parser {
16453
    /**
16454
    Start a parse, returning a [partial parse](#common.PartialParse)
16455
    object. [`fragments`](#common.TreeFragment) can be passed in to
16456
    make the parse incremental.
16457
 
16458
    By default, the entire input is parsed. You can pass `ranges`,
16459
    which should be a sorted array of non-empty, non-overlapping
16460
    ranges, to parse only those ranges. The tree returned in that
16461
    case will start at `ranges[0].from`.
16462
    */
16463
    startParse(input, fragments, ranges) {
16464
        if (typeof input == "string")
16465
            input = new StringInput(input);
16466
        ranges = !ranges ? [new Range(0, input.length)] : ranges.length ? ranges.map(r => new Range(r.from, r.to)) : [new Range(0, 0)];
16467
        return this.createParse(input, fragments || [], ranges);
16468
    }
16469
    /**
16470
    Run a full parse, returning the resulting tree.
16471
    */
16472
    parse(input, fragments, ranges) {
16473
        let parse = this.startParse(input, fragments, ranges);
16474
        for (;;) {
16475
            let done = parse.advance();
16476
            if (done)
16477
                return done;
16478
        }
16479
    }
16480
}
16481
class StringInput {
16482
    constructor(string) {
16483
        this.string = string;
16484
    }
16485
    get length() { return this.string.length; }
16486
    chunk(from) { return this.string.slice(from); }
16487
    get lineChunks() { return false; }
16488
    read(from, to) { return this.string.slice(from, to); }
16489
}
16490
 
16491
/**
16492
Create a parse wrapper that, after the inner parse completes,
16493
scans its tree for mixed language regions with the `nest`
16494
function, runs the resulting [inner parses](#common.NestedParse),
16495
and then [mounts](#common.NodeProp^mounted) their results onto the
16496
tree.
16497
*/
16498
function parseMixed(nest) {
16499
    return (parse, input, fragments, ranges) => new MixedParse(parse, nest, input, fragments, ranges);
16500
}
16501
class InnerParse {
16502
    constructor(parser, parse, overlay, target, from) {
16503
        this.parser = parser;
16504
        this.parse = parse;
16505
        this.overlay = overlay;
16506
        this.target = target;
16507
        this.from = from;
16508
    }
16509
}
16510
function checkRanges(ranges) {
16511
    if (!ranges.length || ranges.some(r => r.from >= r.to))
16512
        throw new RangeError("Invalid inner parse ranges given: " + JSON.stringify(ranges));
16513
}
16514
class ActiveOverlay {
16515
    constructor(parser, predicate, mounts, index, start, target, prev) {
16516
        this.parser = parser;
16517
        this.predicate = predicate;
16518
        this.mounts = mounts;
16519
        this.index = index;
16520
        this.start = start;
16521
        this.target = target;
16522
        this.prev = prev;
16523
        this.depth = 0;
16524
        this.ranges = [];
16525
    }
16526
}
16527
const stoppedInner = new NodeProp({ perNode: true });
16528
class MixedParse {
16529
    constructor(base, nest, input, fragments, ranges) {
16530
        this.nest = nest;
16531
        this.input = input;
16532
        this.fragments = fragments;
16533
        this.ranges = ranges;
16534
        this.inner = [];
16535
        this.innerDone = 0;
16536
        this.baseTree = null;
16537
        this.stoppedAt = null;
16538
        this.baseParse = base;
16539
    }
16540
    advance() {
16541
        if (this.baseParse) {
16542
            let done = this.baseParse.advance();
16543
            if (!done)
16544
                return null;
16545
            this.baseParse = null;
16546
            this.baseTree = done;
16547
            this.startInner();
16548
            if (this.stoppedAt != null)
16549
                for (let inner of this.inner)
16550
                    inner.parse.stopAt(this.stoppedAt);
16551
        }
16552
        if (this.innerDone == this.inner.length) {
16553
            let result = this.baseTree;
16554
            if (this.stoppedAt != null)
16555
                result = new Tree(result.type, result.children, result.positions, result.length, result.propValues.concat([[stoppedInner, this.stoppedAt]]));
16556
            return result;
16557
        }
16558
        let inner = this.inner[this.innerDone], done = inner.parse.advance();
16559
        if (done) {
16560
            this.innerDone++;
16561
            // This is a somewhat dodgy but super helpful hack where we
16562
            // patch up nodes created by the inner parse (and thus
16563
            // presumably not aliased anywhere else) to hold the information
16564
            // about the inner parse.
16565
            let props = Object.assign(Object.create(null), inner.target.props);
16566
            props[NodeProp.mounted.id] = new MountedTree(done, inner.overlay, inner.parser);
16567
            inner.target.props = props;
16568
        }
16569
        return null;
16570
    }
16571
    get parsedPos() {
16572
        if (this.baseParse)
16573
            return 0;
16574
        let pos = this.input.length;
16575
        for (let i = this.innerDone; i < this.inner.length; i++) {
16576
            if (this.inner[i].from < pos)
16577
                pos = Math.min(pos, this.inner[i].parse.parsedPos);
16578
        }
16579
        return pos;
16580
    }
16581
    stopAt(pos) {
16582
        this.stoppedAt = pos;
16583
        if (this.baseParse)
16584
            this.baseParse.stopAt(pos);
16585
        else
16586
            for (let i = this.innerDone; i < this.inner.length; i++)
16587
                this.inner[i].parse.stopAt(pos);
16588
    }
16589
    startInner() {
16590
        let fragmentCursor = new FragmentCursor$1(this.fragments);
16591
        let overlay = null;
16592
        let covered = null;
16593
        let cursor = new TreeCursor(new TreeNode(this.baseTree, this.ranges[0].from, 0, null), IterMode.IncludeAnonymous | IterMode.IgnoreMounts);
16594
        scan: for (let nest, isCovered;;) {
16595
            let enter = true, range;
16596
            if (this.stoppedAt != null && cursor.from >= this.stoppedAt) {
16597
                enter = false;
16598
            }
16599
            else if (fragmentCursor.hasNode(cursor)) {
16600
                if (overlay) {
16601
                    let match = overlay.mounts.find(m => m.frag.from <= cursor.from && m.frag.to >= cursor.to && m.mount.overlay);
16602
                    if (match)
16603
                        for (let r of match.mount.overlay) {
16604
                            let from = r.from + match.pos, to = r.to + match.pos;
16605
                            if (from >= cursor.from && to <= cursor.to && !overlay.ranges.some(r => r.from < to && r.to > from))
16606
                                overlay.ranges.push({ from, to });
16607
                        }
16608
                }
16609
                enter = false;
16610
            }
16611
            else if (covered && (isCovered = checkCover(covered.ranges, cursor.from, cursor.to))) {
16612
                enter = isCovered != 2 /* Cover.Full */;
16613
            }
16614
            else if (!cursor.type.isAnonymous && (nest = this.nest(cursor, this.input)) &&
16615
                (cursor.from < cursor.to || !nest.overlay)) {
16616
                if (!cursor.tree)
16617
                    materialize(cursor);
16618
                let oldMounts = fragmentCursor.findMounts(cursor.from, nest.parser);
16619
                if (typeof nest.overlay == "function") {
16620
                    overlay = new ActiveOverlay(nest.parser, nest.overlay, oldMounts, this.inner.length, cursor.from, cursor.tree, overlay);
16621
                }
16622
                else {
16623
                    let ranges = punchRanges(this.ranges, nest.overlay ||
16624
                        (cursor.from < cursor.to ? [new Range(cursor.from, cursor.to)] : []));
16625
                    if (ranges.length)
16626
                        checkRanges(ranges);
16627
                    if (ranges.length || !nest.overlay)
16628
                        this.inner.push(new InnerParse(nest.parser, ranges.length ? nest.parser.startParse(this.input, enterFragments(oldMounts, ranges), ranges)
16629
                            : nest.parser.startParse(""), nest.overlay ? nest.overlay.map(r => new Range(r.from - cursor.from, r.to - cursor.from)) : null, cursor.tree, ranges.length ? ranges[0].from : cursor.from));
16630
                    if (!nest.overlay)
16631
                        enter = false;
16632
                    else if (ranges.length)
16633
                        covered = { ranges, depth: 0, prev: covered };
16634
                }
16635
            }
16636
            else if (overlay && (range = overlay.predicate(cursor))) {
16637
                if (range === true)
16638
                    range = new Range(cursor.from, cursor.to);
16639
                if (range.from < range.to)
16640
                    overlay.ranges.push(range);
16641
            }
16642
            if (enter && cursor.firstChild()) {
16643
                if (overlay)
16644
                    overlay.depth++;
16645
                if (covered)
16646
                    covered.depth++;
16647
            }
16648
            else {
16649
                for (;;) {
16650
                    if (cursor.nextSibling())
16651
                        break;
16652
                    if (!cursor.parent())
16653
                        break scan;
16654
                    if (overlay && !--overlay.depth) {
16655
                        let ranges = punchRanges(this.ranges, overlay.ranges);
16656
                        if (ranges.length) {
16657
                            checkRanges(ranges);
16658
                            this.inner.splice(overlay.index, 0, new InnerParse(overlay.parser, overlay.parser.startParse(this.input, enterFragments(overlay.mounts, ranges), ranges), overlay.ranges.map(r => new Range(r.from - overlay.start, r.to - overlay.start)), overlay.target, ranges[0].from));
16659
                        }
16660
                        overlay = overlay.prev;
16661
                    }
16662
                    if (covered && !--covered.depth)
16663
                        covered = covered.prev;
16664
                }
16665
            }
16666
        }
16667
    }
16668
}
16669
function checkCover(covered, from, to) {
16670
    for (let range of covered) {
16671
        if (range.from >= to)
16672
            break;
16673
        if (range.to > from)
16674
            return range.from <= from && range.to >= to ? 2 /* Cover.Full */ : 1 /* Cover.Partial */;
16675
    }
16676
    return 0 /* Cover.None */;
16677
}
16678
// Take a piece of buffer and convert it into a stand-alone
16679
// TreeBuffer.
16680
function sliceBuf(buf, startI, endI, nodes, positions, off) {
16681
    if (startI < endI) {
16682
        let from = buf.buffer[startI + 1];
16683
        nodes.push(buf.slice(startI, endI, from));
16684
        positions.push(from - off);
16685
    }
16686
}
16687
// This function takes a node that's in a buffer, and converts it, and
16688
// its parent buffer nodes, into a Tree. This is again acting on the
16689
// assumption that the trees and buffers have been constructed by the
16690
// parse that was ran via the mix parser, and thus aren't shared with
16691
// any other code, making violations of the immutability safe.
16692
function materialize(cursor) {
16693
    let { node } = cursor, stack = [];
16694
    let buffer = node.context.buffer;
16695
    // Scan up to the nearest tree
16696
    do {
16697
        stack.push(cursor.index);
16698
        cursor.parent();
16699
    } while (!cursor.tree);
16700
    // Find the index of the buffer in that tree
16701
    let base = cursor.tree, i = base.children.indexOf(buffer);
16702
    let buf = base.children[i], b = buf.buffer, newStack = [i];
16703
    // Split a level in the buffer, putting the nodes before and after
16704
    // the child that contains `node` into new buffers.
16705
    function split(startI, endI, type, innerOffset, length, stackPos) {
16706
        let targetI = stack[stackPos];
16707
        let children = [], positions = [];
16708
        sliceBuf(buf, startI, targetI, children, positions, innerOffset);
16709
        let from = b[targetI + 1], to = b[targetI + 2];
16710
        newStack.push(children.length);
16711
        let child = stackPos
16712
            ? split(targetI + 4, b[targetI + 3], buf.set.types[b[targetI]], from, to - from, stackPos - 1)
16713
            : node.toTree();
16714
        children.push(child);
16715
        positions.push(from - innerOffset);
16716
        sliceBuf(buf, b[targetI + 3], endI, children, positions, innerOffset);
16717
        return new Tree(type, children, positions, length);
16718
    }
16719
    base.children[i] = split(0, b.length, NodeType.none, 0, buf.length, stack.length - 1);
16720
    // Move the cursor back to the target node
16721
    for (let index of newStack) {
16722
        let tree = cursor.tree.children[index], pos = cursor.tree.positions[index];
16723
        cursor.yield(new TreeNode(tree, pos + cursor.from, index, cursor._tree));
16724
    }
16725
}
16726
class StructureCursor {
16727
    constructor(root, offset) {
16728
        this.offset = offset;
16729
        this.done = false;
16730
        this.cursor = root.cursor(IterMode.IncludeAnonymous | IterMode.IgnoreMounts);
16731
    }
16732
    // Move to the first node (in pre-order) that starts at or after `pos`.
16733
    moveTo(pos) {
16734
        let { cursor } = this, p = pos - this.offset;
16735
        while (!this.done && cursor.from < p) {
16736
            if (cursor.to >= pos && cursor.enter(p, 1, IterMode.IgnoreOverlays | IterMode.ExcludeBuffers)) ;
16737
            else if (!cursor.next(false))
16738
                this.done = true;
16739
        }
16740
    }
16741
    hasNode(cursor) {
16742
        this.moveTo(cursor.from);
16743
        if (!this.done && this.cursor.from + this.offset == cursor.from && this.cursor.tree) {
16744
            for (let tree = this.cursor.tree;;) {
16745
                if (tree == cursor.tree)
16746
                    return true;
16747
                if (tree.children.length && tree.positions[0] == 0 && tree.children[0] instanceof Tree)
16748
                    tree = tree.children[0];
16749
                else
16750
                    break;
16751
            }
16752
        }
16753
        return false;
16754
    }
16755
}
16756
let FragmentCursor$1 = class FragmentCursor {
16757
    constructor(fragments) {
16758
        var _a;
16759
        this.fragments = fragments;
16760
        this.curTo = 0;
16761
        this.fragI = 0;
16762
        if (fragments.length) {
16763
            let first = this.curFrag = fragments[0];
16764
            this.curTo = (_a = first.tree.prop(stoppedInner)) !== null && _a !== void 0 ? _a : first.to;
16765
            this.inner = new StructureCursor(first.tree, -first.offset);
16766
        }
16767
        else {
16768
            this.curFrag = this.inner = null;
16769
        }
16770
    }
16771
    hasNode(node) {
16772
        while (this.curFrag && node.from >= this.curTo)
16773
            this.nextFrag();
16774
        return this.curFrag && this.curFrag.from <= node.from && this.curTo >= node.to && this.inner.hasNode(node);
16775
    }
16776
    nextFrag() {
16777
        var _a;
16778
        this.fragI++;
16779
        if (this.fragI == this.fragments.length) {
16780
            this.curFrag = this.inner = null;
16781
        }
16782
        else {
16783
            let frag = this.curFrag = this.fragments[this.fragI];
16784
            this.curTo = (_a = frag.tree.prop(stoppedInner)) !== null && _a !== void 0 ? _a : frag.to;
16785
            this.inner = new StructureCursor(frag.tree, -frag.offset);
16786
        }
16787
    }
16788
    findMounts(pos, parser) {
16789
        var _a;
16790
        let result = [];
16791
        if (this.inner) {
16792
            this.inner.cursor.moveTo(pos, 1);
16793
            for (let pos = this.inner.cursor.node; pos; pos = pos.parent) {
16794
                let mount = (_a = pos.tree) === null || _a === void 0 ? void 0 : _a.prop(NodeProp.mounted);
16795
                if (mount && mount.parser == parser) {
16796
                    for (let i = this.fragI; i < this.fragments.length; i++) {
16797
                        let frag = this.fragments[i];
16798
                        if (frag.from >= pos.to)
16799
                            break;
16800
                        if (frag.tree == this.curFrag.tree)
16801
                            result.push({
16802
                                frag,
16803
                                pos: pos.from - frag.offset,
16804
                                mount
16805
                            });
16806
                    }
16807
                }
16808
            }
16809
        }
16810
        return result;
16811
    }
16812
};
16813
function punchRanges(outer, ranges) {
16814
    let copy = null, current = ranges;
16815
    for (let i = 1, j = 0; i < outer.length; i++) {
16816
        let gapFrom = outer[i - 1].to, gapTo = outer[i].from;
16817
        for (; j < current.length; j++) {
16818
            let r = current[j];
16819
            if (r.from >= gapTo)
16820
                break;
16821
            if (r.to <= gapFrom)
16822
                continue;
16823
            if (!copy)
16824
                current = copy = ranges.slice();
16825
            if (r.from < gapFrom) {
16826
                copy[j] = new Range(r.from, gapFrom);
16827
                if (r.to > gapTo)
16828
                    copy.splice(j + 1, 0, new Range(gapTo, r.to));
16829
            }
16830
            else if (r.to > gapTo) {
16831
                copy[j--] = new Range(gapTo, r.to);
16832
            }
16833
            else {
16834
                copy.splice(j--, 1);
16835
            }
16836
        }
16837
    }
16838
    return current;
16839
}
16840
function findCoverChanges(a, b, from, to) {
16841
    let iA = 0, iB = 0, inA = false, inB = false, pos = -1e9;
16842
    let result = [];
16843
    for (;;) {
16844
        let nextA = iA == a.length ? 1e9 : inA ? a[iA].to : a[iA].from;
16845
        let nextB = iB == b.length ? 1e9 : inB ? b[iB].to : b[iB].from;
16846
        if (inA != inB) {
16847
            let start = Math.max(pos, from), end = Math.min(nextA, nextB, to);
16848
            if (start < end)
16849
                result.push(new Range(start, end));
16850
        }
16851
        pos = Math.min(nextA, nextB);
16852
        if (pos == 1e9)
16853
            break;
16854
        if (nextA == pos) {
16855
            if (!inA)
16856
                inA = true;
16857
            else {
16858
                inA = false;
16859
                iA++;
16860
            }
16861
        }
16862
        if (nextB == pos) {
16863
            if (!inB)
16864
                inB = true;
16865
            else {
16866
                inB = false;
16867
                iB++;
16868
            }
16869
        }
16870
    }
16871
    return result;
16872
}
16873
// Given a number of fragments for the outer tree, and a set of ranges
16874
// to parse, find fragments for inner trees mounted around those
16875
// ranges, if any.
16876
function enterFragments(mounts, ranges) {
16877
    let result = [];
16878
    for (let { pos, mount, frag } of mounts) {
16879
        let startPos = pos + (mount.overlay ? mount.overlay[0].from : 0), endPos = startPos + mount.tree.length;
16880
        let from = Math.max(frag.from, startPos), to = Math.min(frag.to, endPos);
16881
        if (mount.overlay) {
16882
            let overlay = mount.overlay.map(r => new Range(r.from + pos, r.to + pos));
16883
            let changes = findCoverChanges(ranges, overlay, from, to);
16884
            for (let i = 0, pos = from;; i++) {
16885
                let last = i == changes.length, end = last ? to : changes[i].from;
16886
                if (end > pos)
16887
                    result.push(new TreeFragment(pos, end, mount.tree, -startPos, frag.from >= pos || frag.openStart, frag.to <= end || frag.openEnd));
16888
                if (last)
16889
                    break;
16890
                pos = changes[i].to;
16891
            }
16892
        }
16893
        else {
16894
            result.push(new TreeFragment(from, to, mount.tree, -startPos, frag.from >= startPos || frag.openStart, frag.to <= endPos || frag.openEnd));
16895
        }
16896
    }
16897
    return result;
16898
}
16899
 
16900
let nextTagID = 0;
16901
/**
16902
Highlighting tags are markers that denote a highlighting category.
16903
They are [associated](#highlight.styleTags) with parts of a syntax
16904
tree by a language mode, and then mapped to an actual CSS style by
16905
a [highlighter](#highlight.Highlighter).
16906
 
16907
Because syntax tree node types and highlight styles have to be
16908
able to talk the same language, CodeMirror uses a mostly _closed_
16909
[vocabulary](#highlight.tags) of syntax tags (as opposed to
16910
traditional open string-based systems, which make it hard for
16911
highlighting themes to cover all the tokens produced by the
16912
various languages).
16913
 
16914
It _is_ possible to [define](#highlight.Tag^define) your own
16915
highlighting tags for system-internal use (where you control both
16916
the language package and the highlighter), but such tags will not
16917
be picked up by regular highlighters (though you can derive them
16918
from standard tags to allow highlighters to fall back to those).
16919
*/
16920
class Tag {
16921
    /**
16922
    @internal
16923
    */
16924
    constructor(
16925
    /**
16926
    The set of this tag and all its parent tags, starting with
16927
    this one itself and sorted in order of decreasing specificity.
16928
    */
16929
    set,
16930
    /**
16931
    The base unmodified tag that this one is based on, if it's
16932
    modified @internal
16933
    */
16934
    base,
16935
    /**
16936
    The modifiers applied to this.base @internal
16937
    */
16938
    modified) {
16939
        this.set = set;
16940
        this.base = base;
16941
        this.modified = modified;
16942
        /**
16943
        @internal
16944
        */
16945
        this.id = nextTagID++;
16946
    }
16947
    /**
16948
    Define a new tag. If `parent` is given, the tag is treated as a
16949
    sub-tag of that parent, and
16950
    [highlighters](#highlight.tagHighlighter) that don't mention
16951
    this tag will try to fall back to the parent tag (or grandparent
16952
    tag, etc).
16953
    */
16954
    static define(parent) {
16955
        if (parent === null || parent === void 0 ? void 0 : parent.base)
16956
            throw new Error("Can not derive from a modified tag");
16957
        let tag = new Tag([], null, []);
16958
        tag.set.push(tag);
16959
        if (parent)
16960
            for (let t of parent.set)
16961
                tag.set.push(t);
16962
        return tag;
16963
    }
16964
    /**
16965
    Define a tag _modifier_, which is a function that, given a tag,
16966
    will return a tag that is a subtag of the original. Applying the
16967
    same modifier to a twice tag will return the same value (`m1(t1)
16968
    == m1(t1)`) and applying multiple modifiers will, regardless or
16969
    order, produce the same tag (`m1(m2(t1)) == m2(m1(t1))`).
16970
 
16971
    When multiple modifiers are applied to a given base tag, each
16972
    smaller set of modifiers is registered as a parent, so that for
16973
    example `m1(m2(m3(t1)))` is a subtype of `m1(m2(t1))`,
16974
    `m1(m3(t1)`, and so on.
16975
    */
16976
    static defineModifier() {
16977
        let mod = new Modifier;
16978
        return (tag) => {
16979
            if (tag.modified.indexOf(mod) > -1)
16980
                return tag;
16981
            return Modifier.get(tag.base || tag, tag.modified.concat(mod).sort((a, b) => a.id - b.id));
16982
        };
16983
    }
16984
}
16985
let nextModifierID = 0;
16986
class Modifier {
16987
    constructor() {
16988
        this.instances = [];
16989
        this.id = nextModifierID++;
16990
    }
16991
    static get(base, mods) {
16992
        if (!mods.length)
16993
            return base;
16994
        let exists = mods[0].instances.find(t => t.base == base && sameArray(mods, t.modified));
16995
        if (exists)
16996
            return exists;
16997
        let set = [], tag = new Tag(set, base, mods);
16998
        for (let m of mods)
16999
            m.instances.push(tag);
17000
        let configs = powerSet(mods);
17001
        for (let parent of base.set)
17002
            if (!parent.modified.length)
17003
                for (let config of configs)
17004
                    set.push(Modifier.get(parent, config));
17005
        return tag;
17006
    }
17007
}
17008
function sameArray(a, b) {
17009
    return a.length == b.length && a.every((x, i) => x == b[i]);
17010
}
17011
function powerSet(array) {
17012
    let sets = [[]];
17013
    for (let i = 0; i < array.length; i++) {
17014
        for (let j = 0, e = sets.length; j < e; j++) {
17015
            sets.push(sets[j].concat(array[i]));
17016
        }
17017
    }
17018
    return sets.sort((a, b) => b.length - a.length);
17019
}
17020
/**
17021
This function is used to add a set of tags to a language syntax
17022
via [`NodeSet.extend`](#common.NodeSet.extend) or
17023
[`LRParser.configure`](#lr.LRParser.configure).
17024
 
17025
The argument object maps node selectors to [highlighting
17026
tags](#highlight.Tag) or arrays of tags.
17027
 
17028
Node selectors may hold one or more (space-separated) node paths.
17029
Such a path can be a [node name](#common.NodeType.name), or
17030
multiple node names (or `*` wildcards) separated by slash
17031
characters, as in `"Block/Declaration/VariableName"`. Such a path
17032
matches the final node but only if its direct parent nodes are the
17033
other nodes mentioned. A `*` in such a path matches any parent,
17034
but only a single level—wildcards that match multiple parents
17035
aren't supported, both for efficiency reasons and because Lezer
17036
trees make it rather hard to reason about what they would match.)
17037
 
17038
A path can be ended with `/...` to indicate that the tag assigned
17039
to the node should also apply to all child nodes, even if they
17040
match their own style (by default, only the innermost style is
17041
used).
17042
 
17043
When a path ends in `!`, as in `Attribute!`, no further matching
17044
happens for the node's child nodes, and the entire node gets the
17045
given style.
17046
 
17047
In this notation, node names that contain `/`, `!`, `*`, or `...`
17048
must be quoted as JSON strings.
17049
 
17050
For example:
17051
 
17052
```javascript
17053
parser.withProps(
17054
  styleTags({
17055
    // Style Number and BigNumber nodes
17056
    "Number BigNumber": tags.number,
17057
    // Style Escape nodes whose parent is String
17058
    "String/Escape": tags.escape,
17059
    // Style anything inside Attributes nodes
17060
    "Attributes!": tags.meta,
17061
    // Add a style to all content inside Italic nodes
17062
    "Italic/...": tags.emphasis,
17063
    // Style InvalidString nodes as both `string` and `invalid`
17064
    "InvalidString": [tags.string, tags.invalid],
17065
    // Style the node named "/" as punctuation
17066
    '"/"': tags.punctuation
17067
  })
17068
)
17069
```
17070
*/
17071
function styleTags(spec) {
17072
    let byName = Object.create(null);
17073
    for (let prop in spec) {
17074
        let tags = spec[prop];
17075
        if (!Array.isArray(tags))
17076
            tags = [tags];
17077
        for (let part of prop.split(" "))
17078
            if (part) {
17079
                let pieces = [], mode = 2 /* Mode.Normal */, rest = part;
17080
                for (let pos = 0;;) {
17081
                    if (rest == "..." && pos > 0 && pos + 3 == part.length) {
17082
                        mode = 1 /* Mode.Inherit */;
17083
                        break;
17084
                    }
17085
                    let m = /^"(?:[^"\\]|\\.)*?"|[^\/!]+/.exec(rest);
17086
                    if (!m)
17087
                        throw new RangeError("Invalid path: " + part);
17088
                    pieces.push(m[0] == "*" ? "" : m[0][0] == '"' ? JSON.parse(m[0]) : m[0]);
17089
                    pos += m[0].length;
17090
                    if (pos == part.length)
17091
                        break;
17092
                    let next = part[pos++];
17093
                    if (pos == part.length && next == "!") {
17094
                        mode = 0 /* Mode.Opaque */;
17095
                        break;
17096
                    }
17097
                    if (next != "/")
17098
                        throw new RangeError("Invalid path: " + part);
17099
                    rest = part.slice(pos);
17100
                }
17101
                let last = pieces.length - 1, inner = pieces[last];
17102
                if (!inner)
17103
                    throw new RangeError("Invalid path: " + part);
17104
                let rule = new Rule(tags, mode, last > 0 ? pieces.slice(0, last) : null);
17105
                byName[inner] = rule.sort(byName[inner]);
17106
            }
17107
    }
17108
    return ruleNodeProp.add(byName);
17109
}
17110
const ruleNodeProp = new NodeProp();
17111
class Rule {
17112
    constructor(tags, mode, context, next) {
17113
        this.tags = tags;
17114
        this.mode = mode;
17115
        this.context = context;
17116
        this.next = next;
17117
    }
17118
    get opaque() { return this.mode == 0 /* Mode.Opaque */; }
17119
    get inherit() { return this.mode == 1 /* Mode.Inherit */; }
17120
    sort(other) {
17121
        if (!other || other.depth < this.depth) {
17122
            this.next = other;
17123
            return this;
17124
        }
17125
        other.next = this.sort(other.next);
17126
        return other;
17127
    }
17128
    get depth() { return this.context ? this.context.length : 0; }
17129
}
17130
Rule.empty = new Rule([], 2 /* Mode.Normal */, null);
17131
/**
17132
Define a [highlighter](#highlight.Highlighter) from an array of
17133
tag/class pairs. Classes associated with more specific tags will
17134
take precedence.
17135
*/
17136
function tagHighlighter(tags, options) {
17137
    let map = Object.create(null);
17138
    for (let style of tags) {
17139
        if (!Array.isArray(style.tag))
17140
            map[style.tag.id] = style.class;
17141
        else
17142
            for (let tag of style.tag)
17143
                map[tag.id] = style.class;
17144
    }
17145
    let { scope, all = null } = options || {};
17146
    return {
17147
        style: (tags) => {
17148
            let cls = all;
17149
            for (let tag of tags) {
17150
                for (let sub of tag.set) {
17151
                    let tagClass = map[sub.id];
17152
                    if (tagClass) {
17153
                        cls = cls ? cls + " " + tagClass : tagClass;
17154
                        break;
17155
                    }
17156
                }
17157
            }
17158
            return cls;
17159
        },
17160
        scope
17161
    };
17162
}
17163
function highlightTags(highlighters, tags) {
17164
    let result = null;
17165
    for (let highlighter of highlighters) {
17166
        let value = highlighter.style(tags);
17167
        if (value)
17168
            result = result ? result + " " + value : value;
17169
    }
17170
    return result;
17171
}
17172
/**
17173
Highlight the given [tree](#common.Tree) with the given
17174
[highlighter](#highlight.Highlighter). Often, the higher-level
17175
[`highlightCode`](#highlight.highlightCode) function is easier to
17176
use.
17177
*/
17178
function highlightTree(tree, highlighter,
17179
/**
17180
Assign styling to a region of the text. Will be called, in order
17181
of position, for any ranges where more than zero classes apply.
17182
`classes` is a space separated string of CSS classes.
17183
*/
17184
putStyle,
17185
/**
17186
The start of the range to highlight.
17187
*/
17188
from = 0,
17189
/**
17190
The end of the range.
17191
*/
17192
to = tree.length) {
17193
    let builder = new HighlightBuilder(from, Array.isArray(highlighter) ? highlighter : [highlighter], putStyle);
17194
    builder.highlightRange(tree.cursor(), from, to, "", builder.highlighters);
17195
    builder.flush(to);
17196
}
17197
class HighlightBuilder {
17198
    constructor(at, highlighters, span) {
17199
        this.at = at;
17200
        this.highlighters = highlighters;
17201
        this.span = span;
17202
        this.class = "";
17203
    }
17204
    startSpan(at, cls) {
17205
        if (cls != this.class) {
17206
            this.flush(at);
17207
            if (at > this.at)
17208
                this.at = at;
17209
            this.class = cls;
17210
        }
17211
    }
17212
    flush(to) {
17213
        if (to > this.at && this.class)
17214
            this.span(this.at, to, this.class);
17215
    }
17216
    highlightRange(cursor, from, to, inheritedClass, highlighters) {
17217
        let { type, from: start, to: end } = cursor;
17218
        if (start >= to || end <= from)
17219
            return;
17220
        if (type.isTop)
17221
            highlighters = this.highlighters.filter(h => !h.scope || h.scope(type));
17222
        let cls = inheritedClass;
17223
        let rule = getStyleTags(cursor) || Rule.empty;
17224
        let tagCls = highlightTags(highlighters, rule.tags);
17225
        if (tagCls) {
17226
            if (cls)
17227
                cls += " ";
17228
            cls += tagCls;
17229
            if (rule.mode == 1 /* Mode.Inherit */)
17230
                inheritedClass += (inheritedClass ? " " : "") + tagCls;
17231
        }
17232
        this.startSpan(Math.max(from, start), cls);
17233
        if (rule.opaque)
17234
            return;
17235
        let mounted = cursor.tree && cursor.tree.prop(NodeProp.mounted);
17236
        if (mounted && mounted.overlay) {
17237
            let inner = cursor.node.enter(mounted.overlay[0].from + start, 1);
17238
            let innerHighlighters = this.highlighters.filter(h => !h.scope || h.scope(mounted.tree.type));
17239
            let hasChild = cursor.firstChild();
17240
            for (let i = 0, pos = start;; i++) {
17241
                let next = i < mounted.overlay.length ? mounted.overlay[i] : null;
17242
                let nextPos = next ? next.from + start : end;
17243
                let rangeFrom = Math.max(from, pos), rangeTo = Math.min(to, nextPos);
17244
                if (rangeFrom < rangeTo && hasChild) {
17245
                    while (cursor.from < rangeTo) {
17246
                        this.highlightRange(cursor, rangeFrom, rangeTo, inheritedClass, highlighters);
17247
                        this.startSpan(Math.min(rangeTo, cursor.to), cls);
17248
                        if (cursor.to >= nextPos || !cursor.nextSibling())
17249
                            break;
17250
                    }
17251
                }
17252
                if (!next || nextPos > to)
17253
                    break;
17254
                pos = next.to + start;
17255
                if (pos > from) {
17256
                    this.highlightRange(inner.cursor(), Math.max(from, next.from + start), Math.min(to, pos), "", innerHighlighters);
17257
                    this.startSpan(Math.min(to, pos), cls);
17258
                }
17259
            }
17260
            if (hasChild)
17261
                cursor.parent();
17262
        }
17263
        else if (cursor.firstChild()) {
17264
            if (mounted)
17265
                inheritedClass = "";
17266
            do {
17267
                if (cursor.to <= from)
17268
                    continue;
17269
                if (cursor.from >= to)
17270
                    break;
17271
                this.highlightRange(cursor, from, to, inheritedClass, highlighters);
17272
                this.startSpan(Math.min(to, cursor.to), cls);
17273
            } while (cursor.nextSibling());
17274
            cursor.parent();
17275
        }
17276
    }
17277
}
17278
/**
17279
Match a syntax node's [highlight rules](#highlight.styleTags). If
17280
there's a match, return its set of tags, and whether it is
17281
opaque (uses a `!`) or applies to all child nodes (`/...`).
17282
*/
17283
function getStyleTags(node) {
17284
    let rule = node.type.prop(ruleNodeProp);
17285
    while (rule && rule.context && !node.matchContext(rule.context))
17286
        rule = rule.next;
17287
    return rule || null;
17288
}
17289
const t = Tag.define;
17290
const comment = t(), name = t(), typeName = t(name), propertyName = t(name), literal = t(), string = t(literal), number = t(literal), content = t(), heading = t(content), keyword = t(), operator = t(), punctuation = t(), bracket = t(punctuation), meta = t();
17291
/**
17292
The default set of highlighting [tags](#highlight.Tag).
17293
 
17294
This collection is heavily biased towards programming languages,
17295
and necessarily incomplete. A full ontology of syntactic
17296
constructs would fill a stack of books, and be impractical to
17297
write themes for. So try to make do with this set. If all else
17298
fails, [open an
17299
issue](https://github.com/codemirror/codemirror.next) to propose a
17300
new tag, or [define](#highlight.Tag^define) a local custom tag for
17301
your use case.
17302
 
17303
Note that it is not obligatory to always attach the most specific
17304
tag possible to an element—if your grammar can't easily
17305
distinguish a certain type of element (such as a local variable),
17306
it is okay to style it as its more general variant (a variable).
17307
 
17308
For tags that extend some parent tag, the documentation links to
17309
the parent.
17310
*/
17311
const tags$1 = {
17312
    /**
17313
    A comment.
17314
    */
17315
    comment,
17316
    /**
17317
    A line [comment](#highlight.tags.comment).
17318
    */
17319
    lineComment: t(comment),
17320
    /**
17321
    A block [comment](#highlight.tags.comment).
17322
    */
17323
    blockComment: t(comment),
17324
    /**
17325
    A documentation [comment](#highlight.tags.comment).
17326
    */
17327
    docComment: t(comment),
17328
    /**
17329
    Any kind of identifier.
17330
    */
17331
    name,
17332
    /**
17333
    The [name](#highlight.tags.name) of a variable.
17334
    */
17335
    variableName: t(name),
17336
    /**
17337
    A type [name](#highlight.tags.name).
17338
    */
17339
    typeName: typeName,
17340
    /**
17341
    A tag name (subtag of [`typeName`](#highlight.tags.typeName)).
17342
    */
17343
    tagName: t(typeName),
17344
    /**
17345
    A property or field [name](#highlight.tags.name).
17346
    */
17347
    propertyName: propertyName,
17348
    /**
17349
    An attribute name (subtag of [`propertyName`](#highlight.tags.propertyName)).
17350
    */
17351
    attributeName: t(propertyName),
17352
    /**
17353
    The [name](#highlight.tags.name) of a class.
17354
    */
17355
    className: t(name),
17356
    /**
17357
    A label [name](#highlight.tags.name).
17358
    */
17359
    labelName: t(name),
17360
    /**
17361
    A namespace [name](#highlight.tags.name).
17362
    */
17363
    namespace: t(name),
17364
    /**
17365
    The [name](#highlight.tags.name) of a macro.
17366
    */
17367
    macroName: t(name),
17368
    /**
17369
    A literal value.
17370
    */
17371
    literal,
17372
    /**
17373
    A string [literal](#highlight.tags.literal).
17374
    */
17375
    string,
17376
    /**
17377
    A documentation [string](#highlight.tags.string).
17378
    */
17379
    docString: t(string),
17380
    /**
17381
    A character literal (subtag of [string](#highlight.tags.string)).
17382
    */
17383
    character: t(string),
17384
    /**
17385
    An attribute value (subtag of [string](#highlight.tags.string)).
17386
    */
17387
    attributeValue: t(string),
17388
    /**
17389
    A number [literal](#highlight.tags.literal).
17390
    */
17391
    number,
17392
    /**
17393
    An integer [number](#highlight.tags.number) literal.
17394
    */
17395
    integer: t(number),
17396
    /**
17397
    A floating-point [number](#highlight.tags.number) literal.
17398
    */
17399
    float: t(number),
17400
    /**
17401
    A boolean [literal](#highlight.tags.literal).
17402
    */
17403
    bool: t(literal),
17404
    /**
17405
    Regular expression [literal](#highlight.tags.literal).
17406
    */
17407
    regexp: t(literal),
17408
    /**
17409
    An escape [literal](#highlight.tags.literal), for example a
17410
    backslash escape in a string.
17411
    */
17412
    escape: t(literal),
17413
    /**
17414
    A color [literal](#highlight.tags.literal).
17415
    */
17416
    color: t(literal),
17417
    /**
17418
    A URL [literal](#highlight.tags.literal).
17419
    */
17420
    url: t(literal),
17421
    /**
17422
    A language keyword.
17423
    */
17424
    keyword,
17425
    /**
17426
    The [keyword](#highlight.tags.keyword) for the self or this
17427
    object.
17428
    */
17429
    self: t(keyword),
17430
    /**
17431
    The [keyword](#highlight.tags.keyword) for null.
17432
    */
17433
    null: t(keyword),
17434
    /**
17435
    A [keyword](#highlight.tags.keyword) denoting some atomic value.
17436
    */
17437
    atom: t(keyword),
17438
    /**
17439
    A [keyword](#highlight.tags.keyword) that represents a unit.
17440
    */
17441
    unit: t(keyword),
17442
    /**
17443
    A modifier [keyword](#highlight.tags.keyword).
17444
    */
17445
    modifier: t(keyword),
17446
    /**
17447
    A [keyword](#highlight.tags.keyword) that acts as an operator.
17448
    */
17449
    operatorKeyword: t(keyword),
17450
    /**
17451
    A control-flow related [keyword](#highlight.tags.keyword).
17452
    */
17453
    controlKeyword: t(keyword),
17454
    /**
17455
    A [keyword](#highlight.tags.keyword) that defines something.
17456
    */
17457
    definitionKeyword: t(keyword),
17458
    /**
17459
    A [keyword](#highlight.tags.keyword) related to defining or
17460
    interfacing with modules.
17461
    */
17462
    moduleKeyword: t(keyword),
17463
    /**
17464
    An operator.
17465
    */
17466
    operator,
17467
    /**
17468
    An [operator](#highlight.tags.operator) that dereferences something.
17469
    */
17470
    derefOperator: t(operator),
17471
    /**
17472
    Arithmetic-related [operator](#highlight.tags.operator).
17473
    */
17474
    arithmeticOperator: t(operator),
17475
    /**
17476
    Logical [operator](#highlight.tags.operator).
17477
    */
17478
    logicOperator: t(operator),
17479
    /**
17480
    Bit [operator](#highlight.tags.operator).
17481
    */
17482
    bitwiseOperator: t(operator),
17483
    /**
17484
    Comparison [operator](#highlight.tags.operator).
17485
    */
17486
    compareOperator: t(operator),
17487
    /**
17488
    [Operator](#highlight.tags.operator) that updates its operand.
17489
    */
17490
    updateOperator: t(operator),
17491
    /**
17492
    [Operator](#highlight.tags.operator) that defines something.
17493
    */
17494
    definitionOperator: t(operator),
17495
    /**
17496
    Type-related [operator](#highlight.tags.operator).
17497
    */
17498
    typeOperator: t(operator),
17499
    /**
17500
    Control-flow [operator](#highlight.tags.operator).
17501
    */
17502
    controlOperator: t(operator),
17503
    /**
17504
    Program or markup punctuation.
17505
    */
17506
    punctuation,
17507
    /**
17508
    [Punctuation](#highlight.tags.punctuation) that separates
17509
    things.
17510
    */
17511
    separator: t(punctuation),
17512
    /**
17513
    Bracket-style [punctuation](#highlight.tags.punctuation).
17514
    */
17515
    bracket,
17516
    /**
17517
    Angle [brackets](#highlight.tags.bracket) (usually `<` and `>`
17518
    tokens).
17519
    */
17520
    angleBracket: t(bracket),
17521
    /**
17522
    Square [brackets](#highlight.tags.bracket) (usually `[` and `]`
17523
    tokens).
17524
    */
17525
    squareBracket: t(bracket),
17526
    /**
17527
    Parentheses (usually `(` and `)` tokens). Subtag of
17528
    [bracket](#highlight.tags.bracket).
17529
    */
17530
    paren: t(bracket),
17531
    /**
17532
    Braces (usually `{` and `}` tokens). Subtag of
17533
    [bracket](#highlight.tags.bracket).
17534
    */
17535
    brace: t(bracket),
17536
    /**
17537
    Content, for example plain text in XML or markup documents.
17538
    */
17539
    content,
17540
    /**
17541
    [Content](#highlight.tags.content) that represents a heading.
17542
    */
17543
    heading,
17544
    /**
17545
    A level 1 [heading](#highlight.tags.heading).
17546
    */
17547
    heading1: t(heading),
17548
    /**
17549
    A level 2 [heading](#highlight.tags.heading).
17550
    */
17551
    heading2: t(heading),
17552
    /**
17553
    A level 3 [heading](#highlight.tags.heading).
17554
    */
17555
    heading3: t(heading),
17556
    /**
17557
    A level 4 [heading](#highlight.tags.heading).
17558
    */
17559
    heading4: t(heading),
17560
    /**
17561
    A level 5 [heading](#highlight.tags.heading).
17562
    */
17563
    heading5: t(heading),
17564
    /**
17565
    A level 6 [heading](#highlight.tags.heading).
17566
    */
17567
    heading6: t(heading),
17568
    /**
17569
    A prose separator (such as a horizontal rule).
17570
    */
17571
    contentSeparator: t(content),
17572
    /**
17573
    [Content](#highlight.tags.content) that represents a list.
17574
    */
17575
    list: t(content),
17576
    /**
17577
    [Content](#highlight.tags.content) that represents a quote.
17578
    */
17579
    quote: t(content),
17580
    /**
17581
    [Content](#highlight.tags.content) that is emphasized.
17582
    */
17583
    emphasis: t(content),
17584
    /**
17585
    [Content](#highlight.tags.content) that is styled strong.
17586
    */
17587
    strong: t(content),
17588
    /**
17589
    [Content](#highlight.tags.content) that is part of a link.
17590
    */
17591
    link: t(content),
17592
    /**
17593
    [Content](#highlight.tags.content) that is styled as code or
17594
    monospace.
17595
    */
17596
    monospace: t(content),
17597
    /**
17598
    [Content](#highlight.tags.content) that has a strike-through
17599
    style.
17600
    */
17601
    strikethrough: t(content),
17602
    /**
17603
    Inserted text in a change-tracking format.
17604
    */
17605
    inserted: t(),
17606
    /**
17607
    Deleted text.
17608
    */
17609
    deleted: t(),
17610
    /**
17611
    Changed text.
17612
    */
17613
    changed: t(),
17614
    /**
17615
    An invalid or unsyntactic element.
17616
    */
17617
    invalid: t(),
17618
    /**
17619
    Metadata or meta-instruction.
17620
    */
17621
    meta,
17622
    /**
17623
    [Metadata](#highlight.tags.meta) that applies to the entire
17624
    document.
17625
    */
17626
    documentMeta: t(meta),
17627
    /**
17628
    [Metadata](#highlight.tags.meta) that annotates or adds
17629
    attributes to a given syntactic element.
17630
    */
17631
    annotation: t(meta),
17632
    /**
17633
    Processing instruction or preprocessor directive. Subtag of
17634
    [meta](#highlight.tags.meta).
17635
    */
17636
    processingInstruction: t(meta),
17637
    /**
17638
    [Modifier](#highlight.Tag^defineModifier) that indicates that a
17639
    given element is being defined. Expected to be used with the
17640
    various [name](#highlight.tags.name) tags.
17641
    */
17642
    definition: Tag.defineModifier(),
17643
    /**
17644
    [Modifier](#highlight.Tag^defineModifier) that indicates that
17645
    something is constant. Mostly expected to be used with
17646
    [variable names](#highlight.tags.variableName).
17647
    */
17648
    constant: Tag.defineModifier(),
17649
    /**
17650
    [Modifier](#highlight.Tag^defineModifier) used to indicate that
17651
    a [variable](#highlight.tags.variableName) or [property
17652
    name](#highlight.tags.propertyName) is being called or defined
17653
    as a function.
17654
    */
17655
    function: Tag.defineModifier(),
17656
    /**
17657
    [Modifier](#highlight.Tag^defineModifier) that can be applied to
17658
    [names](#highlight.tags.name) to indicate that they belong to
17659
    the language's standard environment.
17660
    */
17661
    standard: Tag.defineModifier(),
17662
    /**
17663
    [Modifier](#highlight.Tag^defineModifier) that indicates a given
17664
    [names](#highlight.tags.name) is local to some scope.
17665
    */
17666
    local: Tag.defineModifier(),
17667
    /**
17668
    A generic variant [modifier](#highlight.Tag^defineModifier) that
17669
    can be used to tag language-specific alternative variants of
17670
    some common tag. It is recommended for themes to define special
17671
    forms of at least the [string](#highlight.tags.string) and
17672
    [variable name](#highlight.tags.variableName) tags, since those
17673
    come up a lot.
17674
    */
17675
    special: Tag.defineModifier()
17676
};
17677
/**
17678
This is a highlighter that adds stable, predictable classes to
17679
tokens, for styling with external CSS.
17680
 
17681
The following tags are mapped to their name prefixed with `"tok-"`
17682
(for example `"tok-comment"`):
17683
 
17684
* [`link`](#highlight.tags.link)
17685
* [`heading`](#highlight.tags.heading)
17686
* [`emphasis`](#highlight.tags.emphasis)
17687
* [`strong`](#highlight.tags.strong)
17688
* [`keyword`](#highlight.tags.keyword)
17689
* [`atom`](#highlight.tags.atom)
17690
* [`bool`](#highlight.tags.bool)
17691
* [`url`](#highlight.tags.url)
17692
* [`labelName`](#highlight.tags.labelName)
17693
* [`inserted`](#highlight.tags.inserted)
17694
* [`deleted`](#highlight.tags.deleted)
17695
* [`literal`](#highlight.tags.literal)
17696
* [`string`](#highlight.tags.string)
17697
* [`number`](#highlight.tags.number)
17698
* [`variableName`](#highlight.tags.variableName)
17699
* [`typeName`](#highlight.tags.typeName)
17700
* [`namespace`](#highlight.tags.namespace)
17701
* [`className`](#highlight.tags.className)
17702
* [`macroName`](#highlight.tags.macroName)
17703
* [`propertyName`](#highlight.tags.propertyName)
17704
* [`operator`](#highlight.tags.operator)
17705
* [`comment`](#highlight.tags.comment)
17706
* [`meta`](#highlight.tags.meta)
17707
* [`punctuation`](#highlight.tags.punctuation)
17708
* [`invalid`](#highlight.tags.invalid)
17709
 
17710
In addition, these mappings are provided:
17711
 
17712
* [`regexp`](#highlight.tags.regexp),
17713
  [`escape`](#highlight.tags.escape), and
17714
  [`special`](#highlight.tags.special)[`(string)`](#highlight.tags.string)
17715
  are mapped to `"tok-string2"`
17716
* [`special`](#highlight.tags.special)[`(variableName)`](#highlight.tags.variableName)
17717
  to `"tok-variableName2"`
17718
* [`local`](#highlight.tags.local)[`(variableName)`](#highlight.tags.variableName)
17719
  to `"tok-variableName tok-local"`
17720
* [`definition`](#highlight.tags.definition)[`(variableName)`](#highlight.tags.variableName)
17721
  to `"tok-variableName tok-definition"`
17722
* [`definition`](#highlight.tags.definition)[`(propertyName)`](#highlight.tags.propertyName)
17723
  to `"tok-propertyName tok-definition"`
17724
*/
17725
tagHighlighter([
17726
    { tag: tags$1.link, class: "tok-link" },
17727
    { tag: tags$1.heading, class: "tok-heading" },
17728
    { tag: tags$1.emphasis, class: "tok-emphasis" },
17729
    { tag: tags$1.strong, class: "tok-strong" },
17730
    { tag: tags$1.keyword, class: "tok-keyword" },
17731
    { tag: tags$1.atom, class: "tok-atom" },
17732
    { tag: tags$1.bool, class: "tok-bool" },
17733
    { tag: tags$1.url, class: "tok-url" },
17734
    { tag: tags$1.labelName, class: "tok-labelName" },
17735
    { tag: tags$1.inserted, class: "tok-inserted" },
17736
    { tag: tags$1.deleted, class: "tok-deleted" },
17737
    { tag: tags$1.literal, class: "tok-literal" },
17738
    { tag: tags$1.string, class: "tok-string" },
17739
    { tag: tags$1.number, class: "tok-number" },
17740
    { tag: [tags$1.regexp, tags$1.escape, tags$1.special(tags$1.string)], class: "tok-string2" },
17741
    { tag: tags$1.variableName, class: "tok-variableName" },
17742
    { tag: tags$1.local(tags$1.variableName), class: "tok-variableName tok-local" },
17743
    { tag: tags$1.definition(tags$1.variableName), class: "tok-variableName tok-definition" },
17744
    { tag: tags$1.special(tags$1.variableName), class: "tok-variableName2" },
17745
    { tag: tags$1.definition(tags$1.propertyName), class: "tok-propertyName tok-definition" },
17746
    { tag: tags$1.typeName, class: "tok-typeName" },
17747
    { tag: tags$1.namespace, class: "tok-namespace" },
17748
    { tag: tags$1.className, class: "tok-className" },
17749
    { tag: tags$1.macroName, class: "tok-macroName" },
17750
    { tag: tags$1.propertyName, class: "tok-propertyName" },
17751
    { tag: tags$1.operator, class: "tok-operator" },
17752
    { tag: tags$1.comment, class: "tok-comment" },
17753
    { tag: tags$1.meta, class: "tok-meta" },
17754
    { tag: tags$1.invalid, class: "tok-invalid" },
17755
    { tag: tags$1.punctuation, class: "tok-punctuation" }
17756
]);
17757
 
17758
var _a;
17759
/**
17760
Node prop stored in a parser's top syntax node to provide the
17761
facet that stores language-specific data for that language.
17762
*/
17763
const languageDataProp = /*@__PURE__*/new NodeProp();
17764
/**
17765
Helper function to define a facet (to be added to the top syntax
17766
node(s) for a language via
17767
[`languageDataProp`](https://codemirror.net/6/docs/ref/#language.languageDataProp)), that will be
17768
used to associate language data with the language. You
17769
probably only need this when subclassing
17770
[`Language`](https://codemirror.net/6/docs/ref/#language.Language).
17771
*/
17772
function defineLanguageFacet(baseData) {
17773
    return Facet.define({
17774
        combine: baseData ? values => values.concat(baseData) : undefined
17775
    });
17776
}
17777
/**
17778
Syntax node prop used to register sublanguages. Should be added to
17779
the top level node type for the language.
17780
*/
17781
const sublanguageProp = /*@__PURE__*/new NodeProp();
17782
/**
17783
A language object manages parsing and per-language
17784
[metadata](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt). Parse data is
17785
managed as a [Lezer](https://lezer.codemirror.net) tree. The class
17786
can be used directly, via the [`LRLanguage`](https://codemirror.net/6/docs/ref/#language.LRLanguage)
17787
subclass for [Lezer](https://lezer.codemirror.net/) LR parsers, or
17788
via the [`StreamLanguage`](https://codemirror.net/6/docs/ref/#language.StreamLanguage) subclass
17789
for stream parsers.
17790
*/
17791
class Language {
17792
    /**
17793
    Construct a language object. If you need to invoke this
17794
    directly, first define a data facet with
17795
    [`defineLanguageFacet`](https://codemirror.net/6/docs/ref/#language.defineLanguageFacet), and then
17796
    configure your parser to [attach](https://codemirror.net/6/docs/ref/#language.languageDataProp) it
17797
    to the language's outer syntax node.
17798
    */
17799
    constructor(
17800
    /**
17801
    The [language data](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt) facet
17802
    used for this language.
17803
    */
17804
    data, parser, extraExtensions = [],
17805
    /**
17806
    A language name.
17807
    */
17808
    name = "") {
17809
        this.data = data;
17810
        this.name = name;
17811
        // Kludge to define EditorState.tree as a debugging helper,
17812
        // without the EditorState package actually knowing about
17813
        // languages and lezer trees.
17814
        if (!EditorState.prototype.hasOwnProperty("tree"))
17815
            Object.defineProperty(EditorState.prototype, "tree", { get() { return syntaxTree(this); } });
17816
        this.parser = parser;
17817
        this.extension = [
17818
            language.of(this),
17819
            EditorState.languageData.of((state, pos, side) => {
17820
                let top = topNodeAt(state, pos, side), data = top.type.prop(languageDataProp);
17821
                if (!data)
17822
                    return [];
17823
                let base = state.facet(data), sub = top.type.prop(sublanguageProp);
17824
                if (sub) {
17825
                    let innerNode = top.resolve(pos - top.from, side);
17826
                    for (let sublang of sub)
17827
                        if (sublang.test(innerNode, state)) {
17828
                            let data = state.facet(sublang.facet);
17829
                            return sublang.type == "replace" ? data : data.concat(base);
17830
                        }
17831
                }
17832
                return base;
17833
            })
17834
        ].concat(extraExtensions);
17835
    }
17836
    /**
17837
    Query whether this language is active at the given position.
17838
    */
17839
    isActiveAt(state, pos, side = -1) {
17840
        return topNodeAt(state, pos, side).type.prop(languageDataProp) == this.data;
17841
    }
17842
    /**
17843
    Find the document regions that were parsed using this language.
17844
    The returned regions will _include_ any nested languages rooted
17845
    in this language, when those exist.
17846
    */
17847
    findRegions(state) {
17848
        let lang = state.facet(language);
17849
        if ((lang === null || lang === void 0 ? void 0 : lang.data) == this.data)
17850
            return [{ from: 0, to: state.doc.length }];
17851
        if (!lang || !lang.allowsNesting)
17852
            return [];
17853
        let result = [];
17854
        let explore = (tree, from) => {
17855
            if (tree.prop(languageDataProp) == this.data) {
17856
                result.push({ from, to: from + tree.length });
17857
                return;
17858
            }
17859
            let mount = tree.prop(NodeProp.mounted);
17860
            if (mount) {
17861
                if (mount.tree.prop(languageDataProp) == this.data) {
17862
                    if (mount.overlay)
17863
                        for (let r of mount.overlay)
17864
                            result.push({ from: r.from + from, to: r.to + from });
17865
                    else
17866
                        result.push({ from: from, to: from + tree.length });
17867
                    return;
17868
                }
17869
                else if (mount.overlay) {
17870
                    let size = result.length;
17871
                    explore(mount.tree, mount.overlay[0].from + from);
17872
                    if (result.length > size)
17873
                        return;
17874
                }
17875
            }
17876
            for (let i = 0; i < tree.children.length; i++) {
17877
                let ch = tree.children[i];
17878
                if (ch instanceof Tree)
17879
                    explore(ch, tree.positions[i] + from);
17880
            }
17881
        };
17882
        explore(syntaxTree(state), 0);
17883
        return result;
17884
    }
17885
    /**
17886
    Indicates whether this language allows nested languages. The
17887
    default implementation returns true.
17888
    */
17889
    get allowsNesting() { return true; }
17890
}
17891
/**
17892
@internal
17893
*/
17894
Language.setState = /*@__PURE__*/StateEffect.define();
17895
function topNodeAt(state, pos, side) {
17896
    let topLang = state.facet(language), tree = syntaxTree(state).topNode;
17897
    if (!topLang || topLang.allowsNesting) {
17898
        for (let node = tree; node; node = node.enter(pos, side, IterMode.ExcludeBuffers))
17899
            if (node.type.isTop)
17900
                tree = node;
17901
    }
17902
    return tree;
17903
}
17904
/**
17905
A subclass of [`Language`](https://codemirror.net/6/docs/ref/#language.Language) for use with Lezer
17906
[LR parsers](https://lezer.codemirror.net/docs/ref#lr.LRParser)
17907
parsers.
17908
*/
17909
class LRLanguage extends Language {
17910
    constructor(data, parser, name) {
17911
        super(data, parser, [], name);
17912
        this.parser = parser;
17913
    }
17914
    /**
17915
    Define a language from a parser.
17916
    */
17917
    static define(spec) {
17918
        let data = defineLanguageFacet(spec.languageData);
17919
        return new LRLanguage(data, spec.parser.configure({
17920
            props: [languageDataProp.add(type => type.isTop ? data : undefined)]
17921
        }), spec.name);
17922
    }
17923
    /**
17924
    Create a new instance of this language with a reconfigured
17925
    version of its parser and optionally a new name.
17926
    */
17927
    configure(options, name) {
17928
        return new LRLanguage(this.data, this.parser.configure(options), name || this.name);
17929
    }
17930
    get allowsNesting() { return this.parser.hasWrappers(); }
17931
}
17932
/**
17933
Get the syntax tree for a state, which is the current (possibly
17934
incomplete) parse tree of the active
17935
[language](https://codemirror.net/6/docs/ref/#language.Language), or the empty tree if there is no
17936
language available.
17937
*/
17938
function syntaxTree(state) {
17939
    let field = state.field(Language.state, false);
17940
    return field ? field.tree : Tree.empty;
17941
}
17942
/**
17943
Lezer-style
17944
[`Input`](https://lezer.codemirror.net/docs/ref#common.Input)
17945
object for a [`Text`](https://codemirror.net/6/docs/ref/#state.Text) object.
17946
*/
17947
class DocInput {
17948
    /**
17949
    Create an input object for the given document.
17950
    */
17951
    constructor(doc) {
17952
        this.doc = doc;
17953
        this.cursorPos = 0;
17954
        this.string = "";
17955
        this.cursor = doc.iter();
17956
    }
17957
    get length() { return this.doc.length; }
17958
    syncTo(pos) {
17959
        this.string = this.cursor.next(pos - this.cursorPos).value;
17960
        this.cursorPos = pos + this.string.length;
17961
        return this.cursorPos - this.string.length;
17962
    }
17963
    chunk(pos) {
17964
        this.syncTo(pos);
17965
        return this.string;
17966
    }
17967
    get lineChunks() { return true; }
17968
    read(from, to) {
17969
        let stringStart = this.cursorPos - this.string.length;
17970
        if (from < stringStart || to >= this.cursorPos)
17971
            return this.doc.sliceString(from, to);
17972
        else
17973
            return this.string.slice(from - stringStart, to - stringStart);
17974
    }
17975
}
17976
let currentContext = null;
17977
/**
17978
A parse context provided to parsers working on the editor content.
17979
*/
17980
class ParseContext {
17981
    constructor(parser,
17982
    /**
17983
    The current editor state.
17984
    */
17985
    state,
17986
    /**
17987
    Tree fragments that can be reused by incremental re-parses.
17988
    */
17989
    fragments = [],
17990
    /**
17991
    @internal
17992
    */
17993
    tree,
17994
    /**
17995
    @internal
17996
    */
17997
    treeLen,
17998
    /**
17999
    The current editor viewport (or some overapproximation
18000
    thereof). Intended to be used for opportunistically avoiding
18001
    work (in which case
18002
    [`skipUntilInView`](https://codemirror.net/6/docs/ref/#language.ParseContext.skipUntilInView)
18003
    should be called to make sure the parser is restarted when the
18004
    skipped region becomes visible).
18005
    */
18006
    viewport,
18007
    /**
18008
    @internal
18009
    */
18010
    skipped,
18011
    /**
18012
    This is where skipping parsers can register a promise that,
18013
    when resolved, will schedule a new parse. It is cleared when
18014
    the parse worker picks up the promise. @internal
18015
    */
18016
    scheduleOn) {
18017
        this.parser = parser;
18018
        this.state = state;
18019
        this.fragments = fragments;
18020
        this.tree = tree;
18021
        this.treeLen = treeLen;
18022
        this.viewport = viewport;
18023
        this.skipped = skipped;
18024
        this.scheduleOn = scheduleOn;
18025
        this.parse = null;
18026
        /**
18027
        @internal
18028
        */
18029
        this.tempSkipped = [];
18030
    }
18031
    /**
18032
    @internal
18033
    */
18034
    static create(parser, state, viewport) {
18035
        return new ParseContext(parser, state, [], Tree.empty, 0, viewport, [], null);
18036
    }
18037
    startParse() {
18038
        return this.parser.startParse(new DocInput(this.state.doc), this.fragments);
18039
    }
18040
    /**
18041
    @internal
18042
    */
18043
    work(until, upto) {
18044
        if (upto != null && upto >= this.state.doc.length)
18045
            upto = undefined;
18046
        if (this.tree != Tree.empty && this.isDone(upto !== null && upto !== void 0 ? upto : this.state.doc.length)) {
18047
            this.takeTree();
18048
            return true;
18049
        }
18050
        return this.withContext(() => {
18051
            var _a;
18052
            if (typeof until == "number") {
18053
                let endTime = Date.now() + until;
18054
                until = () => Date.now() > endTime;
18055
            }
18056
            if (!this.parse)
18057
                this.parse = this.startParse();
18058
            if (upto != null && (this.parse.stoppedAt == null || this.parse.stoppedAt > upto) &&
18059
                upto < this.state.doc.length)
18060
                this.parse.stopAt(upto);
18061
            for (;;) {
18062
                let done = this.parse.advance();
18063
                if (done) {
18064
                    this.fragments = this.withoutTempSkipped(TreeFragment.addTree(done, this.fragments, this.parse.stoppedAt != null));
18065
                    this.treeLen = (_a = this.parse.stoppedAt) !== null && _a !== void 0 ? _a : this.state.doc.length;
18066
                    this.tree = done;
18067
                    this.parse = null;
18068
                    if (this.treeLen < (upto !== null && upto !== void 0 ? upto : this.state.doc.length))
18069
                        this.parse = this.startParse();
18070
                    else
18071
                        return true;
18072
                }
18073
                if (until())
18074
                    return false;
18075
            }
18076
        });
18077
    }
18078
    /**
18079
    @internal
18080
    */
18081
    takeTree() {
18082
        let pos, tree;
18083
        if (this.parse && (pos = this.parse.parsedPos) >= this.treeLen) {
18084
            if (this.parse.stoppedAt == null || this.parse.stoppedAt > pos)
18085
                this.parse.stopAt(pos);
18086
            this.withContext(() => { while (!(tree = this.parse.advance())) { } });
18087
            this.treeLen = pos;
18088
            this.tree = tree;
18089
            this.fragments = this.withoutTempSkipped(TreeFragment.addTree(this.tree, this.fragments, true));
18090
            this.parse = null;
18091
        }
18092
    }
18093
    withContext(f) {
18094
        let prev = currentContext;
18095
        currentContext = this;
18096
        try {
18097
            return f();
18098
        }
18099
        finally {
18100
            currentContext = prev;
18101
        }
18102
    }
18103
    withoutTempSkipped(fragments) {
18104
        for (let r; r = this.tempSkipped.pop();)
18105
            fragments = cutFragments(fragments, r.from, r.to);
18106
        return fragments;
18107
    }
18108
    /**
18109
    @internal
18110
    */
18111
    changes(changes, newState) {
18112
        let { fragments, tree, treeLen, viewport, skipped } = this;
18113
        this.takeTree();
18114
        if (!changes.empty) {
18115
            let ranges = [];
18116
            changes.iterChangedRanges((fromA, toA, fromB, toB) => ranges.push({ fromA, toA, fromB, toB }));
18117
            fragments = TreeFragment.applyChanges(fragments, ranges);
18118
            tree = Tree.empty;
18119
            treeLen = 0;
18120
            viewport = { from: changes.mapPos(viewport.from, -1), to: changes.mapPos(viewport.to, 1) };
18121
            if (this.skipped.length) {
18122
                skipped = [];
18123
                for (let r of this.skipped) {
18124
                    let from = changes.mapPos(r.from, 1), to = changes.mapPos(r.to, -1);
18125
                    if (from < to)
18126
                        skipped.push({ from, to });
18127
                }
18128
            }
18129
        }
18130
        return new ParseContext(this.parser, newState, fragments, tree, treeLen, viewport, skipped, this.scheduleOn);
18131
    }
18132
    /**
18133
    @internal
18134
    */
18135
    updateViewport(viewport) {
18136
        if (this.viewport.from == viewport.from && this.viewport.to == viewport.to)
18137
            return false;
18138
        this.viewport = viewport;
18139
        let startLen = this.skipped.length;
18140
        for (let i = 0; i < this.skipped.length; i++) {
18141
            let { from, to } = this.skipped[i];
18142
            if (from < viewport.to && to > viewport.from) {
18143
                this.fragments = cutFragments(this.fragments, from, to);
18144
                this.skipped.splice(i--, 1);
18145
            }
18146
        }
18147
        if (this.skipped.length >= startLen)
18148
            return false;
18149
        this.reset();
18150
        return true;
18151
    }
18152
    /**
18153
    @internal
18154
    */
18155
    reset() {
18156
        if (this.parse) {
18157
            this.takeTree();
18158
            this.parse = null;
18159
        }
18160
    }
18161
    /**
18162
    Notify the parse scheduler that the given region was skipped
18163
    because it wasn't in view, and the parse should be restarted
18164
    when it comes into view.
18165
    */
18166
    skipUntilInView(from, to) {
18167
        this.skipped.push({ from, to });
18168
    }
18169
    /**
18170
    Returns a parser intended to be used as placeholder when
18171
    asynchronously loading a nested parser. It'll skip its input and
18172
    mark it as not-really-parsed, so that the next update will parse
18173
    it again.
18174
 
18175
    When `until` is given, a reparse will be scheduled when that
18176
    promise resolves.
18177
    */
18178
    static getSkippingParser(until) {
18179
        return new class extends Parser {
18180
            createParse(input, fragments, ranges) {
18181
                let from = ranges[0].from, to = ranges[ranges.length - 1].to;
18182
                let parser = {
18183
                    parsedPos: from,
18184
                    advance() {
18185
                        let cx = currentContext;
18186
                        if (cx) {
18187
                            for (let r of ranges)
18188
                                cx.tempSkipped.push(r);
18189
                            if (until)
18190
                                cx.scheduleOn = cx.scheduleOn ? Promise.all([cx.scheduleOn, until]) : until;
18191
                        }
18192
                        this.parsedPos = to;
18193
                        return new Tree(NodeType.none, [], [], to - from);
18194
                    },
18195
                    stoppedAt: null,
18196
                    stopAt() { }
18197
                };
18198
                return parser;
18199
            }
18200
        };
18201
    }
18202
    /**
18203
    @internal
18204
    */
18205
    isDone(upto) {
18206
        upto = Math.min(upto, this.state.doc.length);
18207
        let frags = this.fragments;
18208
        return this.treeLen >= upto && frags.length && frags[0].from == 0 && frags[0].to >= upto;
18209
    }
18210
    /**
18211
    Get the context for the current parse, or `null` if no editor
18212
    parse is in progress.
18213
    */
18214
    static get() { return currentContext; }
18215
}
18216
function cutFragments(fragments, from, to) {
18217
    return TreeFragment.applyChanges(fragments, [{ fromA: from, toA: to, fromB: from, toB: to }]);
18218
}
18219
class LanguageState {
18220
    constructor(
18221
    // A mutable parse state that is used to preserve work done during
18222
    // the lifetime of a state when moving to the next state.
18223
    context) {
18224
        this.context = context;
18225
        this.tree = context.tree;
18226
    }
18227
    apply(tr) {
18228
        if (!tr.docChanged && this.tree == this.context.tree)
18229
            return this;
18230
        let newCx = this.context.changes(tr.changes, tr.state);
18231
        // If the previous parse wasn't done, go forward only up to its
18232
        // end position or the end of the viewport, to avoid slowing down
18233
        // state updates with parse work beyond the viewport.
18234
        let upto = this.context.treeLen == tr.startState.doc.length ? undefined
18235
            : Math.max(tr.changes.mapPos(this.context.treeLen), newCx.viewport.to);
18236
        if (!newCx.work(20 /* Work.Apply */, upto))
18237
            newCx.takeTree();
18238
        return new LanguageState(newCx);
18239
    }
18240
    static init(state) {
18241
        let vpTo = Math.min(3000 /* Work.InitViewport */, state.doc.length);
18242
        let parseState = ParseContext.create(state.facet(language).parser, state, { from: 0, to: vpTo });
18243
        if (!parseState.work(20 /* Work.Apply */, vpTo))
18244
            parseState.takeTree();
18245
        return new LanguageState(parseState);
18246
    }
18247
}
18248
Language.state = /*@__PURE__*/StateField.define({
18249
    create: LanguageState.init,
18250
    update(value, tr) {
18251
        for (let e of tr.effects)
18252
            if (e.is(Language.setState))
18253
                return e.value;
18254
        if (tr.startState.facet(language) != tr.state.facet(language))
18255
            return LanguageState.init(tr.state);
18256
        return value.apply(tr);
18257
    }
18258
});
18259
let requestIdle = (callback) => {
18260
    let timeout = setTimeout(() => callback(), 500 /* Work.MaxPause */);
18261
    return () => clearTimeout(timeout);
18262
};
18263
if (typeof requestIdleCallback != "undefined")
18264
    requestIdle = (callback) => {
18265
        let idle = -1, timeout = setTimeout(() => {
18266
            idle = requestIdleCallback(callback, { timeout: 500 /* Work.MaxPause */ - 100 /* Work.MinPause */ });
18267
        }, 100 /* Work.MinPause */);
18268
        return () => idle < 0 ? clearTimeout(timeout) : cancelIdleCallback(idle);
18269
    };
18270
const isInputPending = typeof navigator != "undefined" && ((_a = navigator.scheduling) === null || _a === void 0 ? void 0 : _a.isInputPending)
18271
    ? () => navigator.scheduling.isInputPending() : null;
18272
const parseWorker = /*@__PURE__*/ViewPlugin.fromClass(class ParseWorker {
18273
    constructor(view) {
18274
        this.view = view;
18275
        this.working = null;
18276
        this.workScheduled = 0;
18277
        // End of the current time chunk
18278
        this.chunkEnd = -1;
18279
        // Milliseconds of budget left for this chunk
18280
        this.chunkBudget = -1;
18281
        this.work = this.work.bind(this);
18282
        this.scheduleWork();
18283
    }
18284
    update(update) {
18285
        let cx = this.view.state.field(Language.state).context;
18286
        if (cx.updateViewport(update.view.viewport) || this.view.viewport.to > cx.treeLen)
18287
            this.scheduleWork();
18288
        if (update.docChanged || update.selectionSet) {
18289
            if (this.view.hasFocus)
18290
                this.chunkBudget += 50 /* Work.ChangeBonus */;
18291
            this.scheduleWork();
18292
        }
18293
        this.checkAsyncSchedule(cx);
18294
    }
18295
    scheduleWork() {
18296
        if (this.working)
18297
            return;
18298
        let { state } = this.view, field = state.field(Language.state);
18299
        if (field.tree != field.context.tree || !field.context.isDone(state.doc.length))
18300
            this.working = requestIdle(this.work);
18301
    }
18302
    work(deadline) {
18303
        this.working = null;
18304
        let now = Date.now();
18305
        if (this.chunkEnd < now && (this.chunkEnd < 0 || this.view.hasFocus)) { // Start a new chunk
18306
            this.chunkEnd = now + 30000 /* Work.ChunkTime */;
18307
            this.chunkBudget = 3000 /* Work.ChunkBudget */;
18308
        }
18309
        if (this.chunkBudget <= 0)
18310
            return; // No more budget
18311
        let { state, viewport: { to: vpTo } } = this.view, field = state.field(Language.state);
18312
        if (field.tree == field.context.tree && field.context.isDone(vpTo + 100000 /* Work.MaxParseAhead */))
18313
            return;
18314
        let endTime = Date.now() + Math.min(this.chunkBudget, 100 /* Work.Slice */, deadline && !isInputPending ? Math.max(25 /* Work.MinSlice */, deadline.timeRemaining() - 5) : 1e9);
18315
        let viewportFirst = field.context.treeLen < vpTo && state.doc.length > vpTo + 1000;
18316
        let done = field.context.work(() => {
18317
            return isInputPending && isInputPending() || Date.now() > endTime;
18318
        }, vpTo + (viewportFirst ? 0 : 100000 /* Work.MaxParseAhead */));
18319
        this.chunkBudget -= Date.now() - now;
18320
        if (done || this.chunkBudget <= 0) {
18321
            field.context.takeTree();
18322
            this.view.dispatch({ effects: Language.setState.of(new LanguageState(field.context)) });
18323
        }
18324
        if (this.chunkBudget > 0 && !(done && !viewportFirst))
18325
            this.scheduleWork();
18326
        this.checkAsyncSchedule(field.context);
18327
    }
18328
    checkAsyncSchedule(cx) {
18329
        if (cx.scheduleOn) {
18330
            this.workScheduled++;
18331
            cx.scheduleOn
18332
                .then(() => this.scheduleWork())
18333
                .catch(err => logException(this.view.state, err))
18334
                .then(() => this.workScheduled--);
18335
            cx.scheduleOn = null;
18336
        }
18337
    }
18338
    destroy() {
18339
        if (this.working)
18340
            this.working();
18341
    }
18342
    isWorking() {
18343
        return !!(this.working || this.workScheduled > 0);
18344
    }
18345
}, {
18346
    eventHandlers: { focus() { this.scheduleWork(); } }
18347
});
18348
/**
18349
The facet used to associate a language with an editor state. Used
18350
by `Language` object's `extension` property (so you don't need to
18351
manually wrap your languages in this). Can be used to access the
18352
current language on a state.
18353
*/
18354
const language = /*@__PURE__*/Facet.define({
18355
    combine(languages) { return languages.length ? languages[0] : null; },
18356
    enables: language => [
18357
        Language.state,
18358
        parseWorker,
18359
        EditorView.contentAttributes.compute([language], state => {
18360
            let lang = state.facet(language);
18361
            return lang && lang.name ? { "data-language": lang.name } : {};
18362
        })
18363
    ]
18364
});
18365
/**
18366
This class bundles a [language](https://codemirror.net/6/docs/ref/#language.Language) with an
18367
optional set of supporting extensions. Language packages are
18368
encouraged to export a function that optionally takes a
18369
configuration object and returns a `LanguageSupport` instance, as
18370
the main way for client code to use the package.
18371
*/
18372
class LanguageSupport {
18373
    /**
18374
    Create a language support object.
18375
    */
18376
    constructor(
18377
    /**
18378
    The language object.
18379
    */
18380
    language,
18381
    /**
18382
    An optional set of supporting extensions. When nesting a
18383
    language in another language, the outer language is encouraged
18384
    to include the supporting extensions for its inner languages
18385
    in its own set of support extensions.
18386
    */
18387
    support = []) {
18388
        this.language = language;
18389
        this.support = support;
18390
        this.extension = [language, support];
18391
    }
18392
}
18393
 
18394
/**
18395
Facet that defines a way to provide a function that computes the
18396
appropriate indentation depth, as a column number (see
18397
[`indentString`](https://codemirror.net/6/docs/ref/#language.indentString)), at the start of a given
18398
line. A return value of `null` indicates no indentation can be
18399
determined, and the line should inherit the indentation of the one
18400
above it. A return value of `undefined` defers to the next indent
18401
service.
18402
*/
18403
const indentService = /*@__PURE__*/Facet.define();
18404
/**
18405
Facet for overriding the unit by which indentation happens. Should
18406
be a string consisting either entirely of the same whitespace
18407
character. When not set, this defaults to 2 spaces.
18408
*/
18409
const indentUnit = /*@__PURE__*/Facet.define({
18410
    combine: values => {
18411
        if (!values.length)
18412
            return "  ";
18413
        let unit = values[0];
18414
        if (!unit || /\S/.test(unit) || Array.from(unit).some(e => e != unit[0]))
18415
            throw new Error("Invalid indent unit: " + JSON.stringify(values[0]));
18416
        return unit;
18417
    }
18418
});
18419
/**
18420
Return the _column width_ of an indent unit in the state.
18421
Determined by the [`indentUnit`](https://codemirror.net/6/docs/ref/#language.indentUnit)
18422
facet, and [`tabSize`](https://codemirror.net/6/docs/ref/#state.EditorState^tabSize) when that
18423
contains tabs.
18424
*/
18425
function getIndentUnit(state) {
18426
    let unit = state.facet(indentUnit);
18427
    return unit.charCodeAt(0) == 9 ? state.tabSize * unit.length : unit.length;
18428
}
18429
/**
18430
Create an indentation string that covers columns 0 to `cols`.
18431
Will use tabs for as much of the columns as possible when the
18432
[`indentUnit`](https://codemirror.net/6/docs/ref/#language.indentUnit) facet contains
18433
tabs.
18434
*/
18435
function indentString(state, cols) {
18436
    let result = "", ts = state.tabSize, ch = state.facet(indentUnit)[0];
18437
    if (ch == "\t") {
18438
        while (cols >= ts) {
18439
            result += "\t";
18440
            cols -= ts;
18441
        }
18442
        ch = " ";
18443
    }
18444
    for (let i = 0; i < cols; i++)
18445
        result += ch;
18446
    return result;
18447
}
18448
/**
18449
Get the indentation, as a column number, at the given position.
18450
Will first consult any [indent services](https://codemirror.net/6/docs/ref/#language.indentService)
18451
that are registered, and if none of those return an indentation,
18452
this will check the syntax tree for the [indent node
18453
prop](https://codemirror.net/6/docs/ref/#language.indentNodeProp) and use that if found. Returns a
18454
number when an indentation could be determined, and null
18455
otherwise.
18456
*/
18457
function getIndentation(context, pos) {
18458
    if (context instanceof EditorState)
18459
        context = new IndentContext(context);
18460
    for (let service of context.state.facet(indentService)) {
18461
        let result = service(context, pos);
18462
        if (result !== undefined)
18463
            return result;
18464
    }
18465
    let tree = syntaxTree(context.state);
18466
    return tree.length >= pos ? syntaxIndentation(context, tree, pos) : null;
18467
}
18468
/**
18469
Indentation contexts are used when calling [indentation
18470
services](https://codemirror.net/6/docs/ref/#language.indentService). They provide helper utilities
18471
useful in indentation logic, and can selectively override the
18472
indentation reported for some lines.
18473
*/
18474
class IndentContext {
18475
    /**
18476
    Create an indent context.
18477
    */
18478
    constructor(
18479
    /**
18480
    The editor state.
18481
    */
18482
    state,
18483
    /**
18484
    @internal
18485
    */
18486
    options = {}) {
18487
        this.state = state;
18488
        this.options = options;
18489
        this.unit = getIndentUnit(state);
18490
    }
18491
    /**
18492
    Get a description of the line at the given position, taking
18493
    [simulated line
18494
    breaks](https://codemirror.net/6/docs/ref/#language.IndentContext.constructor^options.simulateBreak)
18495
    into account. If there is such a break at `pos`, the `bias`
18496
    argument determines whether the part of the line line before or
18497
    after the break is used.
18498
    */
18499
    lineAt(pos, bias = 1) {
18500
        let line = this.state.doc.lineAt(pos);
18501
        let { simulateBreak, simulateDoubleBreak } = this.options;
18502
        if (simulateBreak != null && simulateBreak >= line.from && simulateBreak <= line.to) {
18503
            if (simulateDoubleBreak && simulateBreak == pos)
18504
                return { text: "", from: pos };
18505
            else if (bias < 0 ? simulateBreak < pos : simulateBreak <= pos)
18506
                return { text: line.text.slice(simulateBreak - line.from), from: simulateBreak };
18507
            else
18508
                return { text: line.text.slice(0, simulateBreak - line.from), from: line.from };
18509
        }
18510
        return line;
18511
    }
18512
    /**
18513
    Get the text directly after `pos`, either the entire line
18514
    or the next 100 characters, whichever is shorter.
18515
    */
18516
    textAfterPos(pos, bias = 1) {
18517
        if (this.options.simulateDoubleBreak && pos == this.options.simulateBreak)
18518
            return "";
18519
        let { text, from } = this.lineAt(pos, bias);
18520
        return text.slice(pos - from, Math.min(text.length, pos + 100 - from));
18521
    }
18522
    /**
18523
    Find the column for the given position.
18524
    */
18525
    column(pos, bias = 1) {
18526
        let { text, from } = this.lineAt(pos, bias);
18527
        let result = this.countColumn(text, pos - from);
18528
        let override = this.options.overrideIndentation ? this.options.overrideIndentation(from) : -1;
18529
        if (override > -1)
18530
            result += override - this.countColumn(text, text.search(/\S|$/));
18531
        return result;
18532
    }
18533
    /**
18534
    Find the column position (taking tabs into account) of the given
18535
    position in the given string.
18536
    */
18537
    countColumn(line, pos = line.length) {
18538
        return countColumn(line, this.state.tabSize, pos);
18539
    }
18540
    /**
18541
    Find the indentation column of the line at the given point.
18542
    */
18543
    lineIndent(pos, bias = 1) {
18544
        let { text, from } = this.lineAt(pos, bias);
18545
        let override = this.options.overrideIndentation;
18546
        if (override) {
18547
            let overriden = override(from);
18548
            if (overriden > -1)
18549
                return overriden;
18550
        }
18551
        return this.countColumn(text, text.search(/\S|$/));
18552
    }
18553
    /**
18554
    Returns the [simulated line
18555
    break](https://codemirror.net/6/docs/ref/#language.IndentContext.constructor^options.simulateBreak)
18556
    for this context, if any.
18557
    */
18558
    get simulatedBreak() {
18559
        return this.options.simulateBreak || null;
18560
    }
18561
}
18562
/**
18563
A syntax tree node prop used to associate indentation strategies
18564
with node types. Such a strategy is a function from an indentation
18565
context to a column number (see also
18566
[`indentString`](https://codemirror.net/6/docs/ref/#language.indentString)) or null, where null
18567
indicates that no definitive indentation can be determined.
18568
*/
18569
const indentNodeProp = /*@__PURE__*/new NodeProp();
18570
// Compute the indentation for a given position from the syntax tree.
18571
function syntaxIndentation(cx, ast, pos) {
18572
    let stack = ast.resolveStack(pos);
18573
    let inner = stack.node.enterUnfinishedNodesBefore(pos);
18574
    if (inner != stack.node) {
18575
        let add = [];
18576
        for (let cur = inner; cur != stack.node; cur = cur.parent)
18577
            add.push(cur);
18578
        for (let i = add.length - 1; i >= 0; i--)
18579
            stack = { node: add[i], next: stack };
18580
    }
18581
    return indentFor(stack, cx, pos);
18582
}
18583
function indentFor(stack, cx, pos) {
18584
    for (let cur = stack; cur; cur = cur.next) {
18585
        let strategy = indentStrategy(cur.node);
18586
        if (strategy)
18587
            return strategy(TreeIndentContext.create(cx, pos, cur));
18588
    }
18589
    return 0;
18590
}
18591
function ignoreClosed(cx) {
18592
    return cx.pos == cx.options.simulateBreak && cx.options.simulateDoubleBreak;
18593
}
18594
function indentStrategy(tree) {
18595
    let strategy = tree.type.prop(indentNodeProp);
18596
    if (strategy)
18597
        return strategy;
18598
    let first = tree.firstChild, close;
18599
    if (first && (close = first.type.prop(NodeProp.closedBy))) {
18600
        let last = tree.lastChild, closed = last && close.indexOf(last.name) > -1;
18601
        return cx => delimitedStrategy(cx, true, 1, undefined, closed && !ignoreClosed(cx) ? last.from : undefined);
18602
    }
18603
    return tree.parent == null ? topIndent : null;
18604
}
18605
function topIndent() { return 0; }
18606
/**
18607
Objects of this type provide context information and helper
18608
methods to indentation functions registered on syntax nodes.
18609
*/
18610
class TreeIndentContext extends IndentContext {
18611
    constructor(base,
18612
    /**
18613
    The position at which indentation is being computed.
18614
    */
18615
    pos,
18616
    /**
18617
    @internal
18618
    */
18619
    context) {
18620
        super(base.state, base.options);
18621
        this.base = base;
18622
        this.pos = pos;
18623
        this.context = context;
18624
    }
18625
    /**
18626
    The syntax tree node to which the indentation strategy
18627
    applies.
18628
    */
18629
    get node() { return this.context.node; }
18630
    /**
18631
    @internal
18632
    */
18633
    static create(base, pos, context) {
18634
        return new TreeIndentContext(base, pos, context);
18635
    }
18636
    /**
18637
    Get the text directly after `this.pos`, either the entire line
18638
    or the next 100 characters, whichever is shorter.
18639
    */
18640
    get textAfter() {
18641
        return this.textAfterPos(this.pos);
18642
    }
18643
    /**
18644
    Get the indentation at the reference line for `this.node`, which
18645
    is the line on which it starts, unless there is a node that is
18646
    _not_ a parent of this node covering the start of that line. If
18647
    so, the line at the start of that node is tried, again skipping
18648
    on if it is covered by another such node.
18649
    */
18650
    get baseIndent() {
18651
        return this.baseIndentFor(this.node);
18652
    }
18653
    /**
18654
    Get the indentation for the reference line of the given node
18655
    (see [`baseIndent`](https://codemirror.net/6/docs/ref/#language.TreeIndentContext.baseIndent)).
18656
    */
18657
    baseIndentFor(node) {
18658
        let line = this.state.doc.lineAt(node.from);
18659
        // Skip line starts that are covered by a sibling (or cousin, etc)
18660
        for (;;) {
18661
            let atBreak = node.resolve(line.from);
18662
            while (atBreak.parent && atBreak.parent.from == atBreak.from)
18663
                atBreak = atBreak.parent;
18664
            if (isParent(atBreak, node))
18665
                break;
18666
            line = this.state.doc.lineAt(atBreak.from);
18667
        }
18668
        return this.lineIndent(line.from);
18669
    }
18670
    /**
18671
    Continue looking for indentations in the node's parent nodes,
18672
    and return the result of that.
18673
    */
18674
    continue() {
18675
        return indentFor(this.context.next, this.base, this.pos);
18676
    }
18677
}
18678
function isParent(parent, of) {
18679
    for (let cur = of; cur; cur = cur.parent)
18680
        if (parent == cur)
18681
            return true;
18682
    return false;
18683
}
18684
// Check whether a delimited node is aligned (meaning there are
18685
// non-skipped nodes on the same line as the opening delimiter). And
18686
// if so, return the opening token.
18687
function bracketedAligned(context) {
18688
    let tree = context.node;
18689
    let openToken = tree.childAfter(tree.from), last = tree.lastChild;
18690
    if (!openToken)
18691
        return null;
18692
    let sim = context.options.simulateBreak;
18693
    let openLine = context.state.doc.lineAt(openToken.from);
18694
    let lineEnd = sim == null || sim <= openLine.from ? openLine.to : Math.min(openLine.to, sim);
18695
    for (let pos = openToken.to;;) {
18696
        let next = tree.childAfter(pos);
18697
        if (!next || next == last)
18698
            return null;
18699
        if (!next.type.isSkipped)
18700
            return next.from < lineEnd ? openToken : null;
18701
        pos = next.to;
18702
    }
18703
}
18704
/**
18705
An indentation strategy for delimited (usually bracketed) nodes.
18706
Will, by default, indent one unit more than the parent's base
18707
indent unless the line starts with a closing token. When `align`
18708
is true and there are non-skipped nodes on the node's opening
18709
line, the content of the node will be aligned with the end of the
18710
opening node, like this:
18711
 
18712
    foo(bar,
18713
        baz)
18714
*/
18715
function delimitedIndent({ closing, align = true, units = 1 }) {
18716
    return (context) => delimitedStrategy(context, align, units, closing);
18717
}
18718
function delimitedStrategy(context, align, units, closing, closedAt) {
18719
    let after = context.textAfter, space = after.match(/^\s*/)[0].length;
18720
    let closed = closing && after.slice(space, space + closing.length) == closing || closedAt == context.pos + space;
18721
    let aligned = align ? bracketedAligned(context) : null;
18722
    if (aligned)
18723
        return closed ? context.column(aligned.from) : context.column(aligned.to);
18724
    return context.baseIndent + (closed ? 0 : context.unit * units);
18725
}
18726
/**
18727
An indentation strategy that aligns a node's content to its base
18728
indentation.
18729
*/
18730
const flatIndent = (context) => context.baseIndent;
18731
/**
18732
Creates an indentation strategy that, by default, indents
18733
continued lines one unit more than the node's base indentation.
18734
You can provide `except` to prevent indentation of lines that
18735
match a pattern (for example `/^else\b/` in `if`/`else`
18736
constructs), and you can change the amount of units used with the
18737
`units` option.
18738
*/
18739
function continuedIndent({ except, units = 1 } = {}) {
18740
    return (context) => {
18741
        let matchExcept = except && except.test(context.textAfter);
18742
        return context.baseIndent + (matchExcept ? 0 : units * context.unit);
18743
    };
18744
}
18745
const DontIndentBeyond = 200;
18746
/**
18747
Enables reindentation on input. When a language defines an
18748
`indentOnInput` field in its [language
18749
data](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt), which must hold a regular
18750
expression, the line at the cursor will be reindented whenever new
18751
text is typed and the input from the start of the line up to the
18752
cursor matches that regexp.
18753
 
18754
To avoid unneccesary reindents, it is recommended to start the
18755
regexp with `^` (usually followed by `\s*`), and end it with `$`.
18756
For example, `/^\s*\}$/` will reindent when a closing brace is
18757
added at the start of a line.
18758
*/
18759
function indentOnInput() {
18760
    return EditorState.transactionFilter.of(tr => {
18761
        if (!tr.docChanged || !tr.isUserEvent("input.type") && !tr.isUserEvent("input.complete"))
18762
            return tr;
18763
        let rules = tr.startState.languageDataAt("indentOnInput", tr.startState.selection.main.head);
18764
        if (!rules.length)
18765
            return tr;
18766
        let doc = tr.newDoc, { head } = tr.newSelection.main, line = doc.lineAt(head);
18767
        if (head > line.from + DontIndentBeyond)
18768
            return tr;
18769
        let lineStart = doc.sliceString(line.from, head);
18770
        if (!rules.some(r => r.test(lineStart)))
18771
            return tr;
18772
        let { state } = tr, last = -1, changes = [];
18773
        for (let { head } of state.selection.ranges) {
18774
            let line = state.doc.lineAt(head);
18775
            if (line.from == last)
18776
                continue;
18777
            last = line.from;
18778
            let indent = getIndentation(state, line.from);
18779
            if (indent == null)
18780
                continue;
18781
            let cur = /^\s*/.exec(line.text)[0];
18782
            let norm = indentString(state, indent);
18783
            if (cur != norm)
18784
                changes.push({ from: line.from, to: line.from + cur.length, insert: norm });
18785
        }
18786
        return changes.length ? [tr, { changes, sequential: true }] : tr;
18787
    });
18788
}
18789
 
18790
/**
18791
A facet that registers a code folding service. When called with
18792
the extent of a line, such a function should return a foldable
18793
range that starts on that line (but continues beyond it), if one
18794
can be found.
18795
*/
18796
const foldService = /*@__PURE__*/Facet.define();
18797
/**
18798
This node prop is used to associate folding information with
18799
syntax node types. Given a syntax node, it should check whether
18800
that tree is foldable and return the range that can be collapsed
18801
when it is.
18802
*/
18803
const foldNodeProp = /*@__PURE__*/new NodeProp();
18804
/**
18805
[Fold](https://codemirror.net/6/docs/ref/#language.foldNodeProp) function that folds everything but
18806
the first and the last child of a syntax node. Useful for nodes
18807
that start and end with delimiters.
18808
*/
18809
function foldInside(node) {
18810
    let first = node.firstChild, last = node.lastChild;
18811
    return first && first.to < last.from ? { from: first.to, to: last.type.isError ? node.to : last.from } : null;
18812
}
18813
function syntaxFolding(state, start, end) {
18814
    let tree = syntaxTree(state);
18815
    if (tree.length < end)
18816
        return null;
18817
    let stack = tree.resolveStack(end, 1);
18818
    let found = null;
18819
    for (let iter = stack; iter; iter = iter.next) {
18820
        let cur = iter.node;
18821
        if (cur.to <= end || cur.from > end)
18822
            continue;
18823
        if (found && cur.from < start)
18824
            break;
18825
        let prop = cur.type.prop(foldNodeProp);
18826
        if (prop && (cur.to < tree.length - 50 || tree.length == state.doc.length || !isUnfinished(cur))) {
18827
            let value = prop(cur, state);
18828
            if (value && value.from <= end && value.from >= start && value.to > end)
18829
                found = value;
18830
        }
18831
    }
18832
    return found;
18833
}
18834
function isUnfinished(node) {
18835
    let ch = node.lastChild;
18836
    return ch && ch.to == node.to && ch.type.isError;
18837
}
18838
/**
18839
Check whether the given line is foldable. First asks any fold
18840
services registered through
18841
[`foldService`](https://codemirror.net/6/docs/ref/#language.foldService), and if none of them return
18842
a result, tries to query the [fold node
18843
prop](https://codemirror.net/6/docs/ref/#language.foldNodeProp) of syntax nodes that cover the end
18844
of the line.
18845
*/
18846
function foldable(state, lineStart, lineEnd) {
18847
    for (let service of state.facet(foldService)) {
18848
        let result = service(state, lineStart, lineEnd);
18849
        if (result)
18850
            return result;
18851
    }
18852
    return syntaxFolding(state, lineStart, lineEnd);
18853
}
18854
function mapRange(range, mapping) {
18855
    let from = mapping.mapPos(range.from, 1), to = mapping.mapPos(range.to, -1);
18856
    return from >= to ? undefined : { from, to };
18857
}
18858
/**
18859
State effect that can be attached to a transaction to fold the
18860
given range. (You probably only need this in exceptional
18861
circumstances—usually you'll just want to let
18862
[`foldCode`](https://codemirror.net/6/docs/ref/#language.foldCode) and the [fold
18863
gutter](https://codemirror.net/6/docs/ref/#language.foldGutter) create the transactions.)
18864
*/
18865
const foldEffect = /*@__PURE__*/StateEffect.define({ map: mapRange });
18866
/**
18867
State effect that unfolds the given range (if it was folded).
18868
*/
18869
const unfoldEffect = /*@__PURE__*/StateEffect.define({ map: mapRange });
18870
function selectedLines(view) {
18871
    let lines = [];
18872
    for (let { head } of view.state.selection.ranges) {
18873
        if (lines.some(l => l.from <= head && l.to >= head))
18874
            continue;
18875
        lines.push(view.lineBlockAt(head));
18876
    }
18877
    return lines;
18878
}
18879
/**
18880
The state field that stores the folded ranges (as a [decoration
18881
set](https://codemirror.net/6/docs/ref/#view.DecorationSet)). Can be passed to
18882
[`EditorState.toJSON`](https://codemirror.net/6/docs/ref/#state.EditorState.toJSON) and
18883
[`fromJSON`](https://codemirror.net/6/docs/ref/#state.EditorState^fromJSON) to serialize the fold
18884
state.
18885
*/
18886
const foldState = /*@__PURE__*/StateField.define({
18887
    create() {
18888
        return Decoration.none;
18889
    },
18890
    update(folded, tr) {
18891
        folded = folded.map(tr.changes);
18892
        for (let e of tr.effects) {
18893
            if (e.is(foldEffect) && !foldExists(folded, e.value.from, e.value.to)) {
18894
                let { preparePlaceholder } = tr.state.facet(foldConfig);
18895
                let widget = !preparePlaceholder ? foldWidget :
18896
                    Decoration.replace({ widget: new PreparedFoldWidget(preparePlaceholder(tr.state, e.value)) });
18897
                folded = folded.update({ add: [widget.range(e.value.from, e.value.to)] });
18898
            }
18899
            else if (e.is(unfoldEffect)) {
18900
                folded = folded.update({ filter: (from, to) => e.value.from != from || e.value.to != to,
18901
                    filterFrom: e.value.from, filterTo: e.value.to });
18902
            }
18903
        }
18904
        // Clear folded ranges that cover the selection head
18905
        if (tr.selection) {
18906
            let onSelection = false, { head } = tr.selection.main;
18907
            folded.between(head, head, (a, b) => { if (a < head && b > head)
18908
                onSelection = true; });
18909
            if (onSelection)
18910
                folded = folded.update({
18911
                    filterFrom: head,
18912
                    filterTo: head,
18913
                    filter: (a, b) => b <= head || a >= head
18914
                });
18915
        }
18916
        return folded;
18917
    },
18918
    provide: f => EditorView.decorations.from(f),
18919
    toJSON(folded, state) {
18920
        let ranges = [];
18921
        folded.between(0, state.doc.length, (from, to) => { ranges.push(from, to); });
18922
        return ranges;
18923
    },
18924
    fromJSON(value) {
18925
        if (!Array.isArray(value) || value.length % 2)
18926
            throw new RangeError("Invalid JSON for fold state");
18927
        let ranges = [];
18928
        for (let i = 0; i < value.length;) {
18929
            let from = value[i++], to = value[i++];
18930
            if (typeof from != "number" || typeof to != "number")
18931
                throw new RangeError("Invalid JSON for fold state");
18932
            ranges.push(foldWidget.range(from, to));
18933
        }
18934
        return Decoration.set(ranges, true);
18935
    }
18936
});
18937
function findFold(state, from, to) {
18938
    var _a;
18939
    let found = null;
18940
    (_a = state.field(foldState, false)) === null || _a === void 0 ? void 0 : _a.between(from, to, (from, to) => {
18941
        if (!found || found.from > from)
18942
            found = { from, to };
18943
    });
18944
    return found;
18945
}
18946
function foldExists(folded, from, to) {
18947
    let found = false;
18948
    folded.between(from, from, (a, b) => { if (a == from && b == to)
18949
        found = true; });
18950
    return found;
18951
}
18952
function maybeEnable(state, other) {
18953
    return state.field(foldState, false) ? other : other.concat(StateEffect.appendConfig.of(codeFolding()));
18954
}
18955
/**
18956
Fold the lines that are selected, if possible.
18957
*/
18958
const foldCode = view => {
18959
    for (let line of selectedLines(view)) {
18960
        let range = foldable(view.state, line.from, line.to);
18961
        if (range) {
18962
            view.dispatch({ effects: maybeEnable(view.state, [foldEffect.of(range), announceFold(view, range)]) });
18963
            return true;
18964
        }
18965
    }
18966
    return false;
18967
};
18968
/**
18969
Unfold folded ranges on selected lines.
18970
*/
18971
const unfoldCode = view => {
18972
    if (!view.state.field(foldState, false))
18973
        return false;
18974
    let effects = [];
18975
    for (let line of selectedLines(view)) {
18976
        let folded = findFold(view.state, line.from, line.to);
18977
        if (folded)
18978
            effects.push(unfoldEffect.of(folded), announceFold(view, folded, false));
18979
    }
18980
    if (effects.length)
18981
        view.dispatch({ effects });
18982
    return effects.length > 0;
18983
};
18984
function announceFold(view, range, fold = true) {
18985
    let lineFrom = view.state.doc.lineAt(range.from).number, lineTo = view.state.doc.lineAt(range.to).number;
18986
    return EditorView.announce.of(`${view.state.phrase(fold ? "Folded lines" : "Unfolded lines")} ${lineFrom} ${view.state.phrase("to")} ${lineTo}.`);
18987
}
18988
/**
18989
Fold all top-level foldable ranges. Note that, in most cases,
18990
folding information will depend on the [syntax
18991
tree](https://codemirror.net/6/docs/ref/#language.syntaxTree), and folding everything may not work
18992
reliably when the document hasn't been fully parsed (either
18993
because the editor state was only just initialized, or because the
18994
document is so big that the parser decided not to parse it
18995
entirely).
18996
*/
18997
const foldAll = view => {
18998
    let { state } = view, effects = [];
18999
    for (let pos = 0; pos < state.doc.length;) {
19000
        let line = view.lineBlockAt(pos), range = foldable(state, line.from, line.to);
19001
        if (range)
19002
            effects.push(foldEffect.of(range));
19003
        pos = (range ? view.lineBlockAt(range.to) : line).to + 1;
19004
    }
19005
    if (effects.length)
19006
        view.dispatch({ effects: maybeEnable(view.state, effects) });
19007
    return !!effects.length;
19008
};
19009
/**
19010
Unfold all folded code.
19011
*/
19012
const unfoldAll = view => {
19013
    let field = view.state.field(foldState, false);
19014
    if (!field || !field.size)
19015
        return false;
19016
    let effects = [];
19017
    field.between(0, view.state.doc.length, (from, to) => { effects.push(unfoldEffect.of({ from, to })); });
19018
    view.dispatch({ effects });
19019
    return true;
19020
};
19021
/**
19022
Default fold-related key bindings.
19023
 
19024
 - Ctrl-Shift-[ (Cmd-Alt-[ on macOS): [`foldCode`](https://codemirror.net/6/docs/ref/#language.foldCode).
19025
 - Ctrl-Shift-] (Cmd-Alt-] on macOS): [`unfoldCode`](https://codemirror.net/6/docs/ref/#language.unfoldCode).
19026
 - Ctrl-Alt-[: [`foldAll`](https://codemirror.net/6/docs/ref/#language.foldAll).
19027
 - Ctrl-Alt-]: [`unfoldAll`](https://codemirror.net/6/docs/ref/#language.unfoldAll).
19028
*/
19029
const foldKeymap = [
19030
    { key: "Ctrl-Shift-[", mac: "Cmd-Alt-[", run: foldCode },
19031
    { key: "Ctrl-Shift-]", mac: "Cmd-Alt-]", run: unfoldCode },
19032
    { key: "Ctrl-Alt-[", run: foldAll },
19033
    { key: "Ctrl-Alt-]", run: unfoldAll }
19034
];
19035
const defaultConfig = {
19036
    placeholderDOM: null,
19037
    preparePlaceholder: null,
19038
    placeholderText: "…"
19039
};
19040
const foldConfig = /*@__PURE__*/Facet.define({
19041
    combine(values) { return combineConfig(values, defaultConfig); }
19042
});
19043
/**
19044
Create an extension that configures code folding.
19045
*/
19046
function codeFolding(config) {
19047
    let result = [foldState, baseTheme$1$2];
19048
    if (config)
19049
        result.push(foldConfig.of(config));
19050
    return result;
19051
}
19052
function widgetToDOM(view, prepared) {
19053
    let { state } = view, conf = state.facet(foldConfig);
19054
    let onclick = (event) => {
19055
        let line = view.lineBlockAt(view.posAtDOM(event.target));
19056
        let folded = findFold(view.state, line.from, line.to);
19057
        if (folded)
19058
            view.dispatch({ effects: unfoldEffect.of(folded) });
19059
        event.preventDefault();
19060
    };
19061
    if (conf.placeholderDOM)
19062
        return conf.placeholderDOM(view, onclick, prepared);
19063
    let element = document.createElement("span");
19064
    element.textContent = conf.placeholderText;
19065
    element.setAttribute("aria-label", state.phrase("folded code"));
19066
    element.title = state.phrase("unfold");
19067
    element.className = "cm-foldPlaceholder";
19068
    element.onclick = onclick;
19069
    return element;
19070
}
19071
const foldWidget = /*@__PURE__*/Decoration.replace({ widget: /*@__PURE__*/new class extends WidgetType {
19072
        toDOM(view) { return widgetToDOM(view, null); }
19073
    } });
19074
class PreparedFoldWidget extends WidgetType {
19075
    constructor(value) {
19076
        super();
19077
        this.value = value;
19078
    }
19079
    eq(other) { return this.value == other.value; }
19080
    toDOM(view) { return widgetToDOM(view, this.value); }
19081
}
19082
const foldGutterDefaults = {
19083
    openText: "⌄",
19084
    closedText: "›",
19085
    markerDOM: null,
19086
    domEventHandlers: {},
19087
    foldingChanged: () => false
19088
};
19089
class FoldMarker extends GutterMarker {
19090
    constructor(config, open) {
19091
        super();
19092
        this.config = config;
19093
        this.open = open;
19094
    }
19095
    eq(other) { return this.config == other.config && this.open == other.open; }
19096
    toDOM(view) {
19097
        if (this.config.markerDOM)
19098
            return this.config.markerDOM(this.open);
19099
        let span = document.createElement("span");
19100
        span.textContent = this.open ? this.config.openText : this.config.closedText;
19101
        span.title = view.state.phrase(this.open ? "Fold line" : "Unfold line");
19102
        return span;
19103
    }
19104
}
19105
/**
19106
Create an extension that registers a fold gutter, which shows a
19107
fold status indicator before foldable lines (which can be clicked
19108
to fold or unfold the line).
19109
*/
19110
function foldGutter(config = {}) {
19111
    let fullConfig = Object.assign(Object.assign({}, foldGutterDefaults), config);
19112
    let canFold = new FoldMarker(fullConfig, true), canUnfold = new FoldMarker(fullConfig, false);
19113
    let markers = ViewPlugin.fromClass(class {
19114
        constructor(view) {
19115
            this.from = view.viewport.from;
19116
            this.markers = this.buildMarkers(view);
19117
        }
19118
        update(update) {
19119
            if (update.docChanged || update.viewportChanged ||
19120
                update.startState.facet(language) != update.state.facet(language) ||
19121
                update.startState.field(foldState, false) != update.state.field(foldState, false) ||
19122
                syntaxTree(update.startState) != syntaxTree(update.state) ||
19123
                fullConfig.foldingChanged(update))
19124
                this.markers = this.buildMarkers(update.view);
19125
        }
19126
        buildMarkers(view) {
19127
            let builder = new RangeSetBuilder();
19128
            for (let line of view.viewportLineBlocks) {
19129
                let mark = findFold(view.state, line.from, line.to) ? canUnfold
19130
                    : foldable(view.state, line.from, line.to) ? canFold : null;
19131
                if (mark)
19132
                    builder.add(line.from, line.from, mark);
19133
            }
19134
            return builder.finish();
19135
        }
19136
    });
19137
    let { domEventHandlers } = fullConfig;
19138
    return [
19139
        markers,
19140
        gutter({
19141
            class: "cm-foldGutter",
19142
            markers(view) { var _a; return ((_a = view.plugin(markers)) === null || _a === void 0 ? void 0 : _a.markers) || RangeSet.empty; },
19143
            initialSpacer() {
19144
                return new FoldMarker(fullConfig, false);
19145
            },
19146
            domEventHandlers: Object.assign(Object.assign({}, domEventHandlers), { click: (view, line, event) => {
19147
                    if (domEventHandlers.click && domEventHandlers.click(view, line, event))
19148
                        return true;
19149
                    let folded = findFold(view.state, line.from, line.to);
19150
                    if (folded) {
19151
                        view.dispatch({ effects: unfoldEffect.of(folded) });
19152
                        return true;
19153
                    }
19154
                    let range = foldable(view.state, line.from, line.to);
19155
                    if (range) {
19156
                        view.dispatch({ effects: foldEffect.of(range) });
19157
                        return true;
19158
                    }
19159
                    return false;
19160
                } })
19161
        }),
19162
        codeFolding()
19163
    ];
19164
}
19165
const baseTheme$1$2 = /*@__PURE__*/EditorView.baseTheme({
19166
    ".cm-foldPlaceholder": {
19167
        backgroundColor: "#eee",
19168
        border: "1px solid #ddd",
19169
        color: "#888",
19170
        borderRadius: ".2em",
19171
        margin: "0 1px",
19172
        padding: "0 1px",
19173
        cursor: "pointer"
19174
    },
19175
    ".cm-foldGutter span": {
19176
        padding: "0 1px",
19177
        cursor: "pointer"
19178
    }
19179
});
19180
 
19181
/**
19182
A highlight style associates CSS styles with higlighting
19183
[tags](https://lezer.codemirror.net/docs/ref#highlight.Tag).
19184
*/
19185
class HighlightStyle {
19186
    constructor(
19187
    /**
19188
    The tag styles used to create this highlight style.
19189
    */
19190
    specs, options) {
19191
        this.specs = specs;
19192
        let modSpec;
19193
        function def(spec) {
19194
            let cls = StyleModule.newName();
19195
            (modSpec || (modSpec = Object.create(null)))["." + cls] = spec;
19196
            return cls;
19197
        }
19198
        const all = typeof options.all == "string" ? options.all : options.all ? def(options.all) : undefined;
19199
        const scopeOpt = options.scope;
19200
        this.scope = scopeOpt instanceof Language ? (type) => type.prop(languageDataProp) == scopeOpt.data
19201
            : scopeOpt ? (type) => type == scopeOpt : undefined;
19202
        this.style = tagHighlighter(specs.map(style => ({
19203
            tag: style.tag,
19204
            class: style.class || def(Object.assign({}, style, { tag: null }))
19205
        })), {
19206
            all,
19207
        }).style;
19208
        this.module = modSpec ? new StyleModule(modSpec) : null;
19209
        this.themeType = options.themeType;
19210
    }
19211
    /**
19212
    Create a highlighter style that associates the given styles to
19213
    the given tags. The specs must be objects that hold a style tag
19214
    or array of tags in their `tag` property, and either a single
19215
    `class` property providing a static CSS class (for highlighter
19216
    that rely on external styling), or a
19217
    [`style-mod`](https://github.com/marijnh/style-mod#documentation)-style
19218
    set of CSS properties (which define the styling for those tags).
19219
 
19220
    The CSS rules created for a highlighter will be emitted in the
19221
    order of the spec's properties. That means that for elements that
19222
    have multiple tags associated with them, styles defined further
19223
    down in the list will have a higher CSS precedence than styles
19224
    defined earlier.
19225
    */
19226
    static define(specs, options) {
19227
        return new HighlightStyle(specs, options || {});
19228
    }
19229
}
19230
const highlighterFacet = /*@__PURE__*/Facet.define();
19231
const fallbackHighlighter = /*@__PURE__*/Facet.define({
19232
    combine(values) { return values.length ? [values[0]] : null; }
19233
});
19234
function getHighlighters(state) {
19235
    let main = state.facet(highlighterFacet);
19236
    return main.length ? main : state.facet(fallbackHighlighter);
19237
}
19238
/**
19239
Wrap a highlighter in an editor extension that uses it to apply
19240
syntax highlighting to the editor content.
19241
 
19242
When multiple (non-fallback) styles are provided, the styling
19243
applied is the union of the classes they emit.
19244
*/
19245
function syntaxHighlighting(highlighter, options) {
19246
    let ext = [treeHighlighter], themeType;
19247
    if (highlighter instanceof HighlightStyle) {
19248
        if (highlighter.module)
19249
            ext.push(EditorView.styleModule.of(highlighter.module));
19250
        themeType = highlighter.themeType;
19251
    }
19252
    if (options === null || options === void 0 ? void 0 : options.fallback)
19253
        ext.push(fallbackHighlighter.of(highlighter));
19254
    else if (themeType)
19255
        ext.push(highlighterFacet.computeN([EditorView.darkTheme], state => {
19256
            return state.facet(EditorView.darkTheme) == (themeType == "dark") ? [highlighter] : [];
19257
        }));
19258
    else
19259
        ext.push(highlighterFacet.of(highlighter));
19260
    return ext;
19261
}
19262
class TreeHighlighter {
19263
    constructor(view) {
19264
        this.markCache = Object.create(null);
19265
        this.tree = syntaxTree(view.state);
19266
        this.decorations = this.buildDeco(view, getHighlighters(view.state));
19267
        this.decoratedTo = view.viewport.to;
19268
    }
19269
    update(update) {
19270
        let tree = syntaxTree(update.state), highlighters = getHighlighters(update.state);
19271
        let styleChange = highlighters != getHighlighters(update.startState);
19272
        let { viewport } = update.view, decoratedToMapped = update.changes.mapPos(this.decoratedTo, 1);
19273
        if (tree.length < viewport.to && !styleChange && tree.type == this.tree.type && decoratedToMapped >= viewport.to) {
19274
            this.decorations = this.decorations.map(update.changes);
19275
            this.decoratedTo = decoratedToMapped;
19276
        }
19277
        else if (tree != this.tree || update.viewportChanged || styleChange) {
19278
            this.tree = tree;
19279
            this.decorations = this.buildDeco(update.view, highlighters);
19280
            this.decoratedTo = viewport.to;
19281
        }
19282
    }
19283
    buildDeco(view, highlighters) {
19284
        if (!highlighters || !this.tree.length)
19285
            return Decoration.none;
19286
        let builder = new RangeSetBuilder();
19287
        for (let { from, to } of view.visibleRanges) {
19288
            highlightTree(this.tree, highlighters, (from, to, style) => {
19289
                builder.add(from, to, this.markCache[style] || (this.markCache[style] = Decoration.mark({ class: style })));
19290
            }, from, to);
19291
        }
19292
        return builder.finish();
19293
    }
19294
}
19295
const treeHighlighter = /*@__PURE__*/Prec.high(/*@__PURE__*/ViewPlugin.fromClass(TreeHighlighter, {
19296
    decorations: v => v.decorations
19297
}));
19298
/**
19299
A default highlight style (works well with light themes).
19300
*/
19301
const defaultHighlightStyle = /*@__PURE__*/HighlightStyle.define([
19302
    { tag: tags$1.meta,
19303
        color: "#404740" },
19304
    { tag: tags$1.link,
19305
        textDecoration: "underline" },
19306
    { tag: tags$1.heading,
19307
        textDecoration: "underline",
19308
        fontWeight: "bold" },
19309
    { tag: tags$1.emphasis,
19310
        fontStyle: "italic" },
19311
    { tag: tags$1.strong,
19312
        fontWeight: "bold" },
19313
    { tag: tags$1.strikethrough,
19314
        textDecoration: "line-through" },
19315
    { tag: tags$1.keyword,
19316
        color: "#708" },
19317
    { tag: [tags$1.atom, tags$1.bool, tags$1.url, tags$1.contentSeparator, tags$1.labelName],
19318
        color: "#219" },
19319
    { tag: [tags$1.literal, tags$1.inserted],
19320
        color: "#164" },
19321
    { tag: [tags$1.string, tags$1.deleted],
19322
        color: "#a11" },
19323
    { tag: [tags$1.regexp, tags$1.escape, /*@__PURE__*/tags$1.special(tags$1.string)],
19324
        color: "#e40" },
19325
    { tag: /*@__PURE__*/tags$1.definition(tags$1.variableName),
19326
        color: "#00f" },
19327
    { tag: /*@__PURE__*/tags$1.local(tags$1.variableName),
19328
        color: "#30a" },
19329
    { tag: [tags$1.typeName, tags$1.namespace],
19330
        color: "#085" },
19331
    { tag: tags$1.className,
19332
        color: "#167" },
19333
    { tag: [/*@__PURE__*/tags$1.special(tags$1.variableName), tags$1.macroName],
19334
        color: "#256" },
19335
    { tag: /*@__PURE__*/tags$1.definition(tags$1.propertyName),
19336
        color: "#00c" },
19337
    { tag: tags$1.comment,
19338
        color: "#940" },
19339
    { tag: tags$1.invalid,
19340
        color: "#f00" }
19341
]);
19342
 
19343
const baseTheme$3 = /*@__PURE__*/EditorView.baseTheme({
19344
    "&.cm-focused .cm-matchingBracket": { backgroundColor: "#328c8252" },
19345
    "&.cm-focused .cm-nonmatchingBracket": { backgroundColor: "#bb555544" }
19346
});
19347
const DefaultScanDist = 10000, DefaultBrackets = "()[]{}";
19348
const bracketMatchingConfig = /*@__PURE__*/Facet.define({
19349
    combine(configs) {
19350
        return combineConfig(configs, {
19351
            afterCursor: true,
19352
            brackets: DefaultBrackets,
19353
            maxScanDistance: DefaultScanDist,
19354
            renderMatch: defaultRenderMatch
19355
        });
19356
    }
19357
});
19358
const matchingMark = /*@__PURE__*/Decoration.mark({ class: "cm-matchingBracket" }), nonmatchingMark = /*@__PURE__*/Decoration.mark({ class: "cm-nonmatchingBracket" });
19359
function defaultRenderMatch(match) {
19360
    let decorations = [];
19361
    let mark = match.matched ? matchingMark : nonmatchingMark;
19362
    decorations.push(mark.range(match.start.from, match.start.to));
19363
    if (match.end)
19364
        decorations.push(mark.range(match.end.from, match.end.to));
19365
    return decorations;
19366
}
19367
const bracketMatchingState = /*@__PURE__*/StateField.define({
19368
    create() { return Decoration.none; },
19369
    update(deco, tr) {
19370
        if (!tr.docChanged && !tr.selection)
19371
            return deco;
19372
        let decorations = [];
19373
        let config = tr.state.facet(bracketMatchingConfig);
19374
        for (let range of tr.state.selection.ranges) {
19375
            if (!range.empty)
19376
                continue;
19377
            let match = matchBrackets(tr.state, range.head, -1, config)
19378
                || (range.head > 0 && matchBrackets(tr.state, range.head - 1, 1, config))
19379
                || (config.afterCursor &&
19380
                    (matchBrackets(tr.state, range.head, 1, config) ||
19381
                        (range.head < tr.state.doc.length && matchBrackets(tr.state, range.head + 1, -1, config))));
19382
            if (match)
19383
                decorations = decorations.concat(config.renderMatch(match, tr.state));
19384
        }
19385
        return Decoration.set(decorations, true);
19386
    },
19387
    provide: f => EditorView.decorations.from(f)
19388
});
19389
const bracketMatchingUnique = [
19390
    bracketMatchingState,
19391
    baseTheme$3
19392
];
19393
/**
19394
Create an extension that enables bracket matching. Whenever the
19395
cursor is next to a bracket, that bracket and the one it matches
19396
are highlighted. Or, when no matching bracket is found, another
19397
highlighting style is used to indicate this.
19398
*/
19399
function bracketMatching(config = {}) {
19400
    return [bracketMatchingConfig.of(config), bracketMatchingUnique];
19401
}
19402
/**
19403
When larger syntax nodes, such as HTML tags, are marked as
19404
opening/closing, it can be a bit messy to treat the whole node as
19405
a matchable bracket. This node prop allows you to define, for such
19406
a node, a ‘handle’—the part of the node that is highlighted, and
19407
that the cursor must be on to activate highlighting in the first
19408
place.
19409
*/
19410
const bracketMatchingHandle = /*@__PURE__*/new NodeProp();
19411
function matchingNodes(node, dir, brackets) {
19412
    let byProp = node.prop(dir < 0 ? NodeProp.openedBy : NodeProp.closedBy);
19413
    if (byProp)
19414
        return byProp;
19415
    if (node.name.length == 1) {
19416
        let index = brackets.indexOf(node.name);
19417
        if (index > -1 && index % 2 == (dir < 0 ? 1 : 0))
19418
            return [brackets[index + dir]];
19419
    }
19420
    return null;
19421
}
19422
function findHandle(node) {
19423
    let hasHandle = node.type.prop(bracketMatchingHandle);
19424
    return hasHandle ? hasHandle(node.node) : node;
19425
}
19426
/**
19427
Find the matching bracket for the token at `pos`, scanning
19428
direction `dir`. Only the `brackets` and `maxScanDistance`
19429
properties are used from `config`, if given. Returns null if no
19430
bracket was found at `pos`, or a match result otherwise.
19431
*/
19432
function matchBrackets(state, pos, dir, config = {}) {
19433
    let maxScanDistance = config.maxScanDistance || DefaultScanDist, brackets = config.brackets || DefaultBrackets;
19434
    let tree = syntaxTree(state), node = tree.resolveInner(pos, dir);
19435
    for (let cur = node; cur; cur = cur.parent) {
19436
        let matches = matchingNodes(cur.type, dir, brackets);
19437
        if (matches && cur.from < cur.to) {
19438
            let handle = findHandle(cur);
19439
            if (handle && (dir > 0 ? pos >= handle.from && pos < handle.to : pos > handle.from && pos <= handle.to))
19440
                return matchMarkedBrackets(state, pos, dir, cur, handle, matches, brackets);
19441
        }
19442
    }
19443
    return matchPlainBrackets(state, pos, dir, tree, node.type, maxScanDistance, brackets);
19444
}
19445
function matchMarkedBrackets(_state, _pos, dir, token, handle, matching, brackets) {
19446
    let parent = token.parent, firstToken = { from: handle.from, to: handle.to };
19447
    let depth = 0, cursor = parent === null || parent === void 0 ? void 0 : parent.cursor();
19448
    if (cursor && (dir < 0 ? cursor.childBefore(token.from) : cursor.childAfter(token.to)))
19449
        do {
19450
            if (dir < 0 ? cursor.to <= token.from : cursor.from >= token.to) {
19451
                if (depth == 0 && matching.indexOf(cursor.type.name) > -1 && cursor.from < cursor.to) {
19452
                    let endHandle = findHandle(cursor);
19453
                    return { start: firstToken, end: endHandle ? { from: endHandle.from, to: endHandle.to } : undefined, matched: true };
19454
                }
19455
                else if (matchingNodes(cursor.type, dir, brackets)) {
19456
                    depth++;
19457
                }
19458
                else if (matchingNodes(cursor.type, -dir, brackets)) {
19459
                    if (depth == 0) {
19460
                        let endHandle = findHandle(cursor);
19461
                        return {
19462
                            start: firstToken,
19463
                            end: endHandle && endHandle.from < endHandle.to ? { from: endHandle.from, to: endHandle.to } : undefined,
19464
                            matched: false
19465
                        };
19466
                    }
19467
                    depth--;
19468
                }
19469
            }
19470
        } while (dir < 0 ? cursor.prevSibling() : cursor.nextSibling());
19471
    return { start: firstToken, matched: false };
19472
}
19473
function matchPlainBrackets(state, pos, dir, tree, tokenType, maxScanDistance, brackets) {
19474
    let startCh = dir < 0 ? state.sliceDoc(pos - 1, pos) : state.sliceDoc(pos, pos + 1);
19475
    let bracket = brackets.indexOf(startCh);
19476
    if (bracket < 0 || (bracket % 2 == 0) != (dir > 0))
19477
        return null;
19478
    let startToken = { from: dir < 0 ? pos - 1 : pos, to: dir > 0 ? pos + 1 : pos };
19479
    let iter = state.doc.iterRange(pos, dir > 0 ? state.doc.length : 0), depth = 0;
19480
    for (let distance = 0; !(iter.next()).done && distance <= maxScanDistance;) {
19481
        let text = iter.value;
19482
        if (dir < 0)
19483
            distance += text.length;
19484
        let basePos = pos + distance * dir;
19485
        for (let pos = dir > 0 ? 0 : text.length - 1, end = dir > 0 ? text.length : -1; pos != end; pos += dir) {
19486
            let found = brackets.indexOf(text[pos]);
19487
            if (found < 0 || tree.resolveInner(basePos + pos, 1).type != tokenType)
19488
                continue;
19489
            if ((found % 2 == 0) == (dir > 0)) {
19490
                depth++;
19491
            }
19492
            else if (depth == 1) { // Closing
19493
                return { start: startToken, end: { from: basePos + pos, to: basePos + pos + 1 }, matched: (found >> 1) == (bracket >> 1) };
19494
            }
19495
            else {
19496
                depth--;
19497
            }
19498
        }
19499
        if (dir > 0)
19500
            distance += text.length;
19501
    }
19502
    return iter.done ? { start: startToken, matched: false } : null;
19503
}
19504
const noTokens = /*@__PURE__*/Object.create(null);
19505
const typeArray = [NodeType.none];
19506
const warned = [];
19507
// Cache of node types by name and tags
19508
const byTag = /*@__PURE__*/Object.create(null);
19509
const defaultTable = /*@__PURE__*/Object.create(null);
19510
for (let [legacyName, name] of [
19511
    ["variable", "variableName"],
19512
    ["variable-2", "variableName.special"],
19513
    ["string-2", "string.special"],
19514
    ["def", "variableName.definition"],
19515
    ["tag", "tagName"],
19516
    ["attribute", "attributeName"],
19517
    ["type", "typeName"],
19518
    ["builtin", "variableName.standard"],
19519
    ["qualifier", "modifier"],
19520
    ["error", "invalid"],
19521
    ["header", "heading"],
19522
    ["property", "propertyName"]
19523
])
19524
    defaultTable[legacyName] = /*@__PURE__*/createTokenType(noTokens, name);
19525
function warnForPart(part, msg) {
19526
    if (warned.indexOf(part) > -1)
19527
        return;
19528
    warned.push(part);
19529
    console.warn(msg);
19530
}
19531
function createTokenType(extra, tagStr) {
19532
    let tags$1$1 = [];
19533
    for (let name of tagStr.split(" ")) {
19534
        let found = [];
19535
        for (let part of name.split(".")) {
19536
            let value = (extra[part] || tags$1[part]);
19537
            if (!value) {
19538
                warnForPart(part, `Unknown highlighting tag ${part}`);
19539
            }
19540
            else if (typeof value == "function") {
19541
                if (!found.length)
19542
                    warnForPart(part, `Modifier ${part} used at start of tag`);
19543
                else
19544
                    found = found.map(value);
19545
            }
19546
            else {
19547
                if (found.length)
19548
                    warnForPart(part, `Tag ${part} used as modifier`);
19549
                else
19550
                    found = Array.isArray(value) ? value : [value];
19551
            }
19552
        }
19553
        for (let tag of found)
19554
            tags$1$1.push(tag);
19555
    }
19556
    if (!tags$1$1.length)
19557
        return 0;
19558
    let name = tagStr.replace(/ /g, "_"), key = name + " " + tags$1$1.map(t => t.id);
19559
    let known = byTag[key];
19560
    if (known)
19561
        return known.id;
19562
    let type = byTag[key] = NodeType.define({
19563
        id: typeArray.length,
19564
        name,
19565
        props: [styleTags({ [name]: tags$1$1 })]
19566
    });
19567
    typeArray.push(type);
19568
    return type.id;
19569
}
19570
({
19571
    rtl: /*@__PURE__*/Decoration.mark({ class: "cm-iso", inclusive: true, attributes: { dir: "rtl" }, bidiIsolate: Direction.RTL }),
19572
    ltr: /*@__PURE__*/Decoration.mark({ class: "cm-iso", inclusive: true, attributes: { dir: "ltr" }, bidiIsolate: Direction.LTR }),
19573
    auto: /*@__PURE__*/Decoration.mark({ class: "cm-iso", inclusive: true, attributes: { dir: "auto" }, bidiIsolate: null })
19574
});
19575
 
19576
/**
19577
Comment or uncomment the current selection. Will use line comments
19578
if available, otherwise falling back to block comments.
19579
*/
19580
const toggleComment = target => {
19581
    let { state } = target, line = state.doc.lineAt(state.selection.main.from), config = getConfig(target.state, line.from);
19582
    return config.line ? toggleLineComment(target) : config.block ? toggleBlockCommentByLine(target) : false;
19583
};
19584
function command(f, option) {
19585
    return ({ state, dispatch }) => {
19586
        if (state.readOnly)
19587
            return false;
19588
        let tr = f(option, state);
19589
        if (!tr)
19590
            return false;
19591
        dispatch(state.update(tr));
19592
        return true;
19593
    };
19594
}
19595
/**
19596
Comment or uncomment the current selection using line comments.
19597
The line comment syntax is taken from the
19598
[`commentTokens`](https://codemirror.net/6/docs/ref/#commands.CommentTokens) [language
19599
data](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt).
19600
*/
19601
const toggleLineComment = /*@__PURE__*/command(changeLineComment, 0 /* CommentOption.Toggle */);
19602
/**
19603
Comment or uncomment the current selection using block comments.
19604
The block comment syntax is taken from the
19605
[`commentTokens`](https://codemirror.net/6/docs/ref/#commands.CommentTokens) [language
19606
data](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt).
19607
*/
19608
const toggleBlockComment = /*@__PURE__*/command(changeBlockComment, 0 /* CommentOption.Toggle */);
19609
/**
19610
Comment or uncomment the lines around the current selection using
19611
block comments.
19612
*/
19613
const toggleBlockCommentByLine = /*@__PURE__*/command((o, s) => changeBlockComment(o, s, selectedLineRanges(s)), 0 /* CommentOption.Toggle */);
19614
function getConfig(state, pos) {
19615
    let data = state.languageDataAt("commentTokens", pos);
19616
    return data.length ? data[0] : {};
19617
}
19618
const SearchMargin = 50;
19619
/**
19620
Determines if the given range is block-commented in the given
19621
state.
19622
*/
19623
function findBlockComment(state, { open, close }, from, to) {
19624
    let textBefore = state.sliceDoc(from - SearchMargin, from);
19625
    let textAfter = state.sliceDoc(to, to + SearchMargin);
19626
    let spaceBefore = /\s*$/.exec(textBefore)[0].length, spaceAfter = /^\s*/.exec(textAfter)[0].length;
19627
    let beforeOff = textBefore.length - spaceBefore;
19628
    if (textBefore.slice(beforeOff - open.length, beforeOff) == open &&
19629
        textAfter.slice(spaceAfter, spaceAfter + close.length) == close) {
19630
        return { open: { pos: from - spaceBefore, margin: spaceBefore && 1 },
19631
            close: { pos: to + spaceAfter, margin: spaceAfter && 1 } };
19632
    }
19633
    let startText, endText;
19634
    if (to - from <= 2 * SearchMargin) {
19635
        startText = endText = state.sliceDoc(from, to);
19636
    }
19637
    else {
19638
        startText = state.sliceDoc(from, from + SearchMargin);
19639
        endText = state.sliceDoc(to - SearchMargin, to);
19640
    }
19641
    let startSpace = /^\s*/.exec(startText)[0].length, endSpace = /\s*$/.exec(endText)[0].length;
19642
    let endOff = endText.length - endSpace - close.length;
19643
    if (startText.slice(startSpace, startSpace + open.length) == open &&
19644
        endText.slice(endOff, endOff + close.length) == close) {
19645
        return { open: { pos: from + startSpace + open.length,
19646
                margin: /\s/.test(startText.charAt(startSpace + open.length)) ? 1 : 0 },
19647
            close: { pos: to - endSpace - close.length,
19648
                margin: /\s/.test(endText.charAt(endOff - 1)) ? 1 : 0 } };
19649
    }
19650
    return null;
19651
}
19652
function selectedLineRanges(state) {
19653
    let ranges = [];
19654
    for (let r of state.selection.ranges) {
19655
        let fromLine = state.doc.lineAt(r.from);
19656
        let toLine = r.to <= fromLine.to ? fromLine : state.doc.lineAt(r.to);
19657
        let last = ranges.length - 1;
19658
        if (last >= 0 && ranges[last].to > fromLine.from)
19659
            ranges[last].to = toLine.to;
19660
        else
19661
            ranges.push({ from: fromLine.from + /^\s*/.exec(fromLine.text)[0].length, to: toLine.to });
19662
    }
19663
    return ranges;
19664
}
19665
// Performs toggle, comment and uncomment of block comments in
19666
// languages that support them.
19667
function changeBlockComment(option, state, ranges = state.selection.ranges) {
19668
    let tokens = ranges.map(r => getConfig(state, r.from).block);
19669
    if (!tokens.every(c => c))
19670
        return null;
19671
    let comments = ranges.map((r, i) => findBlockComment(state, tokens[i], r.from, r.to));
19672
    if (option != 2 /* CommentOption.Uncomment */ && !comments.every(c => c)) {
19673
        return { changes: state.changes(ranges.map((range, i) => {
19674
                if (comments[i])
19675
                    return [];
19676
                return [{ from: range.from, insert: tokens[i].open + " " }, { from: range.to, insert: " " + tokens[i].close }];
19677
            })) };
19678
    }
19679
    else if (option != 1 /* CommentOption.Comment */ && comments.some(c => c)) {
19680
        let changes = [];
19681
        for (let i = 0, comment; i < comments.length; i++)
19682
            if (comment = comments[i]) {
19683
                let token = tokens[i], { open, close } = comment;
19684
                changes.push({ from: open.pos - token.open.length, to: open.pos + open.margin }, { from: close.pos - close.margin, to: close.pos + token.close.length });
19685
            }
19686
        return { changes };
19687
    }
19688
    return null;
19689
}
19690
// Performs toggle, comment and uncomment of line comments.
19691
function changeLineComment(option, state, ranges = state.selection.ranges) {
19692
    let lines = [];
19693
    let prevLine = -1;
19694
    for (let { from, to } of ranges) {
19695
        let startI = lines.length, minIndent = 1e9;
19696
        let token = getConfig(state, from).line;
19697
        if (!token)
19698
            continue;
19699
        for (let pos = from; pos <= to;) {
19700
            let line = state.doc.lineAt(pos);
19701
            if (line.from > prevLine && (from == to || to > line.from)) {
19702
                prevLine = line.from;
19703
                let indent = /^\s*/.exec(line.text)[0].length;
19704
                let empty = indent == line.length;
19705
                let comment = line.text.slice(indent, indent + token.length) == token ? indent : -1;
19706
                if (indent < line.text.length && indent < minIndent)
19707
                    minIndent = indent;
19708
                lines.push({ line, comment, token, indent, empty, single: false });
19709
            }
19710
            pos = line.to + 1;
19711
        }
19712
        if (minIndent < 1e9)
19713
            for (let i = startI; i < lines.length; i++)
19714
                if (lines[i].indent < lines[i].line.text.length)
19715
                    lines[i].indent = minIndent;
19716
        if (lines.length == startI + 1)
19717
            lines[startI].single = true;
19718
    }
19719
    if (option != 2 /* CommentOption.Uncomment */ && lines.some(l => l.comment < 0 && (!l.empty || l.single))) {
19720
        let changes = [];
19721
        for (let { line, token, indent, empty, single } of lines)
19722
            if (single || !empty)
19723
                changes.push({ from: line.from + indent, insert: token + " " });
19724
        let changeSet = state.changes(changes);
19725
        return { changes: changeSet, selection: state.selection.map(changeSet, 1) };
19726
    }
19727
    else if (option != 1 /* CommentOption.Comment */ && lines.some(l => l.comment >= 0)) {
19728
        let changes = [];
19729
        for (let { line, comment, token } of lines)
19730
            if (comment >= 0) {
19731
                let from = line.from + comment, to = from + token.length;
19732
                if (line.text[to - line.from] == " ")
19733
                    to++;
19734
                changes.push({ from, to });
19735
            }
19736
        return { changes };
19737
    }
19738
    return null;
19739
}
19740
 
19741
const fromHistory = /*@__PURE__*/Annotation.define();
19742
/**
19743
Transaction annotation that will prevent that transaction from
19744
being combined with other transactions in the undo history. Given
19745
`"before"`, it'll prevent merging with previous transactions. With
19746
`"after"`, subsequent transactions won't be combined with this
19747
one. With `"full"`, the transaction is isolated on both sides.
19748
*/
19749
const isolateHistory = /*@__PURE__*/Annotation.define();
19750
/**
19751
This facet provides a way to register functions that, given a
19752
transaction, provide a set of effects that the history should
19753
store when inverting the transaction. This can be used to
19754
integrate some kinds of effects in the history, so that they can
19755
be undone (and redone again).
19756
*/
19757
const invertedEffects = /*@__PURE__*/Facet.define();
19758
const historyConfig = /*@__PURE__*/Facet.define({
19759
    combine(configs) {
19760
        return combineConfig(configs, {
19761
            minDepth: 100,
19762
            newGroupDelay: 500,
19763
            joinToEvent: (_t, isAdjacent) => isAdjacent,
19764
        }, {
19765
            minDepth: Math.max,
19766
            newGroupDelay: Math.min,
19767
            joinToEvent: (a, b) => (tr, adj) => a(tr, adj) || b(tr, adj)
19768
        });
19769
    }
19770
});
19771
const historyField_ = /*@__PURE__*/StateField.define({
19772
    create() {
19773
        return HistoryState.empty;
19774
    },
19775
    update(state, tr) {
19776
        let config = tr.state.facet(historyConfig);
19777
        let fromHist = tr.annotation(fromHistory);
19778
        if (fromHist) {
19779
            let item = HistEvent.fromTransaction(tr, fromHist.selection), from = fromHist.side;
19780
            let other = from == 0 /* BranchName.Done */ ? state.undone : state.done;
19781
            if (item)
19782
                other = updateBranch(other, other.length, config.minDepth, item);
19783
            else
19784
                other = addSelection(other, tr.startState.selection);
19785
            return new HistoryState(from == 0 /* BranchName.Done */ ? fromHist.rest : other, from == 0 /* BranchName.Done */ ? other : fromHist.rest);
19786
        }
19787
        let isolate = tr.annotation(isolateHistory);
19788
        if (isolate == "full" || isolate == "before")
19789
            state = state.isolate();
19790
        if (tr.annotation(Transaction.addToHistory) === false)
19791
            return !tr.changes.empty ? state.addMapping(tr.changes.desc) : state;
19792
        let event = HistEvent.fromTransaction(tr);
19793
        let time = tr.annotation(Transaction.time), userEvent = tr.annotation(Transaction.userEvent);
19794
        if (event)
19795
            state = state.addChanges(event, time, userEvent, config, tr);
19796
        else if (tr.selection)
19797
            state = state.addSelection(tr.startState.selection, time, userEvent, config.newGroupDelay);
19798
        if (isolate == "full" || isolate == "after")
19799
            state = state.isolate();
19800
        return state;
19801
    },
19802
    toJSON(value) {
19803
        return { done: value.done.map(e => e.toJSON()), undone: value.undone.map(e => e.toJSON()) };
19804
    },
19805
    fromJSON(json) {
19806
        return new HistoryState(json.done.map(HistEvent.fromJSON), json.undone.map(HistEvent.fromJSON));
19807
    }
19808
});
19809
/**
19810
Create a history extension with the given configuration.
19811
*/
19812
function history(config = {}) {
19813
    return [
19814
        historyField_,
19815
        historyConfig.of(config),
19816
        EditorView.domEventHandlers({
19817
            beforeinput(e, view) {
19818
                let command = e.inputType == "historyUndo" ? undo : e.inputType == "historyRedo" ? redo : null;
19819
                if (!command)
19820
                    return false;
19821
                e.preventDefault();
19822
                return command(view);
19823
            }
19824
        })
19825
    ];
19826
}
19827
function cmd(side, selection) {
19828
    return function ({ state, dispatch }) {
19829
        if (!selection && state.readOnly)
19830
            return false;
19831
        let historyState = state.field(historyField_, false);
19832
        if (!historyState)
19833
            return false;
19834
        let tr = historyState.pop(side, state, selection);
19835
        if (!tr)
19836
            return false;
19837
        dispatch(tr);
19838
        return true;
19839
    };
19840
}
19841
/**
19842
Undo a single group of history events. Returns false if no group
19843
was available.
19844
*/
19845
const undo = /*@__PURE__*/cmd(0 /* BranchName.Done */, false);
19846
/**
19847
Redo a group of history events. Returns false if no group was
19848
available.
19849
*/
19850
const redo = /*@__PURE__*/cmd(1 /* BranchName.Undone */, false);
19851
/**
19852
Undo a change or selection change.
19853
*/
19854
const undoSelection = /*@__PURE__*/cmd(0 /* BranchName.Done */, true);
19855
/**
19856
Redo a change or selection change.
19857
*/
19858
const redoSelection = /*@__PURE__*/cmd(1 /* BranchName.Undone */, true);
19859
// History events store groups of changes or effects that need to be
19860
// undone/redone together.
19861
class HistEvent {
19862
    constructor(
19863
    // The changes in this event. Normal events hold at least one
19864
    // change or effect. But it may be necessary to store selection
19865
    // events before the first change, in which case a special type of
19866
    // instance is created which doesn't hold any changes, with
19867
    // changes == startSelection == undefined
19868
    changes,
19869
    // The effects associated with this event
19870
    effects,
19871
    // Accumulated mapping (from addToHistory==false) that should be
19872
    // applied to events below this one.
19873
    mapped,
19874
    // The selection before this event
19875
    startSelection,
19876
    // Stores selection changes after this event, to be used for
19877
    // selection undo/redo.
19878
    selectionsAfter) {
19879
        this.changes = changes;
19880
        this.effects = effects;
19881
        this.mapped = mapped;
19882
        this.startSelection = startSelection;
19883
        this.selectionsAfter = selectionsAfter;
19884
    }
19885
    setSelAfter(after) {
19886
        return new HistEvent(this.changes, this.effects, this.mapped, this.startSelection, after);
19887
    }
19888
    toJSON() {
19889
        var _a, _b, _c;
19890
        return {
19891
            changes: (_a = this.changes) === null || _a === void 0 ? void 0 : _a.toJSON(),
19892
            mapped: (_b = this.mapped) === null || _b === void 0 ? void 0 : _b.toJSON(),
19893
            startSelection: (_c = this.startSelection) === null || _c === void 0 ? void 0 : _c.toJSON(),
19894
            selectionsAfter: this.selectionsAfter.map(s => s.toJSON())
19895
        };
19896
    }
19897
    static fromJSON(json) {
19898
        return new HistEvent(json.changes && ChangeSet.fromJSON(json.changes), [], json.mapped && ChangeDesc.fromJSON(json.mapped), json.startSelection && EditorSelection.fromJSON(json.startSelection), json.selectionsAfter.map(EditorSelection.fromJSON));
19899
    }
19900
    // This does not check `addToHistory` and such, it assumes the
19901
    // transaction needs to be converted to an item. Returns null when
19902
    // there are no changes or effects in the transaction.
19903
    static fromTransaction(tr, selection) {
19904
        let effects = none$1;
19905
        for (let invert of tr.startState.facet(invertedEffects)) {
19906
            let result = invert(tr);
19907
            if (result.length)
19908
                effects = effects.concat(result);
19909
        }
19910
        if (!effects.length && tr.changes.empty)
19911
            return null;
19912
        return new HistEvent(tr.changes.invert(tr.startState.doc), effects, undefined, selection || tr.startState.selection, none$1);
19913
    }
19914
    static selection(selections) {
19915
        return new HistEvent(undefined, none$1, undefined, undefined, selections);
19916
    }
19917
}
19918
function updateBranch(branch, to, maxLen, newEvent) {
19919
    let start = to + 1 > maxLen + 20 ? to - maxLen - 1 : 0;
19920
    let newBranch = branch.slice(start, to);
19921
    newBranch.push(newEvent);
19922
    return newBranch;
19923
}
19924
function isAdjacent(a, b) {
19925
    let ranges = [], isAdjacent = false;
19926
    a.iterChangedRanges((f, t) => ranges.push(f, t));
19927
    b.iterChangedRanges((_f, _t, f, t) => {
19928
        for (let i = 0; i < ranges.length;) {
19929
            let from = ranges[i++], to = ranges[i++];
19930
            if (t >= from && f <= to)
19931
                isAdjacent = true;
19932
        }
19933
    });
19934
    return isAdjacent;
19935
}
19936
function eqSelectionShape(a, b) {
19937
    return a.ranges.length == b.ranges.length &&
19938
        a.ranges.filter((r, i) => r.empty != b.ranges[i].empty).length === 0;
19939
}
19940
function conc(a, b) {
19941
    return !a.length ? b : !b.length ? a : a.concat(b);
19942
}
19943
const none$1 = [];
19944
const MaxSelectionsPerEvent = 200;
19945
function addSelection(branch, selection) {
19946
    if (!branch.length) {
19947
        return [HistEvent.selection([selection])];
19948
    }
19949
    else {
19950
        let lastEvent = branch[branch.length - 1];
19951
        let sels = lastEvent.selectionsAfter.slice(Math.max(0, lastEvent.selectionsAfter.length - MaxSelectionsPerEvent));
19952
        if (sels.length && sels[sels.length - 1].eq(selection))
19953
            return branch;
19954
        sels.push(selection);
19955
        return updateBranch(branch, branch.length - 1, 1e9, lastEvent.setSelAfter(sels));
19956
    }
19957
}
19958
// Assumes the top item has one or more selectionAfter values
19959
function popSelection(branch) {
19960
    let last = branch[branch.length - 1];
19961
    let newBranch = branch.slice();
19962
    newBranch[branch.length - 1] = last.setSelAfter(last.selectionsAfter.slice(0, last.selectionsAfter.length - 1));
19963
    return newBranch;
19964
}
19965
// Add a mapping to the top event in the given branch. If this maps
19966
// away all the changes and effects in that item, drop it and
19967
// propagate the mapping to the next item.
19968
function addMappingToBranch(branch, mapping) {
19969
    if (!branch.length)
19970
        return branch;
19971
    let length = branch.length, selections = none$1;
19972
    while (length) {
19973
        let event = mapEvent(branch[length - 1], mapping, selections);
19974
        if (event.changes && !event.changes.empty || event.effects.length) { // Event survived mapping
19975
            let result = branch.slice(0, length);
19976
            result[length - 1] = event;
19977
            return result;
19978
        }
19979
        else { // Drop this event, since there's no changes or effects left
19980
            mapping = event.mapped;
19981
            length--;
19982
            selections = event.selectionsAfter;
19983
        }
19984
    }
19985
    return selections.length ? [HistEvent.selection(selections)] : none$1;
19986
}
19987
function mapEvent(event, mapping, extraSelections) {
19988
    let selections = conc(event.selectionsAfter.length ? event.selectionsAfter.map(s => s.map(mapping)) : none$1, extraSelections);
19989
    // Change-less events don't store mappings (they are always the last event in a branch)
19990
    if (!event.changes)
19991
        return HistEvent.selection(selections);
19992
    let mappedChanges = event.changes.map(mapping), before = mapping.mapDesc(event.changes, true);
19993
    let fullMapping = event.mapped ? event.mapped.composeDesc(before) : before;
19994
    return new HistEvent(mappedChanges, StateEffect.mapEffects(event.effects, mapping), fullMapping, event.startSelection.map(before), selections);
19995
}
19996
const joinableUserEvent = /^(input\.type|delete)($|\.)/;
19997
class HistoryState {
19998
    constructor(done, undone, prevTime = 0, prevUserEvent = undefined) {
19999
        this.done = done;
20000
        this.undone = undone;
20001
        this.prevTime = prevTime;
20002
        this.prevUserEvent = prevUserEvent;
20003
    }
20004
    isolate() {
20005
        return this.prevTime ? new HistoryState(this.done, this.undone) : this;
20006
    }
20007
    addChanges(event, time, userEvent, config, tr) {
20008
        let done = this.done, lastEvent = done[done.length - 1];
20009
        if (lastEvent && lastEvent.changes && !lastEvent.changes.empty && event.changes &&
20010
            (!userEvent || joinableUserEvent.test(userEvent)) &&
20011
            ((!lastEvent.selectionsAfter.length &&
20012
                time - this.prevTime < config.newGroupDelay &&
20013
                config.joinToEvent(tr, isAdjacent(lastEvent.changes, event.changes))) ||
20014
                // For compose (but not compose.start) events, always join with previous event
20015
                userEvent == "input.type.compose")) {
20016
            done = updateBranch(done, done.length - 1, config.minDepth, new HistEvent(event.changes.compose(lastEvent.changes), conc(event.effects, lastEvent.effects), lastEvent.mapped, lastEvent.startSelection, none$1));
20017
        }
20018
        else {
20019
            done = updateBranch(done, done.length, config.minDepth, event);
20020
        }
20021
        return new HistoryState(done, none$1, time, userEvent);
20022
    }
20023
    addSelection(selection, time, userEvent, newGroupDelay) {
20024
        let last = this.done.length ? this.done[this.done.length - 1].selectionsAfter : none$1;
20025
        if (last.length > 0 &&
20026
            time - this.prevTime < newGroupDelay &&
20027
            userEvent == this.prevUserEvent && userEvent && /^select($|\.)/.test(userEvent) &&
20028
            eqSelectionShape(last[last.length - 1], selection))
20029
            return this;
20030
        return new HistoryState(addSelection(this.done, selection), this.undone, time, userEvent);
20031
    }
20032
    addMapping(mapping) {
20033
        return new HistoryState(addMappingToBranch(this.done, mapping), addMappingToBranch(this.undone, mapping), this.prevTime, this.prevUserEvent);
20034
    }
20035
    pop(side, state, onlySelection) {
20036
        let branch = side == 0 /* BranchName.Done */ ? this.done : this.undone;
20037
        if (branch.length == 0)
20038
            return null;
20039
        let event = branch[branch.length - 1], selection = event.selectionsAfter[0] || state.selection;
20040
        if (onlySelection && event.selectionsAfter.length) {
20041
            return state.update({
20042
                selection: event.selectionsAfter[event.selectionsAfter.length - 1],
20043
                annotations: fromHistory.of({ side, rest: popSelection(branch), selection }),
20044
                userEvent: side == 0 /* BranchName.Done */ ? "select.undo" : "select.redo",
20045
                scrollIntoView: true
20046
            });
20047
        }
20048
        else if (!event.changes) {
20049
            return null;
20050
        }
20051
        else {
20052
            let rest = branch.length == 1 ? none$1 : branch.slice(0, branch.length - 1);
20053
            if (event.mapped)
20054
                rest = addMappingToBranch(rest, event.mapped);
20055
            return state.update({
20056
                changes: event.changes,
20057
                selection: event.startSelection,
20058
                effects: event.effects,
20059
                annotations: fromHistory.of({ side, rest, selection }),
20060
                filter: false,
20061
                userEvent: side == 0 /* BranchName.Done */ ? "undo" : "redo",
20062
                scrollIntoView: true
20063
            });
20064
        }
20065
    }
20066
}
20067
HistoryState.empty = /*@__PURE__*/new HistoryState(none$1, none$1);
20068
/**
20069
Default key bindings for the undo history.
20070
 
20071
- Mod-z: [`undo`](https://codemirror.net/6/docs/ref/#commands.undo).
20072
- Mod-y (Mod-Shift-z on macOS) + Ctrl-Shift-z on Linux: [`redo`](https://codemirror.net/6/docs/ref/#commands.redo).
20073
- Mod-u: [`undoSelection`](https://codemirror.net/6/docs/ref/#commands.undoSelection).
20074
- Alt-u (Mod-Shift-u on macOS): [`redoSelection`](https://codemirror.net/6/docs/ref/#commands.redoSelection).
20075
*/
20076
const historyKeymap = [
20077
    { key: "Mod-z", run: undo, preventDefault: true },
20078
    { key: "Mod-y", mac: "Mod-Shift-z", run: redo, preventDefault: true },
20079
    { linux: "Ctrl-Shift-z", run: redo, preventDefault: true },
20080
    { key: "Mod-u", run: undoSelection, preventDefault: true },
20081
    { key: "Alt-u", mac: "Mod-Shift-u", run: redoSelection, preventDefault: true }
20082
];
20083
 
20084
function updateSel(sel, by) {
20085
    return EditorSelection.create(sel.ranges.map(by), sel.mainIndex);
20086
}
20087
function setSel(state, selection) {
20088
    return state.update({ selection, scrollIntoView: true, userEvent: "select" });
20089
}
20090
function moveSel({ state, dispatch }, how) {
20091
    let selection = updateSel(state.selection, how);
20092
    if (selection.eq(state.selection, true))
20093
        return false;
20094
    dispatch(setSel(state, selection));
20095
    return true;
20096
}
20097
function rangeEnd(range, forward) {
20098
    return EditorSelection.cursor(forward ? range.to : range.from);
20099
}
20100
function cursorByChar(view, forward) {
20101
    return moveSel(view, range => range.empty ? view.moveByChar(range, forward) : rangeEnd(range, forward));
20102
}
20103
function ltrAtCursor(view) {
20104
    return view.textDirectionAt(view.state.selection.main.head) == Direction.LTR;
20105
}
20106
/**
20107
Move the selection one character to the left (which is backward in
20108
left-to-right text, forward in right-to-left text).
20109
*/
20110
const cursorCharLeft = view => cursorByChar(view, !ltrAtCursor(view));
20111
/**
20112
Move the selection one character to the right.
20113
*/
20114
const cursorCharRight = view => cursorByChar(view, ltrAtCursor(view));
20115
function cursorByGroup(view, forward) {
20116
    return moveSel(view, range => range.empty ? view.moveByGroup(range, forward) : rangeEnd(range, forward));
20117
}
20118
/**
20119
Move the selection to the left across one group of word or
20120
non-word (but also non-space) characters.
20121
*/
20122
const cursorGroupLeft = view => cursorByGroup(view, !ltrAtCursor(view));
20123
/**
20124
Move the selection one group to the right.
20125
*/
20126
const cursorGroupRight = view => cursorByGroup(view, ltrAtCursor(view));
20127
function interestingNode(state, node, bracketProp) {
20128
    if (node.type.prop(bracketProp))
20129
        return true;
20130
    let len = node.to - node.from;
20131
    return len && (len > 2 || /[^\s,.;:]/.test(state.sliceDoc(node.from, node.to))) || node.firstChild;
20132
}
20133
function moveBySyntax(state, start, forward) {
20134
    let pos = syntaxTree(state).resolveInner(start.head);
20135
    let bracketProp = forward ? NodeProp.closedBy : NodeProp.openedBy;
20136
    // Scan forward through child nodes to see if there's an interesting
20137
    // node ahead.
20138
    for (let at = start.head;;) {
20139
        let next = forward ? pos.childAfter(at) : pos.childBefore(at);
20140
        if (!next)
20141
            break;
20142
        if (interestingNode(state, next, bracketProp))
20143
            pos = next;
20144
        else
20145
            at = forward ? next.to : next.from;
20146
    }
20147
    let bracket = pos.type.prop(bracketProp), match, newPos;
20148
    if (bracket && (match = forward ? matchBrackets(state, pos.from, 1) : matchBrackets(state, pos.to, -1)) && match.matched)
20149
        newPos = forward ? match.end.to : match.end.from;
20150
    else
20151
        newPos = forward ? pos.to : pos.from;
20152
    return EditorSelection.cursor(newPos, forward ? -1 : 1);
20153
}
20154
/**
20155
Move the cursor over the next syntactic element to the left.
20156
*/
20157
const cursorSyntaxLeft = view => moveSel(view, range => moveBySyntax(view.state, range, !ltrAtCursor(view)));
20158
/**
20159
Move the cursor over the next syntactic element to the right.
20160
*/
20161
const cursorSyntaxRight = view => moveSel(view, range => moveBySyntax(view.state, range, ltrAtCursor(view)));
20162
function cursorByLine(view, forward) {
20163
    return moveSel(view, range => {
20164
        if (!range.empty)
20165
            return rangeEnd(range, forward);
20166
        let moved = view.moveVertically(range, forward);
20167
        return moved.head != range.head ? moved : view.moveToLineBoundary(range, forward);
20168
    });
20169
}
20170
/**
20171
Move the selection one line up.
20172
*/
20173
const cursorLineUp = view => cursorByLine(view, false);
20174
/**
20175
Move the selection one line down.
20176
*/
20177
const cursorLineDown = view => cursorByLine(view, true);
20178
function pageInfo(view) {
20179
    let selfScroll = view.scrollDOM.clientHeight < view.scrollDOM.scrollHeight - 2;
20180
    let marginTop = 0, marginBottom = 0, height;
20181
    if (selfScroll) {
20182
        for (let source of view.state.facet(EditorView.scrollMargins)) {
20183
            let margins = source(view);
20184
            if (margins === null || margins === void 0 ? void 0 : margins.top)
20185
                marginTop = Math.max(margins === null || margins === void 0 ? void 0 : margins.top, marginTop);
20186
            if (margins === null || margins === void 0 ? void 0 : margins.bottom)
20187
                marginBottom = Math.max(margins === null || margins === void 0 ? void 0 : margins.bottom, marginBottom);
20188
        }
20189
        height = view.scrollDOM.clientHeight - marginTop - marginBottom;
20190
    }
20191
    else {
20192
        height = (view.dom.ownerDocument.defaultView || window).innerHeight;
20193
    }
20194
    return { marginTop, marginBottom, selfScroll,
20195
        height: Math.max(view.defaultLineHeight, height - 5) };
20196
}
20197
function cursorByPage(view, forward) {
20198
    let page = pageInfo(view);
20199
    let { state } = view, selection = updateSel(state.selection, range => {
20200
        return range.empty ? view.moveVertically(range, forward, page.height)
20201
            : rangeEnd(range, forward);
20202
    });
20203
    if (selection.eq(state.selection))
20204
        return false;
20205
    let effect;
20206
    if (page.selfScroll) {
20207
        let startPos = view.coordsAtPos(state.selection.main.head);
20208
        let scrollRect = view.scrollDOM.getBoundingClientRect();
20209
        let scrollTop = scrollRect.top + page.marginTop, scrollBottom = scrollRect.bottom - page.marginBottom;
20210
        if (startPos && startPos.top > scrollTop && startPos.bottom < scrollBottom)
20211
            effect = EditorView.scrollIntoView(selection.main.head, { y: "start", yMargin: startPos.top - scrollTop });
20212
    }
20213
    view.dispatch(setSel(state, selection), { effects: effect });
20214
    return true;
20215
}
20216
/**
20217
Move the selection one page up.
20218
*/
20219
const cursorPageUp = view => cursorByPage(view, false);
20220
/**
20221
Move the selection one page down.
20222
*/
20223
const cursorPageDown = view => cursorByPage(view, true);
20224
function moveByLineBoundary(view, start, forward) {
20225
    let line = view.lineBlockAt(start.head), moved = view.moveToLineBoundary(start, forward);
20226
    if (moved.head == start.head && moved.head != (forward ? line.to : line.from))
20227
        moved = view.moveToLineBoundary(start, forward, false);
20228
    if (!forward && moved.head == line.from && line.length) {
20229
        let space = /^\s*/.exec(view.state.sliceDoc(line.from, Math.min(line.from + 100, line.to)))[0].length;
20230
        if (space && start.head != line.from + space)
20231
            moved = EditorSelection.cursor(line.from + space);
20232
    }
20233
    return moved;
20234
}
20235
/**
20236
Move the selection to the next line wrap point, or to the end of
20237
the line if there isn't one left on this line.
20238
*/
20239
const cursorLineBoundaryForward = view => moveSel(view, range => moveByLineBoundary(view, range, true));
20240
/**
20241
Move the selection to previous line wrap point, or failing that to
20242
the start of the line. If the line is indented, and the cursor
20243
isn't already at the end of the indentation, this will move to the
20244
end of the indentation instead of the start of the line.
20245
*/
20246
const cursorLineBoundaryBackward = view => moveSel(view, range => moveByLineBoundary(view, range, false));
20247
/**
20248
Move the selection one line wrap point to the left.
20249
*/
20250
const cursorLineBoundaryLeft = view => moveSel(view, range => moveByLineBoundary(view, range, !ltrAtCursor(view)));
20251
/**
20252
Move the selection one line wrap point to the right.
20253
*/
20254
const cursorLineBoundaryRight = view => moveSel(view, range => moveByLineBoundary(view, range, ltrAtCursor(view)));
20255
/**
20256
Move the selection to the start of the line.
20257
*/
20258
const cursorLineStart = view => moveSel(view, range => EditorSelection.cursor(view.lineBlockAt(range.head).from, 1));
20259
/**
20260
Move the selection to the end of the line.
20261
*/
20262
const cursorLineEnd = view => moveSel(view, range => EditorSelection.cursor(view.lineBlockAt(range.head).to, -1));
20263
function toMatchingBracket(state, dispatch, extend) {
20264
    let found = false, selection = updateSel(state.selection, range => {
20265
        let matching = matchBrackets(state, range.head, -1)
20266
            || matchBrackets(state, range.head, 1)
20267
            || (range.head > 0 && matchBrackets(state, range.head - 1, 1))
20268
            || (range.head < state.doc.length && matchBrackets(state, range.head + 1, -1));
20269
        if (!matching || !matching.end)
20270
            return range;
20271
        found = true;
20272
        let head = matching.start.from == range.head ? matching.end.to : matching.end.from;
20273
        return extend ? EditorSelection.range(range.anchor, head) : EditorSelection.cursor(head);
20274
    });
20275
    if (!found)
20276
        return false;
20277
    dispatch(setSel(state, selection));
20278
    return true;
20279
}
20280
/**
20281
Move the selection to the bracket matching the one it is currently
20282
on, if any.
20283
*/
20284
const cursorMatchingBracket = ({ state, dispatch }) => toMatchingBracket(state, dispatch, false);
20285
function extendSel(view, how) {
20286
    let selection = updateSel(view.state.selection, range => {
20287
        let head = how(range);
20288
        return EditorSelection.range(range.anchor, head.head, head.goalColumn, head.bidiLevel || undefined);
20289
    });
20290
    if (selection.eq(view.state.selection))
20291
        return false;
20292
    view.dispatch(setSel(view.state, selection));
20293
    return true;
20294
}
20295
function selectByChar(view, forward) {
20296
    return extendSel(view, range => view.moveByChar(range, forward));
20297
}
20298
/**
20299
Move the selection head one character to the left, while leaving
20300
the anchor in place.
20301
*/
20302
const selectCharLeft = view => selectByChar(view, !ltrAtCursor(view));
20303
/**
20304
Move the selection head one character to the right.
20305
*/
20306
const selectCharRight = view => selectByChar(view, ltrAtCursor(view));
20307
function selectByGroup(view, forward) {
20308
    return extendSel(view, range => view.moveByGroup(range, forward));
20309
}
20310
/**
20311
Move the selection head one [group](https://codemirror.net/6/docs/ref/#commands.cursorGroupLeft) to
20312
the left.
20313
*/
20314
const selectGroupLeft = view => selectByGroup(view, !ltrAtCursor(view));
20315
/**
20316
Move the selection head one group to the right.
20317
*/
20318
const selectGroupRight = view => selectByGroup(view, ltrAtCursor(view));
20319
/**
20320
Move the selection head over the next syntactic element to the left.
20321
*/
20322
const selectSyntaxLeft = view => extendSel(view, range => moveBySyntax(view.state, range, !ltrAtCursor(view)));
20323
/**
20324
Move the selection head over the next syntactic element to the right.
20325
*/
20326
const selectSyntaxRight = view => extendSel(view, range => moveBySyntax(view.state, range, ltrAtCursor(view)));
20327
function selectByLine(view, forward) {
20328
    return extendSel(view, range => view.moveVertically(range, forward));
20329
}
20330
/**
20331
Move the selection head one line up.
20332
*/
20333
const selectLineUp = view => selectByLine(view, false);
20334
/**
20335
Move the selection head one line down.
20336
*/
20337
const selectLineDown = view => selectByLine(view, true);
20338
function selectByPage(view, forward) {
20339
    return extendSel(view, range => view.moveVertically(range, forward, pageInfo(view).height));
20340
}
20341
/**
20342
Move the selection head one page up.
20343
*/
20344
const selectPageUp = view => selectByPage(view, false);
20345
/**
20346
Move the selection head one page down.
20347
*/
20348
const selectPageDown = view => selectByPage(view, true);
20349
/**
20350
Move the selection head to the next line boundary.
20351
*/
20352
const selectLineBoundaryForward = view => extendSel(view, range => moveByLineBoundary(view, range, true));
20353
/**
20354
Move the selection head to the previous line boundary.
20355
*/
20356
const selectLineBoundaryBackward = view => extendSel(view, range => moveByLineBoundary(view, range, false));
20357
/**
20358
Move the selection head one line boundary to the left.
20359
*/
20360
const selectLineBoundaryLeft = view => extendSel(view, range => moveByLineBoundary(view, range, !ltrAtCursor(view)));
20361
/**
20362
Move the selection head one line boundary to the right.
20363
*/
20364
const selectLineBoundaryRight = view => extendSel(view, range => moveByLineBoundary(view, range, ltrAtCursor(view)));
20365
/**
20366
Move the selection head to the start of the line.
20367
*/
20368
const selectLineStart = view => extendSel(view, range => EditorSelection.cursor(view.lineBlockAt(range.head).from));
20369
/**
20370
Move the selection head to the end of the line.
20371
*/
20372
const selectLineEnd = view => extendSel(view, range => EditorSelection.cursor(view.lineBlockAt(range.head).to));
20373
/**
20374
Move the selection to the start of the document.
20375
*/
20376
const cursorDocStart = ({ state, dispatch }) => {
20377
    dispatch(setSel(state, { anchor: 0 }));
20378
    return true;
20379
};
20380
/**
20381
Move the selection to the end of the document.
20382
*/
20383
const cursorDocEnd = ({ state, dispatch }) => {
20384
    dispatch(setSel(state, { anchor: state.doc.length }));
20385
    return true;
20386
};
20387
/**
20388
Move the selection head to the start of the document.
20389
*/
20390
const selectDocStart = ({ state, dispatch }) => {
20391
    dispatch(setSel(state, { anchor: state.selection.main.anchor, head: 0 }));
20392
    return true;
20393
};
20394
/**
20395
Move the selection head to the end of the document.
20396
*/
20397
const selectDocEnd = ({ state, dispatch }) => {
20398
    dispatch(setSel(state, { anchor: state.selection.main.anchor, head: state.doc.length }));
20399
    return true;
20400
};
20401
/**
20402
Select the entire document.
20403
*/
20404
const selectAll = ({ state, dispatch }) => {
20405
    dispatch(state.update({ selection: { anchor: 0, head: state.doc.length }, userEvent: "select" }));
20406
    return true;
20407
};
20408
/**
20409
Expand the selection to cover entire lines.
20410
*/
20411
const selectLine = ({ state, dispatch }) => {
20412
    let ranges = selectedLineBlocks(state).map(({ from, to }) => EditorSelection.range(from, Math.min(to + 1, state.doc.length)));
20413
    dispatch(state.update({ selection: EditorSelection.create(ranges), userEvent: "select" }));
20414
    return true;
20415
};
20416
/**
20417
Select the next syntactic construct that is larger than the
20418
selection. Note that this will only work insofar as the language
20419
[provider](https://codemirror.net/6/docs/ref/#language.language) you use builds up a full
20420
syntax tree.
20421
*/
20422
const selectParentSyntax = ({ state, dispatch }) => {
20423
    let selection = updateSel(state.selection, range => {
20424
        var _a;
20425
        let stack = syntaxTree(state).resolveStack(range.from, 1);
20426
        for (let cur = stack; cur; cur = cur.next) {
20427
            let { node } = cur;
20428
            if (((node.from < range.from && node.to >= range.to) ||
20429
                (node.to > range.to && node.from <= range.from)) &&
20430
                ((_a = node.parent) === null || _a === void 0 ? void 0 : _a.parent))
20431
                return EditorSelection.range(node.to, node.from);
20432
        }
20433
        return range;
20434
    });
20435
    dispatch(setSel(state, selection));
20436
    return true;
20437
};
20438
/**
20439
Simplify the current selection. When multiple ranges are selected,
20440
reduce it to its main range. Otherwise, if the selection is
20441
non-empty, convert it to a cursor selection.
20442
*/
20443
const simplifySelection = ({ state, dispatch }) => {
20444
    let cur = state.selection, selection = null;
20445
    if (cur.ranges.length > 1)
20446
        selection = EditorSelection.create([cur.main]);
20447
    else if (!cur.main.empty)
20448
        selection = EditorSelection.create([EditorSelection.cursor(cur.main.head)]);
20449
    if (!selection)
20450
        return false;
20451
    dispatch(setSel(state, selection));
20452
    return true;
20453
};
20454
function deleteBy(target, by) {
20455
    if (target.state.readOnly)
20456
        return false;
20457
    let event = "delete.selection", { state } = target;
20458
    let changes = state.changeByRange(range => {
20459
        let { from, to } = range;
20460
        if (from == to) {
20461
            let towards = by(range);
20462
            if (towards < from) {
20463
                event = "delete.backward";
20464
                towards = skipAtomic(target, towards, false);
20465
            }
20466
            else if (towards > from) {
20467
                event = "delete.forward";
20468
                towards = skipAtomic(target, towards, true);
20469
            }
20470
            from = Math.min(from, towards);
20471
            to = Math.max(to, towards);
20472
        }
20473
        else {
20474
            from = skipAtomic(target, from, false);
20475
            to = skipAtomic(target, to, true);
20476
        }
20477
        return from == to ? { range } : { changes: { from, to }, range: EditorSelection.cursor(from, from < range.head ? -1 : 1) };
20478
    });
20479
    if (changes.changes.empty)
20480
        return false;
20481
    target.dispatch(state.update(changes, {
20482
        scrollIntoView: true,
20483
        userEvent: event,
20484
        effects: event == "delete.selection" ? EditorView.announce.of(state.phrase("Selection deleted")) : undefined
20485
    }));
20486
    return true;
20487
}
20488
function skipAtomic(target, pos, forward) {
20489
    if (target instanceof EditorView)
20490
        for (let ranges of target.state.facet(EditorView.atomicRanges).map(f => f(target)))
20491
            ranges.between(pos, pos, (from, to) => {
20492
                if (from < pos && to > pos)
20493
                    pos = forward ? to : from;
20494
            });
20495
    return pos;
20496
}
20497
const deleteByChar = (target, forward) => deleteBy(target, range => {
20498
    let pos = range.from, { state } = target, line = state.doc.lineAt(pos), before, targetPos;
20499
    if (!forward && pos > line.from && pos < line.from + 200 &&
20500
        !/[^ \t]/.test(before = line.text.slice(0, pos - line.from))) {
20501
        if (before[before.length - 1] == "\t")
20502
            return pos - 1;
20503
        let col = countColumn(before, state.tabSize), drop = col % getIndentUnit(state) || getIndentUnit(state);
20504
        for (let i = 0; i < drop && before[before.length - 1 - i] == " "; i++)
20505
            pos--;
20506
        targetPos = pos;
20507
    }
20508
    else {
20509
        targetPos = findClusterBreak(line.text, pos - line.from, forward, forward) + line.from;
20510
        if (targetPos == pos && line.number != (forward ? state.doc.lines : 1))
20511
            targetPos += forward ? 1 : -1;
20512
        else if (!forward && /[\ufe00-\ufe0f]/.test(line.text.slice(targetPos - line.from, pos - line.from)))
20513
            targetPos = findClusterBreak(line.text, targetPos - line.from, false, false) + line.from;
20514
    }
20515
    return targetPos;
20516
});
20517
/**
20518
Delete the selection, or, for cursor selections, the character
20519
before the cursor.
20520
*/
20521
const deleteCharBackward = view => deleteByChar(view, false);
20522
/**
20523
Delete the selection or the character after the cursor.
20524
*/
20525
const deleteCharForward = view => deleteByChar(view, true);
20526
const deleteByGroup = (target, forward) => deleteBy(target, range => {
20527
    let pos = range.head, { state } = target, line = state.doc.lineAt(pos);
20528
    let categorize = state.charCategorizer(pos);
20529
    for (let cat = null;;) {
20530
        if (pos == (forward ? line.to : line.from)) {
20531
            if (pos == range.head && line.number != (forward ? state.doc.lines : 1))
20532
                pos += forward ? 1 : -1;
20533
            break;
20534
        }
20535
        let next = findClusterBreak(line.text, pos - line.from, forward) + line.from;
20536
        let nextChar = line.text.slice(Math.min(pos, next) - line.from, Math.max(pos, next) - line.from);
20537
        let nextCat = categorize(nextChar);
20538
        if (cat != null && nextCat != cat)
20539
            break;
20540
        if (nextChar != " " || pos != range.head)
20541
            cat = nextCat;
20542
        pos = next;
20543
    }
20544
    return pos;
20545
});
20546
/**
20547
Delete the selection or backward until the end of the next
20548
[group](https://codemirror.net/6/docs/ref/#view.EditorView.moveByGroup), only skipping groups of
20549
whitespace when they consist of a single space.
20550
*/
20551
const deleteGroupBackward = target => deleteByGroup(target, false);
20552
/**
20553
Delete the selection or forward until the end of the next group.
20554
*/
20555
const deleteGroupForward = target => deleteByGroup(target, true);
20556
/**
20557
Delete the selection, or, if it is a cursor selection, delete to
20558
the end of the line. If the cursor is directly at the end of the
20559
line, delete the line break after it.
20560
*/
20561
const deleteToLineEnd = view => deleteBy(view, range => {
20562
    let lineEnd = view.lineBlockAt(range.head).to;
20563
    return range.head < lineEnd ? lineEnd : Math.min(view.state.doc.length, range.head + 1);
20564
});
20565
/**
20566
Delete the selection, or, if it is a cursor selection, delete to
20567
the start of the line or the next line wrap before the cursor.
20568
*/
20569
const deleteLineBoundaryBackward = view => deleteBy(view, range => {
20570
    let lineStart = view.moveToLineBoundary(range, false).head;
20571
    return range.head > lineStart ? lineStart : Math.max(0, range.head - 1);
20572
});
20573
/**
20574
Delete the selection, or, if it is a cursor selection, delete to
20575
the end of the line or the next line wrap after the cursor.
20576
*/
20577
const deleteLineBoundaryForward = view => deleteBy(view, range => {
20578
    let lineStart = view.moveToLineBoundary(range, true).head;
20579
    return range.head < lineStart ? lineStart : Math.min(view.state.doc.length, range.head + 1);
20580
});
20581
/**
20582
Replace each selection range with a line break, leaving the cursor
20583
on the line before the break.
20584
*/
20585
const splitLine = ({ state, dispatch }) => {
20586
    if (state.readOnly)
20587
        return false;
20588
    let changes = state.changeByRange(range => {
20589
        return { changes: { from: range.from, to: range.to, insert: Text.of(["", ""]) },
20590
            range: EditorSelection.cursor(range.from) };
20591
    });
20592
    dispatch(state.update(changes, { scrollIntoView: true, userEvent: "input" }));
20593
    return true;
20594
};
20595
/**
20596
Flip the characters before and after the cursor(s).
20597
*/
20598
const transposeChars = ({ state, dispatch }) => {
20599
    if (state.readOnly)
20600
        return false;
20601
    let changes = state.changeByRange(range => {
20602
        if (!range.empty || range.from == 0 || range.from == state.doc.length)
20603
            return { range };
20604
        let pos = range.from, line = state.doc.lineAt(pos);
20605
        let from = pos == line.from ? pos - 1 : findClusterBreak(line.text, pos - line.from, false) + line.from;
20606
        let to = pos == line.to ? pos + 1 : findClusterBreak(line.text, pos - line.from, true) + line.from;
20607
        return { changes: { from, to, insert: state.doc.slice(pos, to).append(state.doc.slice(from, pos)) },
20608
            range: EditorSelection.cursor(to) };
20609
    });
20610
    if (changes.changes.empty)
20611
        return false;
20612
    dispatch(state.update(changes, { scrollIntoView: true, userEvent: "move.character" }));
20613
    return true;
20614
};
20615
function selectedLineBlocks(state) {
20616
    let blocks = [], upto = -1;
20617
    for (let range of state.selection.ranges) {
20618
        let startLine = state.doc.lineAt(range.from), endLine = state.doc.lineAt(range.to);
20619
        if (!range.empty && range.to == endLine.from)
20620
            endLine = state.doc.lineAt(range.to - 1);
20621
        if (upto >= startLine.number) {
20622
            let prev = blocks[blocks.length - 1];
20623
            prev.to = endLine.to;
20624
            prev.ranges.push(range);
20625
        }
20626
        else {
20627
            blocks.push({ from: startLine.from, to: endLine.to, ranges: [range] });
20628
        }
20629
        upto = endLine.number + 1;
20630
    }
20631
    return blocks;
20632
}
20633
function moveLine(state, dispatch, forward) {
20634
    if (state.readOnly)
20635
        return false;
20636
    let changes = [], ranges = [];
20637
    for (let block of selectedLineBlocks(state)) {
20638
        if (forward ? block.to == state.doc.length : block.from == 0)
20639
            continue;
20640
        let nextLine = state.doc.lineAt(forward ? block.to + 1 : block.from - 1);
20641
        let size = nextLine.length + 1;
20642
        if (forward) {
20643
            changes.push({ from: block.to, to: nextLine.to }, { from: block.from, insert: nextLine.text + state.lineBreak });
20644
            for (let r of block.ranges)
20645
                ranges.push(EditorSelection.range(Math.min(state.doc.length, r.anchor + size), Math.min(state.doc.length, r.head + size)));
20646
        }
20647
        else {
20648
            changes.push({ from: nextLine.from, to: block.from }, { from: block.to, insert: state.lineBreak + nextLine.text });
20649
            for (let r of block.ranges)
20650
                ranges.push(EditorSelection.range(r.anchor - size, r.head - size));
20651
        }
20652
    }
20653
    if (!changes.length)
20654
        return false;
20655
    dispatch(state.update({
20656
        changes,
20657
        scrollIntoView: true,
20658
        selection: EditorSelection.create(ranges, state.selection.mainIndex),
20659
        userEvent: "move.line"
20660
    }));
20661
    return true;
20662
}
20663
/**
20664
Move the selected lines up one line.
20665
*/
20666
const moveLineUp = ({ state, dispatch }) => moveLine(state, dispatch, false);
20667
/**
20668
Move the selected lines down one line.
20669
*/
20670
const moveLineDown = ({ state, dispatch }) => moveLine(state, dispatch, true);
20671
function copyLine(state, dispatch, forward) {
20672
    if (state.readOnly)
20673
        return false;
20674
    let changes = [];
20675
    for (let block of selectedLineBlocks(state)) {
20676
        if (forward)
20677
            changes.push({ from: block.from, insert: state.doc.slice(block.from, block.to) + state.lineBreak });
20678
        else
20679
            changes.push({ from: block.to, insert: state.lineBreak + state.doc.slice(block.from, block.to) });
20680
    }
20681
    dispatch(state.update({ changes, scrollIntoView: true, userEvent: "input.copyline" }));
20682
    return true;
20683
}
20684
/**
20685
Create a copy of the selected lines. Keep the selection in the top copy.
20686
*/
20687
const copyLineUp = ({ state, dispatch }) => copyLine(state, dispatch, false);
20688
/**
20689
Create a copy of the selected lines. Keep the selection in the bottom copy.
20690
*/
20691
const copyLineDown = ({ state, dispatch }) => copyLine(state, dispatch, true);
20692
/**
20693
Delete selected lines.
20694
*/
20695
const deleteLine = view => {
20696
    if (view.state.readOnly)
20697
        return false;
20698
    let { state } = view, changes = state.changes(selectedLineBlocks(state).map(({ from, to }) => {
20699
        if (from > 0)
20700
            from--;
20701
        else if (to < state.doc.length)
20702
            to++;
20703
        return { from, to };
20704
    }));
20705
    let selection = updateSel(state.selection, range => view.moveVertically(range, true)).map(changes);
20706
    view.dispatch({ changes, selection, scrollIntoView: true, userEvent: "delete.line" });
20707
    return true;
20708
};
20709
function isBetweenBrackets(state, pos) {
20710
    if (/\(\)|\[\]|\{\}/.test(state.sliceDoc(pos - 1, pos + 1)))
20711
        return { from: pos, to: pos };
20712
    let context = syntaxTree(state).resolveInner(pos);
20713
    let before = context.childBefore(pos), after = context.childAfter(pos), closedBy;
20714
    if (before && after && before.to <= pos && after.from >= pos &&
20715
        (closedBy = before.type.prop(NodeProp.closedBy)) && closedBy.indexOf(after.name) > -1 &&
20716
        state.doc.lineAt(before.to).from == state.doc.lineAt(after.from).from &&
20717
        !/\S/.test(state.sliceDoc(before.to, after.from)))
20718
        return { from: before.to, to: after.from };
20719
    return null;
20720
}
20721
/**
20722
Replace the selection with a newline and indent the newly created
20723
line(s). If the current line consists only of whitespace, this
20724
will also delete that whitespace. When the cursor is between
20725
matching brackets, an additional newline will be inserted after
20726
the cursor.
20727
*/
20728
const insertNewlineAndIndent = /*@__PURE__*/newlineAndIndent(false);
20729
/**
20730
Create a blank, indented line below the current line.
20731
*/
20732
const insertBlankLine = /*@__PURE__*/newlineAndIndent(true);
20733
function newlineAndIndent(atEof) {
20734
    return ({ state, dispatch }) => {
20735
        if (state.readOnly)
20736
            return false;
20737
        let changes = state.changeByRange(range => {
20738
            let { from, to } = range, line = state.doc.lineAt(from);
20739
            let explode = !atEof && from == to && isBetweenBrackets(state, from);
20740
            if (atEof)
20741
                from = to = (to <= line.to ? line : state.doc.lineAt(to)).to;
20742
            let cx = new IndentContext(state, { simulateBreak: from, simulateDoubleBreak: !!explode });
20743
            let indent = getIndentation(cx, from);
20744
            if (indent == null)
20745
                indent = countColumn(/^\s*/.exec(state.doc.lineAt(from).text)[0], state.tabSize);
20746
            while (to < line.to && /\s/.test(line.text[to - line.from]))
20747
                to++;
20748
            if (explode)
20749
                ({ from, to } = explode);
20750
            else if (from > line.from && from < line.from + 100 && !/\S/.test(line.text.slice(0, from)))
20751
                from = line.from;
20752
            let insert = ["", indentString(state, indent)];
20753
            if (explode)
20754
                insert.push(indentString(state, cx.lineIndent(line.from, -1)));
20755
            return { changes: { from, to, insert: Text.of(insert) },
20756
                range: EditorSelection.cursor(from + 1 + insert[1].length) };
20757
        });
20758
        dispatch(state.update(changes, { scrollIntoView: true, userEvent: "input" }));
20759
        return true;
20760
    };
20761
}
20762
function changeBySelectedLine(state, f) {
20763
    let atLine = -1;
20764
    return state.changeByRange(range => {
20765
        let changes = [];
20766
        for (let pos = range.from; pos <= range.to;) {
20767
            let line = state.doc.lineAt(pos);
20768
            if (line.number > atLine && (range.empty || range.to > line.from)) {
20769
                f(line, changes, range);
20770
                atLine = line.number;
20771
            }
20772
            pos = line.to + 1;
20773
        }
20774
        let changeSet = state.changes(changes);
20775
        return { changes,
20776
            range: EditorSelection.range(changeSet.mapPos(range.anchor, 1), changeSet.mapPos(range.head, 1)) };
20777
    });
20778
}
20779
/**
20780
Auto-indent the selected lines. This uses the [indentation service
20781
facet](https://codemirror.net/6/docs/ref/#language.indentService) as source for auto-indent
20782
information.
20783
*/
20784
const indentSelection = ({ state, dispatch }) => {
20785
    if (state.readOnly)
20786
        return false;
20787
    let updated = Object.create(null);
20788
    let context = new IndentContext(state, { overrideIndentation: start => {
20789
            let found = updated[start];
20790
            return found == null ? -1 : found;
20791
        } });
20792
    let changes = changeBySelectedLine(state, (line, changes, range) => {
20793
        let indent = getIndentation(context, line.from);
20794
        if (indent == null)
20795
            return;
20796
        if (!/\S/.test(line.text))
20797
            indent = 0;
20798
        let cur = /^\s*/.exec(line.text)[0];
20799
        let norm = indentString(state, indent);
20800
        if (cur != norm || range.from < line.from + cur.length) {
20801
            updated[line.from] = indent;
20802
            changes.push({ from: line.from, to: line.from + cur.length, insert: norm });
20803
        }
20804
    });
20805
    if (!changes.changes.empty)
20806
        dispatch(state.update(changes, { userEvent: "indent" }));
20807
    return true;
20808
};
20809
/**
20810
Add a [unit](https://codemirror.net/6/docs/ref/#language.indentUnit) of indentation to all selected
20811
lines.
20812
*/
20813
const indentMore = ({ state, dispatch }) => {
20814
    if (state.readOnly)
20815
        return false;
20816
    dispatch(state.update(changeBySelectedLine(state, (line, changes) => {
20817
        changes.push({ from: line.from, insert: state.facet(indentUnit) });
20818
    }), { userEvent: "input.indent" }));
20819
    return true;
20820
};
20821
/**
20822
Remove a [unit](https://codemirror.net/6/docs/ref/#language.indentUnit) of indentation from all
20823
selected lines.
20824
*/
20825
const indentLess = ({ state, dispatch }) => {
20826
    if (state.readOnly)
20827
        return false;
20828
    dispatch(state.update(changeBySelectedLine(state, (line, changes) => {
20829
        let space = /^\s*/.exec(line.text)[0];
20830
        if (!space)
20831
            return;
20832
        let col = countColumn(space, state.tabSize), keep = 0;
20833
        let insert = indentString(state, Math.max(0, col - getIndentUnit(state)));
20834
        while (keep < space.length && keep < insert.length && space.charCodeAt(keep) == insert.charCodeAt(keep))
20835
            keep++;
20836
        changes.push({ from: line.from + keep, to: line.from + space.length, insert: insert.slice(keep) });
20837
    }), { userEvent: "delete.dedent" }));
20838
    return true;
20839
};
20840
/**
20841
Array of key bindings containing the Emacs-style bindings that are
20842
available on macOS by default.
20843
 
20844
 - Ctrl-b: [`cursorCharLeft`](https://codemirror.net/6/docs/ref/#commands.cursorCharLeft) ([`selectCharLeft`](https://codemirror.net/6/docs/ref/#commands.selectCharLeft) with Shift)
20845
 - Ctrl-f: [`cursorCharRight`](https://codemirror.net/6/docs/ref/#commands.cursorCharRight) ([`selectCharRight`](https://codemirror.net/6/docs/ref/#commands.selectCharRight) with Shift)
20846
 - Ctrl-p: [`cursorLineUp`](https://codemirror.net/6/docs/ref/#commands.cursorLineUp) ([`selectLineUp`](https://codemirror.net/6/docs/ref/#commands.selectLineUp) with Shift)
20847
 - Ctrl-n: [`cursorLineDown`](https://codemirror.net/6/docs/ref/#commands.cursorLineDown) ([`selectLineDown`](https://codemirror.net/6/docs/ref/#commands.selectLineDown) with Shift)
20848
 - Ctrl-a: [`cursorLineStart`](https://codemirror.net/6/docs/ref/#commands.cursorLineStart) ([`selectLineStart`](https://codemirror.net/6/docs/ref/#commands.selectLineStart) with Shift)
20849
 - Ctrl-e: [`cursorLineEnd`](https://codemirror.net/6/docs/ref/#commands.cursorLineEnd) ([`selectLineEnd`](https://codemirror.net/6/docs/ref/#commands.selectLineEnd) with Shift)
20850
 - Ctrl-d: [`deleteCharForward`](https://codemirror.net/6/docs/ref/#commands.deleteCharForward)
20851
 - Ctrl-h: [`deleteCharBackward`](https://codemirror.net/6/docs/ref/#commands.deleteCharBackward)
20852
 - Ctrl-k: [`deleteToLineEnd`](https://codemirror.net/6/docs/ref/#commands.deleteToLineEnd)
20853
 - Ctrl-Alt-h: [`deleteGroupBackward`](https://codemirror.net/6/docs/ref/#commands.deleteGroupBackward)
20854
 - Ctrl-o: [`splitLine`](https://codemirror.net/6/docs/ref/#commands.splitLine)
20855
 - Ctrl-t: [`transposeChars`](https://codemirror.net/6/docs/ref/#commands.transposeChars)
20856
 - Ctrl-v: [`cursorPageDown`](https://codemirror.net/6/docs/ref/#commands.cursorPageDown)
20857
 - Alt-v: [`cursorPageUp`](https://codemirror.net/6/docs/ref/#commands.cursorPageUp)
20858
*/
20859
const emacsStyleKeymap = [
20860
    { key: "Ctrl-b", run: cursorCharLeft, shift: selectCharLeft, preventDefault: true },
20861
    { key: "Ctrl-f", run: cursorCharRight, shift: selectCharRight },
20862
    { key: "Ctrl-p", run: cursorLineUp, shift: selectLineUp },
20863
    { key: "Ctrl-n", run: cursorLineDown, shift: selectLineDown },
20864
    { key: "Ctrl-a", run: cursorLineStart, shift: selectLineStart },
20865
    { key: "Ctrl-e", run: cursorLineEnd, shift: selectLineEnd },
20866
    { key: "Ctrl-d", run: deleteCharForward },
20867
    { key: "Ctrl-h", run: deleteCharBackward },
20868
    { key: "Ctrl-k", run: deleteToLineEnd },
20869
    { key: "Ctrl-Alt-h", run: deleteGroupBackward },
20870
    { key: "Ctrl-o", run: splitLine },
20871
    { key: "Ctrl-t", run: transposeChars },
20872
    { key: "Ctrl-v", run: cursorPageDown },
20873
];
20874
/**
20875
An array of key bindings closely sticking to platform-standard or
20876
widely used bindings. (This includes the bindings from
20877
[`emacsStyleKeymap`](https://codemirror.net/6/docs/ref/#commands.emacsStyleKeymap), with their `key`
20878
property changed to `mac`.)
20879
 
20880
 - ArrowLeft: [`cursorCharLeft`](https://codemirror.net/6/docs/ref/#commands.cursorCharLeft) ([`selectCharLeft`](https://codemirror.net/6/docs/ref/#commands.selectCharLeft) with Shift)
20881
 - ArrowRight: [`cursorCharRight`](https://codemirror.net/6/docs/ref/#commands.cursorCharRight) ([`selectCharRight`](https://codemirror.net/6/docs/ref/#commands.selectCharRight) with Shift)
20882
 - Ctrl-ArrowLeft (Alt-ArrowLeft on macOS): [`cursorGroupLeft`](https://codemirror.net/6/docs/ref/#commands.cursorGroupLeft) ([`selectGroupLeft`](https://codemirror.net/6/docs/ref/#commands.selectGroupLeft) with Shift)
20883
 - Ctrl-ArrowRight (Alt-ArrowRight on macOS): [`cursorGroupRight`](https://codemirror.net/6/docs/ref/#commands.cursorGroupRight) ([`selectGroupRight`](https://codemirror.net/6/docs/ref/#commands.selectGroupRight) with Shift)
20884
 - Cmd-ArrowLeft (on macOS): [`cursorLineStart`](https://codemirror.net/6/docs/ref/#commands.cursorLineStart) ([`selectLineStart`](https://codemirror.net/6/docs/ref/#commands.selectLineStart) with Shift)
20885
 - Cmd-ArrowRight (on macOS): [`cursorLineEnd`](https://codemirror.net/6/docs/ref/#commands.cursorLineEnd) ([`selectLineEnd`](https://codemirror.net/6/docs/ref/#commands.selectLineEnd) with Shift)
20886
 - ArrowUp: [`cursorLineUp`](https://codemirror.net/6/docs/ref/#commands.cursorLineUp) ([`selectLineUp`](https://codemirror.net/6/docs/ref/#commands.selectLineUp) with Shift)
20887
 - ArrowDown: [`cursorLineDown`](https://codemirror.net/6/docs/ref/#commands.cursorLineDown) ([`selectLineDown`](https://codemirror.net/6/docs/ref/#commands.selectLineDown) with Shift)
20888
 - Cmd-ArrowUp (on macOS): [`cursorDocStart`](https://codemirror.net/6/docs/ref/#commands.cursorDocStart) ([`selectDocStart`](https://codemirror.net/6/docs/ref/#commands.selectDocStart) with Shift)
20889
 - Cmd-ArrowDown (on macOS): [`cursorDocEnd`](https://codemirror.net/6/docs/ref/#commands.cursorDocEnd) ([`selectDocEnd`](https://codemirror.net/6/docs/ref/#commands.selectDocEnd) with Shift)
20890
 - Ctrl-ArrowUp (on macOS): [`cursorPageUp`](https://codemirror.net/6/docs/ref/#commands.cursorPageUp) ([`selectPageUp`](https://codemirror.net/6/docs/ref/#commands.selectPageUp) with Shift)
20891
 - Ctrl-ArrowDown (on macOS): [`cursorPageDown`](https://codemirror.net/6/docs/ref/#commands.cursorPageDown) ([`selectPageDown`](https://codemirror.net/6/docs/ref/#commands.selectPageDown) with Shift)
20892
 - PageUp: [`cursorPageUp`](https://codemirror.net/6/docs/ref/#commands.cursorPageUp) ([`selectPageUp`](https://codemirror.net/6/docs/ref/#commands.selectPageUp) with Shift)
20893
 - PageDown: [`cursorPageDown`](https://codemirror.net/6/docs/ref/#commands.cursorPageDown) ([`selectPageDown`](https://codemirror.net/6/docs/ref/#commands.selectPageDown) with Shift)
20894
 - Home: [`cursorLineBoundaryBackward`](https://codemirror.net/6/docs/ref/#commands.cursorLineBoundaryBackward) ([`selectLineBoundaryBackward`](https://codemirror.net/6/docs/ref/#commands.selectLineBoundaryBackward) with Shift)
20895
 - End: [`cursorLineBoundaryForward`](https://codemirror.net/6/docs/ref/#commands.cursorLineBoundaryForward) ([`selectLineBoundaryForward`](https://codemirror.net/6/docs/ref/#commands.selectLineBoundaryForward) with Shift)
20896
 - Ctrl-Home (Cmd-Home on macOS): [`cursorDocStart`](https://codemirror.net/6/docs/ref/#commands.cursorDocStart) ([`selectDocStart`](https://codemirror.net/6/docs/ref/#commands.selectDocStart) with Shift)
20897
 - Ctrl-End (Cmd-Home on macOS): [`cursorDocEnd`](https://codemirror.net/6/docs/ref/#commands.cursorDocEnd) ([`selectDocEnd`](https://codemirror.net/6/docs/ref/#commands.selectDocEnd) with Shift)
20898
 - Enter: [`insertNewlineAndIndent`](https://codemirror.net/6/docs/ref/#commands.insertNewlineAndIndent)
20899
 - Ctrl-a (Cmd-a on macOS): [`selectAll`](https://codemirror.net/6/docs/ref/#commands.selectAll)
20900
 - Backspace: [`deleteCharBackward`](https://codemirror.net/6/docs/ref/#commands.deleteCharBackward)
20901
 - Delete: [`deleteCharForward`](https://codemirror.net/6/docs/ref/#commands.deleteCharForward)
20902
 - Ctrl-Backspace (Alt-Backspace on macOS): [`deleteGroupBackward`](https://codemirror.net/6/docs/ref/#commands.deleteGroupBackward)
20903
 - Ctrl-Delete (Alt-Delete on macOS): [`deleteGroupForward`](https://codemirror.net/6/docs/ref/#commands.deleteGroupForward)
20904
 - Cmd-Backspace (macOS): [`deleteLineBoundaryBackward`](https://codemirror.net/6/docs/ref/#commands.deleteLineBoundaryBackward).
20905
 - Cmd-Delete (macOS): [`deleteLineBoundaryForward`](https://codemirror.net/6/docs/ref/#commands.deleteLineBoundaryForward).
20906
*/
20907
const standardKeymap = /*@__PURE__*/[
20908
    { key: "ArrowLeft", run: cursorCharLeft, shift: selectCharLeft, preventDefault: true },
20909
    { key: "Mod-ArrowLeft", mac: "Alt-ArrowLeft", run: cursorGroupLeft, shift: selectGroupLeft, preventDefault: true },
20910
    { mac: "Cmd-ArrowLeft", run: cursorLineBoundaryLeft, shift: selectLineBoundaryLeft, preventDefault: true },
20911
    { key: "ArrowRight", run: cursorCharRight, shift: selectCharRight, preventDefault: true },
20912
    { key: "Mod-ArrowRight", mac: "Alt-ArrowRight", run: cursorGroupRight, shift: selectGroupRight, preventDefault: true },
20913
    { mac: "Cmd-ArrowRight", run: cursorLineBoundaryRight, shift: selectLineBoundaryRight, preventDefault: true },
20914
    { key: "ArrowUp", run: cursorLineUp, shift: selectLineUp, preventDefault: true },
20915
    { mac: "Cmd-ArrowUp", run: cursorDocStart, shift: selectDocStart },
20916
    { mac: "Ctrl-ArrowUp", run: cursorPageUp, shift: selectPageUp },
20917
    { key: "ArrowDown", run: cursorLineDown, shift: selectLineDown, preventDefault: true },
20918
    { mac: "Cmd-ArrowDown", run: cursorDocEnd, shift: selectDocEnd },
20919
    { mac: "Ctrl-ArrowDown", run: cursorPageDown, shift: selectPageDown },
20920
    { key: "PageUp", run: cursorPageUp, shift: selectPageUp },
20921
    { key: "PageDown", run: cursorPageDown, shift: selectPageDown },
20922
    { key: "Home", run: cursorLineBoundaryBackward, shift: selectLineBoundaryBackward, preventDefault: true },
20923
    { key: "Mod-Home", run: cursorDocStart, shift: selectDocStart },
20924
    { key: "End", run: cursorLineBoundaryForward, shift: selectLineBoundaryForward, preventDefault: true },
20925
    { key: "Mod-End", run: cursorDocEnd, shift: selectDocEnd },
20926
    { key: "Enter", run: insertNewlineAndIndent },
20927
    { key: "Mod-a", run: selectAll },
20928
    { key: "Backspace", run: deleteCharBackward, shift: deleteCharBackward },
20929
    { key: "Delete", run: deleteCharForward },
20930
    { key: "Mod-Backspace", mac: "Alt-Backspace", run: deleteGroupBackward },
20931
    { key: "Mod-Delete", mac: "Alt-Delete", run: deleteGroupForward },
20932
    { mac: "Mod-Backspace", run: deleteLineBoundaryBackward },
20933
    { mac: "Mod-Delete", run: deleteLineBoundaryForward }
20934
].concat(/*@__PURE__*/emacsStyleKeymap.map(b => ({ mac: b.key, run: b.run, shift: b.shift })));
20935
/**
20936
The default keymap. Includes all bindings from
20937
[`standardKeymap`](https://codemirror.net/6/docs/ref/#commands.standardKeymap) plus the following:
20938
 
20939
- Alt-ArrowLeft (Ctrl-ArrowLeft on macOS): [`cursorSyntaxLeft`](https://codemirror.net/6/docs/ref/#commands.cursorSyntaxLeft) ([`selectSyntaxLeft`](https://codemirror.net/6/docs/ref/#commands.selectSyntaxLeft) with Shift)
20940
- Alt-ArrowRight (Ctrl-ArrowRight on macOS): [`cursorSyntaxRight`](https://codemirror.net/6/docs/ref/#commands.cursorSyntaxRight) ([`selectSyntaxRight`](https://codemirror.net/6/docs/ref/#commands.selectSyntaxRight) with Shift)
20941
- Alt-ArrowUp: [`moveLineUp`](https://codemirror.net/6/docs/ref/#commands.moveLineUp)
20942
- Alt-ArrowDown: [`moveLineDown`](https://codemirror.net/6/docs/ref/#commands.moveLineDown)
20943
- Shift-Alt-ArrowUp: [`copyLineUp`](https://codemirror.net/6/docs/ref/#commands.copyLineUp)
20944
- Shift-Alt-ArrowDown: [`copyLineDown`](https://codemirror.net/6/docs/ref/#commands.copyLineDown)
20945
- Escape: [`simplifySelection`](https://codemirror.net/6/docs/ref/#commands.simplifySelection)
20946
- Ctrl-Enter (Cmd-Enter on macOS): [`insertBlankLine`](https://codemirror.net/6/docs/ref/#commands.insertBlankLine)
20947
- Alt-l (Ctrl-l on macOS): [`selectLine`](https://codemirror.net/6/docs/ref/#commands.selectLine)
20948
- Ctrl-i (Cmd-i on macOS): [`selectParentSyntax`](https://codemirror.net/6/docs/ref/#commands.selectParentSyntax)
20949
- Ctrl-[ (Cmd-[ on macOS): [`indentLess`](https://codemirror.net/6/docs/ref/#commands.indentLess)
20950
- Ctrl-] (Cmd-] on macOS): [`indentMore`](https://codemirror.net/6/docs/ref/#commands.indentMore)
20951
- Ctrl-Alt-\\ (Cmd-Alt-\\ on macOS): [`indentSelection`](https://codemirror.net/6/docs/ref/#commands.indentSelection)
20952
- Shift-Ctrl-k (Shift-Cmd-k on macOS): [`deleteLine`](https://codemirror.net/6/docs/ref/#commands.deleteLine)
20953
- Shift-Ctrl-\\ (Shift-Cmd-\\ on macOS): [`cursorMatchingBracket`](https://codemirror.net/6/docs/ref/#commands.cursorMatchingBracket)
20954
- Ctrl-/ (Cmd-/ on macOS): [`toggleComment`](https://codemirror.net/6/docs/ref/#commands.toggleComment).
20955
- Shift-Alt-a: [`toggleBlockComment`](https://codemirror.net/6/docs/ref/#commands.toggleBlockComment).
20956
*/
20957
const defaultKeymap = /*@__PURE__*/[
20958
    { key: "Alt-ArrowLeft", mac: "Ctrl-ArrowLeft", run: cursorSyntaxLeft, shift: selectSyntaxLeft },
20959
    { key: "Alt-ArrowRight", mac: "Ctrl-ArrowRight", run: cursorSyntaxRight, shift: selectSyntaxRight },
20960
    { key: "Alt-ArrowUp", run: moveLineUp },
20961
    { key: "Shift-Alt-ArrowUp", run: copyLineUp },
20962
    { key: "Alt-ArrowDown", run: moveLineDown },
20963
    { key: "Shift-Alt-ArrowDown", run: copyLineDown },
20964
    { key: "Escape", run: simplifySelection },
20965
    { key: "Mod-Enter", run: insertBlankLine },
20966
    { key: "Alt-l", mac: "Ctrl-l", run: selectLine },
20967
    { key: "Mod-i", run: selectParentSyntax, preventDefault: true },
20968
    { key: "Mod-[", run: indentLess },
20969
    { key: "Mod-]", run: indentMore },
20970
    { key: "Mod-Alt-\\", run: indentSelection },
20971
    { key: "Shift-Mod-k", run: deleteLine },
20972
    { key: "Shift-Mod-\\", run: cursorMatchingBracket },
20973
    { key: "Mod-/", run: toggleComment },
20974
    { key: "Alt-A", run: toggleBlockComment }
20975
].concat(standardKeymap);
20976
 
20977
function crelt() {
20978
  var elt = arguments[0];
20979
  if (typeof elt == "string") elt = document.createElement(elt);
20980
  var i = 1, next = arguments[1];
20981
  if (next && typeof next == "object" && next.nodeType == null && !Array.isArray(next)) {
20982
    for (var name in next) if (Object.prototype.hasOwnProperty.call(next, name)) {
20983
      var value = next[name];
20984
      if (typeof value == "string") elt.setAttribute(name, value);
20985
      else if (value != null) elt[name] = value;
20986
    }
20987
    i++;
20988
  }
20989
  for (; i < arguments.length; i++) add(elt, arguments[i]);
20990
  return elt
20991
}
20992
 
20993
function add(elt, child) {
20994
  if (typeof child == "string") {
20995
    elt.appendChild(document.createTextNode(child));
20996
  } else if (child == null) ; else if (child.nodeType != null) {
20997
    elt.appendChild(child);
20998
  } else if (Array.isArray(child)) {
20999
    for (var i = 0; i < child.length; i++) add(elt, child[i]);
21000
  } else {
21001
    throw new RangeError("Unsupported child node: " + child)
21002
  }
21003
}
21004
 
21005
const basicNormalize = typeof String.prototype.normalize == "function"
21006
    ? x => x.normalize("NFKD") : x => x;
21007
/**
21008
A search cursor provides an iterator over text matches in a
21009
document.
21010
*/
21011
class SearchCursor {
21012
    /**
21013
    Create a text cursor. The query is the search string, `from` to
21014
    `to` provides the region to search.
21015
 
21016
    When `normalize` is given, it will be called, on both the query
21017
    string and the content it is matched against, before comparing.
21018
    You can, for example, create a case-insensitive search by
21019
    passing `s => s.toLowerCase()`.
21020
 
21021
    Text is always normalized with
21022
    [`.normalize("NFKD")`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/normalize)
21023
    (when supported).
21024
    */
21025
    constructor(text, query, from = 0, to = text.length, normalize, test) {
21026
        this.test = test;
21027
        /**
21028
        The current match (only holds a meaningful value after
21029
        [`next`](https://codemirror.net/6/docs/ref/#search.SearchCursor.next) has been called and when
21030
        `done` is false).
21031
        */
21032
        this.value = { from: 0, to: 0 };
21033
        /**
21034
        Whether the end of the iterated region has been reached.
21035
        */
21036
        this.done = false;
21037
        this.matches = [];
21038
        this.buffer = "";
21039
        this.bufferPos = 0;
21040
        this.iter = text.iterRange(from, to);
21041
        this.bufferStart = from;
21042
        this.normalize = normalize ? x => normalize(basicNormalize(x)) : basicNormalize;
21043
        this.query = this.normalize(query);
21044
    }
21045
    peek() {
21046
        if (this.bufferPos == this.buffer.length) {
21047
            this.bufferStart += this.buffer.length;
21048
            this.iter.next();
21049
            if (this.iter.done)
21050
                return -1;
21051
            this.bufferPos = 0;
21052
            this.buffer = this.iter.value;
21053
        }
21054
        return codePointAt(this.buffer, this.bufferPos);
21055
    }
21056
    /**
21057
    Look for the next match. Updates the iterator's
21058
    [`value`](https://codemirror.net/6/docs/ref/#search.SearchCursor.value) and
21059
    [`done`](https://codemirror.net/6/docs/ref/#search.SearchCursor.done) properties. Should be called
21060
    at least once before using the cursor.
21061
    */
21062
    next() {
21063
        while (this.matches.length)
21064
            this.matches.pop();
21065
        return this.nextOverlapping();
21066
    }
21067
    /**
21068
    The `next` method will ignore matches that partially overlap a
21069
    previous match. This method behaves like `next`, but includes
21070
    such matches.
21071
    */
21072
    nextOverlapping() {
21073
        for (;;) {
21074
            let next = this.peek();
21075
            if (next < 0) {
21076
                this.done = true;
21077
                return this;
21078
            }
21079
            let str = fromCodePoint(next), start = this.bufferStart + this.bufferPos;
21080
            this.bufferPos += codePointSize(next);
21081
            let norm = this.normalize(str);
21082
            for (let i = 0, pos = start;; i++) {
21083
                let code = norm.charCodeAt(i);
21084
                let match = this.match(code, pos, this.bufferPos + this.bufferStart);
21085
                if (i == norm.length - 1) {
21086
                    if (match) {
21087
                        this.value = match;
21088
                        return this;
21089
                    }
21090
                    break;
21091
                }
21092
                if (pos == start && i < str.length && str.charCodeAt(i) == code)
21093
                    pos++;
21094
            }
21095
        }
21096
    }
21097
    match(code, pos, end) {
21098
        let match = null;
21099
        for (let i = 0; i < this.matches.length; i += 2) {
21100
            let index = this.matches[i], keep = false;
21101
            if (this.query.charCodeAt(index) == code) {
21102
                if (index == this.query.length - 1) {
21103
                    match = { from: this.matches[i + 1], to: end };
21104
                }
21105
                else {
21106
                    this.matches[i]++;
21107
                    keep = true;
21108
                }
21109
            }
21110
            if (!keep) {
21111
                this.matches.splice(i, 2);
21112
                i -= 2;
21113
            }
21114
        }
21115
        if (this.query.charCodeAt(0) == code) {
21116
            if (this.query.length == 1)
21117
                match = { from: pos, to: end };
21118
            else
21119
                this.matches.push(1, pos);
21120
        }
21121
        if (match && this.test && !this.test(match.from, match.to, this.buffer, this.bufferStart))
21122
            match = null;
21123
        return match;
21124
    }
21125
}
21126
if (typeof Symbol != "undefined")
21127
    SearchCursor.prototype[Symbol.iterator] = function () { return this; };
21128
 
21129
const empty = { from: -1, to: -1, match: /*@__PURE__*//.*/.exec("") };
21130
const baseFlags = "gm" + (/x/.unicode == null ? "" : "u");
21131
/**
21132
This class is similar to [`SearchCursor`](https://codemirror.net/6/docs/ref/#search.SearchCursor)
21133
but searches for a regular expression pattern instead of a plain
21134
string.
21135
*/
21136
class RegExpCursor {
21137
    /**
21138
    Create a cursor that will search the given range in the given
21139
    document. `query` should be the raw pattern (as you'd pass it to
21140
    `new RegExp`).
21141
    */
21142
    constructor(text, query, options, from = 0, to = text.length) {
21143
        this.text = text;
21144
        this.to = to;
21145
        this.curLine = "";
21146
        /**
21147
        Set to `true` when the cursor has reached the end of the search
21148
        range.
21149
        */
21150
        this.done = false;
21151
        /**
21152
        Will contain an object with the extent of the match and the
21153
        match object when [`next`](https://codemirror.net/6/docs/ref/#search.RegExpCursor.next)
21154
        sucessfully finds a match.
21155
        */
21156
        this.value = empty;
21157
        if (/\\[sWDnr]|\n|\r|\[\^/.test(query))
21158
            return new MultilineRegExpCursor(text, query, options, from, to);
21159
        this.re = new RegExp(query, baseFlags + ((options === null || options === void 0 ? void 0 : options.ignoreCase) ? "i" : ""));
21160
        this.test = options === null || options === void 0 ? void 0 : options.test;
21161
        this.iter = text.iter();
21162
        let startLine = text.lineAt(from);
21163
        this.curLineStart = startLine.from;
21164
        this.matchPos = toCharEnd(text, from);
21165
        this.getLine(this.curLineStart);
21166
    }
21167
    getLine(skip) {
21168
        this.iter.next(skip);
21169
        if (this.iter.lineBreak) {
21170
            this.curLine = "";
21171
        }
21172
        else {
21173
            this.curLine = this.iter.value;
21174
            if (this.curLineStart + this.curLine.length > this.to)
21175
                this.curLine = this.curLine.slice(0, this.to - this.curLineStart);
21176
            this.iter.next();
21177
        }
21178
    }
21179
    nextLine() {
21180
        this.curLineStart = this.curLineStart + this.curLine.length + 1;
21181
        if (this.curLineStart > this.to)
21182
            this.curLine = "";
21183
        else
21184
            this.getLine(0);
21185
    }
21186
    /**
21187
    Move to the next match, if there is one.
21188
    */
21189
    next() {
21190
        for (let off = this.matchPos - this.curLineStart;;) {
21191
            this.re.lastIndex = off;
21192
            let match = this.matchPos <= this.to && this.re.exec(this.curLine);
21193
            if (match) {
21194
                let from = this.curLineStart + match.index, to = from + match[0].length;
21195
                this.matchPos = toCharEnd(this.text, to + (from == to ? 1 : 0));
21196
                if (from == this.curLineStart + this.curLine.length)
21197
                    this.nextLine();
21198
                if ((from < to || from > this.value.to) && (!this.test || this.test(from, to, match))) {
21199
                    this.value = { from, to, match };
21200
                    return this;
21201
                }
21202
                off = this.matchPos - this.curLineStart;
21203
            }
21204
            else if (this.curLineStart + this.curLine.length < this.to) {
21205
                this.nextLine();
21206
                off = 0;
21207
            }
21208
            else {
21209
                this.done = true;
21210
                return this;
21211
            }
21212
        }
21213
    }
21214
}
21215
const flattened = /*@__PURE__*/new WeakMap();
21216
// Reusable (partially) flattened document strings
21217
class FlattenedDoc {
21218
    constructor(from, text) {
21219
        this.from = from;
21220
        this.text = text;
21221
    }
21222
    get to() { return this.from + this.text.length; }
21223
    static get(doc, from, to) {
21224
        let cached = flattened.get(doc);
21225
        if (!cached || cached.from >= to || cached.to <= from) {
21226
            let flat = new FlattenedDoc(from, doc.sliceString(from, to));
21227
            flattened.set(doc, flat);
21228
            return flat;
21229
        }
21230
        if (cached.from == from && cached.to == to)
21231
            return cached;
21232
        let { text, from: cachedFrom } = cached;
21233
        if (cachedFrom > from) {
21234
            text = doc.sliceString(from, cachedFrom) + text;
21235
            cachedFrom = from;
21236
        }
21237
        if (cached.to < to)
21238
            text += doc.sliceString(cached.to, to);
21239
        flattened.set(doc, new FlattenedDoc(cachedFrom, text));
21240
        return new FlattenedDoc(from, text.slice(from - cachedFrom, to - cachedFrom));
21241
    }
21242
}
21243
class MultilineRegExpCursor {
21244
    constructor(text, query, options, from, to) {
21245
        this.text = text;
21246
        this.to = to;
21247
        this.done = false;
21248
        this.value = empty;
21249
        this.matchPos = toCharEnd(text, from);
21250
        this.re = new RegExp(query, baseFlags + ((options === null || options === void 0 ? void 0 : options.ignoreCase) ? "i" : ""));
21251
        this.test = options === null || options === void 0 ? void 0 : options.test;
21252
        this.flat = FlattenedDoc.get(text, from, this.chunkEnd(from + 5000 /* Chunk.Base */));
21253
    }
21254
    chunkEnd(pos) {
21255
        return pos >= this.to ? this.to : this.text.lineAt(pos).to;
21256
    }
21257
    next() {
21258
        for (;;) {
21259
            let off = this.re.lastIndex = this.matchPos - this.flat.from;
21260
            let match = this.re.exec(this.flat.text);
21261
            // Skip empty matches directly after the last match
21262
            if (match && !match[0] && match.index == off) {
21263
                this.re.lastIndex = off + 1;
21264
                match = this.re.exec(this.flat.text);
21265
            }
21266
            if (match) {
21267
                let from = this.flat.from + match.index, to = from + match[0].length;
21268
                // If a match goes almost to the end of a noncomplete chunk, try
21269
                // again, since it'll likely be able to match more
21270
                if ((this.flat.to >= this.to || match.index + match[0].length <= this.flat.text.length - 10) &&
21271
                    (!this.test || this.test(from, to, match))) {
21272
                    this.value = { from, to, match };
21273
                    this.matchPos = toCharEnd(this.text, to + (from == to ? 1 : 0));
21274
                    return this;
21275
                }
21276
            }
21277
            if (this.flat.to == this.to) {
21278
                this.done = true;
21279
                return this;
21280
            }
21281
            // Grow the flattened doc
21282
            this.flat = FlattenedDoc.get(this.text, this.flat.from, this.chunkEnd(this.flat.from + this.flat.text.length * 2));
21283
        }
21284
    }
21285
}
21286
if (typeof Symbol != "undefined") {
21287
    RegExpCursor.prototype[Symbol.iterator] = MultilineRegExpCursor.prototype[Symbol.iterator] =
21288
        function () { return this; };
21289
}
21290
function validRegExp(source) {
21291
    try {
21292
        new RegExp(source, baseFlags);
21293
        return true;
21294
    }
21295
    catch (_a) {
21296
        return false;
21297
    }
21298
}
21299
function toCharEnd(text, pos) {
21300
    if (pos >= text.length)
21301
        return pos;
21302
    let line = text.lineAt(pos), next;
21303
    while (pos < line.to && (next = line.text.charCodeAt(pos - line.from)) >= 0xDC00 && next < 0xE000)
21304
        pos++;
21305
    return pos;
21306
}
21307
 
21308
function createLineDialog(view) {
21309
    let line = String(view.state.doc.lineAt(view.state.selection.main.head).number);
21310
    let input = crelt("input", { class: "cm-textfield", name: "line", value: line });
21311
    let dom = crelt("form", {
21312
        class: "cm-gotoLine",
21313
        onkeydown: (event) => {
21314
            if (event.keyCode == 27) { // Escape
21315
                event.preventDefault();
21316
                view.dispatch({ effects: dialogEffect.of(false) });
21317
                view.focus();
21318
            }
21319
            else if (event.keyCode == 13) { // Enter
21320
                event.preventDefault();
21321
                go();
21322
            }
21323
        },
21324
        onsubmit: (event) => {
21325
            event.preventDefault();
21326
            go();
21327
        }
21328
    }, crelt("label", view.state.phrase("Go to line"), ": ", input), " ", crelt("button", { class: "cm-button", type: "submit" }, view.state.phrase("go")));
21329
    function go() {
21330
        let match = /^([+-])?(\d+)?(:\d+)?(%)?$/.exec(input.value);
21331
        if (!match)
21332
            return;
21333
        let { state } = view, startLine = state.doc.lineAt(state.selection.main.head);
21334
        let [, sign, ln, cl, percent] = match;
21335
        let col = cl ? +cl.slice(1) : 0;
21336
        let line = ln ? +ln : startLine.number;
21337
        if (ln && percent) {
21338
            let pc = line / 100;
21339
            if (sign)
21340
                pc = pc * (sign == "-" ? -1 : 1) + (startLine.number / state.doc.lines);
21341
            line = Math.round(state.doc.lines * pc);
21342
        }
21343
        else if (ln && sign) {
21344
            line = line * (sign == "-" ? -1 : 1) + startLine.number;
21345
        }
21346
        let docLine = state.doc.line(Math.max(1, Math.min(state.doc.lines, line)));
21347
        let selection = EditorSelection.cursor(docLine.from + Math.max(0, Math.min(col, docLine.length)));
21348
        view.dispatch({
21349
            effects: [dialogEffect.of(false), EditorView.scrollIntoView(selection.from, { y: 'center' })],
21350
            selection,
21351
        });
21352
        view.focus();
21353
    }
21354
    return { dom };
21355
}
21356
const dialogEffect = /*@__PURE__*/StateEffect.define();
21357
const dialogField = /*@__PURE__*/StateField.define({
21358
    create() { return true; },
21359
    update(value, tr) {
21360
        for (let e of tr.effects)
21361
            if (e.is(dialogEffect))
21362
                value = e.value;
21363
        return value;
21364
    },
21365
    provide: f => showPanel.from(f, val => val ? createLineDialog : null)
21366
});
21367
/**
21368
Command that shows a dialog asking the user for a line number, and
21369
when a valid position is provided, moves the cursor to that line.
21370
 
21371
Supports line numbers, relative line offsets prefixed with `+` or
21372
`-`, document percentages suffixed with `%`, and an optional
21373
column position by adding `:` and a second number after the line
21374
number.
21375
*/
21376
const gotoLine = view => {
21377
    let panel = getPanel(view, createLineDialog);
21378
    if (!panel) {
21379
        let effects = [dialogEffect.of(true)];
21380
        if (view.state.field(dialogField, false) == null)
21381
            effects.push(StateEffect.appendConfig.of([dialogField, baseTheme$1$1]));
21382
        view.dispatch({ effects });
21383
        panel = getPanel(view, createLineDialog);
21384
    }
21385
    if (panel)
21386
        panel.dom.querySelector("input").select();
21387
    return true;
21388
};
21389
const baseTheme$1$1 = /*@__PURE__*/EditorView.baseTheme({
21390
    ".cm-panel.cm-gotoLine": {
21391
        padding: "2px 6px 4px",
21392
        "& label": { fontSize: "80%" }
21393
    }
21394
});
21395
 
21396
const defaultHighlightOptions = {
21397
    highlightWordAroundCursor: false,
21398
    minSelectionLength: 1,
21399
    maxMatches: 100,
21400
    wholeWords: false
21401
};
21402
const highlightConfig = /*@__PURE__*/Facet.define({
21403
    combine(options) {
21404
        return combineConfig(options, defaultHighlightOptions, {
21405
            highlightWordAroundCursor: (a, b) => a || b,
21406
            minSelectionLength: Math.min,
21407
            maxMatches: Math.min
21408
        });
21409
    }
21410
});
21411
/**
21412
This extension highlights text that matches the selection. It uses
21413
the `"cm-selectionMatch"` class for the highlighting. When
21414
`highlightWordAroundCursor` is enabled, the word at the cursor
21415
itself will be highlighted with `"cm-selectionMatch-main"`.
21416
*/
21417
function highlightSelectionMatches(options) {
21418
    let ext = [defaultTheme, matchHighlighter];
21419
    if (options)
21420
        ext.push(highlightConfig.of(options));
21421
    return ext;
21422
}
21423
const matchDeco = /*@__PURE__*/Decoration.mark({ class: "cm-selectionMatch" });
21424
const mainMatchDeco = /*@__PURE__*/Decoration.mark({ class: "cm-selectionMatch cm-selectionMatch-main" });
21425
// Whether the characters directly outside the given positions are non-word characters
21426
function insideWordBoundaries(check, state, from, to) {
21427
    return (from == 0 || check(state.sliceDoc(from - 1, from)) != CharCategory.Word) &&
21428
        (to == state.doc.length || check(state.sliceDoc(to, to + 1)) != CharCategory.Word);
21429
}
21430
// Whether the characters directly at the given positions are word characters
21431
function insideWord(check, state, from, to) {
21432
    return check(state.sliceDoc(from, from + 1)) == CharCategory.Word
21433
        && check(state.sliceDoc(to - 1, to)) == CharCategory.Word;
21434
}
21435
const matchHighlighter = /*@__PURE__*/ViewPlugin.fromClass(class {
21436
    constructor(view) {
21437
        this.decorations = this.getDeco(view);
21438
    }
21439
    update(update) {
21440
        if (update.selectionSet || update.docChanged || update.viewportChanged)
21441
            this.decorations = this.getDeco(update.view);
21442
    }
21443
    getDeco(view) {
21444
        let conf = view.state.facet(highlightConfig);
21445
        let { state } = view, sel = state.selection;
21446
        if (sel.ranges.length > 1)
21447
            return Decoration.none;
21448
        let range = sel.main, query, check = null;
21449
        if (range.empty) {
21450
            if (!conf.highlightWordAroundCursor)
21451
                return Decoration.none;
21452
            let word = state.wordAt(range.head);
21453
            if (!word)
21454
                return Decoration.none;
21455
            check = state.charCategorizer(range.head);
21456
            query = state.sliceDoc(word.from, word.to);
21457
        }
21458
        else {
21459
            let len = range.to - range.from;
21460
            if (len < conf.minSelectionLength || len > 200)
21461
                return Decoration.none;
21462
            if (conf.wholeWords) {
21463
                query = state.sliceDoc(range.from, range.to); // TODO: allow and include leading/trailing space?
21464
                check = state.charCategorizer(range.head);
21465
                if (!(insideWordBoundaries(check, state, range.from, range.to) &&
21466
                    insideWord(check, state, range.from, range.to)))
21467
                    return Decoration.none;
21468
            }
21469
            else {
21470
                query = state.sliceDoc(range.from, range.to);
21471
                if (!query)
21472
                    return Decoration.none;
21473
            }
21474
        }
21475
        let deco = [];
21476
        for (let part of view.visibleRanges) {
21477
            let cursor = new SearchCursor(state.doc, query, part.from, part.to);
21478
            while (!cursor.next().done) {
21479
                let { from, to } = cursor.value;
21480
                if (!check || insideWordBoundaries(check, state, from, to)) {
21481
                    if (range.empty && from <= range.from && to >= range.to)
21482
                        deco.push(mainMatchDeco.range(from, to));
21483
                    else if (from >= range.to || to <= range.from)
21484
                        deco.push(matchDeco.range(from, to));
21485
                    if (deco.length > conf.maxMatches)
21486
                        return Decoration.none;
21487
                }
21488
            }
21489
        }
21490
        return Decoration.set(deco);
21491
    }
21492
}, {
21493
    decorations: v => v.decorations
21494
});
21495
const defaultTheme = /*@__PURE__*/EditorView.baseTheme({
21496
    ".cm-selectionMatch": { backgroundColor: "#99ff7780" },
21497
    ".cm-searchMatch .cm-selectionMatch": { backgroundColor: "transparent" }
21498
});
21499
// Select the words around the cursors.
21500
const selectWord = ({ state, dispatch }) => {
21501
    let { selection } = state;
21502
    let newSel = EditorSelection.create(selection.ranges.map(range => state.wordAt(range.head) || EditorSelection.cursor(range.head)), selection.mainIndex);
21503
    if (newSel.eq(selection))
21504
        return false;
21505
    dispatch(state.update({ selection: newSel }));
21506
    return true;
21507
};
21508
// Find next occurrence of query relative to last cursor. Wrap around
21509
// the document if there are no more matches.
21510
function findNextOccurrence(state, query) {
21511
    let { main, ranges } = state.selection;
21512
    let word = state.wordAt(main.head), fullWord = word && word.from == main.from && word.to == main.to;
21513
    for (let cycled = false, cursor = new SearchCursor(state.doc, query, ranges[ranges.length - 1].to);;) {
21514
        cursor.next();
21515
        if (cursor.done) {
21516
            if (cycled)
21517
                return null;
21518
            cursor = new SearchCursor(state.doc, query, 0, Math.max(0, ranges[ranges.length - 1].from - 1));
21519
            cycled = true;
21520
        }
21521
        else {
21522
            if (cycled && ranges.some(r => r.from == cursor.value.from))
21523
                continue;
21524
            if (fullWord) {
21525
                let word = state.wordAt(cursor.value.from);
21526
                if (!word || word.from != cursor.value.from || word.to != cursor.value.to)
21527
                    continue;
21528
            }
21529
            return cursor.value;
21530
        }
21531
    }
21532
}
21533
/**
21534
Select next occurrence of the current selection. Expand selection
21535
to the surrounding word when the selection is empty.
21536
*/
21537
const selectNextOccurrence = ({ state, dispatch }) => {
21538
    let { ranges } = state.selection;
21539
    if (ranges.some(sel => sel.from === sel.to))
21540
        return selectWord({ state, dispatch });
21541
    let searchedText = state.sliceDoc(ranges[0].from, ranges[0].to);
21542
    if (state.selection.ranges.some(r => state.sliceDoc(r.from, r.to) != searchedText))
21543
        return false;
21544
    let range = findNextOccurrence(state, searchedText);
21545
    if (!range)
21546
        return false;
21547
    dispatch(state.update({
21548
        selection: state.selection.addRange(EditorSelection.range(range.from, range.to), false),
21549
        effects: EditorView.scrollIntoView(range.to)
21550
    }));
21551
    return true;
21552
};
21553
 
21554
const searchConfigFacet = /*@__PURE__*/Facet.define({
21555
    combine(configs) {
21556
        return combineConfig(configs, {
21557
            top: false,
21558
            caseSensitive: false,
21559
            literal: false,
21560
            regexp: false,
21561
            wholeWord: false,
21562
            createPanel: view => new SearchPanel(view),
21563
            scrollToMatch: range => EditorView.scrollIntoView(range)
21564
        });
21565
    }
21566
});
21567
/**
21568
A search query. Part of the editor's search state.
21569
*/
21570
class SearchQuery {
21571
    /**
21572
    Create a query object.
21573
    */
21574
    constructor(config) {
21575
        this.search = config.search;
21576
        this.caseSensitive = !!config.caseSensitive;
21577
        this.literal = !!config.literal;
21578
        this.regexp = !!config.regexp;
21579
        this.replace = config.replace || "";
21580
        this.valid = !!this.search && (!this.regexp || validRegExp(this.search));
21581
        this.unquoted = this.unquote(this.search);
21582
        this.wholeWord = !!config.wholeWord;
21583
    }
21584
    /**
21585
    @internal
21586
    */
21587
    unquote(text) {
21588
        return this.literal ? text :
21589
            text.replace(/\\([nrt\\])/g, (_, ch) => ch == "n" ? "\n" : ch == "r" ? "\r" : ch == "t" ? "\t" : "\\");
21590
    }
21591
    /**
21592
    Compare this query to another query.
21593
    */
21594
    eq(other) {
21595
        return this.search == other.search && this.replace == other.replace &&
21596
            this.caseSensitive == other.caseSensitive && this.regexp == other.regexp &&
21597
            this.wholeWord == other.wholeWord;
21598
    }
21599
    /**
21600
    @internal
21601
    */
21602
    create() {
21603
        return this.regexp ? new RegExpQuery(this) : new StringQuery(this);
21604
    }
21605
    /**
21606
    Get a search cursor for this query, searching through the given
21607
    range in the given state.
21608
    */
21609
    getCursor(state, from = 0, to) {
21610
        let st = state.doc ? state : EditorState.create({ doc: state });
21611
        if (to == null)
21612
            to = st.doc.length;
21613
        return this.regexp ? regexpCursor(this, st, from, to) : stringCursor(this, st, from, to);
21614
    }
21615
}
21616
class QueryType {
21617
    constructor(spec) {
21618
        this.spec = spec;
21619
    }
21620
}
21621
function stringCursor(spec, state, from, to) {
21622
    return new SearchCursor(state.doc, spec.unquoted, from, to, spec.caseSensitive ? undefined : x => x.toLowerCase(), spec.wholeWord ? stringWordTest(state.doc, state.charCategorizer(state.selection.main.head)) : undefined);
21623
}
21624
function stringWordTest(doc, categorizer) {
21625
    return (from, to, buf, bufPos) => {
21626
        if (bufPos > from || bufPos + buf.length < to) {
21627
            bufPos = Math.max(0, from - 2);
21628
            buf = doc.sliceString(bufPos, Math.min(doc.length, to + 2));
21629
        }
21630
        return (categorizer(charBefore(buf, from - bufPos)) != CharCategory.Word ||
21631
            categorizer(charAfter(buf, from - bufPos)) != CharCategory.Word) &&
21632
            (categorizer(charAfter(buf, to - bufPos)) != CharCategory.Word ||
21633
                categorizer(charBefore(buf, to - bufPos)) != CharCategory.Word);
21634
    };
21635
}
21636
class StringQuery extends QueryType {
21637
    constructor(spec) {
21638
        super(spec);
21639
    }
21640
    nextMatch(state, curFrom, curTo) {
21641
        let cursor = stringCursor(this.spec, state, curTo, state.doc.length).nextOverlapping();
21642
        if (cursor.done)
21643
            cursor = stringCursor(this.spec, state, 0, curFrom).nextOverlapping();
21644
        return cursor.done ? null : cursor.value;
21645
    }
21646
    // Searching in reverse is, rather than implementing an inverted search
21647
    // cursor, done by scanning chunk after chunk forward.
21648
    prevMatchInRange(state, from, to) {
21649
        for (let pos = to;;) {
21650
            let start = Math.max(from, pos - 10000 /* FindPrev.ChunkSize */ - this.spec.unquoted.length);
21651
            let cursor = stringCursor(this.spec, state, start, pos), range = null;
21652
            while (!cursor.nextOverlapping().done)
21653
                range = cursor.value;
21654
            if (range)
21655
                return range;
21656
            if (start == from)
21657
                return null;
21658
            pos -= 10000 /* FindPrev.ChunkSize */;
21659
        }
21660
    }
21661
    prevMatch(state, curFrom, curTo) {
21662
        return this.prevMatchInRange(state, 0, curFrom) ||
21663
            this.prevMatchInRange(state, curTo, state.doc.length);
21664
    }
21665
    getReplacement(_result) { return this.spec.unquote(this.spec.replace); }
21666
    matchAll(state, limit) {
21667
        let cursor = stringCursor(this.spec, state, 0, state.doc.length), ranges = [];
21668
        while (!cursor.next().done) {
21669
            if (ranges.length >= limit)
21670
                return null;
21671
            ranges.push(cursor.value);
21672
        }
21673
        return ranges;
21674
    }
21675
    highlight(state, from, to, add) {
21676
        let cursor = stringCursor(this.spec, state, Math.max(0, from - this.spec.unquoted.length), Math.min(to + this.spec.unquoted.length, state.doc.length));
21677
        while (!cursor.next().done)
21678
            add(cursor.value.from, cursor.value.to);
21679
    }
21680
}
21681
function regexpCursor(spec, state, from, to) {
21682
    return new RegExpCursor(state.doc, spec.search, {
21683
        ignoreCase: !spec.caseSensitive,
21684
        test: spec.wholeWord ? regexpWordTest(state.charCategorizer(state.selection.main.head)) : undefined
21685
    }, from, to);
21686
}
21687
function charBefore(str, index) {
21688
    return str.slice(findClusterBreak(str, index, false), index);
21689
}
21690
function charAfter(str, index) {
21691
    return str.slice(index, findClusterBreak(str, index));
21692
}
21693
function regexpWordTest(categorizer) {
21694
    return (_from, _to, match) => !match[0].length ||
21695
        (categorizer(charBefore(match.input, match.index)) != CharCategory.Word ||
21696
            categorizer(charAfter(match.input, match.index)) != CharCategory.Word) &&
21697
            (categorizer(charAfter(match.input, match.index + match[0].length)) != CharCategory.Word ||
21698
                categorizer(charBefore(match.input, match.index + match[0].length)) != CharCategory.Word);
21699
}
21700
class RegExpQuery extends QueryType {
21701
    nextMatch(state, curFrom, curTo) {
21702
        let cursor = regexpCursor(this.spec, state, curTo, state.doc.length).next();
21703
        if (cursor.done)
21704
            cursor = regexpCursor(this.spec, state, 0, curFrom).next();
21705
        return cursor.done ? null : cursor.value;
21706
    }
21707
    prevMatchInRange(state, from, to) {
21708
        for (let size = 1;; size++) {
21709
            let start = Math.max(from, to - size * 10000 /* FindPrev.ChunkSize */);
21710
            let cursor = regexpCursor(this.spec, state, start, to), range = null;
21711
            while (!cursor.next().done)
21712
                range = cursor.value;
21713
            if (range && (start == from || range.from > start + 10))
21714
                return range;
21715
            if (start == from)
21716
                return null;
21717
        }
21718
    }
21719
    prevMatch(state, curFrom, curTo) {
21720
        return this.prevMatchInRange(state, 0, curFrom) ||
21721
            this.prevMatchInRange(state, curTo, state.doc.length);
21722
    }
21723
    getReplacement(result) {
21724
        return this.spec.unquote(this.spec.replace).replace(/\$([$&\d+])/g, (m, i) => i == "$" ? "$"
21725
            : i == "&" ? result.match[0]
21726
                : i != "0" && +i < result.match.length ? result.match[i]
21727
                    : m);
21728
    }
21729
    matchAll(state, limit) {
21730
        let cursor = regexpCursor(this.spec, state, 0, state.doc.length), ranges = [];
21731
        while (!cursor.next().done) {
21732
            if (ranges.length >= limit)
21733
                return null;
21734
            ranges.push(cursor.value);
21735
        }
21736
        return ranges;
21737
    }
21738
    highlight(state, from, to, add) {
21739
        let cursor = regexpCursor(this.spec, state, Math.max(0, from - 250 /* RegExp.HighlightMargin */), Math.min(to + 250 /* RegExp.HighlightMargin */, state.doc.length));
21740
        while (!cursor.next().done)
21741
            add(cursor.value.from, cursor.value.to);
21742
    }
21743
}
21744
/**
21745
A state effect that updates the current search query. Note that
21746
this only has an effect if the search state has been initialized
21747
(by including [`search`](https://codemirror.net/6/docs/ref/#search.search) in your configuration or
21748
by running [`openSearchPanel`](https://codemirror.net/6/docs/ref/#search.openSearchPanel) at least
21749
once).
21750
*/
21751
const setSearchQuery = /*@__PURE__*/StateEffect.define();
21752
const togglePanel$1 = /*@__PURE__*/StateEffect.define();
21753
const searchState = /*@__PURE__*/StateField.define({
21754
    create(state) {
21755
        return new SearchState(defaultQuery(state).create(), null);
21756
    },
21757
    update(value, tr) {
21758
        for (let effect of tr.effects) {
21759
            if (effect.is(setSearchQuery))
21760
                value = new SearchState(effect.value.create(), value.panel);
21761
            else if (effect.is(togglePanel$1))
21762
                value = new SearchState(value.query, effect.value ? createSearchPanel : null);
21763
        }
21764
        return value;
21765
    },
21766
    provide: f => showPanel.from(f, val => val.panel)
21767
});
21768
class SearchState {
21769
    constructor(query, panel) {
21770
        this.query = query;
21771
        this.panel = panel;
21772
    }
21773
}
21774
const matchMark = /*@__PURE__*/Decoration.mark({ class: "cm-searchMatch" }), selectedMatchMark = /*@__PURE__*/Decoration.mark({ class: "cm-searchMatch cm-searchMatch-selected" });
21775
const searchHighlighter = /*@__PURE__*/ViewPlugin.fromClass(class {
21776
    constructor(view) {
21777
        this.view = view;
21778
        this.decorations = this.highlight(view.state.field(searchState));
21779
    }
21780
    update(update) {
21781
        let state = update.state.field(searchState);
21782
        if (state != update.startState.field(searchState) || update.docChanged || update.selectionSet || update.viewportChanged)
21783
            this.decorations = this.highlight(state);
21784
    }
21785
    highlight({ query, panel }) {
21786
        if (!panel || !query.spec.valid)
21787
            return Decoration.none;
21788
        let { view } = this;
21789
        let builder = new RangeSetBuilder();
21790
        for (let i = 0, ranges = view.visibleRanges, l = ranges.length; i < l; i++) {
21791
            let { from, to } = ranges[i];
21792
            while (i < l - 1 && to > ranges[i + 1].from - 2 * 250 /* RegExp.HighlightMargin */)
21793
                to = ranges[++i].to;
21794
            query.highlight(view.state, from, to, (from, to) => {
21795
                let selected = view.state.selection.ranges.some(r => r.from == from && r.to == to);
21796
                builder.add(from, to, selected ? selectedMatchMark : matchMark);
21797
            });
21798
        }
21799
        return builder.finish();
21800
    }
21801
}, {
21802
    decorations: v => v.decorations
21803
});
21804
function searchCommand(f) {
21805
    return view => {
21806
        let state = view.state.field(searchState, false);
21807
        return state && state.query.spec.valid ? f(view, state) : openSearchPanel(view);
21808
    };
21809
}
21810
/**
21811
Open the search panel if it isn't already open, and move the
21812
selection to the first match after the current main selection.
21813
Will wrap around to the start of the document when it reaches the
21814
end.
21815
*/
21816
const findNext = /*@__PURE__*/searchCommand((view, { query }) => {
21817
    let { to } = view.state.selection.main;
21818
    let next = query.nextMatch(view.state, to, to);
21819
    if (!next)
21820
        return false;
21821
    let selection = EditorSelection.single(next.from, next.to);
21822
    let config = view.state.facet(searchConfigFacet);
21823
    view.dispatch({
21824
        selection,
21825
        effects: [announceMatch(view, next), config.scrollToMatch(selection.main, view)],
21826
        userEvent: "select.search"
21827
    });
21828
    selectSearchInput(view);
21829
    return true;
21830
});
21831
/**
21832
Move the selection to the previous instance of the search query,
21833
before the current main selection. Will wrap past the start
21834
of the document to start searching at the end again.
21835
*/
21836
const findPrevious = /*@__PURE__*/searchCommand((view, { query }) => {
21837
    let { state } = view, { from } = state.selection.main;
21838
    let prev = query.prevMatch(state, from, from);
21839
    if (!prev)
21840
        return false;
21841
    let selection = EditorSelection.single(prev.from, prev.to);
21842
    let config = view.state.facet(searchConfigFacet);
21843
    view.dispatch({
21844
        selection,
21845
        effects: [announceMatch(view, prev), config.scrollToMatch(selection.main, view)],
21846
        userEvent: "select.search"
21847
    });
21848
    selectSearchInput(view);
21849
    return true;
21850
});
21851
/**
21852
Select all instances of the search query.
21853
*/
21854
const selectMatches = /*@__PURE__*/searchCommand((view, { query }) => {
21855
    let ranges = query.matchAll(view.state, 1000);
21856
    if (!ranges || !ranges.length)
21857
        return false;
21858
    view.dispatch({
21859
        selection: EditorSelection.create(ranges.map(r => EditorSelection.range(r.from, r.to))),
21860
        userEvent: "select.search.matches"
21861
    });
21862
    return true;
21863
});
21864
/**
21865
Select all instances of the currently selected text.
21866
*/
21867
const selectSelectionMatches = ({ state, dispatch }) => {
21868
    let sel = state.selection;
21869
    if (sel.ranges.length > 1 || sel.main.empty)
21870
        return false;
21871
    let { from, to } = sel.main;
21872
    let ranges = [], main = 0;
21873
    for (let cur = new SearchCursor(state.doc, state.sliceDoc(from, to)); !cur.next().done;) {
21874
        if (ranges.length > 1000)
21875
            return false;
21876
        if (cur.value.from == from)
21877
            main = ranges.length;
21878
        ranges.push(EditorSelection.range(cur.value.from, cur.value.to));
21879
    }
21880
    dispatch(state.update({
21881
        selection: EditorSelection.create(ranges, main),
21882
        userEvent: "select.search.matches"
21883
    }));
21884
    return true;
21885
};
21886
/**
21887
Replace the current match of the search query.
21888
*/
21889
const replaceNext = /*@__PURE__*/searchCommand((view, { query }) => {
21890
    let { state } = view, { from, to } = state.selection.main;
21891
    if (state.readOnly)
21892
        return false;
21893
    let next = query.nextMatch(state, from, from);
21894
    if (!next)
21895
        return false;
21896
    let changes = [], selection, replacement;
21897
    let effects = [];
21898
    if (next.from == from && next.to == to) {
21899
        replacement = state.toText(query.getReplacement(next));
21900
        changes.push({ from: next.from, to: next.to, insert: replacement });
21901
        next = query.nextMatch(state, next.from, next.to);
21902
        effects.push(EditorView.announce.of(state.phrase("replaced match on line $", state.doc.lineAt(from).number) + "."));
21903
    }
21904
    if (next) {
21905
        let off = changes.length == 0 || changes[0].from >= next.to ? 0 : next.to - next.from - replacement.length;
21906
        selection = EditorSelection.single(next.from - off, next.to - off);
21907
        effects.push(announceMatch(view, next));
21908
        effects.push(state.facet(searchConfigFacet).scrollToMatch(selection.main, view));
21909
    }
21910
    view.dispatch({
21911
        changes, selection, effects,
21912
        userEvent: "input.replace"
21913
    });
21914
    return true;
21915
});
21916
/**
21917
Replace all instances of the search query with the given
21918
replacement.
21919
*/
21920
const replaceAll = /*@__PURE__*/searchCommand((view, { query }) => {
21921
    if (view.state.readOnly)
21922
        return false;
21923
    let changes = query.matchAll(view.state, 1e9).map(match => {
21924
        let { from, to } = match;
21925
        return { from, to, insert: query.getReplacement(match) };
21926
    });
21927
    if (!changes.length)
21928
        return false;
21929
    let announceText = view.state.phrase("replaced $ matches", changes.length) + ".";
21930
    view.dispatch({
21931
        changes,
21932
        effects: EditorView.announce.of(announceText),
21933
        userEvent: "input.replace.all"
21934
    });
21935
    return true;
21936
});
21937
function createSearchPanel(view) {
21938
    return view.state.facet(searchConfigFacet).createPanel(view);
21939
}
21940
function defaultQuery(state, fallback) {
21941
    var _a, _b, _c, _d, _e;
21942
    let sel = state.selection.main;
21943
    let selText = sel.empty || sel.to > sel.from + 100 ? "" : state.sliceDoc(sel.from, sel.to);
21944
    if (fallback && !selText)
21945
        return fallback;
21946
    let config = state.facet(searchConfigFacet);
21947
    return new SearchQuery({
21948
        search: ((_a = fallback === null || fallback === void 0 ? void 0 : fallback.literal) !== null && _a !== void 0 ? _a : config.literal) ? selText : selText.replace(/\n/g, "\\n"),
21949
        caseSensitive: (_b = fallback === null || fallback === void 0 ? void 0 : fallback.caseSensitive) !== null && _b !== void 0 ? _b : config.caseSensitive,
21950
        literal: (_c = fallback === null || fallback === void 0 ? void 0 : fallback.literal) !== null && _c !== void 0 ? _c : config.literal,
21951
        regexp: (_d = fallback === null || fallback === void 0 ? void 0 : fallback.regexp) !== null && _d !== void 0 ? _d : config.regexp,
21952
        wholeWord: (_e = fallback === null || fallback === void 0 ? void 0 : fallback.wholeWord) !== null && _e !== void 0 ? _e : config.wholeWord
21953
    });
21954
}
21955
function getSearchInput(view) {
21956
    let panel = getPanel(view, createSearchPanel);
21957
    return panel && panel.dom.querySelector("[main-field]");
21958
}
21959
function selectSearchInput(view) {
21960
    let input = getSearchInput(view);
21961
    if (input && input == view.root.activeElement)
21962
        input.select();
21963
}
21964
/**
21965
Make sure the search panel is open and focused.
21966
*/
21967
const openSearchPanel = view => {
21968
    let state = view.state.field(searchState, false);
21969
    if (state && state.panel) {
21970
        let searchInput = getSearchInput(view);
21971
        if (searchInput && searchInput != view.root.activeElement) {
21972
            let query = defaultQuery(view.state, state.query.spec);
21973
            if (query.valid)
21974
                view.dispatch({ effects: setSearchQuery.of(query) });
21975
            searchInput.focus();
21976
            searchInput.select();
21977
        }
21978
    }
21979
    else {
21980
        view.dispatch({ effects: [
21981
                togglePanel$1.of(true),
21982
                state ? setSearchQuery.of(defaultQuery(view.state, state.query.spec)) : StateEffect.appendConfig.of(searchExtensions)
21983
            ] });
21984
    }
21985
    return true;
21986
};
21987
/**
21988
Close the search panel.
21989
*/
21990
const closeSearchPanel = view => {
21991
    let state = view.state.field(searchState, false);
21992
    if (!state || !state.panel)
21993
        return false;
21994
    let panel = getPanel(view, createSearchPanel);
21995
    if (panel && panel.dom.contains(view.root.activeElement))
21996
        view.focus();
21997
    view.dispatch({ effects: togglePanel$1.of(false) });
21998
    return true;
21999
};
22000
/**
22001
Default search-related key bindings.
22002
 
22003
 - Mod-f: [`openSearchPanel`](https://codemirror.net/6/docs/ref/#search.openSearchPanel)
22004
 - F3, Mod-g: [`findNext`](https://codemirror.net/6/docs/ref/#search.findNext)
22005
 - Shift-F3, Shift-Mod-g: [`findPrevious`](https://codemirror.net/6/docs/ref/#search.findPrevious)
22006
 - Mod-Alt-g: [`gotoLine`](https://codemirror.net/6/docs/ref/#search.gotoLine)
22007
 - Mod-d: [`selectNextOccurrence`](https://codemirror.net/6/docs/ref/#search.selectNextOccurrence)
22008
*/
22009
const searchKeymap = [
22010
    { key: "Mod-f", run: openSearchPanel, scope: "editor search-panel" },
22011
    { key: "F3", run: findNext, shift: findPrevious, scope: "editor search-panel", preventDefault: true },
22012
    { key: "Mod-g", run: findNext, shift: findPrevious, scope: "editor search-panel", preventDefault: true },
22013
    { key: "Escape", run: closeSearchPanel, scope: "editor search-panel" },
22014
    { key: "Mod-Shift-l", run: selectSelectionMatches },
22015
    { key: "Mod-Alt-g", run: gotoLine },
22016
    { key: "Mod-d", run: selectNextOccurrence, preventDefault: true },
22017
];
22018
class SearchPanel {
22019
    constructor(view) {
22020
        this.view = view;
22021
        let query = this.query = view.state.field(searchState).query.spec;
22022
        this.commit = this.commit.bind(this);
22023
        this.searchField = crelt("input", {
22024
            value: query.search,
22025
            placeholder: phrase(view, "Find"),
22026
            "aria-label": phrase(view, "Find"),
22027
            class: "cm-textfield",
22028
            name: "search",
22029
            form: "",
22030
            "main-field": "true",
22031
            onchange: this.commit,
22032
            onkeyup: this.commit
22033
        });
22034
        this.replaceField = crelt("input", {
22035
            value: query.replace,
22036
            placeholder: phrase(view, "Replace"),
22037
            "aria-label": phrase(view, "Replace"),
22038
            class: "cm-textfield",
22039
            name: "replace",
22040
            form: "",
22041
            onchange: this.commit,
22042
            onkeyup: this.commit
22043
        });
22044
        this.caseField = crelt("input", {
22045
            type: "checkbox",
22046
            name: "case",
22047
            form: "",
22048
            checked: query.caseSensitive,
22049
            onchange: this.commit
22050
        });
22051
        this.reField = crelt("input", {
22052
            type: "checkbox",
22053
            name: "re",
22054
            form: "",
22055
            checked: query.regexp,
22056
            onchange: this.commit
22057
        });
22058
        this.wordField = crelt("input", {
22059
            type: "checkbox",
22060
            name: "word",
22061
            form: "",
22062
            checked: query.wholeWord,
22063
            onchange: this.commit
22064
        });
22065
        function button(name, onclick, content) {
22066
            return crelt("button", { class: "cm-button", name, onclick, type: "button" }, content);
22067
        }
22068
        this.dom = crelt("div", { onkeydown: (e) => this.keydown(e), class: "cm-search" }, [
22069
            this.searchField,
22070
            button("next", () => findNext(view), [phrase(view, "next")]),
22071
            button("prev", () => findPrevious(view), [phrase(view, "previous")]),
22072
            button("select", () => selectMatches(view), [phrase(view, "all")]),
22073
            crelt("label", null, [this.caseField, phrase(view, "match case")]),
22074
            crelt("label", null, [this.reField, phrase(view, "regexp")]),
22075
            crelt("label", null, [this.wordField, phrase(view, "by word")]),
22076
            ...view.state.readOnly ? [] : [
22077
                crelt("br"),
22078
                this.replaceField,
22079
                button("replace", () => replaceNext(view), [phrase(view, "replace")]),
22080
                button("replaceAll", () => replaceAll(view), [phrase(view, "replace all")])
22081
            ],
22082
            crelt("button", {
22083
                name: "close",
22084
                onclick: () => closeSearchPanel(view),
22085
                "aria-label": phrase(view, "close"),
22086
                type: "button"
22087
            }, ["×"])
22088
        ]);
22089
    }
22090
    commit() {
22091
        let query = new SearchQuery({
22092
            search: this.searchField.value,
22093
            caseSensitive: this.caseField.checked,
22094
            regexp: this.reField.checked,
22095
            wholeWord: this.wordField.checked,
22096
            replace: this.replaceField.value,
22097
        });
22098
        if (!query.eq(this.query)) {
22099
            this.query = query;
22100
            this.view.dispatch({ effects: setSearchQuery.of(query) });
22101
        }
22102
    }
22103
    keydown(e) {
22104
        if (runScopeHandlers(this.view, e, "search-panel")) {
22105
            e.preventDefault();
22106
        }
22107
        else if (e.keyCode == 13 && e.target == this.searchField) {
22108
            e.preventDefault();
22109
            (e.shiftKey ? findPrevious : findNext)(this.view);
22110
        }
22111
        else if (e.keyCode == 13 && e.target == this.replaceField) {
22112
            e.preventDefault();
22113
            replaceNext(this.view);
22114
        }
22115
    }
22116
    update(update) {
22117
        for (let tr of update.transactions)
22118
            for (let effect of tr.effects) {
22119
                if (effect.is(setSearchQuery) && !effect.value.eq(this.query))
22120
                    this.setQuery(effect.value);
22121
            }
22122
    }
22123
    setQuery(query) {
22124
        this.query = query;
22125
        this.searchField.value = query.search;
22126
        this.replaceField.value = query.replace;
22127
        this.caseField.checked = query.caseSensitive;
22128
        this.reField.checked = query.regexp;
22129
        this.wordField.checked = query.wholeWord;
22130
    }
22131
    mount() {
22132
        this.searchField.select();
22133
    }
22134
    get pos() { return 80; }
22135
    get top() { return this.view.state.facet(searchConfigFacet).top; }
22136
}
22137
function phrase(view, phrase) { return view.state.phrase(phrase); }
22138
const AnnounceMargin = 30;
22139
const Break = /[\s\.,:;?!]/;
22140
function announceMatch(view, { from, to }) {
22141
    let line = view.state.doc.lineAt(from), lineEnd = view.state.doc.lineAt(to).to;
22142
    let start = Math.max(line.from, from - AnnounceMargin), end = Math.min(lineEnd, to + AnnounceMargin);
22143
    let text = view.state.sliceDoc(start, end);
22144
    if (start != line.from) {
22145
        for (let i = 0; i < AnnounceMargin; i++)
22146
            if (!Break.test(text[i + 1]) && Break.test(text[i])) {
22147
                text = text.slice(i);
22148
                break;
22149
            }
22150
    }
22151
    if (end != lineEnd) {
22152
        for (let i = text.length - 1; i > text.length - AnnounceMargin; i--)
22153
            if (!Break.test(text[i - 1]) && Break.test(text[i])) {
22154
                text = text.slice(0, i);
22155
                break;
22156
            }
22157
    }
22158
    return EditorView.announce.of(`${view.state.phrase("current match")}. ${text} ${view.state.phrase("on line")} ${line.number}.`);
22159
}
22160
const baseTheme$2 = /*@__PURE__*/EditorView.baseTheme({
22161
    ".cm-panel.cm-search": {
22162
        padding: "2px 6px 4px",
22163
        position: "relative",
22164
        "& [name=close]": {
22165
            position: "absolute",
22166
            top: "0",
22167
            right: "4px",
22168
            backgroundColor: "inherit",
22169
            border: "none",
22170
            font: "inherit",
22171
            padding: 0,
22172
            margin: 0
22173
        },
22174
        "& input, & button, & label": {
22175
            margin: ".2em .6em .2em 0"
22176
        },
22177
        "& input[type=checkbox]": {
22178
            marginRight: ".2em"
22179
        },
22180
        "& label": {
22181
            fontSize: "80%",
22182
            whiteSpace: "pre"
22183
        }
22184
    },
22185
    "&light .cm-searchMatch": { backgroundColor: "#ffff0054" },
22186
    "&dark .cm-searchMatch": { backgroundColor: "#00ffff8a" },
22187
    "&light .cm-searchMatch-selected": { backgroundColor: "#ff6a0054" },
22188
    "&dark .cm-searchMatch-selected": { backgroundColor: "#ff00ff8a" }
22189
});
22190
const searchExtensions = [
22191
    searchState,
22192
    /*@__PURE__*/Prec.low(searchHighlighter),
22193
    baseTheme$2
22194
];
22195
 
22196
/**
22197
An instance of this is passed to completion source functions.
22198
*/
22199
class CompletionContext {
22200
    /**
22201
    Create a new completion context. (Mostly useful for testing
22202
    completion sources—in the editor, the extension will create
22203
    these for you.)
22204
    */
22205
    constructor(
22206
    /**
22207
    The editor state that the completion happens in.
22208
    */
22209
    state,
22210
    /**
22211
    The position at which the completion is happening.
22212
    */
22213
    pos,
22214
    /**
22215
    Indicates whether completion was activated explicitly, or
22216
    implicitly by typing. The usual way to respond to this is to
22217
    only return completions when either there is part of a
22218
    completable entity before the cursor, or `explicit` is true.
22219
    */
22220
    explicit) {
22221
        this.state = state;
22222
        this.pos = pos;
22223
        this.explicit = explicit;
22224
        /**
22225
        @internal
22226
        */
22227
        this.abortListeners = [];
22228
    }
22229
    /**
22230
    Get the extent, content, and (if there is a token) type of the
22231
    token before `this.pos`.
22232
    */
22233
    tokenBefore(types) {
22234
        let token = syntaxTree(this.state).resolveInner(this.pos, -1);
22235
        while (token && types.indexOf(token.name) < 0)
22236
            token = token.parent;
22237
        return token ? { from: token.from, to: this.pos,
22238
            text: this.state.sliceDoc(token.from, this.pos),
22239
            type: token.type } : null;
22240
    }
22241
    /**
22242
    Get the match of the given expression directly before the
22243
    cursor.
22244
    */
22245
    matchBefore(expr) {
22246
        let line = this.state.doc.lineAt(this.pos);
22247
        let start = Math.max(line.from, this.pos - 250);
22248
        let str = line.text.slice(start - line.from, this.pos - line.from);
22249
        let found = str.search(ensureAnchor(expr, false));
22250
        return found < 0 ? null : { from: start + found, to: this.pos, text: str.slice(found) };
22251
    }
22252
    /**
22253
    Yields true when the query has been aborted. Can be useful in
22254
    asynchronous queries to avoid doing work that will be ignored.
22255
    */
22256
    get aborted() { return this.abortListeners == null; }
22257
    /**
22258
    Allows you to register abort handlers, which will be called when
22259
    the query is
22260
    [aborted](https://codemirror.net/6/docs/ref/#autocomplete.CompletionContext.aborted).
22261
    */
22262
    addEventListener(type, listener) {
22263
        if (type == "abort" && this.abortListeners)
22264
            this.abortListeners.push(listener);
22265
    }
22266
}
22267
function toSet(chars) {
22268
    let flat = Object.keys(chars).join("");
22269
    let words = /\w/.test(flat);
22270
    if (words)
22271
        flat = flat.replace(/\w/g, "");
22272
    return `[${words ? "\\w" : ""}${flat.replace(/[^\w\s]/g, "\\$&")}]`;
22273
}
22274
function prefixMatch(options) {
22275
    let first = Object.create(null), rest = Object.create(null);
22276
    for (let { label } of options) {
22277
        first[label[0]] = true;
22278
        for (let i = 1; i < label.length; i++)
22279
            rest[label[i]] = true;
22280
    }
22281
    let source = toSet(first) + toSet(rest) + "*$";
22282
    return [new RegExp("^" + source), new RegExp(source)];
22283
}
22284
/**
22285
Given a a fixed array of options, return an autocompleter that
22286
completes them.
22287
*/
22288
function completeFromList(list) {
22289
    let options = list.map(o => typeof o == "string" ? { label: o } : o);
22290
    let [validFor, match] = options.every(o => /^\w+$/.test(o.label)) ? [/\w*$/, /\w+$/] : prefixMatch(options);
22291
    return (context) => {
22292
        let token = context.matchBefore(match);
22293
        return token || context.explicit ? { from: token ? token.from : context.pos, options, validFor } : null;
22294
    };
22295
}
22296
/**
22297
Wrap the given completion source so that it will not fire when the
22298
cursor is in a syntax node with one of the given names.
22299
*/
22300
function ifNotIn(nodes, source) {
22301
    return (context) => {
22302
        for (let pos = syntaxTree(context.state).resolveInner(context.pos, -1); pos; pos = pos.parent) {
22303
            if (nodes.indexOf(pos.name) > -1)
22304
                return null;
22305
            if (pos.type.isTop)
22306
                break;
22307
        }
22308
        return source(context);
22309
    };
22310
}
22311
class Option {
22312
    constructor(completion, source, match, score) {
22313
        this.completion = completion;
22314
        this.source = source;
22315
        this.match = match;
22316
        this.score = score;
22317
    }
22318
}
22319
function cur(state) { return state.selection.main.from; }
22320
// Make sure the given regexp has a $ at its end and, if `start` is
22321
// true, a ^ at its start.
22322
function ensureAnchor(expr, start) {
22323
    var _a;
22324
    let { source } = expr;
22325
    let addStart = start && source[0] != "^", addEnd = source[source.length - 1] != "$";
22326
    if (!addStart && !addEnd)
22327
        return expr;
22328
    return new RegExp(`${addStart ? "^" : ""}(?:${source})${addEnd ? "$" : ""}`, (_a = expr.flags) !== null && _a !== void 0 ? _a : (expr.ignoreCase ? "i" : ""));
22329
}
22330
/**
22331
This annotation is added to transactions that are produced by
22332
picking a completion.
22333
*/
22334
const pickedCompletion = /*@__PURE__*/Annotation.define();
22335
/**
22336
Helper function that returns a transaction spec which inserts a
22337
completion's text in the main selection range, and any other
22338
selection range that has the same text in front of it.
22339
*/
22340
function insertCompletionText(state, text, from, to) {
22341
    let { main } = state.selection, fromOff = from - main.from, toOff = to - main.from;
22342
    return Object.assign(Object.assign({}, state.changeByRange(range => {
22343
        if (range != main && from != to &&
22344
            state.sliceDoc(range.from + fromOff, range.from + toOff) != state.sliceDoc(from, to))
22345
            return { range };
22346
        return {
22347
            changes: { from: range.from + fromOff, to: to == main.from ? range.to : range.from + toOff, insert: text },
22348
            range: EditorSelection.cursor(range.from + fromOff + text.length)
22349
        };
22350
    })), { scrollIntoView: true, userEvent: "input.complete" });
22351
}
22352
const SourceCache = /*@__PURE__*/new WeakMap();
22353
function asSource(source) {
22354
    if (!Array.isArray(source))
22355
        return source;
22356
    let known = SourceCache.get(source);
22357
    if (!known)
22358
        SourceCache.set(source, known = completeFromList(source));
22359
    return known;
22360
}
22361
const startCompletionEffect = /*@__PURE__*/StateEffect.define();
22362
const closeCompletionEffect = /*@__PURE__*/StateEffect.define();
22363
 
22364
// A pattern matcher for fuzzy completion matching. Create an instance
22365
// once for a pattern, and then use that to match any number of
22366
// completions.
22367
class FuzzyMatcher {
22368
    constructor(pattern) {
22369
        this.pattern = pattern;
22370
        this.chars = [];
22371
        this.folded = [];
22372
        // Buffers reused by calls to `match` to track matched character
22373
        // positions.
22374
        this.any = [];
22375
        this.precise = [];
22376
        this.byWord = [];
22377
        this.score = 0;
22378
        this.matched = [];
22379
        for (let p = 0; p < pattern.length;) {
22380
            let char = codePointAt(pattern, p), size = codePointSize(char);
22381
            this.chars.push(char);
22382
            let part = pattern.slice(p, p + size), upper = part.toUpperCase();
22383
            this.folded.push(codePointAt(upper == part ? part.toLowerCase() : upper, 0));
22384
            p += size;
22385
        }
22386
        this.astral = pattern.length != this.chars.length;
22387
    }
22388
    ret(score, matched) {
22389
        this.score = score;
22390
        this.matched = matched;
22391
        return this;
22392
    }
22393
    // Matches a given word (completion) against the pattern (input).
22394
    // Will return a boolean indicating whether there was a match and,
22395
    // on success, set `this.score` to the score, `this.matched` to an
22396
    // array of `from, to` pairs indicating the matched parts of `word`.
22397
    //
22398
    // The score is a number that is more negative the worse the match
22399
    // is. See `Penalty` above.
22400
    match(word) {
22401
        if (this.pattern.length == 0)
22402
            return this.ret(-100 /* Penalty.NotFull */, []);
22403
        if (word.length < this.pattern.length)
22404
            return null;
22405
        let { chars, folded, any, precise, byWord } = this;
22406
        // For single-character queries, only match when they occur right
22407
        // at the start
22408
        if (chars.length == 1) {
22409
            let first = codePointAt(word, 0), firstSize = codePointSize(first);
22410
            let score = firstSize == word.length ? 0 : -100 /* Penalty.NotFull */;
22411
            if (first == chars[0]) ;
22412
            else if (first == folded[0])
22413
                score += -200 /* Penalty.CaseFold */;
22414
            else
22415
                return null;
22416
            return this.ret(score, [0, firstSize]);
22417
        }
22418
        let direct = word.indexOf(this.pattern);
22419
        if (direct == 0)
22420
            return this.ret(word.length == this.pattern.length ? 0 : -100 /* Penalty.NotFull */, [0, this.pattern.length]);
22421
        let len = chars.length, anyTo = 0;
22422
        if (direct < 0) {
22423
            for (let i = 0, e = Math.min(word.length, 200); i < e && anyTo < len;) {
22424
                let next = codePointAt(word, i);
22425
                if (next == chars[anyTo] || next == folded[anyTo])
22426
                    any[anyTo++] = i;
22427
                i += codePointSize(next);
22428
            }
22429
            // No match, exit immediately
22430
            if (anyTo < len)
22431
                return null;
22432
        }
22433
        // This tracks the extent of the precise (non-folded, not
22434
        // necessarily adjacent) match
22435
        let preciseTo = 0;
22436
        // Tracks whether there is a match that hits only characters that
22437
        // appear to be starting words. `byWordFolded` is set to true when
22438
        // a case folded character is encountered in such a match
22439
        let byWordTo = 0, byWordFolded = false;
22440
        // If we've found a partial adjacent match, these track its state
22441
        let adjacentTo = 0, adjacentStart = -1, adjacentEnd = -1;
22442
        let hasLower = /[a-z]/.test(word), wordAdjacent = true;
22443
        // Go over the option's text, scanning for the various kinds of matches
22444
        for (let i = 0, e = Math.min(word.length, 200), prevType = 0 /* Tp.NonWord */; i < e && byWordTo < len;) {
22445
            let next = codePointAt(word, i);
22446
            if (direct < 0) {
22447
                if (preciseTo < len && next == chars[preciseTo])
22448
                    precise[preciseTo++] = i;
22449
                if (adjacentTo < len) {
22450
                    if (next == chars[adjacentTo] || next == folded[adjacentTo]) {
22451
                        if (adjacentTo == 0)
22452
                            adjacentStart = i;
22453
                        adjacentEnd = i + 1;
22454
                        adjacentTo++;
22455
                    }
22456
                    else {
22457
                        adjacentTo = 0;
22458
                    }
22459
                }
22460
            }
22461
            let ch, type = next < 0xff
22462
                ? (next >= 48 && next <= 57 || next >= 97 && next <= 122 ? 2 /* Tp.Lower */ : next >= 65 && next <= 90 ? 1 /* Tp.Upper */ : 0 /* Tp.NonWord */)
22463
                : ((ch = fromCodePoint(next)) != ch.toLowerCase() ? 1 /* Tp.Upper */ : ch != ch.toUpperCase() ? 2 /* Tp.Lower */ : 0 /* Tp.NonWord */);
22464
            if (!i || type == 1 /* Tp.Upper */ && hasLower || prevType == 0 /* Tp.NonWord */ && type != 0 /* Tp.NonWord */) {
22465
                if (chars[byWordTo] == next || (folded[byWordTo] == next && (byWordFolded = true)))
22466
                    byWord[byWordTo++] = i;
22467
                else if (byWord.length)
22468
                    wordAdjacent = false;
22469
            }
22470
            prevType = type;
22471
            i += codePointSize(next);
22472
        }
22473
        if (byWordTo == len && byWord[0] == 0 && wordAdjacent)
22474
            return this.result(-100 /* Penalty.ByWord */ + (byWordFolded ? -200 /* Penalty.CaseFold */ : 0), byWord, word);
22475
        if (adjacentTo == len && adjacentStart == 0)
22476
            return this.ret(-200 /* Penalty.CaseFold */ - word.length + (adjacentEnd == word.length ? 0 : -100 /* Penalty.NotFull */), [0, adjacentEnd]);
22477
        if (direct > -1)
22478
            return this.ret(-700 /* Penalty.NotStart */ - word.length, [direct, direct + this.pattern.length]);
22479
        if (adjacentTo == len)
22480
            return this.ret(-200 /* Penalty.CaseFold */ + -700 /* Penalty.NotStart */ - word.length, [adjacentStart, adjacentEnd]);
22481
        if (byWordTo == len)
22482
            return this.result(-100 /* Penalty.ByWord */ + (byWordFolded ? -200 /* Penalty.CaseFold */ : 0) + -700 /* Penalty.NotStart */ +
22483
                (wordAdjacent ? 0 : -1100 /* Penalty.Gap */), byWord, word);
22484
        return chars.length == 2 ? null
22485
            : this.result((any[0] ? -700 /* Penalty.NotStart */ : 0) + -200 /* Penalty.CaseFold */ + -1100 /* Penalty.Gap */, any, word);
22486
    }
22487
    result(score, positions, word) {
22488
        let result = [], i = 0;
22489
        for (let pos of positions) {
22490
            let to = pos + (this.astral ? codePointSize(codePointAt(word, pos)) : 1);
22491
            if (i && result[i - 1] == pos)
22492
                result[i - 1] = to;
22493
            else {
22494
                result[i++] = pos;
22495
                result[i++] = to;
22496
            }
22497
        }
22498
        return this.ret(score - word.length, result);
22499
    }
22500
}
22501
class StrictMatcher {
22502
    constructor(pattern) {
22503
        this.pattern = pattern;
22504
        this.matched = [];
22505
        this.score = 0;
22506
        this.folded = pattern.toLowerCase();
22507
    }
22508
    match(word) {
22509
        if (word.length < this.pattern.length)
22510
            return null;
22511
        let start = word.slice(0, this.pattern.length);
22512
        let match = start == this.pattern ? 0 : start.toLowerCase() == this.folded ? -200 /* Penalty.CaseFold */ : null;
22513
        if (match == null)
22514
            return null;
22515
        this.matched = [0, start.length];
22516
        this.score = match + (word.length == this.pattern.length ? 0 : -100 /* Penalty.NotFull */);
22517
        return this;
22518
    }
22519
}
22520
 
22521
const completionConfig = /*@__PURE__*/Facet.define({
22522
    combine(configs) {
22523
        return combineConfig(configs, {
22524
            activateOnTyping: true,
22525
            activateOnTypingDelay: 100,
22526
            selectOnOpen: true,
22527
            override: null,
22528
            closeOnBlur: true,
22529
            maxRenderedOptions: 100,
22530
            defaultKeymap: true,
22531
            tooltipClass: () => "",
22532
            optionClass: () => "",
22533
            aboveCursor: false,
22534
            icons: true,
22535
            addToOptions: [],
22536
            positionInfo: defaultPositionInfo,
22537
            filterStrict: false,
22538
            compareCompletions: (a, b) => a.label.localeCompare(b.label),
22539
            interactionDelay: 75,
22540
            updateSyncTime: 100
22541
        }, {
22542
            defaultKeymap: (a, b) => a && b,
22543
            closeOnBlur: (a, b) => a && b,
22544
            icons: (a, b) => a && b,
22545
            tooltipClass: (a, b) => c => joinClass(a(c), b(c)),
22546
            optionClass: (a, b) => c => joinClass(a(c), b(c)),
22547
            addToOptions: (a, b) => a.concat(b),
22548
            filterStrict: (a, b) => a || b,
22549
        });
22550
    }
22551
});
22552
function joinClass(a, b) {
22553
    return a ? b ? a + " " + b : a : b;
22554
}
22555
function defaultPositionInfo(view, list, option, info, space, tooltip) {
22556
    let rtl = view.textDirection == Direction.RTL, left = rtl, narrow = false;
22557
    let side = "top", offset, maxWidth;
22558
    let spaceLeft = list.left - space.left, spaceRight = space.right - list.right;
22559
    let infoWidth = info.right - info.left, infoHeight = info.bottom - info.top;
22560
    if (left && spaceLeft < Math.min(infoWidth, spaceRight))
22561
        left = false;
22562
    else if (!left && spaceRight < Math.min(infoWidth, spaceLeft))
22563
        left = true;
22564
    if (infoWidth <= (left ? spaceLeft : spaceRight)) {
22565
        offset = Math.max(space.top, Math.min(option.top, space.bottom - infoHeight)) - list.top;
22566
        maxWidth = Math.min(400 /* Info.Width */, left ? spaceLeft : spaceRight);
22567
    }
22568
    else {
22569
        narrow = true;
22570
        maxWidth = Math.min(400 /* Info.Width */, (rtl ? list.right : space.right - list.left) - 30 /* Info.Margin */);
22571
        let spaceBelow = space.bottom - list.bottom;
22572
        if (spaceBelow >= infoHeight || spaceBelow > list.top) { // Below the completion
22573
            offset = option.bottom - list.top;
22574
        }
22575
        else { // Above it
22576
            side = "bottom";
22577
            offset = list.bottom - option.top;
22578
        }
22579
    }
22580
    let scaleY = (list.bottom - list.top) / tooltip.offsetHeight;
22581
    let scaleX = (list.right - list.left) / tooltip.offsetWidth;
22582
    return {
22583
        style: `${side}: ${offset / scaleY}px; max-width: ${maxWidth / scaleX}px`,
22584
        class: "cm-completionInfo-" + (narrow ? (rtl ? "left-narrow" : "right-narrow") : left ? "left" : "right")
22585
    };
22586
}
22587
 
22588
function optionContent(config) {
22589
    let content = config.addToOptions.slice();
22590
    if (config.icons)
22591
        content.push({
22592
            render(completion) {
22593
                let icon = document.createElement("div");
22594
                icon.classList.add("cm-completionIcon");
22595
                if (completion.type)
22596
                    icon.classList.add(...completion.type.split(/\s+/g).map(cls => "cm-completionIcon-" + cls));
22597
                icon.setAttribute("aria-hidden", "true");
22598
                return icon;
22599
            },
22600
            position: 20
22601
        });
22602
    content.push({
22603
        render(completion, _s, _v, match) {
22604
            let labelElt = document.createElement("span");
22605
            labelElt.className = "cm-completionLabel";
22606
            let label = completion.displayLabel || completion.label, off = 0;
22607
            for (let j = 0; j < match.length;) {
22608
                let from = match[j++], to = match[j++];
22609
                if (from > off)
22610
                    labelElt.appendChild(document.createTextNode(label.slice(off, from)));
22611
                let span = labelElt.appendChild(document.createElement("span"));
22612
                span.appendChild(document.createTextNode(label.slice(from, to)));
22613
                span.className = "cm-completionMatchedText";
22614
                off = to;
22615
            }
22616
            if (off < label.length)
22617
                labelElt.appendChild(document.createTextNode(label.slice(off)));
22618
            return labelElt;
22619
        },
22620
        position: 50
22621
    }, {
22622
        render(completion) {
22623
            if (!completion.detail)
22624
                return null;
22625
            let detailElt = document.createElement("span");
22626
            detailElt.className = "cm-completionDetail";
22627
            detailElt.textContent = completion.detail;
22628
            return detailElt;
22629
        },
22630
        position: 80
22631
    });
22632
    return content.sort((a, b) => a.position - b.position).map(a => a.render);
22633
}
22634
function rangeAroundSelected(total, selected, max) {
22635
    if (total <= max)
22636
        return { from: 0, to: total };
22637
    if (selected < 0)
22638
        selected = 0;
22639
    if (selected <= (total >> 1)) {
22640
        let off = Math.floor(selected / max);
22641
        return { from: off * max, to: (off + 1) * max };
22642
    }
22643
    let off = Math.floor((total - selected) / max);
22644
    return { from: total - (off + 1) * max, to: total - off * max };
22645
}
22646
class CompletionTooltip {
22647
    constructor(view, stateField, applyCompletion) {
22648
        this.view = view;
22649
        this.stateField = stateField;
22650
        this.applyCompletion = applyCompletion;
22651
        this.info = null;
22652
        this.infoDestroy = null;
22653
        this.placeInfoReq = {
22654
            read: () => this.measureInfo(),
22655
            write: (pos) => this.placeInfo(pos),
22656
            key: this
22657
        };
22658
        this.space = null;
22659
        this.currentClass = "";
22660
        let cState = view.state.field(stateField);
22661
        let { options, selected } = cState.open;
22662
        let config = view.state.facet(completionConfig);
22663
        this.optionContent = optionContent(config);
22664
        this.optionClass = config.optionClass;
22665
        this.tooltipClass = config.tooltipClass;
22666
        this.range = rangeAroundSelected(options.length, selected, config.maxRenderedOptions);
22667
        this.dom = document.createElement("div");
22668
        this.dom.className = "cm-tooltip-autocomplete";
22669
        this.updateTooltipClass(view.state);
22670
        this.dom.addEventListener("mousedown", (e) => {
22671
            let { options } = view.state.field(stateField).open;
22672
            for (let dom = e.target, match; dom && dom != this.dom; dom = dom.parentNode) {
22673
                if (dom.nodeName == "LI" && (match = /-(\d+)$/.exec(dom.id)) && +match[1] < options.length) {
22674
                    this.applyCompletion(view, options[+match[1]]);
22675
                    e.preventDefault();
22676
                    return;
22677
                }
22678
            }
22679
        });
22680
        this.dom.addEventListener("focusout", (e) => {
22681
            let state = view.state.field(this.stateField, false);
22682
            if (state && state.tooltip && view.state.facet(completionConfig).closeOnBlur &&
22683
                e.relatedTarget != view.contentDOM)
22684
                view.dispatch({ effects: closeCompletionEffect.of(null) });
22685
        });
22686
        this.showOptions(options, cState.id);
22687
    }
22688
    mount() { this.updateSel(); }
22689
    showOptions(options, id) {
22690
        if (this.list)
22691
            this.list.remove();
22692
        this.list = this.dom.appendChild(this.createListBox(options, id, this.range));
22693
        this.list.addEventListener("scroll", () => {
22694
            if (this.info)
22695
                this.view.requestMeasure(this.placeInfoReq);
22696
        });
22697
    }
22698
    update(update) {
22699
        var _a;
22700
        let cState = update.state.field(this.stateField);
22701
        let prevState = update.startState.field(this.stateField);
22702
        this.updateTooltipClass(update.state);
22703
        if (cState != prevState) {
22704
            let { options, selected, disabled } = cState.open;
22705
            if (!prevState.open || prevState.open.options != options) {
22706
                this.range = rangeAroundSelected(options.length, selected, update.state.facet(completionConfig).maxRenderedOptions);
22707
                this.showOptions(options, cState.id);
22708
            }
22709
            this.updateSel();
22710
            if (disabled != ((_a = prevState.open) === null || _a === void 0 ? void 0 : _a.disabled))
22711
                this.dom.classList.toggle("cm-tooltip-autocomplete-disabled", !!disabled);
22712
        }
22713
    }
22714
    updateTooltipClass(state) {
22715
        let cls = this.tooltipClass(state);
22716
        if (cls != this.currentClass) {
22717
            for (let c of this.currentClass.split(" "))
22718
                if (c)
22719
                    this.dom.classList.remove(c);
22720
            for (let c of cls.split(" "))
22721
                if (c)
22722
                    this.dom.classList.add(c);
22723
            this.currentClass = cls;
22724
        }
22725
    }
22726
    positioned(space) {
22727
        this.space = space;
22728
        if (this.info)
22729
            this.view.requestMeasure(this.placeInfoReq);
22730
    }
22731
    updateSel() {
22732
        let cState = this.view.state.field(this.stateField), open = cState.open;
22733
        if (open.selected > -1 && open.selected < this.range.from || open.selected >= this.range.to) {
22734
            this.range = rangeAroundSelected(open.options.length, open.selected, this.view.state.facet(completionConfig).maxRenderedOptions);
22735
            this.showOptions(open.options, cState.id);
22736
        }
22737
        if (this.updateSelectedOption(open.selected)) {
22738
            this.destroyInfo();
22739
            let { completion } = open.options[open.selected];
22740
            let { info } = completion;
22741
            if (!info)
22742
                return;
22743
            let infoResult = typeof info === "string" ? document.createTextNode(info) : info(completion);
22744
            if (!infoResult)
22745
                return;
22746
            if ("then" in infoResult) {
22747
                infoResult.then(obj => {
22748
                    if (obj && this.view.state.field(this.stateField, false) == cState)
22749
                        this.addInfoPane(obj, completion);
22750
                }).catch(e => logException(this.view.state, e, "completion info"));
22751
            }
22752
            else {
22753
                this.addInfoPane(infoResult, completion);
22754
            }
22755
        }
22756
    }
22757
    addInfoPane(content, completion) {
22758
        this.destroyInfo();
22759
        let wrap = this.info = document.createElement("div");
22760
        wrap.className = "cm-tooltip cm-completionInfo";
22761
        if (content.nodeType != null) {
22762
            wrap.appendChild(content);
22763
            this.infoDestroy = null;
22764
        }
22765
        else {
22766
            let { dom, destroy } = content;
22767
            wrap.appendChild(dom);
22768
            this.infoDestroy = destroy || null;
22769
        }
22770
        this.dom.appendChild(wrap);
22771
        this.view.requestMeasure(this.placeInfoReq);
22772
    }
22773
    updateSelectedOption(selected) {
22774
        let set = null;
22775
        for (let opt = this.list.firstChild, i = this.range.from; opt; opt = opt.nextSibling, i++) {
22776
            if (opt.nodeName != "LI" || !opt.id) {
22777
                i--; // A section header
22778
            }
22779
            else if (i == selected) {
22780
                if (!opt.hasAttribute("aria-selected")) {
22781
                    opt.setAttribute("aria-selected", "true");
22782
                    set = opt;
22783
                }
22784
            }
22785
            else {
22786
                if (opt.hasAttribute("aria-selected"))
22787
                    opt.removeAttribute("aria-selected");
22788
            }
22789
        }
22790
        if (set)
22791
            scrollIntoView(this.list, set);
22792
        return set;
22793
    }
22794
    measureInfo() {
22795
        let sel = this.dom.querySelector("[aria-selected]");
22796
        if (!sel || !this.info)
22797
            return null;
22798
        let listRect = this.dom.getBoundingClientRect();
22799
        let infoRect = this.info.getBoundingClientRect();
22800
        let selRect = sel.getBoundingClientRect();
22801
        let space = this.space;
22802
        if (!space) {
22803
            let win = this.dom.ownerDocument.defaultView || window;
22804
            space = { left: 0, top: 0, right: win.innerWidth, bottom: win.innerHeight };
22805
        }
22806
        if (selRect.top > Math.min(space.bottom, listRect.bottom) - 10 ||
22807
            selRect.bottom < Math.max(space.top, listRect.top) + 10)
22808
            return null;
22809
        return this.view.state.facet(completionConfig).positionInfo(this.view, listRect, selRect, infoRect, space, this.dom);
22810
    }
22811
    placeInfo(pos) {
22812
        if (this.info) {
22813
            if (pos) {
22814
                if (pos.style)
22815
                    this.info.style.cssText = pos.style;
22816
                this.info.className = "cm-tooltip cm-completionInfo " + (pos.class || "");
22817
            }
22818
            else {
22819
                this.info.style.cssText = "top: -1e6px";
22820
            }
22821
        }
22822
    }
22823
    createListBox(options, id, range) {
22824
        const ul = document.createElement("ul");
22825
        ul.id = id;
22826
        ul.setAttribute("role", "listbox");
22827
        ul.setAttribute("aria-expanded", "true");
22828
        ul.setAttribute("aria-label", this.view.state.phrase("Completions"));
22829
        let curSection = null;
22830
        for (let i = range.from; i < range.to; i++) {
22831
            let { completion, match } = options[i], { section } = completion;
22832
            if (section) {
22833
                let name = typeof section == "string" ? section : section.name;
22834
                if (name != curSection && (i > range.from || range.from == 0)) {
22835
                    curSection = name;
22836
                    if (typeof section != "string" && section.header) {
22837
                        ul.appendChild(section.header(section));
22838
                    }
22839
                    else {
22840
                        let header = ul.appendChild(document.createElement("completion-section"));
22841
                        header.textContent = name;
22842
                    }
22843
                }
22844
            }
22845
            const li = ul.appendChild(document.createElement("li"));
22846
            li.id = id + "-" + i;
22847
            li.setAttribute("role", "option");
22848
            let cls = this.optionClass(completion);
22849
            if (cls)
22850
                li.className = cls;
22851
            for (let source of this.optionContent) {
22852
                let node = source(completion, this.view.state, this.view, match);
22853
                if (node)
22854
                    li.appendChild(node);
22855
            }
22856
        }
22857
        if (range.from)
22858
            ul.classList.add("cm-completionListIncompleteTop");
22859
        if (range.to < options.length)
22860
            ul.classList.add("cm-completionListIncompleteBottom");
22861
        return ul;
22862
    }
22863
    destroyInfo() {
22864
        if (this.info) {
22865
            if (this.infoDestroy)
22866
                this.infoDestroy();
22867
            this.info.remove();
22868
            this.info = null;
22869
        }
22870
    }
22871
    destroy() {
22872
        this.destroyInfo();
22873
    }
22874
}
22875
function completionTooltip(stateField, applyCompletion) {
22876
    return (view) => new CompletionTooltip(view, stateField, applyCompletion);
22877
}
22878
function scrollIntoView(container, element) {
22879
    let parent = container.getBoundingClientRect();
22880
    let self = element.getBoundingClientRect();
22881
    let scaleY = parent.height / container.offsetHeight;
22882
    if (self.top < parent.top)
22883
        container.scrollTop -= (parent.top - self.top) / scaleY;
22884
    else if (self.bottom > parent.bottom)
22885
        container.scrollTop += (self.bottom - parent.bottom) / scaleY;
22886
}
22887
 
22888
// Used to pick a preferred option when two options with the same
22889
// label occur in the result.
22890
function score(option) {
22891
    return (option.boost || 0) * 100 + (option.apply ? 10 : 0) + (option.info ? 5 : 0) +
22892
        (option.type ? 1 : 0);
22893
}
22894
function sortOptions(active, state) {
22895
    let options = [];
22896
    let sections = null;
22897
    let addOption = (option) => {
22898
        options.push(option);
22899
        let { section } = option.completion;
22900
        if (section) {
22901
            if (!sections)
22902
                sections = [];
22903
            let name = typeof section == "string" ? section : section.name;
22904
            if (!sections.some(s => s.name == name))
22905
                sections.push(typeof section == "string" ? { name } : section);
22906
        }
22907
    };
22908
    let conf = state.facet(completionConfig);
22909
    for (let a of active)
22910
        if (a.hasResult()) {
22911
            let getMatch = a.result.getMatch;
22912
            if (a.result.filter === false) {
22913
                for (let option of a.result.options) {
22914
                    addOption(new Option(option, a.source, getMatch ? getMatch(option) : [], 1e9 - options.length));
22915
                }
22916
            }
22917
            else {
22918
                let pattern = state.sliceDoc(a.from, a.to), match;
22919
                let matcher = conf.filterStrict ? new StrictMatcher(pattern) : new FuzzyMatcher(pattern);
22920
                for (let option of a.result.options)
22921
                    if (match = matcher.match(option.label)) {
22922
                        let matched = !option.displayLabel ? match.matched : getMatch ? getMatch(option, match.matched) : [];
22923
                        addOption(new Option(option, a.source, matched, match.score + (option.boost || 0)));
22924
                    }
22925
            }
22926
        }
22927
    if (sections) {
22928
        let sectionOrder = Object.create(null), pos = 0;
22929
        let cmp = (a, b) => { var _a, _b; return ((_a = a.rank) !== null && _a !== void 0 ? _a : 1e9) - ((_b = b.rank) !== null && _b !== void 0 ? _b : 1e9) || (a.name < b.name ? -1 : 1); };
22930
        for (let s of sections.sort(cmp)) {
22931
            pos -= 1e5;
22932
            sectionOrder[s.name] = pos;
22933
        }
22934
        for (let option of options) {
22935
            let { section } = option.completion;
22936
            if (section)
22937
                option.score += sectionOrder[typeof section == "string" ? section : section.name];
22938
        }
22939
    }
22940
    let result = [], prev = null;
22941
    let compare = conf.compareCompletions;
22942
    for (let opt of options.sort((a, b) => (b.score - a.score) || compare(a.completion, b.completion))) {
22943
        let cur = opt.completion;
22944
        if (!prev || prev.label != cur.label || prev.detail != cur.detail ||
22945
            (prev.type != null && cur.type != null && prev.type != cur.type) ||
22946
            prev.apply != cur.apply || prev.boost != cur.boost)
22947
            result.push(opt);
22948
        else if (score(opt.completion) > score(prev))
22949
            result[result.length - 1] = opt;
22950
        prev = opt.completion;
22951
    }
22952
    return result;
22953
}
22954
class CompletionDialog {
22955
    constructor(options, attrs, tooltip, timestamp, selected, disabled) {
22956
        this.options = options;
22957
        this.attrs = attrs;
22958
        this.tooltip = tooltip;
22959
        this.timestamp = timestamp;
22960
        this.selected = selected;
22961
        this.disabled = disabled;
22962
    }
22963
    setSelected(selected, id) {
22964
        return selected == this.selected || selected >= this.options.length ? this
22965
            : new CompletionDialog(this.options, makeAttrs(id, selected), this.tooltip, this.timestamp, selected, this.disabled);
22966
    }
22967
    static build(active, state, id, prev, conf) {
22968
        let options = sortOptions(active, state);
22969
        if (!options.length) {
22970
            return prev && active.some(a => a.state == 1 /* State.Pending */) ?
22971
                new CompletionDialog(prev.options, prev.attrs, prev.tooltip, prev.timestamp, prev.selected, true) : null;
22972
        }
22973
        let selected = state.facet(completionConfig).selectOnOpen ? 0 : -1;
22974
        if (prev && prev.selected != selected && prev.selected != -1) {
22975
            let selectedValue = prev.options[prev.selected].completion;
22976
            for (let i = 0; i < options.length; i++)
22977
                if (options[i].completion == selectedValue) {
22978
                    selected = i;
22979
                    break;
22980
                }
22981
        }
22982
        return new CompletionDialog(options, makeAttrs(id, selected), {
22983
            pos: active.reduce((a, b) => b.hasResult() ? Math.min(a, b.from) : a, 1e8),
22984
            create: createTooltip,
22985
            above: conf.aboveCursor,
22986
        }, prev ? prev.timestamp : Date.now(), selected, false);
22987
    }
22988
    map(changes) {
22989
        return new CompletionDialog(this.options, this.attrs, Object.assign(Object.assign({}, this.tooltip), { pos: changes.mapPos(this.tooltip.pos) }), this.timestamp, this.selected, this.disabled);
22990
    }
22991
}
22992
class CompletionState {
22993
    constructor(active, id, open) {
22994
        this.active = active;
22995
        this.id = id;
22996
        this.open = open;
22997
    }
22998
    static start() {
22999
        return new CompletionState(none, "cm-ac-" + Math.floor(Math.random() * 2e6).toString(36), null);
23000
    }
23001
    update(tr) {
23002
        let { state } = tr, conf = state.facet(completionConfig);
23003
        let sources = conf.override ||
23004
            state.languageDataAt("autocomplete", cur(state)).map(asSource);
23005
        let active = sources.map(source => {
23006
            let value = this.active.find(s => s.source == source) ||
23007
                new ActiveSource(source, this.active.some(a => a.state != 0 /* State.Inactive */) ? 1 /* State.Pending */ : 0 /* State.Inactive */);
23008
            return value.update(tr, conf);
23009
        });
23010
        if (active.length == this.active.length && active.every((a, i) => a == this.active[i]))
23011
            active = this.active;
23012
        let open = this.open;
23013
        if (open && tr.docChanged)
23014
            open = open.map(tr.changes);
23015
        if (tr.selection || active.some(a => a.hasResult() && tr.changes.touchesRange(a.from, a.to)) ||
23016
            !sameResults(active, this.active))
23017
            open = CompletionDialog.build(active, state, this.id, open, conf);
23018
        else if (open && open.disabled && !active.some(a => a.state == 1 /* State.Pending */))
23019
            open = null;
23020
        if (!open && active.every(a => a.state != 1 /* State.Pending */) && active.some(a => a.hasResult()))
23021
            active = active.map(a => a.hasResult() ? new ActiveSource(a.source, 0 /* State.Inactive */) : a);
23022
        for (let effect of tr.effects)
23023
            if (effect.is(setSelectedEffect))
23024
                open = open && open.setSelected(effect.value, this.id);
23025
        return active == this.active && open == this.open ? this : new CompletionState(active, this.id, open);
23026
    }
23027
    get tooltip() { return this.open ? this.open.tooltip : null; }
23028
    get attrs() { return this.open ? this.open.attrs : baseAttrs; }
23029
}
23030
function sameResults(a, b) {
23031
    if (a == b)
23032
        return true;
23033
    for (let iA = 0, iB = 0;;) {
23034
        while (iA < a.length && !a[iA].hasResult)
23035
            iA++;
23036
        while (iB < b.length && !b[iB].hasResult)
23037
            iB++;
23038
        let endA = iA == a.length, endB = iB == b.length;
23039
        if (endA || endB)
23040
            return endA == endB;
23041
        if (a[iA++].result != b[iB++].result)
23042
            return false;
23043
    }
23044
}
23045
const baseAttrs = {
23046
    "aria-autocomplete": "list"
23047
};
23048
function makeAttrs(id, selected) {
23049
    let result = {
23050
        "aria-autocomplete": "list",
23051
        "aria-haspopup": "listbox",
23052
        "aria-controls": id
23053
    };
23054
    if (selected > -1)
23055
        result["aria-activedescendant"] = id + "-" + selected;
23056
    return result;
23057
}
23058
const none = [];
23059
function getUserEvent(tr) {
23060
    return tr.isUserEvent("input.type") ? "input" : tr.isUserEvent("delete.backward") ? "delete" : null;
23061
}
23062
class ActiveSource {
23063
    constructor(source, state, explicitPos = -1) {
23064
        this.source = source;
23065
        this.state = state;
23066
        this.explicitPos = explicitPos;
23067
    }
23068
    hasResult() { return false; }
23069
    update(tr, conf) {
23070
        let event = getUserEvent(tr), value = this;
23071
        if (event)
23072
            value = value.handleUserEvent(tr, event, conf);
23073
        else if (tr.docChanged)
23074
            value = value.handleChange(tr);
23075
        else if (tr.selection && value.state != 0 /* State.Inactive */)
23076
            value = new ActiveSource(value.source, 0 /* State.Inactive */);
23077
        for (let effect of tr.effects) {
23078
            if (effect.is(startCompletionEffect))
23079
                value = new ActiveSource(value.source, 1 /* State.Pending */, effect.value ? cur(tr.state) : -1);
23080
            else if (effect.is(closeCompletionEffect))
23081
                value = new ActiveSource(value.source, 0 /* State.Inactive */);
23082
            else if (effect.is(setActiveEffect))
23083
                for (let active of effect.value)
23084
                    if (active.source == value.source)
23085
                        value = active;
23086
        }
23087
        return value;
23088
    }
23089
    handleUserEvent(tr, type, conf) {
23090
        return type == "delete" || !conf.activateOnTyping ? this.map(tr.changes) : new ActiveSource(this.source, 1 /* State.Pending */);
23091
    }
23092
    handleChange(tr) {
23093
        return tr.changes.touchesRange(cur(tr.startState)) ? new ActiveSource(this.source, 0 /* State.Inactive */) : this.map(tr.changes);
23094
    }
23095
    map(changes) {
23096
        return changes.empty || this.explicitPos < 0 ? this : new ActiveSource(this.source, this.state, changes.mapPos(this.explicitPos));
23097
    }
23098
}
23099
class ActiveResult extends ActiveSource {
23100
    constructor(source, explicitPos, result, from, to) {
23101
        super(source, 2 /* State.Result */, explicitPos);
23102
        this.result = result;
23103
        this.from = from;
23104
        this.to = to;
23105
    }
23106
    hasResult() { return true; }
23107
    handleUserEvent(tr, type, conf) {
23108
        var _a;
23109
        let result = this.result;
23110
        if (result.map && !tr.changes.empty)
23111
            result = result.map(result, tr.changes);
23112
        let from = tr.changes.mapPos(this.from), to = tr.changes.mapPos(this.to, 1);
23113
        let pos = cur(tr.state);
23114
        if ((this.explicitPos < 0 ? pos <= from : pos < this.from) ||
23115
            pos > to || !result ||
23116
            type == "delete" && cur(tr.startState) == this.from)
23117
            return new ActiveSource(this.source, type == "input" && conf.activateOnTyping ? 1 /* State.Pending */ : 0 /* State.Inactive */);
23118
        let explicitPos = this.explicitPos < 0 ? -1 : tr.changes.mapPos(this.explicitPos);
23119
        if (checkValid(result.validFor, tr.state, from, to))
23120
            return new ActiveResult(this.source, explicitPos, result, from, to);
23121
        if (result.update &&
23122
            (result = result.update(result, from, to, new CompletionContext(tr.state, pos, explicitPos >= 0))))
23123
            return new ActiveResult(this.source, explicitPos, result, result.from, (_a = result.to) !== null && _a !== void 0 ? _a : cur(tr.state));
23124
        return new ActiveSource(this.source, 1 /* State.Pending */, explicitPos);
23125
    }
23126
    handleChange(tr) {
23127
        return tr.changes.touchesRange(this.from, this.to) ? new ActiveSource(this.source, 0 /* State.Inactive */) : this.map(tr.changes);
23128
    }
23129
    map(mapping) {
23130
        if (mapping.empty)
23131
            return this;
23132
        let result = this.result.map ? this.result.map(this.result, mapping) : this.result;
23133
        if (!result)
23134
            return new ActiveSource(this.source, 0 /* State.Inactive */);
23135
        return new ActiveResult(this.source, this.explicitPos < 0 ? -1 : mapping.mapPos(this.explicitPos), this.result, mapping.mapPos(this.from), mapping.mapPos(this.to, 1));
23136
    }
23137
}
23138
function checkValid(validFor, state, from, to) {
23139
    if (!validFor)
23140
        return false;
23141
    let text = state.sliceDoc(from, to);
23142
    return typeof validFor == "function" ? validFor(text, from, to, state) : ensureAnchor(validFor, true).test(text);
23143
}
23144
const setActiveEffect = /*@__PURE__*/StateEffect.define({
23145
    map(sources, mapping) { return sources.map(s => s.map(mapping)); }
23146
});
23147
const setSelectedEffect = /*@__PURE__*/StateEffect.define();
23148
const completionState = /*@__PURE__*/StateField.define({
23149
    create() { return CompletionState.start(); },
23150
    update(value, tr) { return value.update(tr); },
23151
    provide: f => [
23152
        showTooltip.from(f, val => val.tooltip),
23153
        EditorView.contentAttributes.from(f, state => state.attrs)
23154
    ]
23155
});
23156
function applyCompletion(view, option) {
23157
    const apply = option.completion.apply || option.completion.label;
23158
    let result = view.state.field(completionState).active.find(a => a.source == option.source);
23159
    if (!(result instanceof ActiveResult))
23160
        return false;
23161
    if (typeof apply == "string")
23162
        view.dispatch(Object.assign(Object.assign({}, insertCompletionText(view.state, apply, result.from, result.to)), { annotations: pickedCompletion.of(option.completion) }));
23163
    else
23164
        apply(view, option.completion, result.from, result.to);
23165
    return true;
23166
}
23167
const createTooltip = /*@__PURE__*/completionTooltip(completionState, applyCompletion);
23168
 
23169
/**
23170
Returns a command that moves the completion selection forward or
23171
backward by the given amount.
23172
*/
23173
function moveCompletionSelection(forward, by = "option") {
23174
    return (view) => {
23175
        let cState = view.state.field(completionState, false);
23176
        if (!cState || !cState.open || cState.open.disabled ||
23177
            Date.now() - cState.open.timestamp < view.state.facet(completionConfig).interactionDelay)
23178
            return false;
23179
        let step = 1, tooltip;
23180
        if (by == "page" && (tooltip = getTooltip(view, cState.open.tooltip)))
23181
            step = Math.max(2, Math.floor(tooltip.dom.offsetHeight /
23182
                tooltip.dom.querySelector("li").offsetHeight) - 1);
23183
        let { length } = cState.open.options;
23184
        let selected = cState.open.selected > -1 ? cState.open.selected + step * (forward ? 1 : -1) : forward ? 0 : length - 1;
23185
        if (selected < 0)
23186
            selected = by == "page" ? 0 : length - 1;
23187
        else if (selected >= length)
23188
            selected = by == "page" ? length - 1 : 0;
23189
        view.dispatch({ effects: setSelectedEffect.of(selected) });
23190
        return true;
23191
    };
23192
}
23193
/**
23194
Accept the current completion.
23195
*/
23196
const acceptCompletion = (view) => {
23197
    let cState = view.state.field(completionState, false);
23198
    if (view.state.readOnly || !cState || !cState.open || cState.open.selected < 0 || cState.open.disabled ||
23199
        Date.now() - cState.open.timestamp < view.state.facet(completionConfig).interactionDelay)
23200
        return false;
23201
    return applyCompletion(view, cState.open.options[cState.open.selected]);
23202
};
23203
/**
23204
Explicitly start autocompletion.
23205
*/
23206
const startCompletion = (view) => {
23207
    let cState = view.state.field(completionState, false);
23208
    if (!cState)
23209
        return false;
23210
    view.dispatch({ effects: startCompletionEffect.of(true) });
23211
    return true;
23212
};
23213
/**
23214
Close the currently active completion.
23215
*/
23216
const closeCompletion = (view) => {
23217
    let cState = view.state.field(completionState, false);
23218
    if (!cState || !cState.active.some(a => a.state != 0 /* State.Inactive */))
23219
        return false;
23220
    view.dispatch({ effects: closeCompletionEffect.of(null) });
23221
    return true;
23222
};
23223
class RunningQuery {
23224
    constructor(active, context) {
23225
        this.active = active;
23226
        this.context = context;
23227
        this.time = Date.now();
23228
        this.updates = [];
23229
        // Note that 'undefined' means 'not done yet', whereas 'null' means
23230
        // 'query returned null'.
23231
        this.done = undefined;
23232
    }
23233
}
23234
const MaxUpdateCount = 50, MinAbortTime = 1000;
23235
const completionPlugin = /*@__PURE__*/ViewPlugin.fromClass(class {
23236
    constructor(view) {
23237
        this.view = view;
23238
        this.debounceUpdate = -1;
23239
        this.running = [];
23240
        this.debounceAccept = -1;
23241
        this.pendingStart = false;
23242
        this.composing = 0 /* CompositionState.None */;
23243
        for (let active of view.state.field(completionState).active)
23244
            if (active.state == 1 /* State.Pending */)
23245
                this.startQuery(active);
23246
    }
23247
    update(update) {
23248
        let cState = update.state.field(completionState);
23249
        if (!update.selectionSet && !update.docChanged && update.startState.field(completionState) == cState)
23250
            return;
23251
        let doesReset = update.transactions.some(tr => {
23252
            return (tr.selection || tr.docChanged) && !getUserEvent(tr);
23253
        });
23254
        for (let i = 0; i < this.running.length; i++) {
23255
            let query = this.running[i];
23256
            if (doesReset ||
23257
                query.updates.length + update.transactions.length > MaxUpdateCount && Date.now() - query.time > MinAbortTime) {
23258
                for (let handler of query.context.abortListeners) {
23259
                    try {
23260
                        handler();
23261
                    }
23262
                    catch (e) {
23263
                        logException(this.view.state, e);
23264
                    }
23265
                }
23266
                query.context.abortListeners = null;
23267
                this.running.splice(i--, 1);
23268
            }
23269
            else {
23270
                query.updates.push(...update.transactions);
23271
            }
23272
        }
23273
        if (this.debounceUpdate > -1)
23274
            clearTimeout(this.debounceUpdate);
23275
        if (update.transactions.some(tr => tr.effects.some(e => e.is(startCompletionEffect))))
23276
            this.pendingStart = true;
23277
        let delay = this.pendingStart ? 50 : update.state.facet(completionConfig).activateOnTypingDelay;
23278
        this.debounceUpdate = cState.active.some(a => a.state == 1 /* State.Pending */ && !this.running.some(q => q.active.source == a.source))
23279
            ? setTimeout(() => this.startUpdate(), delay) : -1;
23280
        if (this.composing != 0 /* CompositionState.None */)
23281
            for (let tr of update.transactions) {
23282
                if (getUserEvent(tr) == "input")
23283
                    this.composing = 2 /* CompositionState.Changed */;
23284
                else if (this.composing == 2 /* CompositionState.Changed */ && tr.selection)
23285
                    this.composing = 3 /* CompositionState.ChangedAndMoved */;
23286
            }
23287
    }
23288
    startUpdate() {
23289
        this.debounceUpdate = -1;
23290
        this.pendingStart = false;
23291
        let { state } = this.view, cState = state.field(completionState);
23292
        for (let active of cState.active) {
23293
            if (active.state == 1 /* State.Pending */ && !this.running.some(r => r.active.source == active.source))
23294
                this.startQuery(active);
23295
        }
23296
    }
23297
    startQuery(active) {
23298
        let { state } = this.view, pos = cur(state);
23299
        let context = new CompletionContext(state, pos, active.explicitPos == pos);
23300
        let pending = new RunningQuery(active, context);
23301
        this.running.push(pending);
23302
        Promise.resolve(active.source(context)).then(result => {
23303
            if (!pending.context.aborted) {
23304
                pending.done = result || null;
23305
                this.scheduleAccept();
23306
            }
23307
        }, err => {
23308
            this.view.dispatch({ effects: closeCompletionEffect.of(null) });
23309
            logException(this.view.state, err);
23310
        });
23311
    }
23312
    scheduleAccept() {
23313
        if (this.running.every(q => q.done !== undefined))
23314
            this.accept();
23315
        else if (this.debounceAccept < 0)
23316
            this.debounceAccept = setTimeout(() => this.accept(), this.view.state.facet(completionConfig).updateSyncTime);
23317
    }
23318
    // For each finished query in this.running, try to create a result
23319
    // or, if appropriate, restart the query.
23320
    accept() {
23321
        var _a;
23322
        if (this.debounceAccept > -1)
23323
            clearTimeout(this.debounceAccept);
23324
        this.debounceAccept = -1;
23325
        let updated = [];
23326
        let conf = this.view.state.facet(completionConfig);
23327
        for (let i = 0; i < this.running.length; i++) {
23328
            let query = this.running[i];
23329
            if (query.done === undefined)
23330
                continue;
23331
            this.running.splice(i--, 1);
23332
            if (query.done) {
23333
                let active = new ActiveResult(query.active.source, query.active.explicitPos, query.done, query.done.from, (_a = query.done.to) !== null && _a !== void 0 ? _a : cur(query.updates.length ? query.updates[0].startState : this.view.state));
23334
                // Replay the transactions that happened since the start of
23335
                // the request and see if that preserves the result
23336
                for (let tr of query.updates)
23337
                    active = active.update(tr, conf);
23338
                if (active.hasResult()) {
23339
                    updated.push(active);
23340
                    continue;
23341
                }
23342
            }
23343
            let current = this.view.state.field(completionState).active.find(a => a.source == query.active.source);
23344
            if (current && current.state == 1 /* State.Pending */) {
23345
                if (query.done == null) {
23346
                    // Explicitly failed. Should clear the pending status if it
23347
                    // hasn't been re-set in the meantime.
23348
                    let active = new ActiveSource(query.active.source, 0 /* State.Inactive */);
23349
                    for (let tr of query.updates)
23350
                        active = active.update(tr, conf);
23351
                    if (active.state != 1 /* State.Pending */)
23352
                        updated.push(active);
23353
                }
23354
                else {
23355
                    // Cleared by subsequent transactions. Restart.
23356
                    this.startQuery(current);
23357
                }
23358
            }
23359
        }
23360
        if (updated.length)
23361
            this.view.dispatch({ effects: setActiveEffect.of(updated) });
23362
    }
23363
}, {
23364
    eventHandlers: {
23365
        blur(event) {
23366
            let state = this.view.state.field(completionState, false);
23367
            if (state && state.tooltip && this.view.state.facet(completionConfig).closeOnBlur) {
23368
                let dialog = state.open && getTooltip(this.view, state.open.tooltip);
23369
                if (!dialog || !dialog.dom.contains(event.relatedTarget))
23370
                    setTimeout(() => this.view.dispatch({ effects: closeCompletionEffect.of(null) }), 10);
23371
            }
23372
        },
23373
        compositionstart() {
23374
            this.composing = 1 /* CompositionState.Started */;
23375
        },
23376
        compositionend() {
23377
            if (this.composing == 3 /* CompositionState.ChangedAndMoved */) {
23378
                // Safari fires compositionend events synchronously, possibly
23379
                // from inside an update, so dispatch asynchronously to avoid reentrancy
23380
                setTimeout(() => this.view.dispatch({ effects: startCompletionEffect.of(false) }), 20);
23381
            }
23382
            this.composing = 0 /* CompositionState.None */;
23383
        }
23384
    }
23385
});
23386
const windows = typeof navigator == "object" && /*@__PURE__*//Win/.test(navigator.platform);
23387
const commitCharacters = /*@__PURE__*/Prec.highest(/*@__PURE__*/EditorView.domEventHandlers({
23388
    keydown(event, view) {
23389
        let field = view.state.field(completionState, false);
23390
        if (!field || !field.open || field.open.disabled || field.open.selected < 0 ||
23391
            event.key.length > 1 || event.ctrlKey && !(windows && event.altKey) || event.metaKey)
23392
            return false;
23393
        let option = field.open.options[field.open.selected];
23394
        let result = field.active.find(a => a.source == option.source);
23395
        let commitChars = option.completion.commitCharacters || result.result.commitCharacters;
23396
        if (commitChars && commitChars.indexOf(event.key) > -1)
23397
            applyCompletion(view, option);
23398
        return false;
23399
    }
23400
}));
23401
 
23402
const baseTheme$1 = /*@__PURE__*/EditorView.baseTheme({
23403
    ".cm-tooltip.cm-tooltip-autocomplete": {
23404
        "& > ul": {
23405
            fontFamily: "monospace",
23406
            whiteSpace: "nowrap",
23407
            overflow: "hidden auto",
23408
            maxWidth_fallback: "700px",
23409
            maxWidth: "min(700px, 95vw)",
23410
            minWidth: "250px",
23411
            maxHeight: "10em",
23412
            height: "100%",
23413
            listStyle: "none",
23414
            margin: 0,
23415
            padding: 0,
23416
            "& > li, & > completion-section": {
23417
                padding: "1px 3px",
23418
                lineHeight: 1.2
23419
            },
23420
            "& > li": {
23421
                overflowX: "hidden",
23422
                textOverflow: "ellipsis",
23423
                cursor: "pointer"
23424
            },
23425
            "& > completion-section": {
23426
                display: "list-item",
23427
                borderBottom: "1px solid silver",
23428
                paddingLeft: "0.5em",
23429
                opacity: 0.7
23430
            }
23431
        }
23432
    },
23433
    "&light .cm-tooltip-autocomplete ul li[aria-selected]": {
23434
        background: "#17c",
23435
        color: "white",
23436
    },
23437
    "&light .cm-tooltip-autocomplete-disabled ul li[aria-selected]": {
23438
        background: "#777",
23439
    },
23440
    "&dark .cm-tooltip-autocomplete ul li[aria-selected]": {
23441
        background: "#347",
23442
        color: "white",
23443
    },
23444
    "&dark .cm-tooltip-autocomplete-disabled ul li[aria-selected]": {
23445
        background: "#444",
23446
    },
23447
    ".cm-completionListIncompleteTop:before, .cm-completionListIncompleteBottom:after": {
23448
        content: '"···"',
23449
        opacity: 0.5,
23450
        display: "block",
23451
        textAlign: "center"
23452
    },
23453
    ".cm-tooltip.cm-completionInfo": {
23454
        position: "absolute",
23455
        padding: "3px 9px",
23456
        width: "max-content",
23457
        maxWidth: `${400 /* Info.Width */}px`,
23458
        boxSizing: "border-box"
23459
    },
23460
    ".cm-completionInfo.cm-completionInfo-left": { right: "100%" },
23461
    ".cm-completionInfo.cm-completionInfo-right": { left: "100%" },
23462
    ".cm-completionInfo.cm-completionInfo-left-narrow": { right: `${30 /* Info.Margin */}px` },
23463
    ".cm-completionInfo.cm-completionInfo-right-narrow": { left: `${30 /* Info.Margin */}px` },
23464
    "&light .cm-snippetField": { backgroundColor: "#00000022" },
23465
    "&dark .cm-snippetField": { backgroundColor: "#ffffff22" },
23466
    ".cm-snippetFieldPosition": {
23467
        verticalAlign: "text-top",
23468
        width: 0,
23469
        height: "1.15em",
23470
        display: "inline-block",
23471
        margin: "0 -0.7px -.7em",
23472
        borderLeft: "1.4px dotted #888"
23473
    },
23474
    ".cm-completionMatchedText": {
23475
        textDecoration: "underline"
23476
    },
23477
    ".cm-completionDetail": {
23478
        marginLeft: "0.5em",
23479
        fontStyle: "italic"
23480
    },
23481
    ".cm-completionIcon": {
23482
        fontSize: "90%",
23483
        width: ".8em",
23484
        display: "inline-block",
23485
        textAlign: "center",
23486
        paddingRight: ".6em",
23487
        opacity: "0.6",
23488
        boxSizing: "content-box"
23489
    },
23490
    ".cm-completionIcon-function, .cm-completionIcon-method": {
23491
        "&:after": { content: "'Æ’'" }
23492
    },
23493
    ".cm-completionIcon-class": {
23494
        "&:after": { content: "'○'" }
23495
    },
23496
    ".cm-completionIcon-interface": {
23497
        "&:after": { content: "'◌'" }
23498
    },
23499
    ".cm-completionIcon-variable": {
23500
        "&:after": { content: "'𝑥'" }
23501
    },
23502
    ".cm-completionIcon-constant": {
23503
        "&:after": { content: "'𝐶'" }
23504
    },
23505
    ".cm-completionIcon-type": {
23506
        "&:after": { content: "'𝑡'" }
23507
    },
23508
    ".cm-completionIcon-enum": {
23509
        "&:after": { content: "'∪'" }
23510
    },
23511
    ".cm-completionIcon-property": {
23512
        "&:after": { content: "'â–¡'" }
23513
    },
23514
    ".cm-completionIcon-keyword": {
23515
        "&:after": { content: "'🔑\uFE0E'" } // Disable emoji rendering
23516
    },
23517
    ".cm-completionIcon-namespace": {
23518
        "&:after": { content: "'â–¢'" }
23519
    },
23520
    ".cm-completionIcon-text": {
23521
        "&:after": { content: "'abc'", fontSize: "50%", verticalAlign: "middle" }
23522
    }
23523
});
23524
 
23525
class FieldPos {
23526
    constructor(field, line, from, to) {
23527
        this.field = field;
23528
        this.line = line;
23529
        this.from = from;
23530
        this.to = to;
23531
    }
23532
}
23533
class FieldRange {
23534
    constructor(field, from, to) {
23535
        this.field = field;
23536
        this.from = from;
23537
        this.to = to;
23538
    }
23539
    map(changes) {
23540
        let from = changes.mapPos(this.from, -1, MapMode.TrackDel);
23541
        let to = changes.mapPos(this.to, 1, MapMode.TrackDel);
23542
        return from == null || to == null ? null : new FieldRange(this.field, from, to);
23543
    }
23544
}
23545
class Snippet {
23546
    constructor(lines, fieldPositions) {
23547
        this.lines = lines;
23548
        this.fieldPositions = fieldPositions;
23549
    }
23550
    instantiate(state, pos) {
23551
        let text = [], lineStart = [pos];
23552
        let lineObj = state.doc.lineAt(pos), baseIndent = /^\s*/.exec(lineObj.text)[0];
23553
        for (let line of this.lines) {
23554
            if (text.length) {
23555
                let indent = baseIndent, tabs = /^\t*/.exec(line)[0].length;
23556
                for (let i = 0; i < tabs; i++)
23557
                    indent += state.facet(indentUnit);
23558
                lineStart.push(pos + indent.length - tabs);
23559
                line = indent + line.slice(tabs);
23560
            }
23561
            text.push(line);
23562
            pos += line.length + 1;
23563
        }
23564
        let ranges = this.fieldPositions.map(pos => new FieldRange(pos.field, lineStart[pos.line] + pos.from, lineStart[pos.line] + pos.to));
23565
        return { text, ranges };
23566
    }
23567
    static parse(template) {
23568
        let fields = [];
23569
        let lines = [], positions = [], m;
23570
        for (let line of template.split(/\r\n?|\n/)) {
23571
            while (m = /[#$]\{(?:(\d+)(?::([^}]*))?|([^}]*))\}/.exec(line)) {
23572
                let seq = m[1] ? +m[1] : null, name = m[2] || m[3] || "", found = -1;
23573
                for (let i = 0; i < fields.length; i++) {
23574
                    if (seq != null ? fields[i].seq == seq : name ? fields[i].name == name : false)
23575
                        found = i;
23576
                }
23577
                if (found < 0) {
23578
                    let i = 0;
23579
                    while (i < fields.length && (seq == null || (fields[i].seq != null && fields[i].seq < seq)))
23580
                        i++;
23581
                    fields.splice(i, 0, { seq, name });
23582
                    found = i;
23583
                    for (let pos of positions)
23584
                        if (pos.field >= found)
23585
                            pos.field++;
23586
                }
23587
                positions.push(new FieldPos(found, lines.length, m.index, m.index + name.length));
23588
                line = line.slice(0, m.index) + name + line.slice(m.index + m[0].length);
23589
            }
23590
            for (let esc; esc = /\\([{}])/.exec(line);) {
23591
                line = line.slice(0, esc.index) + esc[1] + line.slice(esc.index + esc[0].length);
23592
                for (let pos of positions)
23593
                    if (pos.line == lines.length && pos.from > esc.index) {
23594
                        pos.from--;
23595
                        pos.to--;
23596
                    }
23597
            }
23598
            lines.push(line);
23599
        }
23600
        return new Snippet(lines, positions);
23601
    }
23602
}
23603
let fieldMarker = /*@__PURE__*/Decoration.widget({ widget: /*@__PURE__*/new class extends WidgetType {
23604
        toDOM() {
23605
            let span = document.createElement("span");
23606
            span.className = "cm-snippetFieldPosition";
23607
            return span;
23608
        }
23609
        ignoreEvent() { return false; }
23610
    } });
23611
let fieldRange = /*@__PURE__*/Decoration.mark({ class: "cm-snippetField" });
23612
class ActiveSnippet {
23613
    constructor(ranges, active) {
23614
        this.ranges = ranges;
23615
        this.active = active;
23616
        this.deco = Decoration.set(ranges.map(r => (r.from == r.to ? fieldMarker : fieldRange).range(r.from, r.to)));
23617
    }
23618
    map(changes) {
23619
        let ranges = [];
23620
        for (let r of this.ranges) {
23621
            let mapped = r.map(changes);
23622
            if (!mapped)
23623
                return null;
23624
            ranges.push(mapped);
23625
        }
23626
        return new ActiveSnippet(ranges, this.active);
23627
    }
23628
    selectionInsideField(sel) {
23629
        return sel.ranges.every(range => this.ranges.some(r => r.field == this.active && r.from <= range.from && r.to >= range.to));
23630
    }
23631
}
23632
const setActive = /*@__PURE__*/StateEffect.define({
23633
    map(value, changes) { return value && value.map(changes); }
23634
});
23635
const moveToField = /*@__PURE__*/StateEffect.define();
23636
const snippetState = /*@__PURE__*/StateField.define({
23637
    create() { return null; },
23638
    update(value, tr) {
23639
        for (let effect of tr.effects) {
23640
            if (effect.is(setActive))
23641
                return effect.value;
23642
            if (effect.is(moveToField) && value)
23643
                return new ActiveSnippet(value.ranges, effect.value);
23644
        }
23645
        if (value && tr.docChanged)
23646
            value = value.map(tr.changes);
23647
        if (value && tr.selection && !value.selectionInsideField(tr.selection))
23648
            value = null;
23649
        return value;
23650
    },
23651
    provide: f => EditorView.decorations.from(f, val => val ? val.deco : Decoration.none)
23652
});
23653
function fieldSelection(ranges, field) {
23654
    return EditorSelection.create(ranges.filter(r => r.field == field).map(r => EditorSelection.range(r.from, r.to)));
23655
}
23656
/**
23657
Convert a snippet template to a function that can
23658
[apply](https://codemirror.net/6/docs/ref/#autocomplete.Completion.apply) it. Snippets are written
23659
using syntax like this:
23660
 
23661
    "for (let ${index} = 0; ${index} < ${end}; ${index}++) {\n\t${}\n}"
23662
 
23663
Each `${}` placeholder (you may also use `#{}`) indicates a field
23664
that the user can fill in. Its name, if any, will be the default
23665
content for the field.
23666
 
23667
When the snippet is activated by calling the returned function,
23668
the code is inserted at the given position. Newlines in the
23669
template are indented by the indentation of the start line, plus
23670
one [indent unit](https://codemirror.net/6/docs/ref/#language.indentUnit) per tab character after
23671
the newline.
23672
 
23673
On activation, (all instances of) the first field are selected.
23674
The user can move between fields with Tab and Shift-Tab as long as
23675
the fields are active. Moving to the last field or moving the
23676
cursor out of the current field deactivates the fields.
23677
 
23678
The order of fields defaults to textual order, but you can add
23679
numbers to placeholders (`${1}` or `${1:defaultText}`) to provide
23680
a custom order.
23681
 
23682
To include a literal `{` or `}` in your template, put a backslash
23683
in front of it. This will be removed and the brace will not be
23684
interpreted as indicating a placeholder.
23685
*/
23686
function snippet(template) {
23687
    let snippet = Snippet.parse(template);
23688
    return (editor, completion, from, to) => {
23689
        let { text, ranges } = snippet.instantiate(editor.state, from);
23690
        let spec = {
23691
            changes: { from, to, insert: Text.of(text) },
23692
            scrollIntoView: true,
23693
            annotations: completion ? [pickedCompletion.of(completion), Transaction.userEvent.of("input.complete")] : undefined
23694
        };
23695
        if (ranges.length)
23696
            spec.selection = fieldSelection(ranges, 0);
23697
        if (ranges.some(r => r.field > 0)) {
23698
            let active = new ActiveSnippet(ranges, 0);
23699
            let effects = spec.effects = [setActive.of(active)];
23700
            if (editor.state.field(snippetState, false) === undefined)
23701
                effects.push(StateEffect.appendConfig.of([snippetState, addSnippetKeymap, snippetPointerHandler, baseTheme$1]));
23702
        }
23703
        editor.dispatch(editor.state.update(spec));
23704
    };
23705
}
23706
function moveField(dir) {
23707
    return ({ state, dispatch }) => {
23708
        let active = state.field(snippetState, false);
23709
        if (!active || dir < 0 && active.active == 0)
23710
            return false;
23711
        let next = active.active + dir, last = dir > 0 && !active.ranges.some(r => r.field == next + dir);
23712
        dispatch(state.update({
23713
            selection: fieldSelection(active.ranges, next),
23714
            effects: setActive.of(last ? null : new ActiveSnippet(active.ranges, next)),
23715
            scrollIntoView: true
23716
        }));
23717
        return true;
23718
    };
23719
}
23720
/**
23721
A command that clears the active snippet, if any.
23722
*/
23723
const clearSnippet = ({ state, dispatch }) => {
23724
    let active = state.field(snippetState, false);
23725
    if (!active)
23726
        return false;
23727
    dispatch(state.update({ effects: setActive.of(null) }));
23728
    return true;
23729
};
23730
/**
23731
Move to the next snippet field, if available.
23732
*/
23733
const nextSnippetField = /*@__PURE__*/moveField(1);
23734
/**
23735
Move to the previous snippet field, if available.
23736
*/
23737
const prevSnippetField = /*@__PURE__*/moveField(-1);
23738
const defaultSnippetKeymap = [
23739
    { key: "Tab", run: nextSnippetField, shift: prevSnippetField },
23740
    { key: "Escape", run: clearSnippet }
23741
];
23742
/**
23743
A facet that can be used to configure the key bindings used by
23744
snippets. The default binds Tab to
23745
[`nextSnippetField`](https://codemirror.net/6/docs/ref/#autocomplete.nextSnippetField), Shift-Tab to
23746
[`prevSnippetField`](https://codemirror.net/6/docs/ref/#autocomplete.prevSnippetField), and Escape
23747
to [`clearSnippet`](https://codemirror.net/6/docs/ref/#autocomplete.clearSnippet).
23748
*/
23749
const snippetKeymap = /*@__PURE__*/Facet.define({
23750
    combine(maps) { return maps.length ? maps[0] : defaultSnippetKeymap; }
23751
});
23752
const addSnippetKeymap = /*@__PURE__*/Prec.highest(/*@__PURE__*/keymap.compute([snippetKeymap], state => state.facet(snippetKeymap)));
23753
/**
23754
Create a completion from a snippet. Returns an object with the
23755
properties from `completion`, plus an `apply` function that
23756
applies the snippet.
23757
*/
23758
function snippetCompletion(template, completion) {
23759
    return Object.assign(Object.assign({}, completion), { apply: snippet(template) });
23760
}
23761
const snippetPointerHandler = /*@__PURE__*/EditorView.domEventHandlers({
23762
    mousedown(event, view) {
23763
        let active = view.state.field(snippetState, false), pos;
23764
        if (!active || (pos = view.posAtCoords({ x: event.clientX, y: event.clientY })) == null)
23765
            return false;
23766
        let match = active.ranges.find(r => r.from <= pos && r.to >= pos);
23767
        if (!match || match.field == active.active)
23768
            return false;
23769
        view.dispatch({
23770
            selection: fieldSelection(active.ranges, match.field),
23771
            effects: setActive.of(active.ranges.some(r => r.field > match.field)
23772
                ? new ActiveSnippet(active.ranges, match.field) : null),
23773
            scrollIntoView: true
23774
        });
23775
        return true;
23776
    }
23777
});
23778
 
23779
const defaults = {
23780
    brackets: ["(", "[", "{", "'", '"'],
23781
    before: ")]}:;>",
23782
    stringPrefixes: []
23783
};
23784
const closeBracketEffect = /*@__PURE__*/StateEffect.define({
23785
    map(value, mapping) {
23786
        let mapped = mapping.mapPos(value, -1, MapMode.TrackAfter);
23787
        return mapped == null ? undefined : mapped;
23788
    }
23789
});
23790
const closedBracket = /*@__PURE__*/new class extends RangeValue {
23791
};
23792
closedBracket.startSide = 1;
23793
closedBracket.endSide = -1;
23794
const bracketState = /*@__PURE__*/StateField.define({
23795
    create() { return RangeSet.empty; },
23796
    update(value, tr) {
23797
        value = value.map(tr.changes);
23798
        if (tr.selection) {
23799
            let line = tr.state.doc.lineAt(tr.selection.main.head);
23800
            value = value.update({ filter: from => from >= line.from && from <= line.to });
23801
        }
23802
        for (let effect of tr.effects)
23803
            if (effect.is(closeBracketEffect))
23804
                value = value.update({ add: [closedBracket.range(effect.value, effect.value + 1)] });
23805
        return value;
23806
    }
23807
});
23808
/**
23809
Extension to enable bracket-closing behavior. When a closeable
23810
bracket is typed, its closing bracket is immediately inserted
23811
after the cursor. When closing a bracket directly in front of a
23812
closing bracket inserted by the extension, the cursor moves over
23813
that bracket.
23814
*/
23815
function closeBrackets() {
23816
    return [inputHandler, bracketState];
23817
}
23818
const definedClosing = "()[]{}<>";
23819
function closing(ch) {
23820
    for (let i = 0; i < definedClosing.length; i += 2)
23821
        if (definedClosing.charCodeAt(i) == ch)
23822
            return definedClosing.charAt(i + 1);
23823
    return fromCodePoint(ch < 128 ? ch : ch + 1);
23824
}
23825
function config(state, pos) {
23826
    return state.languageDataAt("closeBrackets", pos)[0] || defaults;
23827
}
23828
const android$1 = typeof navigator == "object" && /*@__PURE__*//Android\b/.test(navigator.userAgent);
23829
const inputHandler = /*@__PURE__*/EditorView.inputHandler.of((view, from, to, insert) => {
23830
    if ((android$1 ? view.composing : view.compositionStarted) || view.state.readOnly)
23831
        return false;
23832
    let sel = view.state.selection.main;
23833
    if (insert.length > 2 || insert.length == 2 && codePointSize(codePointAt(insert, 0)) == 1 ||
23834
        from != sel.from || to != sel.to)
23835
        return false;
23836
    let tr = insertBracket(view.state, insert);
23837
    if (!tr)
23838
        return false;
23839
    view.dispatch(tr);
23840
    return true;
23841
});
23842
/**
23843
Command that implements deleting a pair of matching brackets when
23844
the cursor is between them.
23845
*/
23846
const deleteBracketPair = ({ state, dispatch }) => {
23847
    if (state.readOnly)
23848
        return false;
23849
    let conf = config(state, state.selection.main.head);
23850
    let tokens = conf.brackets || defaults.brackets;
23851
    let dont = null, changes = state.changeByRange(range => {
23852
        if (range.empty) {
23853
            let before = prevChar(state.doc, range.head);
23854
            for (let token of tokens) {
23855
                if (token == before && nextChar(state.doc, range.head) == closing(codePointAt(token, 0)))
23856
                    return { changes: { from: range.head - token.length, to: range.head + token.length },
23857
                        range: EditorSelection.cursor(range.head - token.length) };
23858
            }
23859
        }
23860
        return { range: dont = range };
23861
    });
23862
    if (!dont)
23863
        dispatch(state.update(changes, { scrollIntoView: true, userEvent: "delete.backward" }));
23864
    return !dont;
23865
};
23866
/**
23867
Close-brackets related key bindings. Binds Backspace to
23868
[`deleteBracketPair`](https://codemirror.net/6/docs/ref/#autocomplete.deleteBracketPair).
23869
*/
23870
const closeBracketsKeymap = [
23871
    { key: "Backspace", run: deleteBracketPair }
23872
];
23873
/**
23874
Implements the extension's behavior on text insertion. If the
23875
given string counts as a bracket in the language around the
23876
selection, and replacing the selection with it requires custom
23877
behavior (inserting a closing version or skipping past a
23878
previously-closed bracket), this function returns a transaction
23879
representing that custom behavior. (You only need this if you want
23880
to programmatically insert brackets—the
23881
[`closeBrackets`](https://codemirror.net/6/docs/ref/#autocomplete.closeBrackets) extension will
23882
take care of running this for user input.)
23883
*/
23884
function insertBracket(state, bracket) {
23885
    let conf = config(state, state.selection.main.head);
23886
    let tokens = conf.brackets || defaults.brackets;
23887
    for (let tok of tokens) {
23888
        let closed = closing(codePointAt(tok, 0));
23889
        if (bracket == tok)
23890
            return closed == tok ? handleSame(state, tok, tokens.indexOf(tok + tok + tok) > -1, conf)
23891
                : handleOpen(state, tok, closed, conf.before || defaults.before);
23892
        if (bracket == closed && closedBracketAt(state, state.selection.main.from))
23893
            return handleClose(state, tok, closed);
23894
    }
23895
    return null;
23896
}
23897
function closedBracketAt(state, pos) {
23898
    let found = false;
23899
    state.field(bracketState).between(0, state.doc.length, from => {
23900
        if (from == pos)
23901
            found = true;
23902
    });
23903
    return found;
23904
}
23905
function nextChar(doc, pos) {
23906
    let next = doc.sliceString(pos, pos + 2);
23907
    return next.slice(0, codePointSize(codePointAt(next, 0)));
23908
}
23909
function prevChar(doc, pos) {
23910
    let prev = doc.sliceString(pos - 2, pos);
23911
    return codePointSize(codePointAt(prev, 0)) == prev.length ? prev : prev.slice(1);
23912
}
23913
function handleOpen(state, open, close, closeBefore) {
23914
    let dont = null, changes = state.changeByRange(range => {
23915
        if (!range.empty)
23916
            return { changes: [{ insert: open, from: range.from }, { insert: close, from: range.to }],
23917
                effects: closeBracketEffect.of(range.to + open.length),
23918
                range: EditorSelection.range(range.anchor + open.length, range.head + open.length) };
23919
        let next = nextChar(state.doc, range.head);
23920
        if (!next || /\s/.test(next) || closeBefore.indexOf(next) > -1)
23921
            return { changes: { insert: open + close, from: range.head },
23922
                effects: closeBracketEffect.of(range.head + open.length),
23923
                range: EditorSelection.cursor(range.head + open.length) };
23924
        return { range: dont = range };
23925
    });
23926
    return dont ? null : state.update(changes, {
23927
        scrollIntoView: true,
23928
        userEvent: "input.type"
23929
    });
23930
}
23931
function handleClose(state, _open, close) {
23932
    let dont = null, changes = state.changeByRange(range => {
23933
        if (range.empty && nextChar(state.doc, range.head) == close)
23934
            return { changes: { from: range.head, to: range.head + close.length, insert: close },
23935
                range: EditorSelection.cursor(range.head + close.length) };
23936
        return dont = { range };
23937
    });
23938
    return dont ? null : state.update(changes, {
23939
        scrollIntoView: true,
23940
        userEvent: "input.type"
23941
    });
23942
}
23943
// Handles cases where the open and close token are the same, and
23944
// possibly triple quotes (as in `"""abc"""`-style quoting).
23945
function handleSame(state, token, allowTriple, config) {
23946
    let stringPrefixes = config.stringPrefixes || defaults.stringPrefixes;
23947
    let dont = null, changes = state.changeByRange(range => {
23948
        if (!range.empty)
23949
            return { changes: [{ insert: token, from: range.from }, { insert: token, from: range.to }],
23950
                effects: closeBracketEffect.of(range.to + token.length),
23951
                range: EditorSelection.range(range.anchor + token.length, range.head + token.length) };
23952
        let pos = range.head, next = nextChar(state.doc, pos), start;
23953
        if (next == token) {
23954
            if (nodeStart(state, pos)) {
23955
                return { changes: { insert: token + token, from: pos },
23956
                    effects: closeBracketEffect.of(pos + token.length),
23957
                    range: EditorSelection.cursor(pos + token.length) };
23958
            }
23959
            else if (closedBracketAt(state, pos)) {
23960
                let isTriple = allowTriple && state.sliceDoc(pos, pos + token.length * 3) == token + token + token;
23961
                let content = isTriple ? token + token + token : token;
23962
                return { changes: { from: pos, to: pos + content.length, insert: content },
23963
                    range: EditorSelection.cursor(pos + content.length) };
23964
            }
23965
        }
23966
        else if (allowTriple && state.sliceDoc(pos - 2 * token.length, pos) == token + token &&
23967
            (start = canStartStringAt(state, pos - 2 * token.length, stringPrefixes)) > -1 &&
23968
            nodeStart(state, start)) {
23969
            return { changes: { insert: token + token + token + token, from: pos },
23970
                effects: closeBracketEffect.of(pos + token.length),
23971
                range: EditorSelection.cursor(pos + token.length) };
23972
        }
23973
        else if (state.charCategorizer(pos)(next) != CharCategory.Word) {
23974
            if (canStartStringAt(state, pos, stringPrefixes) > -1 && !probablyInString(state, pos, token, stringPrefixes))
23975
                return { changes: { insert: token + token, from: pos },
23976
                    effects: closeBracketEffect.of(pos + token.length),
23977
                    range: EditorSelection.cursor(pos + token.length) };
23978
        }
23979
        return { range: dont = range };
23980
    });
23981
    return dont ? null : state.update(changes, {
23982
        scrollIntoView: true,
23983
        userEvent: "input.type"
23984
    });
23985
}
23986
function nodeStart(state, pos) {
23987
    let tree = syntaxTree(state).resolveInner(pos + 1);
23988
    return tree.parent && tree.from == pos;
23989
}
23990
function probablyInString(state, pos, quoteToken, prefixes) {
23991
    let node = syntaxTree(state).resolveInner(pos, -1);
23992
    let maxPrefix = prefixes.reduce((m, p) => Math.max(m, p.length), 0);
23993
    for (let i = 0; i < 5; i++) {
23994
        let start = state.sliceDoc(node.from, Math.min(node.to, node.from + quoteToken.length + maxPrefix));
23995
        let quotePos = start.indexOf(quoteToken);
23996
        if (!quotePos || quotePos > -1 && prefixes.indexOf(start.slice(0, quotePos)) > -1) {
23997
            let first = node.firstChild;
23998
            while (first && first.from == node.from && first.to - first.from > quoteToken.length + quotePos) {
23999
                if (state.sliceDoc(first.to - quoteToken.length, first.to) == quoteToken)
24000
                    return false;
24001
                first = first.firstChild;
24002
            }
24003
            return true;
24004
        }
24005
        let parent = node.to == pos && node.parent;
24006
        if (!parent)
24007
            break;
24008
        node = parent;
24009
    }
24010
    return false;
24011
}
24012
function canStartStringAt(state, pos, prefixes) {
24013
    let charCat = state.charCategorizer(pos);
24014
    if (charCat(state.sliceDoc(pos - 1, pos)) != CharCategory.Word)
24015
        return pos;
24016
    for (let prefix of prefixes) {
24017
        let start = pos - prefix.length;
24018
        if (state.sliceDoc(start, pos) == prefix && charCat(state.sliceDoc(start - 1, start)) != CharCategory.Word)
24019
            return start;
24020
    }
24021
    return -1;
24022
}
24023
 
24024
/**
24025
Returns an extension that enables autocompletion.
24026
*/
24027
function autocompletion(config = {}) {
24028
    return [
24029
        commitCharacters,
24030
        completionState,
24031
        completionConfig.of(config),
24032
        completionPlugin,
24033
        completionKeymapExt,
24034
        baseTheme$1
24035
    ];
24036
}
24037
/**
24038
Basic keybindings for autocompletion.
24039
 
24040
 - Ctrl-Space: [`startCompletion`](https://codemirror.net/6/docs/ref/#autocomplete.startCompletion)
24041
 - Escape: [`closeCompletion`](https://codemirror.net/6/docs/ref/#autocomplete.closeCompletion)
24042
 - ArrowDown: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(true)`
24043
 - ArrowUp: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(false)`
24044
 - PageDown: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(true, "page")`
24045
 - PageDown: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(true, "page")`
24046
 - Enter: [`acceptCompletion`](https://codemirror.net/6/docs/ref/#autocomplete.acceptCompletion)
24047
*/
24048
const completionKeymap = [
24049
    { key: "Ctrl-Space", run: startCompletion },
24050
    { key: "Escape", run: closeCompletion },
24051
    { key: "ArrowDown", run: /*@__PURE__*/moveCompletionSelection(true) },
24052
    { key: "ArrowUp", run: /*@__PURE__*/moveCompletionSelection(false) },
24053
    { key: "PageDown", run: /*@__PURE__*/moveCompletionSelection(true, "page") },
24054
    { key: "PageUp", run: /*@__PURE__*/moveCompletionSelection(false, "page") },
24055
    { key: "Enter", run: acceptCompletion }
24056
];
24057
const completionKeymapExt = /*@__PURE__*/Prec.highest(/*@__PURE__*/keymap.computeN([completionConfig], state => state.facet(completionConfig).defaultKeymap ? [completionKeymap] : []));
24058
 
24059
class SelectedDiagnostic {
24060
    constructor(from, to, diagnostic) {
24061
        this.from = from;
24062
        this.to = to;
24063
        this.diagnostic = diagnostic;
24064
    }
24065
}
24066
class LintState {
24067
    constructor(diagnostics, panel, selected) {
24068
        this.diagnostics = diagnostics;
24069
        this.panel = panel;
24070
        this.selected = selected;
24071
    }
24072
    static init(diagnostics, panel, state) {
24073
        // Filter the list of diagnostics for which to create markers
24074
        let markedDiagnostics = diagnostics;
24075
        let diagnosticFilter = state.facet(lintConfig).markerFilter;
24076
        if (diagnosticFilter)
24077
            markedDiagnostics = diagnosticFilter(markedDiagnostics, state);
24078
        let ranges = Decoration.set(markedDiagnostics.map((d) => {
24079
            // For zero-length ranges or ranges covering only a line break, create a widget
24080
            return d.from == d.to || (d.from == d.to - 1 && state.doc.lineAt(d.from).to == d.from)
24081
                ? Decoration.widget({
24082
                    widget: new DiagnosticWidget(d),
24083
                    diagnostic: d
24084
                }).range(d.from)
24085
                : Decoration.mark({
24086
                    attributes: { class: "cm-lintRange cm-lintRange-" + d.severity + (d.markClass ? " " + d.markClass : "") },
24087
                    diagnostic: d,
24088
                    inclusive: true
24089
                }).range(d.from, d.to);
24090
        }), true);
24091
        return new LintState(ranges, panel, findDiagnostic(ranges));
24092
    }
24093
}
24094
function findDiagnostic(diagnostics, diagnostic = null, after = 0) {
24095
    let found = null;
24096
    diagnostics.between(after, 1e9, (from, to, { spec }) => {
24097
        if (diagnostic && spec.diagnostic != diagnostic)
24098
            return;
24099
        found = new SelectedDiagnostic(from, to, spec.diagnostic);
24100
        return false;
24101
    });
24102
    return found;
24103
}
24104
function hideTooltip(tr, tooltip) {
24105
    let line = tr.startState.doc.lineAt(tooltip.pos);
24106
    return !!(tr.effects.some(e => e.is(setDiagnosticsEffect)) || tr.changes.touchesRange(line.from, line.to));
24107
}
24108
function maybeEnableLint(state, effects) {
24109
    return state.field(lintState, false) ? effects : effects.concat(StateEffect.appendConfig.of(lintExtensions));
24110
}
24111
/**
24112
The state effect that updates the set of active diagnostics. Can
24113
be useful when writing an extension that needs to track these.
24114
*/
24115
const setDiagnosticsEffect = /*@__PURE__*/StateEffect.define();
24116
const togglePanel = /*@__PURE__*/StateEffect.define();
24117
const movePanelSelection = /*@__PURE__*/StateEffect.define();
24118
const lintState = /*@__PURE__*/StateField.define({
24119
    create() {
24120
        return new LintState(Decoration.none, null, null);
24121
    },
24122
    update(value, tr) {
24123
        if (tr.docChanged) {
24124
            let mapped = value.diagnostics.map(tr.changes), selected = null;
24125
            if (value.selected) {
24126
                let selPos = tr.changes.mapPos(value.selected.from, 1);
24127
                selected = findDiagnostic(mapped, value.selected.diagnostic, selPos) || findDiagnostic(mapped, null, selPos);
24128
            }
24129
            value = new LintState(mapped, value.panel, selected);
24130
        }
24131
        for (let effect of tr.effects) {
24132
            if (effect.is(setDiagnosticsEffect)) {
24133
                value = LintState.init(effect.value, value.panel, tr.state);
24134
            }
24135
            else if (effect.is(togglePanel)) {
24136
                value = new LintState(value.diagnostics, effect.value ? LintPanel.open : null, value.selected);
24137
            }
24138
            else if (effect.is(movePanelSelection)) {
24139
                value = new LintState(value.diagnostics, value.panel, effect.value);
24140
            }
24141
        }
24142
        return value;
24143
    },
24144
    provide: f => [showPanel.from(f, val => val.panel),
24145
        EditorView.decorations.from(f, s => s.diagnostics)]
24146
});
24147
const activeMark = /*@__PURE__*/Decoration.mark({ class: "cm-lintRange cm-lintRange-active", inclusive: true });
24148
function lintTooltip(view, pos, side) {
24149
    let { diagnostics } = view.state.field(lintState);
24150
    let found = [], stackStart = 2e8, stackEnd = 0;
24151
    diagnostics.between(pos - (side < 0 ? 1 : 0), pos + (side > 0 ? 1 : 0), (from, to, { spec }) => {
24152
        if (pos >= from && pos <= to &&
24153
            (from == to || ((pos > from || side > 0) && (pos < to || side < 0)))) {
24154
            found.push(spec.diagnostic);
24155
            stackStart = Math.min(from, stackStart);
24156
            stackEnd = Math.max(to, stackEnd);
24157
        }
24158
    });
24159
    let diagnosticFilter = view.state.facet(lintConfig).tooltipFilter;
24160
    if (diagnosticFilter)
24161
        found = diagnosticFilter(found, view.state);
24162
    if (!found.length)
24163
        return null;
24164
    return {
24165
        pos: stackStart,
24166
        end: stackEnd,
24167
        above: view.state.doc.lineAt(stackStart).to < stackEnd,
24168
        create() {
24169
            return { dom: diagnosticsTooltip(view, found) };
24170
        }
24171
    };
24172
}
24173
function diagnosticsTooltip(view, diagnostics) {
24174
    return crelt("ul", { class: "cm-tooltip-lint" }, diagnostics.map(d => renderDiagnostic(view, d, false)));
24175
}
24176
/**
24177
Command to open and focus the lint panel.
24178
*/
24179
const openLintPanel = (view) => {
24180
    let field = view.state.field(lintState, false);
24181
    if (!field || !field.panel)
24182
        view.dispatch({ effects: maybeEnableLint(view.state, [togglePanel.of(true)]) });
24183
    let panel = getPanel(view, LintPanel.open);
24184
    if (panel)
24185
        panel.dom.querySelector(".cm-panel-lint ul").focus();
24186
    return true;
24187
};
24188
/**
24189
Command to close the lint panel, when open.
24190
*/
24191
const closeLintPanel = (view) => {
24192
    let field = view.state.field(lintState, false);
24193
    if (!field || !field.panel)
24194
        return false;
24195
    view.dispatch({ effects: togglePanel.of(false) });
24196
    return true;
24197
};
24198
/**
24199
Move the selection to the next diagnostic.
24200
*/
24201
const nextDiagnostic = (view) => {
24202
    let field = view.state.field(lintState, false);
24203
    if (!field)
24204
        return false;
24205
    let sel = view.state.selection.main, next = field.diagnostics.iter(sel.to + 1);
24206
    if (!next.value) {
24207
        next = field.diagnostics.iter(0);
24208
        if (!next.value || next.from == sel.from && next.to == sel.to)
24209
            return false;
24210
    }
24211
    view.dispatch({ selection: { anchor: next.from, head: next.to }, scrollIntoView: true });
24212
    return true;
24213
};
24214
/**
24215
A set of default key bindings for the lint functionality.
24216
 
24217
- Ctrl-Shift-m (Cmd-Shift-m on macOS): [`openLintPanel`](https://codemirror.net/6/docs/ref/#lint.openLintPanel)
24218
- F8: [`nextDiagnostic`](https://codemirror.net/6/docs/ref/#lint.nextDiagnostic)
24219
*/
24220
const lintKeymap = [
24221
    { key: "Mod-Shift-m", run: openLintPanel, preventDefault: true },
24222
    { key: "F8", run: nextDiagnostic }
24223
];
24224
const lintConfig = /*@__PURE__*/Facet.define({
24225
    combine(input) {
24226
        return Object.assign({ sources: input.map(i => i.source).filter(x => x != null) }, combineConfig(input.map(i => i.config), {
24227
            delay: 750,
24228
            markerFilter: null,
24229
            tooltipFilter: null,
24230
            needsRefresh: null
24231
        }, {
24232
            needsRefresh: (a, b) => !a ? b : !b ? a : u => a(u) || b(u)
24233
        }));
24234
    }
24235
});
24236
function assignKeys(actions) {
24237
    let assigned = [];
24238
    if (actions)
24239
        actions: for (let { name } of actions) {
24240
            for (let i = 0; i < name.length; i++) {
24241
                let ch = name[i];
24242
                if (/[a-zA-Z]/.test(ch) && !assigned.some(c => c.toLowerCase() == ch.toLowerCase())) {
24243
                    assigned.push(ch);
24244
                    continue actions;
24245
                }
24246
            }
24247
            assigned.push("");
24248
        }
24249
    return assigned;
24250
}
24251
function renderDiagnostic(view, diagnostic, inPanel) {
24252
    var _a;
24253
    let keys = inPanel ? assignKeys(diagnostic.actions) : [];
24254
    return crelt("li", { class: "cm-diagnostic cm-diagnostic-" + diagnostic.severity }, crelt("span", { class: "cm-diagnosticText" }, diagnostic.renderMessage ? diagnostic.renderMessage() : diagnostic.message), (_a = diagnostic.actions) === null || _a === void 0 ? void 0 : _a.map((action, i) => {
24255
        let fired = false, click = (e) => {
24256
            e.preventDefault();
24257
            if (fired)
24258
                return;
24259
            fired = true;
24260
            let found = findDiagnostic(view.state.field(lintState).diagnostics, diagnostic);
24261
            if (found)
24262
                action.apply(view, found.from, found.to);
24263
        };
24264
        let { name } = action, keyIndex = keys[i] ? name.indexOf(keys[i]) : -1;
24265
        let nameElt = keyIndex < 0 ? name : [name.slice(0, keyIndex),
24266
            crelt("u", name.slice(keyIndex, keyIndex + 1)),
24267
            name.slice(keyIndex + 1)];
24268
        return crelt("button", {
24269
            type: "button",
24270
            class: "cm-diagnosticAction",
24271
            onclick: click,
24272
            onmousedown: click,
24273
            "aria-label": ` Action: ${name}${keyIndex < 0 ? "" : ` (access key "${keys[i]})"`}.`
24274
        }, nameElt);
24275
    }), diagnostic.source && crelt("div", { class: "cm-diagnosticSource" }, diagnostic.source));
24276
}
24277
class DiagnosticWidget extends WidgetType {
24278
    constructor(diagnostic) {
24279
        super();
24280
        this.diagnostic = diagnostic;
24281
    }
24282
    eq(other) { return other.diagnostic == this.diagnostic; }
24283
    toDOM() {
24284
        return crelt("span", { class: "cm-lintPoint cm-lintPoint-" + this.diagnostic.severity });
24285
    }
24286
}
24287
class PanelItem {
24288
    constructor(view, diagnostic) {
24289
        this.diagnostic = diagnostic;
24290
        this.id = "item_" + Math.floor(Math.random() * 0xffffffff).toString(16);
24291
        this.dom = renderDiagnostic(view, diagnostic, true);
24292
        this.dom.id = this.id;
24293
        this.dom.setAttribute("role", "option");
24294
    }
24295
}
24296
class LintPanel {
24297
    constructor(view) {
24298
        this.view = view;
24299
        this.items = [];
24300
        let onkeydown = (event) => {
24301
            if (event.keyCode == 27) { // Escape
24302
                closeLintPanel(this.view);
24303
                this.view.focus();
24304
            }
24305
            else if (event.keyCode == 38 || event.keyCode == 33) { // ArrowUp, PageUp
24306
                this.moveSelection((this.selectedIndex - 1 + this.items.length) % this.items.length);
24307
            }
24308
            else if (event.keyCode == 40 || event.keyCode == 34) { // ArrowDown, PageDown
24309
                this.moveSelection((this.selectedIndex + 1) % this.items.length);
24310
            }
24311
            else if (event.keyCode == 36) { // Home
24312
                this.moveSelection(0);
24313
            }
24314
            else if (event.keyCode == 35) { // End
24315
                this.moveSelection(this.items.length - 1);
24316
            }
24317
            else if (event.keyCode == 13) { // Enter
24318
                this.view.focus();
24319
            }
24320
            else if (event.keyCode >= 65 && event.keyCode <= 90 && this.selectedIndex >= 0) { // A-Z
24321
                let { diagnostic } = this.items[this.selectedIndex], keys = assignKeys(diagnostic.actions);
24322
                for (let i = 0; i < keys.length; i++)
24323
                    if (keys[i].toUpperCase().charCodeAt(0) == event.keyCode) {
24324
                        let found = findDiagnostic(this.view.state.field(lintState).diagnostics, diagnostic);
24325
                        if (found)
24326
                            diagnostic.actions[i].apply(view, found.from, found.to);
24327
                    }
24328
            }
24329
            else {
24330
                return;
24331
            }
24332
            event.preventDefault();
24333
        };
24334
        let onclick = (event) => {
24335
            for (let i = 0; i < this.items.length; i++) {
24336
                if (this.items[i].dom.contains(event.target))
24337
                    this.moveSelection(i);
24338
            }
24339
        };
24340
        this.list = crelt("ul", {
24341
            tabIndex: 0,
24342
            role: "listbox",
24343
            "aria-label": this.view.state.phrase("Diagnostics"),
24344
            onkeydown,
24345
            onclick
24346
        });
24347
        this.dom = crelt("div", { class: "cm-panel-lint" }, this.list, crelt("button", {
24348
            type: "button",
24349
            name: "close",
24350
            "aria-label": this.view.state.phrase("close"),
24351
            onclick: () => closeLintPanel(this.view)
24352
        }, "×"));
24353
        this.update();
24354
    }
24355
    get selectedIndex() {
24356
        let selected = this.view.state.field(lintState).selected;
24357
        if (!selected)
24358
            return -1;
24359
        for (let i = 0; i < this.items.length; i++)
24360
            if (this.items[i].diagnostic == selected.diagnostic)
24361
                return i;
24362
        return -1;
24363
    }
24364
    update() {
24365
        let { diagnostics, selected } = this.view.state.field(lintState);
24366
        let i = 0, needsSync = false, newSelectedItem = null;
24367
        diagnostics.between(0, this.view.state.doc.length, (_start, _end, { spec }) => {
24368
            let found = -1, item;
24369
            for (let j = i; j < this.items.length; j++)
24370
                if (this.items[j].diagnostic == spec.diagnostic) {
24371
                    found = j;
24372
                    break;
24373
                }
24374
            if (found < 0) {
24375
                item = new PanelItem(this.view, spec.diagnostic);
24376
                this.items.splice(i, 0, item);
24377
                needsSync = true;
24378
            }
24379
            else {
24380
                item = this.items[found];
24381
                if (found > i) {
24382
                    this.items.splice(i, found - i);
24383
                    needsSync = true;
24384
                }
24385
            }
24386
            if (selected && item.diagnostic == selected.diagnostic) {
24387
                if (!item.dom.hasAttribute("aria-selected")) {
24388
                    item.dom.setAttribute("aria-selected", "true");
24389
                    newSelectedItem = item;
24390
                }
24391
            }
24392
            else if (item.dom.hasAttribute("aria-selected")) {
24393
                item.dom.removeAttribute("aria-selected");
24394
            }
24395
            i++;
24396
        });
24397
        while (i < this.items.length && !(this.items.length == 1 && this.items[0].diagnostic.from < 0)) {
24398
            needsSync = true;
24399
            this.items.pop();
24400
        }
24401
        if (this.items.length == 0) {
24402
            this.items.push(new PanelItem(this.view, {
24403
                from: -1, to: -1,
24404
                severity: "info",
24405
                message: this.view.state.phrase("No diagnostics")
24406
            }));
24407
            needsSync = true;
24408
        }
24409
        if (newSelectedItem) {
24410
            this.list.setAttribute("aria-activedescendant", newSelectedItem.id);
24411
            this.view.requestMeasure({
24412
                key: this,
24413
                read: () => ({ sel: newSelectedItem.dom.getBoundingClientRect(), panel: this.list.getBoundingClientRect() }),
24414
                write: ({ sel, panel }) => {
24415
                    let scaleY = panel.height / this.list.offsetHeight;
24416
                    if (sel.top < panel.top)
24417
                        this.list.scrollTop -= (panel.top - sel.top) / scaleY;
24418
                    else if (sel.bottom > panel.bottom)
24419
                        this.list.scrollTop += (sel.bottom - panel.bottom) / scaleY;
24420
                }
24421
            });
24422
        }
24423
        else if (this.selectedIndex < 0) {
24424
            this.list.removeAttribute("aria-activedescendant");
24425
        }
24426
        if (needsSync)
24427
            this.sync();
24428
    }
24429
    sync() {
24430
        let domPos = this.list.firstChild;
24431
        function rm() {
24432
            let prev = domPos;
24433
            domPos = prev.nextSibling;
24434
            prev.remove();
24435
        }
24436
        for (let item of this.items) {
24437
            if (item.dom.parentNode == this.list) {
24438
                while (domPos != item.dom)
24439
                    rm();
24440
                domPos = item.dom.nextSibling;
24441
            }
24442
            else {
24443
                this.list.insertBefore(item.dom, domPos);
24444
            }
24445
        }
24446
        while (domPos)
24447
            rm();
24448
    }
24449
    moveSelection(selectedIndex) {
24450
        if (this.selectedIndex < 0)
24451
            return;
24452
        let field = this.view.state.field(lintState);
24453
        let selection = findDiagnostic(field.diagnostics, this.items[selectedIndex].diagnostic);
24454
        if (!selection)
24455
            return;
24456
        this.view.dispatch({
24457
            selection: { anchor: selection.from, head: selection.to },
24458
            scrollIntoView: true,
24459
            effects: movePanelSelection.of(selection)
24460
        });
24461
    }
24462
    static open(view) { return new LintPanel(view); }
24463
}
24464
function svg(content, attrs = `viewBox="0 0 40 40"`) {
24465
    return `url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" ${attrs}>${encodeURIComponent(content)}</svg>')`;
24466
}
24467
function underline(color) {
24468
    return svg(`<path d="m0 2.5 l2 -1.5 l1 0 l2 1.5 l1 0" stroke="${color}" fill="none" stroke-width=".7"/>`, `width="6" height="3"`);
24469
}
24470
const baseTheme = /*@__PURE__*/EditorView.baseTheme({
24471
    ".cm-diagnostic": {
24472
        padding: "3px 6px 3px 8px",
24473
        marginLeft: "-1px",
24474
        display: "block",
24475
        whiteSpace: "pre-wrap"
24476
    },
24477
    ".cm-diagnostic-error": { borderLeft: "5px solid #d11" },
24478
    ".cm-diagnostic-warning": { borderLeft: "5px solid orange" },
24479
    ".cm-diagnostic-info": { borderLeft: "5px solid #999" },
24480
    ".cm-diagnostic-hint": { borderLeft: "5px solid #66d" },
24481
    ".cm-diagnosticAction": {
24482
        font: "inherit",
24483
        border: "none",
24484
        padding: "2px 4px",
24485
        backgroundColor: "#444",
24486
        color: "white",
24487
        borderRadius: "3px",
24488
        marginLeft: "8px",
24489
        cursor: "pointer"
24490
    },
24491
    ".cm-diagnosticSource": {
24492
        fontSize: "70%",
24493
        opacity: .7
24494
    },
24495
    ".cm-lintRange": {
24496
        backgroundPosition: "left bottom",
24497
        backgroundRepeat: "repeat-x",
24498
        paddingBottom: "0.7px",
24499
    },
24500
    ".cm-lintRange-error": { backgroundImage: /*@__PURE__*/underline("#d11") },
24501
    ".cm-lintRange-warning": { backgroundImage: /*@__PURE__*/underline("orange") },
24502
    ".cm-lintRange-info": { backgroundImage: /*@__PURE__*/underline("#999") },
24503
    ".cm-lintRange-hint": { backgroundImage: /*@__PURE__*/underline("#66d") },
24504
    ".cm-lintRange-active": { backgroundColor: "#ffdd9980" },
24505
    ".cm-tooltip-lint": {
24506
        padding: 0,
24507
        margin: 0
24508
    },
24509
    ".cm-lintPoint": {
24510
        position: "relative",
24511
        "&:after": {
24512
            content: '""',
24513
            position: "absolute",
24514
            bottom: 0,
24515
            left: "-2px",
24516
            borderLeft: "3px solid transparent",
24517
            borderRight: "3px solid transparent",
24518
            borderBottom: "4px solid #d11"
24519
        }
24520
    },
24521
    ".cm-lintPoint-warning": {
24522
        "&:after": { borderBottomColor: "orange" }
24523
    },
24524
    ".cm-lintPoint-info": {
24525
        "&:after": { borderBottomColor: "#999" }
24526
    },
24527
    ".cm-lintPoint-hint": {
24528
        "&:after": { borderBottomColor: "#66d" }
24529
    },
24530
    ".cm-panel.cm-panel-lint": {
24531
        position: "relative",
24532
        "& ul": {
24533
            maxHeight: "100px",
24534
            overflowY: "auto",
24535
            "& [aria-selected]": {
24536
                backgroundColor: "#ddd",
24537
                "& u": { textDecoration: "underline" }
24538
            },
24539
            "&:focus [aria-selected]": {
24540
                background_fallback: "#bdf",
24541
                backgroundColor: "Highlight",
24542
                color_fallback: "white",
24543
                color: "HighlightText"
24544
            },
24545
            "& u": { textDecoration: "none" },
24546
            padding: 0,
24547
            margin: 0
24548
        },
24549
        "& [name=close]": {
24550
            position: "absolute",
24551
            top: "0",
24552
            right: "2px",
24553
            background: "inherit",
24554
            border: "none",
24555
            font: "inherit",
24556
            padding: 0,
24557
            margin: 0
24558
        }
24559
    }
24560
});
24561
const lintExtensions = [
24562
    lintState,
24563
    /*@__PURE__*/EditorView.decorations.compute([lintState], state => {
24564
        let { selected, panel } = state.field(lintState);
24565
        return !selected || !panel || selected.from == selected.to ? Decoration.none : Decoration.set([
24566
            activeMark.range(selected.from, selected.to)
24567
        ]);
24568
    }),
24569
    /*@__PURE__*/hoverTooltip(lintTooltip, { hideOn: hideTooltip }),
24570
    baseTheme
24571
];
24572
 
24573
// (The superfluous function calls around the list of extensions work
24574
// around current limitations in tree-shaking software.)
24575
/**
24576
This is an extension value that just pulls together a number of
24577
extensions that you might want in a basic editor. It is meant as a
24578
convenient helper to quickly set up CodeMirror without installing
24579
and importing a lot of separate packages.
24580
 
24581
Specifically, it includes...
24582
 
24583
 - [the default command bindings](https://codemirror.net/6/docs/ref/#commands.defaultKeymap)
24584
 - [line numbers](https://codemirror.net/6/docs/ref/#view.lineNumbers)
24585
 - [special character highlighting](https://codemirror.net/6/docs/ref/#view.highlightSpecialChars)
24586
 - [the undo history](https://codemirror.net/6/docs/ref/#commands.history)
24587
 - [a fold gutter](https://codemirror.net/6/docs/ref/#language.foldGutter)
24588
 - [custom selection drawing](https://codemirror.net/6/docs/ref/#view.drawSelection)
24589
 - [drop cursor](https://codemirror.net/6/docs/ref/#view.dropCursor)
24590
 - [multiple selections](https://codemirror.net/6/docs/ref/#state.EditorState^allowMultipleSelections)
24591
 - [reindentation on input](https://codemirror.net/6/docs/ref/#language.indentOnInput)
24592
 - [the default highlight style](https://codemirror.net/6/docs/ref/#language.defaultHighlightStyle) (as fallback)
24593
 - [bracket matching](https://codemirror.net/6/docs/ref/#language.bracketMatching)
24594
 - [bracket closing](https://codemirror.net/6/docs/ref/#autocomplete.closeBrackets)
24595
 - [autocompletion](https://codemirror.net/6/docs/ref/#autocomplete.autocompletion)
24596
 - [rectangular selection](https://codemirror.net/6/docs/ref/#view.rectangularSelection) and [crosshair cursor](https://codemirror.net/6/docs/ref/#view.crosshairCursor)
24597
 - [active line highlighting](https://codemirror.net/6/docs/ref/#view.highlightActiveLine)
24598
 - [active line gutter highlighting](https://codemirror.net/6/docs/ref/#view.highlightActiveLineGutter)
24599
 - [selection match highlighting](https://codemirror.net/6/docs/ref/#search.highlightSelectionMatches)
24600
 - [search](https://codemirror.net/6/docs/ref/#search.searchKeymap)
24601
 - [linting](https://codemirror.net/6/docs/ref/#lint.lintKeymap)
24602
 
24603
(You'll probably want to add some language package to your setup
24604
too.)
24605
 
24606
This extension does not allow customization. The idea is that,
24607
once you decide you want to configure your editor more precisely,
24608
you take this package's source (which is just a bunch of imports
24609
and an array literal), copy it into your own code, and adjust it
24610
as desired.
24611
*/
24612
const basicSetup = /*@__PURE__*/(() => [
24613
    lineNumbers(),
24614
    highlightActiveLineGutter(),
24615
    highlightSpecialChars(),
24616
    history(),
24617
    foldGutter(),
24618
    drawSelection(),
24619
    dropCursor(),
24620
    EditorState.allowMultipleSelections.of(true),
24621
    indentOnInput(),
24622
    syntaxHighlighting(defaultHighlightStyle, { fallback: true }),
24623
    bracketMatching(),
24624
    closeBrackets(),
24625
    autocompletion(),
24626
    rectangularSelection(),
24627
    crosshairCursor(),
24628
    highlightActiveLine(),
24629
    highlightSelectionMatches(),
24630
    keymap.of([
24631
        ...closeBracketsKeymap,
24632
        ...defaultKeymap,
24633
        ...searchKeymap,
24634
        ...historyKeymap,
24635
        ...foldKeymap,
24636
        ...completionKeymap,
24637
        ...lintKeymap
24638
    ])
24639
])();
24640
 
24641
/**
24642
A parse stack. These are used internally by the parser to track
24643
parsing progress. They also provide some properties and methods
24644
that external code such as a tokenizer can use to get information
24645
about the parse state.
24646
*/
24647
class Stack {
24648
    /**
24649
    @internal
24650
    */
24651
    constructor(
24652
    /**
24653
    The parse that this stack is part of @internal
24654
    */
24655
    p,
24656
    /**
24657
    Holds state, input pos, buffer index triplets for all but the
24658
    top state @internal
24659
    */
24660
    stack,
24661
    /**
24662
    The current parse state @internal
24663
    */
24664
    state,
24665
    // The position at which the next reduce should take place. This
24666
    // can be less than `this.pos` when skipped expressions have been
24667
    // added to the stack (which should be moved outside of the next
24668
    // reduction)
24669
    /**
24670
    @internal
24671
    */
24672
    reducePos,
24673
    /**
24674
    The input position up to which this stack has parsed.
24675
    */
24676
    pos,
24677
    /**
24678
    The dynamic score of the stack, including dynamic precedence
24679
    and error-recovery penalties
24680
    @internal
24681
    */
24682
    score,
24683
    // The output buffer. Holds (type, start, end, size) quads
24684
    // representing nodes created by the parser, where `size` is
24685
    // amount of buffer array entries covered by this node.
24686
    /**
24687
    @internal
24688
    */
24689
    buffer,
24690
    // The base offset of the buffer. When stacks are split, the split
24691
    // instance shared the buffer history with its parent up to
24692
    // `bufferBase`, which is the absolute offset (including the
24693
    // offset of previous splits) into the buffer at which this stack
24694
    // starts writing.
24695
    /**
24696
    @internal
24697
    */
24698
    bufferBase,
24699
    /**
24700
    @internal
24701
    */
24702
    curContext,
24703
    /**
24704
    @internal
24705
    */
24706
    lookAhead = 0,
24707
    // A parent stack from which this was split off, if any. This is
24708
    // set up so that it always points to a stack that has some
24709
    // additional buffer content, never to a stack with an equal
24710
    // `bufferBase`.
24711
    /**
24712
    @internal
24713
    */
24714
    parent) {
24715
        this.p = p;
24716
        this.stack = stack;
24717
        this.state = state;
24718
        this.reducePos = reducePos;
24719
        this.pos = pos;
24720
        this.score = score;
24721
        this.buffer = buffer;
24722
        this.bufferBase = bufferBase;
24723
        this.curContext = curContext;
24724
        this.lookAhead = lookAhead;
24725
        this.parent = parent;
24726
    }
24727
    /**
24728
    @internal
24729
    */
24730
    toString() {
24731
        return `[${this.stack.filter((_, i) => i % 3 == 0).concat(this.state)}]@${this.pos}${this.score ? "!" + this.score : ""}`;
24732
    }
24733
    // Start an empty stack
24734
    /**
24735
    @internal
24736
    */
24737
    static start(p, state, pos = 0) {
24738
        let cx = p.parser.context;
24739
        return new Stack(p, [], state, pos, pos, 0, [], 0, cx ? new StackContext(cx, cx.start) : null, 0, null);
24740
    }
24741
    /**
24742
    The stack's current [context](#lr.ContextTracker) value, if
24743
    any. Its type will depend on the context tracker's type
24744
    parameter, or it will be `null` if there is no context
24745
    tracker.
24746
    */
24747
    get context() { return this.curContext ? this.curContext.context : null; }
24748
    // Push a state onto the stack, tracking its start position as well
24749
    // as the buffer base at that point.
24750
    /**
24751
    @internal
24752
    */
24753
    pushState(state, start) {
24754
        this.stack.push(this.state, start, this.bufferBase + this.buffer.length);
24755
        this.state = state;
24756
    }
24757
    // Apply a reduce action
24758
    /**
24759
    @internal
24760
    */
24761
    reduce(action) {
24762
        var _a;
24763
        let depth = action >> 19 /* Action.ReduceDepthShift */, type = action & 65535 /* Action.ValueMask */;
24764
        let { parser } = this.p;
24765
        let dPrec = parser.dynamicPrecedence(type);
24766
        if (dPrec)
24767
            this.score += dPrec;
24768
        if (depth == 0) {
24769
            this.pushState(parser.getGoto(this.state, type, true), this.reducePos);
24770
            // Zero-depth reductions are a special case—they add stuff to
24771
            // the stack without popping anything off.
24772
            if (type < parser.minRepeatTerm)
24773
                this.storeNode(type, this.reducePos, this.reducePos, 4, true);
24774
            this.reduceContext(type, this.reducePos);
24775
            return;
24776
        }
24777
        // Find the base index into `this.stack`, content after which will
24778
        // be dropped. Note that with `StayFlag` reductions we need to
24779
        // consume two extra frames (the dummy parent node for the skipped
24780
        // expression and the state that we'll be staying in, which should
24781
        // be moved to `this.state`).
24782
        let base = this.stack.length - ((depth - 1) * 3) - (action & 262144 /* Action.StayFlag */ ? 6 : 0);
24783
        let start = base ? this.stack[base - 2] : this.p.ranges[0].from, size = this.reducePos - start;
24784
        // This is a kludge to try and detect overly deep left-associative
24785
        // trees, which will not increase the parse stack depth and thus
24786
        // won't be caught by the regular stack-depth limit check.
24787
        if (size >= 2000 /* Recover.MinBigReduction */ && !((_a = this.p.parser.nodeSet.types[type]) === null || _a === void 0 ? void 0 : _a.isAnonymous)) {
24788
            if (start == this.p.lastBigReductionStart) {
24789
                this.p.bigReductionCount++;
24790
                this.p.lastBigReductionSize = size;
24791
            }
24792
            else if (this.p.lastBigReductionSize < size) {
24793
                this.p.bigReductionCount = 1;
24794
                this.p.lastBigReductionStart = start;
24795
                this.p.lastBigReductionSize = size;
24796
            }
24797
        }
24798
        let bufferBase = base ? this.stack[base - 1] : 0, count = this.bufferBase + this.buffer.length - bufferBase;
24799
        // Store normal terms or `R -> R R` repeat reductions
24800
        if (type < parser.minRepeatTerm || (action & 131072 /* Action.RepeatFlag */)) {
24801
            let pos = parser.stateFlag(this.state, 1 /* StateFlag.Skipped */) ? this.pos : this.reducePos;
24802
            this.storeNode(type, start, pos, count + 4, true);
24803
        }
24804
        if (action & 262144 /* Action.StayFlag */) {
24805
            this.state = this.stack[base];
24806
        }
24807
        else {
24808
            let baseStateID = this.stack[base - 3];
24809
            this.state = parser.getGoto(baseStateID, type, true);
24810
        }
24811
        while (this.stack.length > base)
24812
            this.stack.pop();
24813
        this.reduceContext(type, start);
24814
    }
24815
    // Shift a value into the buffer
24816
    /**
24817
    @internal
24818
    */
24819
    storeNode(term, start, end, size = 4, isReduce = false) {
24820
        if (term == 0 /* Term.Err */ &&
24821
            (!this.stack.length || this.stack[this.stack.length - 1] < this.buffer.length + this.bufferBase)) {
24822
            // Try to omit/merge adjacent error nodes
24823
            let cur = this, top = this.buffer.length;
24824
            if (top == 0 && cur.parent) {
24825
                top = cur.bufferBase - cur.parent.bufferBase;
24826
                cur = cur.parent;
24827
            }
24828
            if (top > 0 && cur.buffer[top - 4] == 0 /* Term.Err */ && cur.buffer[top - 1] > -1) {
24829
                if (start == end)
24830
                    return;
24831
                if (cur.buffer[top - 2] >= start) {
24832
                    cur.buffer[top - 2] = end;
24833
                    return;
24834
                }
24835
            }
24836
        }
24837
        if (!isReduce || this.pos == end) { // Simple case, just append
24838
            this.buffer.push(term, start, end, size);
24839
        }
24840
        else { // There may be skipped nodes that have to be moved forward
24841
            let index = this.buffer.length;
24842
            if (index > 0 && this.buffer[index - 4] != 0 /* Term.Err */)
24843
                while (index > 0 && this.buffer[index - 2] > end) {
24844
                    // Move this record forward
24845
                    this.buffer[index] = this.buffer[index - 4];
24846
                    this.buffer[index + 1] = this.buffer[index - 3];
24847
                    this.buffer[index + 2] = this.buffer[index - 2];
24848
                    this.buffer[index + 3] = this.buffer[index - 1];
24849
                    index -= 4;
24850
                    if (size > 4)
24851
                        size -= 4;
24852
                }
24853
            this.buffer[index] = term;
24854
            this.buffer[index + 1] = start;
24855
            this.buffer[index + 2] = end;
24856
            this.buffer[index + 3] = size;
24857
        }
24858
    }
24859
    // Apply a shift action
24860
    /**
24861
    @internal
24862
    */
24863
    shift(action, type, start, end) {
24864
        if (action & 131072 /* Action.GotoFlag */) {
24865
            this.pushState(action & 65535 /* Action.ValueMask */, this.pos);
24866
        }
24867
        else if ((action & 262144 /* Action.StayFlag */) == 0) { // Regular shift
24868
            let nextState = action, { parser } = this.p;
24869
            if (end > this.pos || type <= parser.maxNode) {
24870
                this.pos = end;
24871
                if (!parser.stateFlag(nextState, 1 /* StateFlag.Skipped */))
24872
                    this.reducePos = end;
24873
            }
24874
            this.pushState(nextState, start);
24875
            this.shiftContext(type, start);
24876
            if (type <= parser.maxNode)
24877
                this.buffer.push(type, start, end, 4);
24878
        }
24879
        else { // Shift-and-stay, which means this is a skipped token
24880
            this.pos = end;
24881
            this.shiftContext(type, start);
24882
            if (type <= this.p.parser.maxNode)
24883
                this.buffer.push(type, start, end, 4);
24884
        }
24885
    }
24886
    // Apply an action
24887
    /**
24888
    @internal
24889
    */
24890
    apply(action, next, nextStart, nextEnd) {
24891
        if (action & 65536 /* Action.ReduceFlag */)
24892
            this.reduce(action);
24893
        else
24894
            this.shift(action, next, nextStart, nextEnd);
24895
    }
24896
    // Add a prebuilt (reused) node into the buffer.
24897
    /**
24898
    @internal
24899
    */
24900
    useNode(value, next) {
24901
        let index = this.p.reused.length - 1;
24902
        if (index < 0 || this.p.reused[index] != value) {
24903
            this.p.reused.push(value);
24904
            index++;
24905
        }
24906
        let start = this.pos;
24907
        this.reducePos = this.pos = start + value.length;
24908
        this.pushState(next, start);
24909
        this.buffer.push(index, start, this.reducePos, -1 /* size == -1 means this is a reused value */);
24910
        if (this.curContext)
24911
            this.updateContext(this.curContext.tracker.reuse(this.curContext.context, value, this, this.p.stream.reset(this.pos - value.length)));
24912
    }
24913
    // Split the stack. Due to the buffer sharing and the fact
24914
    // that `this.stack` tends to stay quite shallow, this isn't very
24915
    // expensive.
24916
    /**
24917
    @internal
24918
    */
24919
    split() {
24920
        let parent = this;
24921
        let off = parent.buffer.length;
24922
        // Because the top of the buffer (after this.pos) may be mutated
24923
        // to reorder reductions and skipped tokens, and shared buffers
24924
        // should be immutable, this copies any outstanding skipped tokens
24925
        // to the new buffer, and puts the base pointer before them.
24926
        while (off > 0 && parent.buffer[off - 2] > parent.reducePos)
24927
            off -= 4;
24928
        let buffer = parent.buffer.slice(off), base = parent.bufferBase + off;
24929
        // Make sure parent points to an actual parent with content, if there is such a parent.
24930
        while (parent && base == parent.bufferBase)
24931
            parent = parent.parent;
24932
        return new Stack(this.p, this.stack.slice(), this.state, this.reducePos, this.pos, this.score, buffer, base, this.curContext, this.lookAhead, parent);
24933
    }
24934
    // Try to recover from an error by 'deleting' (ignoring) one token.
24935
    /**
24936
    @internal
24937
    */
24938
    recoverByDelete(next, nextEnd) {
24939
        let isNode = next <= this.p.parser.maxNode;
24940
        if (isNode)
24941
            this.storeNode(next, this.pos, nextEnd, 4);
24942
        this.storeNode(0 /* Term.Err */, this.pos, nextEnd, isNode ? 8 : 4);
24943
        this.pos = this.reducePos = nextEnd;
24944
        this.score -= 190 /* Recover.Delete */;
24945
    }
24946
    /**
24947
    Check if the given term would be able to be shifted (optionally
24948
    after some reductions) on this stack. This can be useful for
24949
    external tokenizers that want to make sure they only provide a
24950
    given token when it applies.
24951
    */
24952
    canShift(term) {
24953
        for (let sim = new SimulatedStack(this);;) {
24954
            let action = this.p.parser.stateSlot(sim.state, 4 /* ParseState.DefaultReduce */) || this.p.parser.hasAction(sim.state, term);
24955
            if (action == 0)
24956
                return false;
24957
            if ((action & 65536 /* Action.ReduceFlag */) == 0)
24958
                return true;
24959
            sim.reduce(action);
24960
        }
24961
    }
24962
    // Apply up to Recover.MaxNext recovery actions that conceptually
24963
    // inserts some missing token or rule.
24964
    /**
24965
    @internal
24966
    */
24967
    recoverByInsert(next) {
24968
        if (this.stack.length >= 300 /* Recover.MaxInsertStackDepth */)
24969
            return [];
24970
        let nextStates = this.p.parser.nextStates(this.state);
24971
        if (nextStates.length > 4 /* Recover.MaxNext */ << 1 || this.stack.length >= 120 /* Recover.DampenInsertStackDepth */) {
24972
            let best = [];
24973
            for (let i = 0, s; i < nextStates.length; i += 2) {
24974
                if ((s = nextStates[i + 1]) != this.state && this.p.parser.hasAction(s, next))
24975
                    best.push(nextStates[i], s);
24976
            }
24977
            if (this.stack.length < 120 /* Recover.DampenInsertStackDepth */)
24978
                for (let i = 0; best.length < 4 /* Recover.MaxNext */ << 1 && i < nextStates.length; i += 2) {
24979
                    let s = nextStates[i + 1];
24980
                    if (!best.some((v, i) => (i & 1) && v == s))
24981
                        best.push(nextStates[i], s);
24982
                }
24983
            nextStates = best;
24984
        }
24985
        let result = [];
24986
        for (let i = 0; i < nextStates.length && result.length < 4 /* Recover.MaxNext */; i += 2) {
24987
            let s = nextStates[i + 1];
24988
            if (s == this.state)
24989
                continue;
24990
            let stack = this.split();
24991
            stack.pushState(s, this.pos);
24992
            stack.storeNode(0 /* Term.Err */, stack.pos, stack.pos, 4, true);
24993
            stack.shiftContext(nextStates[i], this.pos);
24994
            stack.reducePos = this.pos;
24995
            stack.score -= 200 /* Recover.Insert */;
24996
            result.push(stack);
24997
        }
24998
        return result;
24999
    }
25000
    // Force a reduce, if possible. Return false if that can't
25001
    // be done.
25002
    /**
25003
    @internal
25004
    */
25005
    forceReduce() {
25006
        let { parser } = this.p;
25007
        let reduce = parser.stateSlot(this.state, 5 /* ParseState.ForcedReduce */);
25008
        if ((reduce & 65536 /* Action.ReduceFlag */) == 0)
25009
            return false;
25010
        if (!parser.validAction(this.state, reduce)) {
25011
            let depth = reduce >> 19 /* Action.ReduceDepthShift */, term = reduce & 65535 /* Action.ValueMask */;
25012
            let target = this.stack.length - depth * 3;
25013
            if (target < 0 || parser.getGoto(this.stack[target], term, false) < 0) {
25014
                let backup = this.findForcedReduction();
25015
                if (backup == null)
25016
                    return false;
25017
                reduce = backup;
25018
            }
25019
            this.storeNode(0 /* Term.Err */, this.pos, this.pos, 4, true);
25020
            this.score -= 100 /* Recover.Reduce */;
25021
        }
25022
        this.reducePos = this.pos;
25023
        this.reduce(reduce);
25024
        return true;
25025
    }
25026
    /**
25027
    Try to scan through the automaton to find some kind of reduction
25028
    that can be applied. Used when the regular ForcedReduce field
25029
    isn't a valid action. @internal
25030
    */
25031
    findForcedReduction() {
25032
        let { parser } = this.p, seen = [];
25033
        let explore = (state, depth) => {
25034
            if (seen.includes(state))
25035
                return;
25036
            seen.push(state);
25037
            return parser.allActions(state, (action) => {
25038
                if (action & (262144 /* Action.StayFlag */ | 131072 /* Action.GotoFlag */)) ;
25039
                else if (action & 65536 /* Action.ReduceFlag */) {
25040
                    let rDepth = (action >> 19 /* Action.ReduceDepthShift */) - depth;
25041
                    if (rDepth > 1) {
25042
                        let term = action & 65535 /* Action.ValueMask */, target = this.stack.length - rDepth * 3;
25043
                        if (target >= 0 && parser.getGoto(this.stack[target], term, false) >= 0)
25044
                            return (rDepth << 19 /* Action.ReduceDepthShift */) | 65536 /* Action.ReduceFlag */ | term;
25045
                    }
25046
                }
25047
                else {
25048
                    let found = explore(action, depth + 1);
25049
                    if (found != null)
25050
                        return found;
25051
                }
25052
            });
25053
        };
25054
        return explore(this.state, 0);
25055
    }
25056
    /**
25057
    @internal
25058
    */
25059
    forceAll() {
25060
        while (!this.p.parser.stateFlag(this.state, 2 /* StateFlag.Accepting */)) {
25061
            if (!this.forceReduce()) {
25062
                this.storeNode(0 /* Term.Err */, this.pos, this.pos, 4, true);
25063
                break;
25064
            }
25065
        }
25066
        return this;
25067
    }
25068
    /**
25069
    Check whether this state has no further actions (assumed to be a direct descendant of the
25070
    top state, since any other states must be able to continue
25071
    somehow). @internal
25072
    */
25073
    get deadEnd() {
25074
        if (this.stack.length != 3)
25075
            return false;
25076
        let { parser } = this.p;
25077
        return parser.data[parser.stateSlot(this.state, 1 /* ParseState.Actions */)] == 65535 /* Seq.End */ &&
25078
            !parser.stateSlot(this.state, 4 /* ParseState.DefaultReduce */);
25079
    }
25080
    /**
25081
    Restart the stack (put it back in its start state). Only safe
25082
    when this.stack.length == 3 (state is directly below the top
25083
    state). @internal
25084
    */
25085
    restart() {
25086
        this.storeNode(0 /* Term.Err */, this.pos, this.pos, 4, true);
25087
        this.state = this.stack[0];
25088
        this.stack.length = 0;
25089
    }
25090
    /**
25091
    @internal
25092
    */
25093
    sameState(other) {
25094
        if (this.state != other.state || this.stack.length != other.stack.length)
25095
            return false;
25096
        for (let i = 0; i < this.stack.length; i += 3)
25097
            if (this.stack[i] != other.stack[i])
25098
                return false;
25099
        return true;
25100
    }
25101
    /**
25102
    Get the parser used by this stack.
25103
    */
25104
    get parser() { return this.p.parser; }
25105
    /**
25106
    Test whether a given dialect (by numeric ID, as exported from
25107
    the terms file) is enabled.
25108
    */
25109
    dialectEnabled(dialectID) { return this.p.parser.dialect.flags[dialectID]; }
25110
    shiftContext(term, start) {
25111
        if (this.curContext)
25112
            this.updateContext(this.curContext.tracker.shift(this.curContext.context, term, this, this.p.stream.reset(start)));
25113
    }
25114
    reduceContext(term, start) {
25115
        if (this.curContext)
25116
            this.updateContext(this.curContext.tracker.reduce(this.curContext.context, term, this, this.p.stream.reset(start)));
25117
    }
25118
    /**
25119
    @internal
25120
    */
25121
    emitContext() {
25122
        let last = this.buffer.length - 1;
25123
        if (last < 0 || this.buffer[last] != -3)
25124
            this.buffer.push(this.curContext.hash, this.pos, this.pos, -3);
25125
    }
25126
    /**
25127
    @internal
25128
    */
25129
    emitLookAhead() {
25130
        let last = this.buffer.length - 1;
25131
        if (last < 0 || this.buffer[last] != -4)
25132
            this.buffer.push(this.lookAhead, this.pos, this.pos, -4);
25133
    }
25134
    updateContext(context) {
25135
        if (context != this.curContext.context) {
25136
            let newCx = new StackContext(this.curContext.tracker, context);
25137
            if (newCx.hash != this.curContext.hash)
25138
                this.emitContext();
25139
            this.curContext = newCx;
25140
        }
25141
    }
25142
    /**
25143
    @internal
25144
    */
25145
    setLookAhead(lookAhead) {
25146
        if (lookAhead > this.lookAhead) {
25147
            this.emitLookAhead();
25148
            this.lookAhead = lookAhead;
25149
        }
25150
    }
25151
    /**
25152
    @internal
25153
    */
25154
    close() {
25155
        if (this.curContext && this.curContext.tracker.strict)
25156
            this.emitContext();
25157
        if (this.lookAhead > 0)
25158
            this.emitLookAhead();
25159
    }
25160
}
25161
class StackContext {
25162
    constructor(tracker, context) {
25163
        this.tracker = tracker;
25164
        this.context = context;
25165
        this.hash = tracker.strict ? tracker.hash(context) : 0;
25166
    }
25167
}
25168
// Used to cheaply run some reductions to scan ahead without mutating
25169
// an entire stack
25170
class SimulatedStack {
25171
    constructor(start) {
25172
        this.start = start;
25173
        this.state = start.state;
25174
        this.stack = start.stack;
25175
        this.base = this.stack.length;
25176
    }
25177
    reduce(action) {
25178
        let term = action & 65535 /* Action.ValueMask */, depth = action >> 19 /* Action.ReduceDepthShift */;
25179
        if (depth == 0) {
25180
            if (this.stack == this.start.stack)
25181
                this.stack = this.stack.slice();
25182
            this.stack.push(this.state, 0, 0);
25183
            this.base += 3;
25184
        }
25185
        else {
25186
            this.base -= (depth - 1) * 3;
25187
        }
25188
        let goto = this.start.p.parser.getGoto(this.stack[this.base - 3], term, true);
25189
        this.state = goto;
25190
    }
25191
}
25192
// This is given to `Tree.build` to build a buffer, and encapsulates
25193
// the parent-stack-walking necessary to read the nodes.
25194
class StackBufferCursor {
25195
    constructor(stack, pos, index) {
25196
        this.stack = stack;
25197
        this.pos = pos;
25198
        this.index = index;
25199
        this.buffer = stack.buffer;
25200
        if (this.index == 0)
25201
            this.maybeNext();
25202
    }
25203
    static create(stack, pos = stack.bufferBase + stack.buffer.length) {
25204
        return new StackBufferCursor(stack, pos, pos - stack.bufferBase);
25205
    }
25206
    maybeNext() {
25207
        let next = this.stack.parent;
25208
        if (next != null) {
25209
            this.index = this.stack.bufferBase - next.bufferBase;
25210
            this.stack = next;
25211
            this.buffer = next.buffer;
25212
        }
25213
    }
25214
    get id() { return this.buffer[this.index - 4]; }
25215
    get start() { return this.buffer[this.index - 3]; }
25216
    get end() { return this.buffer[this.index - 2]; }
25217
    get size() { return this.buffer[this.index - 1]; }
25218
    next() {
25219
        this.index -= 4;
25220
        this.pos -= 4;
25221
        if (this.index == 0)
25222
            this.maybeNext();
25223
    }
25224
    fork() {
25225
        return new StackBufferCursor(this.stack, this.pos, this.index);
25226
    }
25227
}
25228
 
25229
// See lezer-generator/src/encode.ts for comments about the encoding
25230
// used here
25231
function decodeArray(input, Type = Uint16Array) {
25232
    if (typeof input != "string")
25233
        return input;
25234
    let array = null;
25235
    for (let pos = 0, out = 0; pos < input.length;) {
25236
        let value = 0;
25237
        for (;;) {
25238
            let next = input.charCodeAt(pos++), stop = false;
25239
            if (next == 126 /* Encode.BigValCode */) {
25240
                value = 65535 /* Encode.BigVal */;
25241
                break;
25242
            }
25243
            if (next >= 92 /* Encode.Gap2 */)
25244
                next--;
25245
            if (next >= 34 /* Encode.Gap1 */)
25246
                next--;
25247
            let digit = next - 32 /* Encode.Start */;
25248
            if (digit >= 46 /* Encode.Base */) {
25249
                digit -= 46 /* Encode.Base */;
25250
                stop = true;
25251
            }
25252
            value += digit;
25253
            if (stop)
25254
                break;
25255
            value *= 46 /* Encode.Base */;
25256
        }
25257
        if (array)
25258
            array[out++] = value;
25259
        else
25260
            array = new Type(value);
25261
    }
25262
    return array;
25263
}
25264
 
25265
class CachedToken {
25266
    constructor() {
25267
        this.start = -1;
25268
        this.value = -1;
25269
        this.end = -1;
25270
        this.extended = -1;
25271
        this.lookAhead = 0;
25272
        this.mask = 0;
25273
        this.context = 0;
25274
    }
25275
}
25276
const nullToken = new CachedToken;
25277
/**
25278
[Tokenizers](#lr.ExternalTokenizer) interact with the input
25279
through this interface. It presents the input as a stream of
25280
characters, tracking lookahead and hiding the complexity of
25281
[ranges](#common.Parser.parse^ranges) from tokenizer code.
25282
*/
25283
class InputStream {
25284
    /**
25285
    @internal
25286
    */
25287
    constructor(
25288
    /**
25289
    @internal
25290
    */
25291
    input,
25292
    /**
25293
    @internal
25294
    */
25295
    ranges) {
25296
        this.input = input;
25297
        this.ranges = ranges;
25298
        /**
25299
        @internal
25300
        */
25301
        this.chunk = "";
25302
        /**
25303
        @internal
25304
        */
25305
        this.chunkOff = 0;
25306
        /**
25307
        Backup chunk
25308
        */
25309
        this.chunk2 = "";
25310
        this.chunk2Pos = 0;
25311
        /**
25312
        The character code of the next code unit in the input, or -1
25313
        when the stream is at the end of the input.
25314
        */
25315
        this.next = -1;
25316
        /**
25317
        @internal
25318
        */
25319
        this.token = nullToken;
25320
        this.rangeIndex = 0;
25321
        this.pos = this.chunkPos = ranges[0].from;
25322
        this.range = ranges[0];
25323
        this.end = ranges[ranges.length - 1].to;
25324
        this.readNext();
25325
    }
25326
    /**
25327
    @internal
25328
    */
25329
    resolveOffset(offset, assoc) {
25330
        let range = this.range, index = this.rangeIndex;
25331
        let pos = this.pos + offset;
25332
        while (pos < range.from) {
25333
            if (!index)
25334
                return null;
25335
            let next = this.ranges[--index];
25336
            pos -= range.from - next.to;
25337
            range = next;
25338
        }
25339
        while (assoc < 0 ? pos > range.to : pos >= range.to) {
25340
            if (index == this.ranges.length - 1)
25341
                return null;
25342
            let next = this.ranges[++index];
25343
            pos += next.from - range.to;
25344
            range = next;
25345
        }
25346
        return pos;
25347
    }
25348
    /**
25349
    @internal
25350
    */
25351
    clipPos(pos) {
25352
        if (pos >= this.range.from && pos < this.range.to)
25353
            return pos;
25354
        for (let range of this.ranges)
25355
            if (range.to > pos)
25356
                return Math.max(pos, range.from);
25357
        return this.end;
25358
    }
25359
    /**
25360
    Look at a code unit near the stream position. `.peek(0)` equals
25361
    `.next`, `.peek(-1)` gives you the previous character, and so
25362
    on.
25363
 
25364
    Note that looking around during tokenizing creates dependencies
25365
    on potentially far-away content, which may reduce the
25366
    effectiveness incremental parsing—when looking forward—or even
25367
    cause invalid reparses when looking backward more than 25 code
25368
    units, since the library does not track lookbehind.
25369
    */
25370
    peek(offset) {
25371
        let idx = this.chunkOff + offset, pos, result;
25372
        if (idx >= 0 && idx < this.chunk.length) {
25373
            pos = this.pos + offset;
25374
            result = this.chunk.charCodeAt(idx);
25375
        }
25376
        else {
25377
            let resolved = this.resolveOffset(offset, 1);
25378
            if (resolved == null)
25379
                return -1;
25380
            pos = resolved;
25381
            if (pos >= this.chunk2Pos && pos < this.chunk2Pos + this.chunk2.length) {
25382
                result = this.chunk2.charCodeAt(pos - this.chunk2Pos);
25383
            }
25384
            else {
25385
                let i = this.rangeIndex, range = this.range;
25386
                while (range.to <= pos)
25387
                    range = this.ranges[++i];
25388
                this.chunk2 = this.input.chunk(this.chunk2Pos = pos);
25389
                if (pos + this.chunk2.length > range.to)
25390
                    this.chunk2 = this.chunk2.slice(0, range.to - pos);
25391
                result = this.chunk2.charCodeAt(0);
25392
            }
25393
        }
25394
        if (pos >= this.token.lookAhead)
25395
            this.token.lookAhead = pos + 1;
25396
        return result;
25397
    }
25398
    /**
25399
    Accept a token. By default, the end of the token is set to the
25400
    current stream position, but you can pass an offset (relative to
25401
    the stream position) to change that.
25402
    */
25403
    acceptToken(token, endOffset = 0) {
25404
        let end = endOffset ? this.resolveOffset(endOffset, -1) : this.pos;
25405
        if (end == null || end < this.token.start)
25406
            throw new RangeError("Token end out of bounds");
25407
        this.token.value = token;
25408
        this.token.end = end;
25409
    }
25410
    /**
25411
    Accept a token ending at a specific given position.
25412
    */
25413
    acceptTokenTo(token, endPos) {
25414
        this.token.value = token;
25415
        this.token.end = endPos;
25416
    }
25417
    getChunk() {
25418
        if (this.pos >= this.chunk2Pos && this.pos < this.chunk2Pos + this.chunk2.length) {
25419
            let { chunk, chunkPos } = this;
25420
            this.chunk = this.chunk2;
25421
            this.chunkPos = this.chunk2Pos;
25422
            this.chunk2 = chunk;
25423
            this.chunk2Pos = chunkPos;
25424
            this.chunkOff = this.pos - this.chunkPos;
25425
        }
25426
        else {
25427
            this.chunk2 = this.chunk;
25428
            this.chunk2Pos = this.chunkPos;
25429
            let nextChunk = this.input.chunk(this.pos);
25430
            let end = this.pos + nextChunk.length;
25431
            this.chunk = end > this.range.to ? nextChunk.slice(0, this.range.to - this.pos) : nextChunk;
25432
            this.chunkPos = this.pos;
25433
            this.chunkOff = 0;
25434
        }
25435
    }
25436
    readNext() {
25437
        if (this.chunkOff >= this.chunk.length) {
25438
            this.getChunk();
25439
            if (this.chunkOff == this.chunk.length)
25440
                return this.next = -1;
25441
        }
25442
        return this.next = this.chunk.charCodeAt(this.chunkOff);
25443
    }
25444
    /**
25445
    Move the stream forward N (defaults to 1) code units. Returns
25446
    the new value of [`next`](#lr.InputStream.next).
25447
    */
25448
    advance(n = 1) {
25449
        this.chunkOff += n;
25450
        while (this.pos + n >= this.range.to) {
25451
            if (this.rangeIndex == this.ranges.length - 1)
25452
                return this.setDone();
25453
            n -= this.range.to - this.pos;
25454
            this.range = this.ranges[++this.rangeIndex];
25455
            this.pos = this.range.from;
25456
        }
25457
        this.pos += n;
25458
        if (this.pos >= this.token.lookAhead)
25459
            this.token.lookAhead = this.pos + 1;
25460
        return this.readNext();
25461
    }
25462
    setDone() {
25463
        this.pos = this.chunkPos = this.end;
25464
        this.range = this.ranges[this.rangeIndex = this.ranges.length - 1];
25465
        this.chunk = "";
25466
        return this.next = -1;
25467
    }
25468
    /**
25469
    @internal
25470
    */
25471
    reset(pos, token) {
25472
        if (token) {
25473
            this.token = token;
25474
            token.start = pos;
25475
            token.lookAhead = pos + 1;
25476
            token.value = token.extended = -1;
25477
        }
25478
        else {
25479
            this.token = nullToken;
25480
        }
25481
        if (this.pos != pos) {
25482
            this.pos = pos;
25483
            if (pos == this.end) {
25484
                this.setDone();
25485
                return this;
25486
            }
25487
            while (pos < this.range.from)
25488
                this.range = this.ranges[--this.rangeIndex];
25489
            while (pos >= this.range.to)
25490
                this.range = this.ranges[++this.rangeIndex];
25491
            if (pos >= this.chunkPos && pos < this.chunkPos + this.chunk.length) {
25492
                this.chunkOff = pos - this.chunkPos;
25493
            }
25494
            else {
25495
                this.chunk = "";
25496
                this.chunkOff = 0;
25497
            }
25498
            this.readNext();
25499
        }
25500
        return this;
25501
    }
25502
    /**
25503
    @internal
25504
    */
25505
    read(from, to) {
25506
        if (from >= this.chunkPos && to <= this.chunkPos + this.chunk.length)
25507
            return this.chunk.slice(from - this.chunkPos, to - this.chunkPos);
25508
        if (from >= this.chunk2Pos && to <= this.chunk2Pos + this.chunk2.length)
25509
            return this.chunk2.slice(from - this.chunk2Pos, to - this.chunk2Pos);
25510
        if (from >= this.range.from && to <= this.range.to)
25511
            return this.input.read(from, to);
25512
        let result = "";
25513
        for (let r of this.ranges) {
25514
            if (r.from >= to)
25515
                break;
25516
            if (r.to > from)
25517
                result += this.input.read(Math.max(r.from, from), Math.min(r.to, to));
25518
        }
25519
        return result;
25520
    }
25521
}
25522
/**
25523
@internal
25524
*/
25525
class TokenGroup {
25526
    constructor(data, id) {
25527
        this.data = data;
25528
        this.id = id;
25529
    }
25530
    token(input, stack) {
25531
        let { parser } = stack.p;
25532
        readToken(this.data, input, stack, this.id, parser.data, parser.tokenPrecTable);
25533
    }
25534
}
25535
TokenGroup.prototype.contextual = TokenGroup.prototype.fallback = TokenGroup.prototype.extend = false;
25536
/**
25537
@hide
25538
*/
25539
class LocalTokenGroup {
25540
    constructor(data, precTable, elseToken) {
25541
        this.precTable = precTable;
25542
        this.elseToken = elseToken;
25543
        this.data = typeof data == "string" ? decodeArray(data) : data;
25544
    }
25545
    token(input, stack) {
25546
        let start = input.pos, skipped = 0;
25547
        for (;;) {
25548
            let atEof = input.next < 0, nextPos = input.resolveOffset(1, 1);
25549
            readToken(this.data, input, stack, 0, this.data, this.precTable);
25550
            if (input.token.value > -1)
25551
                break;
25552
            if (this.elseToken == null)
25553
                return;
25554
            if (!atEof)
25555
                skipped++;
25556
            if (nextPos == null)
25557
                break;
25558
            input.reset(nextPos, input.token);
25559
        }
25560
        if (skipped) {
25561
            input.reset(start, input.token);
25562
            input.acceptToken(this.elseToken, skipped);
25563
        }
25564
    }
25565
}
25566
LocalTokenGroup.prototype.contextual = TokenGroup.prototype.fallback = TokenGroup.prototype.extend = false;
25567
/**
25568
`@external tokens` declarations in the grammar should resolve to
25569
an instance of this class.
25570
*/
25571
class ExternalTokenizer {
25572
    /**
25573
    Create a tokenizer. The first argument is the function that,
25574
    given an input stream, scans for the types of tokens it
25575
    recognizes at the stream's position, and calls
25576
    [`acceptToken`](#lr.InputStream.acceptToken) when it finds
25577
    one.
25578
    */
25579
    constructor(
25580
    /**
25581
    @internal
25582
    */
25583
    token, options = {}) {
25584
        this.token = token;
25585
        this.contextual = !!options.contextual;
25586
        this.fallback = !!options.fallback;
25587
        this.extend = !!options.extend;
25588
    }
25589
}
25590
// Tokenizer data is stored a big uint16 array containing, for each
25591
// state:
25592
//
25593
//  - A group bitmask, indicating what token groups are reachable from
25594
//    this state, so that paths that can only lead to tokens not in
25595
//    any of the current groups can be cut off early.
25596
//
25597
//  - The position of the end of the state's sequence of accepting
25598
//    tokens
25599
//
25600
//  - The number of outgoing edges for the state
25601
//
25602
//  - The accepting tokens, as (token id, group mask) pairs
25603
//
25604
//  - The outgoing edges, as (start character, end character, state
25605
//    index) triples, with end character being exclusive
25606
//
25607
// This function interprets that data, running through a stream as
25608
// long as new states with the a matching group mask can be reached,
25609
// and updating `input.token` when it matches a token.
25610
function readToken(data, input, stack, group, precTable, precOffset) {
25611
    let state = 0, groupMask = 1 << group, { dialect } = stack.p.parser;
25612
    scan: for (;;) {
25613
        if ((groupMask & data[state]) == 0)
25614
            break;
25615
        let accEnd = data[state + 1];
25616
        // Check whether this state can lead to a token in the current group
25617
        // Accept tokens in this state, possibly overwriting
25618
        // lower-precedence / shorter tokens
25619
        for (let i = state + 3; i < accEnd; i += 2)
25620
            if ((data[i + 1] & groupMask) > 0) {
25621
                let term = data[i];
25622
                if (dialect.allows(term) &&
25623
                    (input.token.value == -1 || input.token.value == term ||
25624
                        overrides(term, input.token.value, precTable, precOffset))) {
25625
                    input.acceptToken(term);
25626
                    break;
25627
                }
25628
            }
25629
        let next = input.next, low = 0, high = data[state + 2];
25630
        // Special case for EOF
25631
        if (input.next < 0 && high > low && data[accEnd + high * 3 - 3] == 65535 /* Seq.End */) {
25632
            state = data[accEnd + high * 3 - 1];
25633
            continue scan;
25634
        }
25635
        // Do a binary search on the state's edges
25636
        for (; low < high;) {
25637
            let mid = (low + high) >> 1;
25638
            let index = accEnd + mid + (mid << 1);
25639
            let from = data[index], to = data[index + 1] || 0x10000;
25640
            if (next < from)
25641
                high = mid;
25642
            else if (next >= to)
25643
                low = mid + 1;
25644
            else {
25645
                state = data[index + 2];
25646
                input.advance();
25647
                continue scan;
25648
            }
25649
        }
25650
        break;
25651
    }
25652
}
25653
function findOffset(data, start, term) {
25654
    for (let i = start, next; (next = data[i]) != 65535 /* Seq.End */; i++)
25655
        if (next == term)
25656
            return i - start;
25657
    return -1;
25658
}
25659
function overrides(token, prev, tableData, tableOffset) {
25660
    let iPrev = findOffset(tableData, tableOffset, prev);
25661
    return iPrev < 0 || findOffset(tableData, tableOffset, token) < iPrev;
25662
}
25663
 
25664
// Environment variable used to control console output
25665
const verbose = typeof process != "undefined" && process.env && /\bparse\b/.test(process.env.LOG);
25666
let stackIDs = null;
25667
function cutAt(tree, pos, side) {
25668
    let cursor = tree.cursor(IterMode.IncludeAnonymous);
25669
    cursor.moveTo(pos);
25670
    for (;;) {
25671
        if (!(side < 0 ? cursor.childBefore(pos) : cursor.childAfter(pos)))
25672
            for (;;) {
25673
                if ((side < 0 ? cursor.to < pos : cursor.from > pos) && !cursor.type.isError)
25674
                    return side < 0 ? Math.max(0, Math.min(cursor.to - 1, pos - 25 /* Safety.Margin */))
25675
                        : Math.min(tree.length, Math.max(cursor.from + 1, pos + 25 /* Safety.Margin */));
25676
                if (side < 0 ? cursor.prevSibling() : cursor.nextSibling())
25677
                    break;
25678
                if (!cursor.parent())
25679
                    return side < 0 ? 0 : tree.length;
25680
            }
25681
    }
25682
}
25683
class FragmentCursor {
25684
    constructor(fragments, nodeSet) {
25685
        this.fragments = fragments;
25686
        this.nodeSet = nodeSet;
25687
        this.i = 0;
25688
        this.fragment = null;
25689
        this.safeFrom = -1;
25690
        this.safeTo = -1;
25691
        this.trees = [];
25692
        this.start = [];
25693
        this.index = [];
25694
        this.nextFragment();
25695
    }
25696
    nextFragment() {
25697
        let fr = this.fragment = this.i == this.fragments.length ? null : this.fragments[this.i++];
25698
        if (fr) {
25699
            this.safeFrom = fr.openStart ? cutAt(fr.tree, fr.from + fr.offset, 1) - fr.offset : fr.from;
25700
            this.safeTo = fr.openEnd ? cutAt(fr.tree, fr.to + fr.offset, -1) - fr.offset : fr.to;
25701
            while (this.trees.length) {
25702
                this.trees.pop();
25703
                this.start.pop();
25704
                this.index.pop();
25705
            }
25706
            this.trees.push(fr.tree);
25707
            this.start.push(-fr.offset);
25708
            this.index.push(0);
25709
            this.nextStart = this.safeFrom;
25710
        }
25711
        else {
25712
            this.nextStart = 1e9;
25713
        }
25714
    }
25715
    // `pos` must be >= any previously given `pos` for this cursor
25716
    nodeAt(pos) {
25717
        if (pos < this.nextStart)
25718
            return null;
25719
        while (this.fragment && this.safeTo <= pos)
25720
            this.nextFragment();
25721
        if (!this.fragment)
25722
            return null;
25723
        for (;;) {
25724
            let last = this.trees.length - 1;
25725
            if (last < 0) { // End of tree
25726
                this.nextFragment();
25727
                return null;
25728
            }
25729
            let top = this.trees[last], index = this.index[last];
25730
            if (index == top.children.length) {
25731
                this.trees.pop();
25732
                this.start.pop();
25733
                this.index.pop();
25734
                continue;
25735
            }
25736
            let next = top.children[index];
25737
            let start = this.start[last] + top.positions[index];
25738
            if (start > pos) {
25739
                this.nextStart = start;
25740
                return null;
25741
            }
25742
            if (next instanceof Tree) {
25743
                if (start == pos) {
25744
                    if (start < this.safeFrom)
25745
                        return null;
25746
                    let end = start + next.length;
25747
                    if (end <= this.safeTo) {
25748
                        let lookAhead = next.prop(NodeProp.lookAhead);
25749
                        if (!lookAhead || end + lookAhead < this.fragment.to)
25750
                            return next;
25751
                    }
25752
                }
25753
                this.index[last]++;
25754
                if (start + next.length >= Math.max(this.safeFrom, pos)) { // Enter this node
25755
                    this.trees.push(next);
25756
                    this.start.push(start);
25757
                    this.index.push(0);
25758
                }
25759
            }
25760
            else {
25761
                this.index[last]++;
25762
                this.nextStart = start + next.length;
25763
            }
25764
        }
25765
    }
25766
}
25767
class TokenCache {
25768
    constructor(parser, stream) {
25769
        this.stream = stream;
25770
        this.tokens = [];
25771
        this.mainToken = null;
25772
        this.actions = [];
25773
        this.tokens = parser.tokenizers.map(_ => new CachedToken);
25774
    }
25775
    getActions(stack) {
25776
        let actionIndex = 0;
25777
        let main = null;
25778
        let { parser } = stack.p, { tokenizers } = parser;
25779
        let mask = parser.stateSlot(stack.state, 3 /* ParseState.TokenizerMask */);
25780
        let context = stack.curContext ? stack.curContext.hash : 0;
25781
        let lookAhead = 0;
25782
        for (let i = 0; i < tokenizers.length; i++) {
25783
            if (((1 << i) & mask) == 0)
25784
                continue;
25785
            let tokenizer = tokenizers[i], token = this.tokens[i];
25786
            if (main && !tokenizer.fallback)
25787
                continue;
25788
            if (tokenizer.contextual || token.start != stack.pos || token.mask != mask || token.context != context) {
25789
                this.updateCachedToken(token, tokenizer, stack);
25790
                token.mask = mask;
25791
                token.context = context;
25792
            }
25793
            if (token.lookAhead > token.end + 25 /* Safety.Margin */)
25794
                lookAhead = Math.max(token.lookAhead, lookAhead);
25795
            if (token.value != 0 /* Term.Err */) {
25796
                let startIndex = actionIndex;
25797
                if (token.extended > -1)
25798
                    actionIndex = this.addActions(stack, token.extended, token.end, actionIndex);
25799
                actionIndex = this.addActions(stack, token.value, token.end, actionIndex);
25800
                if (!tokenizer.extend) {
25801
                    main = token;
25802
                    if (actionIndex > startIndex)
25803
                        break;
25804
                }
25805
            }
25806
        }
25807
        while (this.actions.length > actionIndex)
25808
            this.actions.pop();
25809
        if (lookAhead)
25810
            stack.setLookAhead(lookAhead);
25811
        if (!main && stack.pos == this.stream.end) {
25812
            main = new CachedToken;
25813
            main.value = stack.p.parser.eofTerm;
25814
            main.start = main.end = stack.pos;
25815
            actionIndex = this.addActions(stack, main.value, main.end, actionIndex);
25816
        }
25817
        this.mainToken = main;
25818
        return this.actions;
25819
    }
25820
    getMainToken(stack) {
25821
        if (this.mainToken)
25822
            return this.mainToken;
25823
        let main = new CachedToken, { pos, p } = stack;
25824
        main.start = pos;
25825
        main.end = Math.min(pos + 1, p.stream.end);
25826
        main.value = pos == p.stream.end ? p.parser.eofTerm : 0 /* Term.Err */;
25827
        return main;
25828
    }
25829
    updateCachedToken(token, tokenizer, stack) {
25830
        let start = this.stream.clipPos(stack.pos);
25831
        tokenizer.token(this.stream.reset(start, token), stack);
25832
        if (token.value > -1) {
25833
            let { parser } = stack.p;
25834
            for (let i = 0; i < parser.specialized.length; i++)
25835
                if (parser.specialized[i] == token.value) {
25836
                    let result = parser.specializers[i](this.stream.read(token.start, token.end), stack);
25837
                    if (result >= 0 && stack.p.parser.dialect.allows(result >> 1)) {
25838
                        if ((result & 1) == 0 /* Specialize.Specialize */)
25839
                            token.value = result >> 1;
25840
                        else
25841
                            token.extended = result >> 1;
25842
                        break;
25843
                    }
25844
                }
25845
        }
25846
        else {
25847
            token.value = 0 /* Term.Err */;
25848
            token.end = this.stream.clipPos(start + 1);
25849
        }
25850
    }
25851
    putAction(action, token, end, index) {
25852
        // Don't add duplicate actions
25853
        for (let i = 0; i < index; i += 3)
25854
            if (this.actions[i] == action)
25855
                return index;
25856
        this.actions[index++] = action;
25857
        this.actions[index++] = token;
25858
        this.actions[index++] = end;
25859
        return index;
25860
    }
25861
    addActions(stack, token, end, index) {
25862
        let { state } = stack, { parser } = stack.p, { data } = parser;
25863
        for (let set = 0; set < 2; set++) {
25864
            for (let i = parser.stateSlot(state, set ? 2 /* ParseState.Skip */ : 1 /* ParseState.Actions */);; i += 3) {
25865
                if (data[i] == 65535 /* Seq.End */) {
25866
                    if (data[i + 1] == 1 /* Seq.Next */) {
25867
                        i = pair(data, i + 2);
25868
                    }
25869
                    else {
25870
                        if (index == 0 && data[i + 1] == 2 /* Seq.Other */)
25871
                            index = this.putAction(pair(data, i + 2), token, end, index);
25872
                        break;
25873
                    }
25874
                }
25875
                if (data[i] == token)
25876
                    index = this.putAction(pair(data, i + 1), token, end, index);
25877
            }
25878
        }
25879
        return index;
25880
    }
25881
}
25882
class Parse {
25883
    constructor(parser, input, fragments, ranges) {
25884
        this.parser = parser;
25885
        this.input = input;
25886
        this.ranges = ranges;
25887
        this.recovering = 0;
25888
        this.nextStackID = 0x2654; // ♔, ♕, ♖, ♗, ♘, ♙, ♠, ♡, ♢, ♣, ♤, ♥, ♦, ♧
25889
        this.minStackPos = 0;
25890
        this.reused = [];
25891
        this.stoppedAt = null;
25892
        this.lastBigReductionStart = -1;
25893
        this.lastBigReductionSize = 0;
25894
        this.bigReductionCount = 0;
25895
        this.stream = new InputStream(input, ranges);
25896
        this.tokens = new TokenCache(parser, this.stream);
25897
        this.topTerm = parser.top[1];
25898
        let { from } = ranges[0];
25899
        this.stacks = [Stack.start(this, parser.top[0], from)];
25900
        this.fragments = fragments.length && this.stream.end - from > parser.bufferLength * 4
25901
            ? new FragmentCursor(fragments, parser.nodeSet) : null;
25902
    }
25903
    get parsedPos() {
25904
        return this.minStackPos;
25905
    }
25906
    // Move the parser forward. This will process all parse stacks at
25907
    // `this.pos` and try to advance them to a further position. If no
25908
    // stack for such a position is found, it'll start error-recovery.
25909
    //
25910
    // When the parse is finished, this will return a syntax tree. When
25911
    // not, it returns `null`.
25912
    advance() {
25913
        let stacks = this.stacks, pos = this.minStackPos;
25914
        // This will hold stacks beyond `pos`.
25915
        let newStacks = this.stacks = [];
25916
        let stopped, stoppedTokens;
25917
        // If a large amount of reductions happened with the same start
25918
        // position, force the stack out of that production in order to
25919
        // avoid creating a tree too deep to recurse through.
25920
        // (This is an ugly kludge, because unfortunately there is no
25921
        // straightforward, cheap way to check for this happening, due to
25922
        // the history of reductions only being available in an
25923
        // expensive-to-access format in the stack buffers.)
25924
        if (this.bigReductionCount > 300 /* Rec.MaxLeftAssociativeReductionCount */ && stacks.length == 1) {
25925
            let [s] = stacks;
25926
            while (s.forceReduce() && s.stack.length && s.stack[s.stack.length - 2] >= this.lastBigReductionStart) { }
25927
            this.bigReductionCount = this.lastBigReductionSize = 0;
25928
        }
25929
        // Keep advancing any stacks at `pos` until they either move
25930
        // forward or can't be advanced. Gather stacks that can't be
25931
        // advanced further in `stopped`.
25932
        for (let i = 0; i < stacks.length; i++) {
25933
            let stack = stacks[i];
25934
            for (;;) {
25935
                this.tokens.mainToken = null;
25936
                if (stack.pos > pos) {
25937
                    newStacks.push(stack);
25938
                }
25939
                else if (this.advanceStack(stack, newStacks, stacks)) {
25940
                    continue;
25941
                }
25942
                else {
25943
                    if (!stopped) {
25944
                        stopped = [];
25945
                        stoppedTokens = [];
25946
                    }
25947
                    stopped.push(stack);
25948
                    let tok = this.tokens.getMainToken(stack);
25949
                    stoppedTokens.push(tok.value, tok.end);
25950
                }
25951
                break;
25952
            }
25953
        }
25954
        if (!newStacks.length) {
25955
            let finished = stopped && findFinished(stopped);
25956
            if (finished) {
25957
                if (verbose)
25958
                    console.log("Finish with " + this.stackID(finished));
25959
                return this.stackToTree(finished);
25960
            }
25961
            if (this.parser.strict) {
25962
                if (verbose && stopped)
25963
                    console.log("Stuck with token " + (this.tokens.mainToken ? this.parser.getName(this.tokens.mainToken.value) : "none"));
25964
                throw new SyntaxError("No parse at " + pos);
25965
            }
25966
            if (!this.recovering)
25967
                this.recovering = 5 /* Rec.Distance */;
25968
        }
25969
        if (this.recovering && stopped) {
25970
            let finished = this.stoppedAt != null && stopped[0].pos > this.stoppedAt ? stopped[0]
25971
                : this.runRecovery(stopped, stoppedTokens, newStacks);
25972
            if (finished) {
25973
                if (verbose)
25974
                    console.log("Force-finish " + this.stackID(finished));
25975
                return this.stackToTree(finished.forceAll());
25976
            }
25977
        }
25978
        if (this.recovering) {
25979
            let maxRemaining = this.recovering == 1 ? 1 : this.recovering * 3 /* Rec.MaxRemainingPerStep */;
25980
            if (newStacks.length > maxRemaining) {
25981
                newStacks.sort((a, b) => b.score - a.score);
25982
                while (newStacks.length > maxRemaining)
25983
                    newStacks.pop();
25984
            }
25985
            if (newStacks.some(s => s.reducePos > pos))
25986
                this.recovering--;
25987
        }
25988
        else if (newStacks.length > 1) {
25989
            // Prune stacks that are in the same state, or that have been
25990
            // running without splitting for a while, to avoid getting stuck
25991
            // with multiple successful stacks running endlessly on.
25992
            outer: for (let i = 0; i < newStacks.length - 1; i++) {
25993
                let stack = newStacks[i];
25994
                for (let j = i + 1; j < newStacks.length; j++) {
25995
                    let other = newStacks[j];
25996
                    if (stack.sameState(other) ||
25997
                        stack.buffer.length > 500 /* Rec.MinBufferLengthPrune */ && other.buffer.length > 500 /* Rec.MinBufferLengthPrune */) {
25998
                        if (((stack.score - other.score) || (stack.buffer.length - other.buffer.length)) > 0) {
25999
                            newStacks.splice(j--, 1);
26000
                        }
26001
                        else {
26002
                            newStacks.splice(i--, 1);
26003
                            continue outer;
26004
                        }
26005
                    }
26006
                }
26007
            }
26008
            if (newStacks.length > 12 /* Rec.MaxStackCount */)
26009
                newStacks.splice(12 /* Rec.MaxStackCount */, newStacks.length - 12 /* Rec.MaxStackCount */);
26010
        }
26011
        this.minStackPos = newStacks[0].pos;
26012
        for (let i = 1; i < newStacks.length; i++)
26013
            if (newStacks[i].pos < this.minStackPos)
26014
                this.minStackPos = newStacks[i].pos;
26015
        return null;
26016
    }
26017
    stopAt(pos) {
26018
        if (this.stoppedAt != null && this.stoppedAt < pos)
26019
            throw new RangeError("Can't move stoppedAt forward");
26020
        this.stoppedAt = pos;
26021
    }
26022
    // Returns an updated version of the given stack, or null if the
26023
    // stack can't advance normally. When `split` and `stacks` are
26024
    // given, stacks split off by ambiguous operations will be pushed to
26025
    // `split`, or added to `stacks` if they move `pos` forward.
26026
    advanceStack(stack, stacks, split) {
26027
        let start = stack.pos, { parser } = this;
26028
        let base = verbose ? this.stackID(stack) + " -> " : "";
26029
        if (this.stoppedAt != null && start > this.stoppedAt)
26030
            return stack.forceReduce() ? stack : null;
26031
        if (this.fragments) {
26032
            let strictCx = stack.curContext && stack.curContext.tracker.strict, cxHash = strictCx ? stack.curContext.hash : 0;
26033
            for (let cached = this.fragments.nodeAt(start); cached;) {
26034
                let match = this.parser.nodeSet.types[cached.type.id] == cached.type ? parser.getGoto(stack.state, cached.type.id) : -1;
26035
                if (match > -1 && cached.length && (!strictCx || (cached.prop(NodeProp.contextHash) || 0) == cxHash)) {
26036
                    stack.useNode(cached, match);
26037
                    if (verbose)
26038
                        console.log(base + this.stackID(stack) + ` (via reuse of ${parser.getName(cached.type.id)})`);
26039
                    return true;
26040
                }
26041
                if (!(cached instanceof Tree) || cached.children.length == 0 || cached.positions[0] > 0)
26042
                    break;
26043
                let inner = cached.children[0];
26044
                if (inner instanceof Tree && cached.positions[0] == 0)
26045
                    cached = inner;
26046
                else
26047
                    break;
26048
            }
26049
        }
26050
        let defaultReduce = parser.stateSlot(stack.state, 4 /* ParseState.DefaultReduce */);
26051
        if (defaultReduce > 0) {
26052
            stack.reduce(defaultReduce);
26053
            if (verbose)
26054
                console.log(base + this.stackID(stack) + ` (via always-reduce ${parser.getName(defaultReduce & 65535 /* Action.ValueMask */)})`);
26055
            return true;
26056
        }
26057
        if (stack.stack.length >= 8400 /* Rec.CutDepth */) {
26058
            while (stack.stack.length > 6000 /* Rec.CutTo */ && stack.forceReduce()) { }
26059
        }
26060
        let actions = this.tokens.getActions(stack);
26061
        for (let i = 0; i < actions.length;) {
26062
            let action = actions[i++], term = actions[i++], end = actions[i++];
26063
            let last = i == actions.length || !split;
26064
            let localStack = last ? stack : stack.split();
26065
            let main = this.tokens.mainToken;
26066
            localStack.apply(action, term, main ? main.start : localStack.pos, end);
26067
            if (verbose)
26068
                console.log(base + this.stackID(localStack) + ` (via ${(action & 65536 /* Action.ReduceFlag */) == 0 ? "shift"
26069
                    : `reduce of ${parser.getName(action & 65535 /* Action.ValueMask */)}`} for ${parser.getName(term)} @ ${start}${localStack == stack ? "" : ", split"})`);
26070
            if (last)
26071
                return true;
26072
            else if (localStack.pos > start)
26073
                stacks.push(localStack);
26074
            else
26075
                split.push(localStack);
26076
        }
26077
        return false;
26078
    }
26079
    // Advance a given stack forward as far as it will go. Returns the
26080
    // (possibly updated) stack if it got stuck, or null if it moved
26081
    // forward and was given to `pushStackDedup`.
26082
    advanceFully(stack, newStacks) {
26083
        let pos = stack.pos;
26084
        for (;;) {
26085
            if (!this.advanceStack(stack, null, null))
26086
                return false;
26087
            if (stack.pos > pos) {
26088
                pushStackDedup(stack, newStacks);
26089
                return true;
26090
            }
26091
        }
26092
    }
26093
    runRecovery(stacks, tokens, newStacks) {
26094
        let finished = null, restarted = false;
26095
        for (let i = 0; i < stacks.length; i++) {
26096
            let stack = stacks[i], token = tokens[i << 1], tokenEnd = tokens[(i << 1) + 1];
26097
            let base = verbose ? this.stackID(stack) + " -> " : "";
26098
            if (stack.deadEnd) {
26099
                if (restarted)
26100
                    continue;
26101
                restarted = true;
26102
                stack.restart();
26103
                if (verbose)
26104
                    console.log(base + this.stackID(stack) + " (restarted)");
26105
                let done = this.advanceFully(stack, newStacks);
26106
                if (done)
26107
                    continue;
26108
            }
26109
            let force = stack.split(), forceBase = base;
26110
            for (let j = 0; force.forceReduce() && j < 10 /* Rec.ForceReduceLimit */; j++) {
26111
                if (verbose)
26112
                    console.log(forceBase + this.stackID(force) + " (via force-reduce)");
26113
                let done = this.advanceFully(force, newStacks);
26114
                if (done)
26115
                    break;
26116
                if (verbose)
26117
                    forceBase = this.stackID(force) + " -> ";
26118
            }
26119
            for (let insert of stack.recoverByInsert(token)) {
26120
                if (verbose)
26121
                    console.log(base + this.stackID(insert) + " (via recover-insert)");
26122
                this.advanceFully(insert, newStacks);
26123
            }
26124
            if (this.stream.end > stack.pos) {
26125
                if (tokenEnd == stack.pos) {
26126
                    tokenEnd++;
26127
                    token = 0 /* Term.Err */;
26128
                }
26129
                stack.recoverByDelete(token, tokenEnd);
26130
                if (verbose)
26131
                    console.log(base + this.stackID(stack) + ` (via recover-delete ${this.parser.getName(token)})`);
26132
                pushStackDedup(stack, newStacks);
26133
            }
26134
            else if (!finished || finished.score < stack.score) {
26135
                finished = stack;
26136
            }
26137
        }
26138
        return finished;
26139
    }
26140
    // Convert the stack's buffer to a syntax tree.
26141
    stackToTree(stack) {
26142
        stack.close();
26143
        return Tree.build({ buffer: StackBufferCursor.create(stack),
26144
            nodeSet: this.parser.nodeSet,
26145
            topID: this.topTerm,
26146
            maxBufferLength: this.parser.bufferLength,
26147
            reused: this.reused,
26148
            start: this.ranges[0].from,
26149
            length: stack.pos - this.ranges[0].from,
26150
            minRepeatType: this.parser.minRepeatTerm });
26151
    }
26152
    stackID(stack) {
26153
        let id = (stackIDs || (stackIDs = new WeakMap)).get(stack);
26154
        if (!id)
26155
            stackIDs.set(stack, id = String.fromCodePoint(this.nextStackID++));
26156
        return id + stack;
26157
    }
26158
}
26159
function pushStackDedup(stack, newStacks) {
26160
    for (let i = 0; i < newStacks.length; i++) {
26161
        let other = newStacks[i];
26162
        if (other.pos == stack.pos && other.sameState(stack)) {
26163
            if (newStacks[i].score < stack.score)
26164
                newStacks[i] = stack;
26165
            return;
26166
        }
26167
    }
26168
    newStacks.push(stack);
26169
}
26170
class Dialect {
26171
    constructor(source, flags, disabled) {
26172
        this.source = source;
26173
        this.flags = flags;
26174
        this.disabled = disabled;
26175
    }
26176
    allows(term) { return !this.disabled || this.disabled[term] == 0; }
26177
}
26178
const id = x => x;
26179
/**
26180
Context trackers are used to track stateful context (such as
26181
indentation in the Python grammar, or parent elements in the XML
26182
grammar) needed by external tokenizers. You declare them in a
26183
grammar file as `@context exportName from "module"`.
26184
 
26185
Context values should be immutable, and can be updated (replaced)
26186
on shift or reduce actions.
26187
 
26188
The export used in a `@context` declaration should be of this
26189
type.
26190
*/
26191
class ContextTracker {
26192
    /**
26193
    Define a context tracker.
26194
    */
26195
    constructor(spec) {
26196
        this.start = spec.start;
26197
        this.shift = spec.shift || id;
26198
        this.reduce = spec.reduce || id;
26199
        this.reuse = spec.reuse || id;
26200
        this.hash = spec.hash || (() => 0);
26201
        this.strict = spec.strict !== false;
26202
    }
26203
}
26204
/**
26205
Holds the parse tables for a given grammar, as generated by
26206
`lezer-generator`, and provides [methods](#common.Parser) to parse
26207
content with.
26208
*/
26209
class LRParser extends Parser {
26210
    /**
26211
    @internal
26212
    */
26213
    constructor(spec) {
26214
        super();
26215
        /**
26216
        @internal
26217
        */
26218
        this.wrappers = [];
26219
        if (spec.version != 14 /* File.Version */)
26220
            throw new RangeError(`Parser version (${spec.version}) doesn't match runtime version (${14 /* File.Version */})`);
26221
        let nodeNames = spec.nodeNames.split(" ");
26222
        this.minRepeatTerm = nodeNames.length;
26223
        for (let i = 0; i < spec.repeatNodeCount; i++)
26224
            nodeNames.push("");
26225
        let topTerms = Object.keys(spec.topRules).map(r => spec.topRules[r][1]);
26226
        let nodeProps = [];
26227
        for (let i = 0; i < nodeNames.length; i++)
26228
            nodeProps.push([]);
26229
        function setProp(nodeID, prop, value) {
26230
            nodeProps[nodeID].push([prop, prop.deserialize(String(value))]);
26231
        }
26232
        if (spec.nodeProps)
26233
            for (let propSpec of spec.nodeProps) {
26234
                let prop = propSpec[0];
26235
                if (typeof prop == "string")
26236
                    prop = NodeProp[prop];
26237
                for (let i = 1; i < propSpec.length;) {
26238
                    let next = propSpec[i++];
26239
                    if (next >= 0) {
26240
                        setProp(next, prop, propSpec[i++]);
26241
                    }
26242
                    else {
26243
                        let value = propSpec[i + -next];
26244
                        for (let j = -next; j > 0; j--)
26245
                            setProp(propSpec[i++], prop, value);
26246
                        i++;
26247
                    }
26248
                }
26249
            }
26250
        this.nodeSet = new NodeSet(nodeNames.map((name, i) => NodeType.define({
26251
            name: i >= this.minRepeatTerm ? undefined : name,
26252
            id: i,
26253
            props: nodeProps[i],
26254
            top: topTerms.indexOf(i) > -1,
26255
            error: i == 0,
26256
            skipped: spec.skippedNodes && spec.skippedNodes.indexOf(i) > -1
26257
        })));
26258
        if (spec.propSources)
26259
            this.nodeSet = this.nodeSet.extend(...spec.propSources);
26260
        this.strict = false;
26261
        this.bufferLength = DefaultBufferLength;
26262
        let tokenArray = decodeArray(spec.tokenData);
26263
        this.context = spec.context;
26264
        this.specializerSpecs = spec.specialized || [];
26265
        this.specialized = new Uint16Array(this.specializerSpecs.length);
26266
        for (let i = 0; i < this.specializerSpecs.length; i++)
26267
            this.specialized[i] = this.specializerSpecs[i].term;
26268
        this.specializers = this.specializerSpecs.map(getSpecializer);
26269
        this.states = decodeArray(spec.states, Uint32Array);
26270
        this.data = decodeArray(spec.stateData);
26271
        this.goto = decodeArray(spec.goto);
26272
        this.maxTerm = spec.maxTerm;
26273
        this.tokenizers = spec.tokenizers.map(value => typeof value == "number" ? new TokenGroup(tokenArray, value) : value);
26274
        this.topRules = spec.topRules;
26275
        this.dialects = spec.dialects || {};
26276
        this.dynamicPrecedences = spec.dynamicPrecedences || null;
26277
        this.tokenPrecTable = spec.tokenPrec;
26278
        this.termNames = spec.termNames || null;
26279
        this.maxNode = this.nodeSet.types.length - 1;
26280
        this.dialect = this.parseDialect();
26281
        this.top = this.topRules[Object.keys(this.topRules)[0]];
26282
    }
26283
    createParse(input, fragments, ranges) {
26284
        let parse = new Parse(this, input, fragments, ranges);
26285
        for (let w of this.wrappers)
26286
            parse = w(parse, input, fragments, ranges);
26287
        return parse;
26288
    }
26289
    /**
26290
    Get a goto table entry @internal
26291
    */
26292
    getGoto(state, term, loose = false) {
26293
        let table = this.goto;
26294
        if (term >= table[0])
26295
            return -1;
26296
        for (let pos = table[term + 1];;) {
26297
            let groupTag = table[pos++], last = groupTag & 1;
26298
            let target = table[pos++];
26299
            if (last && loose)
26300
                return target;
26301
            for (let end = pos + (groupTag >> 1); pos < end; pos++)
26302
                if (table[pos] == state)
26303
                    return target;
26304
            if (last)
26305
                return -1;
26306
        }
26307
    }
26308
    /**
26309
    Check if this state has an action for a given terminal @internal
26310
    */
26311
    hasAction(state, terminal) {
26312
        let data = this.data;
26313
        for (let set = 0; set < 2; set++) {
26314
            for (let i = this.stateSlot(state, set ? 2 /* ParseState.Skip */ : 1 /* ParseState.Actions */), next;; i += 3) {
26315
                if ((next = data[i]) == 65535 /* Seq.End */) {
26316
                    if (data[i + 1] == 1 /* Seq.Next */)
26317
                        next = data[i = pair(data, i + 2)];
26318
                    else if (data[i + 1] == 2 /* Seq.Other */)
26319
                        return pair(data, i + 2);
26320
                    else
26321
                        break;
26322
                }
26323
                if (next == terminal || next == 0 /* Term.Err */)
26324
                    return pair(data, i + 1);
26325
            }
26326
        }
26327
        return 0;
26328
    }
26329
    /**
26330
    @internal
26331
    */
26332
    stateSlot(state, slot) {
26333
        return this.states[(state * 6 /* ParseState.Size */) + slot];
26334
    }
26335
    /**
26336
    @internal
26337
    */
26338
    stateFlag(state, flag) {
26339
        return (this.stateSlot(state, 0 /* ParseState.Flags */) & flag) > 0;
26340
    }
26341
    /**
26342
    @internal
26343
    */
26344
    validAction(state, action) {
26345
        return !!this.allActions(state, a => a == action ? true : null);
26346
    }
26347
    /**
26348
    @internal
26349
    */
26350
    allActions(state, action) {
26351
        let deflt = this.stateSlot(state, 4 /* ParseState.DefaultReduce */);
26352
        let result = deflt ? action(deflt) : undefined;
26353
        for (let i = this.stateSlot(state, 1 /* ParseState.Actions */); result == null; i += 3) {
26354
            if (this.data[i] == 65535 /* Seq.End */) {
26355
                if (this.data[i + 1] == 1 /* Seq.Next */)
26356
                    i = pair(this.data, i + 2);
26357
                else
26358
                    break;
26359
            }
26360
            result = action(pair(this.data, i + 1));
26361
        }
26362
        return result;
26363
    }
26364
    /**
26365
    Get the states that can follow this one through shift actions or
26366
    goto jumps. @internal
26367
    */
26368
    nextStates(state) {
26369
        let result = [];
26370
        for (let i = this.stateSlot(state, 1 /* ParseState.Actions */);; i += 3) {
26371
            if (this.data[i] == 65535 /* Seq.End */) {
26372
                if (this.data[i + 1] == 1 /* Seq.Next */)
26373
                    i = pair(this.data, i + 2);
26374
                else
26375
                    break;
26376
            }
26377
            if ((this.data[i + 2] & (65536 /* Action.ReduceFlag */ >> 16)) == 0) {
26378
                let value = this.data[i + 1];
26379
                if (!result.some((v, i) => (i & 1) && v == value))
26380
                    result.push(this.data[i], value);
26381
            }
26382
        }
26383
        return result;
26384
    }
26385
    /**
26386
    Configure the parser. Returns a new parser instance that has the
26387
    given settings modified. Settings not provided in `config` are
26388
    kept from the original parser.
26389
    */
26390
    configure(config) {
26391
        // Hideous reflection-based kludge to make it easy to create a
26392
        // slightly modified copy of a parser.
26393
        let copy = Object.assign(Object.create(LRParser.prototype), this);
26394
        if (config.props)
26395
            copy.nodeSet = this.nodeSet.extend(...config.props);
26396
        if (config.top) {
26397
            let info = this.topRules[config.top];
26398
            if (!info)
26399
                throw new RangeError(`Invalid top rule name ${config.top}`);
26400
            copy.top = info;
26401
        }
26402
        if (config.tokenizers)
26403
            copy.tokenizers = this.tokenizers.map(t => {
26404
                let found = config.tokenizers.find(r => r.from == t);
26405
                return found ? found.to : t;
26406
            });
26407
        if (config.specializers) {
26408
            copy.specializers = this.specializers.slice();
26409
            copy.specializerSpecs = this.specializerSpecs.map((s, i) => {
26410
                let found = config.specializers.find(r => r.from == s.external);
26411
                if (!found)
26412
                    return s;
26413
                let spec = Object.assign(Object.assign({}, s), { external: found.to });
26414
                copy.specializers[i] = getSpecializer(spec);
26415
                return spec;
26416
            });
26417
        }
26418
        if (config.contextTracker)
26419
            copy.context = config.contextTracker;
26420
        if (config.dialect)
26421
            copy.dialect = this.parseDialect(config.dialect);
26422
        if (config.strict != null)
26423
            copy.strict = config.strict;
26424
        if (config.wrap)
26425
            copy.wrappers = copy.wrappers.concat(config.wrap);
26426
        if (config.bufferLength != null)
26427
            copy.bufferLength = config.bufferLength;
26428
        return copy;
26429
    }
26430
    /**
26431
    Tells you whether any [parse wrappers](#lr.ParserConfig.wrap)
26432
    are registered for this parser.
26433
    */
26434
    hasWrappers() {
26435
        return this.wrappers.length > 0;
26436
    }
26437
    /**
26438
    Returns the name associated with a given term. This will only
26439
    work for all terms when the parser was generated with the
26440
    `--names` option. By default, only the names of tagged terms are
26441
    stored.
26442
    */
26443
    getName(term) {
26444
        return this.termNames ? this.termNames[term] : String(term <= this.maxNode && this.nodeSet.types[term].name || term);
26445
    }
26446
    /**
26447
    The eof term id is always allocated directly after the node
26448
    types. @internal
26449
    */
26450
    get eofTerm() { return this.maxNode + 1; }
26451
    /**
26452
    The type of top node produced by the parser.
26453
    */
26454
    get topNode() { return this.nodeSet.types[this.top[1]]; }
26455
    /**
26456
    @internal
26457
    */
26458
    dynamicPrecedence(term) {
26459
        let prec = this.dynamicPrecedences;
26460
        return prec == null ? 0 : prec[term] || 0;
26461
    }
26462
    /**
26463
    @internal
26464
    */
26465
    parseDialect(dialect) {
26466
        let values = Object.keys(this.dialects), flags = values.map(() => false);
26467
        if (dialect)
26468
            for (let part of dialect.split(" ")) {
26469
                let id = values.indexOf(part);
26470
                if (id >= 0)
26471
                    flags[id] = true;
26472
            }
26473
        let disabled = null;
26474
        for (let i = 0; i < values.length; i++)
26475
            if (!flags[i]) {
26476
                for (let j = this.dialects[values[i]], id; (id = this.data[j++]) != 65535 /* Seq.End */;)
26477
                    (disabled || (disabled = new Uint8Array(this.maxTerm + 1)))[id] = 1;
26478
            }
26479
        return new Dialect(dialect, flags, disabled);
26480
    }
26481
    /**
26482
    Used by the output of the parser generator. Not available to
26483
    user code. @hide
26484
    */
26485
    static deserialize(spec) {
26486
        return new LRParser(spec);
26487
    }
26488
}
26489
function pair(data, off) { return data[off] | (data[off + 1] << 16); }
26490
function findFinished(stacks) {
26491
    let best = null;
26492
    for (let stack of stacks) {
26493
        let stopped = stack.p.stoppedAt;
26494
        if ((stack.pos == stack.p.stream.end || stopped != null && stack.pos > stopped) &&
26495
            stack.p.parser.stateFlag(stack.state, 2 /* StateFlag.Accepting */) &&
26496
            (!best || best.score < stack.score))
26497
            best = stack;
26498
    }
26499
    return best;
26500
}
26501
function getSpecializer(spec) {
26502
    if (spec.external) {
26503
        let mask = spec.extend ? 1 /* Specialize.Extend */ : 0 /* Specialize.Specialize */;
26504
        return (value, stack) => (spec.external(value, stack) << 1) | mask;
26505
    }
26506
    return spec.get;
26507
}
26508
 
26509
// This file was generated by lezer-generator. You probably shouldn't edit it.
26510
const scriptText = 54,
26511
  StartCloseScriptTag = 1,
26512
  styleText = 55,
26513
  StartCloseStyleTag = 2,
26514
  textareaText = 56,
26515
  StartCloseTextareaTag = 3,
26516
  EndTag = 4,
26517
  SelfClosingEndTag = 5,
26518
  StartTag$1 = 6,
26519
  StartScriptTag = 7,
26520
  StartStyleTag = 8,
26521
  StartTextareaTag = 9,
26522
  StartSelfClosingTag = 10,
26523
  StartCloseTag$1 = 11,
26524
  NoMatchStartCloseTag = 12,
26525
  MismatchedStartCloseTag = 13,
26526
  missingCloseTag = 57,
26527
  IncompleteCloseTag = 14,
26528
  commentContent$1$1 = 58,
26529
  Element$2 = 20,
26530
  TagName = 22,
26531
  Attribute = 23,
26532
  AttributeName = 24,
26533
  AttributeValue = 26,
26534
  UnquotedAttributeValue = 27,
26535
  ScriptText = 28,
26536
  StyleText = 31,
26537
  TextareaText = 34,
26538
  OpenTag$1 = 36,
26539
  CloseTag = 37,
26540
  Dialect_noMatch = 0,
26541
  Dialect_selfClosing = 1;
26542
 
26543
/* Hand-written tokenizers for HTML. */
26544
 
26545
const selfClosers$1 = {
26546
  area: true, base: true, br: true, col: true, command: true,
26547
  embed: true, frame: true, hr: true, img: true, input: true,
26548
  keygen: true, link: true, meta: true, param: true, source: true,
26549
  track: true, wbr: true, menuitem: true
26550
};
26551
 
26552
const implicitlyClosed = {
26553
  dd: true, li: true, optgroup: true, option: true, p: true,
26554
  rp: true, rt: true, tbody: true, td: true, tfoot: true,
26555
  th: true, tr: true
26556
};
26557
 
26558
const closeOnOpen = {
26559
  dd: {dd: true, dt: true},
26560
  dt: {dd: true, dt: true},
26561
  li: {li: true},
26562
  option: {option: true, optgroup: true},
26563
  optgroup: {optgroup: true},
26564
  p: {
26565
    address: true, article: true, aside: true, blockquote: true, dir: true,
26566
    div: true, dl: true, fieldset: true, footer: true, form: true,
26567
    h1: true, h2: true, h3: true, h4: true, h5: true, h6: true,
26568
    header: true, hgroup: true, hr: true, menu: true, nav: true, ol: true,
26569
    p: true, pre: true, section: true, table: true, ul: true
26570
  },
26571
  rp: {rp: true, rt: true},
26572
  rt: {rp: true, rt: true},
26573
  tbody: {tbody: true, tfoot: true},
26574
  td: {td: true, th: true},
26575
  tfoot: {tbody: true},
26576
  th: {td: true, th: true},
26577
  thead: {tbody: true, tfoot: true},
26578
  tr: {tr: true}
26579
};
26580
 
26581
function nameChar$1(ch) {
26582
  return ch == 45 || ch == 46 || ch == 58 || ch >= 65 && ch <= 90 || ch == 95 || ch >= 97 && ch <= 122 || ch >= 161
26583
}
26584
 
26585
function isSpace$1(ch) {
26586
  return ch == 9 || ch == 10 || ch == 13 || ch == 32
26587
}
26588
 
26589
let cachedName$1 = null, cachedInput$1 = null, cachedPos$1 = 0;
26590
function tagNameAfter$1(input, offset) {
26591
  let pos = input.pos + offset;
26592
  if (cachedPos$1 == pos && cachedInput$1 == input) return cachedName$1
26593
  let next = input.peek(offset);
26594
  while (isSpace$1(next)) next = input.peek(++offset);
26595
  let name = "";
26596
  for (;;) {
26597
    if (!nameChar$1(next)) break
26598
    name += String.fromCharCode(next);
26599
    next = input.peek(++offset);
26600
  }
26601
  // Undefined to signal there's a <? or <!, null for just missing
26602
  cachedInput$1 = input; cachedPos$1 = pos;
26603
  return cachedName$1 = name ? name.toLowerCase() : next == question || next == bang ? undefined : null
26604
}
26605
 
26606
const lessThan = 60, greaterThan = 62, slash$1 = 47, question = 63, bang = 33, dash$1 = 45;
26607
 
26608
function ElementContext$1(name, parent) {
26609
  this.name = name;
26610
  this.parent = parent;
26611
  this.hash = parent ? parent.hash : 0;
26612
  for (let i = 0; i < name.length; i++) this.hash += (this.hash << 4) + name.charCodeAt(i) + (name.charCodeAt(i) << 8);
26613
}
26614
 
26615
const startTagTerms = [StartTag$1, StartSelfClosingTag, StartScriptTag, StartStyleTag, StartTextareaTag];
26616
 
26617
const elementContext$1 = new ContextTracker({
26618
  start: null,
26619
  shift(context, term, stack, input) {
26620
    return startTagTerms.indexOf(term) > -1 ? new ElementContext$1(tagNameAfter$1(input, 1) || "", context) : context
26621
  },
26622
  reduce(context, term) {
26623
    return term == Element$2 && context ? context.parent : context
26624
  },
26625
  reuse(context, node, stack, input) {
26626
    let type = node.type.id;
26627
    return type == StartTag$1 || type == OpenTag$1
26628
      ? new ElementContext$1(tagNameAfter$1(input, 1) || "", context) : context
26629
  },
26630
  hash(context) { return context ? context.hash : 0 },
26631
  strict: false
26632
});
26633
 
26634
const tagStart = new ExternalTokenizer((input, stack) => {
26635
  if (input.next != lessThan) {
26636
    // End of file, close any open tags
26637
    if (input.next < 0 && stack.context) input.acceptToken(missingCloseTag);
26638
    return
26639
  }
26640
  input.advance();
26641
  let close = input.next == slash$1;
26642
  if (close) input.advance();
26643
  let name = tagNameAfter$1(input, 0);
26644
  if (name === undefined) return
26645
  if (!name) return input.acceptToken(close ? IncompleteCloseTag : StartTag$1)
26646
 
26647
  let parent = stack.context ? stack.context.name : null;
26648
  if (close) {
26649
    if (name == parent) return input.acceptToken(StartCloseTag$1)
26650
    if (parent && implicitlyClosed[parent]) return input.acceptToken(missingCloseTag, -2)
26651
    if (stack.dialectEnabled(Dialect_noMatch)) return input.acceptToken(NoMatchStartCloseTag)
26652
    for (let cx = stack.context; cx; cx = cx.parent) if (cx.name == name) return
26653
    input.acceptToken(MismatchedStartCloseTag);
26654
  } else {
26655
    if (name == "script") return input.acceptToken(StartScriptTag)
26656
    if (name == "style") return input.acceptToken(StartStyleTag)
26657
    if (name == "textarea") return input.acceptToken(StartTextareaTag)
26658
    if (selfClosers$1.hasOwnProperty(name)) return input.acceptToken(StartSelfClosingTag)
26659
    if (parent && closeOnOpen[parent] && closeOnOpen[parent][name]) input.acceptToken(missingCloseTag, -1);
26660
    else input.acceptToken(StartTag$1);
26661
  }
26662
}, {contextual: true});
26663
 
26664
const commentContent$2 = new ExternalTokenizer(input => {
26665
  for (let dashes = 0, i = 0;; i++) {
26666
    if (input.next < 0) {
26667
      if (i) input.acceptToken(commentContent$1$1);
26668
      break
26669
    }
26670
    if (input.next == dash$1) {
26671
      dashes++;
26672
    } else if (input.next == greaterThan && dashes >= 2) {
26673
      if (i >= 3) input.acceptToken(commentContent$1$1, -2);
26674
      break
26675
    } else {
26676
      dashes = 0;
26677
    }
26678
    input.advance();
26679
  }
26680
});
26681
 
26682
function inForeignElement(context) {
26683
  for (; context; context = context.parent)
26684
    if (context.name == "svg" || context.name == "math") return true
26685
  return false
26686
}
26687
 
26688
const endTag = new ExternalTokenizer((input, stack) => {
26689
  if (input.next == slash$1 && input.peek(1) == greaterThan) {
26690
    let selfClosing = stack.dialectEnabled(Dialect_selfClosing) || inForeignElement(stack.context);
26691
    input.acceptToken(selfClosing ? SelfClosingEndTag : EndTag, 2);
26692
  } else if (input.next == greaterThan) {
26693
    input.acceptToken(EndTag, 1);
26694
  }
26695
});
26696
 
26697
function contentTokenizer(tag, textToken, endToken) {
26698
  let lastState = 2 + tag.length;
26699
  return new ExternalTokenizer(input => {
26700
    // state means:
26701
    // - 0 nothing matched
26702
    // - 1 '<' matched
26703
    // - 2 '</' + possibly whitespace matched
26704
    // - 3-(1+tag.length) part of the tag matched
26705
    // - lastState whole tag + possibly whitespace matched
26706
    for (let state = 0, matchedLen = 0, i = 0;; i++) {
26707
      if (input.next < 0) {
26708
        if (i) input.acceptToken(textToken);
26709
        break
26710
      }
26711
      if (state == 0 && input.next == lessThan ||
26712
          state == 1 && input.next == slash$1 ||
26713
          state >= 2 && state < lastState && input.next == tag.charCodeAt(state - 2)) {
26714
        state++;
26715
        matchedLen++;
26716
      } else if ((state == 2 || state == lastState) && isSpace$1(input.next)) {
26717
        matchedLen++;
26718
      } else if (state == lastState && input.next == greaterThan) {
26719
        if (i > matchedLen)
26720
          input.acceptToken(textToken, -matchedLen);
26721
        else
26722
          input.acceptToken(endToken, -(matchedLen - 2));
26723
        break
26724
      } else if ((input.next == 10 /* '\n' */ || input.next == 13 /* '\r' */) && i) {
26725
        input.acceptToken(textToken, 1);
26726
        break
26727
      } else {
26728
        state = matchedLen = 0;
26729
      }
26730
      input.advance();
26731
    }
26732
  })
26733
}
26734
 
26735
const scriptTokens = contentTokenizer("script", scriptText, StartCloseScriptTag);
26736
 
26737
const styleTokens = contentTokenizer("style", styleText, StartCloseStyleTag);
26738
 
26739
const textareaTokens = contentTokenizer("textarea", textareaText, StartCloseTextareaTag);
26740
 
26741
const htmlHighlighting = styleTags({
26742
  "Text RawText": tags$1.content,
26743
  "StartTag StartCloseTag SelfClosingEndTag EndTag": tags$1.angleBracket,
26744
  TagName: tags$1.tagName,
26745
  "MismatchedCloseTag/TagName": [tags$1.tagName,  tags$1.invalid],
26746
  AttributeName: tags$1.attributeName,
26747
  "AttributeValue UnquotedAttributeValue": tags$1.attributeValue,
26748
  Is: tags$1.definitionOperator,
26749
  "EntityReference CharacterReference": tags$1.character,
26750
  Comment: tags$1.blockComment,
26751
  ProcessingInst: tags$1.processingInstruction,
26752
  DoctypeDecl: tags$1.documentMeta
26753
});
26754
 
26755
// This file was generated by lezer-generator. You probably shouldn't edit it.
26756
const parser$3 = LRParser.deserialize({
26757
  version: 14,
26758
  states: ",xOVO!rOOO!WQ#tO'#CqO!]Q#tO'#CzO!bQ#tO'#C}O!gQ#tO'#DQO!lQ#tO'#DSO!qOaO'#CpO!|ObO'#CpO#XOdO'#CpO$eO!rO'#CpOOO`'#Cp'#CpO$lO$fO'#DTO$tQ#tO'#DVO$yQ#tO'#DWOOO`'#Dk'#DkOOO`'#DY'#DYQVO!rOOO%OQ&rO,59]O%ZQ&rO,59fO%fQ&rO,59iO%qQ&rO,59lO%|Q&rO,59nOOOa'#D^'#D^O&XOaO'#CxO&dOaO,59[OOOb'#D_'#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WfOPlX!ZlX~OP!WO!Z!XO~O!XiOQoX!ZoX~OQ!ZO!Z!XO~O!YlORrX!ZrX~OR!]O!Z!XO~O!Z!XO~P#dOf!_O~O![sO!e!aO~OS!bO~OS!cO~Oi!dOSgXTgXhgX~OS!fOT!gOhyO~OS!hOT!gOhyO~OS!iOT!gOhyO~OS!jOT!gOhyO~OS!gOT!gOhyO~Of!kO~Of!lO~Of!mO~OS!nO~Ok!qO!`!oO!b!pO~OS!rO~OS!sO~OS!tO~Oa!uOb!uOc!uO!`!wO!a!uO~Oa!xOb!xOc!xO!b!wO!c!xO~Oa!uOb!uOc!uO!`!{O!a!uO~Oa!xOb!xOc!xO!b!{O!c!xO~OT~bac!dx{!d~",
26760
  goto: "%p!`PPPPPPPPPPPPPPPPPPPP!a!gP!mPP!yP!|#P#S#Y#]#`#f#i#l#r#x!aP!a!aP$O$U$l$r$x%O%U%[%bPPPPPPPP%hX^OX`pXUOX`pezabcde{!O!Q!S!UR!q!dRhUR!XhXVOX`pRkVR!XkXWOX`pRnWR!XnXXOX`pQrXR!XpXYOX`pQ`ORx`Q{aQ!ObQ!QcQ!SdQ!UeZ!e{!O!Q!S!UQ!v!oR!z!vQ!y!pR!|!yQgUR!VgQjVR!YjQmWR![mQpXR!^pQtZR!`tS_O`ToXp",
26761
  nodeNames: "⚠ StartCloseTag StartCloseTag StartCloseTag EndTag SelfClosingEndTag StartTag StartTag StartTag StartTag StartTag StartCloseTag StartCloseTag StartCloseTag IncompleteCloseTag Document Text EntityReference CharacterReference InvalidEntity Element OpenTag TagName Attribute AttributeName Is AttributeValue UnquotedAttributeValue ScriptText CloseTag OpenTag StyleText CloseTag OpenTag TextareaText CloseTag OpenTag CloseTag SelfClosingTag Comment ProcessingInst MismatchedCloseTag CloseTag DoctypeDecl",
26762
  maxTerm: 67,
26763
  context: elementContext$1,
26764
  nodeProps: [
26765
    ["closedBy", -10,1,2,3,7,8,9,10,11,12,13,"EndTag",6,"EndTag SelfClosingEndTag",-4,21,30,33,36,"CloseTag"],
26766
    ["openedBy", 4,"StartTag StartCloseTag",5,"StartTag",-4,29,32,35,37,"OpenTag"],
26767
    ["group", -9,14,17,18,19,20,39,40,41,42,"Entity",16,"Entity TextContent",-3,28,31,34,"TextContent Entity"],
26768
    ["isolate", -11,21,29,30,32,33,35,36,37,38,41,42,"ltr",-3,26,27,39,""]
26769
  ],
26770
  propSources: [htmlHighlighting],
26771
  skippedNodes: [0],
26772
  repeatNodeCount: 9,
26773
  tokenData: "!<p!aR!YOX$qXY,QYZ,QZ[$q[]&X]^,Q^p$qpq,Qqr-_rs3_sv-_vw3}wxHYx}-_}!OH{!O!P-_!P!Q$q!Q![-_![!]Mz!]!^-_!^!_!$S!_!`!;x!`!a&X!a!c-_!c!}Mz!}#R-_#R#SMz#S#T1k#T#oMz#o#s-_#s$f$q$f%W-_%W%oMz%o%p-_%p&aMz&a&b-_&b1pMz1p4U-_4U4dMz4d4e-_4e$ISMz$IS$I`-_$I`$IbMz$Ib$Kh-_$Kh%#tMz%#t&/x-_&/x&EtMz&Et&FV-_&FV;'SMz;'S;:j!#|;:j;=`3X<%l?&r-_?&r?AhMz?Ah?BY$q?BY?MnMz?MnO$q!Z$|c`PkW!a`!cpOX$qXZ&XZ[$q[^&X^p$qpq&Xqr$qrs&}sv$qvw+Pwx(tx!^$q!^!_*V!_!a&X!a#S$q#S#T&X#T;'S$q;'S;=`+z<%lO$q!R&bX`P!a`!cpOr&Xrs&}sv&Xwx(tx!^&X!^!_*V!_;'S&X;'S;=`*y<%lO&Xq'UV`P!cpOv&}wx'kx!^&}!^!_(V!_;'S&};'S;=`(n<%lO&}P'pT`POv'kw!^'k!_;'S'k;'S;=`(P<%lO'kP(SP;=`<%l'kp([S!cpOv(Vx;'S(V;'S;=`(h<%lO(Vp(kP;=`<%l(Vq(qP;=`<%l&}a({W`P!a`Or(trs'ksv(tw!^(t!^!_)e!_;'S(t;'S;=`*P<%lO(t`)jT!a`Or)esv)ew;'S)e;'S;=`)y<%lO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6V!a!b!6i!b;'S!6V;'S;=`!7Q<%lO!6VP!6lTO!`!6V!`!a!6{!a;'S!6V;'S;=`!7Q<%lO!6VP!7QOxPP!7TP;=`<%l!6Vq!7]V!cpOv!5kvx!6Vx!`!5k!`!a!7r!a;'S!5k;'S;=`!8V<%lO!5kq!7yS!cpxPOv(Vx;'S(V;'S;=`(h<%lO(Vq!8YP;=`<%l!5ka!8bX!a`Or!8]rs!6Vsv!8]vw!6Vw!a!8]!a!b!8}!b;'S!8];'S;=`!:V<%lO!8]a!9SX!a`Or!8]rs!6Vsv!8]vw!6Vw!`!8]!`!a!9o!a;'S!8];'S;=`!:V<%lO!8]a!9vT!a`xPOr)esv)ew;'S)e;'S;=`)y<%lO)ea!:YP;=`<%l!8]!R!:dY!a`!cpOr!4trs!5ksv!4tvw!6Vwx!8]x!`!4t!`!a!;S!a;'S!4t;'S;=`!;r<%lO!4t!R!;]V!a`!cpxPOr*Vrs(Vsv*Vwx)ex;'S*V;'S;=`*s<%lO*V!R!;uP;=`<%l!4t!V!<TXiS`P!a`!cpOr&Xrs&}sv&Xwx(tx!^&X!^!_*V!_;'S&X;'S;=`*y<%lO&X",
26774
  tokenizers: [scriptTokens, styleTokens, textareaTokens, endTag, tagStart, commentContent$2, 0, 1, 2, 3, 4, 5],
26775
  topRules: {"Document":[0,15]},
26776
  dialects: {noMatch: 0, selfClosing: 509},
26777
  tokenPrec: 511
26778
});
26779
 
26780
function getAttrs(openTag, input) {
26781
  let attrs = Object.create(null);
26782
  for (let att of openTag.getChildren(Attribute)) {
26783
    let name = att.getChild(AttributeName), value = att.getChild(AttributeValue) || att.getChild(UnquotedAttributeValue);
26784
    if (name) attrs[input.read(name.from, name.to)] =
26785
      !value ? "" : value.type.id == AttributeValue ? input.read(value.from + 1, value.to - 1) : input.read(value.from, value.to);
26786
  }
26787
  return attrs
26788
}
26789
 
26790
function findTagName(openTag, input) {
26791
  let tagNameNode = openTag.getChild(TagName);
26792
  return tagNameNode ? input.read(tagNameNode.from, tagNameNode.to) : " "
26793
}
26794
 
26795
function maybeNest(node, input, tags) {
26796
  let attrs;
26797
  for (let tag of tags) {
26798
    if (!tag.attrs || tag.attrs(attrs || (attrs = getAttrs(node.node.parent.firstChild, input))))
26799
      return {parser: tag.parser}
26800
  }
26801
  return null
26802
}
26803
 
26804
// tags?: {
26805
//   tag: string,
26806
//   attrs?: ({[attr: string]: string}) => boolean,
26807
//   parser: Parser
26808
// }[]
26809
// attributes?: {
26810
//   name: string,
26811
//   tagName?: string,
26812
//   parser: Parser
26813
// }[]
26814
 
26815
function configureNesting(tags = [], attributes = []) {
26816
  let script = [], style = [], textarea = [], other = [];
26817
  for (let tag of tags) {
26818
    let array = tag.tag == "script" ? script : tag.tag == "style" ? style : tag.tag == "textarea" ? textarea : other;
26819
    array.push(tag);
26820
  }
26821
  let attrs = attributes.length ? Object.create(null) : null;
26822
  for (let attr of attributes) (attrs[attr.name] || (attrs[attr.name] = [])).push(attr);
26823
 
26824
  return parseMixed((node, input) => {
26825
    let id = node.type.id;
26826
    if (id == ScriptText) return maybeNest(node, input, script)
26827
    if (id == StyleText) return maybeNest(node, input, style)
26828
    if (id == TextareaText) return maybeNest(node, input, textarea)
26829
 
26830
    if (id == Element$2 && other.length) {
26831
      let n = node.node, open = n.firstChild, tagName = open && findTagName(open, input), attrs;
26832
      if (tagName) for (let tag of other) {
26833
        if (tag.tag == tagName && (!tag.attrs || tag.attrs(attrs || (attrs = getAttrs(n, input))))) {
26834
          let close = n.lastChild;
26835
          let to = close.type.id == CloseTag ? close.from : n.to;
26836
          if (to > open.to)
26837
            return {parser: tag.parser, overlay: [{from: open.to, to}]}
26838
        }
26839
      }
26840
    }
26841
 
26842
    if (attrs && id == Attribute) {
26843
      let n = node.node, nameNode;
26844
      if (nameNode = n.firstChild) {
26845
        let matches = attrs[input.read(nameNode.from, nameNode.to)];
26846
        if (matches) for (let attr of matches) {
26847
          if (attr.tagName && attr.tagName != findTagName(n.parent, input)) continue
26848
          let value = n.lastChild;
26849
          if (value.type.id == AttributeValue) {
26850
            let from = value.from + 1;
26851
            let last = value.lastChild, to = value.to - (last && last.isError ? 0 : 1);
26852
            if (to > from) return {parser: attr.parser, overlay: [{from, to}]}
26853
          } else if (value.type.id == UnquotedAttributeValue) {
26854
            return {parser: attr.parser, overlay: [{from: value.from, to: value.to}]}
26855
          }
26856
        }
26857
      }
26858
    }
26859
    return null
26860
  })
26861
}
26862
 
26863
// This file was generated by lezer-generator. You probably shouldn't edit it.
26864
const descendantOp = 99,
26865
  Unit = 1,
26866
  callee = 100,
26867
  identifier$2 = 101,
26868
  VariableName = 2;
26869
 
26870
/* Hand-written tokenizers for CSS tokens that can't be
26871
   expressed by Lezer's built-in tokenizer. */
26872
 
26873
const space$1 = [9, 10, 11, 12, 13, 32, 133, 160, 5760, 8192, 8193, 8194, 8195, 8196, 8197,
26874
               8198, 8199, 8200, 8201, 8202, 8232, 8233, 8239, 8287, 12288];
26875
const colon = 58, parenL = 40, underscore = 95, bracketL = 91, dash = 45, period = 46,
26876
      hash = 35, percent = 37, ampersand = 38, backslash = 92, newline$1 = 10;
26877
 
26878
function isAlpha(ch) { return ch >= 65 && ch <= 90 || ch >= 97 && ch <= 122 || ch >= 161 }
26879
 
26880
function isDigit(ch) { return ch >= 48 && ch <= 57 }
26881
 
26882
const identifiers = new ExternalTokenizer((input, stack) => {
26883
  for (let inside = false, dashes = 0, i = 0;; i++) {
26884
    let {next} = input;
26885
    if (isAlpha(next) || next == dash || next == underscore || (inside && isDigit(next))) {
26886
      if (!inside && (next != dash || i > 0)) inside = true;
26887
      if (dashes === i && next == dash) dashes++;
26888
      input.advance();
26889
    } else if (next == backslash && input.peek(1) != newline$1) {
26890
      input.advance();
26891
      if (input.next > -1) input.advance();
26892
      inside = true;
26893
    } else {
26894
      if (inside)
26895
        input.acceptToken(next == parenL ? callee : dashes == 2 && stack.canShift(VariableName) ? VariableName : identifier$2);
26896
      break
26897
    }
26898
  }
26899
});
26900
 
26901
const descendant = new ExternalTokenizer(input => {
26902
  if (space$1.includes(input.peek(-1))) {
26903
    let {next} = input;
26904
    if (isAlpha(next) || next == underscore || next == hash || next == period ||
26905
        next == bracketL || next == colon && isAlpha(input.peek(1)) ||
26906
        next == dash || next == ampersand)
26907
      input.acceptToken(descendantOp);
26908
  }
26909
});
26910
 
26911
const unitToken = new ExternalTokenizer(input => {
26912
  if (!space$1.includes(input.peek(-1))) {
26913
    let {next} = input;
26914
    if (next == percent) { input.advance(); input.acceptToken(Unit); }
26915
    if (isAlpha(next)) {
26916
      do { input.advance(); } while (isAlpha(input.next) || isDigit(input.next))
26917
      input.acceptToken(Unit);
26918
    }
26919
  }
26920
});
26921
 
26922
const cssHighlighting = styleTags({
26923
  "AtKeyword import charset namespace keyframes media supports": tags$1.definitionKeyword,
26924
  "from to selector": tags$1.keyword,
26925
  NamespaceName: tags$1.namespace,
26926
  KeyframeName: tags$1.labelName,
26927
  KeyframeRangeName: tags$1.operatorKeyword,
26928
  TagName: tags$1.tagName,
26929
  ClassName: tags$1.className,
26930
  PseudoClassName: tags$1.constant(tags$1.className),
26931
  IdName: tags$1.labelName,
26932
  "FeatureName PropertyName": tags$1.propertyName,
26933
  AttributeName: tags$1.attributeName,
26934
  NumberLiteral: tags$1.number,
26935
  KeywordQuery: tags$1.keyword,
26936
  UnaryQueryOp: tags$1.operatorKeyword,
26937
  "CallTag ValueName": tags$1.atom,
26938
  VariableName: tags$1.variableName,
26939
  Callee: tags$1.operatorKeyword,
26940
  Unit: tags$1.unit,
26941
  "UniversalSelector NestingSelector": tags$1.definitionOperator,
26942
  MatchOp: tags$1.compareOperator,
26943
  "ChildOp SiblingOp, LogicOp": tags$1.logicOperator,
26944
  BinOp: tags$1.arithmeticOperator,
26945
  Important: tags$1.modifier,
26946
  Comment: tags$1.blockComment,
26947
  ColorLiteral: tags$1.color,
26948
  "ParenthesizedContent StringLiteral": tags$1.string,
26949
  ":": tags$1.punctuation,
26950
  "PseudoOp #": tags$1.derefOperator,
26951
  "; ,": tags$1.separator,
26952
  "( )": tags$1.paren,
26953
  "[ ]": tags$1.squareBracket,
26954
  "{ }": tags$1.brace
26955
});
26956
 
26957
// This file was generated by lezer-generator. You probably shouldn't edit it.
26958
const spec_callee = {__proto__:null,lang:32, "nth-child":32, "nth-last-child":32, "nth-of-type":32, "nth-last-of-type":32, dir:32, "host-context":32, url:60, "url-prefix":60, domain:60, regexp:60, selector:138};
26959
const spec_AtKeyword = {__proto__:null,"@import":118, "@media":142, "@charset":146, "@namespace":150, "@keyframes":156, "@supports":168};
26960
const spec_identifier$1 = {__proto__:null,not:132, only:132};
26961
const parser$2 = LRParser.deserialize({
26962
  version: 14,
26963
  states: ":^QYQ[OOO#_Q[OOP#fOWOOOOQP'#Cd'#CdOOQP'#Cc'#CcO#kQ[O'#CfO$_QXO'#CaO$fQ[O'#ChO$qQ[O'#DTO$vQ[O'#DWOOQP'#Em'#EmO${QdO'#DgO%jQ[O'#DtO${QdO'#DvO%{Q[O'#DxO&WQ[O'#D{O&`Q[O'#ERO&nQ[O'#ETOOQS'#El'#ElOOQS'#EW'#EWQYQ[OOO&uQXO'#CdO'jQWO'#DcO'oQWO'#EsO'zQ[O'#EsQOQWOOP(UO#tO'#C_POOO)C@[)C@[OOQP'#Cg'#CgOOQP,59Q,59QO#kQ[O,59QO(aQ[O'#E[O({QWO,58{O)TQ[O,59SO$qQ[O,59oO$vQ[O,59rO(aQ[O,59uO(aQ[O,59wO(aQ[O,59xO)`Q[O'#DbOOQS,58{,58{OOQP'#Ck'#CkOOQO'#DR'#DROOQP,59S,59SO)gQWO,59SO)lQWO,59SOOQP'#DV'#DVOOQP,59o,59oOOQO'#DX'#DXO)qQ`O,59rOOQS'#Cp'#CpO${QdO'#CqO)yQvO'#CsO+ZQtO,5:ROOQO'#Cx'#CxO)lQWO'#CwO+oQWO'#CyO+tQ[O'#DOOOQS'#Ep'#EpOOQO'#Dj'#DjO+|Q[O'#DqO,[QWO'#EtO&`Q[O'#DoO,jQWO'#DrOOQO'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$[#dR$]#e",
26966
  nodeNames: "⚠ Unit VariableName Comment StyleSheet RuleSet UniversalSelector TagSelector TagName NestingSelector ClassSelector ClassName PseudoClassSelector : :: PseudoClassName PseudoClassName ) ( ArgList ValueName ParenthesizedValue ColorLiteral NumberLiteral StringLiteral BinaryExpression BinOp CallExpression Callee CallLiteral CallTag ParenthesizedContent ] [ LineNames LineName , PseudoClassName ArgList IdSelector # IdName AttributeSelector AttributeName MatchOp ChildSelector ChildOp DescendantSelector SiblingSelector SiblingOp } { Block Declaration PropertyName Important ; ImportStatement AtKeyword import KeywordQuery FeatureQuery FeatureName BinaryQuery LogicOp UnaryQuery UnaryQueryOp ParenthesizedQuery SelectorQuery selector MediaStatement media CharsetStatement charset NamespaceStatement namespace NamespaceName KeyframesStatement keyframes KeyframeName KeyframeList KeyframeSelector KeyframeRangeName SupportsStatement supports AtRule Styles",
26967
  maxTerm: 117,
26968
  nodeProps: [
26969
    ["isolate", -2,3,24,""],
26970
    ["openedBy", 17,"(",32,"[",50,"{"],
26971
    ["closedBy", 18,")",33,"]",51,"}"]
26972
  ],
26973
  propSources: [cssHighlighting],
26974
  skippedNodes: [0,3,87],
26975
  repeatNodeCount: 11,
26976
  tokenData: "J^~R!^OX$}X^%u^p$}pq%uqr)Xrs.Rst/utu6duv$}vw7^wx7oxy9^yz9oz{9t{|:_|}?Q}!O?c!O!P@Q!P!Q@i!Q![Ab![!]B]!]!^CX!^!_$}!_!`Cj!`!aC{!a!b$}!b!cDw!c!}$}!}#OFa#O#P$}#P#QFr#Q#R6d#R#T$}#T#UGT#U#c$}#c#dHf#d#o$}#o#pH{#p#q6d#q#rI^#r#sIo#s#y$}#y#z%u#z$f$}$f$g%u$g#BY$}#BY#BZ%u#BZ$IS$}$IS$I_%u$I_$I|$}$I|$JO%u$JO$JT$}$JT$JU%u$JU$KV$}$KV$KW%u$KW&FU$}&FU&FV%u&FV;'S$};'S;=`JW<%lO$}`%QSOy%^z;'S%^;'S;=`%o<%lO%^`%cSo`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%^bHiUOy%^z#f%^#f#gHR#g;'S%^;'S;=`%o<%lO%^fIQS!TUOy%^z;'S%^;'S;=`%o<%lO%^nIcS!S^Oy%^z;'S%^;'S;=`%o<%lO%^fItU!RQOy%^z!_%^!_!`6y!`;'S%^;'S;=`%o<%lO%^`JZP;=`<%l$}",
26977
  tokenizers: [descendant, unitToken, identifiers, 1, 2, 3, 4, new LocalTokenGroup("m~RRYZ[z{a~~g~aO#^~~dP!P!Qg~lO#_~~", 28, 105)],
26978
  topRules: {"StyleSheet":[0,4],"Styles":[1,86]},
26979
  specialized: [{term: 100, get: (value) => spec_callee[value] || -1},{term: 58, get: (value) => spec_AtKeyword[value] || -1},{term: 101, get: (value) => spec_identifier$1[value] || -1}],
26980
  tokenPrec: 1200
26981
});
26982
 
26983
let _properties = null;
26984
function properties() {
26985
    if (!_properties && typeof document == "object" && document.body) {
26986
        let { style } = document.body, names = [], seen = new Set;
26987
        for (let prop in style)
26988
            if (prop != "cssText" && prop != "cssFloat") {
26989
                if (typeof style[prop] == "string") {
26990
                    if (/[A-Z]/.test(prop))
26991
                        prop = prop.replace(/[A-Z]/g, ch => "-" + ch.toLowerCase());
26992
                    if (!seen.has(prop)) {
26993
                        names.push(prop);
26994
                        seen.add(prop);
26995
                    }
26996
                }
26997
            }
26998
        _properties = names.sort().map(name => ({ type: "property", label: name }));
26999
    }
27000
    return _properties || [];
27001
}
27002
const pseudoClasses = /*@__PURE__*/[
27003
    "active", "after", "any-link", "autofill", "backdrop", "before",
27004
    "checked", "cue", "default", "defined", "disabled", "empty",
27005
    "enabled", "file-selector-button", "first", "first-child",
27006
    "first-letter", "first-line", "first-of-type", "focus",
27007
    "focus-visible", "focus-within", "fullscreen", "has", "host",
27008
    "host-context", "hover", "in-range", "indeterminate", "invalid",
27009
    "is", "lang", "last-child", "last-of-type", "left", "link", "marker",
27010
    "modal", "not", "nth-child", "nth-last-child", "nth-last-of-type",
27011
    "nth-of-type", "only-child", "only-of-type", "optional", "out-of-range",
27012
    "part", "placeholder", "placeholder-shown", "read-only", "read-write",
27013
    "required", "right", "root", "scope", "selection", "slotted", "target",
27014
    "target-text", "valid", "visited", "where"
27015
].map(name => ({ type: "class", label: name }));
27016
const values = /*@__PURE__*/[
27017
    "above", "absolute", "activeborder", "additive", "activecaption", "after-white-space",
27018
    "ahead", "alias", "all", "all-scroll", "alphabetic", "alternate", "always",
27019
    "antialiased", "appworkspace", "asterisks", "attr", "auto", "auto-flow", "avoid", "avoid-column",
27020
    "avoid-page", "avoid-region", "axis-pan", "background", "backwards", "baseline", "below",
27021
    "bidi-override", "blink", "block", "block-axis", "bold", "bolder", "border", "border-box",
27022
    "both", "bottom", "break", "break-all", "break-word", "bullets", "button", "button-bevel",
27023
    "buttonface", "buttonhighlight", "buttonshadow", "buttontext", "calc", "capitalize",
27024
    "caps-lock-indicator", "caption", "captiontext", "caret", "cell", "center", "checkbox", "circle",
27025
    "cjk-decimal", "clear", "clip", "close-quote", "col-resize", "collapse", "color", "color-burn",
27026
    "color-dodge", "column", "column-reverse", "compact", "condensed", "contain", "content",
27027
    "contents", "content-box", "context-menu", "continuous", "copy", "counter", "counters", "cover",
27028
    "crop", "cross", "crosshair", "currentcolor", "cursive", "cyclic", "darken", "dashed", "decimal",
27029
    "decimal-leading-zero", "default", "default-button", "dense", "destination-atop", "destination-in",
27030
    "destination-out", "destination-over", "difference", "disc", "discard", "disclosure-closed",
27031
    "disclosure-open", "document", "dot-dash", "dot-dot-dash", "dotted", "double", "down", "e-resize",
27032
    "ease", "ease-in", "ease-in-out", "ease-out", "element", "ellipse", "ellipsis", "embed", "end",
27033
    "ethiopic-abegede-gez", "ethiopic-halehame-aa-er", "ethiopic-halehame-gez", "ew-resize", "exclusion",
27034
    "expanded", "extends", "extra-condensed", "extra-expanded", "fantasy", "fast", "fill", "fill-box",
27035
    "fixed", "flat", "flex", "flex-end", "flex-start", "footnotes", "forwards", "from",
27036
    "geometricPrecision", "graytext", "grid", "groove", "hand", "hard-light", "help", "hidden", "hide",
27037
    "higher", "highlight", "highlighttext", "horizontal", "hsl", "hsla", "hue", "icon", "ignore",
27038
    "inactiveborder", "inactivecaption", "inactivecaptiontext", "infinite", "infobackground", "infotext",
27039
    "inherit", "initial", "inline", "inline-axis", "inline-block", "inline-flex", "inline-grid",
27040
    "inline-table", "inset", "inside", "intrinsic", "invert", "italic", "justify", "keep-all",
27041
    "landscape", "large", "larger", "left", "level", "lighter", "lighten", "line-through", "linear",
27042
    "linear-gradient", "lines", "list-item", "listbox", "listitem", "local", "logical", "loud", "lower",
27043
    "lower-hexadecimal", "lower-latin", "lower-norwegian", "lowercase", "ltr", "luminosity", "manipulation",
27044
    "match", "matrix", "matrix3d", "medium", "menu", "menutext", "message-box", "middle", "min-intrinsic",
27045
    "mix", "monospace", "move", "multiple", "multiple_mask_images", "multiply", "n-resize", "narrower",
27046
    "ne-resize", "nesw-resize", "no-close-quote", "no-drop", "no-open-quote", "no-repeat", "none",
27047
    "normal", "not-allowed", "nowrap", "ns-resize", "numbers", "numeric", "nw-resize", "nwse-resize",
27048
    "oblique", "opacity", "open-quote", "optimizeLegibility", "optimizeSpeed", "outset", "outside",
27049
    "outside-shape", "overlay", "overline", "padding", "padding-box", "painted", "page", "paused",
27050
    "perspective", "pinch-zoom", "plus-darker", "plus-lighter", "pointer", "polygon", "portrait",
27051
    "pre", "pre-line", "pre-wrap", "preserve-3d", "progress", "push-button", "radial-gradient", "radio",
27052
    "read-only", "read-write", "read-write-plaintext-only", "rectangle", "region", "relative", "repeat",
27053
    "repeating-linear-gradient", "repeating-radial-gradient", "repeat-x", "repeat-y", "reset", "reverse",
27054
    "rgb", "rgba", "ridge", "right", "rotate", "rotate3d", "rotateX", "rotateY", "rotateZ", "round",
27055
    "row", "row-resize", "row-reverse", "rtl", "run-in", "running", "s-resize", "sans-serif", "saturation",
27056
    "scale", "scale3d", "scaleX", "scaleY", "scaleZ", "screen", "scroll", "scrollbar", "scroll-position",
27057
    "se-resize", "self-start", "self-end", "semi-condensed", "semi-expanded", "separate", "serif", "show",
27058
    "single", "skew", "skewX", "skewY", "skip-white-space", "slide", "slider-horizontal",
27059
    "slider-vertical", "sliderthumb-horizontal", "sliderthumb-vertical", "slow", "small", "small-caps",
27060
    "small-caption", "smaller", "soft-light", "solid", "source-atop", "source-in", "source-out",
27061
    "source-over", "space", "space-around", "space-between", "space-evenly", "spell-out", "square", "start",
27062
    "static", "status-bar", "stretch", "stroke", "stroke-box", "sub", "subpixel-antialiased", "svg_masks",
27063
    "super", "sw-resize", "symbolic", "symbols", "system-ui", "table", "table-caption", "table-cell",
27064
    "table-column", "table-column-group", "table-footer-group", "table-header-group", "table-row",
27065
    "table-row-group", "text", "text-bottom", "text-top", "textarea", "textfield", "thick", "thin",
27066
    "threeddarkshadow", "threedface", "threedhighlight", "threedlightshadow", "threedshadow", "to", "top",
27067
    "transform", "translate", "translate3d", "translateX", "translateY", "translateZ", "transparent",
27068
    "ultra-condensed", "ultra-expanded", "underline", "unidirectional-pan", "unset", "up", "upper-latin",
27069
    "uppercase", "url", "var", "vertical", "vertical-text", "view-box", "visible", "visibleFill",
27070
    "visiblePainted", "visibleStroke", "visual", "w-resize", "wait", "wave", "wider", "window", "windowframe",
27071
    "windowtext", "words", "wrap", "wrap-reverse", "x-large", "x-small", "xor", "xx-large", "xx-small"
27072
].map(name => ({ type: "keyword", label: name })).concat(/*@__PURE__*/[
27073
    "aliceblue", "antiquewhite", "aqua", "aquamarine", "azure", "beige",
27074
    "bisque", "black", "blanchedalmond", "blue", "blueviolet", "brown",
27075
    "burlywood", "cadetblue", "chartreuse", "chocolate", "coral", "cornflowerblue",
27076
    "cornsilk", "crimson", "cyan", "darkblue", "darkcyan", "darkgoldenrod",
27077
    "darkgray", "darkgreen", "darkkhaki", "darkmagenta", "darkolivegreen",
27078
    "darkorange", "darkorchid", "darkred", "darksalmon", "darkseagreen",
27079
    "darkslateblue", "darkslategray", "darkturquoise", "darkviolet",
27080
    "deeppink", "deepskyblue", "dimgray", "dodgerblue", "firebrick",
27081
    "floralwhite", "forestgreen", "fuchsia", "gainsboro", "ghostwhite",
27082
    "gold", "goldenrod", "gray", "grey", "green", "greenyellow", "honeydew",
27083
    "hotpink", "indianred", "indigo", "ivory", "khaki", "lavender",
27084
    "lavenderblush", "lawngreen", "lemonchiffon", "lightblue", "lightcoral",
27085
    "lightcyan", "lightgoldenrodyellow", "lightgray", "lightgreen", "lightpink",
27086
    "lightsalmon", "lightseagreen", "lightskyblue", "lightslategray",
27087
    "lightsteelblue", "lightyellow", "lime", "limegreen", "linen", "magenta",
27088
    "maroon", "mediumaquamarine", "mediumblue", "mediumorchid", "mediumpurple",
27089
    "mediumseagreen", "mediumslateblue", "mediumspringgreen", "mediumturquoise",
27090
    "mediumvioletred", "midnightblue", "mintcream", "mistyrose", "moccasin",
27091
    "navajowhite", "navy", "oldlace", "olive", "olivedrab", "orange", "orangered",
27092
    "orchid", "palegoldenrod", "palegreen", "paleturquoise", "palevioletred",
27093
    "papayawhip", "peachpuff", "peru", "pink", "plum", "powderblue",
27094
    "purple", "rebeccapurple", "red", "rosybrown", "royalblue", "saddlebrown",
27095
    "salmon", "sandybrown", "seagreen", "seashell", "sienna", "silver", "skyblue",
27096
    "slateblue", "slategray", "snow", "springgreen", "steelblue", "tan",
27097
    "teal", "thistle", "tomato", "turquoise", "violet", "wheat", "white",
27098
    "whitesmoke", "yellow", "yellowgreen"
27099
].map(name => ({ type: "constant", label: name })));
27100
const tags = /*@__PURE__*/[
27101
    "a", "abbr", "address", "article", "aside", "b", "bdi", "bdo", "blockquote", "body",
27102
    "br", "button", "canvas", "caption", "cite", "code", "col", "colgroup", "dd", "del",
27103
    "details", "dfn", "dialog", "div", "dl", "dt", "em", "figcaption", "figure", "footer",
27104
    "form", "header", "hgroup", "h1", "h2", "h3", "h4", "h5", "h6", "hr", "html", "i", "iframe",
27105
    "img", "input", "ins", "kbd", "label", "legend", "li", "main", "meter", "nav", "ol", "output",
27106
    "p", "pre", "ruby", "section", "select", "small", "source", "span", "strong", "sub", "summary",
27107
    "sup", "table", "tbody", "td", "template", "textarea", "tfoot", "th", "thead", "tr", "u", "ul"
27108
].map(name => ({ type: "type", label: name }));
27109
const identifier$1 = /^(\w[\w-]*|-\w[\w-]*|)$/, variable = /^-(-[\w-]*)?$/;
27110
function isVarArg(node, doc) {
27111
    var _a;
27112
    if (node.name == "(" || node.type.isError)
27113
        node = node.parent || node;
27114
    if (node.name != "ArgList")
27115
        return false;
27116
    let callee = (_a = node.parent) === null || _a === void 0 ? void 0 : _a.firstChild;
27117
    if ((callee === null || callee === void 0 ? void 0 : callee.name) != "Callee")
27118
        return false;
27119
    return doc.sliceString(callee.from, callee.to) == "var";
27120
}
27121
const VariablesByNode = /*@__PURE__*/new NodeWeakMap();
27122
const declSelector = ["Declaration"];
27123
function astTop(node) {
27124
    for (let cur = node;;) {
27125
        if (cur.type.isTop)
27126
            return cur;
27127
        if (!(cur = cur.parent))
27128
            return node;
27129
    }
27130
}
27131
function variableNames(doc, node, isVariable) {
27132
    if (node.to - node.from > 4096) {
27133
        let known = VariablesByNode.get(node);
27134
        if (known)
27135
            return known;
27136
        let result = [], seen = new Set, cursor = node.cursor(IterMode.IncludeAnonymous);
27137
        if (cursor.firstChild())
27138
            do {
27139
                for (let option of variableNames(doc, cursor.node, isVariable))
27140
                    if (!seen.has(option.label)) {
27141
                        seen.add(option.label);
27142
                        result.push(option);
27143
                    }
27144
            } while (cursor.nextSibling());
27145
        VariablesByNode.set(node, result);
27146
        return result;
27147
    }
27148
    else {
27149
        let result = [], seen = new Set;
27150
        node.cursor().iterate(node => {
27151
            var _a;
27152
            if (isVariable(node) && node.matchContext(declSelector) && ((_a = node.node.nextSibling) === null || _a === void 0 ? void 0 : _a.name) == ":") {
27153
                let name = doc.sliceString(node.from, node.to);
27154
                if (!seen.has(name)) {
27155
                    seen.add(name);
27156
                    result.push({ label: name, type: "variable" });
27157
                }
27158
            }
27159
        });
27160
        return result;
27161
    }
27162
}
27163
/**
27164
Create a completion source for a CSS dialect, providing a
27165
predicate for determining what kind of syntax node can act as a
27166
completable variable. This is used by language modes like Sass and
27167
Less to reuse this package's completion logic.
27168
*/
27169
const defineCSSCompletionSource = (isVariable) => context => {
27170
    let { state, pos } = context, node = syntaxTree(state).resolveInner(pos, -1);
27171
    let isDash = node.type.isError && node.from == node.to - 1 && state.doc.sliceString(node.from, node.to) == "-";
27172
    if (node.name == "PropertyName" ||
27173
        (isDash || node.name == "TagName") && /^(Block|Styles)$/.test(node.resolve(node.to).name))
27174
        return { from: node.from, options: properties(), validFor: identifier$1 };
27175
    if (node.name == "ValueName")
27176
        return { from: node.from, options: values, validFor: identifier$1 };
27177
    if (node.name == "PseudoClassName")
27178
        return { from: node.from, options: pseudoClasses, validFor: identifier$1 };
27179
    if (isVariable(node) || (context.explicit || isDash) && isVarArg(node, state.doc))
27180
        return { from: isVariable(node) || isDash ? node.from : pos,
27181
            options: variableNames(state.doc, astTop(node), isVariable),
27182
            validFor: variable };
27183
    if (node.name == "TagName") {
27184
        for (let { parent } = node; parent; parent = parent.parent)
27185
            if (parent.name == "Block")
27186
                return { from: node.from, options: properties(), validFor: identifier$1 };
27187
        return { from: node.from, options: tags, validFor: identifier$1 };
27188
    }
27189
    if (!context.explicit)
27190
        return null;
27191
    let above = node.resolve(pos), before = above.childBefore(pos);
27192
    if (before && before.name == ":" && above.name == "PseudoClassSelector")
27193
        return { from: pos, options: pseudoClasses, validFor: identifier$1 };
27194
    if (before && before.name == ":" && above.name == "Declaration" || above.name == "ArgList")
27195
        return { from: pos, options: values, validFor: identifier$1 };
27196
    if (above.name == "Block" || above.name == "Styles")
27197
        return { from: pos, options: properties(), validFor: identifier$1 };
27198
    return null;
27199
};
27200
/**
27201
CSS property, variable, and value keyword completion source.
27202
*/
27203
const cssCompletionSource = /*@__PURE__*/defineCSSCompletionSource(n => n.name == "VariableName");
27204
 
27205
/**
27206
A language provider based on the [Lezer CSS
27207
parser](https://github.com/lezer-parser/css), extended with
27208
highlighting and indentation information.
27209
*/
27210
const cssLanguage = /*@__PURE__*/LRLanguage.define({
27211
    name: "css",
27212
    parser: /*@__PURE__*/parser$2.configure({
27213
        props: [
27214
            /*@__PURE__*/indentNodeProp.add({
27215
                Declaration: /*@__PURE__*/continuedIndent()
27216
            }),
27217
            /*@__PURE__*/foldNodeProp.add({
27218
                "Block KeyframeList": foldInside
27219
            })
27220
        ]
27221
    }),
27222
    languageData: {
27223
        commentTokens: { block: { open: "/*", close: "*/" } },
27224
        indentOnInput: /^\s*\}$/,
27225
        wordChars: "-"
27226
    }
27227
});
27228
/**
27229
Language support for CSS.
27230
*/
27231
function css() {
27232
    return new LanguageSupport(cssLanguage, cssLanguage.data.of({ autocomplete: cssCompletionSource }));
27233
}
27234
 
27235
// This file was generated by lezer-generator. You probably shouldn't edit it.
27236
const noSemi = 309,
27237
  incdec = 1,
27238
  incdecPrefix = 2,
27239
  JSXStartTag = 3,
27240
  insertSemi = 310,
27241
  spaces = 312,
27242
  newline = 313,
27243
  LineComment = 4,
27244
  BlockComment = 5,
27245
  Dialect_jsx = 0;
27246
 
27247
/* Hand-written tokenizers for JavaScript tokens that can't be
27248
   expressed by lezer's built-in tokenizer. */
27249
 
27250
const space = [9, 10, 11, 12, 13, 32, 133, 160, 5760, 8192, 8193, 8194, 8195, 8196, 8197, 8198, 8199, 8200,
27251
               8201, 8202, 8232, 8233, 8239, 8287, 12288];
27252
 
27253
const braceR = 125, semicolon = 59, slash = 47, star = 42, plus = 43, minus = 45, lt = 60, comma = 44;
27254
 
27255
const trackNewline = new ContextTracker({
27256
  start: false,
27257
  shift(context, term) {
27258
    return term == LineComment || term == BlockComment || term == spaces ? context : term == newline
27259
  },
27260
  strict: false
27261
});
27262
 
27263
const insertSemicolon = new ExternalTokenizer((input, stack) => {
27264
  let {next} = input;
27265
  if (next == braceR || next == -1 || stack.context)
27266
    input.acceptToken(insertSemi);
27267
}, {contextual: true, fallback: true});
27268
 
27269
const noSemicolon = new ExternalTokenizer((input, stack) => {
27270
  let {next} = input, after;
27271
  if (space.indexOf(next) > -1) return
27272
  if (next == slash && ((after = input.peek(1)) == slash || after == star)) return
27273
  if (next != braceR && next != semicolon && next != -1 && !stack.context)
27274
    input.acceptToken(noSemi);
27275
}, {contextual: true});
27276
 
27277
const incdecToken = new ExternalTokenizer((input, stack) => {
27278
  let {next} = input;
27279
  if (next == plus || next == minus) {
27280
    input.advance();
27281
    if (next == input.next) {
27282
      input.advance();
27283
      let mayPostfix = !stack.context && stack.canShift(incdec);
27284
      input.acceptToken(mayPostfix ? incdec : incdecPrefix);
27285
    }
27286
  }
27287
}, {contextual: true});
27288
 
27289
function identifierChar(ch, start) {
27290
  return ch >= 65 && ch <= 90 || ch >= 97 && ch <= 122 || ch == 95 || ch >= 192 ||
27291
    !start && ch >= 48 && ch <= 57
27292
}
27293
 
27294
const jsx = new ExternalTokenizer((input, stack) => {
27295
  if (input.next != lt || !stack.dialectEnabled(Dialect_jsx)) return
27296
  input.advance();
27297
  if (input.next == slash) return
27298
  // Scan for an identifier followed by a comma or 'extends', don't
27299
  // treat this as a start tag if present.
27300
  let back = 0;
27301
  while (space.indexOf(input.next) > -1) { input.advance(); back++; }
27302
  if (identifierChar(input.next, true)) {
27303
    input.advance();
27304
    back++;
27305
    while (identifierChar(input.next, false)) { input.advance(); back++; }
27306
    while (space.indexOf(input.next) > -1) { input.advance(); back++; }
27307
    if (input.next == comma) return
27308
    for (let i = 0;; i++) {
27309
      if (i == 7) {
27310
        if (!identifierChar(input.next, true)) return
27311
        break
27312
      }
27313
      if (input.next != "extends".charCodeAt(i)) break
27314
      input.advance();
27315
      back++;
27316
    }
27317
  }
27318
  input.acceptToken(JSXStartTag, -back);
27319
});
27320
 
27321
const jsHighlight = styleTags({
27322
  "get set async static": tags$1.modifier,
27323
  "for while do if else switch try catch finally return throw break continue default case": tags$1.controlKeyword,
27324
  "in of await yield void typeof delete instanceof": tags$1.operatorKeyword,
27325
  "let var const using function class extends": tags$1.definitionKeyword,
27326
  "import export from": tags$1.moduleKeyword,
27327
  "with debugger as new": tags$1.keyword,
27328
  TemplateString: tags$1.special(tags$1.string),
27329
  super: tags$1.atom,
27330
  BooleanLiteral: tags$1.bool,
27331
  this: tags$1.self,
27332
  null: tags$1.null,
27333
  Star: tags$1.modifier,
27334
  VariableName: tags$1.variableName,
27335
  "CallExpression/VariableName TaggedTemplateExpression/VariableName": tags$1.function(tags$1.variableName),
27336
  VariableDefinition: tags$1.definition(tags$1.variableName),
27337
  Label: tags$1.labelName,
27338
  PropertyName: tags$1.propertyName,
27339
  PrivatePropertyName: tags$1.special(tags$1.propertyName),
27340
  "CallExpression/MemberExpression/PropertyName": tags$1.function(tags$1.propertyName),
27341
  "FunctionDeclaration/VariableDefinition": tags$1.function(tags$1.definition(tags$1.variableName)),
27342
  "ClassDeclaration/VariableDefinition": tags$1.definition(tags$1.className),
27343
  PropertyDefinition: tags$1.definition(tags$1.propertyName),
27344
  PrivatePropertyDefinition: tags$1.definition(tags$1.special(tags$1.propertyName)),
27345
  UpdateOp: tags$1.updateOperator,
27346
  "LineComment Hashbang": tags$1.lineComment,
27347
  BlockComment: tags$1.blockComment,
27348
  Number: tags$1.number,
27349
  String: tags$1.string,
27350
  Escape: tags$1.escape,
27351
  ArithOp: tags$1.arithmeticOperator,
27352
  LogicOp: tags$1.logicOperator,
27353
  BitOp: tags$1.bitwiseOperator,
27354
  CompareOp: tags$1.compareOperator,
27355
  RegExp: tags$1.regexp,
27356
  Equals: tags$1.definitionOperator,
27357
  Arrow: tags$1.function(tags$1.punctuation),
27358
  ": Spread": tags$1.punctuation,
27359
  "( )": tags$1.paren,
27360
  "[ ]": tags$1.squareBracket,
27361
  "{ }": tags$1.brace,
27362
  "InterpolationStart InterpolationEnd": tags$1.special(tags$1.brace),
27363
  ".": tags$1.derefOperator,
27364
  ", ;": tags$1.separator,
27365
  "@": tags$1.meta,
27366
 
27367
  TypeName: tags$1.typeName,
27368
  TypeDefinition: tags$1.definition(tags$1.typeName),
27369
  "type enum interface implements namespace module declare": tags$1.definitionKeyword,
27370
  "abstract global Privacy readonly override": tags$1.modifier,
27371
  "is keyof unique infer": tags$1.operatorKeyword,
27372
 
27373
  JSXAttributeValue: tags$1.attributeValue,
27374
  JSXText: tags$1.content,
27375
  "JSXStartTag JSXStartCloseTag JSXSelfCloseEndTag JSXEndTag": tags$1.angleBracket,
27376
  "JSXIdentifier JSXNameSpacedName": tags$1.tagName,
27377
  "JSXAttribute/JSXIdentifier JSXAttribute/JSXNameSpacedName": tags$1.attributeName,
27378
  "JSXBuiltin/JSXIdentifier": tags$1.standard(tags$1.tagName)
27379
});
27380
 
27381
// This file was generated by lezer-generator. You probably shouldn't edit it.
27382
const spec_identifier = {__proto__:null,export:18, as:23, from:31, default:34, async:39, function:40, extends:52, this:56, true:64, false:64, null:76, void:80, typeof:84, super:102, new:136, delete:152, yield:161, await:165, class:170, public:227, private:227, protected:227, readonly:229, instanceof:248, satisfies:251, in:252, const:254, import:286, keyof:339, unique:343, infer:349, is:385, abstract:405, implements:407, type:409, let:412, var:414, using:417, interface:423, enum:427, namespace:433, module:435, declare:439, global:443, for:462, of:471, while:474, with:478, do:482, if:486, else:488, switch:492, case:498, try:504, catch:508, finally:512, return:516, throw:520, break:524, continue:528, debugger:532};
27383
const spec_word = {__proto__:null,async:123, get:125, set:127, declare:187, public:189, private:189, protected:189, static:191, abstract:193, override:195, readonly:201, accessor:203, new:389};
27384
const spec_LessThan = {__proto__:null,"<":143};
27385
const parser$1 = LRParser.deserialize({
27386
  version: 14,
27387
  states: "$=WO%TQ^OOO%[Q^OOO'_Q`OOP(lOWOOO*zQ08SO'#ChO+RO!bO'#CiO+aO#tO'#CiO+oO?MpO'#D^O.QQ^O'#DdO.bQ^O'#DoO%[Q^O'#DyO0fQ^O'#EROOQ07b'#EZ'#EZO1PQWO'#EWOOQO'#El'#ElOOQO'#Ie'#IeO1XQWO'#GmO1dQWO'#EkO1iQWO'#EkO3kQ08SO'#JiO6[Q08SO'#JjO6xQWO'#FZO6}Q&jO'#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;eQ7R;mQ7y5_Q8g6ZQ8k6dQ8t;nQ8z;wQ8{;xQ9q8mQ:R9^Q:Y9oQ:k#SR<X<eR#[WR'V!el!tQ!r!v!y!z'['h'i'j-]-m1b5d5fS'R!e-TS-Q'S'ZR2h-ZR(u#xR(x#yQ!fQT-['[-]]!qQ!r'[-]1b5dQ#p]R'e:jY!uQ'[-]1b5dQ'g!rS'q!v!yS's!z5fS-l'h'iQ-n'jR2v-mT#kZ%cS#jZ%cS%im,gU(b#h#i#lS.Q(c(dQ.U(eQ0i+WQ2{.RU2|.S.T.VS6j2}3OR8n6kd#^W#W#Z%f(O(X*V+T-{/fr#gZm#h#i#l%c(c(d(e+W.R.S.T.V2}3O6kS*Y$y*^Q/m*ZQ1w,gQ2_,}Q4Q/iQ6X2VQ7X4RQ8f6YT<P'T+UV#aW%f*VU#`W%f*VS(P#W(XU(U#Z+T/fS-S'T+UT-v(O-{V'Y!e%g*WQ$lfR)t$qT)i$l)jR3x.}T*[$y*^T*d$|*VQ0m+`Q3Q.^Q5g1dQ6o3UQ8Q5jQ8q6nQ9`8PQ9r8pQ:T9bQ:]9tQ:b:UR:e:^nqOXst!Z#d%k&n&p&q&s,k,p1}2QQ&h!VR,`&etmOXst!U!V!Z#d%k&e&n&p&q&s,k,p1}2QR,g&kT%jm,gR1^,PR,_&cQ&R|R+w&SR+m%|T&l!W&oT&m!W&oT2P,p2Q",
27390
  nodeNames: "⚠ ArithOp ArithOp JSXStartTag LineComment BlockComment Script Hashbang ExportDeclaration export Star as VariableName String Escape from ; default FunctionDeclaration async function VariableDefinition > < TypeParamList TypeDefinition extends ThisType this LiteralType ArithOp Number BooleanLiteral TemplateType InterpolationEnd Interpolation InterpolationStart NullType null VoidType void TypeofType typeof MemberExpression . ?. PropertyName [ TemplateString Escape Interpolation super RegExp ] ArrayExpression Spread , } { ObjectExpression Property async get set PropertyDefinition Block : NewExpression new TypeArgList CompareOp < ) ( ArgList UnaryExpression delete LogicOp BitOp YieldExpression yield AwaitExpression await ParenthesizedExpression ClassExpression class ClassBody MethodDeclaration Decorator @ MemberExpression PrivatePropertyName CallExpression declare Privacy static abstract override PrivatePropertyDefinition PropertyDeclaration readonly accessor Optional TypeAnnotation Equals StaticBlock FunctionExpression ArrowFunction ParamList ParamList ArrayPattern ObjectPattern PatternProperty Privacy readonly Arrow MemberExpression BinaryExpression ArithOp ArithOp ArithOp ArithOp BitOp CompareOp instanceof satisfies in const CompareOp BitOp BitOp BitOp LogicOp LogicOp ConditionalExpression LogicOp LogicOp AssignmentExpression UpdateOp PostfixExpression CallExpression TaggedTemplateExpression DynamicImport import ImportMeta JSXElement JSXSelfCloseEndTag JSXSelfClosingTag JSXIdentifier JSXBuiltin JSXIdentifier JSXNamespacedName JSXMemberExpression JSXSpreadAttribute JSXAttribute JSXAttributeValue JSXEscape JSXEndTag JSXOpenTag JSXFragmentTag JSXText JSXEscape JSXStartCloseTag JSXCloseTag PrefixCast ArrowFunction TypeParamList SequenceExpression KeyofType keyof UniqueType unique ImportType InferredType infer TypeName ParenthesizedType FunctionSignature ParamList NewSignature IndexedType TupleType Label ArrayType ReadonlyType ObjectType MethodType PropertyType IndexSignature PropertyDefinition CallSignature TypePredicate is NewSignature new UnionType LogicOp IntersectionType LogicOp ConditionalType ParameterizedType ClassDeclaration abstract implements type VariableDeclaration let var using TypeAliasDeclaration InterfaceDeclaration interface EnumDeclaration enum EnumBody NamespaceDeclaration namespace module AmbientDeclaration declare GlobalDeclaration global ClassDeclaration ClassBody AmbientFunctionDeclaration ExportGroup VariableName VariableName ImportDeclaration ImportGroup ForStatement for ForSpec ForInSpec ForOfSpec of WhileStatement while WithStatement with DoStatement do IfStatement if else SwitchStatement switch SwitchBody CaseLabel case DefaultLabel TryStatement try CatchClause catch FinallyClause finally ReturnStatement return ThrowStatement throw BreakStatement break ContinueStatement continue DebuggerStatement debugger LabeledStatement ExpressionStatement SingleExpression SingleClassItem",
27391
  maxTerm: 372,
27392
  context: trackNewline,
27393
  nodeProps: [
27394
    ["isolate", -8,4,5,13,33,35,48,50,52,""],
27395
    ["group", -26,8,16,18,65,201,205,209,210,212,215,218,228,230,236,238,240,242,245,251,257,259,261,263,265,267,268,"Statement",-32,12,13,28,31,32,38,48,51,52,54,59,67,75,79,81,83,84,106,107,116,117,134,137,139,140,141,142,144,145,164,165,167,"Expression",-23,27,29,33,37,39,41,168,170,172,173,175,176,177,179,180,181,183,184,185,195,197,199,200,"Type",-3,87,99,105,"ClassItem"],
27396
    ["openedBy", 22,"<",34,"InterpolationStart",53,"[",57,"{",72,"(",157,"JSXStartCloseTag"],
27397
    ["closedBy", 23,">",36,"InterpolationEnd",47,"]",58,"}",73,")",162,"JSXEndTag"]
27398
  ],
27399
  propSources: [jsHighlight],
27400
  skippedNodes: [0,4,5,271],
27401
  repeatNodeCount: 37,
27402
  tokenData: "$HR(CSR!bOX%ZXY+gYZ-yZ[+g[]%Z]^.c^p%Zpq+gqr/mrs3cst:_tuEruvJSvwLkwx! Yxy!'iyz!(sz{!)}{|!,q|}!.O}!O!,q!O!P!/Y!P!Q!9j!Q!R#:O!R![#<_![!]#I_!]!^#Jk!^!_#Ku!_!`$![!`!a$$v!a!b$*T!b!c$.S!c!}Er!}#O$/^#O#P$0h#P#Q$6P#Q#R$7Z#R#SEr#S#T$8h#T#o$9r#o#p$>S#p#q$>x#q#r$@Y#r#s$Af#s$f%Z$f$g+g$g#BYEr#BY#BZ$Bp#BZ$ISEr$IS$I_$Bp$I_$I|Er$I|$I}$E{$I}$JO$E{$JO$JTEr$JT$JU$Bp$JU$KVEr$KV$KW$Bp$KW&FUEr&FU&FV$Bp&FV;'SEr;'S;=`I|<%l?HTEr?HT?HU$Bp?HUOEr(n%d_$f&j(Op(R!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z&j&hT$f&jO!^&c!_#o&c#p;'S&c;'S;=`&w<%lO&c&j&zP;=`<%l&c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, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, insertSemicolon, new LocalTokenGroup("$S~RRtu[#O#Pg#S#T#|~_P#o#pb~gOt~~jVO#i!P#i#j!U#j#l!P#l#m!q#m;'S!P;'S;=`#v<%lO!P~!UO!R~~!XS!Q![!e!c!i!e#T#Z!e#o#p#Z~!hR!Q![!q!c!i!q#T#Z!q~!tR!Q![!}!c!i!}#T#Z!}~#QR!Q![!P!c!i!P#T#Z!P~#^R!Q![#g!c!i#g#T#Z#g~#jS!Q![#g!c!i#g#T#Z#g#q#r!P~#yP;=`<%l!P~$RO(Z~~", 141, 332), new LocalTokenGroup("j~RQYZXz{^~^O'x~~aP!P!Qd~iO'y~~", 25, 315)],
27404
  topRules: {"Script":[0,6],"SingleExpression":[1,269],"SingleClassItem":[2,270]},
27405
  dialects: {jsx: 0, ts: 14826},
27406
  dynamicPrecedences: {"69":1,"79":1,"81":1,"165":1,"193":1},
27407
  specialized: [{term: 319, get: (value) => spec_identifier[value] || -1},{term: 334, get: (value) => spec_word[value] || -1},{term: 70, get: (value) => spec_LessThan[value] || -1}],
27408
  tokenPrec: 14850
27409
});
27410
 
27411
/**
27412
A collection of JavaScript-related
27413
[snippets](https://codemirror.net/6/docs/ref/#autocomplete.snippet).
27414
*/
27415
const snippets = [
27416
    /*@__PURE__*/snippetCompletion("function ${name}(${params}) {\n\t${}\n}", {
27417
        label: "function",
27418
        detail: "definition",
27419
        type: "keyword"
27420
    }),
27421
    /*@__PURE__*/snippetCompletion("for (let ${index} = 0; ${index} < ${bound}; ${index}++) {\n\t${}\n}", {
27422
        label: "for",
27423
        detail: "loop",
27424
        type: "keyword"
27425
    }),
27426
    /*@__PURE__*/snippetCompletion("for (let ${name} of ${collection}) {\n\t${}\n}", {
27427
        label: "for",
27428
        detail: "of loop",
27429
        type: "keyword"
27430
    }),
27431
    /*@__PURE__*/snippetCompletion("do {\n\t${}\n} while (${})", {
27432
        label: "do",
27433
        detail: "loop",
27434
        type: "keyword"
27435
    }),
27436
    /*@__PURE__*/snippetCompletion("while (${}) {\n\t${}\n}", {
27437
        label: "while",
27438
        detail: "loop",
27439
        type: "keyword"
27440
    }),
27441
    /*@__PURE__*/snippetCompletion("try {\n\t${}\n} catch (${error}) {\n\t${}\n}", {
27442
        label: "try",
27443
        detail: "/ catch block",
27444
        type: "keyword"
27445
    }),
27446
    /*@__PURE__*/snippetCompletion("if (${}) {\n\t${}\n}", {
27447
        label: "if",
27448
        detail: "block",
27449
        type: "keyword"
27450
    }),
27451
    /*@__PURE__*/snippetCompletion("if (${}) {\n\t${}\n} else {\n\t${}\n}", {
27452
        label: "if",
27453
        detail: "/ else block",
27454
        type: "keyword"
27455
    }),
27456
    /*@__PURE__*/snippetCompletion("class ${name} {\n\tconstructor(${params}) {\n\t\t${}\n\t}\n}", {
27457
        label: "class",
27458
        detail: "definition",
27459
        type: "keyword"
27460
    }),
27461
    /*@__PURE__*/snippetCompletion("import {${names}} from \"${module}\"\n${}", {
27462
        label: "import",
27463
        detail: "named",
27464
        type: "keyword"
27465
    }),
27466
    /*@__PURE__*/snippetCompletion("import ${name} from \"${module}\"\n${}", {
27467
        label: "import",
27468
        detail: "default",
27469
        type: "keyword"
27470
    })
27471
];
27472
/**
27473
A collection of snippet completions for TypeScript. Includes the
27474
JavaScript [snippets](https://codemirror.net/6/docs/ref/#lang-javascript.snippets).
27475
*/
27476
const typescriptSnippets = /*@__PURE__*/snippets.concat([
27477
    /*@__PURE__*/snippetCompletion("interface ${name} {\n\t${}\n}", {
27478
        label: "interface",
27479
        detail: "definition",
27480
        type: "keyword"
27481
    }),
27482
    /*@__PURE__*/snippetCompletion("type ${name} = ${type}", {
27483
        label: "type",
27484
        detail: "definition",
27485
        type: "keyword"
27486
    }),
27487
    /*@__PURE__*/snippetCompletion("enum ${name} {\n\t${}\n}", {
27488
        label: "enum",
27489
        detail: "definition",
27490
        type: "keyword"
27491
    })
27492
]);
27493
 
27494
const cache = /*@__PURE__*/new NodeWeakMap();
27495
const ScopeNodes = /*@__PURE__*/new Set([
27496
    "Script", "Block",
27497
    "FunctionExpression", "FunctionDeclaration", "ArrowFunction", "MethodDeclaration",
27498
    "ForStatement"
27499
]);
27500
function defID(type) {
27501
    return (node, def) => {
27502
        let id = node.node.getChild("VariableDefinition");
27503
        if (id)
27504
            def(id, type);
27505
        return true;
27506
    };
27507
}
27508
const functionContext = ["FunctionDeclaration"];
27509
const gatherCompletions = {
27510
    FunctionDeclaration: /*@__PURE__*/defID("function"),
27511
    ClassDeclaration: /*@__PURE__*/defID("class"),
27512
    ClassExpression: () => true,
27513
    EnumDeclaration: /*@__PURE__*/defID("constant"),
27514
    TypeAliasDeclaration: /*@__PURE__*/defID("type"),
27515
    NamespaceDeclaration: /*@__PURE__*/defID("namespace"),
27516
    VariableDefinition(node, def) { if (!node.matchContext(functionContext))
27517
        def(node, "variable"); },
27518
    TypeDefinition(node, def) { def(node, "type"); },
27519
    __proto__: null
27520
};
27521
function getScope(doc, node) {
27522
    let cached = cache.get(node);
27523
    if (cached)
27524
        return cached;
27525
    let completions = [], top = true;
27526
    function def(node, type) {
27527
        let name = doc.sliceString(node.from, node.to);
27528
        completions.push({ label: name, type });
27529
    }
27530
    node.cursor(IterMode.IncludeAnonymous).iterate(node => {
27531
        if (top) {
27532
            top = false;
27533
        }
27534
        else if (node.name) {
27535
            let gather = gatherCompletions[node.name];
27536
            if (gather && gather(node, def) || ScopeNodes.has(node.name))
27537
                return false;
27538
        }
27539
        else if (node.to - node.from > 8192) {
27540
            // Allow caching for bigger internal nodes
27541
            for (let c of getScope(doc, node.node))
27542
                completions.push(c);
27543
            return false;
27544
        }
27545
    });
27546
    cache.set(node, completions);
27547
    return completions;
27548
}
27549
const Identifier$1 = /^[\w$\xa1-\uffff][\w$\d\xa1-\uffff]*$/;
27550
const dontComplete = [
27551
    "TemplateString", "String", "RegExp",
27552
    "LineComment", "BlockComment",
27553
    "VariableDefinition", "TypeDefinition", "Label",
27554
    "PropertyDefinition", "PropertyName",
27555
    "PrivatePropertyDefinition", "PrivatePropertyName",
27556
    ".", "?."
27557
];
27558
/**
27559
Completion source that looks up locally defined names in
27560
JavaScript code.
27561
*/
27562
function localCompletionSource(context) {
27563
    let inner = syntaxTree(context.state).resolveInner(context.pos, -1);
27564
    if (dontComplete.indexOf(inner.name) > -1)
27565
        return null;
27566
    let isWord = inner.name == "VariableName" ||
27567
        inner.to - inner.from < 20 && Identifier$1.test(context.state.sliceDoc(inner.from, inner.to));
27568
    if (!isWord && !context.explicit)
27569
        return null;
27570
    let options = [];
27571
    for (let pos = inner; pos; pos = pos.parent) {
27572
        if (ScopeNodes.has(pos.name))
27573
            options = options.concat(getScope(context.state.doc, pos));
27574
    }
27575
    return {
27576
        options,
27577
        from: isWord ? inner.from : context.pos,
27578
        validFor: Identifier$1
27579
    };
27580
}
27581
 
27582
/**
27583
A language provider based on the [Lezer JavaScript
27584
parser](https://github.com/lezer-parser/javascript), extended with
27585
highlighting and indentation information.
27586
*/
27587
const javascriptLanguage = /*@__PURE__*/LRLanguage.define({
27588
    name: "javascript",
27589
    parser: /*@__PURE__*/parser$1.configure({
27590
        props: [
27591
            /*@__PURE__*/indentNodeProp.add({
27592
                IfStatement: /*@__PURE__*/continuedIndent({ except: /^\s*({|else\b)/ }),
27593
                TryStatement: /*@__PURE__*/continuedIndent({ except: /^\s*({|catch\b|finally\b)/ }),
27594
                LabeledStatement: flatIndent,
27595
                SwitchBody: context => {
27596
                    let after = context.textAfter, closed = /^\s*\}/.test(after), isCase = /^\s*(case|default)\b/.test(after);
27597
                    return context.baseIndent + (closed ? 0 : isCase ? 1 : 2) * context.unit;
27598
                },
27599
                Block: /*@__PURE__*/delimitedIndent({ closing: "}" }),
27600
                ArrowFunction: cx => cx.baseIndent + cx.unit,
27601
                "TemplateString BlockComment": () => null,
27602
                "Statement Property": /*@__PURE__*/continuedIndent({ except: /^{/ }),
27603
                JSXElement(context) {
27604
                    let closed = /^\s*<\//.test(context.textAfter);
27605
                    return context.lineIndent(context.node.from) + (closed ? 0 : context.unit);
27606
                },
27607
                JSXEscape(context) {
27608
                    let closed = /\s*\}/.test(context.textAfter);
27609
                    return context.lineIndent(context.node.from) + (closed ? 0 : context.unit);
27610
                },
27611
                "JSXOpenTag JSXSelfClosingTag"(context) {
27612
                    return context.column(context.node.from) + context.unit;
27613
                }
27614
            }),
27615
            /*@__PURE__*/foldNodeProp.add({
27616
                "Block ClassBody SwitchBody EnumBody ObjectExpression ArrayExpression ObjectType": foldInside,
27617
                BlockComment(tree) { return { from: tree.from + 2, to: tree.to - 2 }; }
27618
            })
27619
        ]
27620
    }),
27621
    languageData: {
27622
        closeBrackets: { brackets: ["(", "[", "{", "'", '"', "`"] },
27623
        commentTokens: { line: "//", block: { open: "/*", close: "*/" } },
27624
        indentOnInput: /^\s*(?:case |default:|\{|\}|<\/)$/,
27625
        wordChars: "$"
27626
    }
27627
});
27628
const jsxSublanguage = {
27629
    test: node => /^JSX/.test(node.name),
27630
    facet: /*@__PURE__*/defineLanguageFacet({ commentTokens: { block: { open: "{/*", close: "*/}" } } })
27631
};
27632
/**
27633
A language provider for TypeScript.
27634
*/
27635
const typescriptLanguage = /*@__PURE__*/javascriptLanguage.configure({ dialect: "ts" }, "typescript");
27636
/**
27637
Language provider for JSX.
27638
*/
27639
const jsxLanguage = /*@__PURE__*/javascriptLanguage.configure({
27640
    dialect: "jsx",
27641
    props: [/*@__PURE__*/sublanguageProp.add(n => n.isTop ? [jsxSublanguage] : undefined)]
27642
});
27643
/**
27644
Language provider for JSX + TypeScript.
27645
*/
27646
const tsxLanguage = /*@__PURE__*/javascriptLanguage.configure({
27647
    dialect: "jsx ts",
27648
    props: [/*@__PURE__*/sublanguageProp.add(n => n.isTop ? [jsxSublanguage] : undefined)]
27649
}, "typescript");
27650
let kwCompletion = (name) => ({ label: name, type: "keyword" });
27651
const keywords = /*@__PURE__*/"break case const continue default delete export extends false finally in instanceof let new return static super switch this throw true typeof var yield".split(" ").map(kwCompletion);
27652
const typescriptKeywords = /*@__PURE__*/keywords.concat(/*@__PURE__*/["declare", "implements", "private", "protected", "public"].map(kwCompletion));
27653
/**
27654
JavaScript support. Includes [snippet](https://codemirror.net/6/docs/ref/#lang-javascript.snippets)
27655
and local variable completion.
27656
*/
27657
function javascript(config = {}) {
27658
    let lang = config.jsx ? (config.typescript ? tsxLanguage : jsxLanguage)
27659
        : config.typescript ? typescriptLanguage : javascriptLanguage;
27660
    let completions = config.typescript ? typescriptSnippets.concat(typescriptKeywords) : snippets.concat(keywords);
27661
    return new LanguageSupport(lang, [
27662
        javascriptLanguage.data.of({
27663
            autocomplete: ifNotIn(dontComplete, completeFromList(completions))
27664
        }),
27665
        javascriptLanguage.data.of({
27666
            autocomplete: localCompletionSource
27667
        }),
27668
        config.jsx ? autoCloseTags$2 : [],
27669
    ]);
27670
}
27671
function findOpenTag(node) {
27672
    for (;;) {
27673
        if (node.name == "JSXOpenTag" || node.name == "JSXSelfClosingTag" || node.name == "JSXFragmentTag")
27674
            return node;
27675
        if (node.name == "JSXEscape" || !node.parent)
27676
            return null;
27677
        node = node.parent;
27678
    }
27679
}
27680
function elementName$3(doc, tree, max = doc.length) {
27681
    for (let ch = tree === null || tree === void 0 ? void 0 : tree.firstChild; ch; ch = ch.nextSibling) {
27682
        if (ch.name == "JSXIdentifier" || ch.name == "JSXBuiltin" || ch.name == "JSXNamespacedName" ||
27683
            ch.name == "JSXMemberExpression")
27684
            return doc.sliceString(ch.from, Math.min(ch.to, max));
27685
    }
27686
    return "";
27687
}
27688
const android = typeof navigator == "object" && /*@__PURE__*//Android\b/.test(navigator.userAgent);
27689
/**
27690
Extension that will automatically insert JSX close tags when a `>` or
27691
`/` is typed.
27692
*/
27693
const autoCloseTags$2 = /*@__PURE__*/EditorView.inputHandler.of((view, from, to, text, defaultInsert) => {
27694
    if ((android ? view.composing : view.compositionStarted) || view.state.readOnly ||
27695
        from != to || (text != ">" && text != "/") ||
27696
        !javascriptLanguage.isActiveAt(view.state, from, -1))
27697
        return false;
27698
    let base = defaultInsert(), { state } = base;
27699
    let closeTags = state.changeByRange(range => {
27700
        var _a;
27701
        let { head } = range, around = syntaxTree(state).resolveInner(head - 1, -1), name;
27702
        if (around.name == "JSXStartTag")
27703
            around = around.parent;
27704
        if (state.doc.sliceString(head - 1, head) != text || around.name == "JSXAttributeValue" && around.to > head) ;
27705
        else if (text == ">" && around.name == "JSXFragmentTag") {
27706
            return { range, changes: { from: head, insert: `</>` } };
27707
        }
27708
        else if (text == "/" && around.name == "JSXStartCloseTag") {
27709
            let empty = around.parent, base = empty.parent;
27710
            if (base && empty.from == head - 2 &&
27711
                ((name = elementName$3(state.doc, base.firstChild, head)) || ((_a = base.firstChild) === null || _a === void 0 ? void 0 : _a.name) == "JSXFragmentTag")) {
27712
                let insert = `${name}>`;
27713
                return { range: EditorSelection.cursor(head + insert.length, -1), changes: { from: head, insert } };
27714
            }
27715
        }
27716
        else if (text == ">") {
27717
            let openTag = findOpenTag(around);
27718
            if (openTag && openTag.name == "JSXOpenTag" &&
27719
                !/^\/?>|^<\//.test(state.doc.sliceString(head, head + 2)) &&
27720
                (name = elementName$3(state.doc, openTag, head)))
27721
                return { range, changes: { from: head, insert: `</${name}>` } };
27722
        }
27723
        return { range };
27724
    });
27725
    if (closeTags.changes.empty)
27726
        return false;
27727
    view.dispatch([
27728
        base,
27729
        state.update(closeTags, { userEvent: "input.complete", scrollIntoView: true })
27730
    ]);
27731
    return true;
27732
});
27733
 
27734
const Targets = ["_blank", "_self", "_top", "_parent"];
27735
const Charsets = ["ascii", "utf-8", "utf-16", "latin1", "latin1"];
27736
const Methods = ["get", "post", "put", "delete"];
27737
const Encs = ["application/x-www-form-urlencoded", "multipart/form-data", "text/plain"];
27738
const Bool = ["true", "false"];
27739
const S = {}; // Empty tag spec
27740
const Tags = {
27741
    a: {
27742
        attrs: {
27743
            href: null, ping: null, type: null,
27744
            media: null,
27745
            target: Targets,
27746
            hreflang: null
27747
        }
27748
    },
27749
    abbr: S,
27750
    address: S,
27751
    area: {
27752
        attrs: {
27753
            alt: null, coords: null, href: null, target: null, ping: null,
27754
            media: null, hreflang: null, type: null,
27755
            shape: ["default", "rect", "circle", "poly"]
27756
        }
27757
    },
27758
    article: S,
27759
    aside: S,
27760
    audio: {
27761
        attrs: {
27762
            src: null, mediagroup: null,
27763
            crossorigin: ["anonymous", "use-credentials"],
27764
            preload: ["none", "metadata", "auto"],
27765
            autoplay: ["autoplay"],
27766
            loop: ["loop"],
27767
            controls: ["controls"]
27768
        }
27769
    },
27770
    b: S,
27771
    base: { attrs: { href: null, target: Targets } },
27772
    bdi: S,
27773
    bdo: S,
27774
    blockquote: { attrs: { cite: null } },
27775
    body: S,
27776
    br: S,
27777
    button: {
27778
        attrs: {
27779
            form: null, formaction: null, name: null, value: null,
27780
            autofocus: ["autofocus"],
27781
            disabled: ["autofocus"],
27782
            formenctype: Encs,
27783
            formmethod: Methods,
27784
            formnovalidate: ["novalidate"],
27785
            formtarget: Targets,
27786
            type: ["submit", "reset", "button"]
27787
        }
27788
    },
27789
    canvas: { attrs: { width: null, height: null } },
27790
    caption: S,
27791
    center: S,
27792
    cite: S,
27793
    code: S,
27794
    col: { attrs: { span: null } },
27795
    colgroup: { attrs: { span: null } },
27796
    command: {
27797
        attrs: {
27798
            type: ["command", "checkbox", "radio"],
27799
            label: null, icon: null, radiogroup: null, command: null, title: null,
27800
            disabled: ["disabled"],
27801
            checked: ["checked"]
27802
        }
27803
    },
27804
    data: { attrs: { value: null } },
27805
    datagrid: { attrs: { disabled: ["disabled"], multiple: ["multiple"] } },
27806
    datalist: { attrs: { data: null } },
27807
    dd: S,
27808
    del: { attrs: { cite: null, datetime: null } },
27809
    details: { attrs: { open: ["open"] } },
27810
    dfn: S,
27811
    div: S,
27812
    dl: S,
27813
    dt: S,
27814
    em: S,
27815
    embed: { attrs: { src: null, type: null, width: null, height: null } },
27816
    eventsource: { attrs: { src: null } },
27817
    fieldset: { attrs: { disabled: ["disabled"], form: null, name: null } },
27818
    figcaption: S,
27819
    figure: S,
27820
    footer: S,
27821
    form: {
27822
        attrs: {
27823
            action: null, name: null,
27824
            "accept-charset": Charsets,
27825
            autocomplete: ["on", "off"],
27826
            enctype: Encs,
27827
            method: Methods,
27828
            novalidate: ["novalidate"],
27829
            target: Targets
27830
        }
27831
    },
27832
    h1: S, h2: S, h3: S, h4: S, h5: S, h6: S,
27833
    head: {
27834
        children: ["title", "base", "link", "style", "meta", "script", "noscript", "command"]
27835
    },
27836
    header: S,
27837
    hgroup: S,
27838
    hr: S,
27839
    html: {
27840
        attrs: { manifest: null }
27841
    },
27842
    i: S,
27843
    iframe: {
27844
        attrs: {
27845
            src: null, srcdoc: null, name: null, width: null, height: null,
27846
            sandbox: ["allow-top-navigation", "allow-same-origin", "allow-forms", "allow-scripts"],
27847
            seamless: ["seamless"]
27848
        }
27849
    },
27850
    img: {
27851
        attrs: {
27852
            alt: null, src: null, ismap: null, usemap: null, width: null, height: null,
27853
            crossorigin: ["anonymous", "use-credentials"]
27854
        }
27855
    },
27856
    input: {
27857
        attrs: {
27858
            alt: null, dirname: null, form: null, formaction: null,
27859
            height: null, list: null, max: null, maxlength: null, min: null,
27860
            name: null, pattern: null, placeholder: null, size: null, src: null,
27861
            step: null, value: null, width: null,
27862
            accept: ["audio/*", "video/*", "image/*"],
27863
            autocomplete: ["on", "off"],
27864
            autofocus: ["autofocus"],
27865
            checked: ["checked"],
27866
            disabled: ["disabled"],
27867
            formenctype: Encs,
27868
            formmethod: Methods,
27869
            formnovalidate: ["novalidate"],
27870
            formtarget: Targets,
27871
            multiple: ["multiple"],
27872
            readonly: ["readonly"],
27873
            required: ["required"],
27874
            type: ["hidden", "text", "search", "tel", "url", "email", "password", "datetime", "date", "month",
27875
                "week", "time", "datetime-local", "number", "range", "color", "checkbox", "radio",
27876
                "file", "submit", "image", "reset", "button"]
27877
        }
27878
    },
27879
    ins: { attrs: { cite: null, datetime: null } },
27880
    kbd: S,
27881
    keygen: {
27882
        attrs: {
27883
            challenge: null, form: null, name: null,
27884
            autofocus: ["autofocus"],
27885
            disabled: ["disabled"],
27886
            keytype: ["RSA"]
27887
        }
27888
    },
27889
    label: { attrs: { for: null, form: null } },
27890
    legend: S,
27891
    li: { attrs: { value: null } },
27892
    link: {
27893
        attrs: {
27894
            href: null, type: null,
27895
            hreflang: null,
27896
            media: null,
27897
            sizes: ["all", "16x16", "16x16 32x32", "16x16 32x32 64x64"]
27898
        }
27899
    },
27900
    map: { attrs: { name: null } },
27901
    mark: S,
27902
    menu: { attrs: { label: null, type: ["list", "context", "toolbar"] } },
27903
    meta: {
27904
        attrs: {
27905
            content: null,
27906
            charset: Charsets,
27907
            name: ["viewport", "application-name", "author", "description", "generator", "keywords"],
27908
            "http-equiv": ["content-language", "content-type", "default-style", "refresh"]
27909
        }
27910
    },
27911
    meter: { attrs: { value: null, min: null, low: null, high: null, max: null, optimum: null } },
27912
    nav: S,
27913
    noscript: S,
27914
    object: {
27915
        attrs: {
27916
            data: null, type: null, name: null, usemap: null, form: null, width: null, height: null,
27917
            typemustmatch: ["typemustmatch"]
27918
        }
27919
    },
27920
    ol: { attrs: { reversed: ["reversed"], start: null, type: ["1", "a", "A", "i", "I"] },
27921
        children: ["li", "script", "template", "ul", "ol"] },
27922
    optgroup: { attrs: { disabled: ["disabled"], label: null } },
27923
    option: { attrs: { disabled: ["disabled"], label: null, selected: ["selected"], value: null } },
27924
    output: { attrs: { for: null, form: null, name: null } },
27925
    p: S,
27926
    param: { attrs: { name: null, value: null } },
27927
    pre: S,
27928
    progress: { attrs: { value: null, max: null } },
27929
    q: { attrs: { cite: null } },
27930
    rp: S,
27931
    rt: S,
27932
    ruby: S,
27933
    samp: S,
27934
    script: {
27935
        attrs: {
27936
            type: ["text/javascript"],
27937
            src: null,
27938
            async: ["async"],
27939
            defer: ["defer"],
27940
            charset: Charsets
27941
        }
27942
    },
27943
    section: S,
27944
    select: {
27945
        attrs: {
27946
            form: null, name: null, size: null,
27947
            autofocus: ["autofocus"],
27948
            disabled: ["disabled"],
27949
            multiple: ["multiple"]
27950
        }
27951
    },
27952
    slot: { attrs: { name: null } },
27953
    small: S,
27954
    source: { attrs: { src: null, type: null, media: null } },
27955
    span: S,
27956
    strong: S,
27957
    style: {
27958
        attrs: {
27959
            type: ["text/css"],
27960
            media: null,
27961
            scoped: null
27962
        }
27963
    },
27964
    sub: S,
27965
    summary: S,
27966
    sup: S,
27967
    table: S,
27968
    tbody: S,
27969
    td: { attrs: { colspan: null, rowspan: null, headers: null } },
27970
    template: S,
27971
    textarea: {
27972
        attrs: {
27973
            dirname: null, form: null, maxlength: null, name: null, placeholder: null,
27974
            rows: null, cols: null,
27975
            autofocus: ["autofocus"],
27976
            disabled: ["disabled"],
27977
            readonly: ["readonly"],
27978
            required: ["required"],
27979
            wrap: ["soft", "hard"]
27980
        }
27981
    },
27982
    tfoot: S,
27983
    th: { attrs: { colspan: null, rowspan: null, headers: null, scope: ["row", "col", "rowgroup", "colgroup"] } },
27984
    thead: S,
27985
    time: { attrs: { datetime: null } },
27986
    title: S,
27987
    tr: S,
27988
    track: {
27989
        attrs: {
27990
            src: null, label: null, default: null,
27991
            kind: ["subtitles", "captions", "descriptions", "chapters", "metadata"],
27992
            srclang: null
27993
        }
27994
    },
27995
    ul: { children: ["li", "script", "template", "ul", "ol"] },
27996
    var: S,
27997
    video: {
27998
        attrs: {
27999
            src: null, poster: null, width: null, height: null,
28000
            crossorigin: ["anonymous", "use-credentials"],
28001
            preload: ["auto", "metadata", "none"],
28002
            autoplay: ["autoplay"],
28003
            mediagroup: ["movie"],
28004
            muted: ["muted"],
28005
            controls: ["controls"]
28006
        }
28007
    },
28008
    wbr: S
28009
};
28010
const GlobalAttrs = {
28011
    accesskey: null,
28012
    class: null,
28013
    contenteditable: Bool,
28014
    contextmenu: null,
28015
    dir: ["ltr", "rtl", "auto"],
28016
    draggable: ["true", "false", "auto"],
28017
    dropzone: ["copy", "move", "link", "string:", "file:"],
28018
    hidden: ["hidden"],
28019
    id: null,
28020
    inert: ["inert"],
28021
    itemid: null,
28022
    itemprop: null,
28023
    itemref: null,
28024
    itemscope: ["itemscope"],
28025
    itemtype: null,
28026
    lang: ["ar", "bn", "de", "en-GB", "en-US", "es", "fr", "hi", "id", "ja", "pa", "pt", "ru", "tr", "zh"],
28027
    spellcheck: Bool,
28028
    autocorrect: Bool,
28029
    autocapitalize: Bool,
28030
    style: null,
28031
    tabindex: null,
28032
    title: null,
28033
    translate: ["yes", "no"],
28034
    rel: ["stylesheet", "alternate", "author", "bookmark", "help", "license", "next", "nofollow", "noreferrer", "prefetch", "prev", "search", "tag"],
28035
    role: /*@__PURE__*/"alert application article banner button cell checkbox complementary contentinfo dialog document feed figure form grid gridcell heading img list listbox listitem main navigation region row rowgroup search switch tab table tabpanel textbox timer".split(" "),
28036
    "aria-activedescendant": null,
28037
    "aria-atomic": Bool,
28038
    "aria-autocomplete": ["inline", "list", "both", "none"],
28039
    "aria-busy": Bool,
28040
    "aria-checked": ["true", "false", "mixed", "undefined"],
28041
    "aria-controls": null,
28042
    "aria-describedby": null,
28043
    "aria-disabled": Bool,
28044
    "aria-dropeffect": null,
28045
    "aria-expanded": ["true", "false", "undefined"],
28046
    "aria-flowto": null,
28047
    "aria-grabbed": ["true", "false", "undefined"],
28048
    "aria-haspopup": Bool,
28049
    "aria-hidden": Bool,
28050
    "aria-invalid": ["true", "false", "grammar", "spelling"],
28051
    "aria-label": null,
28052
    "aria-labelledby": null,
28053
    "aria-level": null,
28054
    "aria-live": ["off", "polite", "assertive"],
28055
    "aria-multiline": Bool,
28056
    "aria-multiselectable": Bool,
28057
    "aria-owns": null,
28058
    "aria-posinset": null,
28059
    "aria-pressed": ["true", "false", "mixed", "undefined"],
28060
    "aria-readonly": Bool,
28061
    "aria-relevant": null,
28062
    "aria-required": Bool,
28063
    "aria-selected": ["true", "false", "undefined"],
28064
    "aria-setsize": null,
28065
    "aria-sort": ["ascending", "descending", "none", "other"],
28066
    "aria-valuemax": null,
28067
    "aria-valuemin": null,
28068
    "aria-valuenow": null,
28069
    "aria-valuetext": null
28070
};
28071
const eventAttributes = /*@__PURE__*/("beforeunload copy cut dragstart dragover dragleave dragenter dragend " +
28072
    "drag paste focus blur change click load mousedown mouseenter mouseleave " +
28073
    "mouseup keydown keyup resize scroll unload").split(" ").map(n => "on" + n);
28074
for (let a of eventAttributes)
28075
    GlobalAttrs[a] = null;
28076
class Schema {
28077
    constructor(extraTags, extraAttrs) {
28078
        this.tags = Object.assign(Object.assign({}, Tags), extraTags);
28079
        this.globalAttrs = Object.assign(Object.assign({}, GlobalAttrs), extraAttrs);
28080
        this.allTags = Object.keys(this.tags);
28081
        this.globalAttrNames = Object.keys(this.globalAttrs);
28082
    }
28083
}
28084
Schema.default = /*@__PURE__*/new Schema;
28085
function elementName$2(doc, tree, max = doc.length) {
28086
    if (!tree)
28087
        return "";
28088
    let tag = tree.firstChild;
28089
    let name = tag && tag.getChild("TagName");
28090
    return name ? doc.sliceString(name.from, Math.min(name.to, max)) : "";
28091
}
28092
function findParentElement$1(tree, skip = false) {
28093
    for (; tree; tree = tree.parent)
28094
        if (tree.name == "Element") {
28095
            if (skip)
28096
                skip = false;
28097
            else
28098
                return tree;
28099
        }
28100
    return null;
28101
}
28102
function allowedChildren(doc, tree, schema) {
28103
    let parentInfo = schema.tags[elementName$2(doc, findParentElement$1(tree))];
28104
    return (parentInfo === null || parentInfo === void 0 ? void 0 : parentInfo.children) || schema.allTags;
28105
}
28106
function openTags(doc, tree) {
28107
    let open = [];
28108
    for (let parent = findParentElement$1(tree); parent && !parent.type.isTop; parent = findParentElement$1(parent.parent)) {
28109
        let tagName = elementName$2(doc, parent);
28110
        if (tagName && parent.lastChild.name == "CloseTag")
28111
            break;
28112
        if (tagName && open.indexOf(tagName) < 0 && (tree.name == "EndTag" || tree.from >= parent.firstChild.to))
28113
            open.push(tagName);
28114
    }
28115
    return open;
28116
}
28117
const identifier = /^[:\-\.\w\u00b7-\uffff]*$/;
28118
function completeTag(state, schema, tree, from, to) {
28119
    let end = /\s*>/.test(state.sliceDoc(to, to + 5)) ? "" : ">";
28120
    let parent = findParentElement$1(tree, true);
28121
    return { from, to,
28122
        options: allowedChildren(state.doc, parent, schema).map(tagName => ({ label: tagName, type: "type" })).concat(openTags(state.doc, tree).map((tag, i) => ({ label: "/" + tag, apply: "/" + tag + end,
28123
            type: "type", boost: 99 - i }))),
28124
        validFor: /^\/?[:\-\.\w\u00b7-\uffff]*$/ };
28125
}
28126
function completeCloseTag(state, tree, from, to) {
28127
    let end = /\s*>/.test(state.sliceDoc(to, to + 5)) ? "" : ">";
28128
    return { from, to,
28129
        options: openTags(state.doc, tree).map((tag, i) => ({ label: tag, apply: tag + end, type: "type", boost: 99 - i })),
28130
        validFor: identifier };
28131
}
28132
function completeStartTag(state, schema, tree, pos) {
28133
    let options = [], level = 0;
28134
    for (let tagName of allowedChildren(state.doc, tree, schema))
28135
        options.push({ label: "<" + tagName, type: "type" });
28136
    for (let open of openTags(state.doc, tree))
28137
        options.push({ label: "</" + open + ">", type: "type", boost: 99 - level++ });
28138
    return { from: pos, to: pos, options, validFor: /^<\/?[:\-\.\w\u00b7-\uffff]*$/ };
28139
}
28140
function completeAttrName(state, schema, tree, from, to) {
28141
    let elt = findParentElement$1(tree), info = elt ? schema.tags[elementName$2(state.doc, elt)] : null;
28142
    let localAttrs = info && info.attrs ? Object.keys(info.attrs) : [];
28143
    let names = info && info.globalAttrs === false ? localAttrs
28144
        : localAttrs.length ? localAttrs.concat(schema.globalAttrNames) : schema.globalAttrNames;
28145
    return { from, to,
28146
        options: names.map(attrName => ({ label: attrName, type: "property" })),
28147
        validFor: identifier };
28148
}
28149
function completeAttrValue(state, schema, tree, from, to) {
28150
    var _a;
28151
    let nameNode = (_a = tree.parent) === null || _a === void 0 ? void 0 : _a.getChild("AttributeName");
28152
    let options = [], token = undefined;
28153
    if (nameNode) {
28154
        let attrName = state.sliceDoc(nameNode.from, nameNode.to);
28155
        let attrs = schema.globalAttrs[attrName];
28156
        if (!attrs) {
28157
            let elt = findParentElement$1(tree), info = elt ? schema.tags[elementName$2(state.doc, elt)] : null;
28158
            attrs = (info === null || info === void 0 ? void 0 : info.attrs) && info.attrs[attrName];
28159
        }
28160
        if (attrs) {
28161
            let base = state.sliceDoc(from, to).toLowerCase(), quoteStart = '"', quoteEnd = '"';
28162
            if (/^['"]/.test(base)) {
28163
                token = base[0] == '"' ? /^[^"]*$/ : /^[^']*$/;
28164
                quoteStart = "";
28165
                quoteEnd = state.sliceDoc(to, to + 1) == base[0] ? "" : base[0];
28166
                base = base.slice(1);
28167
                from++;
28168
            }
28169
            else {
28170
                token = /^[^\s<>='"]*$/;
28171
            }
28172
            for (let value of attrs)
28173
                options.push({ label: value, apply: quoteStart + value + quoteEnd, type: "constant" });
28174
        }
28175
    }
28176
    return { from, to, options, validFor: token };
28177
}
28178
function htmlCompletionFor(schema, context) {
28179
    let { state, pos } = context, tree = syntaxTree(state).resolveInner(pos, -1), around = tree.resolve(pos);
28180
    for (let scan = pos, before; around == tree && (before = tree.childBefore(scan));) {
28181
        let last = before.lastChild;
28182
        if (!last || !last.type.isError || last.from < last.to)
28183
            break;
28184
        around = tree = before;
28185
        scan = last.from;
28186
    }
28187
    if (tree.name == "TagName") {
28188
        return tree.parent && /CloseTag$/.test(tree.parent.name) ? completeCloseTag(state, tree, tree.from, pos)
28189
            : completeTag(state, schema, tree, tree.from, pos);
28190
    }
28191
    else if (tree.name == "StartTag") {
28192
        return completeTag(state, schema, tree, pos, pos);
28193
    }
28194
    else if (tree.name == "StartCloseTag" || tree.name == "IncompleteCloseTag") {
28195
        return completeCloseTag(state, tree, pos, pos);
28196
    }
28197
    else if (tree.name == "OpenTag" || tree.name == "SelfClosingTag" || tree.name == "AttributeName") {
28198
        return completeAttrName(state, schema, tree, tree.name == "AttributeName" ? tree.from : pos, pos);
28199
    }
28200
    else if (tree.name == "Is" || tree.name == "AttributeValue" || tree.name == "UnquotedAttributeValue") {
28201
        return completeAttrValue(state, schema, tree, tree.name == "Is" ? pos : tree.from, pos);
28202
    }
28203
    else if (context.explicit && (around.name == "Element" || around.name == "Text" || around.name == "Document")) {
28204
        return completeStartTag(state, schema, tree, pos);
28205
    }
28206
    else {
28207
        return null;
28208
    }
28209
}
28210
/**
28211
Create a completion source for HTML extended with additional tags
28212
or attributes.
28213
*/
28214
function htmlCompletionSourceWith(config) {
28215
    let { extraTags, extraGlobalAttributes: extraAttrs } = config;
28216
    let schema = extraAttrs || extraTags ? new Schema(extraTags, extraAttrs) : Schema.default;
28217
    return (context) => htmlCompletionFor(schema, context);
28218
}
28219
 
28220
const jsonParser = /*@__PURE__*/javascriptLanguage.parser.configure({ top: "SingleExpression" });
28221
const defaultNesting = [
28222
    { tag: "script",
28223
        attrs: attrs => attrs.type == "text/typescript" || attrs.lang == "ts",
28224
        parser: typescriptLanguage.parser },
28225
    { tag: "script",
28226
        attrs: attrs => attrs.type == "text/babel" || attrs.type == "text/jsx",
28227
        parser: jsxLanguage.parser },
28228
    { tag: "script",
28229
        attrs: attrs => attrs.type == "text/typescript-jsx",
28230
        parser: tsxLanguage.parser },
28231
    { tag: "script",
28232
        attrs(attrs) {
28233
            return /^(importmap|speculationrules|application\/(.+\+)?json)$/i.test(attrs.type);
28234
        },
28235
        parser: jsonParser },
28236
    { tag: "script",
28237
        attrs(attrs) {
28238
            return !attrs.type || /^(?:text|application)\/(?:x-)?(?:java|ecma)script$|^module$|^$/i.test(attrs.type);
28239
        },
28240
        parser: javascriptLanguage.parser },
28241
    { tag: "style",
28242
        attrs(attrs) {
28243
            return (!attrs.lang || attrs.lang == "css") && (!attrs.type || /^(text\/)?(x-)?(stylesheet|css)$/i.test(attrs.type));
28244
        },
28245
        parser: cssLanguage.parser }
28246
];
28247
const defaultAttrs = /*@__PURE__*/[
28248
    { name: "style",
28249
        parser: /*@__PURE__*/cssLanguage.parser.configure({ top: "Styles" }) }
28250
].concat(/*@__PURE__*/eventAttributes.map(name => ({ name, parser: javascriptLanguage.parser })));
28251
/**
28252
A language provider based on the [Lezer HTML
28253
parser](https://github.com/lezer-parser/html), extended with the
28254
JavaScript and CSS parsers to parse the content of `<script>` and
28255
`<style>` tags.
28256
*/
28257
const htmlPlain = /*@__PURE__*/LRLanguage.define({
28258
    name: "html",
28259
    parser: /*@__PURE__*/parser$3.configure({
28260
        props: [
28261
            /*@__PURE__*/indentNodeProp.add({
28262
                Element(context) {
28263
                    let after = /^(\s*)(<\/)?/.exec(context.textAfter);
28264
                    if (context.node.to <= context.pos + after[0].length)
28265
                        return context.continue();
28266
                    return context.lineIndent(context.node.from) + (after[2] ? 0 : context.unit);
28267
                },
28268
                "OpenTag CloseTag SelfClosingTag"(context) {
28269
                    return context.column(context.node.from) + context.unit;
28270
                },
28271
                Document(context) {
28272
                    if (context.pos + /\s*/.exec(context.textAfter)[0].length < context.node.to)
28273
                        return context.continue();
28274
                    let endElt = null, close;
28275
                    for (let cur = context.node;;) {
28276
                        let last = cur.lastChild;
28277
                        if (!last || last.name != "Element" || last.to != cur.to)
28278
                            break;
28279
                        endElt = cur = last;
28280
                    }
28281
                    if (endElt && !((close = endElt.lastChild) && (close.name == "CloseTag" || close.name == "SelfClosingTag")))
28282
                        return context.lineIndent(endElt.from) + context.unit;
28283
                    return null;
28284
                }
28285
            }),
28286
            /*@__PURE__*/foldNodeProp.add({
28287
                Element(node) {
28288
                    let first = node.firstChild, last = node.lastChild;
28289
                    if (!first || first.name != "OpenTag")
28290
                        return null;
28291
                    return { from: first.to, to: last.name == "CloseTag" ? last.from : node.to };
28292
                }
28293
            }),
28294
            /*@__PURE__*/bracketMatchingHandle.add({
28295
                "OpenTag CloseTag": node => node.getChild("TagName")
28296
            })
28297
        ]
28298
    }),
28299
    languageData: {
28300
        commentTokens: { block: { open: "<!--", close: "-->" } },
28301
        indentOnInput: /^\s*<\/\w+\W$/,
28302
        wordChars: "-._"
28303
    }
28304
});
28305
/**
28306
A language provider based on the [Lezer HTML
28307
parser](https://github.com/lezer-parser/html), extended with the
28308
JavaScript and CSS parsers to parse the content of `<script>` and
28309
`<style>` tags.
28310
*/
28311
const htmlLanguage = /*@__PURE__*/htmlPlain.configure({
28312
    wrap: /*@__PURE__*/configureNesting(defaultNesting, defaultAttrs)
28313
});
28314
/**
28315
Language support for HTML, including
28316
[`htmlCompletion`](https://codemirror.net/6/docs/ref/#lang-html.htmlCompletion) and JavaScript and
28317
CSS support extensions.
28318
*/
28319
function html(config = {}) {
28320
    let dialect = "", wrap;
28321
    if (config.matchClosingTags === false)
28322
        dialect = "noMatch";
28323
    if (config.selfClosingTags === true)
28324
        dialect = (dialect ? dialect + " " : "") + "selfClosing";
28325
    if (config.nestedLanguages && config.nestedLanguages.length ||
28326
        config.nestedAttributes && config.nestedAttributes.length)
28327
        wrap = configureNesting((config.nestedLanguages || []).concat(defaultNesting), (config.nestedAttributes || []).concat(defaultAttrs));
28328
    let lang = wrap ? htmlPlain.configure({ wrap, dialect }) : dialect ? htmlLanguage.configure({ dialect }) : htmlLanguage;
28329
    return new LanguageSupport(lang, [
28330
        htmlLanguage.data.of({ autocomplete: htmlCompletionSourceWith(config) }),
28331
        config.autoCloseTags !== false ? autoCloseTags$1 : [],
28332
        javascript().support,
28333
        css().support
28334
    ]);
28335
}
28336
const selfClosers = /*@__PURE__*/new Set(/*@__PURE__*/"area base br col command embed frame hr img input keygen link meta param source track wbr menuitem".split(" "));
28337
/**
28338
Extension that will automatically insert close tags when a `>` or
28339
`/` is typed.
28340
*/
28341
const autoCloseTags$1 = /*@__PURE__*/EditorView.inputHandler.of((view, from, to, text, insertTransaction) => {
28342
    if (view.composing || view.state.readOnly || from != to || (text != ">" && text != "/") ||
28343
        !htmlLanguage.isActiveAt(view.state, from, -1))
28344
        return false;
28345
    let base = insertTransaction(), { state } = base;
28346
    let closeTags = state.changeByRange(range => {
28347
        var _a, _b, _c;
28348
        let didType = state.doc.sliceString(range.from - 1, range.to) == text;
28349
        let { head } = range, around = syntaxTree(state).resolveInner(head - 1, -1), name;
28350
        if (around.name == "TagName" || around.name == "StartTag")
28351
            around = around.parent;
28352
        if (didType && text == ">" && around.name == "OpenTag") {
28353
            if (((_b = (_a = around.parent) === null || _a === void 0 ? void 0 : _a.lastChild) === null || _b === void 0 ? void 0 : _b.name) != "CloseTag" &&
28354
                (name = elementName$2(state.doc, around.parent, head)) &&
28355
                !selfClosers.has(name)) {
28356
                let to = head + (state.doc.sliceString(head, head + 1) === ">" ? 1 : 0);
28357
                let insert = `</${name}>`;
28358
                return { range, changes: { from: head, to, insert } };
28359
            }
28360
        }
28361
        else if (didType && text == "/" && around.name == "IncompleteCloseTag") {
28362
            let base = around.parent;
28363
            if (around.from == head - 2 && ((_c = base.lastChild) === null || _c === void 0 ? void 0 : _c.name) != "CloseTag" &&
28364
                (name = elementName$2(state.doc, base, head)) && !selfClosers.has(name)) {
28365
                let to = head + (state.doc.sliceString(head, head + 1) === ">" ? 1 : 0);
28366
                let insert = `${name}>`;
28367
                return {
28368
                    range: EditorSelection.cursor(head + insert.length, -1),
28369
                    changes: { from: head, to, insert }
28370
                };
28371
            }
28372
        }
28373
        return { range };
28374
    });
28375
    if (closeTags.changes.empty)
28376
        return false;
28377
    view.dispatch([
28378
        base,
28379
        state.update(closeTags, {
28380
            userEvent: "input.complete",
28381
            scrollIntoView: true
28382
        })
28383
    ]);
28384
    return true;
28385
});
28386
 
28387
// This file was generated by lezer-generator. You probably shouldn't edit it.
28388
const StartTag = 1,
28389
  StartCloseTag = 2,
28390
  MissingCloseTag = 3,
28391
  mismatchedStartCloseTag = 4,
28392
  incompleteStartCloseTag = 5,
28393
  commentContent$1 = 35,
28394
  piContent$1 = 36,
28395
  cdataContent$1 = 37,
28396
  Element$1 = 11,
28397
  OpenTag = 13;
28398
 
28399
/* Hand-written tokenizer for XML tag matching. */
28400
 
28401
function nameChar(ch) {
28402
  return ch == 45 || ch == 46 || ch == 58 || ch >= 65 && ch <= 90 || ch == 95 || ch >= 97 && ch <= 122 || ch >= 161
28403
}
28404
 
28405
function isSpace(ch) {
28406
  return ch == 9 || ch == 10 || ch == 13 || ch == 32
28407
}
28408
 
28409
let cachedName = null, cachedInput = null, cachedPos = 0;
28410
function tagNameAfter(input, offset) {
28411
  let pos = input.pos + offset;
28412
  if (cachedInput == input && cachedPos == pos) return cachedName
28413
  while (isSpace(input.peek(offset))) offset++;
28414
  let name = "";
28415
  for (;;) {
28416
    let next = input.peek(offset);
28417
    if (!nameChar(next)) break
28418
    name += String.fromCharCode(next);
28419
    offset++;
28420
  }
28421
  cachedInput = input; cachedPos = pos;
28422
  return cachedName = name || null
28423
}
28424
 
28425
function ElementContext(name, parent) {
28426
  this.name = name;
28427
  this.parent = parent;
28428
  this.hash = parent ? parent.hash : 0;
28429
  for (let i = 0; i < name.length; i++) this.hash += (this.hash << 4) + name.charCodeAt(i) + (name.charCodeAt(i) << 8);
28430
}
28431
 
28432
const elementContext = new ContextTracker({
28433
  start: null,
28434
  shift(context, term, stack, input) {
28435
    return term == StartTag ? new ElementContext(tagNameAfter(input, 1) || "", context) : context
28436
  },
28437
  reduce(context, term) {
28438
    return term == Element$1 && context ? context.parent : context
28439
  },
28440
  reuse(context, node, _stack, input) {
28441
    let type = node.type.id;
28442
    return type == StartTag || type == OpenTag
28443
      ? new ElementContext(tagNameAfter(input, 1) || "", context) : context
28444
  },
28445
  hash(context) { return context ? context.hash : 0 },
28446
  strict: false
28447
});
28448
 
28449
const startTag = new ExternalTokenizer((input, stack) => {
28450
  if (input.next != 60 /* '<' */) return
28451
  input.advance();
28452
  if (input.next == 47 /* '/' */) {
28453
    input.advance();
28454
    let name = tagNameAfter(input, 0);
28455
    if (!name) return input.acceptToken(incompleteStartCloseTag)
28456
    if (stack.context && name == stack.context.name) return input.acceptToken(StartCloseTag)
28457
    for (let cx = stack.context; cx; cx = cx.parent) if (cx.name == name) return input.acceptToken(MissingCloseTag, -2)
28458
    input.acceptToken(mismatchedStartCloseTag);
28459
  } else if (input.next != 33 /* '!' */ && input.next != 63 /* '?' */) {
28460
    return input.acceptToken(StartTag)
28461
  }
28462
}, {contextual: true});
28463
 
28464
function scanTo(type, end) {
28465
  return new ExternalTokenizer(input => {
28466
    let len = 0, first = end.charCodeAt(0);
28467
    scan: for (;; input.advance(), len++) {
28468
      if (input.next < 0) break
28469
      if (input.next == first) {
28470
        for (let i = 1; i < end.length; i++)
28471
          if (input.peek(i) != end.charCodeAt(i)) continue scan
28472
        break
28473
      }
28474
    }
28475
    if (len) input.acceptToken(type);
28476
  })
28477
}
28478
 
28479
const commentContent = scanTo(commentContent$1, "-->");
28480
const piContent = scanTo(piContent$1, "?>");
28481
const cdataContent = scanTo(cdataContent$1, "]]>");
28482
 
28483
const xmlHighlighting = styleTags({
28484
  Text: tags$1.content,
28485
  "StartTag StartCloseTag EndTag SelfCloseEndTag": tags$1.angleBracket,
28486
  TagName: tags$1.tagName,
28487
  "MismatchedCloseTag/TagName": [tags$1.tagName, tags$1.invalid],
28488
  AttributeName: tags$1.attributeName,
28489
  AttributeValue: tags$1.attributeValue,
28490
  Is: tags$1.definitionOperator,
28491
  "EntityReference CharacterReference": tags$1.character,
28492
  Comment: tags$1.blockComment,
28493
  ProcessingInst: tags$1.processingInstruction,
28494
  DoctypeDecl: tags$1.documentMeta,
28495
  Cdata: tags$1.special(tags$1.string)
28496
});
28497
 
28498
// This file was generated by lezer-generator. You probably shouldn't edit it.
28499
const parser = LRParser.deserialize({
28500
  version: 14,
28501
  states: ",SOQOaOOOrOxO'#CfOzOpO'#CiO!tOaO'#CgOOOP'#Cg'#CgO!{OrO'#CrO#TOtO'#CsO#]OpO'#CtOOOP'#DS'#DSOOOP'#Cv'#CvQQOaOOOOOW'#Cw'#CwO#eOxO,59QOOOP,59Q,59QOOOO'#Cx'#CxO#mOpO,59TO#uO!bO,59TOOOP'#C{'#C{O$TOaO,59RO$[OpO'#CoOOOP,59R,59ROOOQ'#C|'#C|O$dOrO,59^OOOP,59^,59^OOOS'#C}'#C}O$lOtO,59_OOOP,59_,59_O$tOpO,59`O$|OpO,59`OOOP-E6t-E6tOOOW-E6u-E6uOOOP1G.l1G.lO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vO{!pO~O",
28503
  goto: "%[wPPPPPPPPPPxxP!OP!UPP!_!iP!oxxxP!u!{#R$Z$j$p$v$|PPPP%SXWORYbXRORYb_t`qru!T!U!bQ!h!YS!o!e!fR!t!nQdRRybXSORYbQYORmYQ[PRn[Q_QQkVjp_krz!R!T!X!Z!^!`!f!i!nQr`QzcQ!RlQ!TqQ!XsQ!ZtQ!^{Q!`!QQ!f!YQ!i!]R!n!eQu`S!UqrU![u!U!bR!b!TQ!q!gR!u!qQbRRxbQfTR|fQiUR!OiSXOYTaRb",
28504
  nodeNames: "⚠ StartTag StartCloseTag MissingCloseTag StartCloseTag StartCloseTag Document Text EntityReference CharacterReference Cdata Element EndTag OpenTag TagName Attribute AttributeName Is AttributeValue CloseTag SelfCloseEndTag SelfClosingTag Comment ProcessingInst MismatchedCloseTag DoctypeDecl",
28505
  maxTerm: 47,
28506
  context: elementContext,
28507
  nodeProps: [
28508
    ["closedBy", 1,"SelfCloseEndTag EndTag",13,"CloseTag MissingCloseTag"],
28509
    ["openedBy", 12,"StartTag StartCloseTag",19,"OpenTag",20,"StartTag"],
28510
    ["isolate", -6,13,18,19,21,22,24,""]
28511
  ],
28512
  propSources: [xmlHighlighting],
28513
  skippedNodes: [0],
28514
  repeatNodeCount: 8,
28515
  tokenData: "Jy~R!XOX$nXY&kYZ&kZ]$n]^&k^p$npq&kqr$nrs'ssv$nvw(Zw}$n}!O,^!O!P$n!P!Q.m!Q![$n![!]0V!]!^$n!^!_3h!_!`El!`!aF_!a!bGQ!b!c$n!c!}0V!}#P$n#P#QHj#Q#R$n#R#S0V#S#T$n#T#o0V#o%W$n%W%o0V%o%p$n%p&a0V&a&b$n&b1p0V1p4U$n4U4d0V4d4e$n4e$IS0V$IS$I`$n$I`$Ib0V$Ib$Kh$n$Kh%#t0V%#t&/x$n&/x&Et0V&Et&FV$n&FV;'S0V;'S;:j3b;:j;=`&e<%l?&r$n?&r?Ah0V?Ah?BY$n?BY?Mn0V?MnO$nX$uWVP{WOr$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$nrs%_sv$nw!^$n!^!_%y!_!`$n!`!aJW!a;'S$n;'S;=`&e<%lO$nZJaWwQVP{WOr$nrs%_sv$nw!^$n!^!_%y!_;'S$n;'S;=`&e<%lO$n",
28516
  tokenizers: [startTag, commentContent, piContent, cdataContent, 0, 1, 2, 3],
28517
  topRules: {"Document":[0,6]},
28518
  tokenPrec: 0
28519
});
28520
 
28521
function tagName(doc, tag) {
28522
    let name = tag && tag.getChild("TagName");
28523
    return name ? doc.sliceString(name.from, name.to) : "";
28524
}
28525
function elementName$1(doc, tree) {
28526
    let tag = tree && tree.firstChild;
28527
    return !tag || tag.name != "OpenTag" ? "" : tagName(doc, tag);
28528
}
28529
function attrName(doc, tag, pos) {
28530
    let attr = tag && tag.getChildren("Attribute").find(a => a.from <= pos && a.to >= pos);
28531
    let name = attr && attr.getChild("AttributeName");
28532
    return name ? doc.sliceString(name.from, name.to) : "";
28533
}
28534
function findParentElement(tree) {
28535
    for (let cur = tree && tree.parent; cur; cur = cur.parent)
28536
        if (cur.name == "Element")
28537
            return cur;
28538
    return null;
28539
}
28540
function findLocation(state, pos) {
28541
    var _a;
28542
    let at = syntaxTree(state).resolveInner(pos, -1), inTag = null;
28543
    for (let cur = at; !inTag && cur.parent; cur = cur.parent)
28544
        if (cur.name == "OpenTag" || cur.name == "CloseTag" || cur.name == "SelfClosingTag" || cur.name == "MismatchedCloseTag")
28545
            inTag = cur;
28546
    if (inTag && (inTag.to > pos || inTag.lastChild.type.isError)) {
28547
        let elt = inTag.parent;
28548
        if (at.name == "TagName")
28549
            return inTag.name == "CloseTag" || inTag.name == "MismatchedCloseTag"
28550
                ? { type: "closeTag", from: at.from, context: elt }
28551
                : { type: "openTag", from: at.from, context: findParentElement(elt) };
28552
        if (at.name == "AttributeName")
28553
            return { type: "attrName", from: at.from, context: inTag };
28554
        if (at.name == "AttributeValue")
28555
            return { type: "attrValue", from: at.from, context: inTag };
28556
        let before = at == inTag || at.name == "Attribute" ? at.childBefore(pos) : at;
28557
        if ((before === null || before === void 0 ? void 0 : before.name) == "StartTag")
28558
            return { type: "openTag", from: pos, context: findParentElement(elt) };
28559
        if ((before === null || before === void 0 ? void 0 : before.name) == "StartCloseTag" && before.to <= pos)
28560
            return { type: "closeTag", from: pos, context: elt };
28561
        if ((before === null || before === void 0 ? void 0 : before.name) == "Is")
28562
            return { type: "attrValue", from: pos, context: inTag };
28563
        if (before)
28564
            return { type: "attrName", from: pos, context: inTag };
28565
        return null;
28566
    }
28567
    else if (at.name == "StartCloseTag") {
28568
        return { type: "closeTag", from: pos, context: at.parent };
28569
    }
28570
    while (at.parent && at.to == pos && !((_a = at.lastChild) === null || _a === void 0 ? void 0 : _a.type.isError))
28571
        at = at.parent;
28572
    if (at.name == "Element" || at.name == "Text" || at.name == "Document")
28573
        return { type: "tag", from: pos, context: at.name == "Element" ? at : findParentElement(at) };
28574
    return null;
28575
}
28576
class Element {
28577
    constructor(spec, attrs, attrValues) {
28578
        this.attrs = attrs;
28579
        this.attrValues = attrValues;
28580
        this.children = [];
28581
        this.name = spec.name;
28582
        this.completion = Object.assign(Object.assign({ type: "type" }, spec.completion || {}), { label: this.name });
28583
        this.openCompletion = Object.assign(Object.assign({}, this.completion), { label: "<" + this.name });
28584
        this.closeCompletion = Object.assign(Object.assign({}, this.completion), { label: "</" + this.name + ">", boost: 2 });
28585
        this.closeNameCompletion = Object.assign(Object.assign({}, this.completion), { label: this.name + ">" });
28586
        this.text = spec.textContent ? spec.textContent.map(s => ({ label: s, type: "text" })) : [];
28587
    }
28588
}
28589
const Identifier = /^[:\-\.\w\u00b7-\uffff]*$/;
28590
function attrCompletion(spec) {
28591
    return Object.assign(Object.assign({ type: "property" }, spec.completion || {}), { label: spec.name });
28592
}
28593
function valueCompletion(spec) {
28594
    return typeof spec == "string" ? { label: `"${spec}"`, type: "constant" }
28595
        : /^"/.test(spec.label) ? spec
28596
            : Object.assign(Object.assign({}, spec), { label: `"${spec.label}"` });
28597
}
28598
/**
28599
Create a completion source for the given schema.
28600
*/
28601
function completeFromSchema(eltSpecs, attrSpecs) {
28602
    let allAttrs = [], globalAttrs = [];
28603
    let attrValues = Object.create(null);
28604
    for (let s of attrSpecs) {
28605
        let completion = attrCompletion(s);
28606
        allAttrs.push(completion);
28607
        if (s.global)
28608
            globalAttrs.push(completion);
28609
        if (s.values)
28610
            attrValues[s.name] = s.values.map(valueCompletion);
28611
    }
28612
    let allElements = [], topElements = [];
28613
    let byName = Object.create(null);
28614
    for (let s of eltSpecs) {
28615
        let attrs = globalAttrs, attrVals = attrValues;
28616
        if (s.attributes)
28617
            attrs = attrs.concat(s.attributes.map(s => {
28618
                if (typeof s == "string")
28619
                    return allAttrs.find(a => a.label == s) || { label: s, type: "property" };
28620
                if (s.values) {
28621
                    if (attrVals == attrValues)
28622
                        attrVals = Object.create(attrVals);
28623
                    attrVals[s.name] = s.values.map(valueCompletion);
28624
                }
28625
                return attrCompletion(s);
28626
            }));
28627
        let elt = new Element(s, attrs, attrVals);
28628
        byName[elt.name] = elt;
28629
        allElements.push(elt);
28630
        if (s.top)
28631
            topElements.push(elt);
28632
    }
28633
    if (!topElements.length)
28634
        topElements = allElements;
28635
    for (let i = 0; i < allElements.length; i++) {
28636
        let s = eltSpecs[i], elt = allElements[i];
28637
        if (s.children) {
28638
            for (let ch of s.children)
28639
                if (byName[ch])
28640
                    elt.children.push(byName[ch]);
28641
        }
28642
        else {
28643
            elt.children = allElements;
28644
        }
28645
    }
28646
    return cx => {
28647
        var _a;
28648
        let { doc } = cx.state, loc = findLocation(cx.state, cx.pos);
28649
        if (!loc || (loc.type == "tag" && !cx.explicit))
28650
            return null;
28651
        let { type, from, context } = loc;
28652
        if (type == "openTag") {
28653
            let children = topElements;
28654
            let parentName = elementName$1(doc, context);
28655
            if (parentName) {
28656
                let parent = byName[parentName];
28657
                children = (parent === null || parent === void 0 ? void 0 : parent.children) || allElements;
28658
            }
28659
            return {
28660
                from,
28661
                options: children.map(ch => ch.completion),
28662
                validFor: Identifier
28663
            };
28664
        }
28665
        else if (type == "closeTag") {
28666
            let parentName = elementName$1(doc, context);
28667
            return parentName ? {
28668
                from,
28669
                to: cx.pos + (doc.sliceString(cx.pos, cx.pos + 1) == ">" ? 1 : 0),
28670
                options: [((_a = byName[parentName]) === null || _a === void 0 ? void 0 : _a.closeNameCompletion) || { label: parentName + ">", type: "type" }],
28671
                validFor: Identifier
28672
            } : null;
28673
        }
28674
        else if (type == "attrName") {
28675
            let parent = byName[tagName(doc, context)];
28676
            return {
28677
                from,
28678
                options: (parent === null || parent === void 0 ? void 0 : parent.attrs) || globalAttrs,
28679
                validFor: Identifier
28680
            };
28681
        }
28682
        else if (type == "attrValue") {
28683
            let attr = attrName(doc, context, from);
28684
            if (!attr)
28685
                return null;
28686
            let parent = byName[tagName(doc, context)];
28687
            let values = ((parent === null || parent === void 0 ? void 0 : parent.attrValues) || attrValues)[attr];
28688
            if (!values || !values.length)
28689
                return null;
28690
            return {
28691
                from,
28692
                to: cx.pos + (doc.sliceString(cx.pos, cx.pos + 1) == '"' ? 1 : 0),
28693
                options: values,
28694
                validFor: /^"[^"]*"?$/
28695
            };
28696
        }
28697
        else if (type == "tag") {
28698
            let parentName = elementName$1(doc, context), parent = byName[parentName];
28699
            let closing = [], last = context && context.lastChild;
28700
            if (parentName && (!last || last.name != "CloseTag" || tagName(doc, last) != parentName))
28701
                closing.push(parent ? parent.closeCompletion : { label: "</" + parentName + ">", type: "type", boost: 2 });
28702
            let options = closing.concat(((parent === null || parent === void 0 ? void 0 : parent.children) || (context ? allElements : topElements)).map(e => e.openCompletion));
28703
            if (context && (parent === null || parent === void 0 ? void 0 : parent.text.length)) {
28704
                let openTag = context.firstChild;
28705
                if (openTag.to > cx.pos - 20 && !/\S/.test(cx.state.sliceDoc(openTag.to, cx.pos)))
28706
                    options = options.concat(parent.text);
28707
            }
28708
            return {
28709
                from,
28710
                options,
28711
                validFor: /^<\/?[:\-\.\w\u00b7-\uffff]*$/
28712
            };
28713
        }
28714
        else {
28715
            return null;
28716
        }
28717
    };
28718
}
28719
 
28720
/**
28721
A language provider based on the [Lezer XML
28722
parser](https://github.com/lezer-parser/xml), extended with
28723
highlighting and indentation information.
28724
*/
28725
const xmlLanguage = /*@__PURE__*/LRLanguage.define({
28726
    name: "xml",
28727
    parser: /*@__PURE__*/parser.configure({
28728
        props: [
28729
            /*@__PURE__*/indentNodeProp.add({
28730
                Element(context) {
28731
                    let closed = /^\s*<\//.test(context.textAfter);
28732
                    return context.lineIndent(context.node.from) + (closed ? 0 : context.unit);
28733
                },
28734
                "OpenTag CloseTag SelfClosingTag"(context) {
28735
                    return context.column(context.node.from) + context.unit;
28736
                }
28737
            }),
28738
            /*@__PURE__*/foldNodeProp.add({
28739
                Element(subtree) {
28740
                    let first = subtree.firstChild, last = subtree.lastChild;
28741
                    if (!first || first.name != "OpenTag")
28742
                        return null;
28743
                    return { from: first.to, to: last.name == "CloseTag" ? last.from : subtree.to };
28744
                }
28745
            }),
28746
            /*@__PURE__*/bracketMatchingHandle.add({
28747
                "OpenTag CloseTag": node => node.getChild("TagName")
28748
            })
28749
        ]
28750
    }),
28751
    languageData: {
28752
        commentTokens: { block: { open: "<!--", close: "-->" } },
28753
        indentOnInput: /^\s*<\/$/
28754
    }
28755
});
28756
/**
28757
XML language support. Includes schema-based autocompletion when
28758
configured.
28759
*/
28760
function xml(conf = {}) {
28761
    let support = [xmlLanguage.data.of({
28762
            autocomplete: completeFromSchema(conf.elements || [], conf.attributes || [])
28763
        })];
28764
    if (conf.autoCloseTags !== false)
28765
        support.push(autoCloseTags);
28766
    return new LanguageSupport(xmlLanguage, support);
28767
}
28768
function elementName(doc, tree, max = doc.length) {
28769
    if (!tree)
28770
        return "";
28771
    let tag = tree.firstChild;
28772
    let name = tag && tag.getChild("TagName");
28773
    return name ? doc.sliceString(name.from, Math.min(name.to, max)) : "";
28774
}
28775
/**
28776
Extension that will automatically insert close tags when a `>` or
28777
`/` is typed.
28778
*/
28779
const autoCloseTags = /*@__PURE__*/EditorView.inputHandler.of((view, from, to, text, insertTransaction) => {
28780
    if (view.composing || view.state.readOnly || from != to || (text != ">" && text != "/") ||
28781
        !xmlLanguage.isActiveAt(view.state, from, -1))
28782
        return false;
28783
    let base = insertTransaction(), { state } = base;
28784
    let closeTags = state.changeByRange(range => {
28785
        var _a, _b, _c;
28786
        let { head } = range;
28787
        let didType = state.doc.sliceString(head - 1, head) == text;
28788
        let after = syntaxTree(state).resolveInner(head, -1), name;
28789
        if (didType && text == ">" && after.name == "EndTag") {
28790
            let tag = after.parent;
28791
            if (((_b = (_a = tag.parent) === null || _a === void 0 ? void 0 : _a.lastChild) === null || _b === void 0 ? void 0 : _b.name) != "CloseTag" &&
28792
                (name = elementName(state.doc, tag.parent, head))) {
28793
                let to = head + (state.doc.sliceString(head, head + 1) === ">" ? 1 : 0);
28794
                let insert = `</${name}>`;
28795
                return { range, changes: { from: head, to, insert } };
28796
            }
28797
        }
28798
        else if (didType && text == "/" && after.name == "StartCloseTag") {
28799
            let base = after.parent;
28800
            if (after.from == head - 2 && ((_c = base.lastChild) === null || _c === void 0 ? void 0 : _c.name) != "CloseTag" &&
28801
                (name = elementName(state.doc, base, head))) {
28802
                let to = head + (state.doc.sliceString(head, head + 1) === ">" ? 1 : 0);
28803
                let insert = `${name}>`;
28804
                return {
28805
                    range: EditorSelection.cursor(head + insert.length, -1),
28806
                    changes: { from: head, to, insert }
28807
                };
28808
            }
28809
        }
28810
        return { range };
28811
    });
28812
    if (closeTags.changes.empty)
28813
        return false;
28814
    view.dispatch([
28815
        base,
28816
        state.update(closeTags, {
28817
            userEvent: "input.complete",
28818
            scrollIntoView: true
28819
        })
28820
    ]);
28821
    return true;
28822
});
28823
 
28824
// This file is part of Moodle - https://moodle.org/
28825
//
28826
// Moodle is free software: you can redistribute it and/or modify
28827
// it under the terms of the GNU General Public License as published by
28828
// the Free Software Foundation, either version 3 of the License, or
28829
// (at your option) any later version.
28830
//
28831
// Moodle is distributed in the hope that it will be useful,
28832
// but WITHOUT ANY WARRANTY; without even the implied warranty of
28833
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
28834
// GNU General Public License for more details.
28835
//
28836
// You should have received a copy of the GNU General Public License
28837
// along with Moodle.  If not, see <https://www.gnu.org/licenses/>.
28838
 
28839
 
28840
const lang = {
28841
    html,
28842
    javascript,
28843
    xml,
28844
};
28845
 
28846
export { EditorState, EditorView, basicSetup, lang };